var muxjs=null;
(function(f){muxjs = f();return;if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.muxjs = f()}})(function(){var define,module,exports;return (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){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * A stream-based aac to mp4 converter. This utility can be used to
 * deliver mp4s to a SourceBuffer on platforms that support native
 * Media Source Extensions.
 */
'use strict';
var Stream = require(49);
var aacUtils = require(2);

// Constants
var AacStream;

/**
 * Splits an incoming stream of binary data into ADTS and ID3 Frames.
 */

AacStream = function() {
  var
    everything = new Uint8Array(),
    timeStamp = 0;

  AacStream.prototype.init.call(this);

  this.setTimestamp = function(timestamp) {
    timeStamp = timestamp;
  };

  this.push = function(bytes) {
    var
      frameSize = 0,
      byteIndex = 0,
      bytesLeft,
      chunk,
      packet,
      tempLength;

    // If there are bytes remaining from the last segment, prepend them to the
    // bytes that were pushed in
    if (everything.length) {
      tempLength = everything.length;
      everything = new Uint8Array(bytes.byteLength + tempLength);
      everything.set(everything.subarray(0, tempLength));
      everything.set(bytes, tempLength);
    } else {
      everything = bytes;
    }

    while (everything.length - byteIndex >= 3) {
      if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
          (everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
          (everything[byteIndex + 2] === '3'.charCodeAt(0))) {

        // Exit early because we don't have enough to parse
        // the ID3 tag header
        if (everything.length - byteIndex < 10) {
          break;
        }

        // check framesize
        frameSize = aacUtils.parseId3TagSize(everything, byteIndex);

        // Exit early if we don't have enough in the buffer
        // to emit a full packet
        // Add to byteIndex to support multiple ID3 tags in sequence
        if (byteIndex + frameSize > everything.length) {
          break;
        }
        chunk = {
          type: 'timed-metadata',
          data: everything.subarray(byteIndex, byteIndex + frameSize)
        };
        this.trigger('data', chunk);
        byteIndex += frameSize;
        continue;
      } else if (((everything[byteIndex] & 0xff) === 0xff) &&
                 ((everything[byteIndex + 1] & 0xf0) === 0xf0)) {

        // Exit early because we don't have enough to parse
        // the ADTS frame header
        if (everything.length - byteIndex < 7) {
          break;
        }

        frameSize = aacUtils.parseAdtsSize(everything, byteIndex);

        // Exit early if we don't have enough in the buffer
        // to emit a full packet
        if (byteIndex + frameSize > everything.length) {
          break;
        }

        packet = {
          type: 'audio',
          data: everything.subarray(byteIndex, byteIndex + frameSize),
          pts: timeStamp,
          dts: timeStamp
        };
        this.trigger('data', packet);
        byteIndex += frameSize;
        continue;
      }
      byteIndex++;
    }
    bytesLeft = everything.length - byteIndex;

    if (bytesLeft > 0) {
      everything = everything.subarray(byteIndex);
    } else {
      everything = new Uint8Array();
    }
  };

  this.reset = function() {
    everything = new Uint8Array();
    this.trigger('reset');
  };

  this.endTimeline = function() {
    everything = new Uint8Array();
    this.trigger('endedtimeline');
  };
};

AacStream.prototype = new Stream();

module.exports = AacStream;

},{"2":2,"49":49}],2:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Utilities to detect basic properties and metadata about Aac data.
 */
'use strict';

var ADTS_SAMPLING_FREQUENCIES = [
  96000,
  88200,
  64000,
  48000,
  44100,
  32000,
  24000,
  22050,
  16000,
  12000,
  11025,
  8000,
  7350
];

var parseId3TagSize = function(header, byteIndex) {
  var
    returnSize = (header[byteIndex + 6] << 21) |
                 (header[byteIndex + 7] << 14) |
                 (header[byteIndex + 8] << 7) |
                 (header[byteIndex + 9]),
    flags = header[byteIndex + 5],
    footerPresent = (flags & 16) >> 4;

  // if we get a negative returnSize clamp it to 0
  returnSize = returnSize >= 0 ? returnSize : 0;

  if (footerPresent) {
    return returnSize + 20;
  }
  return returnSize + 10;
};

var getId3Offset = function(data, offset) {
  if (data.length - offset < 10 ||
      data[offset] !== 'I'.charCodeAt(0) ||
      data[offset + 1] !== 'D'.charCodeAt(0) ||
      data[offset + 2] !== '3'.charCodeAt(0)) {
    return offset;
  }

  offset += parseId3TagSize(data, offset);

  return getId3Offset(data, offset);
};


// TODO: use vhs-utils
var isLikelyAacData = function(data) {
  var offset = getId3Offset(data, 0);

  return data.length >= offset + 2 &&
    (data[offset] & 0xFF) === 0xFF &&
    (data[offset + 1] & 0xF0) === 0xF0 &&
    // verify that the 2 layer bits are 0, aka this
    // is not mp3 data but aac data.
    (data[offset + 1] & 0x16) === 0x10;
};

var parseSyncSafeInteger = function(data) {
  return (data[0] << 21) |
          (data[1] << 14) |
          (data[2] << 7) |
          (data[3]);
};

// return a percent-encoded representation of the specified byte range
// @see http://en.wikipedia.org/wiki/Percent-encoding
var percentEncode = function(bytes, start, end) {
  var i, result = '';
  for (i = start; i < end; i++) {
    result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  }
  return result;
};

// return the string representation of the specified byte range,
// interpreted as ISO-8859-1.
var parseIso88591 = function(bytes, start, end) {
  return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
};

var parseAdtsSize = function(header, byteIndex) {
  var
    lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
    middle = header[byteIndex + 4] << 3,
    highTwo = header[byteIndex + 3] & 0x3 << 11;

  return (highTwo | middle) | lowThree;
};

var parseType = function(header, byteIndex) {
  if ((header[byteIndex] === 'I'.charCodeAt(0)) &&
      (header[byteIndex + 1] === 'D'.charCodeAt(0)) &&
      (header[byteIndex + 2] === '3'.charCodeAt(0))) {
    return 'timed-metadata';
  } else if ((header[byteIndex] & 0xff === 0xff) &&
             ((header[byteIndex + 1] & 0xf0) === 0xf0)) {
    return 'audio';
  }
  return null;
};

var parseSampleRate = function(packet) {
  var i = 0;

  while (i + 5 < packet.length) {
    if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
      // If a valid header was not found,  jump one forward and attempt to
      // find a valid ADTS header starting at the next byte
      i++;
      continue;
    }
    return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  }

  return null;
};

var parseAacTimestamp = function(packet) {
  var frameStart, frameSize, frame, frameHeader;

  // find the start of the first frame and the end of the tag
  frameStart = 10;
  if (packet[5] & 0x40) {
    // advance the frame start past the extended header
    frameStart += 4; // header size field
    frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  }

  // parse one or more ID3 frames
  // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  do {
    // determine the number of bytes in this frame
    frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
    if (frameSize < 1) {
      return null;
    }
    frameHeader = String.fromCharCode(packet[frameStart],
                                      packet[frameStart + 1],
                                      packet[frameStart + 2],
                                      packet[frameStart + 3]);

    if (frameHeader === 'PRIV') {
      frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);

      for (var i = 0; i < frame.byteLength; i++) {
        if (frame[i] === 0) {
          var owner = parseIso88591(frame, 0, i);
          if (owner === 'com.apple.streaming.transportStreamTimestamp') {
            var d = frame.subarray(i + 1);
            var size = ((d[3] & 0x01)  << 30) |
                       (d[4]  << 22) |
                       (d[5] << 14) |
                       (d[6] << 6) |
                       (d[7] >>> 2);
            size *= 4;
            size += d[7] & 0x03;

            return size;
          }
          break;
        }
      }
    }

    frameStart += 10; // advance past the frame header
    frameStart += frameSize; // advance past the frame body
  } while (frameStart < packet.byteLength);
  return null;
};

module.exports = {
  isLikelyAacData: isLikelyAacData,
  parseId3TagSize: parseId3TagSize,
  parseAdtsSize: parseAdtsSize,
  parseType: parseType,
  parseSampleRate: parseSampleRate,
  parseAacTimestamp: parseAacTimestamp
};

},{}],3:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var Stream = require(49);
var ONE_SECOND_IN_TS = require(47).ONE_SECOND_IN_TS;

var AdtsStream;

var
  ADTS_SAMPLING_FREQUENCIES = [
    96000,
    88200,
    64000,
    48000,
    44100,
    32000,
    24000,
    22050,
    16000,
    12000,
    11025,
    8000,
    7350
  ];

/*
 * Accepts a ElementaryStream and emits data events with parsed
 * AAC Audio Frames of the individual packets. Input audio in ADTS
 * format is unpacked and re-emitted as AAC frames.
 *
 * @see http://wiki.multimedia.cx/index.php?title=ADTS
 * @see http://wiki.multimedia.cx/?title=Understanding_AAC
 */
AdtsStream = function(handlePartialSegments) {
  var
    buffer,
    frameNum = 0;

  AdtsStream.prototype.init.call(this);

  this.push = function(packet) {
    var
      i = 0,
      frameLength,
      protectionSkipBytes,
      frameEnd,
      oldBuffer,
      sampleCount,
      adtsFrameDuration;

    if (!handlePartialSegments) {
      frameNum = 0;
    }

    if (packet.type !== 'audio') {
      // ignore non-audio data
      return;
    }

    // Prepend any data in the buffer to the input data so that we can parse
    // aac frames the cross a PES packet boundary
    if (buffer) {
      oldBuffer = buffer;
      buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
      buffer.set(oldBuffer);
      buffer.set(packet.data, oldBuffer.byteLength);
    } else {
      buffer = packet.data;
    }

    // unpack any ADTS frames which have been fully received
    // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
    while (i + 5 < buffer.length) {

      // Look for the start of an ADTS header..
      if ((buffer[i] !== 0xFF) || (buffer[i + 1] & 0xF6) !== 0xF0) {
        // If a valid header was not found,  jump one forward and attempt to
        // find a valid ADTS header starting at the next byte
        i++;
        continue;
      }

      // The protection skip bit tells us if we have 2 bytes of CRC data at the
      // end of the ADTS header
      protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;

      // Frame length is a 13 bit integer starting 16 bits from the
      // end of the sync sequence
      frameLength = ((buffer[i + 3] & 0x03) << 11) |
        (buffer[i + 4] << 3) |
        ((buffer[i + 5] & 0xe0) >> 5);

      sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
      adtsFrameDuration = (sampleCount * ONE_SECOND_IN_TS) /
        ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];

      frameEnd = i + frameLength;

      // If we don't have enough data to actually finish this ADTS frame, return
      // and wait for more data
      if (buffer.byteLength < frameEnd) {
        return;
      }

      // Otherwise, deliver the complete AAC frame
      this.trigger('data', {
        pts: packet.pts + (frameNum * adtsFrameDuration),
        dts: packet.dts + (frameNum * adtsFrameDuration),
        sampleCount: sampleCount,
        audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
        channelcount: ((buffer[i + 2] & 1) << 2) |
          ((buffer[i + 3] & 0xc0) >>> 6),
        samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
        samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
        // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
        samplesize: 16,
        data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
      });

      frameNum++;

      // If the buffer is empty, clear it and return
      if (buffer.byteLength === frameEnd) {
        buffer = undefined;
        return;
      }

      // Remove the finished frame from the buffer and start the process again
      buffer = buffer.subarray(frameEnd);
    }
  };

  this.flush = function() {
    frameNum = 0;
    this.trigger('done');
  };

  this.reset = function() {
    buffer = void 0;
    this.trigger('reset');
  };

  this.endTimeline = function() {
    buffer = void 0;
    this.trigger('endedtimeline');
  };
};

AdtsStream.prototype = new Stream();

module.exports = AdtsStream;

},{"47":47,"49":49}],4:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var Stream = require(49);
var ExpGolomb = require(48);

var H264Stream, NalByteStream;
var PROFILES_WITH_OPTIONAL_SPS_DATA;

/**
 * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
 */
NalByteStream = function() {
  var
    syncPoint = 0,
    i,
    buffer;
  NalByteStream.prototype.init.call(this);

  /*
   * Scans a byte stream and triggers a data event with the NAL units found.
   * @param {Object} data Event received from H264Stream
   * @param {Uint8Array} data.data The h264 byte stream to be scanned
   *
   * @see H264Stream.push
   */
  this.push = function(data) {
    var swapBuffer;

    if (!buffer) {
      buffer = data.data;
    } else {
      swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
      swapBuffer.set(buffer);
      swapBuffer.set(data.data, buffer.byteLength);
      buffer = swapBuffer;
    }
    var len = buffer.byteLength;

    // Rec. ITU-T H.264, Annex B
    // scan for NAL unit boundaries

    // a match looks like this:
    // 0 0 1 .. NAL .. 0 0 1
    // ^ sync point        ^ i
    // or this:
    // 0 0 1 .. NAL .. 0 0 0
    // ^ sync point        ^ i

    // advance the sync point to a NAL start, if necessary
    for (; syncPoint < len - 3; syncPoint++) {
      if (buffer[syncPoint + 2] === 1) {
        // the sync point is properly aligned
        i = syncPoint + 5;
        break;
      }
    }

    while (i < len) {
      // look at the current byte to determine if we've hit the end of
      // a NAL unit boundary
      switch (buffer[i]) {
      case 0:
        // skip past non-sync sequences
        if (buffer[i - 1] !== 0) {
          i += 2;
          break;
        } else if (buffer[i - 2] !== 0) {
          i++;
          break;
        }

        // deliver the NAL unit if it isn't empty
        if (syncPoint + 3 !== i - 2) {
          this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
        }

        // drop trailing zeroes
        do {
          i++;
        } while (buffer[i] !== 1 && i < len);
        syncPoint = i - 2;
        i += 3;
        break;
      case 1:
        // skip past non-sync sequences
        if (buffer[i - 1] !== 0 ||
            buffer[i - 2] !== 0) {
          i += 3;
          break;
        }

        // deliver the NAL unit
        this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
        syncPoint = i - 2;
        i += 3;
        break;
      default:
        // the current byte isn't a one or zero, so it cannot be part
        // of a sync sequence
        i += 3;
        break;
      }
    }
    // filter out the NAL units that were delivered
    buffer = buffer.subarray(syncPoint);
    i -= syncPoint;
    syncPoint = 0;
  };

  this.reset = function() {
    buffer = null;
    syncPoint = 0;
    this.trigger('reset');
  };

  this.flush = function() {
    // deliver the last buffered NAL unit
    if (buffer && buffer.byteLength > 3) {
      this.trigger('data', buffer.subarray(syncPoint + 3));
    }
    // reset the stream state
    buffer = null;
    syncPoint = 0;
    this.trigger('done');
  };

  this.endTimeline = function() {
    this.flush();
    this.trigger('endedtimeline');
  };
};
NalByteStream.prototype = new Stream();

// values of profile_idc that indicate additional fields are included in the SPS
// see Recommendation ITU-T H.264 (4/2013),
// 7.3.2.1.1 Sequence parameter set data syntax
PROFILES_WITH_OPTIONAL_SPS_DATA = {
  100: true,
  110: true,
  122: true,
  244: true,
  44: true,
  83: true,
  86: true,
  118: true,
  128: true,
  138: true,
  139: true,
  134: true
};

/**
 * Accepts input from a ElementaryStream and produces H.264 NAL unit data
 * events.
 */
H264Stream = function() {
  var
    nalByteStream = new NalByteStream(),
    self,
    trackId,
    currentPts,
    currentDts,

    discardEmulationPreventionBytes,
    readSequenceParameterSet,
    skipScalingList;

  H264Stream.prototype.init.call(this);
  self = this;

  /*
   * Pushes a packet from a stream onto the NalByteStream
   *
   * @param {Object} packet - A packet received from a stream
   * @param {Uint8Array} packet.data - The raw bytes of the packet
   * @param {Number} packet.dts - Decode timestamp of the packet
   * @param {Number} packet.pts - Presentation timestamp of the packet
   * @param {Number} packet.trackId - The id of the h264 track this packet came from
   * @param {('video'|'audio')} packet.type - The type of packet
   *
   */
  this.push = function(packet) {
    if (packet.type !== 'video') {
      return;
    }
    trackId = packet.trackId;
    currentPts = packet.pts;
    currentDts = packet.dts;

    nalByteStream.push(packet);
  };

  /*
   * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
   * for the NALUs to the next stream component.
   * Also, preprocess caption and sequence parameter NALUs.
   *
   * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
   * @see NalByteStream.push
   */
  nalByteStream.on('data', function(data) {
    var
      event = {
        trackId: trackId,
        pts: currentPts,
        dts: currentDts,
        data: data
      };

    switch (data[0] & 0x1f) {
    case 0x05:
      event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
      break;
    case 0x06:
      event.nalUnitType = 'sei_rbsp';
      event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
      break;
    case 0x07:
      event.nalUnitType = 'seq_parameter_set_rbsp';
      event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
      event.config = readSequenceParameterSet(event.escapedRBSP);
      break;
    case 0x08:
      event.nalUnitType = 'pic_parameter_set_rbsp';
      break;
    case 0x09:
      event.nalUnitType = 'access_unit_delimiter_rbsp';
      break;

    default:
      break;
    }
    // This triggers data on the H264Stream
    self.trigger('data', event);
  });
  nalByteStream.on('done', function() {
    self.trigger('done');
  });
  nalByteStream.on('partialdone', function() {
    self.trigger('partialdone');
  });
  nalByteStream.on('reset', function() {
    self.trigger('reset');
  });
  nalByteStream.on('endedtimeline', function() {
    self.trigger('endedtimeline');
  });

  this.flush = function() {
    nalByteStream.flush();
  };

  this.partialFlush = function() {
    nalByteStream.partialFlush();
  };

  this.reset = function() {
    nalByteStream.reset();
  };

  this.endTimeline = function() {
    nalByteStream.endTimeline();
  };

  /**
   * Advance the ExpGolomb decoder past a scaling list. The scaling
   * list is optionally transmitted as part of a sequence parameter
   * set and is not relevant to transmuxing.
   * @param count {number} the number of entries in this scaling list
   * @param expGolombDecoder {object} an ExpGolomb pointed to the
   * start of a scaling list
   * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
   */
  skipScalingList = function(count, expGolombDecoder) {
    var
      lastScale = 8,
      nextScale = 8,
      j,
      deltaScale;

    for (j = 0; j < count; j++) {
      if (nextScale !== 0) {
        deltaScale = expGolombDecoder.readExpGolomb();
        nextScale = (lastScale + deltaScale + 256) % 256;
      }

      lastScale = (nextScale === 0) ? lastScale : nextScale;
    }
  };

  /**
   * Expunge any "Emulation Prevention" bytes from a "Raw Byte
   * Sequence Payload"
   * @param data {Uint8Array} the bytes of a RBSP from a NAL
   * unit
   * @return {Uint8Array} the RBSP without any Emulation
   * Prevention Bytes
   */
  discardEmulationPreventionBytes = function(data) {
    var
      length = data.byteLength,
      emulationPreventionBytesPositions = [],
      i = 1,
      newLength, newData;

    // Find all `Emulation Prevention Bytes`
    while (i < length - 2) {
      if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
        emulationPreventionBytesPositions.push(i + 2);
        i += 2;
      } else {
        i++;
      }
    }

    // If no Emulation Prevention Bytes were found just return the original
    // array
    if (emulationPreventionBytesPositions.length === 0) {
      return data;
    }

    // Create a new array to hold the NAL unit data
    newLength = length - emulationPreventionBytesPositions.length;
    newData = new Uint8Array(newLength);
    var sourceIndex = 0;

    for (i = 0; i < newLength; sourceIndex++, i++) {
      if (sourceIndex === emulationPreventionBytesPositions[0]) {
        // Skip this byte
        sourceIndex++;
        // Remove this position index
        emulationPreventionBytesPositions.shift();
      }
      newData[i] = data[sourceIndex];
    }

    return newData;
  };

  /**
   * Read a sequence parameter set and return some interesting video
   * properties. A sequence parameter set is the H264 metadata that
   * describes the properties of upcoming video frames.
   * @param data {Uint8Array} the bytes of a sequence parameter set
   * @return {object} an object with configuration parsed from the
   * sequence parameter set, including the dimensions of the
   * associated video frames.
   */
  readSequenceParameterSet = function(data) {
    var
      frameCropLeftOffset = 0,
      frameCropRightOffset = 0,
      frameCropTopOffset = 0,
      frameCropBottomOffset = 0,
      sarScale = 1,
      expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
      chromaFormatIdc, picOrderCntType,
      numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
      picHeightInMapUnitsMinus1,
      frameMbsOnlyFlag,
      scalingListCount,
      sarRatio,
      aspectRatioIdc,
      i;

    expGolombDecoder = new ExpGolomb(data);
    profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
    profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
    levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
    expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id

    // some profiles have more optional data we don't need
    if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
      chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
      if (chromaFormatIdc === 3) {
        expGolombDecoder.skipBits(1); // separate_colour_plane_flag
      }
      expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
      expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
      expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
      if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
        scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
        for (i = 0; i < scalingListCount; i++) {
          if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
            if (i < 6) {
              skipScalingList(16, expGolombDecoder);
            } else {
              skipScalingList(64, expGolombDecoder);
            }
          }
        }
      }
    }

    expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
    picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();

    if (picOrderCntType === 0) {
      expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
    } else if (picOrderCntType === 1) {
      expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
      expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
      expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
      numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
      for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
        expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
      }
    }

    expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
    expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag

    picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
    picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();

    frameMbsOnlyFlag = expGolombDecoder.readBits(1);
    if (frameMbsOnlyFlag === 0) {
      expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
    }

    expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
    if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
      frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
      frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
      frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
      frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
    }
    if (expGolombDecoder.readBoolean()) {
      // vui_parameters_present_flag
      if (expGolombDecoder.readBoolean()) {
        // aspect_ratio_info_present_flag
        aspectRatioIdc = expGolombDecoder.readUnsignedByte();
        switch (aspectRatioIdc) {
          case 1: sarRatio = [1, 1]; break;
          case 2: sarRatio = [12, 11]; break;
          case 3: sarRatio = [10, 11]; break;
          case 4: sarRatio = [16, 11]; break;
          case 5: sarRatio = [40, 33]; break;
          case 6: sarRatio = [24, 11]; break;
          case 7: sarRatio = [20, 11]; break;
          case 8: sarRatio = [32, 11]; break;
          case 9: sarRatio = [80, 33]; break;
          case 10: sarRatio = [18, 11]; break;
          case 11: sarRatio = [15, 11]; break;
          case 12: sarRatio = [64, 33]; break;
          case 13: sarRatio = [160, 99]; break;
          case 14: sarRatio = [4, 3]; break;
          case 15: sarRatio = [3, 2]; break;
          case 16: sarRatio = [2, 1]; break;
          case 255: {
            sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
                        expGolombDecoder.readUnsignedByte(),
                        expGolombDecoder.readUnsignedByte() << 8 |
                        expGolombDecoder.readUnsignedByte() ];
            break;
          }
        }
        if (sarRatio) {
          sarScale = sarRatio[0] / sarRatio[1];
        }
      }
    }
    return {
      profileIdc: profileIdc,
      levelIdc: levelIdc,
      profileCompatibility: profileCompatibility,
      width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
      height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2),
      sarRatio: sarRatio
    };
  };

};
H264Stream.prototype = new Stream();

module.exports = {
  H264Stream: H264Stream,
  NalByteStream: NalByteStream
};

},{"48":48,"49":49}],5:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
module.exports = {
  Adts: require(3),
  h264: require(4)
};

},{"3":3,"4":4}],6:[function(require,module,exports){
// constants
var AUDIO_PROPERTIES = [
  'audioobjecttype',
  'channelcount',
  'samplerate',
  'samplingfrequencyindex',
  'samplesize'
];

module.exports = AUDIO_PROPERTIES;

},{}],7:[function(require,module,exports){
var VIDEO_PROPERTIES = [
  'width',
  'height',
  'profileIdc',
  'levelIdc',
  'profileCompatibility',
  'sarRatio'
];


module.exports = VIDEO_PROPERTIES;

},{}],8:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
var highPrefix = [33, 16, 5, 32, 164, 27];
var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
var zeroFill = function(count) {
  var a = [];
  while (count--) {
    a.push(0);
  }
  return a;
};

var makeTable = function(metaTable) {
  return Object.keys(metaTable).reduce(function(obj, key) {
    obj[key] = new Uint8Array(metaTable[key].reduce(function(arr, part) {
      return arr.concat(part);
    }, []));
    return obj;
  }, {});
};


var silence;

module.exports = function() {
  if (!silence) {
    // Frames-of-silence to use for filling in missing AAC frames
    var coneOfSilence = {
      96000: [highPrefix, [227, 64], zeroFill(154), [56]],
      88200: [highPrefix, [231], zeroFill(170), [56]],
      64000: [highPrefix, [248, 192], zeroFill(240), [56]],
      48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
      44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
      32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
      24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
      16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
      12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
      11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
      8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
    };
    silence = makeTable(coneOfSilence);
  }
  return silence;
};

},{}],9:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var Stream = require(49);

/**
 * The final stage of the transmuxer that emits the flv tags
 * for audio, video, and metadata. Also tranlates in time and
 * outputs caption data and id3 cues.
 */
var CoalesceStream = function(options) {
  // Number of Tracks per output segment
  // If greater than 1, we combine multiple
  // tracks into a single segment
  this.numberOfTracks = 0;
  this.metadataStream = options.metadataStream;

  this.videoTags = [];
  this.audioTags = [];
  this.videoTrack = null;
  this.audioTrack = null;
  this.pendingCaptions = [];
  this.pendingMetadata = [];
  this.pendingTracks = 0;
  this.processedTracks = 0;

  CoalesceStream.prototype.init.call(this);

  // Take output from multiple
  this.push = function(output) {
    // buffer incoming captions until the associated video segment
    // finishes
    if (output.text) {
      return this.pendingCaptions.push(output);
    }
    // buffer incoming id3 tags until the final flush
    if (output.frames) {
      return this.pendingMetadata.push(output);
    }

    if (output.track.type === 'video') {
      this.videoTrack = output.track;
      this.videoTags = output.tags;
      this.pendingTracks++;
    }
    if (output.track.type === 'audio') {
      this.audioTrack = output.track;
      this.audioTags = output.tags;
      this.pendingTracks++;
    }
  };
};

CoalesceStream.prototype = new Stream();
CoalesceStream.prototype.flush = function(flushSource) {
  var
    id3,
    caption,
    i,
    timelineStartPts,
    event = {
      tags: {},
      captions: [],
      captionStreams: {},
      metadata: []
    };

  if (this.pendingTracks < this.numberOfTracks) {
    if (flushSource !== 'VideoSegmentStream' &&
        flushSource !== 'AudioSegmentStream') {
      // Return because we haven't received a flush from a data-generating
      // portion of the segment (meaning that we have only recieved meta-data
      // or captions.)
      return;
    } else if (this.pendingTracks === 0) {
      // In the case where we receive a flush without any data having been
      // received we consider it an emitted track for the purposes of coalescing
      // `done` events.
      // We do this for the case where there is an audio and video track in the
      // segment but no audio data. (seen in several playlists with alternate
      // audio tracks and no audio present in the main TS segments.)
      this.processedTracks++;

      if (this.processedTracks < this.numberOfTracks) {
        return;
      }
    }
  }

  this.processedTracks += this.pendingTracks;
  this.pendingTracks = 0;

  if (this.processedTracks < this.numberOfTracks) {
    return;
  }

  if (this.videoTrack) {
    timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  } else if (this.audioTrack) {
    timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  }

  event.tags.videoTags = this.videoTags;
  event.tags.audioTags = this.audioTags;

  // Translate caption PTS times into second offsets into the
  // video timeline for the segment, and add track info
  for (i = 0; i < this.pendingCaptions.length; i++) {
    caption = this.pendingCaptions[i];
    caption.startTime = caption.startPts - timelineStartPts;
    caption.startTime /= 90e3;
    caption.endTime = caption.endPts - timelineStartPts;
    caption.endTime /= 90e3;
    event.captionStreams[caption.stream] = true;
    event.captions.push(caption);
  }

  // Translate ID3 frame PTS times into second offsets into the
  // video timeline for the segment
  for (i = 0; i < this.pendingMetadata.length; i++) {
    id3 = this.pendingMetadata[i];
    id3.cueTime = id3.pts - timelineStartPts;
    id3.cueTime /= 90e3;
    event.metadata.push(id3);
  }
  // We add this to every single emitted segment even though we only need
  // it for the first
  event.metadata.dispatchType = this.metadataStream.dispatchType;

  // Reset stream state
  this.videoTrack = null;
  this.audioTrack = null;
  this.videoTags = [];
  this.audioTags = [];
  this.pendingCaptions.length = 0;
  this.pendingMetadata.length = 0;
  this.pendingTracks = 0;
  this.processedTracks = 0;

  // Emit the final segment
  this.trigger('data', event);

  this.trigger('done');
};

module.exports = CoalesceStream;

},{"49":49}],10:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var FlvTag = require(11);

// For information on the FLV format, see
// http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
// Technically, this function returns the header and a metadata FLV tag
// if duration is greater than zero
// duration in seconds
// @return {object} the bytes of the FLV header as a Uint8Array
var getFlvHeader = function(duration, audio, video) { // :ByteArray {
  var
    headBytes = new Uint8Array(3 + 1 + 1 + 4),
    head = new DataView(headBytes.buffer),
    metadata,
    result,
    metadataLength;

  // default arguments
  duration = duration || 0;
  audio = audio === undefined ? true : audio;
  video = video === undefined ? true : video;

  // signature
  head.setUint8(0, 0x46); // 'F'
  head.setUint8(1, 0x4c); // 'L'
  head.setUint8(2, 0x56); // 'V'

  // version
  head.setUint8(3, 0x01);

  // flags
  head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));

  // data offset, should be 9 for FLV v1
  head.setUint32(5, headBytes.byteLength);

  // init the first FLV tag
  if (duration <= 0) {
    // no duration available so just write the first field of the first
    // FLV tag
    result = new Uint8Array(headBytes.byteLength + 4);
    result.set(headBytes);
    result.set([0, 0, 0, 0], headBytes.byteLength);
    return result;
  }

  // write out the duration metadata tag
  metadata = new FlvTag(FlvTag.METADATA_TAG);
  metadata.pts = metadata.dts = 0;
  metadata.writeMetaDataDouble('duration', duration);
  metadataLength = metadata.finalize().length;
  result = new Uint8Array(headBytes.byteLength + metadataLength);
  result.set(headBytes);
  result.set(head.byteLength, metadataLength);

  return result;
};

module.exports = getFlvHeader;

},{"11":11}],11:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * An object that stores the bytes of an FLV tag and methods for
 * querying and manipulating that data.
 * @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf
 */
'use strict';

var FlvTag;

// (type:uint, extraData:Boolean = false) extends ByteArray
FlvTag = function(type, extraData) {
  var
    // Counter if this is a metadata tag, nal start marker if this is a video
    // tag. unused if this is an audio tag
    adHoc = 0, // :uint

    // The default size is 16kb but this is not enough to hold iframe
    // data and the resizing algorithm costs a bit so we create a larger
    // starting buffer for video tags
    bufferStartSize = 16384,

    // checks whether the FLV tag has enough capacity to accept the proposed
    // write and re-allocates the internal buffers if necessary
    prepareWrite = function(flv, count) {
      var
        bytes,
        minLength = flv.position + count;
      if (minLength < flv.bytes.byteLength) {
        // there's enough capacity so do nothing
        return;
      }

      // allocate a new buffer and copy over the data that will not be modified
      bytes = new Uint8Array(minLength * 2);
      bytes.set(flv.bytes.subarray(0, flv.position), 0);
      flv.bytes = bytes;
      flv.view = new DataView(flv.bytes.buffer);
    },

    // commonly used metadata properties
    widthBytes = FlvTag.widthBytes || new Uint8Array('width'.length),
    heightBytes = FlvTag.heightBytes || new Uint8Array('height'.length),
    videocodecidBytes = FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length),
    i;

  if (!FlvTag.widthBytes) {
    // calculating the bytes of common metadata names ahead of time makes the
    // corresponding writes faster because we don't have to loop over the
    // characters
    // re-test with test/perf.html if you're planning on changing this
    for (i = 0; i < 'width'.length; i++) {
      widthBytes[i] = 'width'.charCodeAt(i);
    }
    for (i = 0; i < 'height'.length; i++) {
      heightBytes[i] = 'height'.charCodeAt(i);
    }
    for (i = 0; i < 'videocodecid'.length; i++) {
      videocodecidBytes[i] = 'videocodecid'.charCodeAt(i);
    }

    FlvTag.widthBytes = widthBytes;
    FlvTag.heightBytes = heightBytes;
    FlvTag.videocodecidBytes = videocodecidBytes;
  }

  this.keyFrame = false; // :Boolean

  switch (type) {
  case FlvTag.VIDEO_TAG:
    this.length = 16;
    // Start the buffer at 256k
    bufferStartSize *= 6;
    break;
  case FlvTag.AUDIO_TAG:
    this.length = 13;
    this.keyFrame = true;
    break;
  case FlvTag.METADATA_TAG:
    this.length = 29;
    this.keyFrame = true;
    break;
  default:
    throw new Error('Unknown FLV tag type');
  }

  this.bytes = new Uint8Array(bufferStartSize);
  this.view = new DataView(this.bytes.buffer);
  this.bytes[0] = type;
  this.position = this.length;
  this.keyFrame = extraData; // Defaults to false

  // presentation timestamp
  this.pts = 0;
  // decoder timestamp
  this.dts = 0;

  // ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)
  this.writeBytes = function(bytes, offset, length) {
    var
      start = offset || 0,
      end;
    length = length || bytes.byteLength;
    end = start + length;

    prepareWrite(this, length);
    this.bytes.set(bytes.subarray(start, end), this.position);

    this.position += length;
    this.length = Math.max(this.length, this.position);
  };

  // ByteArray#writeByte(value:int):void
  this.writeByte = function(byte) {
    prepareWrite(this, 1);
    this.bytes[this.position] = byte;
    this.position++;
    this.length = Math.max(this.length, this.position);
  };

  // ByteArray#writeShort(value:int):void
  this.writeShort = function(short) {
    prepareWrite(this, 2);
    this.view.setUint16(this.position, short);
    this.position += 2;
    this.length = Math.max(this.length, this.position);
  };

  // Negative index into array
  // (pos:uint):int
  this.negIndex = function(pos) {
    return this.bytes[this.length - pos];
  };

  // The functions below ONLY work when this[0] == VIDEO_TAG.
  // We are not going to check for that because we dont want the overhead
  // (nal:ByteArray = null):int
  this.nalUnitSize = function() {
    if (adHoc === 0) {
      return 0;
    }

    return this.length - (adHoc + 4);
  };

  this.startNalUnit = function() {
    // remember position and add 4 bytes
    if (adHoc > 0) {
      throw new Error('Attempted to create new NAL wihout closing the old one');
    }

    // reserve 4 bytes for nal unit size
    adHoc = this.length;
    this.length += 4;
    this.position = this.length;
  };

  // (nal:ByteArray = null):void
  this.endNalUnit = function(nalContainer) {
    var
      nalStart, // :uint
      nalLength; // :uint

    // Rewind to the marker and write the size
    if (this.length === adHoc + 4) {
      // we started a nal unit, but didnt write one, so roll back the 4 byte size value
      this.length -= 4;
    } else if (adHoc > 0) {
      nalStart = adHoc + 4;
      nalLength = this.length - nalStart;

      this.position = adHoc;
      this.view.setUint32(this.position, nalLength);
      this.position = this.length;

      if (nalContainer) {
        // Add the tag to the NAL unit
        nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength));
      }
    }

    adHoc = 0;
  };

  /**
   * Write out a 64-bit floating point valued metadata property. This method is
   * called frequently during a typical parse and needs to be fast.
   */
  // (key:String, val:Number):void
  this.writeMetaDataDouble = function(key, val) {
    var i;
    prepareWrite(this, 2 + key.length + 9);

    // write size of property name
    this.view.setUint16(this.position, key.length);
    this.position += 2;

    // this next part looks terrible but it improves parser throughput by
    // 10kB/s in my testing

    // write property name
    if (key === 'width') {
      this.bytes.set(widthBytes, this.position);
      this.position += 5;
    } else if (key === 'height') {
      this.bytes.set(heightBytes, this.position);
      this.position += 6;
    } else if (key === 'videocodecid') {
      this.bytes.set(videocodecidBytes, this.position);
      this.position += 12;
    } else {
      for (i = 0; i < key.length; i++) {
        this.bytes[this.position] = key.charCodeAt(i);
        this.position++;
      }
    }

    // skip null byte
    this.position++;

    // write property value
    this.view.setFloat64(this.position, val);
    this.position += 8;

    // update flv tag length
    this.length = Math.max(this.length, this.position);
    ++adHoc;
  };

  // (key:String, val:Boolean):void
  this.writeMetaDataBoolean = function(key, val) {
    var i;
    prepareWrite(this, 2);
    this.view.setUint16(this.position, key.length);
    this.position += 2;
    for (i = 0; i < key.length; i++) {
      // if key.charCodeAt(i) >= 255, handle error
      prepareWrite(this, 1);
      this.bytes[this.position] = key.charCodeAt(i);
      this.position++;
    }
    prepareWrite(this, 2);
    this.view.setUint8(this.position, 0x01);
    this.position++;
    this.view.setUint8(this.position, val ? 0x01 : 0x00);
    this.position++;
    this.length = Math.max(this.length, this.position);
    ++adHoc;
  };

  // ():ByteArray
  this.finalize = function() {
    var
      dtsDelta, // :int
      len; // :int

    switch (this.bytes[0]) {
      // Video Data
    case FlvTag.VIDEO_TAG:
       // We only support AVC, 1 = key frame (for AVC, a seekable
       // frame), 2 = inter frame (for AVC, a non-seekable frame)
      this.bytes[11] = ((this.keyFrame || extraData) ? 0x10 : 0x20) | 0x07;
      this.bytes[12] = extraData ?  0x00 : 0x01;

      dtsDelta = this.pts - this.dts;
      this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16;
      this.bytes[14] = (dtsDelta & 0x0000FF00) >>>  8;
      this.bytes[15] = (dtsDelta & 0x000000FF) >>>  0;
      break;

    case FlvTag.AUDIO_TAG:
      this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo
      this.bytes[12] = extraData ? 0x00 : 0x01;
      break;

    case FlvTag.METADATA_TAG:
      this.position = 11;
      this.view.setUint8(this.position, 0x02); // String type
      this.position++;
      this.view.setUint16(this.position, 0x0A); // 10 Bytes
      this.position += 2;
      // set "onMetaData"
      this.bytes.set([0x6f, 0x6e, 0x4d, 0x65,
                      0x74, 0x61, 0x44, 0x61,
                      0x74, 0x61], this.position);
      this.position += 10;
      this.bytes[this.position] = 0x08; // Array type
      this.position++;
      this.view.setUint32(this.position, adHoc);
      this.position = this.length;
      this.bytes.set([0, 0, 9], this.position);
      this.position += 3; // End Data Tag
      this.length = this.position;
      break;
    }

    len = this.length - 11;

    // write the DataSize field
    this.bytes[ 1] = (len & 0x00FF0000) >>> 16;
    this.bytes[ 2] = (len & 0x0000FF00) >>>  8;
    this.bytes[ 3] = (len & 0x000000FF) >>>  0;
    // write the Timestamp
    this.bytes[ 4] = (this.dts & 0x00FF0000) >>> 16;
    this.bytes[ 5] = (this.dts & 0x0000FF00) >>>  8;
    this.bytes[ 6] = (this.dts & 0x000000FF) >>>  0;
    this.bytes[ 7] = (this.dts & 0xFF000000) >>> 24;
    // write the StreamID
    this.bytes[ 8] = 0;
    this.bytes[ 9] = 0;
    this.bytes[10] = 0;

    // Sometimes we're at the end of the view and have one slot to write a
    // uint32, so, prepareWrite of count 4, since, view is uint8
    prepareWrite(this, 4);
    this.view.setUint32(this.length, this.length);
    this.length += 4;
    this.position += 4;

    // trim down the byte buffer to what is actually being used
    this.bytes = this.bytes.subarray(0, this.length);
    this.frameTime = FlvTag.frameTime(this.bytes);
    // if bytes.bytelength isn't equal to this.length, handle error
    return this;
  };
};

FlvTag.AUDIO_TAG = 0x08; // == 8, :uint
FlvTag.VIDEO_TAG = 0x09; // == 9, :uint
FlvTag.METADATA_TAG = 0x12; // == 18, :uint

// (tag:ByteArray):Boolean {
FlvTag.isAudioFrame = function(tag) {
  return FlvTag.AUDIO_TAG === tag[0];
};

// (tag:ByteArray):Boolean {
FlvTag.isVideoFrame = function(tag) {
  return FlvTag.VIDEO_TAG === tag[0];
};

// (tag:ByteArray):Boolean {
FlvTag.isMetaData = function(tag) {
  return FlvTag.METADATA_TAG === tag[0];
};

// (tag:ByteArray):Boolean {
FlvTag.isKeyFrame = function(tag) {
  if (FlvTag.isVideoFrame(tag)) {
    return tag[11] === 0x17;
  }

  if (FlvTag.isAudioFrame(tag)) {
    return true;
  }

  if (FlvTag.isMetaData(tag)) {
    return true;
  }

  return false;
};

// (tag:ByteArray):uint {
FlvTag.frameTime = function(tag) {
  var pts = tag[ 4] << 16; // :uint
  pts |= tag[ 5] <<  8;
  pts |= tag[ 6] <<  0;
  pts |= tag[ 7] << 24;
  return pts;
};

module.exports = FlvTag;

},{}],12:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
module.exports = {
  tag: require(11),
  Transmuxer: require(14),
  getFlvHeader: require(10)
};

},{"10":10,"11":11,"14":14}],13:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var TagList = function() {
  var self = this;

  this.list = [];

  this.push = function(tag) {
    this.list.push({
      bytes: tag.bytes,
      dts: tag.dts,
      pts: tag.pts,
      keyFrame: tag.keyFrame,
      metaDataTag: tag.metaDataTag
    });
  };

  Object.defineProperty(this, 'length', {
    get: function() {
      return self.list.length;
    }
  });
};

module.exports = TagList;

},{}],14:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var Stream = require(49);
var FlvTag = require(11);
var m2ts = require(18);
var AdtsStream = require(3);
var H264Stream = require(4).H264Stream;
var CoalesceStream = require(9);
var TagList = require(13);

var
  Transmuxer,
  VideoSegmentStream,
  AudioSegmentStream,
  collectTimelineInfo,
  metaDataTag,
  extraDataTag;

/**
 * Store information about the start and end of the tracka and the
 * duration for each frame/sample we process in order to calculate
 * the baseMediaDecodeTime
 */
collectTimelineInfo = function(track, data) {
  if (typeof data.pts === 'number') {
    if (track.timelineStartInfo.pts === undefined) {
      track.timelineStartInfo.pts = data.pts;
    } else {
      track.timelineStartInfo.pts =
        Math.min(track.timelineStartInfo.pts, data.pts);
    }
  }

  if (typeof data.dts === 'number') {
    if (track.timelineStartInfo.dts === undefined) {
      track.timelineStartInfo.dts = data.dts;
    } else {
      track.timelineStartInfo.dts =
        Math.min(track.timelineStartInfo.dts, data.dts);
    }
  }
};

metaDataTag = function(track, pts) {
  var
    tag = new FlvTag(FlvTag.METADATA_TAG); // :FlvTag

  tag.dts = pts;
  tag.pts = pts;

  tag.writeMetaDataDouble('videocodecid', 7);
  tag.writeMetaDataDouble('width', track.width);
  tag.writeMetaDataDouble('height', track.height);

  return tag;
};

extraDataTag = function(track, pts) {
  var
    i,
    tag = new FlvTag(FlvTag.VIDEO_TAG, true);

  tag.dts = pts;
  tag.pts = pts;

  tag.writeByte(0x01);// version
  tag.writeByte(track.profileIdc);// profile
  tag.writeByte(track.profileCompatibility);// compatibility
  tag.writeByte(track.levelIdc);// level
  tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits)
  tag.writeByte(0xE0 | 0x01); // reserved (3 bits), num of SPS (5 bits)
  tag.writeShort(track.sps[0].length); // data of SPS
  tag.writeBytes(track.sps[0]); // SPS

  tag.writeByte(track.pps.length); // num of PPS (will there ever be more that 1 PPS?)
  for (i = 0; i < track.pps.length; ++i) {
    tag.writeShort(track.pps[i].length); // 2 bytes for length of PPS
    tag.writeBytes(track.pps[i]); // data of PPS
  }

  return tag;
};

/**
 * Constructs a single-track, media segment from AAC data
 * events. The output of this stream can be fed to flash.
 */
AudioSegmentStream = function(track) {
  var
    adtsFrames = [],
    videoKeyFrames = [],
    oldExtraData;

  AudioSegmentStream.prototype.init.call(this);

  this.push = function(data) {
    collectTimelineInfo(track, data);

    if (track) {
      track.audioobjecttype = data.audioobjecttype;
      track.channelcount = data.channelcount;
      track.samplerate = data.samplerate;
      track.samplingfrequencyindex = data.samplingfrequencyindex;
      track.samplesize = data.samplesize;
      track.extraData = (track.audioobjecttype << 11) |
                        (track.samplingfrequencyindex << 7) |
                        (track.channelcount << 3);
    }

    data.pts = Math.round(data.pts / 90);
    data.dts = Math.round(data.dts / 90);

    // buffer audio data until end() is called
    adtsFrames.push(data);
  };

  this.flush = function() {
    var currentFrame, adtsFrame, lastMetaPts, tags = new TagList();
    // return early if no audio data has been observed
    if (adtsFrames.length === 0) {
      this.trigger('done', 'AudioSegmentStream');
      return;
    }

    lastMetaPts = -Infinity;

    while (adtsFrames.length) {
      currentFrame = adtsFrames.shift();

      // write out a metadata frame at every video key frame
      if (videoKeyFrames.length && currentFrame.pts >= videoKeyFrames[0]) {
        lastMetaPts = videoKeyFrames.shift();
        this.writeMetaDataTags(tags, lastMetaPts);
      }

      // also write out metadata tags every 1 second so that the decoder
      // is re-initialized quickly after seeking into a different
      // audio configuration.
      if (track.extraData !== oldExtraData || currentFrame.pts - lastMetaPts >= 1000) {
        this.writeMetaDataTags(tags, currentFrame.pts);
        oldExtraData = track.extraData;
        lastMetaPts = currentFrame.pts;
      }

      adtsFrame = new FlvTag(FlvTag.AUDIO_TAG);
      adtsFrame.pts = currentFrame.pts;
      adtsFrame.dts = currentFrame.dts;

      adtsFrame.writeBytes(currentFrame.data);

      tags.push(adtsFrame.finalize());
    }

    videoKeyFrames.length = 0;
    oldExtraData = null;
    this.trigger('data', {track: track, tags: tags.list});

    this.trigger('done', 'AudioSegmentStream');
  };

  this.writeMetaDataTags = function(tags, pts) {
    var adtsFrame;

    adtsFrame = new FlvTag(FlvTag.METADATA_TAG);
    // For audio, DTS is always the same as PTS. We want to set the DTS
    // however so we can compare with video DTS to determine approximate
    // packet order
    adtsFrame.pts = pts;
    adtsFrame.dts = pts;

    // AAC is always 10
    adtsFrame.writeMetaDataDouble('audiocodecid', 10);
    adtsFrame.writeMetaDataBoolean('stereo', track.channelcount === 2);
    adtsFrame.writeMetaDataDouble('audiosamplerate', track.samplerate);
    // Is AAC always 16 bit?
    adtsFrame.writeMetaDataDouble('audiosamplesize', 16);

    tags.push(adtsFrame.finalize());

    adtsFrame = new FlvTag(FlvTag.AUDIO_TAG, true);
    // For audio, DTS is always the same as PTS. We want to set the DTS
    // however so we can compare with video DTS to determine approximate
    // packet order
    adtsFrame.pts = pts;
    adtsFrame.dts = pts;

    adtsFrame.view.setUint16(adtsFrame.position, track.extraData);
    adtsFrame.position += 2;
    adtsFrame.length = Math.max(adtsFrame.length, adtsFrame.position);

    tags.push(adtsFrame.finalize());
  };

  this.onVideoKeyFrame = function(pts) {
    videoKeyFrames.push(pts);
  };
};
AudioSegmentStream.prototype = new Stream();

/**
 * Store FlvTags for the h264 stream
 * @param track {object} track metadata configuration
 */
VideoSegmentStream = function(track) {
  var
    nalUnits = [],
    config,
    h264Frame;
  VideoSegmentStream.prototype.init.call(this);

  this.finishFrame = function(tags, frame) {
    if (!frame) {
      return;
    }
    // Check if keyframe and the length of tags.
    // This makes sure we write metadata on the first frame of a segment.
    if (config && track && track.newMetadata &&
        (frame.keyFrame || tags.length === 0)) {
      // Push extra data on every IDR frame in case we did a stream change + seek
      var metaTag = metaDataTag(config, frame.dts).finalize();
      var extraTag = extraDataTag(track, frame.dts).finalize();

      metaTag.metaDataTag = extraTag.metaDataTag = true;

      tags.push(metaTag);
      tags.push(extraTag);
      track.newMetadata = false;

      this.trigger('keyframe', frame.dts);
    }

    frame.endNalUnit();
    tags.push(frame.finalize());
    h264Frame = null;
  };

  this.push = function(data) {
    collectTimelineInfo(track, data);

    data.pts = Math.round(data.pts / 90);
    data.dts = Math.round(data.dts / 90);

    // buffer video until flush() is called
    nalUnits.push(data);
  };

  this.flush = function() {
    var
      currentNal,
      tags = new TagList();

    // Throw away nalUnits at the start of the byte stream until we find
    // the first AUD
    while (nalUnits.length) {
      if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
        break;
      }
      nalUnits.shift();
    }

    // return early if no video data has been observed
    if (nalUnits.length === 0) {
      this.trigger('done', 'VideoSegmentStream');
      return;
    }

    while (nalUnits.length) {
      currentNal = nalUnits.shift();

      // record the track config
      if (currentNal.nalUnitType === 'seq_parameter_set_rbsp') {
        track.newMetadata = true;
        config = currentNal.config;
        track.width = config.width;
        track.height = config.height;
        track.sps = [currentNal.data];
        track.profileIdc = config.profileIdc;
        track.levelIdc = config.levelIdc;
        track.profileCompatibility = config.profileCompatibility;
        h264Frame.endNalUnit();
      } else if (currentNal.nalUnitType === 'pic_parameter_set_rbsp') {
        track.newMetadata = true;
        track.pps = [currentNal.data];
        h264Frame.endNalUnit();
      } else if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
        if (h264Frame) {
          this.finishFrame(tags, h264Frame);
        }
        h264Frame = new FlvTag(FlvTag.VIDEO_TAG);
        h264Frame.pts = currentNal.pts;
        h264Frame.dts = currentNal.dts;
      } else {
        if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
          // the current sample is a key frame
          h264Frame.keyFrame = true;
        }
        h264Frame.endNalUnit();
      }
      h264Frame.startNalUnit();
      h264Frame.writeBytes(currentNal.data);
    }
    if (h264Frame) {
      this.finishFrame(tags, h264Frame);
    }

    this.trigger('data', {track: track, tags: tags.list});

    // Continue with the flush process now
    this.trigger('done', 'VideoSegmentStream');
  };
};

VideoSegmentStream.prototype = new Stream();

/**
 * An object that incrementally transmuxes MPEG2 Trasport Stream
 * chunks into an FLV.
 */
Transmuxer = function(options) {
  var
    self = this,

    packetStream, parseStream, elementaryStream,
    videoTimestampRolloverStream, audioTimestampRolloverStream,
    timedMetadataTimestampRolloverStream,
    adtsStream, h264Stream,
    videoSegmentStream, audioSegmentStream, captionStream,
    coalesceStream;

  Transmuxer.prototype.init.call(this);

  options = options || {};

  // expose the metadata stream
  this.metadataStream = new m2ts.MetadataStream();

  options.metadataStream = this.metadataStream;

  // set up the parsing pipeline
  packetStream = new m2ts.TransportPacketStream();
  parseStream = new m2ts.TransportParseStream();
  elementaryStream = new m2ts.ElementaryStream();
  videoTimestampRolloverStream = new m2ts.TimestampRolloverStream('video');
  audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');

  adtsStream = new AdtsStream();
  h264Stream = new H264Stream();
  coalesceStream = new CoalesceStream(options);

  // disassemble MPEG2-TS packets into elementary streams
  packetStream
    .pipe(parseStream)
    .pipe(elementaryStream);

  // !!THIS ORDER IS IMPORTANT!!
  // demux the streams
  elementaryStream
    .pipe(videoTimestampRolloverStream)
    .pipe(h264Stream);
  elementaryStream
    .pipe(audioTimestampRolloverStream)
    .pipe(adtsStream);

  elementaryStream
    .pipe(timedMetadataTimestampRolloverStream)
    .pipe(this.metadataStream)
    .pipe(coalesceStream);
  // if CEA-708 parsing is available, hook up a caption stream
  captionStream = new m2ts.CaptionStream();
  h264Stream.pipe(captionStream)
    .pipe(coalesceStream);

  // hook up the segment streams once track metadata is delivered
  elementaryStream.on('data', function(data) {
    var i, videoTrack, audioTrack;

    if (data.type === 'metadata') {
      i = data.tracks.length;

      // scan the tracks listed in the metadata
      while (i--) {
        if (data.tracks[i].type === 'video') {
          videoTrack = data.tracks[i];
        } else if (data.tracks[i].type === 'audio') {
          audioTrack = data.tracks[i];
        }
      }

      // hook up the video segment stream to the first track with h264 data
      if (videoTrack && !videoSegmentStream) {
        coalesceStream.numberOfTracks++;
        videoSegmentStream = new VideoSegmentStream(videoTrack);

        // Set up the final part of the video pipeline
        h264Stream
          .pipe(videoSegmentStream)
          .pipe(coalesceStream);
      }

      if (audioTrack && !audioSegmentStream) {
        // hook up the audio segment stream to the first track with aac data
        coalesceStream.numberOfTracks++;
        audioSegmentStream = new AudioSegmentStream(audioTrack);

        // Set up the final part of the audio pipeline
        adtsStream
          .pipe(audioSegmentStream)
          .pipe(coalesceStream);

        if (videoSegmentStream) {
          videoSegmentStream.on('keyframe', audioSegmentStream.onVideoKeyFrame);
        }
      }
    }
  });

  // feed incoming data to the front of the parsing pipeline
  this.push = function(data) {
    packetStream.push(data);
  };

  // flush any buffered data
  this.flush = function() {
    // Start at the top of the pipeline and flush all pending work
    packetStream.flush();
  };

  // Caption data has to be reset when seeking outside buffered range
  this.resetCaptions = function() {
    captionStream.reset();
  };

  // Re-emit any data coming from the coalesce stream to the outside world
  coalesceStream.on('data', function(event) {
    self.trigger('data', event);
  });

  // Let the consumer know we have finished flushing the entire pipeline
  coalesceStream.on('done', function() {
    self.trigger('done');
  });
};
Transmuxer.prototype = new Stream();

// forward compatibility
module.exports = Transmuxer;

},{"11":11,"13":13,"18":18,"3":3,"4":4,"49":49,"9":9}],15:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var muxjs = {
  codecs: require(5),
  mp4: require(27),
  flv: require(12),
  mp2t: require(17),
  partial: require(34)
};

// include all the tools when the full library is required
muxjs.mp4.tools = require(39);
muxjs.flv.tools = require(38);
muxjs.mp2t.tools = require(45);


module.exports = muxjs;

},{"12":12,"17":17,"27":27,"34":34,"38":38,"39":39,"45":45,"5":5}],16:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Reads in-band caption information from a video elementary
 * stream. Captions must follow the CEA-708 standard for injection
 * into an MPEG-2 transport streams.
 * @see https://en.wikipedia.org/wiki/CEA-708
 * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
 */

'use strict';

// -----------------
// Link To Transport
// -----------------

var Stream = require(49);
var cea708Parser = require(37);

var CaptionStream = function() {

  CaptionStream.prototype.init.call(this);

  this.captionPackets_ = [];

  this.ccStreams_ = [
    new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
    new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
    new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
    new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  ];

  this.cc708Stream_ = new Cea708Stream(); // eslint-disable-line no-use-before-define

  this.reset();

  // forward data and done events from CCs to this CaptionStream
  this.ccStreams_.forEach(function(cc) {
    cc.on('data', this.trigger.bind(this, 'data'));
    cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
    cc.on('done', this.trigger.bind(this, 'done'));
  }, this);

  this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));

};

CaptionStream.prototype = new Stream();
CaptionStream.prototype.push = function(event) {
  var sei, userData, newCaptionPackets;

  // only examine SEI NALs
  if (event.nalUnitType !== 'sei_rbsp') {
    return;
  }

  // parse the sei
  sei = cea708Parser.parseSei(event.escapedRBSP);

  // no payload data, skip
  if (!sei.payload) {
    return;
  }

  // ignore everything but user_data_registered_itu_t_t35
  if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
    return;
  }

  // parse out the user data payload
  userData = cea708Parser.parseUserData(sei);

  // ignore unrecognized userData
  if (!userData) {
    return;
  }

  // Sometimes, the same segment # will be downloaded twice. To stop the
  // caption data from being processed twice, we track the latest dts we've
  // received and ignore everything with a dts before that. However, since
  // data for a specific dts can be split across packets on either side of
  // a segment boundary, we need to make sure we *don't* ignore the packets
  // from the *next* segment that have dts === this.latestDts_. By constantly
  // tracking the number of packets received with dts === this.latestDts_, we
  // know how many should be ignored once we start receiving duplicates.
  if (event.dts < this.latestDts_) {
    // We've started getting older data, so set the flag.
    this.ignoreNextEqualDts_ = true;
    return;
  } else if ((event.dts === this.latestDts_) && (this.ignoreNextEqualDts_)) {
    this.numSameDts_--;
    if (!this.numSameDts_) {
      // We've received the last duplicate packet, time to start processing again
      this.ignoreNextEqualDts_ = false;
    }
    return;
  }

  // parse out CC data packets and save them for later
  newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  if (this.latestDts_ !== event.dts) {
    this.numSameDts_ = 0;
  }
  this.numSameDts_++;
  this.latestDts_ = event.dts;
};

CaptionStream.prototype.flushCCStreams = function(flushType) {
  this.ccStreams_.forEach(function(cc) {
    return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  }, this);
};

CaptionStream.prototype.flushStream = function(flushType) {
  // make sure we actually parsed captions before proceeding
  if (!this.captionPackets_.length) {
    this.flushCCStreams(flushType);
    return;
  }

  // In Chrome, the Array#sort function is not stable so add a
  // presortIndex that we can use to ensure we get a stable-sort
  this.captionPackets_.forEach(function(elem, idx) {
    elem.presortIndex = idx;
  });

  // sort caption byte-pairs based on their PTS values
  this.captionPackets_.sort(function(a, b) {
    if (a.pts === b.pts) {
      return a.presortIndex - b.presortIndex;
    }
    return a.pts - b.pts;
  });

  this.captionPackets_.forEach(function(packet) {
    if (packet.type < 2) {
      // Dispatch packet to the right Cea608Stream
      this.dispatchCea608Packet(packet);
    } else {
      // Dispatch packet to the Cea708Stream
      this.dispatchCea708Packet(packet);
    }
  }, this);

  this.captionPackets_.length = 0;
  this.flushCCStreams(flushType);
};

CaptionStream.prototype.flush = function() {
  return this.flushStream('flush');
};

// Only called if handling partial data
CaptionStream.prototype.partialFlush = function() {
  return this.flushStream('partialFlush');
};

CaptionStream.prototype.reset = function() {
  this.latestDts_ = null;
  this.ignoreNextEqualDts_ = false;
  this.numSameDts_ = 0;
  this.activeCea608Channel_ = [null, null];
  this.ccStreams_.forEach(function(ccStream) {
    ccStream.reset();
  });
};

// From the CEA-608 spec:
/*
 * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
 * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
 * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
 * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
 * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
 * to switch to captioning or Text.
*/
// With that in mind, we ignore any data between an XDS control code and a
// subsequent closed-captioning control code.
CaptionStream.prototype.dispatchCea608Packet = function(packet) {
  // NOTE: packet.type is the CEA608 field
  if (this.setsTextOrXDSActive(packet)) {
    this.activeCea608Channel_[packet.type] = null;
  } else if (this.setsChannel1Active(packet)) {
    this.activeCea608Channel_[packet.type] = 0;
  } else if (this.setsChannel2Active(packet)) {
    this.activeCea608Channel_[packet.type] = 1;
  }
  if (this.activeCea608Channel_[packet.type] === null) {
    // If we haven't received anything to set the active channel, or the
    // packets are Text/XDS data, discard the data; we don't want jumbled
    // captions
    return;
  }
  this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
};

CaptionStream.prototype.setsChannel1Active = function(packet) {
  return ((packet.ccData & 0x7800) === 0x1000);
};
CaptionStream.prototype.setsChannel2Active = function(packet) {
  return ((packet.ccData & 0x7800) === 0x1800);
};
CaptionStream.prototype.setsTextOrXDSActive = function(packet) {
  return ((packet.ccData & 0x7100) === 0x0100) ||
    ((packet.ccData & 0x78fe) === 0x102a) ||
    ((packet.ccData & 0x78fe) === 0x182a);
};

CaptionStream.prototype.dispatchCea708Packet = function(packet) {
  this.cc708Stream_.push(packet);
};


// ----------------------
// Session to Application
// ----------------------

// This hash maps special and extended character codes to their
// proper Unicode equivalent. The first one-byte key is just a
// non-standard character code. The two-byte keys that follow are
// the extended CEA708 character codes, along with the preceding
// 0x10 extended character byte to distinguish these codes from
// non-extended character codes. Every CEA708 character code that
// is not in this object maps directly to a standard unicode
// character code.
// The transparent space and non-breaking transparent space are
// technically not fully supported since there is no code to
// make them transparent, so they have normal non-transparent
// stand-ins.
// The special closed caption (CC) character isn't a standard
// unicode character, so a fairly similar unicode character was
// chosen in it's place.
var CHARACTER_TRANSLATION_708 = {
  0x7f: 0x266a,   // ♪
  0x1020: 0x20,   // Transparent Space
  0x1021: 0xa0,   // Nob-breaking Transparent Space
  0x1025: 0x2026, // …
  0x102a: 0x0160, // Š
  0x102c: 0x0152, // Œ
  0x1030: 0x2588, // █
  0x1031: 0x2018, // ‘
  0x1032: 0x2019, // ’
  0x1033: 0x201c, // “
  0x1034: 0x201d, // ”
  0x1035: 0x2022, // •
  0x1039: 0x2122, // ™
  0x103a: 0x0161, // š
  0x103c: 0x0153, // œ
  0x103d: 0x2120, // ℠
  0x103f: 0x0178, // Ÿ
  0x1076: 0x215b, // ⅛
  0x1077: 0x215c, // ⅜
  0x1078: 0x215d, // ⅝
  0x1079: 0x215e, // ⅞
  0x107a: 0x23d0, // ⏐
  0x107b: 0x23a4, // ⎤
  0x107c: 0x23a3, // ⎣
  0x107d: 0x23af, // ⎯
  0x107e: 0x23a6, // ⎦
  0x107f: 0x23a1, // ⎡
  0x10a0: 0x3138  // ㄸ (CC char)
};

var get708CharFromCode = function(code) {
  var newCode = CHARACTER_TRANSLATION_708[code] || code;

  if ((code & 0x1000) && code === newCode) {
    // Invalid extended code
    return '';
  }
  return String.fromCharCode(newCode);
};

var within708TextBlock = function(b) {
  return (0x20 <= b && b <= 0x7f) || (0xa0 <= b && b <= 0xff);
};

var Cea708Window = function(windowNum) {
  this.windowNum = windowNum;
  this.reset();
};

Cea708Window.prototype.reset = function() {
  this.clearText();
  this.pendingNewLine = false;
  this.winAttr = {};
  this.penAttr = {};
  this.penLoc = {};
  this.penColor = {};

  // These default values are arbitrary,
  // defineWindow will usually override them
  this.visible = 0;
  this.rowLock = 0;
  this.columnLock = 0;
  this.priority = 0;
  this.relativePositioning = 0;
  this.anchorVertical = 0;
  this.anchorHorizontal = 0;
  this.anchorPoint = 0;
  this.rowCount = 1;
  this.virtualRowCount = this.rowCount + 1;
  this.columnCount = 41;
  this.windowStyle = 0;
  this.penStyle = 0;
};

Cea708Window.prototype.getText = function() {
  return this.rows.join('\n');
};

Cea708Window.prototype.clearText = function() {
  this.rows = [''];
  this.rowIdx = 0;
};

Cea708Window.prototype.newLine = function(pts) {
  if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
    this.beforeRowOverflow(pts);
  }

  if (this.rows.length > 0) {
    this.rows.push('');
    this.rowIdx++;
  }

  // Show all virtual rows since there's no visible scrolling
  while (this.rows.length > this.virtualRowCount) {
    this.rows.shift();
    this.rowIdx--;
  }
};

Cea708Window.prototype.isEmpty = function() {
  if (this.rows.length === 0) {
    return true;
  } else if (this.rows.length === 1) {
    return this.rows[0] === '';
  }

  return false;
};

Cea708Window.prototype.addText = function(text) {
  this.rows[this.rowIdx] += text;
};

Cea708Window.prototype.backspace = function() {
  if (!this.isEmpty()) {
    var row = this.rows[this.rowIdx];

    this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  }
};

var Cea708Service = function(serviceNum) {
  this.serviceNum = serviceNum;
  this.text = '';
  this.currentWindow = new Cea708Window(-1);
  this.windows = [];
};

/**
 * Initialize service windows
 * Must be run before service use
 *
 * @param  {Integer}  pts               PTS value
 * @param  {Function} beforeRowOverflow Function to execute before row overflow of a window
 */
Cea708Service.prototype.init = function(pts, beforeRowOverflow) {
  this.startPts = pts;

  for (var win = 0; win < 8; win++) {
    this.windows[win] = new Cea708Window(win);

    if (typeof beforeRowOverflow === 'function') {
      this.windows[win].beforeRowOverflow = beforeRowOverflow;
    }
  }
};

/**
 * Set current window of service to be affected by commands
 *
 * @param  {Integer} windowNum Window number
 */
Cea708Service.prototype.setCurrentWindow = function(windowNum) {
  this.currentWindow = this.windows[windowNum];
};

var Cea708Stream = function() {
  Cea708Stream.prototype.init.call(this);

  var self = this;
  this.current708Packet = null;
  this.services = {};

  this.push = function(packet) {
    if (packet.type === 3) {
      // 708 packet start
      self.new708Packet();
      self.add708Bytes(packet);
    } else {
      if (self.current708Packet === null) {
        // This should only happen at the start of a file if there's no packet start.
        self.new708Packet();
      }

      self.add708Bytes(packet);
    }
  };
};
Cea708Stream.prototype = new Stream();

/**
 * Push current 708 packet, create new 708 packet.
 */
Cea708Stream.prototype.new708Packet = function() {
  if (this.current708Packet !== null) {
    this.push708Packet();
  }

  this.current708Packet = {
    data: [],
    ptsVals: []
  };
};

/**
 * Add pts and both bytes from packet into current 708 packet.
 */
Cea708Stream.prototype.add708Bytes = function(packet) {
  var data = packet.ccData;
  var byte0 = data >>> 8;
  var byte1 = data & 0xff;

  // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  // that service blocks will always line up with byte pairs.
  this.current708Packet.ptsVals.push(packet.pts);
  this.current708Packet.data.push(byte0);
  this.current708Packet.data.push(byte1);
};

/**
 * Parse completed 708 packet into service blocks and push each service block.
 */
Cea708Stream.prototype.push708Packet = function() {
  var packet708 = this.current708Packet;
  var packetData = packet708.data;
  var serviceNum = null;
  var blockSize = null;
  var i = 0;
  var b = packetData[i++];

  packet708.seq = b >> 6;
  packet708.sizeCode = b & 0x3f; // 0b00111111;

  for (; i < packetData.length; i++) {
    b = packetData[i++];
    serviceNum = b >> 5;
    blockSize = b & 0x1f; // 0b00011111

    if (serviceNum === 7 && blockSize > 0) {
      // Extended service num
      b = packetData[i++];
      serviceNum = b;
    }

    this.pushServiceBlock(serviceNum, i, blockSize);

    if (blockSize > 0) {
      i += blockSize - 1;
    }
  }
};

/**
 * Parse service block, execute commands, read text.
 *
 * Note: While many of these commands serve important purposes,
 * many others just parse out the parameters or attributes, but
 * nothing is done with them because this is not a full and complete
 * implementation of the entire 708 spec.
 *
 * @param  {Integer} serviceNum Service number
 * @param  {Integer} start      Start index of the 708 packet data
 * @param  {Integer} size       Block size
 */
Cea708Stream.prototype.pushServiceBlock = function(serviceNum, start, size) {
  var b;
  var i = start;
  var packetData = this.current708Packet.data;
  var service = this.services[serviceNum];

  if (!service) {
    service = this.initService(serviceNum, i);
  }

  for (; i < start + size && i < packetData.length; i++) {
    b = packetData[i];

    if (within708TextBlock(b)) {
      i = this.handleText(i, service);
    } else if (b === 0x10) {
      i = this.extendedCommands(i, service);
    } else if (0x80 <= b && b <= 0x87) {
      i = this.setCurrentWindow(i, service);
    } else if (0x98 <= b && b <= 0x9f) {
      i = this.defineWindow(i, service);
    } else if (b === 0x88) {
      i = this.clearWindows(i, service);
    } else if (b === 0x8c) {
      i = this.deleteWindows(i, service);
    } else if (b === 0x89) {
      i = this.displayWindows(i, service);
    } else if (b === 0x8a) {
      i = this.hideWindows(i, service);
    } else if (b === 0x8b) {
      i = this.toggleWindows(i, service);
    } else if (b === 0x97) {
      i = this.setWindowAttributes(i, service);
    } else if (b === 0x90) {
      i = this.setPenAttributes(i, service);
    } else if (b === 0x91) {
      i = this.setPenColor(i, service);
    } else if (b === 0x92) {
      i = this.setPenLocation(i, service);
    } else if (b === 0x8f) {
      service = this.reset(i, service);
    } else if (b === 0x08) {
      // BS: Backspace
      service.currentWindow.backspace();
    } else if (b === 0x0c) {
      // FF: Form feed
      service.currentWindow.clearText();
    } else if (b === 0x0d) {
      // CR: Carriage return
      service.currentWindow.pendingNewLine = true;
    } else if (b === 0x0e) {
      // HCR: Horizontal carriage return
      service.currentWindow.clearText();
    } else if (b === 0x8d) {
      // DLY: Delay, nothing to do
      i++;
    } else if (b === 0x8e) {
      // DLC: Delay cancel, nothing to do
    } else if (b === 0x03) {
      // ETX: End Text, don't need to do anything
    } else if (b === 0x00) {
      // Padding
    } else {
      // Unknown command
    }
  }
};

/**
 * Execute an extended command
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.extendedCommands = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[++i];
  if (within708TextBlock(b)) {
    i = this.handleText(i, service, true);
  } else {
    // Unknown command
  }

  return i;
};

/**
 * Get PTS value of a given byte index
 *
 * @param  {Integer} byteIndex  Index of the byte
 * @return {Integer}            PTS
 */
Cea708Stream.prototype.getPts = function(byteIndex) {
  // There's 1 pts value per 2 bytes
  return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
};

/**
 * Initializes a service
 *
 * @param  {Integer} serviceNum Service number
 * @return {Service}            Initialized service object
 */
Cea708Stream.prototype.initService = function(serviceNum, i) {
  var self = this;

  this.services[serviceNum] = new Cea708Service(serviceNum);
  this.services[serviceNum].init(this.getPts(i), function(pts) {
    self.flushDisplayed(pts, self.services[serviceNum]);
  });

  return this.services[serviceNum];
};

/**
 * Execute text writing to current window
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.handleText = function(i, service, isExtended) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var extended = isExtended ? 0x1000 : 0x0000;
  var char = get708CharFromCode(extended | b);
  var win = service.currentWindow;

  if (win.pendingNewLine && !win.isEmpty()) {
    win.newLine(this.getPts(i));
  }
  win.pendingNewLine = false;
  win.addText(char);

  return i;
};

/**
 * Parse and execute the CW# command.
 *
 * Set the current window.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.setCurrentWindow = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var windowNum = b & 0x07;

  service.setCurrentWindow(windowNum);

  return i;
};

/**
 * Parse and execute the DF# command.
 *
 * Define a window and set it as the current window.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.defineWindow = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var windowNum = b & 0x07;
  service.setCurrentWindow(windowNum);
  var win = service.currentWindow;

  b = packetData[++i];
  win.visible    = (b & 0x20) >> 5; // v
  win.rowLock    = (b & 0x10) >> 4; // rl
  win.columnLock = (b & 0x08) >> 3; // cl
  win.priority   = b & 0x07;        // p

  b = packetData[++i];
  win.relativePositioning = (b & 0x80) >> 7; // rp
  win.anchorVertical      = b & 0x7f;        // av

  b = packetData[++i];
  win.anchorHorizontal = b; // ah

  b = packetData[++i];
  win.anchorPoint = (b & 0xf0) >> 4; // ap
  win.rowCount    = b & 0x0f;        // rc

  b = packetData[++i];
  win.columnCount = b & 0x3f; // cc

  b = packetData[++i];
  win.windowStyle = (b & 0x38) >> 3; // ws
  win.penStyle    = b & 0x07;        // ps

  // The spec says there are (rowCount+1) "virtual rows"
  win.virtualRowCount = win.rowCount + 1;

  return i;
};

/**
 * Parse and execute the SWA command.
 *
 * Set attributes of the current window.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.setWindowAttributes = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var winAttr = service.currentWindow.winAttr;

  b = packetData[++i];
  winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  winAttr.fillRed     = (b & 0x30) >> 4; // fr
  winAttr.fillGreen   = (b & 0x0c) >> 2; // fg
  winAttr.fillBlue    = b & 0x03;        // fb

  b = packetData[++i];
  winAttr.borderType  = (b & 0xc0) >> 6; // bt
  winAttr.borderRed   = (b & 0x30) >> 4; // br
  winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  winAttr.borderBlue  = b & 0x03;        // bb

  b = packetData[++i];
  winAttr.borderType     += (b & 0x80) >> 5; // bt
  winAttr.wordWrap        = (b & 0x40) >> 6; // ww
  winAttr.printDirection  = (b & 0x30) >> 4; // pd
  winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  winAttr.justify         = b & 0x03;        // j

  b = packetData[++i];
  winAttr.effectSpeed     = (b & 0xf0) >> 4; // es
  winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  winAttr.displayEffect   = b & 0x03;        // de

  return i;
};

/**
 * Gather text from all displayed windows and push a caption to output.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 */
Cea708Stream.prototype.flushDisplayed = function(pts, service) {
  var displayedText = [];

  // TODO: Positioning not supported, displaying multiple windows will not necessarily
  // display text in the correct order, but sample files so far have not shown any issue.
  for (var winId = 0; winId < 8; winId++) {
    if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
      displayedText.push(service.windows[winId].getText());
    }
  }

  service.endPts = pts;
  service.text = displayedText.join('\n\n');
  this.pushCaption(service);

  service.startPts = pts;
};

/**
 * Push a caption to output if the caption contains text.
 *
 * @param  {Service} service  The service object to be affected
 */
Cea708Stream.prototype.pushCaption = function(service) {
  if (service.text !== '') {
    this.trigger('data', {
      startPts: service.startPts,
      endPts: service.endPts,
      text: service.text,
      stream: 'cc708_' + service.serviceNum
    });

    service.text = '';
    service.startPts = service.endPts;
  }
};

/**
 * Parse and execute the DSW command.
 *
 * Set visible property of windows based on the parsed bitmask.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.displayWindows = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[++i];
  var pts = this.getPts(i);

  this.flushDisplayed(pts, service);

  for (var winId = 0; winId < 8; winId++) {
    if (b & (0x01 << winId)) {
      service.windows[winId].visible = 1;
    }
  }

  return i;
};

/**
 * Parse and execute the HDW command.
 *
 * Set visible property of windows based on the parsed bitmask.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.hideWindows = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[++i];
  var pts = this.getPts(i);

  this.flushDisplayed(pts, service);

  for (var winId = 0; winId < 8; winId++) {
    if (b & (0x01 << winId)) {
      service.windows[winId].visible = 0;
    }
  }

  return i;
};

/**
 * Parse and execute the TGW command.
 *
 * Set visible property of windows based on the parsed bitmask.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.toggleWindows = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[++i];
  var pts = this.getPts(i);

  this.flushDisplayed(pts, service);

  for (var winId = 0; winId < 8; winId++) {
    if (b & (0x01 << winId)) {
      service.windows[winId].visible ^= 1;
    }
  }

  return i;
};

/**
 * Parse and execute the CLW command.
 *
 * Clear text of windows based on the parsed bitmask.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.clearWindows = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[++i];
  var pts = this.getPts(i);

  this.flushDisplayed(pts, service);

  for (var winId = 0; winId < 8; winId++) {
    if (b & (0x01 << winId)) {
      service.windows[winId].clearText();
    }
  }

  return i;
};

/**
 * Parse and execute the DLW command.
 *
 * Re-initialize windows based on the parsed bitmask.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.deleteWindows = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[++i];
  var pts = this.getPts(i);

  this.flushDisplayed(pts, service);

  for (var winId = 0; winId < 8; winId++) {
    if (b & (0x01 << winId)) {
      service.windows[winId].reset();
    }
  }

  return i;
};

/**
 * Parse and execute the SPA command.
 *
 * Set pen attributes of the current window.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.setPenAttributes = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var penAttr = service.currentWindow.penAttr;

  b = packetData[++i];
  penAttr.textTag = (b & 0xf0) >> 4; // tt
  penAttr.offset  = (b & 0x0c) >> 2; // o
  penAttr.penSize = b & 0x03;        // s

  b = packetData[++i];
  penAttr.italics   = (b & 0x80) >> 7; // i
  penAttr.underline = (b & 0x40) >> 6; // u
  penAttr.edgeType  = (b & 0x38) >> 3; // et
  penAttr.fontStyle = b & 0x07;        // fs

  return i;
};

/**
 * Parse and execute the SPC command.
 *
 * Set pen color of the current window.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.setPenColor = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var penColor = service.currentWindow.penColor;

  b = packetData[++i];
  penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  penColor.fgRed     = (b & 0x30) >> 4; // fr
  penColor.fgGreen   = (b & 0x0c) >> 2; // fg
  penColor.fgBlue    = b & 0x03;        // fb

  b = packetData[++i];
  penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  penColor.bgRed     = (b & 0x30) >> 4; // br
  penColor.bgGreen   = (b & 0x0c) >> 2; // bg
  penColor.bgBlue    = b & 0x03;        // bb

  b = packetData[++i];
  penColor.edgeRed   = (b & 0x30) >> 4; // er
  penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  penColor.edgeBlue  = b & 0x03;        // eb

  return i;
};

/**
 * Parse and execute the SPL command.
 *
 * Set pen location of the current window.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Integer}          New index after parsing
 */
Cea708Stream.prototype.setPenLocation = function(i, service) {
  var packetData = this.current708Packet.data;
  var b = packetData[i];
  var penLoc = service.currentWindow.penLoc;

  // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  service.currentWindow.pendingNewLine = true;

  b = packetData[++i];
  penLoc.row = b & 0x0f; // r

  b = packetData[++i];
  penLoc.column = b & 0x3f; // c

  return i;
};

/**
 * Execute the RST command.
 *
 * Reset service to a clean slate. Re-initialize.
 *
 * @param  {Integer} i        Current index in the 708 packet
 * @param  {Service} service  The service object to be affected
 * @return {Service}          Re-initialized service
 */
Cea708Stream.prototype.reset = function(i, service) {
  var pts = this.getPts(i);

  this.flushDisplayed(pts, service);

  return this.initService(service.serviceNum, i);
};


// This hash maps non-ASCII, special, and extended character codes to their
// proper Unicode equivalent. The first keys that are only a single byte
// are the non-standard ASCII characters, which simply map the CEA608 byte
// to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
// character codes, but have their MSB bitmasked with 0x03 so that a lookup
// can be performed regardless of the field and data channel on which the
// character code was received.
var CHARACTER_TRANSLATION = {
  0x2a: 0xe1,     // á
  0x5c: 0xe9,     // é
  0x5e: 0xed,     // í
  0x5f: 0xf3,     // ó
  0x60: 0xfa,     // ú
  0x7b: 0xe7,     // ç
  0x7c: 0xf7,     // ÷
  0x7d: 0xd1,     // Ñ
  0x7e: 0xf1,     // ñ
  0x7f: 0x2588,   // █
  0x0130: 0xae,   // ®
  0x0131: 0xb0,   // °
  0x0132: 0xbd,   // ½
  0x0133: 0xbf,   // ¿
  0x0134: 0x2122, // ™
  0x0135: 0xa2,   // ¢
  0x0136: 0xa3,   // £
  0x0137: 0x266a, // ♪
  0x0138: 0xe0,   // à
  0x0139: 0xa0,   //
  0x013a: 0xe8,   // è
  0x013b: 0xe2,   // â
  0x013c: 0xea,   // ê
  0x013d: 0xee,   // î
  0x013e: 0xf4,   // ô
  0x013f: 0xfb,   // û
  0x0220: 0xc1,   // Á
  0x0221: 0xc9,   // É
  0x0222: 0xd3,   // Ó
  0x0223: 0xda,   // Ú
  0x0224: 0xdc,   // Ü
  0x0225: 0xfc,   // ü
  0x0226: 0x2018, // ‘
  0x0227: 0xa1,   // ¡
  0x0228: 0x2a,   // *
  0x0229: 0x27,   // '
  0x022a: 0x2014, // —
  0x022b: 0xa9,   // ©
  0x022c: 0x2120, // ℠
  0x022d: 0x2022, // •
  0x022e: 0x201c, // “
  0x022f: 0x201d, // ”
  0x0230: 0xc0,   // À
  0x0231: 0xc2,   // Â
  0x0232: 0xc7,   // Ç
  0x0233: 0xc8,   // È
  0x0234: 0xca,   // Ê
  0x0235: 0xcb,   // Ë
  0x0236: 0xeb,   // ë
  0x0237: 0xce,   // Î
  0x0238: 0xcf,   // Ï
  0x0239: 0xef,   // ï
  0x023a: 0xd4,   // Ô
  0x023b: 0xd9,   // Ù
  0x023c: 0xf9,   // ù
  0x023d: 0xdb,   // Û
  0x023e: 0xab,   // «
  0x023f: 0xbb,   // »
  0x0320: 0xc3,   // Ã
  0x0321: 0xe3,   // ã
  0x0322: 0xcd,   // Í
  0x0323: 0xcc,   // Ì
  0x0324: 0xec,   // ì
  0x0325: 0xd2,   // Ò
  0x0326: 0xf2,   // ò
  0x0327: 0xd5,   // Õ
  0x0328: 0xf5,   // õ
  0x0329: 0x7b,   // {
  0x032a: 0x7d,   // }
  0x032b: 0x5c,   // \
  0x032c: 0x5e,   // ^
  0x032d: 0x5f,   // _
  0x032e: 0x7c,   // |
  0x032f: 0x7e,   // ~
  0x0330: 0xc4,   // Ä
  0x0331: 0xe4,   // ä
  0x0332: 0xd6,   // Ö
  0x0333: 0xf6,   // ö
  0x0334: 0xdf,   // ß
  0x0335: 0xa5,   // ¥
  0x0336: 0xa4,   // ¤
  0x0337: 0x2502, // │
  0x0338: 0xc5,   // Å
  0x0339: 0xe5,   // å
  0x033a: 0xd8,   // Ø
  0x033b: 0xf8,   // ø
  0x033c: 0x250c, // ┌
  0x033d: 0x2510, // ┐
  0x033e: 0x2514, // └
  0x033f: 0x2518  // ┘
};

var getCharFromCode = function(code) {
  if (code === null) {
    return '';
  }
  code = CHARACTER_TRANSLATION[code] || code;
  return String.fromCharCode(code);
};

// the index of the last row in a CEA-608 display buffer
var BOTTOM_ROW = 14;

// This array is used for mapping PACs -> row #, since there's no way of
// getting it through bit logic.
var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620,
            0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420];

// CEA-608 captions are rendered onto a 34x15 matrix of character
// cells. The "bottom" row is the last element in the outer array.
var createDisplayBuffer = function() {
  var result = [], i = BOTTOM_ROW + 1;
  while (i--) {
    result.push('');
  }
  return result;
};

var Cea608Stream = function(field, dataChannel) {
  Cea608Stream.prototype.init.call(this);

  this.field_ = field || 0;
  this.dataChannel_ = dataChannel || 0;

  this.name_ = 'CC' + (((this.field_ << 1) | this.dataChannel_) + 1);

  this.setConstants();
  this.reset();

  this.push = function(packet) {
    var data, swap, char0, char1, text;
    // remove the parity bits
    data = packet.ccData & 0x7f7f;

    // ignore duplicate control codes; the spec demands they're sent twice
    if (data === this.lastControlCode_) {
      this.lastControlCode_ = null;
      return;
    }

    // Store control codes
    if ((data & 0xf000) === 0x1000) {
      this.lastControlCode_ = data;
    } else if (data !== this.PADDING_) {
      this.lastControlCode_ = null;
    }

    char0 = data >>> 8;
    char1 = data & 0xff;

    if (data === this.PADDING_) {
      return;

    } else if (data === this.RESUME_CAPTION_LOADING_) {
      this.mode_ = 'popOn';

    } else if (data === this.END_OF_CAPTION_) {
      // If an EOC is received while in paint-on mode, the displayed caption
      // text should be swapped to non-displayed memory as if it was a pop-on
      // caption. Because of that, we should explicitly switch back to pop-on
      // mode
      this.mode_ = 'popOn';
      this.clearFormatting(packet.pts);
      // if a caption was being displayed, it's gone now
      this.flushDisplayed(packet.pts);

      // flip memory
      swap = this.displayed_;
      this.displayed_ = this.nonDisplayed_;
      this.nonDisplayed_ = swap;

      // start measuring the time to display the caption
      this.startPts_ = packet.pts;

    } else if (data === this.ROLL_UP_2_ROWS_) {
      this.rollUpRows_ = 2;
      this.setRollUp(packet.pts);
    } else if (data === this.ROLL_UP_3_ROWS_) {
      this.rollUpRows_ = 3;
      this.setRollUp(packet.pts);
    } else if (data === this.ROLL_UP_4_ROWS_) {
      this.rollUpRows_ = 4;
      this.setRollUp(packet.pts);
    } else if (data === this.CARRIAGE_RETURN_) {
      this.clearFormatting(packet.pts);
      this.flushDisplayed(packet.pts);
      this.shiftRowsUp_();
      this.startPts_ = packet.pts;

    } else if (data === this.BACKSPACE_) {
      if (this.mode_ === 'popOn') {
        this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
      } else {
        this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
      }
    } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
      this.flushDisplayed(packet.pts);
      this.displayed_ = createDisplayBuffer();
    } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
      this.nonDisplayed_ = createDisplayBuffer();

    } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
      if (this.mode_ !== 'paintOn') {
        // NOTE: This should be removed when proper caption positioning is
        // implemented
        this.flushDisplayed(packet.pts);
        this.displayed_ = createDisplayBuffer();
      }
      this.mode_ = 'paintOn';
      this.startPts_ = packet.pts;

    // Append special characters to caption text
    } else if (this.isSpecialCharacter(char0, char1)) {
      // Bitmask char0 so that we can apply character transformations
      // regardless of field and data channel.
      // Then byte-shift to the left and OR with char1 so we can pass the
      // entire character code to `getCharFromCode`.
      char0 = (char0 & 0x03) << 8;
      text = getCharFromCode(char0 | char1);
      this[this.mode_](packet.pts, text);
      this.column_++;

    // Append extended characters to caption text
    } else if (this.isExtCharacter(char0, char1)) {
      // Extended characters always follow their "non-extended" equivalents.
      // IE if a "è" is desired, you'll always receive "eè"; non-compliant
      // decoders are supposed to drop the "è", while compliant decoders
      // backspace the "e" and insert "è".

      // Delete the previous character
      if (this.mode_ === 'popOn') {
        this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
      } else {
        this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
      }

      // Bitmask char0 so that we can apply character transformations
      // regardless of field and data channel.
      // Then byte-shift to the left and OR with char1 so we can pass the
      // entire character code to `getCharFromCode`.
      char0 = (char0 & 0x03) << 8;
      text = getCharFromCode(char0 | char1);
      this[this.mode_](packet.pts, text);
      this.column_++;

    // Process mid-row codes
    } else if (this.isMidRowCode(char0, char1)) {
      // Attributes are not additive, so clear all formatting
      this.clearFormatting(packet.pts);

      // According to the standard, mid-row codes
      // should be replaced with spaces, so add one now
      this[this.mode_](packet.pts, ' ');
      this.column_++;

      if ((char1 & 0xe) === 0xe) {
        this.addFormatting(packet.pts, ['i']);
      }

      if ((char1 & 0x1) === 0x1) {
        this.addFormatting(packet.pts, ['u']);
      }

    // Detect offset control codes and adjust cursor
    } else if (this.isOffsetControlCode(char0, char1)) {
      // Cursor position is set by indent PAC (see below) in 4-column
      // increments, with an additional offset code of 1-3 to reach any
      // of the 32 columns specified by CEA-608. So all we need to do
      // here is increment the column cursor by the given offset.
      this.column_ += (char1 & 0x03);

    // Detect PACs (Preamble Address Codes)
    } else if (this.isPAC(char0, char1)) {

      // There's no logic for PAC -> row mapping, so we have to just
      // find the row code in an array and use its index :(
      var row = ROWS.indexOf(data & 0x1f20);

      // Configure the caption window if we're in roll-up mode
      if (this.mode_ === 'rollUp') {
        // This implies that the base row is incorrectly set.
        // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
        // of roll-up rows set.
        if (row - this.rollUpRows_ + 1 < 0) {
          row = this.rollUpRows_ - 1;
        }

        this.setRollUp(packet.pts, row);
      }

      if (row !== this.row_) {
        // formatting is only persistent for current row
        this.clearFormatting(packet.pts);
        this.row_ = row;
      }
      // All PACs can apply underline, so detect and apply
      // (All odd-numbered second bytes set underline)
      if ((char1 & 0x1) && (this.formatting_.indexOf('u') === -1)) {
          this.addFormatting(packet.pts, ['u']);
      }

      if ((data & 0x10) === 0x10) {
        // We've got an indent level code. Each successive even number
        // increments the column cursor by 4, so we can get the desired
        // column position by bit-shifting to the right (to get n/2)
        // and multiplying by 4.
        this.column_ = ((data & 0xe) >> 1) * 4;
      }

      if (this.isColorPAC(char1)) {
        // it's a color code, though we only support white, which
        // can be either normal or italicized. white italics can be
        // either 0x4e or 0x6e depending on the row, so we just
        // bitwise-and with 0xe to see if italics should be turned on
        if ((char1 & 0xe) === 0xe) {
          this.addFormatting(packet.pts, ['i']);
        }
      }

    // We have a normal character in char0, and possibly one in char1
    } else if (this.isNormalChar(char0)) {
      if (char1 === 0x00) {
        char1 = null;
      }
      text = getCharFromCode(char0);
      text += getCharFromCode(char1);
      this[this.mode_](packet.pts, text);
      this.column_ += text.length;

    } // finish data processing

  };
};
Cea608Stream.prototype = new Stream();
// Trigger a cue point that captures the current state of the
// display buffer
Cea608Stream.prototype.flushDisplayed = function(pts) {
  var content = this.displayed_
    // remove spaces from the start and end of the string
    .map(function(row) {
      try {
        return row.trim();
      } catch (e) {
        // Ordinarily, this shouldn't happen. However, caption
        // parsing errors should not throw exceptions and
        // break playback.
        // eslint-disable-next-line no-console
        console.error('Skipping malformed caption.');
        return '';
      }
    })
    // combine all text rows to display in one cue
    .join('\n')
    // and remove blank rows from the start and end, but not the middle
    .replace(/^\n+|\n+$/g, '');

  if (content.length) {
    this.trigger('data', {
      startPts: this.startPts_,
      endPts: pts,
      text: content,
      stream: this.name_
    });
  }
};

/**
 * Zero out the data, used for startup and on seek
 */
Cea608Stream.prototype.reset = function() {
  this.mode_ = 'popOn';
  // When in roll-up mode, the index of the last row that will
  // actually display captions. If a caption is shifted to a row
  // with a lower index than this, it is cleared from the display
  // buffer
  this.topRow_ = 0;
  this.startPts_ = 0;
  this.displayed_ = createDisplayBuffer();
  this.nonDisplayed_ = createDisplayBuffer();
  this.lastControlCode_ = null;

  // Track row and column for proper line-breaking and spacing
  this.column_ = 0;
  this.row_ = BOTTOM_ROW;
  this.rollUpRows_ = 2;

  // This variable holds currently-applied formatting
  this.formatting_ = [];
};

/**
 * Sets up control code and related constants for this instance
 */
Cea608Stream.prototype.setConstants = function() {
  // The following attributes have these uses:
  // ext_ :    char0 for mid-row codes, and the base for extended
  //           chars (ext_+0, ext_+1, and ext_+2 are char0s for
  //           extended codes)
  // control_: char0 for control codes, except byte-shifted to the
  //           left so that we can do this.control_ | CONTROL_CODE
  // offset_:  char0 for tab offset codes
  //
  // It's also worth noting that control codes, and _only_ control codes,
  // differ between field 1 and field2. Field 2 control codes are always
  // their field 1 value plus 1. That's why there's the "| field" on the
  // control value.
  if (this.dataChannel_ === 0) {
    this.BASE_     = 0x10;
    this.EXT_      = 0x11;
    this.CONTROL_  = (0x14 | this.field_) << 8;
    this.OFFSET_   = 0x17;
  } else if (this.dataChannel_ === 1) {
    this.BASE_     = 0x18;
    this.EXT_      = 0x19;
    this.CONTROL_  = (0x1c | this.field_) << 8;
    this.OFFSET_   = 0x1f;
  }

  // Constants for the LSByte command codes recognized by Cea608Stream. This
  // list is not exhaustive. For a more comprehensive listing and semantics see
  // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  // Padding
  this.PADDING_                    = 0x0000;
  // Pop-on Mode
  this.RESUME_CAPTION_LOADING_     = this.CONTROL_ | 0x20;
  this.END_OF_CAPTION_             = this.CONTROL_ | 0x2f;
  // Roll-up Mode
  this.ROLL_UP_2_ROWS_             = this.CONTROL_ | 0x25;
  this.ROLL_UP_3_ROWS_             = this.CONTROL_ | 0x26;
  this.ROLL_UP_4_ROWS_             = this.CONTROL_ | 0x27;
  this.CARRIAGE_RETURN_            = this.CONTROL_ | 0x2d;
  // paint-on mode
  this.RESUME_DIRECT_CAPTIONING_   = this.CONTROL_ | 0x29;
  // Erasure
  this.BACKSPACE_                  = this.CONTROL_ | 0x21;
  this.ERASE_DISPLAYED_MEMORY_     = this.CONTROL_ | 0x2c;
  this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
};

/**
 * Detects if the 2-byte packet data is a special character
 *
 * Special characters have a second byte in the range 0x30 to 0x3f,
 * with the first byte being 0x11 (for data channel 1) or 0x19 (for
 * data channel 2).
 *
 * @param  {Integer} char0 The first byte
 * @param  {Integer} char1 The second byte
 * @return {Boolean}       Whether the 2 bytes are an special character
 */
Cea608Stream.prototype.isSpecialCharacter = function(char0, char1) {
  return (char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f);
};

/**
 * Detects if the 2-byte packet data is an extended character
 *
 * Extended characters have a second byte in the range 0x20 to 0x3f,
 * with the first byte being 0x12 or 0x13 (for data channel 1) or
 * 0x1a or 0x1b (for data channel 2).
 *
 * @param  {Integer} char0 The first byte
 * @param  {Integer} char1 The second byte
 * @return {Boolean}       Whether the 2 bytes are an extended character
 */
Cea608Stream.prototype.isExtCharacter = function(char0, char1) {
  return ((char0 === (this.EXT_ + 1) || char0 === (this.EXT_ + 2)) &&
    (char1 >= 0x20 && char1 <= 0x3f));
};

/**
 * Detects if the 2-byte packet is a mid-row code
 *
 * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
 * the first byte being 0x11 (for data channel 1) or 0x19 (for data
 * channel 2).
 *
 * @param  {Integer} char0 The first byte
 * @param  {Integer} char1 The second byte
 * @return {Boolean}       Whether the 2 bytes are a mid-row code
 */
Cea608Stream.prototype.isMidRowCode = function(char0, char1) {
  return (char0 === this.EXT_ && (char1 >= 0x20 && char1 <= 0x2f));
};

/**
 * Detects if the 2-byte packet is an offset control code
 *
 * Offset control codes have a second byte in the range 0x21 to 0x23,
 * with the first byte being 0x17 (for data channel 1) or 0x1f (for
 * data channel 2).
 *
 * @param  {Integer} char0 The first byte
 * @param  {Integer} char1 The second byte
 * @return {Boolean}       Whether the 2 bytes are an offset control code
 */
Cea608Stream.prototype.isOffsetControlCode = function(char0, char1) {
  return (char0 === this.OFFSET_ && (char1 >= 0x21 && char1 <= 0x23));
};

/**
 * Detects if the 2-byte packet is a Preamble Address Code
 *
 * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
 * or 0x18 to 0x1f (for data channel 2), with the second byte in the
 * range 0x40 to 0x7f.
 *
 * @param  {Integer} char0 The first byte
 * @param  {Integer} char1 The second byte
 * @return {Boolean}       Whether the 2 bytes are a PAC
 */
Cea608Stream.prototype.isPAC = function(char0, char1) {
  return (char0 >= this.BASE_ && char0 < (this.BASE_ + 8) &&
    (char1 >= 0x40 && char1 <= 0x7f));
};

/**
 * Detects if a packet's second byte is in the range of a PAC color code
 *
 * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
 * 0x60 to 0x6f.
 *
 * @param  {Integer} char1 The second byte
 * @return {Boolean}       Whether the byte is a color PAC
 */
Cea608Stream.prototype.isColorPAC = function(char1) {
  return ((char1 >= 0x40 && char1 <= 0x4f) || (char1 >= 0x60 && char1 <= 0x7f));
};

/**
 * Detects if a single byte is in the range of a normal character
 *
 * Normal text bytes are in the range 0x20 to 0x7f.
 *
 * @param  {Integer} char  The byte
 * @return {Boolean}       Whether the byte is a normal character
 */
Cea608Stream.prototype.isNormalChar = function(char) {
  return (char >= 0x20 && char <= 0x7f);
};

/**
 * Configures roll-up
 *
 * @param  {Integer} pts         Current PTS
 * @param  {Integer} newBaseRow  Used by PACs to slide the current window to
 *                               a new position
 */
Cea608Stream.prototype.setRollUp = function(pts, newBaseRow) {
  // Reset the base row to the bottom row when switching modes
  if (this.mode_ !== 'rollUp') {
    this.row_ = BOTTOM_ROW;
    this.mode_ = 'rollUp';
    // Spec says to wipe memories when switching to roll-up
    this.flushDisplayed(pts);
    this.nonDisplayed_ = createDisplayBuffer();
    this.displayed_ = createDisplayBuffer();
  }

  if (newBaseRow !== undefined && newBaseRow !== this.row_) {
    // move currently displayed captions (up or down) to the new base row
    for (var i = 0; i < this.rollUpRows_; i++) {
      this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
      this.displayed_[this.row_ - i] = '';
    }
  }

  if (newBaseRow === undefined) {
    newBaseRow = this.row_;
  }

  this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
};

// Adds the opening HTML tag for the passed character to the caption text,
// and keeps track of it for later closing
Cea608Stream.prototype.addFormatting = function(pts, format) {
  this.formatting_ = this.formatting_.concat(format);
  var text = format.reduce(function(text, format) {
    return text + '<' + format + '>';
  }, '');
  this[this.mode_](pts, text);
};

// Adds HTML closing tags for current formatting to caption text and
// clears remembered formatting
Cea608Stream.prototype.clearFormatting = function(pts) {
  if (!this.formatting_.length) {
    return;
  }
  var text = this.formatting_.reverse().reduce(function(text, format) {
    return text + '</' + format + '>';
  }, '');
  this.formatting_ = [];
  this[this.mode_](pts, text);
};

// Mode Implementations
Cea608Stream.prototype.popOn = function(pts, text) {
  var baseRow = this.nonDisplayed_[this.row_];

  // buffer characters
  baseRow += text;
  this.nonDisplayed_[this.row_] = baseRow;
};

Cea608Stream.prototype.rollUp = function(pts, text) {
  var baseRow = this.displayed_[this.row_];

  baseRow += text;
  this.displayed_[this.row_] = baseRow;

};

Cea608Stream.prototype.shiftRowsUp_ = function() {
  var i;
  // clear out inactive rows
  for (i = 0; i < this.topRow_; i++) {
    this.displayed_[i] = '';
  }
  for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
    this.displayed_[i] = '';
  }
  // shift displayed rows up
  for (i = this.topRow_; i < this.row_; i++) {
    this.displayed_[i] = this.displayed_[i + 1];
  }
  // clear out the bottom row
  this.displayed_[this.row_] = '';
};

Cea608Stream.prototype.paintOn = function(pts, text) {
  var baseRow = this.displayed_[this.row_];

  baseRow += text;
  this.displayed_[this.row_] = baseRow;
};

// exports
module.exports = {
  CaptionStream: CaptionStream,
  Cea608Stream: Cea608Stream,
  Cea708Stream: Cea708Stream
};

},{"37":37,"49":49}],17:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
module.exports = require(18);

},{"18":18}],18:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * A stream-based mp2t to mp4 converter. This utility can be used to
 * deliver mp4s to a SourceBuffer on platforms that support native
 * Media Source Extensions.
 */
'use strict';
var Stream = require(49),
  CaptionStream = require(16),
  StreamTypes = require(21),
  TimestampRolloverStream = require(22).TimestampRolloverStream;

// object types
var TransportPacketStream, TransportParseStream, ElementaryStream;

// constants
var
  MP2T_PACKET_LENGTH = 188, // bytes
  SYNC_BYTE = 0x47;

/**
 * Splits an incoming stream of binary data into MPEG-2 Transport
 * Stream packets.
 */
TransportPacketStream = function() {
  var
    buffer = new Uint8Array(MP2T_PACKET_LENGTH),
    bytesInBuffer = 0;

  TransportPacketStream.prototype.init.call(this);

   // Deliver new bytes to the stream.

  /**
   * Split a stream of data into M2TS packets
  **/
  this.push = function(bytes) {
    var
      startIndex = 0,
      endIndex = MP2T_PACKET_LENGTH,
      everything;

    // If there are bytes remaining from the last segment, prepend them to the
    // bytes that were pushed in
    if (bytesInBuffer) {
      everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
      everything.set(buffer.subarray(0, bytesInBuffer));
      everything.set(bytes, bytesInBuffer);
      bytesInBuffer = 0;
    } else {
      everything = bytes;
    }

    // While we have enough data for a packet
    while (endIndex < everything.byteLength) {
      // Look for a pair of start and end sync bytes in the data..
      if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
        // We found a packet so emit it and jump one whole packet forward in
        // the stream
        this.trigger('data', everything.subarray(startIndex, endIndex));
        startIndex += MP2T_PACKET_LENGTH;
        endIndex += MP2T_PACKET_LENGTH;
        continue;
      }
      // If we get here, we have somehow become de-synchronized and we need to step
      // forward one byte at a time until we find a pair of sync bytes that denote
      // a packet
      startIndex++;
      endIndex++;
    }

    // If there was some data left over at the end of the segment that couldn't
    // possibly be a whole packet, keep it because it might be the start of a packet
    // that continues in the next segment
    if (startIndex < everything.byteLength) {
      buffer.set(everything.subarray(startIndex), 0);
      bytesInBuffer = everything.byteLength - startIndex;
    }
  };

  /**
   * Passes identified M2TS packets to the TransportParseStream to be parsed
  **/
  this.flush = function() {
    // If the buffer contains a whole packet when we are being flushed, emit it
    // and empty the buffer. Otherwise hold onto the data because it may be
    // important for decoding the next segment
    if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
      this.trigger('data', buffer);
      bytesInBuffer = 0;
    }
    this.trigger('done');
  };

  this.endTimeline = function() {
    this.flush();
    this.trigger('endedtimeline');
  };

  this.reset = function() {
    bytesInBuffer = 0;
    this.trigger('reset');
  };
};
TransportPacketStream.prototype = new Stream();

/**
 * Accepts an MP2T TransportPacketStream and emits data events with parsed
 * forms of the individual transport stream packets.
 */
TransportParseStream = function() {
  var parsePsi, parsePat, parsePmt, self;
  TransportParseStream.prototype.init.call(this);
  self = this;

  this.packetsWaitingForPmt = [];
  this.programMapTable = undefined;

  parsePsi = function(payload, psi) {
    var offset = 0;

    // PSI packets may be split into multiple sections and those
    // sections may be split into multiple packets. If a PSI
    // section starts in this packet, the payload_unit_start_indicator
    // will be true and the first byte of the payload will indicate
    // the offset from the current position to the start of the
    // section.
    if (psi.payloadUnitStartIndicator) {
      offset += payload[offset] + 1;
    }

    if (psi.type === 'pat') {
      parsePat(payload.subarray(offset), psi);
    } else {
      parsePmt(payload.subarray(offset), psi);
    }
  };

  parsePat = function(payload, pat) {
    pat.section_number = payload[7]; // eslint-disable-line camelcase
    pat.last_section_number = payload[8]; // eslint-disable-line camelcase

    // skip the PSI header and parse the first PMT entry
    self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
    pat.pmtPid = self.pmtPid;
  };

  /**
   * Parse out the relevant fields of a Program Map Table (PMT).
   * @param payload {Uint8Array} the PMT-specific portion of an MP2T
   * packet. The first byte in this array should be the table_id
   * field.
   * @param pmt {object} the object that should be decorated with
   * fields parsed from the PMT.
   */
  parsePmt = function(payload, pmt) {
    var sectionLength, tableEnd, programInfoLength, offset;

    // PMTs can be sent ahead of the time when they should actually
    // take effect. We don't believe this should ever be the case
    // for HLS but we'll ignore "forward" PMT declarations if we see
    // them. Future PMT declarations have the current_next_indicator
    // set to zero.
    if (!(payload[5] & 0x01)) {
      return;
    }

    // overwrite any existing program map table
    self.programMapTable = {
      video: null,
      audio: null,
      'timed-metadata': {}
    };

    // the mapping table ends at the end of the current section
    sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
    tableEnd = 3 + sectionLength - 4;

    // to determine where the table is, we have to figure out how
    // long the program info descriptors are
    programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];

    // advance the offset to the first entry in the mapping table
    offset = 12 + programInfoLength;
    while (offset < tableEnd) {
      var streamType = payload[offset];
      var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2];

      // only map a single elementary_pid for audio and video stream types
      // TODO: should this be done for metadata too? for now maintain behavior of
      //       multiple metadata streams
      if (streamType === StreamTypes.H264_STREAM_TYPE &&
          self.programMapTable.video === null) {
        self.programMapTable.video = pid;
      } else if (streamType === StreamTypes.ADTS_STREAM_TYPE &&
                 self.programMapTable.audio === null) {
        self.programMapTable.audio = pid;
      } else if (streamType === StreamTypes.METADATA_STREAM_TYPE) {
        // map pid to stream type for metadata streams
        self.programMapTable['timed-metadata'][pid] = streamType;
      }

      // move to the next table entry
      // skip past the elementary stream descriptors, if present
      offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
    }

    // record the map on the packet as well
    pmt.programMapTable = self.programMapTable;
  };

  /**
   * Deliver a new MP2T packet to the next stream in the pipeline.
   */
  this.push = function(packet) {
    var
      result = {},
      offset = 4;

    result.payloadUnitStartIndicator = !!(packet[1] & 0x40);

    // pid is a 13-bit field starting at the last bit of packet[1]
    result.pid = packet[1] & 0x1f;
    result.pid <<= 8;
    result.pid |= packet[2];

    // if an adaption field is present, its length is specified by the
    // fifth byte of the TS packet header. The adaptation field is
    // used to add stuffing to PES packets that don't fill a complete
    // TS packet, and to specify some forms of timing and control data
    // that we do not currently use.
    if (((packet[3] & 0x30) >>> 4) > 0x01) {
      offset += packet[offset] + 1;
    }

    // parse the rest of the packet based on the type
    if (result.pid === 0) {
      result.type = 'pat';
      parsePsi(packet.subarray(offset), result);
      this.trigger('data', result);
    } else if (result.pid === this.pmtPid) {
      result.type = 'pmt';
      parsePsi(packet.subarray(offset), result);
      this.trigger('data', result);

      // if there are any packets waiting for a PMT to be found, process them now
      while (this.packetsWaitingForPmt.length) {
        this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
      }
    } else if (this.programMapTable === undefined) {
      // When we have not seen a PMT yet, defer further processing of
      // PES packets until one has been parsed
      this.packetsWaitingForPmt.push([packet, offset, result]);
    } else {
      this.processPes_(packet, offset, result);
    }
  };

  this.processPes_ = function(packet, offset, result) {
    // set the appropriate stream type
    if (result.pid === this.programMapTable.video) {
      result.streamType = StreamTypes.H264_STREAM_TYPE;
    } else if (result.pid === this.programMapTable.audio) {
      result.streamType = StreamTypes.ADTS_STREAM_TYPE;
    } else {
      // if not video or audio, it is timed-metadata or unknown
      // if unknown, streamType will be undefined
      result.streamType = this.programMapTable['timed-metadata'][result.pid];
    }

    result.type = 'pes';
    result.data = packet.subarray(offset);
    this.trigger('data', result);
  };
};
TransportParseStream.prototype = new Stream();
TransportParseStream.STREAM_TYPES  = {
  h264: 0x1b,
  adts: 0x0f
};

/**
 * Reconsistutes program elementary stream (PES) packets from parsed
 * transport stream packets. That is, if you pipe an
 * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
 * events will be events which capture the bytes for individual PES
 * packets plus relevant metadata that has been extracted from the
 * container.
 */
ElementaryStream = function() {
  var
    self = this,
    // PES packet fragments
    video = {
      data: [],
      size: 0
    },
    audio = {
      data: [],
      size: 0
    },
    timedMetadata = {
      data: [],
      size: 0
    },
    programMapTable,
    parsePes = function(payload, pes) {
      var ptsDtsFlags;

      // get the packet length, this will be 0 for video
      pes.packetLength = 6 + ((payload[4] << 8) | payload[5]);

      // find out if this packets starts a new keyframe
      pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
      // PES packets may be annotated with a PTS value, or a PTS value
      // and a DTS value. Determine what combination of values is
      // available to work with.
      ptsDtsFlags = payload[7];

      // PTS and DTS are normally stored as a 33-bit number.  Javascript
      // performs all bitwise operations on 32-bit integers but javascript
      // supports a much greater range (52-bits) of integer using standard
      // mathematical operations.
      // We construct a 31-bit value using bitwise operators over the 31
      // most significant bits and then multiply by 4 (equal to a left-shift
      // of 2) before we add the final 2 least significant bits of the
      // timestamp (equal to an OR.)
      if (ptsDtsFlags & 0xC0) {
        // the PTS and DTS are not written out directly. For information
        // on how they are encoded, see
        // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
        pes.pts = (payload[9] & 0x0E) << 27 |
          (payload[10] & 0xFF) << 20 |
          (payload[11] & 0xFE) << 12 |
          (payload[12] & 0xFF) <<  5 |
          (payload[13] & 0xFE) >>>  3;
        pes.pts *= 4; // Left shift by 2
        pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
        pes.dts = pes.pts;
        if (ptsDtsFlags & 0x40) {
          pes.dts = (payload[14] & 0x0E) << 27 |
            (payload[15] & 0xFF) << 20 |
            (payload[16] & 0xFE) << 12 |
            (payload[17] & 0xFF) << 5 |
            (payload[18] & 0xFE) >>> 3;
          pes.dts *= 4; // Left shift by 2
          pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
        }
      }
      // the data section starts immediately after the PES header.
      // pes_header_data_length specifies the number of header bytes
      // that follow the last byte of the field.
      pes.data = payload.subarray(9 + payload[8]);
    },
    /**
      * Pass completely parsed PES packets to the next stream in the pipeline
     **/
    flushStream = function(stream, type, forceFlush) {
      var
        packetData = new Uint8Array(stream.size),
        event = {
          type: type
        },
        i = 0,
        offset = 0,
        packetFlushable = false,
        fragment;

      // do nothing if there is not enough buffered data for a complete
      // PES header
      if (!stream.data.length || stream.size < 9) {
        return;
      }
      event.trackId = stream.data[0].pid;

      // reassemble the packet
      for (i = 0; i < stream.data.length; i++) {
        fragment = stream.data[i];

        packetData.set(fragment.data, offset);
        offset += fragment.data.byteLength;
      }

      // parse assembled packet's PES header
      parsePes(packetData, event);

      // non-video PES packets MUST have a non-zero PES_packet_length
      // check that there is enough stream data to fill the packet
      packetFlushable = type === 'video' || event.packetLength <= stream.size;

      // flush pending packets if the conditions are right
      if (forceFlush || packetFlushable) {
        stream.size = 0;
        stream.data.length = 0;
      }

      // only emit packets that are complete. this is to avoid assembling
      // incomplete PES packets due to poor segmentation
      if (packetFlushable) {
        self.trigger('data', event);
      }
    };

  ElementaryStream.prototype.init.call(this);

  /**
   * Identifies M2TS packet types and parses PES packets using metadata
   * parsed from the PMT
   **/
  this.push = function(data) {
    ({
      pat: function() {
        // we have to wait for the PMT to arrive as well before we
        // have any meaningful metadata
      },
      pes: function() {
        var stream, streamType;

        switch (data.streamType) {
        case StreamTypes.H264_STREAM_TYPE:
          stream = video;
          streamType = 'video';
          break;
        case StreamTypes.ADTS_STREAM_TYPE:
          stream = audio;
          streamType = 'audio';
          break;
        case StreamTypes.METADATA_STREAM_TYPE:
          stream = timedMetadata;
          streamType = 'timed-metadata';
          break;
        default:
          // ignore unknown stream types
          return;
        }

        // if a new packet is starting, we can flush the completed
        // packet
        if (data.payloadUnitStartIndicator) {
          flushStream(stream, streamType, true);
        }

        // buffer this fragment until we are sure we've received the
        // complete payload
        stream.data.push(data);
        stream.size += data.data.byteLength;
      },
      pmt: function() {
        var
          event = {
            type: 'metadata',
            tracks: []
          };

        programMapTable = data.programMapTable;

        // translate audio and video streams to tracks
        if (programMapTable.video !== null) {
          event.tracks.push({
            timelineStartInfo: {
              baseMediaDecodeTime: 0
            },
            id: +programMapTable.video,
            codec: 'avc',
            type: 'video'
          });
        }
        if (programMapTable.audio !== null) {
          event.tracks.push({
            timelineStartInfo: {
              baseMediaDecodeTime: 0
            },
            id: +programMapTable.audio,
            codec: 'adts',
            type: 'audio'
          });
        }

        self.trigger('data', event);
      }
    })[data.type]();
  };

  this.reset = function() {
    video.size = 0;
    video.data.length = 0;
    audio.size = 0;
    audio.data.length = 0;
    this.trigger('reset');
  };

  /**
   * Flush any remaining input. Video PES packets may be of variable
   * length. Normally, the start of a new video packet can trigger the
   * finalization of the previous packet. That is not possible if no
   * more video is forthcoming, however. In that case, some other
   * mechanism (like the end of the file) has to be employed. When it is
   * clear that no additional data is forthcoming, calling this method
   * will flush the buffered packets.
   */
  this.flushStreams_ = function() {
    // !!THIS ORDER IS IMPORTANT!!
    // video first then audio
    flushStream(video, 'video');
    flushStream(audio, 'audio');
    flushStream(timedMetadata, 'timed-metadata');
  };

  this.flush = function() {
    this.flushStreams_();
    this.trigger('done');
  };
};
ElementaryStream.prototype = new Stream();

var m2ts = {
  PAT_PID: 0x0000,
  MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  TransportPacketStream: TransportPacketStream,
  TransportParseStream: TransportParseStream,
  ElementaryStream: ElementaryStream,
  TimestampRolloverStream: TimestampRolloverStream,
  CaptionStream: CaptionStream.CaptionStream,
  Cea608Stream: CaptionStream.Cea608Stream,
  Cea708Stream: CaptionStream.Cea708Stream,
  MetadataStream: require(19)
};

for (var type in StreamTypes) {
  if (StreamTypes.hasOwnProperty(type)) {
    m2ts[type] = StreamTypes[type];
  }
}

module.exports = m2ts;

},{"16":16,"19":19,"21":21,"22":22,"49":49}],19:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Accepts program elementary stream (PES) data events and parses out
 * ID3 metadata from them, if present.
 * @see http://id3.org/id3v2.3.0
 */
'use strict';
var
  Stream = require(49),
  StreamTypes = require(21),
  // return a percent-encoded representation of the specified byte range
  // @see http://en.wikipedia.org/wiki/Percent-encoding
  percentEncode = function(bytes, start, end) {
    var i, result = '';
    for (i = start; i < end; i++) {
      result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
    }
    return result;
  },
  // return the string representation of the specified byte range,
  // interpreted as UTf-8.
  parseUtf8 = function(bytes, start, end) {
    return decodeURIComponent(percentEncode(bytes, start, end));
  },
  // return the string representation of the specified byte range,
  // interpreted as ISO-8859-1.
  parseIso88591 = function(bytes, start, end) {
    return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  },
  parseSyncSafeInteger = function(data) {
    return (data[0] << 21) |
            (data[1] << 14) |
            (data[2] << 7) |
            (data[3]);
  },
  tagParsers = {
    TXXX: function(tag) {
      var i;
      if (tag.data[0] !== 3) {
        // ignore frames with unrecognized character encodings
        return;
      }

      for (i = 1; i < tag.data.length; i++) {
        if (tag.data[i] === 0) {
          // parse the text fields
          tag.description = parseUtf8(tag.data, 1, i);
          // do not include the null terminator in the tag value
          tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
          break;
        }
      }
      tag.data = tag.value;
    },
    WXXX: function(tag) {
      var i;
      if (tag.data[0] !== 3) {
        // ignore frames with unrecognized character encodings
        return;
      }

      for (i = 1; i < tag.data.length; i++) {
        if (tag.data[i] === 0) {
          // parse the description and URL fields
          tag.description = parseUtf8(tag.data, 1, i);
          tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
          break;
        }
      }
    },
    PRIV: function(tag) {
      var i;

      for (i = 0; i < tag.data.length; i++) {
        if (tag.data[i] === 0) {
          // parse the description and URL fields
          tag.owner = parseIso88591(tag.data, 0, i);
          break;
        }
      }
      tag.privateData = tag.data.subarray(i + 1);
      tag.data = tag.privateData;
    }
  },
  MetadataStream;

MetadataStream = function(options) {
  var
    settings = {
      debug: !!(options && options.debug),

      // the bytes of the program-level descriptor field in MP2T
      // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
      // program element descriptors"
      descriptor: options && options.descriptor
    },
    // the total size in bytes of the ID3 tag being parsed
    tagSize = 0,
    // tag data that is not complete enough to be parsed
    buffer = [],
    // the total number of bytes currently in the buffer
    bufferSize = 0,
    i;

  MetadataStream.prototype.init.call(this);

  // calculate the text track in-band metadata track dispatch type
  // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
  if (settings.descriptor) {
    for (i = 0; i < settings.descriptor.length; i++) {
      this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
    }
  }

  this.push = function(chunk) {
    var tag, frameStart, frameSize, frame, i, frameHeader;
    if (chunk.type !== 'timed-metadata') {
      return;
    }

    // if data_alignment_indicator is set in the PES header,
    // we must have the start of a new ID3 tag. Assume anything
    // remaining in the buffer was malformed and throw it out
    if (chunk.dataAlignmentIndicator) {
      bufferSize = 0;
      buffer.length = 0;
    }

    // ignore events that don't look like ID3 data
    if (buffer.length === 0 &&
        (chunk.data.length < 10 ||
          chunk.data[0] !== 'I'.charCodeAt(0) ||
          chunk.data[1] !== 'D'.charCodeAt(0) ||
          chunk.data[2] !== '3'.charCodeAt(0))) {
      if (settings.debug) {
        // eslint-disable-next-line no-console
        console.log('Skipping unrecognized metadata packet');
      }
      return;
    }

    // add this chunk to the data we've collected so far

    buffer.push(chunk);
    bufferSize += chunk.data.byteLength;

    // grab the size of the entire frame from the ID3 header
    if (buffer.length === 1) {
      // the frame size is transmitted as a 28-bit integer in the
      // last four bytes of the ID3 header.
      // The most significant bit of each byte is dropped and the
      // results concatenated to recover the actual value.
      tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));

      // ID3 reports the tag size excluding the header but it's more
      // convenient for our comparisons to include it
      tagSize += 10;
    }

    // if the entire frame has not arrived, wait for more data
    if (bufferSize < tagSize) {
      return;
    }

    // collect the entire frame so it can be parsed
    tag = {
      data: new Uint8Array(tagSize),
      frames: [],
      pts: buffer[0].pts,
      dts: buffer[0].dts
    };
    for (i = 0; i < tagSize;) {
      tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
      i += buffer[0].data.byteLength;
      bufferSize -= buffer[0].data.byteLength;
      buffer.shift();
    }

    // find the start of the first frame and the end of the tag
    frameStart = 10;
    if (tag.data[5] & 0x40) {
      // advance the frame start past the extended header
      frameStart += 4; // header size field
      frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));

      // clip any padding off the end
      tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
    }

    // parse one or more ID3 frames
    // http://id3.org/id3v2.3.0#ID3v2_frame_overview
    do {
      // determine the number of bytes in this frame
      frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
      if (frameSize < 1) {
         // eslint-disable-next-line no-console
        return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
      }
      frameHeader = String.fromCharCode(tag.data[frameStart],
                                        tag.data[frameStart + 1],
                                        tag.data[frameStart + 2],
                                        tag.data[frameStart + 3]);


      frame = {
        id: frameHeader,
        data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
      };
      frame.key = frame.id;
      if (tagParsers[frame.id]) {
        tagParsers[frame.id](frame);

        // handle the special PRIV frame used to indicate the start
        // time for raw AAC data
        if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
          var
            d = frame.data,
            size = ((d[3] & 0x01)  << 30) |
                   (d[4]  << 22) |
                   (d[5] << 14) |
                   (d[6] << 6) |
                   (d[7] >>> 2);

          size *= 4;
          size += d[7] & 0x03;
          frame.timeStamp = size;
          // in raw AAC, all subsequent data will be timestamped based
          // on the value of this frame
          // we couldn't have known the appropriate pts and dts before
          // parsing this ID3 tag so set those values now
          if (tag.pts === undefined && tag.dts === undefined) {
            tag.pts = frame.timeStamp;
            tag.dts = frame.timeStamp;
          }
          this.trigger('timestamp', frame);
        }
      }
      tag.frames.push(frame);

      frameStart += 10; // advance past the frame header
      frameStart += frameSize; // advance past the frame body
    } while (frameStart < tagSize);
    this.trigger('data', tag);
  };
};
MetadataStream.prototype = new Stream();

module.exports = MetadataStream;

},{"21":21,"49":49}],20:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Utilities to detect basic properties and metadata about TS Segments.
 */
'use strict';

var StreamTypes = require(21);

var parsePid = function(packet) {
  var pid = packet[1] & 0x1f;
  pid <<= 8;
  pid |= packet[2];
  return pid;
};

var parsePayloadUnitStartIndicator = function(packet) {
  return !!(packet[1] & 0x40);
};

var parseAdaptionField = function(packet) {
  var offset = 0;
  // if an adaption field is present, its length is specified by the
  // fifth byte of the TS packet header. The adaptation field is
  // used to add stuffing to PES packets that don't fill a complete
  // TS packet, and to specify some forms of timing and control data
  // that we do not currently use.
  if (((packet[3] & 0x30) >>> 4) > 0x01) {
    offset += packet[4] + 1;
  }
  return offset;
};

var parseType = function(packet, pmtPid) {
  var pid = parsePid(packet);
  if (pid === 0) {
    return 'pat';
  } else if (pid === pmtPid) {
    return 'pmt';
  } else if (pmtPid) {
    return 'pes';
  }
  return null;
};

var parsePat = function(packet) {
  var pusi = parsePayloadUnitStartIndicator(packet);
  var offset = 4 + parseAdaptionField(packet);

  if (pusi) {
    offset += packet[offset] + 1;
  }

  return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
};

var parsePmt = function(packet) {
  var programMapTable = {};
  var pusi = parsePayloadUnitStartIndicator(packet);
  var payloadOffset = 4 + parseAdaptionField(packet);

  if (pusi) {
    payloadOffset += packet[payloadOffset] + 1;
  }

  // PMTs can be sent ahead of the time when they should actually
  // take effect. We don't believe this should ever be the case
  // for HLS but we'll ignore "forward" PMT declarations if we see
  // them. Future PMT declarations have the current_next_indicator
  // set to zero.
  if (!(packet[payloadOffset + 5] & 0x01)) {
    return;
  }

  var sectionLength, tableEnd, programInfoLength;
  // the mapping table ends at the end of the current section
  sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  tableEnd = 3 + sectionLength - 4;

  // to determine where the table is, we have to figure out how
  // long the program info descriptors are
  programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11];

  // advance the offset to the first entry in the mapping table
  var offset = 12 + programInfoLength;
  while (offset < tableEnd) {
    var i = payloadOffset + offset;
    // add an entry that maps the elementary_pid to the stream_type
    programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i];

    // move to the next table entry
    // skip past the elementary stream descriptors, if present
    offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  }
  return programMapTable;
};

var parsePesType = function(packet, programMapTable) {
  var pid = parsePid(packet);
  var type = programMapTable[pid];
  switch (type) {
    case StreamTypes.H264_STREAM_TYPE:
      return 'video';
    case StreamTypes.ADTS_STREAM_TYPE:
      return 'audio';
    case StreamTypes.METADATA_STREAM_TYPE:
      return 'timed-metadata';
    default:
      return null;
  }
};

var parsePesTime = function(packet) {
  var pusi = parsePayloadUnitStartIndicator(packet);
  if (!pusi) {
    return null;
  }

  var offset = 4 + parseAdaptionField(packet);

  if (offset >= packet.byteLength) {
    // From the H 222.0 MPEG-TS spec
    // "For transport stream packets carrying PES packets, stuffing is needed when there
    //  is insufficient PES packet data to completely fill the transport stream packet
    //  payload bytes. Stuffing is accomplished by defining an adaptation field longer than
    //  the sum of the lengths of the data elements in it, so that the payload bytes
    //  remaining after the adaptation field exactly accommodates the available PES packet
    //  data."
    //
    // If the offset is >= the length of the packet, then the packet contains no data
    // and instead is just adaption field stuffing bytes
    return null;
  }

  var pes = null;
  var ptsDtsFlags;

  // PES packets may be annotated with a PTS value, or a PTS value
  // and a DTS value. Determine what combination of values is
  // available to work with.
  ptsDtsFlags = packet[offset + 7];

  // PTS and DTS are normally stored as a 33-bit number.  Javascript
  // performs all bitwise operations on 32-bit integers but javascript
  // supports a much greater range (52-bits) of integer using standard
  // mathematical operations.
  // We construct a 31-bit value using bitwise operators over the 31
  // most significant bits and then multiply by 4 (equal to a left-shift
  // of 2) before we add the final 2 least significant bits of the
  // timestamp (equal to an OR.)
  if (ptsDtsFlags & 0xC0) {
    pes = {};
    // the PTS and DTS are not written out directly. For information
    // on how they are encoded, see
    // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
    pes.pts = (packet[offset + 9] & 0x0E) << 27 |
      (packet[offset + 10] & 0xFF) << 20 |
      (packet[offset + 11] & 0xFE) << 12 |
      (packet[offset + 12] & 0xFF) <<  5 |
      (packet[offset + 13] & 0xFE) >>>  3;
    pes.pts *= 4; // Left shift by 2
    pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
    pes.dts = pes.pts;
    if (ptsDtsFlags & 0x40) {
      pes.dts = (packet[offset + 14] & 0x0E) << 27 |
        (packet[offset + 15] & 0xFF) << 20 |
        (packet[offset + 16] & 0xFE) << 12 |
        (packet[offset + 17] & 0xFF) << 5 |
        (packet[offset + 18] & 0xFE) >>> 3;
      pes.dts *= 4; // Left shift by 2
      pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
    }
  }
  return pes;
};

var parseNalUnitType = function(type) {
  switch (type) {
    case 0x05:
      return 'slice_layer_without_partitioning_rbsp_idr';
    case 0x06:
      return 'sei_rbsp';
    case 0x07:
      return 'seq_parameter_set_rbsp';
    case 0x08:
      return 'pic_parameter_set_rbsp';
    case 0x09:
      return 'access_unit_delimiter_rbsp';
    default:
      return null;
  }
};

var videoPacketContainsKeyFrame = function(packet) {
  var offset = 4 + parseAdaptionField(packet);
  var frameBuffer = packet.subarray(offset);
  var frameI = 0;
  var frameSyncPoint = 0;
  var foundKeyFrame = false;
  var nalType;

  // advance the sync point to a NAL start, if necessary
  for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
    if (frameBuffer[frameSyncPoint + 2] === 1) {
      // the sync point is properly aligned
      frameI = frameSyncPoint + 5;
      break;
    }
  }

  while (frameI < frameBuffer.byteLength) {
    // look at the current byte to determine if we've hit the end of
    // a NAL unit boundary
    switch (frameBuffer[frameI]) {
    case 0:
      // skip past non-sync sequences
      if (frameBuffer[frameI - 1] !== 0) {
        frameI += 2;
        break;
      } else if (frameBuffer[frameI - 2] !== 0) {
        frameI++;
        break;
      }

      if (frameSyncPoint + 3 !== frameI - 2) {
        nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
        if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
          foundKeyFrame = true;
        }
      }

      // drop trailing zeroes
      do {
        frameI++;
      } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
      frameSyncPoint = frameI - 2;
      frameI += 3;
      break;
    case 1:
      // skip past non-sync sequences
      if (frameBuffer[frameI - 1] !== 0 ||
          frameBuffer[frameI - 2] !== 0) {
        frameI += 3;
        break;
      }

      nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
      if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
        foundKeyFrame = true;
      }
      frameSyncPoint = frameI - 2;
      frameI += 3;
      break;
    default:
      // the current byte isn't a one or zero, so it cannot be part
      // of a sync sequence
      frameI += 3;
      break;
    }
  }
  frameBuffer = frameBuffer.subarray(frameSyncPoint);
  frameI -= frameSyncPoint;
  frameSyncPoint = 0;
  // parse the final nal
  if (frameBuffer && frameBuffer.byteLength > 3) {
    nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
    if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
      foundKeyFrame = true;
    }
  }

  return foundKeyFrame;
};


module.exports = {
  parseType: parseType,
  parsePat: parsePat,
  parsePmt: parsePmt,
  parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  parsePesType: parsePesType,
  parsePesTime: parsePesTime,
  videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
};

},{"21":21}],21:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

module.exports = {
  H264_STREAM_TYPE: 0x1B,
  ADTS_STREAM_TYPE: 0x0F,
  METADATA_STREAM_TYPE: 0x15
};

},{}],22:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Accepts program elementary stream (PES) data events and corrects
 * decode and presentation time stamps to account for a rollover
 * of the 33 bit value.
 */

'use strict';

var Stream = require(49);

var MAX_TS = 8589934592;

var RO_THRESH = 4294967296;

var TYPE_SHARED = 'shared';

var handleRollover = function(value, reference) {
  var direction = 1;

  if (value > reference) {
    // If the current timestamp value is greater than our reference timestamp and we detect a
    // timestamp rollover, this means the roll over is happening in the opposite direction.
    // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
    // point will be set to a small number, e.g. 1. The user then seeks backwards over the
    // rollover point. In loading this segment, the timestamp values will be very large,
    // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
    // the time stamp to be `value - 2^33`.
    direction = -1;
  }

  // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  // cause an incorrect adjustment.
  while (Math.abs(reference - value) > RO_THRESH) {
    value += (direction * MAX_TS);
  }

  return value;
};

var TimestampRolloverStream = function(type) {
  var lastDTS, referenceDTS;

  TimestampRolloverStream.prototype.init.call(this);

  // The "shared" type is used in cases where a stream will contain muxed
  // video and audio. We could use `undefined` here, but having a string
  // makes debugging a little clearer.
  this.type_ = type || TYPE_SHARED;

  this.push = function(data) {

    // Any "shared" rollover streams will accept _all_ data. Otherwise,
    // streams will only accept data that matches their type.
    if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
      return;
    }

    if (referenceDTS === undefined) {
      referenceDTS = data.dts;
    }

    data.dts = handleRollover(data.dts, referenceDTS);
    data.pts = handleRollover(data.pts, referenceDTS);

    lastDTS = data.dts;

    this.trigger('data', data);
  };

  this.flush = function() {
    referenceDTS = lastDTS;
    this.trigger('done');
  };

  this.endTimeline = function() {
    this.flush();
    this.trigger('endedtimeline');
  };

  this.discontinuity = function() {
    referenceDTS = void 0;
    lastDTS = void 0;
  };

  this.reset = function() {
    this.discontinuity();
    this.trigger('reset');
  };
};

TimestampRolloverStream.prototype = new Stream();

module.exports = {
  TimestampRolloverStream: TimestampRolloverStream,
  handleRollover: handleRollover
};

},{"49":49}],23:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
var coneOfSilence = require(8);
var clock = require(47);

/**
 * Sum the `byteLength` properties of the data in each AAC frame
 */
var sumFrameByteLengths = function(array) {
  var
    i,
    currentObj,
    sum = 0;

  // sum the byteLength's all each nal unit in the frame
  for (i = 0; i < array.length; i++) {
    currentObj = array[i];
    sum += currentObj.data.byteLength;
  }

  return sum;
};

// Possibly pad (prefix) the audio track with silence if appending this track
// would lead to the introduction of a gap in the audio buffer
var prefixWithSilence = function(
  track,
  frames,
  audioAppendStartTs,
  videoBaseMediaDecodeTime
) {
  var
    baseMediaDecodeTimeTs,
    frameDuration = 0,
    audioGapDuration = 0,
    audioFillFrameCount = 0,
    audioFillDuration = 0,
    silentFrame,
    i,
    firstFrame;

  if (!frames.length) {
    return;
  }

  baseMediaDecodeTimeTs =
    clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate);
  // determine frame clock duration based on sample rate, round up to avoid overfills
  frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));

  if (audioAppendStartTs && videoBaseMediaDecodeTime) {
    // insert the shortest possible amount (audio gap or audio to video gap)
    audioGapDuration =
      baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime);
    // number of full frames in the audio gap
    audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
    audioFillDuration = audioFillFrameCount * frameDuration;
  }

  // don't attempt to fill gaps smaller than a single frame or larger
  // than a half second
  if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
    return;
  }

  silentFrame = coneOfSilence()[track.samplerate];

  if (!silentFrame) {
    // we don't have a silent frame pregenerated for the sample rate, so use a frame
    // from the content instead
    silentFrame = frames[0].data;
  }

  for (i = 0; i < audioFillFrameCount; i++) {
    firstFrame = frames[0];

    frames.splice(0, 0, {
      data: silentFrame,
      dts: firstFrame.dts - frameDuration,
      pts: firstFrame.pts - frameDuration
    });
  }

  track.baseMediaDecodeTime -=
    Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
};

// If the audio segment extends before the earliest allowed dts
// value, remove AAC frames until starts at or after the earliest
// allowed DTS so that we don't end up with a negative baseMedia-
// DecodeTime for the audio track
var trimAdtsFramesByEarliestDts = function(adtsFrames, track, earliestAllowedDts) {
  if (track.minSegmentDts >= earliestAllowedDts) {
    return adtsFrames;
  }

  // We will need to recalculate the earliest segment Dts
  track.minSegmentDts = Infinity;

  return adtsFrames.filter(function(currentFrame) {
    // If this is an allowed frame, keep it and record it's Dts
    if (currentFrame.dts >= earliestAllowedDts) {
      track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
      track.minSegmentPts = track.minSegmentDts;
      return true;
    }
    // Otherwise, discard it
    return false;
  });
};

// generate the track's raw mdat data from an array of frames
var generateSampleTable = function(frames) {
  var
    i,
    currentFrame,
    samples = [];

  for (i = 0; i < frames.length; i++) {
    currentFrame = frames[i];
    samples.push({
      size: currentFrame.data.byteLength,
      duration: 1024 // For AAC audio, all samples contain 1024 samples
    });
  }
  return samples;
};

// generate the track's sample table from an array of frames
var concatenateFrameData = function(frames) {
  var
    i,
    currentFrame,
    dataOffset = 0,
    data = new Uint8Array(sumFrameByteLengths(frames));

  for (i = 0; i < frames.length; i++) {
    currentFrame = frames[i];

    data.set(currentFrame.data, dataOffset);
    dataOffset += currentFrame.data.byteLength;
  }
  return data;
};

module.exports = {
  prefixWithSilence: prefixWithSilence,
  trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  generateSampleTable: generateSampleTable,
  concatenateFrameData: concatenateFrameData
};

},{"47":47,"8":8}],24:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Reads in-band CEA-708 captions out of FMP4 segments.
 * @see https://en.wikipedia.org/wiki/CEA-708
 */
'use strict';

var discardEmulationPreventionBytes = require(37).discardEmulationPreventionBytes;
var CaptionStream = require(16).CaptionStream;
var findBox = require(25);
var parseTfdt = require(42);
var parseTrun = require(44);
var parseTfhd = require(43);

/**
  * Maps an offset in the mdat to a sample based on the the size of the samples.
  * Assumes that `parseSamples` has been called first.
  *
  * @param {Number} offset - The offset into the mdat
  * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  * @return {?Object} The matching sample, or null if no match was found.
  *
  * @see ISO-BMFF-12/2015, Section 8.8.8
 **/
var mapToSample = function(offset, samples) {
  var approximateOffset = offset;

  for (var i = 0; i < samples.length; i++) {
    var sample = samples[i];

    if (approximateOffset < sample.size) {
      return sample;
    }

    approximateOffset -= sample.size;
  }

  return null;
};

/**
  * Finds SEI nal units contained in a Media Data Box.
  * Assumes that `parseSamples` has been called first.
  *
  * @param {Uint8Array} avcStream - The bytes of the mdat
  * @param {Object[]} samples - The samples parsed out by `parseSamples`
  * @param {Number} trackId - The trackId of this video track
  * @return {Object[]} seiNals - the parsed SEI NALUs found.
  *   The contents of the seiNal should match what is expected by
  *   CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  *
  * @see ISO-BMFF-12/2015, Section 8.1.1
  * @see Rec. ITU-T H.264, 7.3.2.3.1
 **/
var findSeiNals = function(avcStream, samples, trackId) {
  var
    avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
    result = [],
    seiNal,
    i,
    length,
    lastMatchedSample;

  for (i = 0; i + 4 < avcStream.length; i += length) {
    length = avcView.getUint32(i);
    i += 4;

    // Bail if this doesn't appear to be an H264 stream
    if (length <= 0) {
      continue;
    }

    switch (avcStream[i] & 0x1F) {
    case 0x06:
      var data = avcStream.subarray(i + 1, i + 1 + length);
      var matchingSample = mapToSample(i, samples);

      seiNal = {
        nalUnitType: 'sei_rbsp',
        size: length,
        data: data,
        escapedRBSP: discardEmulationPreventionBytes(data),
        trackId: trackId
      };

      if (matchingSample) {
        seiNal.pts = matchingSample.pts;
        seiNal.dts = matchingSample.dts;
        lastMatchedSample = matchingSample;
      } else if (lastMatchedSample) {
        // If a matching sample cannot be found, use the last
        // sample's values as they should be as close as possible
        seiNal.pts = lastMatchedSample.pts;
        seiNal.dts = lastMatchedSample.dts;
      } else {
        // eslint-disable-next-line no-console
        console.log("We've encountered a nal unit without data. See mux.js#233.");
        break;
      }

      result.push(seiNal);
      break;
    default:
      break;
    }
  }

  return result;
};

/**
  * Parses sample information out of Track Run Boxes and calculates
  * the absolute presentation and decode timestamps of each sample.
  *
  * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
      @see ISO-BMFF-12/2015, Section 8.8.12
  * @param {Object} tfhd - The parsed Track Fragment Header
  *   @see inspect.parseTfhd
  * @return {Object[]} the parsed samples
  *
  * @see ISO-BMFF-12/2015, Section 8.8.8
 **/
var parseSamples = function(truns, baseMediaDecodeTime, tfhd) {
  var currentDts = baseMediaDecodeTime;
  var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  var defaultSampleSize = tfhd.defaultSampleSize || 0;
  var trackId = tfhd.trackId;
  var allSamples = [];

  truns.forEach(function(trun) {
    // Note: We currently do not parse the sample table as well
    // as the trun. It's possible some sources will require this.
    // moov > trak > mdia > minf > stbl
    var trackRun = parseTrun(trun);
    var samples = trackRun.samples;

    samples.forEach(function(sample) {
      if (sample.duration === undefined) {
        sample.duration = defaultSampleDuration;
      }
      if (sample.size === undefined) {
        sample.size = defaultSampleSize;
      }
      sample.trackId = trackId;
      sample.dts = currentDts;
      if (sample.compositionTimeOffset === undefined) {
        sample.compositionTimeOffset = 0;
      }
      sample.pts = currentDts + sample.compositionTimeOffset;

      currentDts += sample.duration;
    });

    allSamples = allSamples.concat(samples);
  });

  return allSamples;
};

/**
  * Parses out caption nals from an FMP4 segment's video tracks.
  *
  * @param {Uint8Array} segment - The bytes of a single segment
  * @param {Number} videoTrackId - The trackId of a video track in the segment
  * @return {Object.<Number, Object[]>} A mapping of video trackId to
  *   a list of seiNals found in that track
 **/
var parseCaptionNals = function(segment, videoTrackId) {
  // To get the samples
  var trafs = findBox(segment, ['moof', 'traf']);
  // To get SEI NAL units
  var mdats = findBox(segment, ['mdat']);
  var captionNals = {};
  var mdatTrafPairs = [];

  // Pair up each traf with a mdat as moofs and mdats are in pairs
  mdats.forEach(function(mdat, index) {
    var matchingTraf = trafs[index];
    mdatTrafPairs.push({
      mdat: mdat,
      traf: matchingTraf
    });
  });

  mdatTrafPairs.forEach(function(pair) {
    var mdat = pair.mdat;
    var traf = pair.traf;
    var tfhd = findBox(traf, ['tfhd']);
    // Exactly 1 tfhd per traf
    var headerInfo = parseTfhd(tfhd[0]);
    var trackId = headerInfo.trackId;
    var tfdt = findBox(traf, ['tfdt']);
    // Either 0 or 1 tfdt per traf
    var baseMediaDecodeTime = (tfdt.length > 0) ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
    var truns = findBox(traf, ['trun']);
    var samples;
    var seiNals;

    // Only parse video data for the chosen video track
    if (videoTrackId === trackId && truns.length > 0) {
      samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);

      seiNals = findSeiNals(mdat, samples, trackId);

      if (!captionNals[trackId]) {
        captionNals[trackId] = [];
      }

      captionNals[trackId] = captionNals[trackId].concat(seiNals);
    }
  });

  return captionNals;
};

/**
  * Parses out inband captions from an MP4 container and returns
  * caption objects that can be used by WebVTT and the TextTrack API.
  * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  *
  * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  * @param {Number} trackId - The id of the video track to parse
  * @param {Number} timescale - The timescale for the video track from the init segment
  *
  * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  * @return {String} parsedCaptions[].text - The visible content of the caption
 **/
var parseEmbeddedCaptions = function(segment, trackId, timescale) {
  var seiNals;

  // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  if (trackId === null) {
    return null;
  }

  seiNals = parseCaptionNals(segment, trackId);

  return {
    seiNals: seiNals[trackId],
    timescale: timescale
  };
};

/**
  * Converts SEI NALUs into captions that can be used by video.js
 **/
var CaptionParser = function() {
  var isInitialized = false;
  var captionStream;

  // Stores segments seen before trackId and timescale are set
  var segmentCache;
  // Stores video track ID of the track being parsed
  var trackId;
  // Stores the timescale of the track being parsed
  var timescale;
  // Stores captions parsed so far
  var parsedCaptions;
  // Stores whether we are receiving partial data or not
  var parsingPartial;

  /**
    * A method to indicate whether a CaptionParser has been initalized
    * @returns {Boolean}
   **/
  this.isInitialized = function() {
    return isInitialized;
  };

  /**
    * Initializes the underlying CaptionStream, SEI NAL parsing
    * and management, and caption collection
   **/
  this.init = function(options) {
    captionStream = new CaptionStream();
    isInitialized = true;
    parsingPartial = options ? options.isPartial : false;

    // Collect dispatched captions
    captionStream.on('data', function(event) {
      // Convert to seconds in the source's timescale
      event.startTime = event.startPts / timescale;
      event.endTime = event.endPts / timescale;

      parsedCaptions.captions.push(event);
      parsedCaptions.captionStreams[event.stream] = true;
    });
  };

  /**
    * Determines if a new video track will be selected
    * or if the timescale changed
    * @return {Boolean}
   **/
  this.isNewInit = function(videoTrackIds, timescales) {
    if ((videoTrackIds && videoTrackIds.length === 0) ||
        (timescales && typeof timescales === 'object' &&
          Object.keys(timescales).length === 0)) {
      return false;
    }

    return trackId !== videoTrackIds[0] ||
      timescale !== timescales[trackId];
  };

  /**
    * Parses out SEI captions and interacts with underlying
    * CaptionStream to return dispatched captions
    *
    * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
    * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
    * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
    * @see parseEmbeddedCaptions
    * @see m2ts/caption-stream.js
   **/
  this.parse = function(segment, videoTrackIds, timescales) {
    var parsedData;

    if (!this.isInitialized()) {
      return null;

    // This is not likely to be a video segment
    } else if (!videoTrackIds || !timescales) {
      return null;

    } else if (this.isNewInit(videoTrackIds, timescales)) {
      // Use the first video track only as there is no
      // mechanism to switch to other video tracks
      trackId = videoTrackIds[0];
      timescale = timescales[trackId];

    // If an init segment has not been seen yet, hold onto segment
    // data until we have one.
    // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
    } else if (trackId === null || !timescale) {
      segmentCache.push(segment);
      return null;
    }

    // Now that a timescale and trackId is set, parse cached segments
    while (segmentCache.length > 0) {
      var cachedSegment = segmentCache.shift();

      this.parse(cachedSegment, videoTrackIds, timescales);
    }

    parsedData = parseEmbeddedCaptions(segment, trackId, timescale);

    if (parsedData === null || !parsedData.seiNals) {
      return null;
    }

    this.pushNals(parsedData.seiNals);
    // Force the parsed captions to be dispatched
    this.flushStream();

    return parsedCaptions;
  };

  /**
    * Pushes SEI NALUs onto CaptionStream
    * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
    * Assumes that `parseCaptionNals` has been called first
    * @see m2ts/caption-stream.js
    **/
  this.pushNals = function(nals) {
    if (!this.isInitialized() || !nals || nals.length === 0) {
      return null;
    }

    nals.forEach(function(nal) {
      captionStream.push(nal);
    });
  };

  /**
    * Flushes underlying CaptionStream to dispatch processed, displayable captions
    * @see m2ts/caption-stream.js
   **/
  this.flushStream = function() {
    if (!this.isInitialized()) {
      return null;
    }

    if (!parsingPartial) {
      captionStream.flush();
    } else {
      captionStream.partialFlush();
    }
  };

  /**
    * Reset caption buckets for new data
   **/
  this.clearParsedCaptions = function() {
    parsedCaptions.captions = [];
    parsedCaptions.captionStreams = {};
  };

  /**
    * Resets underlying CaptionStream
    * @see m2ts/caption-stream.js
   **/
  this.resetCaptionStream = function() {
    if (!this.isInitialized()) {
      return null;
    }

    captionStream.reset();
  };

  /**
    * Convenience method to clear all captions flushed from the
    * CaptionStream and still being parsed
    * @see m2ts/caption-stream.js
   **/
  this.clearAllCaptions = function() {
    this.clearParsedCaptions();
    this.resetCaptionStream();
  };

  /**
    * Reset caption parser
   **/
  this.reset = function() {
    segmentCache = [];
    trackId = null;
    timescale = null;

    if (!parsedCaptions) {
      parsedCaptions = {
        captions: [],
        // CC1, CC2, CC3, CC4
        captionStreams: {}
      };
    } else {
      this.clearParsedCaptions();
    }

    this.resetCaptionStream();
  };

  this.reset();
};

module.exports = CaptionParser;

},{"16":16,"25":25,"37":37,"42":42,"43":43,"44":44}],25:[function(require,module,exports){
var toUnsigned = require(46).toUnsigned;
var parseType = require(29);

var findBox = function(data, path) {
  var results = [],
    i, size, type, end, subresults;

  if (!path.length) {
    // short-circuit the search for empty paths
    return null;
  }

  for (i = 0; i < data.byteLength;) {
    size = toUnsigned(data[i]     << 24 |
      data[i + 1] << 16 |
      data[i + 2] <<  8 |
      data[i + 3]);

    type = parseType(data.subarray(i + 4, i + 8));

    end = size > 1 ? i + size : data.byteLength;

    if (type === path[0]) {
      if (path.length === 1) {
        // this is the end of the path and we've found the box we were
        // looking for
        results.push(data.subarray(i + 8, end));
      } else {
        // recursively search for the next box along the path
        subresults = findBox(data.subarray(i + 8, end), path.slice(1));
        if (subresults.length) {
          results = results.concat(subresults);
        }
      }
    }
    i = end;
  }

  // we've finished searching all of data
  return results;
};

module.exports = findBox;


},{"29":29,"46":46}],26:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
// Convert an array of nal units into an array of frames with each frame being
// composed of the nal units that make up that frame
// Also keep track of cummulative data about the frame from the nal units such
// as the frame duration, starting pts, etc.
var groupNalsIntoFrames = function(nalUnits) {
  var
    i,
    currentNal,
    currentFrame = [],
    frames = [];

  // TODO added for LHLS, make sure this is OK
  frames.byteLength = 0;
  frames.nalCount = 0;
  frames.duration = 0;

  currentFrame.byteLength = 0;

  for (i = 0; i < nalUnits.length; i++) {
    currentNal = nalUnits[i];

    // Split on 'aud'-type nal units
    if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
      // Since the very first nal unit is expected to be an AUD
      // only push to the frames array when currentFrame is not empty
      if (currentFrame.length) {
        currentFrame.duration = currentNal.dts - currentFrame.dts;
        // TODO added for LHLS, make sure this is OK
        frames.byteLength += currentFrame.byteLength;
        frames.nalCount += currentFrame.length;
        frames.duration += currentFrame.duration;
        frames.push(currentFrame);
      }
      currentFrame = [currentNal];
      currentFrame.byteLength = currentNal.data.byteLength;
      currentFrame.pts = currentNal.pts;
      currentFrame.dts = currentNal.dts;
    } else {
      // Specifically flag key frames for ease of use later
      if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
        currentFrame.keyFrame = true;
      }
      currentFrame.duration = currentNal.dts - currentFrame.dts;
      currentFrame.byteLength += currentNal.data.byteLength;
      currentFrame.push(currentNal);
    }
  }

  // For the last frame, use the duration of the previous frame if we
  // have nothing better to go on
  if (frames.length &&
      (!currentFrame.duration ||
       currentFrame.duration <= 0)) {
    currentFrame.duration = frames[frames.length - 1].duration;
  }

  // Push the final frame
  // TODO added for LHLS, make sure this is OK
  frames.byteLength += currentFrame.byteLength;
  frames.nalCount += currentFrame.length;
  frames.duration += currentFrame.duration;

  frames.push(currentFrame);
  return frames;
};

// Convert an array of frames into an array of Gop with each Gop being composed
// of the frames that make up that Gop
// Also keep track of cummulative data about the Gop from the frames such as the
// Gop duration, starting pts, etc.
var groupFramesIntoGops = function(frames) {
  var
    i,
    currentFrame,
    currentGop = [],
    gops = [];

  // We must pre-set some of the values on the Gop since we
  // keep running totals of these values
  currentGop.byteLength = 0;
  currentGop.nalCount = 0;
  currentGop.duration = 0;
  currentGop.pts = frames[0].pts;
  currentGop.dts = frames[0].dts;

  // store some metadata about all the Gops
  gops.byteLength = 0;
  gops.nalCount = 0;
  gops.duration = 0;
  gops.pts = frames[0].pts;
  gops.dts = frames[0].dts;

  for (i = 0; i < frames.length; i++) {
    currentFrame = frames[i];

    if (currentFrame.keyFrame) {
      // Since the very first frame is expected to be an keyframe
      // only push to the gops array when currentGop is not empty
      if (currentGop.length) {
        gops.push(currentGop);
        gops.byteLength += currentGop.byteLength;
        gops.nalCount += currentGop.nalCount;
        gops.duration += currentGop.duration;
      }

      currentGop = [currentFrame];
      currentGop.nalCount = currentFrame.length;
      currentGop.byteLength = currentFrame.byteLength;
      currentGop.pts = currentFrame.pts;
      currentGop.dts = currentFrame.dts;
      currentGop.duration = currentFrame.duration;
    } else {
      currentGop.duration += currentFrame.duration;
      currentGop.nalCount += currentFrame.length;
      currentGop.byteLength += currentFrame.byteLength;
      currentGop.push(currentFrame);
    }
  }

  if (gops.length && currentGop.duration <= 0) {
    currentGop.duration = gops[gops.length - 1].duration;
  }
  gops.byteLength += currentGop.byteLength;
  gops.nalCount += currentGop.nalCount;
  gops.duration += currentGop.duration;

  // push the final Gop
  gops.push(currentGop);
  return gops;
};

/*
 * Search for the first keyframe in the GOPs and throw away all frames
 * until that keyframe. Then extend the duration of the pulled keyframe
 * and pull the PTS and DTS of the keyframe so that it covers the time
 * range of the frames that were disposed.
 *
 * @param {Array} gops video GOPs
 * @returns {Array} modified video GOPs
 */
var extendFirstKeyFrame = function(gops) {
  var currentGop;

  if (!gops[0][0].keyFrame && gops.length > 1) {
    // Remove the first GOP
    currentGop = gops.shift();

    gops.byteLength -= currentGop.byteLength;
    gops.nalCount -= currentGop.nalCount;

    // Extend the first frame of what is now the
    // first gop to cover the time period of the
    // frames we just removed
    gops[0][0].dts = currentGop.dts;
    gops[0][0].pts = currentGop.pts;
    gops[0][0].duration += currentGop.duration;
  }

  return gops;
};

/**
 * Default sample object
 * see ISO/IEC 14496-12:2012, section 8.6.4.3
 */
var createDefaultSample = function() {
  return {
    size: 0,
    flags: {
      isLeading: 0,
      dependsOn: 1,
      isDependedOn: 0,
      hasRedundancy: 0,
      degradationPriority: 0,
      isNonSyncSample: 1
    }
  };
};

/*
 * Collates information from a video frame into an object for eventual
 * entry into an MP4 sample table.
 *
 * @param {Object} frame the video frame
 * @param {Number} dataOffset the byte offset to position the sample
 * @return {Object} object containing sample table info for a frame
 */
var sampleForFrame = function(frame, dataOffset) {
  var sample = createDefaultSample();

  sample.dataOffset = dataOffset;
  sample.compositionTimeOffset = frame.pts - frame.dts;
  sample.duration = frame.duration;
  sample.size = 4 * frame.length; // Space for nal unit size
  sample.size += frame.byteLength;

  if (frame.keyFrame) {
    sample.flags.dependsOn = 2;
    sample.flags.isNonSyncSample = 0;
  }

  return sample;
};

// generate the track's sample table from an array of gops
var generateSampleTable = function(gops, baseDataOffset) {
  var
    h, i,
    sample,
    currentGop,
    currentFrame,
    dataOffset = baseDataOffset || 0,
    samples = [];

  for (h = 0; h < gops.length; h++) {
    currentGop = gops[h];

    for (i = 0; i < currentGop.length; i++) {
      currentFrame = currentGop[i];

      sample = sampleForFrame(currentFrame, dataOffset);

      dataOffset += sample.size;

      samples.push(sample);
    }
  }
  return samples;
};

// generate the track's raw mdat data from an array of gops
var concatenateNalData = function(gops) {
  var
    h, i, j,
    currentGop,
    currentFrame,
    currentNal,
    dataOffset = 0,
    nalsByteLength = gops.byteLength,
    numberOfNals = gops.nalCount,
    totalByteLength = nalsByteLength + 4 * numberOfNals,
    data = new Uint8Array(totalByteLength),
    view = new DataView(data.buffer);

  // For each Gop..
  for (h = 0; h < gops.length; h++) {
    currentGop = gops[h];

    // For each Frame..
    for (i = 0; i < currentGop.length; i++) {
      currentFrame = currentGop[i];

      // For each NAL..
      for (j = 0; j < currentFrame.length; j++) {
        currentNal = currentFrame[j];

        view.setUint32(dataOffset, currentNal.data.byteLength);
        dataOffset += 4;
        data.set(currentNal.data, dataOffset);
        dataOffset += currentNal.data.byteLength;
      }
    }
  }
  return data;
};

// generate the track's sample table from a frame
var generateSampleTableForFrame = function(frame, baseDataOffset) {
  var
    sample,
    dataOffset = baseDataOffset || 0,
    samples = [];

  sample = sampleForFrame(frame, dataOffset);
  samples.push(sample);

  return samples;
};

// generate the track's raw mdat data from a frame
var concatenateNalDataForFrame = function(frame) {
  var
    i,
    currentNal,
    dataOffset = 0,
    nalsByteLength = frame.byteLength,
    numberOfNals = frame.length,
    totalByteLength = nalsByteLength + 4 * numberOfNals,
    data = new Uint8Array(totalByteLength),
    view = new DataView(data.buffer);

  // For each NAL..
  for (i = 0; i < frame.length; i++) {
    currentNal = frame[i];

    view.setUint32(dataOffset, currentNal.data.byteLength);
    dataOffset += 4;
    data.set(currentNal.data, dataOffset);
    dataOffset += currentNal.data.byteLength;
  }

  return data;
};

module.exports = {
  groupNalsIntoFrames: groupNalsIntoFrames,
  groupFramesIntoGops: groupFramesIntoGops,
  extendFirstKeyFrame: extendFirstKeyFrame,
  generateSampleTable: generateSampleTable,
  concatenateNalData: concatenateNalData,
  generateSampleTableForFrame: generateSampleTableForFrame,
  concatenateNalDataForFrame: concatenateNalDataForFrame
};

},{}],27:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
module.exports = {
  generator: require(28),
  probe: require(30),
  Transmuxer: require(32).Transmuxer,
  AudioSegmentStream: require(32).AudioSegmentStream,
  VideoSegmentStream: require(32).VideoSegmentStream,
  CaptionParser: require(24)
};

},{"24":24,"28":28,"30":30,"32":32}],28:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Functions that generate fragmented MP4s suitable for use with Media
 * Source Extensions.
 */
'use strict';

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

var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd,
    trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex,
    trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
    AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;

// pre-calculate constants
(function() {
  var i;
  types = {
    avc1: [], // codingname
    avcC: [],
    btrt: [],
    dinf: [],
    dref: [],
    esds: [],
    ftyp: [],
    hdlr: [],
    mdat: [],
    mdhd: [],
    mdia: [],
    mfhd: [],
    minf: [],
    moof: [],
    moov: [],
    mp4a: [], // codingname
    mvex: [],
    mvhd: [],
    pasp: [],
    sdtp: [],
    smhd: [],
    stbl: [],
    stco: [],
    stsc: [],
    stsd: [],
    stsz: [],
    stts: [],
    styp: [],
    tfdt: [],
    tfhd: [],
    traf: [],
    trak: [],
    trun: [],
    trex: [],
    tkhd: [],
    vmhd: []
  };

  // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  // don't throw an error
  if (typeof Uint8Array === 'undefined') {
    return;
  }

  for (i in types) {
    if (types.hasOwnProperty(i)) {
      types[i] = [
        i.charCodeAt(0),
        i.charCodeAt(1),
        i.charCodeAt(2),
        i.charCodeAt(3)
      ];
    }
  }

  MAJOR_BRAND = new Uint8Array([
    'i'.charCodeAt(0),
    's'.charCodeAt(0),
    'o'.charCodeAt(0),
    'm'.charCodeAt(0)
  ]);
  AVC1_BRAND = new Uint8Array([
    'a'.charCodeAt(0),
    'v'.charCodeAt(0),
    'c'.charCodeAt(0),
    '1'.charCodeAt(0)
  ]);
  MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  VIDEO_HDLR = new Uint8Array([
    0x00, // version 0
    0x00, 0x00, 0x00, // flags
    0x00, 0x00, 0x00, 0x00, // pre_defined
    0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
    0x00, 0x00, 0x00, 0x00, // reserved
    0x00, 0x00, 0x00, 0x00, // reserved
    0x00, 0x00, 0x00, 0x00, // reserved
    0x56, 0x69, 0x64, 0x65,
    0x6f, 0x48, 0x61, 0x6e,
    0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  ]);
  AUDIO_HDLR = new Uint8Array([
    0x00, // version 0
    0x00, 0x00, 0x00, // flags
    0x00, 0x00, 0x00, 0x00, // pre_defined
    0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
    0x00, 0x00, 0x00, 0x00, // reserved
    0x00, 0x00, 0x00, 0x00, // reserved
    0x00, 0x00, 0x00, 0x00, // reserved
    0x53, 0x6f, 0x75, 0x6e,
    0x64, 0x48, 0x61, 0x6e,
    0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  ]);
  HDLR_TYPES = {
    video: VIDEO_HDLR,
    audio: AUDIO_HDLR
  };
  DREF = new Uint8Array([
    0x00, // version 0
    0x00, 0x00, 0x00, // flags
    0x00, 0x00, 0x00, 0x01, // entry_count
    0x00, 0x00, 0x00, 0x0c, // entry_size
    0x75, 0x72, 0x6c, 0x20, // 'url' type
    0x00, // version 0
    0x00, 0x00, 0x01 // entry_flags
  ]);
  SMHD = new Uint8Array([
    0x00,             // version
    0x00, 0x00, 0x00, // flags
    0x00, 0x00,       // balance, 0 means centered
    0x00, 0x00        // reserved
  ]);
  STCO = new Uint8Array([
    0x00, // version
    0x00, 0x00, 0x00, // flags
    0x00, 0x00, 0x00, 0x00 // entry_count
  ]);
  STSC = STCO;
  STSZ = new Uint8Array([
    0x00, // version
    0x00, 0x00, 0x00, // flags
    0x00, 0x00, 0x00, 0x00, // sample_size
    0x00, 0x00, 0x00, 0x00 // sample_count
  ]);
  STTS = STCO;
  VMHD = new Uint8Array([
    0x00, // version
    0x00, 0x00, 0x01, // flags
    0x00, 0x00, // graphicsmode
    0x00, 0x00,
    0x00, 0x00,
    0x00, 0x00 // opcolor
  ]);
}());

box = function(type) {
  var
    payload = [],
    size = 0,
    i,
    result,
    view;

  for (i = 1; i < arguments.length; i++) {
    payload.push(arguments[i]);
  }

  i = payload.length;

  // calculate the total size we need to allocate
  while (i--) {
    size += payload[i].byteLength;
  }
  result = new Uint8Array(size + 8);
  view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  view.setUint32(0, result.byteLength);
  result.set(type, 4);

  // copy the payload into the result
  for (i = 0, size = 8; i < payload.length; i++) {
    result.set(payload[i], size);
    size += payload[i].byteLength;
  }
  return result;
};

dinf = function() {
  return box(types.dinf, box(types.dref, DREF));
};

esds = function(track) {
  return box(types.esds, new Uint8Array([
    0x00, // version
    0x00, 0x00, 0x00, // flags

    // ES_Descriptor
    0x03, // tag, ES_DescrTag
    0x19, // length
    0x00, 0x00, // ES_ID
    0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority

    // DecoderConfigDescriptor
    0x04, // tag, DecoderConfigDescrTag
    0x11, // length
    0x40, // object type
    0x15,  // streamType
    0x00, 0x06, 0x00, // bufferSizeDB
    0x00, 0x00, 0xda, 0xc0, // maxBitrate
    0x00, 0x00, 0xda, 0xc0, // avgBitrate

    // DecoderSpecificInfo
    0x05, // tag, DecoderSpecificInfoTag
    0x02, // length
    // ISO/IEC 14496-3, AudioSpecificConfig
    // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
    (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
    (track.samplingfrequencyindex << 7) | (track.channelcount << 3),
    0x06, 0x01, 0x02 // GASpecificConfig
  ]));
};

ftyp = function() {
  return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
};

hdlr = function(type) {
  return box(types.hdlr, HDLR_TYPES[type]);
};
mdat = function(data) {
  return box(types.mdat, data);
};
mdhd = function(track) {
  var result = new Uint8Array([
    0x00,                   // version 0
    0x00, 0x00, 0x00,       // flags
    0x00, 0x00, 0x00, 0x02, // creation_time
    0x00, 0x00, 0x00, 0x03, // modification_time
    0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second

    (track.duration >>> 24) & 0xFF,
    (track.duration >>> 16) & 0xFF,
    (track.duration >>>  8) & 0xFF,
    track.duration & 0xFF,  // duration
    0x55, 0xc4,             // 'und' language (undetermined)
    0x00, 0x00
  ]);

  // Use the sample rate from the track metadata, when it is
  // defined. The sample rate can be parsed out of an ADTS header, for
  // instance.
  if (track.samplerate) {
    result[12] = (track.samplerate >>> 24) & 0xFF;
    result[13] = (track.samplerate >>> 16) & 0xFF;
    result[14] = (track.samplerate >>>  8) & 0xFF;
    result[15] = (track.samplerate)        & 0xFF;
  }

  return box(types.mdhd, result);
};
mdia = function(track) {
  return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
};
mfhd = function(sequenceNumber) {
  return box(types.mfhd, new Uint8Array([
    0x00,
    0x00, 0x00, 0x00, // flags
    (sequenceNumber & 0xFF000000) >> 24,
    (sequenceNumber & 0xFF0000) >> 16,
    (sequenceNumber & 0xFF00) >> 8,
    sequenceNumber & 0xFF // sequence_number
  ]));
};
minf = function(track) {
  return box(types.minf,
             track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
             dinf(),
             stbl(track));
};
moof = function(sequenceNumber, tracks) {
  var
    trackFragments = [],
    i = tracks.length;
  // build traf boxes for each track fragment
  while (i--) {
    trackFragments[i] = traf(tracks[i]);
  }
  return box.apply(null, [
    types.moof,
    mfhd(sequenceNumber)
  ].concat(trackFragments));
};
/**
 * Returns a movie box.
 * @param tracks {array} the tracks associated with this movie
 * @see ISO/IEC 14496-12:2012(E), section 8.2.1
 */
moov = function(tracks) {
  var
    i = tracks.length,
    boxes = [];

  while (i--) {
    boxes[i] = trak(tracks[i]);
  }

  return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
};
mvex = function(tracks) {
  var
    i = tracks.length,
    boxes = [];

  while (i--) {
    boxes[i] = trex(tracks[i]);
  }
  return box.apply(null, [types.mvex].concat(boxes));
};
mvhd = function(duration) {
  var
    bytes = new Uint8Array([
      0x00, // version 0
      0x00, 0x00, 0x00, // flags
      0x00, 0x00, 0x00, 0x01, // creation_time
      0x00, 0x00, 0x00, 0x02, // modification_time
      0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
      (duration & 0xFF000000) >> 24,
      (duration & 0xFF0000) >> 16,
      (duration & 0xFF00) >> 8,
      duration & 0xFF, // duration
      0x00, 0x01, 0x00, 0x00, // 1.0 rate
      0x01, 0x00, // 1.0 volume
      0x00, 0x00, // reserved
      0x00, 0x00, 0x00, 0x00, // reserved
      0x00, 0x00, 0x00, 0x00, // reserved
      0x00, 0x01, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x01, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, // pre_defined
      0xff, 0xff, 0xff, 0xff // next_track_ID
    ]);
  return box(types.mvhd, bytes);
};

sdtp = function(track) {
  var
    samples = track.samples || [],
    bytes = new Uint8Array(4 + samples.length),
    flags,
    i;

  // leave the full box header (4 bytes) all zero

  // write the sample table
  for (i = 0; i < samples.length; i++) {
    flags = samples[i].flags;

    bytes[i + 4] = (flags.dependsOn << 4) |
      (flags.isDependedOn << 2) |
      (flags.hasRedundancy);
  }

  return box(types.sdtp,
             bytes);
};

stbl = function(track) {
  return box(types.stbl,
             stsd(track),
             box(types.stts, STTS),
             box(types.stsc, STSC),
             box(types.stsz, STSZ),
             box(types.stco, STCO));
};

(function() {
  var videoSample, audioSample;

  stsd = function(track) {

    return box(types.stsd, new Uint8Array([
      0x00, // version 0
      0x00, 0x00, 0x00, // flags
      0x00, 0x00, 0x00, 0x01
    ]), track.type === 'video' ? videoSample(track) : audioSample(track));
  };

  videoSample = function(track) {
    var
      sps = track.sps || [],
      pps = track.pps || [],
      sequenceParameterSets = [],
      pictureParameterSets = [],
      i,
      avc1Box;

    // assemble the SPSs
    for (i = 0; i < sps.length; i++) {
      sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
      sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
      sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
    }

    // assemble the PPSs
    for (i = 0; i < pps.length; i++) {
      pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
      pictureParameterSets.push((pps[i].byteLength & 0xFF));
      pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
    }

    avc1Box = [
      types.avc1, new Uint8Array([
        0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, // reserved
        0x00, 0x01, // data_reference_index
        0x00, 0x00, // pre_defined
        0x00, 0x00, // reserved
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, // pre_defined
        (track.width & 0xff00) >> 8,
        track.width & 0xff, // width
        (track.height & 0xff00) >> 8,
        track.height & 0xff, // height
        0x00, 0x48, 0x00, 0x00, // horizresolution
        0x00, 0x48, 0x00, 0x00, // vertresolution
        0x00, 0x00, 0x00, 0x00, // reserved
        0x00, 0x01, // frame_count
        0x13,
        0x76, 0x69, 0x64, 0x65,
        0x6f, 0x6a, 0x73, 0x2d,
        0x63, 0x6f, 0x6e, 0x74,
        0x72, 0x69, 0x62, 0x2d,
        0x68, 0x6c, 0x73, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, // compressorname
        0x00, 0x18, // depth = 24
        0x11, 0x11 // pre_defined = -1
      ]),
      box(types.avcC, new Uint8Array([
        0x01, // configurationVersion
        track.profileIdc, // AVCProfileIndication
        track.profileCompatibility, // profile_compatibility
        track.levelIdc, // AVCLevelIndication
        0xff // lengthSizeMinusOne, hard-coded to 4 bytes
      ].concat(
        [sps.length], // numOfSequenceParameterSets
        sequenceParameterSets, // "SPS"
        [pps.length], // numOfPictureParameterSets
        pictureParameterSets // "PPS"
      ))),
      box(types.btrt, new Uint8Array([
        0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
        0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
        0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
      ]))
    ];

    if (track.sarRatio) {
      var
        hSpacing = track.sarRatio[0],
        vSpacing = track.sarRatio[1];

        avc1Box.push(
          box(types.pasp, new Uint8Array([
            (hSpacing & 0xFF000000) >> 24,
            (hSpacing & 0xFF0000) >> 16,
            (hSpacing & 0xFF00) >> 8,
            hSpacing & 0xFF,
            (vSpacing & 0xFF000000) >> 24,
            (vSpacing & 0xFF0000) >> 16,
            (vSpacing & 0xFF00) >> 8,
            vSpacing & 0xFF
          ]))
        );
    }

    return box.apply(null, avc1Box);
  };

  audioSample = function(track) {
    return box(types.mp4a, new Uint8Array([

      // SampleEntry, ISO/IEC 14496-12
      0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, // reserved
      0x00, 0x01, // data_reference_index

      // AudioSampleEntry, ISO/IEC 14496-12
      0x00, 0x00, 0x00, 0x00, // reserved
      0x00, 0x00, 0x00, 0x00, // reserved
      (track.channelcount & 0xff00) >> 8,
      (track.channelcount & 0xff), // channelcount

      (track.samplesize & 0xff00) >> 8,
      (track.samplesize & 0xff), // samplesize
      0x00, 0x00, // pre_defined
      0x00, 0x00, // reserved

      (track.samplerate & 0xff00) >> 8,
      (track.samplerate & 0xff),
      0x00, 0x00 // samplerate, 16.16

      // MP4AudioSampleEntry, ISO/IEC 14496-14
    ]), esds(track));
  };
}());

tkhd = function(track) {
  var result = new Uint8Array([
    0x00, // version 0
    0x00, 0x00, 0x07, // flags
    0x00, 0x00, 0x00, 0x00, // creation_time
    0x00, 0x00, 0x00, 0x00, // modification_time
    (track.id & 0xFF000000) >> 24,
    (track.id & 0xFF0000) >> 16,
    (track.id & 0xFF00) >> 8,
    track.id & 0xFF, // track_ID
    0x00, 0x00, 0x00, 0x00, // reserved
    (track.duration & 0xFF000000) >> 24,
    (track.duration & 0xFF0000) >> 16,
    (track.duration & 0xFF00) >> 8,
    track.duration & 0xFF, // duration
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, // reserved
    0x00, 0x00, // layer
    0x00, 0x00, // alternate_group
    0x01, 0x00, // non-audio track volume
    0x00, 0x00, // reserved
    0x00, 0x01, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x01, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
    (track.width & 0xFF00) >> 8,
    track.width & 0xFF,
    0x00, 0x00, // width
    (track.height & 0xFF00) >> 8,
    track.height & 0xFF,
    0x00, 0x00 // height
  ]);

  return box(types.tkhd, result);
};

/**
 * Generate a track fragment (traf) box. A traf box collects metadata
 * about tracks in a movie fragment (moof) box.
 */
traf = function(track) {
  var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun,
      sampleDependencyTable, dataOffset,
      upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;

  trackFragmentHeader = box(types.tfhd, new Uint8Array([
    0x00, // version 0
    0x00, 0x00, 0x3a, // flags
    (track.id & 0xFF000000) >> 24,
    (track.id & 0xFF0000) >> 16,
    (track.id & 0xFF00) >> 8,
    (track.id & 0xFF), // track_ID
    0x00, 0x00, 0x00, 0x01, // sample_description_index
    0x00, 0x00, 0x00, 0x00, // default_sample_duration
    0x00, 0x00, 0x00, 0x00, // default_sample_size
    0x00, 0x00, 0x00, 0x00  // default_sample_flags
  ]));

  upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
  lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));

  trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
    0x01, // version 1
    0x00, 0x00, 0x00, // flags
    // baseMediaDecodeTime
    (upperWordBaseMediaDecodeTime >>> 24) & 0xFF,
    (upperWordBaseMediaDecodeTime >>> 16) & 0xFF,
    (upperWordBaseMediaDecodeTime >>>  8) & 0xFF,
    upperWordBaseMediaDecodeTime & 0xFF,
    (lowerWordBaseMediaDecodeTime >>> 24) & 0xFF,
    (lowerWordBaseMediaDecodeTime >>> 16) & 0xFF,
    (lowerWordBaseMediaDecodeTime >>>  8) & 0xFF,
    lowerWordBaseMediaDecodeTime & 0xFF
  ]));

  // the data offset specifies the number of bytes from the start of
  // the containing moof to the first payload byte of the associated
  // mdat
  dataOffset = (32 + // tfhd
                20 + // tfdt
                8 +  // traf header
                16 + // mfhd
                8 +  // moof header
                8);  // mdat header

  // audio tracks require less metadata
  if (track.type === 'audio') {
    trackFragmentRun = trun(track, dataOffset);
    return box(types.traf,
               trackFragmentHeader,
               trackFragmentDecodeTime,
               trackFragmentRun);
  }

  // video tracks should contain an independent and disposable samples
  // box (sdtp)
  // generate one and adjust offsets to match
  sampleDependencyTable = sdtp(track);
  trackFragmentRun = trun(track,
                          sampleDependencyTable.length + dataOffset);
  return box(types.traf,
             trackFragmentHeader,
             trackFragmentDecodeTime,
             trackFragmentRun,
             sampleDependencyTable);
};

/**
 * Generate a track box.
 * @param track {object} a track definition
 * @return {Uint8Array} the track box
 */
trak = function(track) {
  track.duration = track.duration || 0xffffffff;
  return box(types.trak,
             tkhd(track),
             mdia(track));
};

trex = function(track) {
  var result = new Uint8Array([
    0x00, // version 0
    0x00, 0x00, 0x00, // flags
    (track.id & 0xFF000000) >> 24,
    (track.id & 0xFF0000) >> 16,
    (track.id & 0xFF00) >> 8,
    (track.id & 0xFF), // track_ID
    0x00, 0x00, 0x00, 0x01, // default_sample_description_index
    0x00, 0x00, 0x00, 0x00, // default_sample_duration
    0x00, 0x00, 0x00, 0x00, // default_sample_size
    0x00, 0x01, 0x00, 0x01 // default_sample_flags
  ]);
  // the last two bytes of default_sample_flags is the sample
  // degradation priority, a hint about the importance of this sample
  // relative to others. Lower the degradation priority for all sample
  // types other than video.
  if (track.type !== 'video') {
    result[result.length - 1] = 0x00;
  }

  return box(types.trex, result);
};

(function() {
  var audioTrun, videoTrun, trunHeader;

  // This method assumes all samples are uniform. That is, if a
  // duration is present for the first sample, it will be present for
  // all subsequent samples.
  // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  trunHeader = function(samples, offset) {
    var durationPresent = 0, sizePresent = 0,
        flagsPresent = 0, compositionTimeOffset = 0;

    // trun flag constants
    if (samples.length) {
      if (samples[0].duration !== undefined) {
        durationPresent = 0x1;
      }
      if (samples[0].size !== undefined) {
        sizePresent = 0x2;
      }
      if (samples[0].flags !== undefined) {
        flagsPresent = 0x4;
      }
      if (samples[0].compositionTimeOffset !== undefined) {
        compositionTimeOffset = 0x8;
      }
    }

    return [
      0x00, // version 0
      0x00,
      durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
      0x01, // flags
      (samples.length & 0xFF000000) >>> 24,
      (samples.length & 0xFF0000) >>> 16,
      (samples.length & 0xFF00) >>> 8,
      samples.length & 0xFF, // sample_count
      (offset & 0xFF000000) >>> 24,
      (offset & 0xFF0000) >>> 16,
      (offset & 0xFF00) >>> 8,
      offset & 0xFF // data_offset
    ];
  };

  videoTrun = function(track, offset) {
    var bytesOffest, bytes, header, samples, sample, i;

    samples = track.samples || [];
    offset += 8 + 12 + (16 * samples.length);
    header = trunHeader(samples, offset);
    bytes = new Uint8Array(header.length + samples.length * 16);
    bytes.set(header);
    bytesOffest = header.length;

    for (i = 0; i < samples.length; i++) {
      sample = samples[i];

      bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
      bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
      bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
      bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
      bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
      bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
      bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
      bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
      bytes[bytesOffest++] = (sample.flags.isLeading << 2) | sample.flags.dependsOn;
      bytes[bytesOffest++] = (sample.flags.isDependedOn << 6) |
          (sample.flags.hasRedundancy << 4) |
          (sample.flags.paddingValue << 1) |
          sample.flags.isNonSyncSample;
      bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
      bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
      bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
      bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
      bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
      bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
    }
    return box(types.trun, bytes);
  };

  audioTrun = function(track, offset) {
    var bytes, bytesOffest, header, samples, sample, i;

    samples = track.samples || [];
    offset += 8 + 12 + (8 * samples.length);

    header = trunHeader(samples, offset);
    bytes = new Uint8Array(header.length + samples.length * 8);
    bytes.set(header);
    bytesOffest = header.length;

    for (i = 0; i < samples.length; i++) {
      sample = samples[i];
      bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
      bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
      bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
      bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
      bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
      bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
      bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
      bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
    }

    return box(types.trun, bytes);
  };

  trun = function(track, offset) {
    if (track.type === 'audio') {
      return audioTrun(track, offset);
    }

    return videoTrun(track, offset);
  };
}());

module.exports = {
  ftyp: ftyp,
  mdat: mdat,
  moof: moof,
  moov: moov,
  initSegment: function(tracks) {
    var
      fileType = ftyp(),
      movie = moov(tracks),
      result;

    result = new Uint8Array(fileType.byteLength + movie.byteLength);
    result.set(fileType);
    result.set(movie, fileType.byteLength);
    return result;
  }
};

},{}],29:[function(require,module,exports){
var parseType = function(buffer) {
  var result = '';
  result += String.fromCharCode(buffer[0]);
  result += String.fromCharCode(buffer[1]);
  result += String.fromCharCode(buffer[2]);
  result += String.fromCharCode(buffer[3]);
  return result;
};


module.exports = parseType;

},{}],30:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Utilities to detect basic properties and metadata about MP4s.
 */
'use strict';

var toUnsigned = require(46).toUnsigned;
var toHexString = require(46).toHexString;
var findBox = require(25);
var parseType = require(29);
var parseTfhd = require(43);
var parseTrun = require(44);
var parseTfdt = require(42);
var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks,
  getTimescaleFromMediaHeader;

/**
 * Parses an MP4 initialization segment and extracts the timescale
 * values for any declared tracks. Timescale values indicate the
 * number of clock ticks per second to assume for time-based values
 * elsewhere in the MP4.
 *
 * To determine the start time of an MP4, you need two pieces of
 * information: the timescale unit and the earliest base media decode
 * time. Multiple timescales can be specified within an MP4 but the
 * base media decode time is always expressed in the timescale from
 * the media header box for the track:
 * ```
 * moov > trak > mdia > mdhd.timescale
 * ```
 * @param init {Uint8Array} the bytes of the init segment
 * @return {object} a hash of track ids to timescale values or null if
 * the init segment is malformed.
 */
timescale = function(init) {
  var
    result = {},
    traks = findBox(init, ['moov', 'trak']);

  // mdhd timescale
  return traks.reduce(function(result, trak) {
    var tkhd, version, index, id, mdhd;

    tkhd = findBox(trak, ['tkhd'])[0];
    if (!tkhd) {
      return null;
    }
    version = tkhd[0];
    index = version === 0 ? 12 : 20;
    id = toUnsigned(tkhd[index]     << 24 |
                    tkhd[index + 1] << 16 |
                    tkhd[index + 2] <<  8 |
                    tkhd[index + 3]);

    mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
    if (!mdhd) {
      return null;
    }
    version = mdhd[0];
    index = version === 0 ? 12 : 20;
    result[id] = toUnsigned(mdhd[index]     << 24 |
                            mdhd[index + 1] << 16 |
                            mdhd[index + 2] <<  8 |
                            mdhd[index + 3]);
    return result;
  }, result);
};

/**
 * Determine the base media decode start time, in seconds, for an MP4
 * fragment. If multiple fragments are specified, the earliest time is
 * returned.
 *
 * The base media decode time can be parsed from track fragment
 * metadata:
 * ```
 * moof > traf > tfdt.baseMediaDecodeTime
 * ```
 * It requires the timescale value from the mdhd to interpret.
 *
 * @param timescale {object} a hash of track ids to timescale values.
 * @return {number} the earliest base media decode start time for the
 * fragment, in seconds
 */
startTime = function(timescale, fragment) {
  var trafs, baseTimes, result;

  // we need info from two childrend of each track fragment box
  trafs = findBox(fragment, ['moof', 'traf']);

  // determine the start times for each track
  baseTimes = [].concat.apply([], trafs.map(function(traf) {
    return findBox(traf, ['tfhd']).map(function(tfhd) {
      var id, scale, baseTime;

      // get the track id from the tfhd
      id = toUnsigned(tfhd[4] << 24 |
                      tfhd[5] << 16 |
                      tfhd[6] <<  8 |
                      tfhd[7]);
      // assume a 90kHz clock if no timescale was specified
      scale = timescale[id] || 90e3;

      // get the base media decode time from the tfdt
      baseTime = findBox(traf, ['tfdt']).map(function(tfdt) {
        var version, result;

        version = tfdt[0];
        result = toUnsigned(tfdt[4] << 24 |
                            tfdt[5] << 16 |
                            tfdt[6] <<  8 |
                            tfdt[7]);
        if (version ===  1) {
          result *= Math.pow(2, 32);
          result += toUnsigned(tfdt[8]  << 24 |
                               tfdt[9]  << 16 |
                               tfdt[10] <<  8 |
                               tfdt[11]);
        }
        return result;
      })[0];
      baseTime = typeof baseTime === 'number' && !isNaN(baseTime) ? baseTime : Infinity;

      // convert base time to seconds
      return baseTime / scale;
    });
  }));

  // return the minimum
  result = Math.min.apply(null, baseTimes);
  return isFinite(result) ? result : 0;
};

/**
 * Determine the composition start, in seconds, for an MP4
 * fragment.
 *
 * The composition start time of a fragment can be calculated using the base
 * media decode time, composition time offset, and timescale, as follows:
 *
 * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
 *
 * All of the aforementioned information is contained within a media fragment's
 * `traf` box, except for timescale info, which comes from the initialization
 * segment, so a track id (also contained within a `traf`) is also necessary to
 * associate it with a timescale
 *
 *
 * @param timescales {object} - a hash of track ids to timescale values.
 * @param fragment {Unit8Array} - the bytes of a media segment
 * @return {number} the composition start time for the fragment, in seconds
 **/
compositionStartTime = function(timescales, fragment) {
  var trafBoxes = findBox(fragment, ['moof', 'traf']);
  var baseMediaDecodeTime = 0;
  var compositionTimeOffset = 0;
  var trackId;

  if (trafBoxes && trafBoxes.length) {
    // The spec states that track run samples contained within a `traf` box are contiguous, but
    // it does not explicitly state whether the `traf` boxes themselves are contiguous.
    // We will assume that they are, so we only need the first to calculate start time.
    var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
    var trun = findBox(trafBoxes[0], ['trun'])[0];
    var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];

    if (tfhd) {
      var parsedTfhd = parseTfhd(tfhd);

      trackId = parsedTfhd.trackId;
    }

    if (tfdt) {
      var parsedTfdt = parseTfdt(tfdt);

      baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
    }

    if (trun) {
      var parsedTrun = parseTrun(trun);

      if (parsedTrun.samples && parsedTrun.samples.length) {
        compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
      }
    }
  }

  // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  // specified.
  var timescale = timescales[trackId] || 90e3;

  // return the composition start time, in seconds
  return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
};

/**
  * Find the trackIds of the video tracks in this source.
  * Found by parsing the Handler Reference and Track Header Boxes:
  *   moov > trak > mdia > hdlr
  *   moov > trak > tkhd
  *
  * @param {Uint8Array} init - The bytes of the init segment for this source
  * @return {Number[]} A list of trackIds
  *
  * @see ISO-BMFF-12/2015, Section 8.4.3
 **/
getVideoTrackIds = function(init) {
  var traks = findBox(init, ['moov', 'trak']);
  var videoTrackIds = [];

  traks.forEach(function(trak) {
    var hdlrs = findBox(trak, ['mdia', 'hdlr']);
    var tkhds = findBox(trak, ['tkhd']);

    hdlrs.forEach(function(hdlr, index) {
      var handlerType = parseType(hdlr.subarray(8, 12));
      var tkhd = tkhds[index];
      var view;
      var version;
      var trackId;

      if (handlerType === 'vide') {
        view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
        version = view.getUint8(0);
        trackId = (version === 0) ? view.getUint32(12) : view.getUint32(20);

        videoTrackIds.push(trackId);
      }
    });
  });

  return videoTrackIds;
};

getTimescaleFromMediaHeader = function(mdhd) {
  // mdhd is a FullBox, meaning it will have its own version as the first byte
  var version = mdhd[0];
  var index = version === 0 ? 12 : 20;

  return toUnsigned(
    mdhd[index]     << 24 |
    mdhd[index + 1] << 16 |
    mdhd[index + 2] <<  8 |
    mdhd[index + 3]
  );
};

/**
 * Get all the video, audio, and hint tracks from a non fragmented
 * mp4 segment
 */
getTracks = function(init) {
  var traks = findBox(init, ['moov', 'trak']);
  var tracks = [];

  traks.forEach(function(trak) {
    var track = {};
    var tkhd = findBox(trak, ['tkhd'])[0];
    var view, tkhdVersion;

    // id
    if (tkhd) {
      view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
      tkhdVersion = view.getUint8(0);

      track.id = (tkhdVersion === 0) ? view.getUint32(12) : view.getUint32(20);
    }

    var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];

    // type
    if (hdlr) {
      var type = parseType(hdlr.subarray(8, 12));

      if (type === 'vide') {
        track.type = 'video';
      } else if (type === 'soun') {
        track.type = 'audio';
      } else {
        track.type = type;
      }
    }


    // codec
    var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];

    if (stsd) {
      var sampleDescriptions = stsd.subarray(8);
      // gives the codec type string
      track.codec = parseType(sampleDescriptions.subarray(4, 8));

      var codecBox = findBox(sampleDescriptions, [track.codec])[0];
      var codecConfig, codecConfigType;

      if (codecBox) {
        // https://tools.ietf.org/html/rfc6381#section-3.3
        if ((/^[a-z]vc[1-9]$/i).test(track.codec)) {
          // we don't need anything but the "config" parameter of the
          // avc1 codecBox
          codecConfig = codecBox.subarray(78);
          codecConfigType = parseType(codecConfig.subarray(4, 8));

          if (codecConfigType === 'avcC' && codecConfig.length > 11) {
            track.codec += '.';

            // left padded with zeroes for single digit hex
            // profile idc
            track.codec +=  toHexString(codecConfig[9]);
            // the byte containing the constraint_set flags
            track.codec += toHexString(codecConfig[10]);
            // level idc
            track.codec += toHexString(codecConfig[11]);
          } else {
            // TODO: show a warning that we couldn't parse the codec
            // and are using the default
            track.codec = 'avc1.4d400d';
          }
        } else if ((/^mp4[a,v]$/i).test(track.codec)) {
          // we do not need anything but the streamDescriptor of the mp4a codecBox
          codecConfig = codecBox.subarray(28);
          codecConfigType = parseType(codecConfig.subarray(4, 8));

          if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
            track.codec += '.' + toHexString(codecConfig[19]);
            // this value is only a single digit
            track.codec += '.' + toHexString((codecConfig[20] >>> 2) & 0x3f).replace(/^0/, '');
          } else {
            // TODO: show a warning that we couldn't parse the codec
            // and are using the default
            track.codec = 'mp4a.40.2';
          }
        } else {
          // flac, opus, etc
          track.codec = track.codec.toLowerCase();
        }
      }
    }

    var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];

    if (mdhd) {
      track.timescale = getTimescaleFromMediaHeader(mdhd);
    }

    tracks.push(track);
  });

  return tracks;
};

module.exports = {
  // export mp4 inspector's findBox and parseType for backwards compatibility
  findBox: findBox,
  parseType: parseType,
  timescale: timescale,
  startTime: startTime,
  compositionStartTime: compositionStartTime,
  videoTrackIds: getVideoTrackIds,
  tracks: getTracks,
  getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
};

},{"25":25,"29":29,"42":42,"43":43,"44":44,"46":46}],31:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
var ONE_SECOND_IN_TS = require(47).ONE_SECOND_IN_TS;

/**
 * Store information about the start and end of the track and the
 * duration for each frame/sample we process in order to calculate
 * the baseMediaDecodeTime
 */
var collectDtsInfo = function(track, data) {
  if (typeof data.pts === 'number') {
    if (track.timelineStartInfo.pts === undefined) {
      track.timelineStartInfo.pts = data.pts;
    }

    if (track.minSegmentPts === undefined) {
      track.minSegmentPts = data.pts;
    } else {
      track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
    }

    if (track.maxSegmentPts === undefined) {
      track.maxSegmentPts = data.pts;
    } else {
      track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
    }
  }

  if (typeof data.dts === 'number') {
    if (track.timelineStartInfo.dts === undefined) {
      track.timelineStartInfo.dts = data.dts;
    }

    if (track.minSegmentDts === undefined) {
      track.minSegmentDts = data.dts;
    } else {
      track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
    }

    if (track.maxSegmentDts === undefined) {
      track.maxSegmentDts = data.dts;
    } else {
      track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
    }
  }
};

/**
 * Clear values used to calculate the baseMediaDecodeTime between
 * tracks
 */
var clearDtsInfo = function(track) {
  delete track.minSegmentDts;
  delete track.maxSegmentDts;
  delete track.minSegmentPts;
  delete track.maxSegmentPts;
};

/**
 * Calculate the track's baseMediaDecodeTime based on the earliest
 * DTS the transmuxer has ever seen and the minimum DTS for the
 * current track
 * @param track {object} track metadata configuration
 * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
 *        in the source; false to adjust the first segment to start at 0.
 */
var calculateTrackBaseMediaDecodeTime = function(track, keepOriginalTimestamps) {
  var
    baseMediaDecodeTime,
    scale,
    minSegmentDts = track.minSegmentDts;

  // Optionally adjust the time so the first segment starts at zero.
  if (!keepOriginalTimestamps) {
    minSegmentDts -= track.timelineStartInfo.dts;
  }

  // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  // we want the start of the first segment to be placed
  baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;

  // Add to that the distance this segment is from the very first
  baseMediaDecodeTime += minSegmentDts;

  // baseMediaDecodeTime must not become negative
  baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);

  if (track.type === 'audio') {
    // Audio has a different clock equal to the sampling_rate so we need to
    // scale the PTS values into the clock rate of the track
    scale = track.samplerate / ONE_SECOND_IN_TS;
    baseMediaDecodeTime *= scale;
    baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  }

  return baseMediaDecodeTime;
};

module.exports = {
  clearDtsInfo: clearDtsInfo,
  calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  collectDtsInfo: collectDtsInfo
};

},{"47":47}],32:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * A stream-based mp2t to mp4 converter. This utility can be used to
 * deliver mp4s to a SourceBuffer on platforms that support native
 * Media Source Extensions.
 */
'use strict';

var Stream = require(49);
var mp4 = require(28);
var frameUtils = require(26);
var audioFrameUtils = require(23);
var trackDecodeInfo = require(31);
var m2ts = require(18);
var clock = require(47);
var AdtsStream = require(3);
var H264Stream = require(4).H264Stream;
var AacStream = require(1);
var isLikelyAacData = require(2).isLikelyAacData;
var ONE_SECOND_IN_TS = require(47).ONE_SECOND_IN_TS;
var AUDIO_PROPERTIES = require(6);
var VIDEO_PROPERTIES = require(7);

// object types
var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;

/**
 * Compare two arrays (even typed) for same-ness
 */
var arrayEquals = function(a, b) {
  var
    i;

  if (a.length !== b.length) {
    return false;
  }

  // compare the value of each element in the array
  for (i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }

  return true;
};

var generateVideoSegmentTimingInfo = function(
  baseMediaDecodeTime,
  startDts,
  startPts,
  endDts,
  endPts,
  prependedContentDuration
) {
  var
    ptsOffsetFromDts = startPts - startDts,
    decodeDuration = endDts - startDts,
    presentationDuration = endPts - startPts;

  // The PTS and DTS values are based on the actual stream times from the segment,
  // however, the player time values will reflect a start from the baseMediaDecodeTime.
  // In order to provide relevant values for the player times, base timing info on the
  // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  return {
    start: {
      dts: baseMediaDecodeTime,
      pts: baseMediaDecodeTime + ptsOffsetFromDts
    },
    end: {
      dts: baseMediaDecodeTime + decodeDuration,
      pts: baseMediaDecodeTime + presentationDuration
    },
    prependedContentDuration: prependedContentDuration,
    baseMediaDecodeTime: baseMediaDecodeTime
  };
};

/**
 * Constructs a single-track, ISO BMFF media segment from AAC data
 * events. The output of this stream can be fed to a SourceBuffer
 * configured with a suitable initialization segment.
 * @param track {object} track metadata configuration
 * @param options {object} transmuxer options object
 * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
 *        in the source; false to adjust the first segment to start at 0.
 */
AudioSegmentStream = function(track, options) {
  var
    adtsFrames = [],
    sequenceNumber = 0,
    earliestAllowedDts = 0,
    audioAppendStartTs = 0,
    videoBaseMediaDecodeTime = Infinity;

  options = options || {};

  AudioSegmentStream.prototype.init.call(this);

  this.push = function(data) {
    trackDecodeInfo.collectDtsInfo(track, data);

    if (track) {
      AUDIO_PROPERTIES.forEach(function(prop) {
        track[prop] = data[prop];
      });
    }

    // buffer audio data until end() is called
    adtsFrames.push(data);
  };

  this.setEarliestDts = function(earliestDts) {
    earliestAllowedDts = earliestDts;
  };

  this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
    videoBaseMediaDecodeTime = baseMediaDecodeTime;
  };

  this.setAudioAppendStart = function(timestamp) {
    audioAppendStartTs = timestamp;
  };

  this.flush = function() {
    var
      frames,
      moof,
      mdat,
      boxes,
      frameDuration;

    // return early if no audio data has been observed
    if (adtsFrames.length === 0) {
      this.trigger('done', 'AudioSegmentStream');
      return;
    }

    frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
      adtsFrames, track, earliestAllowedDts);
    track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
      track, options.keepOriginalTimestamps);

    audioFrameUtils.prefixWithSilence(
      track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);

    // we have to build the index from byte locations to
    // samples (that is, adts frames) in the audio data
    track.samples = audioFrameUtils.generateSampleTable(frames);

    // concatenate the audio data to constuct the mdat
    mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));

    adtsFrames = [];

    moof = mp4.moof(sequenceNumber, [track]);
    boxes = new Uint8Array(moof.byteLength + mdat.byteLength);

    // bump the sequence number for next time
    sequenceNumber++;

    boxes.set(moof);
    boxes.set(mdat, moof.byteLength);

    trackDecodeInfo.clearDtsInfo(track);

    frameDuration = Math.ceil(ONE_SECOND_IN_TS * 1024 / track.samplerate);

    // TODO this check was added to maintain backwards compatibility (particularly with
    // tests) on adding the timingInfo event. However, it seems unlikely that there's a
    // valid use-case where an init segment/data should be triggered without associated
    // frames. Leaving for now, but should be looked into.
    if (frames.length) {
      this.trigger('timingInfo', {
        start: frames[0].pts,
        end: frames[0].pts + (frames.length * frameDuration)
      });
    }
    this.trigger('data', {track: track, boxes: boxes});
    this.trigger('done', 'AudioSegmentStream');
  };

  this.reset = function() {
    trackDecodeInfo.clearDtsInfo(track);
    adtsFrames = [];
    this.trigger('reset');
  };
};

AudioSegmentStream.prototype = new Stream();

/**
 * Constructs a single-track, ISO BMFF media segment from H264 data
 * events. The output of this stream can be fed to a SourceBuffer
 * configured with a suitable initialization segment.
 * @param track {object} track metadata configuration
 * @param options {object} transmuxer options object
 * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
 *        gopsToAlignWith list when attempting to align gop pts
 * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
 *        in the source; false to adjust the first segment to start at 0.
 */
VideoSegmentStream = function(track, options) {
  var
    sequenceNumber = 0,
    nalUnits = [],
    gopsToAlignWith = [],
    config,
    pps;

  options = options || {};

  VideoSegmentStream.prototype.init.call(this);

  delete track.minPTS;

  this.gopCache_ = [];

  /**
    * Constructs a ISO BMFF segment given H264 nalUnits
    * @param {Object} nalUnit A data event representing a nalUnit
    * @param {String} nalUnit.nalUnitType
    * @param {Object} nalUnit.config Properties for a mp4 track
    * @param {Uint8Array} nalUnit.data The nalUnit bytes
    * @see lib/codecs/h264.js
   **/
  this.push = function(nalUnit) {
    trackDecodeInfo.collectDtsInfo(track, nalUnit);

    // record the track config
    if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
      config = nalUnit.config;
      track.sps = [nalUnit.data];

      VIDEO_PROPERTIES.forEach(function(prop) {
        track[prop] = config[prop];
      }, this);
    }

    if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
        !pps) {
      pps = nalUnit.data;
      track.pps = [nalUnit.data];
    }

    // buffer video until flush() is called
    nalUnits.push(nalUnit);
  };

  /**
    * Pass constructed ISO BMFF track and boxes on to the
    * next stream in the pipeline
   **/
  this.flush = function() {
    var
      frames,
      gopForFusion,
      gops,
      moof,
      mdat,
      boxes,
      prependedContentDuration = 0,
      firstGop,
      lastGop;

    // Throw away nalUnits at the start of the byte stream until
    // we find the first AUD
    while (nalUnits.length) {
      if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
        break;
      }
      nalUnits.shift();
    }

    // Return early if no video data has been observed
    if (nalUnits.length === 0) {
      this.resetStream_();
      this.trigger('done', 'VideoSegmentStream');
      return;
    }

    // Organize the raw nal-units into arrays that represent
    // higher-level constructs such as frames and gops
    // (group-of-pictures)
    frames = frameUtils.groupNalsIntoFrames(nalUnits);
    gops = frameUtils.groupFramesIntoGops(frames);

    // If the first frame of this fragment is not a keyframe we have
    // a problem since MSE (on Chrome) requires a leading keyframe.
    //
    // We have two approaches to repairing this situation:
    // 1) GOP-FUSION:
    //    This is where we keep track of the GOPS (group-of-pictures)
    //    from previous fragments and attempt to find one that we can
    //    prepend to the current fragment in order to create a valid
    //    fragment.
    // 2) KEYFRAME-PULLING:
    //    Here we search for the first keyframe in the fragment and
    //    throw away all the frames between the start of the fragment
    //    and that keyframe. We then extend the duration and pull the
    //    PTS of the keyframe forward so that it covers the time range
    //    of the frames that were disposed of.
    //
    // #1 is far prefereable over #2 which can cause "stuttering" but
    // requires more things to be just right.
    if (!gops[0][0].keyFrame) {
      // Search for a gop for fusion from our gopCache
      gopForFusion = this.getGopForFusion_(nalUnits[0], track);

      if (gopForFusion) {
        // in order to provide more accurate timing information about the segment, save
        // the number of seconds prepended to the original segment due to GOP fusion
        prependedContentDuration = gopForFusion.duration;

        gops.unshift(gopForFusion);
        // Adjust Gops' metadata to account for the inclusion of the
        // new gop at the beginning
        gops.byteLength += gopForFusion.byteLength;
        gops.nalCount += gopForFusion.nalCount;
        gops.pts = gopForFusion.pts;
        gops.dts = gopForFusion.dts;
        gops.duration += gopForFusion.duration;
      } else {
        // If we didn't find a candidate gop fall back to keyframe-pulling
        gops = frameUtils.extendFirstKeyFrame(gops);
      }
    }

    // Trim gops to align with gopsToAlignWith
    if (gopsToAlignWith.length) {
      var alignedGops;

      if (options.alignGopsAtEnd) {
        alignedGops = this.alignGopsAtEnd_(gops);
      } else {
        alignedGops = this.alignGopsAtStart_(gops);
      }

      if (!alignedGops) {
        // save all the nals in the last GOP into the gop cache
        this.gopCache_.unshift({
          gop: gops.pop(),
          pps: track.pps,
          sps: track.sps
        });

        // Keep a maximum of 6 GOPs in the cache
        this.gopCache_.length = Math.min(6, this.gopCache_.length);

        // Clear nalUnits
        nalUnits = [];

        // return early no gops can be aligned with desired gopsToAlignWith
        this.resetStream_();
        this.trigger('done', 'VideoSegmentStream');
        return;
      }

      // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
      // when recalculated before sending off to CoalesceStream
      trackDecodeInfo.clearDtsInfo(track);

      gops = alignedGops;
    }

    trackDecodeInfo.collectDtsInfo(track, gops);

    // First, we have to build the index from byte locations to
    // samples (that is, frames) in the video data
    track.samples = frameUtils.generateSampleTable(gops);

    // Concatenate the video data and construct the mdat
    mdat = mp4.mdat(frameUtils.concatenateNalData(gops));

    track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
      track, options.keepOriginalTimestamps);

    this.trigger('processedGopsInfo', gops.map(function(gop) {
      return {
        pts: gop.pts,
        dts: gop.dts,
        byteLength: gop.byteLength
      };
    }));

    firstGop = gops[0];
    lastGop = gops[gops.length - 1];

    this.trigger(
      'segmentTimingInfo',
      generateVideoSegmentTimingInfo(
        track.baseMediaDecodeTime,
        firstGop.dts,
        firstGop.pts,
        lastGop.dts + lastGop.duration,
        lastGop.pts + lastGop.duration,
        prependedContentDuration));

    this.trigger('timingInfo', {
      start: gops[0].pts,
      end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
    });

    // save all the nals in the last GOP into the gop cache
    this.gopCache_.unshift({
      gop: gops.pop(),
      pps: track.pps,
      sps: track.sps
    });

    // Keep a maximum of 6 GOPs in the cache
    this.gopCache_.length = Math.min(6, this.gopCache_.length);

    // Clear nalUnits
    nalUnits = [];

    this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
    this.trigger('timelineStartInfo', track.timelineStartInfo);

    moof = mp4.moof(sequenceNumber, [track]);

    // it would be great to allocate this array up front instead of
    // throwing away hundreds of media segment fragments
    boxes = new Uint8Array(moof.byteLength + mdat.byteLength);

    // Bump the sequence number for next time
    sequenceNumber++;

    boxes.set(moof);
    boxes.set(mdat, moof.byteLength);

    this.trigger('data', {track: track, boxes: boxes});

    this.resetStream_();

    // Continue with the flush process now
    this.trigger('done', 'VideoSegmentStream');
  };

  this.reset = function() {
    this.resetStream_();
    nalUnits = [];
    this.gopCache_.length = 0;
    gopsToAlignWith.length = 0;
    this.trigger('reset');
  };

  this.resetStream_ = function() {
    trackDecodeInfo.clearDtsInfo(track);

    // reset config and pps because they may differ across segments
    // for instance, when we are rendition switching
    config = undefined;
    pps = undefined;
  };

  // Search for a candidate Gop for gop-fusion from the gop cache and
  // return it or return null if no good candidate was found
  this.getGopForFusion_ = function(nalUnit) {
    var
      halfSecond = 45000, // Half-a-second in a 90khz clock
      allowableOverlap = 10000, // About 3 frames @ 30fps
      nearestDistance = Infinity,
      dtsDistance,
      nearestGopObj,
      currentGop,
      currentGopObj,
      i;

    // Search for the GOP nearest to the beginning of this nal unit
    for (i = 0; i < this.gopCache_.length; i++) {
      currentGopObj = this.gopCache_[i];
      currentGop = currentGopObj.gop;

      // Reject Gops with different SPS or PPS
      if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
          !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
        continue;
      }

      // Reject Gops that would require a negative baseMediaDecodeTime
      if (currentGop.dts < track.timelineStartInfo.dts) {
        continue;
      }

      // The distance between the end of the gop and the start of the nalUnit
      dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;

      // Only consider GOPS that start before the nal unit and end within
      // a half-second of the nal unit
      if (dtsDistance >= -allowableOverlap &&
          dtsDistance <= halfSecond) {

        // Always use the closest GOP we found if there is more than
        // one candidate
        if (!nearestGopObj ||
            nearestDistance > dtsDistance) {
          nearestGopObj = currentGopObj;
          nearestDistance = dtsDistance;
        }
      }
    }

    if (nearestGopObj) {
      return nearestGopObj.gop;
    }
    return null;
  };

  // trim gop list to the first gop found that has a matching pts with a gop in the list
  // of gopsToAlignWith starting from the START of the list
  this.alignGopsAtStart_ = function(gops) {
    var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;

    byteLength = gops.byteLength;
    nalCount = gops.nalCount;
    duration = gops.duration;
    alignIndex = gopIndex = 0;

    while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
      align = gopsToAlignWith[alignIndex];
      gop = gops[gopIndex];

      if (align.pts === gop.pts) {
        break;
      }

      if (gop.pts > align.pts) {
        // this current gop starts after the current gop we want to align on, so increment
        // align index
        alignIndex++;
        continue;
      }

      // current gop starts before the current gop we want to align on. so increment gop
      // index
      gopIndex++;
      byteLength -= gop.byteLength;
      nalCount -= gop.nalCount;
      duration -= gop.duration;
    }

    if (gopIndex === 0) {
      // no gops to trim
      return gops;
    }

    if (gopIndex === gops.length) {
      // all gops trimmed, skip appending all gops
      return null;
    }

    alignedGops = gops.slice(gopIndex);
    alignedGops.byteLength = byteLength;
    alignedGops.duration = duration;
    alignedGops.nalCount = nalCount;
    alignedGops.pts = alignedGops[0].pts;
    alignedGops.dts = alignedGops[0].dts;

    return alignedGops;
  };

  // trim gop list to the first gop found that has a matching pts with a gop in the list
  // of gopsToAlignWith starting from the END of the list
  this.alignGopsAtEnd_ = function(gops) {
    var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;

    alignIndex = gopsToAlignWith.length - 1;
    gopIndex = gops.length - 1;
    alignEndIndex = null;
    matchFound = false;

    while (alignIndex >= 0 && gopIndex >= 0) {
      align = gopsToAlignWith[alignIndex];
      gop = gops[gopIndex];

      if (align.pts === gop.pts) {
        matchFound = true;
        break;
      }

      if (align.pts > gop.pts) {
        alignIndex--;
        continue;
      }

      if (alignIndex === gopsToAlignWith.length - 1) {
        // gop.pts is greater than the last alignment candidate. If no match is found
        // by the end of this loop, we still want to append gops that come after this
        // point
        alignEndIndex = gopIndex;
      }

      gopIndex--;
    }

    if (!matchFound && alignEndIndex === null) {
      return null;
    }

    var trimIndex;

    if (matchFound) {
      trimIndex = gopIndex;
    } else {
      trimIndex = alignEndIndex;
    }

    if (trimIndex === 0) {
      return gops;
    }

    var alignedGops = gops.slice(trimIndex);
    var metadata = alignedGops.reduce(function(total, gop) {
      total.byteLength += gop.byteLength;
      total.duration += gop.duration;
      total.nalCount += gop.nalCount;
      return total;
    }, { byteLength: 0, duration: 0, nalCount: 0 });

    alignedGops.byteLength = metadata.byteLength;
    alignedGops.duration = metadata.duration;
    alignedGops.nalCount = metadata.nalCount;
    alignedGops.pts = alignedGops[0].pts;
    alignedGops.dts = alignedGops[0].dts;

    return alignedGops;
  };

  this.alignGopsWith = function(newGopsToAlignWith) {
    gopsToAlignWith = newGopsToAlignWith;
  };
};

VideoSegmentStream.prototype = new Stream();

/**
 * A Stream that can combine multiple streams (ie. audio & video)
 * into a single output segment for MSE. Also supports audio-only
 * and video-only streams.
 * @param options {object} transmuxer options object
 * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
 *        in the source; false to adjust the first segment to start at media timeline start.
 */
CoalesceStream = function(options, metadataStream) {
  // Number of Tracks per output segment
  // If greater than 1, we combine multiple
  // tracks into a single segment
  this.numberOfTracks = 0;
  this.metadataStream = metadataStream;

  options = options || {};

  if (typeof options.remux !== 'undefined') {
    this.remuxTracks = !!options.remux;
  } else {
    this.remuxTracks = true;
  }

  if (typeof options.keepOriginalTimestamps === 'boolean') {
    this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  } else {
    this.keepOriginalTimestamps = false;
  }

  this.pendingTracks = [];
  this.videoTrack = null;
  this.pendingBoxes = [];
  this.pendingCaptions = [];
  this.pendingMetadata = [];
  this.pendingBytes = 0;
  this.emittedTracks = 0;

  CoalesceStream.prototype.init.call(this);

  // Take output from multiple
  this.push = function(output) {
    // buffer incoming captions until the associated video segment
    // finishes
    if (output.text) {
      return this.pendingCaptions.push(output);
    }
    // buffer incoming id3 tags until the final flush
    if (output.frames) {
      return this.pendingMetadata.push(output);
    }

    // Add this track to the list of pending tracks and store
    // important information required for the construction of
    // the final segment
    this.pendingTracks.push(output.track);
    this.pendingBytes += output.boxes.byteLength;

    // TODO: is there an issue for this against chrome?
    // We unshift audio and push video because
    // as of Chrome 75 when switching from
    // one init segment to another if the video
    // mdat does not appear after the audio mdat
    // only audio will play for the duration of our transmux.
    if (output.track.type === 'video') {
      this.videoTrack = output.track;
      this.pendingBoxes.push(output.boxes);
    }
    if (output.track.type === 'audio') {
      this.audioTrack = output.track;
      this.pendingBoxes.unshift(output.boxes);
    }
  };
};

CoalesceStream.prototype = new Stream();
CoalesceStream.prototype.flush = function(flushSource) {
  var
    offset = 0,
    event = {
      captions: [],
      captionStreams: {},
      metadata: [],
      info: {}
    },
    caption,
    id3,
    initSegment,
    timelineStartPts = 0,
    i;

  if (this.pendingTracks.length < this.numberOfTracks) {
    if (flushSource !== 'VideoSegmentStream' &&
        flushSource !== 'AudioSegmentStream') {
      // Return because we haven't received a flush from a data-generating
      // portion of the segment (meaning that we have only recieved meta-data
      // or captions.)
      return;
    } else if (this.remuxTracks) {
      // Return until we have enough tracks from the pipeline to remux (if we
      // are remuxing audio and video into a single MP4)
      return;
    } else if (this.pendingTracks.length === 0) {
      // In the case where we receive a flush without any data having been
      // received we consider it an emitted track for the purposes of coalescing
      // `done` events.
      // We do this for the case where there is an audio and video track in the
      // segment but no audio data. (seen in several playlists with alternate
      // audio tracks and no audio present in the main TS segments.)
      this.emittedTracks++;

      if (this.emittedTracks >= this.numberOfTracks) {
        this.trigger('done');
        this.emittedTracks = 0;
      }
      return;
    }
  }

  if (this.videoTrack) {
    timelineStartPts = this.videoTrack.timelineStartInfo.pts;
    VIDEO_PROPERTIES.forEach(function(prop) {
      event.info[prop] = this.videoTrack[prop];
    }, this);
  } else if (this.audioTrack) {
    timelineStartPts = this.audioTrack.timelineStartInfo.pts;
    AUDIO_PROPERTIES.forEach(function(prop) {
      event.info[prop] = this.audioTrack[prop];
    }, this);
  }

  if (this.videoTrack || this.audioTrack) {
    if (this.pendingTracks.length === 1) {
      event.type = this.pendingTracks[0].type;
    } else {
      event.type = 'combined';
    }

    this.emittedTracks += this.pendingTracks.length;

    initSegment = mp4.initSegment(this.pendingTracks);

    // Create a new typed array to hold the init segment
    event.initSegment = new Uint8Array(initSegment.byteLength);

    // Create an init segment containing a moov
    // and track definitions
    event.initSegment.set(initSegment);

    // Create a new typed array to hold the moof+mdats
    event.data = new Uint8Array(this.pendingBytes);

    // Append each moof+mdat (one per track) together
    for (i = 0; i < this.pendingBoxes.length; i++) {
      event.data.set(this.pendingBoxes[i], offset);
      offset += this.pendingBoxes[i].byteLength;
    }

    // Translate caption PTS times into second offsets to match the
    // video timeline for the segment, and add track info
    for (i = 0; i < this.pendingCaptions.length; i++) {
      caption = this.pendingCaptions[i];
      caption.startTime = clock.metadataTsToSeconds(
        caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
      caption.endTime = clock.metadataTsToSeconds(
        caption.endPts, timelineStartPts, this.keepOriginalTimestamps);

      event.captionStreams[caption.stream] = true;
      event.captions.push(caption);
    }

    // Translate ID3 frame PTS times into second offsets to match the
    // video timeline for the segment
    for (i = 0; i < this.pendingMetadata.length; i++) {
      id3 = this.pendingMetadata[i];
      id3.cueTime = clock.metadataTsToSeconds(
        id3.pts, timelineStartPts, this.keepOriginalTimestamps);

      event.metadata.push(id3);
    }

    // We add this to every single emitted segment even though we only need
    // it for the first
    event.metadata.dispatchType = this.metadataStream.dispatchType;

    // Reset stream state
    this.pendingTracks.length = 0;
    this.videoTrack = null;
    this.pendingBoxes.length = 0;
    this.pendingCaptions.length = 0;
    this.pendingBytes = 0;
    this.pendingMetadata.length = 0;

    // Emit the built segment
    // We include captions and ID3 tags for backwards compatibility,
    // ideally we should send only video and audio in the data event
    this.trigger('data', event);
    // Emit each caption to the outside world
    // Ideally, this would happen immediately on parsing captions,
    // but we need to ensure that video data is sent back first
    // so that caption timing can be adjusted to match video timing
    for (i = 0; i < event.captions.length; i++) {
      caption = event.captions[i];

      this.trigger('caption', caption);
    }
    // Emit each id3 tag to the outside world
    // Ideally, this would happen immediately on parsing the tag,
    // but we need to ensure that video data is sent back first
    // so that ID3 frame timing can be adjusted to match video timing
    for (i = 0; i < event.metadata.length; i++) {
      id3 = event.metadata[i];

      this.trigger('id3Frame', id3);
    }
  }

  // Only emit `done` if all tracks have been flushed and emitted
  if (this.emittedTracks >= this.numberOfTracks) {
    this.trigger('done');
    this.emittedTracks = 0;
  }
};

CoalesceStream.prototype.setRemux = function(val) {
  this.remuxTracks = val;
};
/**
 * A Stream that expects MP2T binary data as input and produces
 * corresponding media segments, suitable for use with Media Source
 * Extension (MSE) implementations that support the ISO BMFF byte
 * stream format, like Chrome.
 */
Transmuxer = function(options) {
  var
    self = this,
    hasFlushed = true,
    videoTrack,
    audioTrack;

  Transmuxer.prototype.init.call(this);

  options = options || {};
  this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  this.transmuxPipeline_ = {};

  this.setupAacPipeline = function() {
    var pipeline = {};
    this.transmuxPipeline_ = pipeline;

    pipeline.type = 'aac';
    pipeline.metadataStream = new m2ts.MetadataStream();

    // set up the parsing pipeline
    pipeline.aacStream = new AacStream();
    pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
    pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
    pipeline.adtsStream = new AdtsStream();
    pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
    pipeline.headOfPipeline = pipeline.aacStream;

    pipeline.aacStream
      .pipe(pipeline.audioTimestampRolloverStream)
      .pipe(pipeline.adtsStream);
    pipeline.aacStream
      .pipe(pipeline.timedMetadataTimestampRolloverStream)
      .pipe(pipeline.metadataStream)
      .pipe(pipeline.coalesceStream);

    pipeline.metadataStream.on('timestamp', function(frame) {
      pipeline.aacStream.setTimestamp(frame.timeStamp);
    });

    pipeline.aacStream.on('data', function(data) {
      if ((data.type !== 'timed-metadata' && data.type !== 'audio') || pipeline.audioSegmentStream) {
        return;
      }

      audioTrack = audioTrack || {
        timelineStartInfo: {
          baseMediaDecodeTime: self.baseMediaDecodeTime
        },
        codec: 'adts',
        type: 'audio'
      };
      // hook up the audio segment stream to the first track with aac data
      pipeline.coalesceStream.numberOfTracks++;
      pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);

      pipeline.audioSegmentStream.on('timingInfo',
        self.trigger.bind(self, 'audioTimingInfo'));

      // Set up the final part of the audio pipeline
      pipeline.adtsStream
        .pipe(pipeline.audioSegmentStream)
        .pipe(pipeline.coalesceStream);

      // emit pmt info
      self.trigger('trackinfo', {
        hasAudio: !!audioTrack,
        hasVideo: !!videoTrack
      });
    });

    // Re-emit any data coming from the coalesce stream to the outside world
    pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
    // Let the consumer know we have finished flushing the entire pipeline
    pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  };

  this.setupTsPipeline = function() {
    var pipeline = {};
    this.transmuxPipeline_ = pipeline;

    pipeline.type = 'ts';
    pipeline.metadataStream = new m2ts.MetadataStream();

    // set up the parsing pipeline
    pipeline.packetStream = new m2ts.TransportPacketStream();
    pipeline.parseStream = new m2ts.TransportParseStream();
    pipeline.elementaryStream = new m2ts.ElementaryStream();
    pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
    pipeline.adtsStream = new AdtsStream();
    pipeline.h264Stream = new H264Stream();
    pipeline.captionStream = new m2ts.CaptionStream();
    pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
    pipeline.headOfPipeline = pipeline.packetStream;

    // disassemble MPEG2-TS packets into elementary streams
    pipeline.packetStream
      .pipe(pipeline.parseStream)
      .pipe(pipeline.elementaryStream)
      .pipe(pipeline.timestampRolloverStream);

    // !!THIS ORDER IS IMPORTANT!!
    // demux the streams
    pipeline.timestampRolloverStream
      .pipe(pipeline.h264Stream);

    pipeline.timestampRolloverStream
      .pipe(pipeline.adtsStream);

    pipeline.timestampRolloverStream
      .pipe(pipeline.metadataStream)
      .pipe(pipeline.coalesceStream);

    // Hook up CEA-608/708 caption stream
    pipeline.h264Stream.pipe(pipeline.captionStream)
      .pipe(pipeline.coalesceStream);

    pipeline.elementaryStream.on('data', function(data) {
      var i;

      if (data.type === 'metadata') {
        i = data.tracks.length;

        // scan the tracks listed in the metadata
        while (i--) {
          if (!videoTrack && data.tracks[i].type === 'video') {
            videoTrack = data.tracks[i];
            videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
          } else if (!audioTrack && data.tracks[i].type === 'audio') {
            audioTrack = data.tracks[i];
            audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
          }
        }

        // hook up the video segment stream to the first track with h264 data
        if (videoTrack && !pipeline.videoSegmentStream) {
          pipeline.coalesceStream.numberOfTracks++;
          pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);

          pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
            // When video emits timelineStartInfo data after a flush, we forward that
            // info to the AudioSegmentStream, if it exists, because video timeline
            // data takes precedence.  Do not do this if keepOriginalTimestamps is set,
            // because this is a particularly subtle form of timestamp alteration.
            if (audioTrack && !options.keepOriginalTimestamps) {
              audioTrack.timelineStartInfo = timelineStartInfo;
              // On the first segment we trim AAC frames that exist before the
              // very earliest DTS we have seen in video because Chrome will
              // interpret any video track with a baseMediaDecodeTime that is
              // non-zero as a gap.
              pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
            }
          });

          pipeline.videoSegmentStream.on('processedGopsInfo',
            self.trigger.bind(self, 'gopInfo'));
          pipeline.videoSegmentStream.on('segmentTimingInfo',
            self.trigger.bind(self, 'videoSegmentTimingInfo'));

          pipeline.videoSegmentStream.on('baseMediaDecodeTime', function(baseMediaDecodeTime) {
            if (audioTrack) {
              pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
            }
          });

          pipeline.videoSegmentStream.on('timingInfo',
            self.trigger.bind(self, 'videoTimingInfo'));

          // Set up the final part of the video pipeline
          pipeline.h264Stream
            .pipe(pipeline.videoSegmentStream)
            .pipe(pipeline.coalesceStream);
        }

        if (audioTrack && !pipeline.audioSegmentStream) {
          // hook up the audio segment stream to the first track with aac data
          pipeline.coalesceStream.numberOfTracks++;
          pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);

          pipeline.audioSegmentStream.on('timingInfo',
            self.trigger.bind(self, 'audioTimingInfo'));

          // Set up the final part of the audio pipeline
          pipeline.adtsStream
            .pipe(pipeline.audioSegmentStream)
            .pipe(pipeline.coalesceStream);
        }

        // emit pmt info
        self.trigger('trackinfo', {
          hasAudio: !!audioTrack,
          hasVideo: !!videoTrack
        });
      }
    });

    // Re-emit any data coming from the coalesce stream to the outside world
    pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
    pipeline.coalesceStream.on('id3Frame', function(id3Frame) {
      id3Frame.dispatchType = pipeline.metadataStream.dispatchType;

      self.trigger('id3Frame', id3Frame);
    });
    pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption'));
    // Let the consumer know we have finished flushing the entire pipeline
    pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  };

  // hook up the segment streams once track metadata is delivered
  this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
    var pipeline = this.transmuxPipeline_;

    if (!options.keepOriginalTimestamps) {
      this.baseMediaDecodeTime = baseMediaDecodeTime;
    }

    if (audioTrack) {
      audioTrack.timelineStartInfo.dts = undefined;
      audioTrack.timelineStartInfo.pts = undefined;
      trackDecodeInfo.clearDtsInfo(audioTrack);
      if (pipeline.audioTimestampRolloverStream) {
        pipeline.audioTimestampRolloverStream.discontinuity();
      }
    }
    if (videoTrack) {
      if (pipeline.videoSegmentStream) {
        pipeline.videoSegmentStream.gopCache_ = [];
      }
      videoTrack.timelineStartInfo.dts = undefined;
      videoTrack.timelineStartInfo.pts = undefined;
      trackDecodeInfo.clearDtsInfo(videoTrack);
      pipeline.captionStream.reset();
    }

    if (pipeline.timestampRolloverStream) {
      pipeline.timestampRolloverStream.discontinuity();
    }
  };

  this.setAudioAppendStart = function(timestamp) {
    if (audioTrack) {
      this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
    }
  };

  this.setRemux = function(val) {
    var pipeline = this.transmuxPipeline_;

    options.remux = val;

    if (pipeline && pipeline.coalesceStream) {
      pipeline.coalesceStream.setRemux(val);
    }
  };

  this.alignGopsWith = function(gopsToAlignWith) {
    if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
      this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
    }
  };

  // feed incoming data to the front of the parsing pipeline
  this.push = function(data) {
    if (hasFlushed) {
      var isAac = isLikelyAacData(data);

      if (isAac && this.transmuxPipeline_.type !== 'aac') {
        this.setupAacPipeline();
      } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
        this.setupTsPipeline();
      }
      hasFlushed = false;
    }
    this.transmuxPipeline_.headOfPipeline.push(data);
  };

  // flush any buffered data
  this.flush = function() {
    hasFlushed = true;
    // Start at the top of the pipeline and flush all pending work
    this.transmuxPipeline_.headOfPipeline.flush();
  };

  this.endTimeline = function() {
    this.transmuxPipeline_.headOfPipeline.endTimeline();
  };

  this.reset = function() {
    if (this.transmuxPipeline_.headOfPipeline) {
      this.transmuxPipeline_.headOfPipeline.reset();
    }
  };

  // Caption data has to be reset when seeking outside buffered range
  this.resetCaptions = function() {
    if (this.transmuxPipeline_.captionStream) {
      this.transmuxPipeline_.captionStream.reset();
    }
  };

};
Transmuxer.prototype = new Stream();

module.exports = {
  Transmuxer: Transmuxer,
  VideoSegmentStream: VideoSegmentStream,
  AudioSegmentStream: AudioSegmentStream,
  AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  // exported for testing
  generateVideoSegmentTimingInfo: generateVideoSegmentTimingInfo
};

},{"1":1,"18":18,"2":2,"23":23,"26":26,"28":28,"3":3,"31":31,"4":4,"47":47,"49":49,"6":6,"7":7}],33:[function(require,module,exports){
'use strict';

var Stream = require(49);
var mp4 = require(28);
var audioFrameUtils = require(23);
var trackInfo = require(31);
var ONE_SECOND_IN_TS = require(47).ONE_SECOND_IN_TS;
var AUDIO_PROPERTIES = require(6);

/**
 * Constructs a single-track, ISO BMFF media segment from AAC data
 * events. The output of this stream can be fed to a SourceBuffer
 * configured with a suitable initialization segment.
 */
var AudioSegmentStream = function(track, options) {
  var
    adtsFrames = [],
    sequenceNumber = 0,
    earliestAllowedDts = 0,
    audioAppendStartTs = 0,
    videoBaseMediaDecodeTime = Infinity,
    segmentStartPts = null,
    segmentEndPts = null;

  options = options || {};

  AudioSegmentStream.prototype.init.call(this);

  this.push = function(data) {
    trackInfo.collectDtsInfo(track, data);

    if (track) {
      AUDIO_PROPERTIES.forEach(function(prop) {
        track[prop] = data[prop];
      });
    }

    // buffer audio data until end() is called
    adtsFrames.push(data);
  };

  this.setEarliestDts = function(earliestDts) {
    earliestAllowedDts = earliestDts;
  };

  this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
    videoBaseMediaDecodeTime = baseMediaDecodeTime;
  };

  this.setAudioAppendStart = function(timestamp) {
    audioAppendStartTs = timestamp;
  };

  this.processFrames_ = function() {
    var
      frames,
      moof,
      mdat,
      boxes,
      timingInfo;

    // return early if no audio data has been observed
    if (adtsFrames.length === 0) {
      return;
    }

    frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
      adtsFrames, track, earliestAllowedDts);
    if (frames.length === 0) {
      // return early if the frames are all after the earliest allowed DTS
      // TODO should we clear the adtsFrames?
      return;
    }

    track.baseMediaDecodeTime = trackInfo.calculateTrackBaseMediaDecodeTime(
      track, options.keepOriginalTimestamps);

    audioFrameUtils.prefixWithSilence(
      track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);

    // we have to build the index from byte locations to
    // samples (that is, adts frames) in the audio data
    track.samples = audioFrameUtils.generateSampleTable(frames);

    // concatenate the audio data to constuct the mdat
    mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));

    adtsFrames = [];

    moof = mp4.moof(sequenceNumber, [track]);

    // bump the sequence number for next time
    sequenceNumber++;

    track.initSegment = mp4.initSegment([track]);

    // it would be great to allocate this array up front instead of
    // throwing away hundreds of media segment fragments
    boxes = new Uint8Array(moof.byteLength + mdat.byteLength);

    boxes.set(moof);
    boxes.set(mdat, moof.byteLength);

    trackInfo.clearDtsInfo(track);

    if (segmentStartPts === null) {
      segmentEndPts = segmentStartPts = frames[0].pts;
    }

    segmentEndPts += frames.length * (ONE_SECOND_IN_TS * 1024 / track.samplerate);

    timingInfo = { start: segmentStartPts };

    this.trigger('timingInfo', timingInfo);
    this.trigger('data', {track: track, boxes: boxes});
  };

  this.flush = function() {
    this.processFrames_();
    // trigger final timing info
    this.trigger('timingInfo', {
      start: segmentStartPts,
      end: segmentEndPts
    });
    this.resetTiming_();
    this.trigger('done', 'AudioSegmentStream');
  };

  this.partialFlush = function() {
    this.processFrames_();
    this.trigger('partialdone', 'AudioSegmentStream');
  };

  this.endTimeline = function() {
    this.flush();
    this.trigger('endedtimeline', 'AudioSegmentStream');
  };

  this.resetTiming_ = function() {
    trackInfo.clearDtsInfo(track);
    segmentStartPts = null;
    segmentEndPts = null;
  };

  this.reset = function() {
    this.resetTiming_();
    adtsFrames = [];
    this.trigger('reset');
  };
};

AudioSegmentStream.prototype = new Stream();

module.exports = AudioSegmentStream;

},{"23":23,"28":28,"31":31,"47":47,"49":49,"6":6}],34:[function(require,module,exports){
module.exports = {
  Transmuxer: require(35)
};

},{"35":35}],35:[function(require,module,exports){
var Stream = require(49);
var m2ts = require(18);
var codecs = require(5);
var AudioSegmentStream = require(33);
var VideoSegmentStream = require(36);
var trackInfo = require(31);
var isLikelyAacData = require(2).isLikelyAacData;
var AdtsStream = require(3);
var AacStream = require(1);
var clock = require(47);

var createPipeline = function(object) {
  object.prototype = new Stream();
  object.prototype.init.call(object);

  return object;
};

var tsPipeline = function(options) {
  var
    pipeline = {
      type: 'ts',
      tracks: {
        audio: null,
        video: null
      },
      packet: new m2ts.TransportPacketStream(),
      parse: new m2ts.TransportParseStream(),
      elementary: new m2ts.ElementaryStream(),
      timestampRollover: new m2ts.TimestampRolloverStream(),
      adts: new codecs.Adts(),
      h264: new codecs.h264.H264Stream(),
      captionStream: new m2ts.CaptionStream(),
      metadataStream: new m2ts.MetadataStream()
  };

  pipeline.headOfPipeline = pipeline.packet;

  // Transport Stream
  pipeline.packet
    .pipe(pipeline.parse)
    .pipe(pipeline.elementary)
    .pipe(pipeline.timestampRollover);

  // H264
  pipeline.timestampRollover
    .pipe(pipeline.h264);

  // Hook up CEA-608/708 caption stream
  pipeline.h264
    .pipe(pipeline.captionStream);

  pipeline.timestampRollover
    .pipe(pipeline.metadataStream);

  // ADTS
  pipeline.timestampRollover
    .pipe(pipeline.adts);

  pipeline.elementary.on('data', function(data) {
    if (data.type !== 'metadata') {
      return;
    }

    for (var i = 0; i < data.tracks.length; i++) {
      if (!pipeline.tracks[data.tracks[i].type]) {
        pipeline.tracks[data.tracks[i].type] = data.tracks[i];
        pipeline.tracks[data.tracks[i].type].timelineStartInfo.baseMediaDecodeTime = options.baseMediaDecodeTime;
      }
    }

    if (pipeline.tracks.video && !pipeline.videoSegmentStream) {
      pipeline.videoSegmentStream = new VideoSegmentStream(pipeline.tracks.video, options);

      pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
        if (pipeline.tracks.audio && !options.keepOriginalTimestamps) {
          pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - options.baseMediaDecodeTime);
        }
      });

      pipeline.videoSegmentStream.on('timingInfo',
                                     pipeline.trigger.bind(pipeline, 'videoTimingInfo'));

      pipeline.videoSegmentStream.on('data', function(data) {
        pipeline.trigger('data', {
          type: 'video',
          data: data
        });
      });

      pipeline.videoSegmentStream.on('done',
                                     pipeline.trigger.bind(pipeline, 'done'));
      pipeline.videoSegmentStream.on('partialdone',
                                     pipeline.trigger.bind(pipeline, 'partialdone'));
      pipeline.videoSegmentStream.on('endedtimeline',
                                     pipeline.trigger.bind(pipeline, 'endedtimeline'));

      pipeline.h264
        .pipe(pipeline.videoSegmentStream);
    }

    if (pipeline.tracks.audio && !pipeline.audioSegmentStream) {
      pipeline.audioSegmentStream = new AudioSegmentStream(pipeline.tracks.audio, options);

      pipeline.audioSegmentStream.on('data', function(data) {
        pipeline.trigger('data', {
          type: 'audio',
          data: data
        });
      });

      pipeline.audioSegmentStream.on('done',
                                     pipeline.trigger.bind(pipeline, 'done'));
      pipeline.audioSegmentStream.on('partialdone',
                                     pipeline.trigger.bind(pipeline, 'partialdone'));
      pipeline.audioSegmentStream.on('endedtimeline',
                                     pipeline.trigger.bind(pipeline, 'endedtimeline'));

      pipeline.audioSegmentStream.on('timingInfo',
                                     pipeline.trigger.bind(pipeline, 'audioTimingInfo'));

      pipeline.adts
        .pipe(pipeline.audioSegmentStream);
    }

    // emit pmt info
    pipeline.trigger('trackinfo', {
      hasAudio: !!pipeline.tracks.audio,
      hasVideo: !!pipeline.tracks.video
    });
  });

  pipeline.captionStream.on('data', function(caption) {
    var timelineStartPts;

    if (pipeline.tracks.video) {
      timelineStartPts = pipeline.tracks.video.timelineStartInfo.pts || 0;
    } else {
      // This will only happen if we encounter caption packets before
      // video data in a segment. This is an unusual/unlikely scenario,
      // so we assume the timeline starts at zero for now.
      timelineStartPts = 0;
    }

    // Translate caption PTS times into second offsets into the
    // video timeline for the segment
    caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, options.keepOriginalTimestamps);
    caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, options.keepOriginalTimestamps);

    pipeline.trigger('caption', caption);
  });

  pipeline = createPipeline(pipeline);

  pipeline.metadataStream.on('data', pipeline.trigger.bind(pipeline, 'id3Frame'));

  return pipeline;
};

var aacPipeline = function(options) {
  var
    pipeline = {
    type: 'aac',
    tracks: {
      audio: null
    },
    metadataStream: new m2ts.MetadataStream(),
    aacStream: new AacStream(),
    audioRollover: new m2ts.TimestampRolloverStream('audio'),
    timedMetadataRollover: new m2ts.TimestampRolloverStream('timed-metadata'),
    adtsStream: new AdtsStream(true)
  };

  // set up the parsing pipeline
  pipeline.headOfPipeline = pipeline.aacStream;

  pipeline.aacStream
    .pipe(pipeline.audioRollover)
    .pipe(pipeline.adtsStream);
  pipeline.aacStream
    .pipe(pipeline.timedMetadataRollover)
    .pipe(pipeline.metadataStream);

  pipeline.metadataStream.on('timestamp', function(frame) {
    pipeline.aacStream.setTimestamp(frame.timeStamp);
  });

  pipeline.aacStream.on('data', function(data) {
    if ((data.type !== 'timed-metadata' && data.type !== 'audio') || pipeline.audioSegmentStream) {
      return;
    }

    pipeline.tracks.audio = pipeline.tracks.audio || {
      timelineStartInfo: {
        baseMediaDecodeTime: options.baseMediaDecodeTime
      },
      codec: 'adts',
      type: 'audio'
    };

    // hook up the audio segment stream to the first track with aac data
    pipeline.audioSegmentStream = new AudioSegmentStream(pipeline.tracks.audio, options);

    pipeline.audioSegmentStream.on('data', function(data) {
      pipeline.trigger('data', {
        type: 'audio',
        data: data
      });
    });

    pipeline.audioSegmentStream.on('partialdone',
                                   pipeline.trigger.bind(pipeline, 'partialdone'));
    pipeline.audioSegmentStream.on('done', pipeline.trigger.bind(pipeline, 'done'));
    pipeline.audioSegmentStream.on('endedtimeline',
                                   pipeline.trigger.bind(pipeline, 'endedtimeline'));
    pipeline.audioSegmentStream.on('timingInfo',
                                   pipeline.trigger.bind(pipeline, 'audioTimingInfo'));

    // Set up the final part of the audio pipeline
    pipeline.adtsStream
      .pipe(pipeline.audioSegmentStream);

    pipeline.trigger('trackinfo', {
      hasAudio: !!pipeline.tracks.audio,
      hasVideo: !!pipeline.tracks.video
    });
  });

  // set the pipeline up as a stream before binding to get access to the trigger function
  pipeline = createPipeline(pipeline);

  pipeline.metadataStream.on('data', pipeline.trigger.bind(pipeline, 'id3Frame'));

  return pipeline;
};

var setupPipelineListeners = function(pipeline, transmuxer) {
  pipeline.on('data', transmuxer.trigger.bind(transmuxer, 'data'));
  pipeline.on('done', transmuxer.trigger.bind(transmuxer, 'done'));
  pipeline.on('partialdone', transmuxer.trigger.bind(transmuxer, 'partialdone'));
  pipeline.on('endedtimeline', transmuxer.trigger.bind(transmuxer, 'endedtimeline'));
  pipeline.on('audioTimingInfo', transmuxer.trigger.bind(transmuxer, 'audioTimingInfo'));
  pipeline.on('videoTimingInfo', transmuxer.trigger.bind(transmuxer, 'videoTimingInfo'));
  pipeline.on('trackinfo', transmuxer.trigger.bind(transmuxer, 'trackinfo'));
  pipeline.on('id3Frame', function(event) {
    // add this to every single emitted segment even though it's only needed for the first
    event.dispatchType = pipeline.metadataStream.dispatchType;
    // keep original time, can be adjusted if needed at a higher level
    event.cueTime = clock.videoTsToSeconds(event.pts);

    transmuxer.trigger('id3Frame', event);
  });
  pipeline.on('caption', function(event) {
    transmuxer.trigger('caption', event);
  });
};

var Transmuxer = function(options) {
  var
    pipeline = null,
    hasFlushed = true;

  options = options || {};

  Transmuxer.prototype.init.call(this);
  options.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;

  this.push = function(bytes) {
    if (hasFlushed) {
      var isAac = isLikelyAacData(bytes);

      if (isAac && (!pipeline || pipeline.type !== 'aac')) {
        pipeline = aacPipeline(options);
        setupPipelineListeners(pipeline, this);
      } else if (!isAac && (!pipeline || pipeline.type !== 'ts')) {
        pipeline = tsPipeline(options);
        setupPipelineListeners(pipeline, this);
      }
      hasFlushed = false;
    }

    pipeline.headOfPipeline.push(bytes);
  };

  this.flush = function() {
    if (!pipeline) {
      return;
    }

    hasFlushed = true;
    pipeline.headOfPipeline.flush();
  };

  this.partialFlush = function() {
    if (!pipeline) {
      return;
    }

    pipeline.headOfPipeline.partialFlush();
  };

  this.endTimeline = function() {
    if (!pipeline) {
      return;
    }

    pipeline.headOfPipeline.endTimeline();
  };

  this.reset = function() {
    if (!pipeline) {
      return;
    }

    pipeline.headOfPipeline.reset();
  };

  this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
    if (!options.keepOriginalTimestamps) {
      options.baseMediaDecodeTime = baseMediaDecodeTime;
    }

    if (!pipeline) {
      return;
    }

    if (pipeline.tracks.audio) {
      pipeline.tracks.audio.timelineStartInfo.dts = undefined;
      pipeline.tracks.audio.timelineStartInfo.pts = undefined;
      trackInfo.clearDtsInfo(pipeline.tracks.audio);
      if (pipeline.audioRollover) {
        pipeline.audioRollover.discontinuity();
      }
    }
    if (pipeline.tracks.video) {
      if (pipeline.videoSegmentStream) {
        pipeline.videoSegmentStream.gopCache_ = [];
      }
      pipeline.tracks.video.timelineStartInfo.dts = undefined;
      pipeline.tracks.video.timelineStartInfo.pts = undefined;
      trackInfo.clearDtsInfo(pipeline.tracks.video);
      // pipeline.captionStream.reset();
    }

    if (pipeline.timestampRollover) {
      pipeline.timestampRollover.discontinuity();

    }
  };

  this.setRemux = function(val) {
    options.remux = val;

    if (pipeline && pipeline.coalesceStream) {
      pipeline.coalesceStream.setRemux(val);
    }
  };


  this.setAudioAppendStart = function(audioAppendStart) {
    if (!pipeline || !pipeline.tracks.audio || !pipeline.audioSegmentStream) {
      return;
    }

    pipeline.audioSegmentStream.setAudioAppendStart(audioAppendStart);
  };

  // TODO GOP alignment support
  // Support may be a bit trickier than with full segment appends, as GOPs may be split
  // and processed in a more granular fashion
  this.alignGopsWith = function(gopsToAlignWith) {
    return;
  };
};

Transmuxer.prototype = new Stream();

module.exports = Transmuxer;

},{"1":1,"18":18,"2":2,"3":3,"31":31,"33":33,"36":36,"47":47,"49":49,"5":5}],36:[function(require,module,exports){
/**
 * Constructs a single-track, ISO BMFF media segment from H264 data
 * events. The output of this stream can be fed to a SourceBuffer
 * configured with a suitable initialization segment.
 * @param track {object} track metadata configuration
 * @param options {object} transmuxer options object
 * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
 *        gopsToAlignWith list when attempting to align gop pts
 */
'use strict';

var Stream = require(49);
var mp4 = require(28);
var trackInfo = require(31);
var frameUtils = require(26);
var VIDEO_PROPERTIES = require(7);

var VideoSegmentStream = function(track, options) {
  var
    sequenceNumber = 0,
    nalUnits = [],
    frameCache = [],
    // gopsToAlignWith = [],
    config,
    pps,
    segmentStartPts = null,
    segmentEndPts = null,
    gops,
    ensureNextFrameIsKeyFrame = true;

  options = options || {};

  VideoSegmentStream.prototype.init.call(this);

  this.push = function(nalUnit) {
    trackInfo.collectDtsInfo(track, nalUnit);
    if (typeof track.timelineStartInfo.dts === 'undefined') {
      track.timelineStartInfo.dts = nalUnit.dts;
    }

    // record the track config
    if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
      config = nalUnit.config;
      track.sps = [nalUnit.data];

      VIDEO_PROPERTIES.forEach(function(prop) {
        track[prop] = config[prop];
      }, this);
    }

    if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
        !pps) {
      pps = nalUnit.data;
      track.pps = [nalUnit.data];
    }

    // buffer video until flush() is called
    nalUnits.push(nalUnit);
  };

  this.processNals_ = function(cacheLastFrame) {
    var i;

    nalUnits = frameCache.concat(nalUnits);

    // Throw away nalUnits at the start of the byte stream until
    // we find the first AUD
    while (nalUnits.length) {
      if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
        break;
      }
      nalUnits.shift();
    }

    // Return early if no video data has been observed
    if (nalUnits.length === 0) {
      return;
    }

    var frames = frameUtils.groupNalsIntoFrames(nalUnits);

    if (!frames.length) {
      return;
    }

    // note that the frame cache may also protect us from cases where we haven't
    // pushed data for the entire first or last frame yet
    frameCache = frames[frames.length - 1];

    if (cacheLastFrame) {
      frames.pop();
      frames.duration -= frameCache.duration;
      frames.nalCount -= frameCache.length;
      frames.byteLength -= frameCache.byteLength;
    }

    if (!frames.length) {
      nalUnits = [];
      return;
    }

    this.trigger('timelineStartInfo', track.timelineStartInfo);

    if (ensureNextFrameIsKeyFrame) {
      gops = frameUtils.groupFramesIntoGops(frames);

      if (!gops[0][0].keyFrame) {
        gops = frameUtils.extendFirstKeyFrame(gops);

        if (!gops[0][0].keyFrame) {
          // we haven't yet gotten a key frame, so reset nal units to wait for more nal
          // units
          nalUnits = ([].concat.apply([], frames)).concat(frameCache);
          frameCache = [];
          return;
        }

        frames = [].concat.apply([], gops);
        frames.duration = gops.duration;
      }
      ensureNextFrameIsKeyFrame = false;
    }

    if (segmentStartPts === null) {
      segmentStartPts = frames[0].pts;
      segmentEndPts = segmentStartPts;
    }

    segmentEndPts += frames.duration;

    this.trigger('timingInfo', {
      start: segmentStartPts,
      end: segmentEndPts
    });

    for (i = 0; i < frames.length; i++) {
      var frame = frames[i];

      track.samples = frameUtils.generateSampleTableForFrame(frame);

      var mdat = mp4.mdat(frameUtils.concatenateNalDataForFrame(frame));

      trackInfo.clearDtsInfo(track);
      trackInfo.collectDtsInfo(track, frame);

      track.baseMediaDecodeTime = trackInfo.calculateTrackBaseMediaDecodeTime(
        track, options.keepOriginalTimestamps);

      var moof = mp4.moof(sequenceNumber, [track]);

      sequenceNumber++;

      track.initSegment = mp4.initSegment([track]);

      var boxes = new Uint8Array(moof.byteLength + mdat.byteLength);

      boxes.set(moof);
      boxes.set(mdat, moof.byteLength);

      this.trigger('data', {
        track: track,
        boxes: boxes,
        sequence: sequenceNumber,
        videoFrameDts: frame.dts,
        videoFramePts: frame.pts
      });
    }

    nalUnits = [];
  };

  this.resetTimingAndConfig_ = function() {
    config = undefined;
    pps = undefined;
    segmentStartPts = null;
    segmentEndPts = null;
  };

  this.partialFlush = function() {
    this.processNals_(true);
    this.trigger('partialdone', 'VideoSegmentStream');
  };

  this.flush = function() {
    this.processNals_(false);
    // reset config and pps because they may differ across segments
    // for instance, when we are rendition switching
    this.resetTimingAndConfig_();
    this.trigger('done', 'VideoSegmentStream');
  };

  this.endTimeline = function() {
    this.flush();
    this.trigger('endedtimeline', 'VideoSegmentStream');
  };

  this.reset = function() {
    this.resetTimingAndConfig_();
    frameCache = [];
    nalUnits = [];
    ensureNextFrameIsKeyFrame = true;
    this.trigger('reset');
  };
};

VideoSegmentStream.prototype = new Stream();

module.exports = VideoSegmentStream;

},{"26":26,"28":28,"31":31,"49":49,"7":7}],37:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Reads in-band caption information from a video elementary
 * stream. Captions must follow the CEA-708 standard for injection
 * into an MPEG-2 transport streams.
 * @see https://en.wikipedia.org/wiki/CEA-708
 * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
 */

'use strict';

// Supplemental enhancement information (SEI) NAL units have a
// payload type field to indicate how they are to be
// interpreted. CEAS-708 caption content is always transmitted with
// payload type 0x04.
var USER_DATA_REGISTERED_ITU_T_T35 = 4,
    RBSP_TRAILING_BITS = 128;

/**
  * Parse a supplemental enhancement information (SEI) NAL unit.
  * Stops parsing once a message of type ITU T T35 has been found.
  *
  * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  * @return {object} the parsed SEI payload
  * @see Rec. ITU-T H.264, 7.3.2.3.1
  */
var parseSei = function(bytes) {
  var
    i = 0,
    result = {
      payloadType: -1,
      payloadSize: 0
    },
    payloadType = 0,
    payloadSize = 0;

  // go through the sei_rbsp parsing each each individual sei_message
  while (i < bytes.byteLength) {
    // stop once we have hit the end of the sei_rbsp
    if (bytes[i] === RBSP_TRAILING_BITS) {
      break;
    }

    // Parse payload type
    while (bytes[i] === 0xFF) {
      payloadType += 255;
      i++;
    }
    payloadType += bytes[i++];

    // Parse payload size
    while (bytes[i] === 0xFF) {
      payloadSize += 255;
      i++;
    }
    payloadSize += bytes[i++];

    // this sei_message is a 608/708 caption so save it and break
    // there can only ever be one caption message in a frame's sei
    if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
      var userIdentifier = String.fromCharCode(
        bytes[i + 3],
        bytes[i + 4],
        bytes[i + 5],
        bytes[i + 6]);

      if (userIdentifier === 'GA94') {
        result.payloadType = payloadType;
        result.payloadSize = payloadSize;
        result.payload = bytes.subarray(i, i + payloadSize);
        break;
      } else {
        result.payload = void 0;
      }
    }

    // skip the payload and parse the next message
    i += payloadSize;
    payloadType = 0;
    payloadSize = 0;
  }

  return result;
};

// see ANSI/SCTE 128-1 (2013), section 8.1
var parseUserData = function(sei) {
  // itu_t_t35_contry_code must be 181 (United States) for
  // captions
  if (sei.payload[0] !== 181) {
    return null;
  }

  // itu_t_t35_provider_code should be 49 (ATSC) for captions
  if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
    return null;
  }

  // the user_identifier should be "GA94" to indicate ATSC1 data
  if (String.fromCharCode(sei.payload[3],
                          sei.payload[4],
                          sei.payload[5],
                          sei.payload[6]) !== 'GA94') {
    return null;
  }

  // finally, user_data_type_code should be 0x03 for caption data
  if (sei.payload[7] !== 0x03) {
    return null;
  }

  // return the user_data_type_structure and strip the trailing
  // marker bits
  return sei.payload.subarray(8, sei.payload.length - 1);
};

// see CEA-708-D, section 4.4
var parseCaptionPackets = function(pts, userData) {
  var results = [], i, count, offset, data;

  // if this is just filler, return immediately
  if (!(userData[0] & 0x40)) {
    return results;
  }

  // parse out the cc_data_1 and cc_data_2 fields
  count = userData[0] & 0x1f;
  for (i = 0; i < count; i++) {
    offset = i * 3;
    data = {
      type: userData[offset + 2] & 0x03,
      pts: pts
    };

    // capture cc data when cc_valid is 1
    if (userData[offset + 2] & 0x04) {
      data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
      results.push(data);
    }
  }
  return results;
};

var discardEmulationPreventionBytes = function(data) {
    var
      length = data.byteLength,
      emulationPreventionBytesPositions = [],
      i = 1,
      newLength, newData;

    // Find all `Emulation Prevention Bytes`
    while (i < length - 2) {
      if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
        emulationPreventionBytesPositions.push(i + 2);
        i += 2;
      } else {
        i++;
      }
    }

    // If no Emulation Prevention Bytes were found just return the original
    // array
    if (emulationPreventionBytesPositions.length === 0) {
      return data;
    }

    // Create a new array to hold the NAL unit data
    newLength = length - emulationPreventionBytesPositions.length;
    newData = new Uint8Array(newLength);
    var sourceIndex = 0;

    for (i = 0; i < newLength; sourceIndex++, i++) {
      if (sourceIndex === emulationPreventionBytesPositions[0]) {
        // Skip this byte
        sourceIndex++;
        // Remove this position index
        emulationPreventionBytesPositions.shift();
      }
      newData[i] = data[sourceIndex];
    }

    return newData;
};

// exports
module.exports = {
  parseSei: parseSei,
  parseUserData: parseUserData,
  parseCaptionPackets: parseCaptionPackets,
  discardEmulationPreventionBytes: discardEmulationPreventionBytes,
  USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
};

},{}],38:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var
  tagTypes = {
    0x08: 'audio',
    0x09: 'video',
    0x12: 'metadata'
  },
  hex = function(val) {
    return '0x' + ('00' + val.toString(16)).slice(-2).toUpperCase();
  },
  hexStringList = function(data) {
    var arr = [], i;

    while (data.byteLength > 0) {
      i = 0;
      arr.push(hex(data[i++]));
      data = data.subarray(i);
    }
    return arr.join(' ');
  },
  parseAVCTag = function(tag, obj) {
    var
      avcPacketTypes = [
        'AVC Sequence Header',
        'AVC NALU',
        'AVC End-of-Sequence'
      ],
      compositionTime = (tag[1] & parseInt('01111111', 2) << 16) | (tag[2] << 8) | tag[3];

    obj = obj || {};

    obj.avcPacketType = avcPacketTypes[tag[0]];
    obj.CompositionTime = (tag[1] & parseInt('10000000', 2)) ? -compositionTime : compositionTime;

    if (tag[0] === 1) {
      obj.nalUnitTypeRaw = hexStringList(tag.subarray(4, 100));
    } else {
      obj.data = hexStringList(tag.subarray(4));
    }

    return obj;
  },
  parseVideoTag = function(tag, obj) {
    var
      frameTypes = [
        'Unknown',
        'Keyframe (for AVC, a seekable frame)',
        'Inter frame (for AVC, a nonseekable frame)',
        'Disposable inter frame (H.263 only)',
        'Generated keyframe (reserved for server use only)',
        'Video info/command frame'
      ],
      codecID = tag[0] & parseInt('00001111', 2);

    obj = obj || {};

    obj.frameType = frameTypes[(tag[0] & parseInt('11110000', 2)) >>> 4];
    obj.codecID = codecID;

    if (codecID === 7) {
      return parseAVCTag(tag.subarray(1), obj);
    }
    return obj;
  },
  parseAACTag = function(tag, obj) {
    var packetTypes = [
      'AAC Sequence Header',
      'AAC Raw'
    ];

    obj = obj || {};

    obj.aacPacketType = packetTypes[tag[0]];
    obj.data = hexStringList(tag.subarray(1));

    return obj;
  },
  parseAudioTag = function(tag, obj) {
    var
      formatTable = [
        'Linear PCM, platform endian',
        'ADPCM',
        'MP3',
        'Linear PCM, little endian',
        'Nellymoser 16-kHz mono',
        'Nellymoser 8-kHz mono',
        'Nellymoser',
        'G.711 A-law logarithmic PCM',
        'G.711 mu-law logarithmic PCM',
        'reserved',
        'AAC',
        'Speex',
        'MP3 8-Khz',
        'Device-specific sound'
      ],
      samplingRateTable = [
        '5.5-kHz',
        '11-kHz',
        '22-kHz',
        '44-kHz'
      ],
      soundFormat = (tag[0] & parseInt('11110000', 2)) >>> 4;

    obj = obj || {};

    obj.soundFormat = formatTable[soundFormat];
    obj.soundRate = samplingRateTable[(tag[0] & parseInt('00001100', 2)) >>> 2];
    obj.soundSize = ((tag[0] & parseInt('00000010', 2)) >>> 1) ? '16-bit' : '8-bit';
    obj.soundType = (tag[0] & parseInt('00000001', 2)) ? 'Stereo' : 'Mono';

    if (soundFormat === 10) {
      return parseAACTag(tag.subarray(1), obj);
    }
    return obj;
  },
  parseGenericTag = function(tag) {
    return {
      tagType: tagTypes[tag[0]],
      dataSize: (tag[1] << 16) | (tag[2] << 8) | tag[3],
      timestamp: (tag[7] << 24) | (tag[4] << 16) | (tag[5] << 8) | tag[6],
      streamID: (tag[8] << 16) | (tag[9] << 8) | tag[10]
    };
  },
  inspectFlvTag = function(tag) {
    var header = parseGenericTag(tag);
    switch (tag[0]) {
      case 0x08:
        parseAudioTag(tag.subarray(11), header);
        break;
      case 0x09:
        parseVideoTag(tag.subarray(11), header);
        break;
      case 0x12:
    }
    return header;
  },
  inspectFlv = function(bytes) {
    var i = 9, // header
        dataSize,
        parsedResults = [],
        tag;

    // traverse the tags
    i += 4; // skip previous tag size
    while (i < bytes.byteLength) {
      dataSize = bytes[i + 1] << 16;
      dataSize |= bytes[i + 2] << 8;
      dataSize |= bytes[i + 3];
      dataSize += 11;

      tag = bytes.subarray(i, i + dataSize);
      parsedResults.push(inspectFlvTag(tag));
      i += dataSize + 4;
    }
    return parsedResults;
  },
  textifyFlv = function(flvTagArray) {
    return JSON.stringify(flvTagArray, null, 2);
  };

module.exports = {
  inspectTag: inspectFlvTag,
  inspect: inspectFlv,
  textify: textifyFlv
};

},{}],39:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Parse the internal MP4 structure into an equivalent javascript
 * object.
 */
'use strict';

var
  inspectMp4,
  textifyMp4,
  parseMp4Date = function(seconds) {
    return new Date(seconds * 1000 - 2082844800000);
  },
  parseType = require(29),
  findBox = require(25),
  nalParse = function(avcStream) {
    var
      avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
      result = [],
      i,
      length;
    for (i = 0; i + 4 < avcStream.length; i += length) {
      length = avcView.getUint32(i);
      i += 4;

      // bail if this doesn't appear to be an H264 stream
      if (length <= 0) {
        result.push('<span style=\'color:red;\'>MALFORMED DATA</span>');
        continue;
      }

      switch (avcStream[i] & 0x1F) {
      case 0x01:
        result.push('slice_layer_without_partitioning_rbsp');
        break;
      case 0x05:
        result.push('slice_layer_without_partitioning_rbsp_idr');
        break;
      case 0x06:
        result.push('sei_rbsp');
        break;
      case 0x07:
        result.push('seq_parameter_set_rbsp');
        break;
      case 0x08:
        result.push('pic_parameter_set_rbsp');
        break;
      case 0x09:
        result.push('access_unit_delimiter_rbsp');
        break;
      default:
        result.push('UNKNOWN NAL - ' + avcStream[i] & 0x1F);
        break;
      }
    }
    return result;
  },

  // registry of handlers for individual mp4 box types
  parse = {
    // codingname, not a first-class box type. stsd entries share the
    // same format as real boxes so the parsing infrastructure can be
    // shared
    avc1: function(data) {
      var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
      return {
        dataReferenceIndex: view.getUint16(6),
        width: view.getUint16(24),
        height: view.getUint16(26),
        horizresolution: view.getUint16(28) + (view.getUint16(30) / 16),
        vertresolution: view.getUint16(32) + (view.getUint16(34) / 16),
        frameCount: view.getUint16(40),
        depth: view.getUint16(74),
        config: inspectMp4(data.subarray(78, data.byteLength))
      };
    },
    avcC: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          configurationVersion: data[0],
          avcProfileIndication: data[1],
          profileCompatibility: data[2],
          avcLevelIndication: data[3],
          lengthSizeMinusOne: data[4] & 0x03,
          sps: [],
          pps: []
        },
        numOfSequenceParameterSets = data[5] & 0x1f,
        numOfPictureParameterSets,
        nalSize,
        offset,
        i;

      // iterate past any SPSs
      offset = 6;
      for (i = 0; i < numOfSequenceParameterSets; i++) {
        nalSize = view.getUint16(offset);
        offset += 2;
        result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
        offset += nalSize;
      }
      // iterate past any PPSs
      numOfPictureParameterSets = data[offset];
      offset++;
      for (i = 0; i < numOfPictureParameterSets; i++) {
        nalSize = view.getUint16(offset);
        offset += 2;
        result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
        offset += nalSize;
      }
      return result;
    },
    btrt: function(data) {
      var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
      return {
        bufferSizeDB: view.getUint32(0),
        maxBitrate: view.getUint32(4),
        avgBitrate: view.getUint32(8)
      };
    },
    esds: function(data) {
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        esId: (data[6] << 8) | data[7],
        streamPriority: data[8] & 0x1f,
        decoderConfig: {
          objectProfileIndication: data[11],
          streamType: (data[12] >>> 2) & 0x3f,
          bufferSize: (data[13] << 16) | (data[14] << 8) | data[15],
          maxBitrate: (data[16] << 24) |
            (data[17] << 16) |
            (data[18] <<  8) |
            data[19],
          avgBitrate: (data[20] << 24) |
            (data[21] << 16) |
            (data[22] <<  8) |
            data[23],
          decoderConfigDescriptor: {
            tag: data[24],
            length: data[25],
            audioObjectType: (data[26] >>> 3) & 0x1f,
            samplingFrequencyIndex: ((data[26] & 0x07) << 1) |
              ((data[27] >>> 7) & 0x01),
            channelConfiguration: (data[27] >>> 3) & 0x0f
          }
        }
      };
    },
    ftyp: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          majorBrand: parseType(data.subarray(0, 4)),
          minorVersion: view.getUint32(4),
          compatibleBrands: []
        },
        i = 8;
      while (i < data.byteLength) {
        result.compatibleBrands.push(parseType(data.subarray(i, i + 4)));
        i += 4;
      }
      return result;
    },
    dinf: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    dref: function(data) {
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        dataReferences: inspectMp4(data.subarray(8))
      };
    },
    hdlr: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          version: view.getUint8(0),
          flags: new Uint8Array(data.subarray(1, 4)),
          handlerType: parseType(data.subarray(8, 12)),
          name: ''
        },
        i = 8;

      // parse out the name field
      for (i = 24; i < data.byteLength; i++) {
        if (data[i] === 0x00) {
          // the name field is null-terminated
          i++;
          break;
        }
        result.name += String.fromCharCode(data[i]);
      }
      // decode UTF-8 to javascript's internal representation
      // see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
      result.name = decodeURIComponent(escape(result.name));

      return result;
    },
    mdat: function(data) {
      return {
        byteLength: data.byteLength,
        nals: nalParse(data)
      };
    },
    mdhd: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        i = 4,
        language,
        result = {
          version: view.getUint8(0),
          flags: new Uint8Array(data.subarray(1, 4)),
          language: ''
        };
      if (result.version === 1) {
        i += 4;
        result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
        i += 8;
        result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
        i += 4;
        result.timescale = view.getUint32(i);
        i += 8;
        result.duration = view.getUint32(i); // truncating top 4 bytes
      } else {
        result.creationTime = parseMp4Date(view.getUint32(i));
        i += 4;
        result.modificationTime = parseMp4Date(view.getUint32(i));
        i += 4;
        result.timescale = view.getUint32(i);
        i += 4;
        result.duration = view.getUint32(i);
      }
      i += 4;
      // language is stored as an ISO-639-2/T code in an array of three 5-bit fields
      // each field is the packed difference between its ASCII value and 0x60
      language = view.getUint16(i);
      result.language += String.fromCharCode((language >> 10) + 0x60);
      result.language += String.fromCharCode(((language & 0x03e0) >> 5) + 0x60);
      result.language += String.fromCharCode((language & 0x1f) + 0x60);

      return result;
    },
    mdia: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    mfhd: function(data) {
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        sequenceNumber: (data[4] << 24) |
          (data[5] << 16) |
          (data[6] << 8) |
          (data[7])
      };
    },
    minf: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    // codingname, not a first-class box type. stsd entries share the
    // same format as real boxes so the parsing infrastructure can be
    // shared
    mp4a: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          // 6 bytes reserved
          dataReferenceIndex: view.getUint16(6),
          // 4 + 4 bytes reserved
          channelcount: view.getUint16(16),
          samplesize: view.getUint16(18),
          // 2 bytes pre_defined
          // 2 bytes reserved
          samplerate: view.getUint16(24) + (view.getUint16(26) / 65536)
        };

      // if there are more bytes to process, assume this is an ISO/IEC
      // 14496-14 MP4AudioSampleEntry and parse the ESDBox
      if (data.byteLength > 28) {
        result.streamDescriptor = inspectMp4(data.subarray(28))[0];
      }
      return result;
    },
    moof: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    moov: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    mvex: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    mvhd: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        i = 4,
        result = {
          version: view.getUint8(0),
          flags: new Uint8Array(data.subarray(1, 4))
        };

      if (result.version === 1) {
        i += 4;
        result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
        i += 8;
        result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
        i += 4;
        result.timescale = view.getUint32(i);
        i += 8;
        result.duration = view.getUint32(i); // truncating top 4 bytes
      } else {
        result.creationTime = parseMp4Date(view.getUint32(i));
        i += 4;
        result.modificationTime = parseMp4Date(view.getUint32(i));
        i += 4;
        result.timescale = view.getUint32(i);
        i += 4;
        result.duration = view.getUint32(i);
      }
      i += 4;

      // convert fixed-point, base 16 back to a number
      result.rate = view.getUint16(i) + (view.getUint16(i + 2) / 16);
      i += 4;
      result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
      i += 2;
      i += 2;
      i += 2 * 4;
      result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
      i += 9 * 4;
      i += 6 * 4;
      result.nextTrackId = view.getUint32(i);
      return result;
    },
    pdin: function(data) {
      var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
      return {
        version: view.getUint8(0),
        flags: new Uint8Array(data.subarray(1, 4)),
        rate: view.getUint32(4),
        initialDelay: view.getUint32(8)
      };
    },
    sdtp: function(data) {
      var
        result = {
          version: data[0],
          flags: new Uint8Array(data.subarray(1, 4)),
          samples: []
        }, i;

      for (i = 4; i < data.byteLength; i++) {
        result.samples.push({
          dependsOn: (data[i] & 0x30) >> 4,
          isDependedOn: (data[i] & 0x0c) >> 2,
          hasRedundancy: data[i] & 0x03
        });
      }
      return result;
    },
    sidx: require(41),
    smhd: function(data) {
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        balance: data[4] + (data[5] / 256)
      };
    },
    stbl: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    stco: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          version: data[0],
          flags: new Uint8Array(data.subarray(1, 4)),
          chunkOffsets: []
        },
        entryCount = view.getUint32(4),
        i;
      for (i = 8; entryCount; i += 4, entryCount--) {
        result.chunkOffsets.push(view.getUint32(i));
      }
      return result;
    },
    stsc: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        entryCount = view.getUint32(4),
        result = {
          version: data[0],
          flags: new Uint8Array(data.subarray(1, 4)),
          sampleToChunks: []
        },
        i;
      for (i = 8; entryCount; i += 12, entryCount--) {
        result.sampleToChunks.push({
          firstChunk: view.getUint32(i),
          samplesPerChunk: view.getUint32(i + 4),
          sampleDescriptionIndex: view.getUint32(i + 8)
        });
      }
      return result;
    },
    stsd: function(data) {
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        sampleDescriptions: inspectMp4(data.subarray(8))
      };
    },
    stsz: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          version: data[0],
          flags: new Uint8Array(data.subarray(1, 4)),
          sampleSize: view.getUint32(4),
          entries: []
        },
        i;
      for (i = 12; i < data.byteLength; i += 4) {
        result.entries.push(view.getUint32(i));
      }
      return result;
    },
    stts: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        result = {
          version: data[0],
          flags: new Uint8Array(data.subarray(1, 4)),
          timeToSamples: []
        },
        entryCount = view.getUint32(4),
        i;

      for (i = 8; entryCount; i += 8, entryCount--) {
        result.timeToSamples.push({
          sampleCount: view.getUint32(i),
          sampleDelta: view.getUint32(i + 4)
        });
      }
      return result;
    },
    styp: function(data) {
      return parse.ftyp(data);
    },
    tfdt: require(42),
    tfhd: require(43),
    tkhd: function(data) {
      var
        view = new DataView(data.buffer, data.byteOffset, data.byteLength),
        i = 4,
        result = {
          version: view.getUint8(0),
          flags: new Uint8Array(data.subarray(1, 4))
        };
      if (result.version === 1) {
        i += 4;
        result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
        i += 8;
        result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
        i += 4;
        result.trackId = view.getUint32(i);
        i += 4;
        i += 8;
        result.duration = view.getUint32(i); // truncating top 4 bytes
      } else {
        result.creationTime = parseMp4Date(view.getUint32(i));
        i += 4;
        result.modificationTime = parseMp4Date(view.getUint32(i));
        i += 4;
        result.trackId = view.getUint32(i);
        i += 4;
        i += 4;
        result.duration = view.getUint32(i);
      }
      i += 4;
      i += 2 * 4;
      result.layer = view.getUint16(i);
      i += 2;
      result.alternateGroup = view.getUint16(i);
      i += 2;
      // convert fixed-point, base 16 back to a number
      result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
      i += 2;
      i += 2;
      result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
      i += 9 * 4;
      result.width = view.getUint16(i) + (view.getUint16(i + 2) / 65536);
      i += 4;
      result.height = view.getUint16(i) + (view.getUint16(i + 2) / 65536);
      return result;
    },
    traf: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    trak: function(data) {
      return {
        boxes: inspectMp4(data)
      };
    },
    trex: function(data) {
      var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        trackId: view.getUint32(4),
        defaultSampleDescriptionIndex: view.getUint32(8),
        defaultSampleDuration: view.getUint32(12),
        defaultSampleSize: view.getUint32(16),
        sampleDependsOn: data[20] & 0x03,
        sampleIsDependedOn: (data[21] & 0xc0) >> 6,
        sampleHasRedundancy: (data[21] & 0x30) >> 4,
        samplePaddingValue: (data[21] & 0x0e) >> 1,
        sampleIsDifferenceSample: !!(data[21] & 0x01),
        sampleDegradationPriority: view.getUint16(22)
      };
    },
    trun: require(44),
    'url ': function(data) {
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4))
      };
    },
    vmhd: function(data) {
      var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
      return {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        graphicsmode: view.getUint16(4),
        opcolor: new Uint16Array([view.getUint16(6),
                                  view.getUint16(8),
                                  view.getUint16(10)])
      };
    }
  };


/**
 * Return a javascript array of box objects parsed from an ISO base
 * media file.
 * @param data {Uint8Array} the binary data of the media to be inspected
 * @return {array} a javascript array of potentially nested box objects
 */
inspectMp4 = function(data) {
  var
    i = 0,
    result = [],
    view,
    size,
    type,
    end,
    box;

  // Convert data from Uint8Array to ArrayBuffer, to follow Dataview API
  var ab = new ArrayBuffer(data.length);
  var v = new Uint8Array(ab);
  for (var z = 0; z < data.length; ++z) {
      v[z] = data[z];
  }
  view = new DataView(ab);

  while (i < data.byteLength) {
    // parse box data
    size = view.getUint32(i);
    type =  parseType(data.subarray(i + 4, i + 8));
    end = size > 1 ? i + size : data.byteLength;

    // parse type-specific data
    box = (parse[type] || function(data) {
      return {
        data: data
      };
    })(data.subarray(i + 8, end));
    box.size = size;
    box.type = type;

    // store this box and move to the next
    result.push(box);
    i = end;
  }
  return result;
};

/**
 * Returns a textual representation of the javascript represtentation
 * of an MP4 file. You can use it as an alternative to
 * JSON.stringify() to compare inspected MP4s.
 * @param inspectedMp4 {array} the parsed array of boxes in an MP4
 * file
 * @param depth {number} (optional) the number of ancestor boxes of
 * the elements of inspectedMp4. Assumed to be zero if unspecified.
 * @return {string} a text representation of the parsed MP4
 */
textifyMp4 = function(inspectedMp4, depth) {
  var indent;
  depth = depth || 0;
  indent = new Array(depth * 2 + 1).join(' ');

  // iterate over all the boxes
  return inspectedMp4.map(function(box, index) {

    // list the box type first at the current indentation level
    return indent + box.type + '\n' +

      // the type is already included and handle child boxes separately
      Object.keys(box).filter(function(key) {
        return key !== 'type' && key !== 'boxes';

      // output all the box properties
      }).map(function(key) {
        var prefix = indent + '  ' + key + ': ',
            value = box[key];

        // print out raw bytes as hexademical
        if (value instanceof Uint8Array || value instanceof Uint32Array) {
          var bytes = Array.prototype.slice.call(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))
              .map(function(byte) {
                return ' ' + ('00' + byte.toString(16)).slice(-2);
              }).join('').match(/.{1,24}/g);
          if (!bytes) {
            return prefix + '<>';
          }
          if (bytes.length === 1) {
            return prefix + '<' + bytes.join('').slice(1) + '>';
          }
          return prefix + '<\n' + bytes.map(function(line) {
            return indent + '  ' + line;
          }).join('\n') + '\n' + indent + '  >';
        }

        // stringify generic objects
        return prefix +
            JSON.stringify(value, null, 2)
              .split('\n').map(function(line, index) {
                if (index === 0) {
                  return line;
                }
                return indent + '  ' + line;
              }).join('\n');
      }).join('\n') +

    // recursively textify the child boxes
    (box.boxes ? '\n' + textifyMp4(box.boxes, depth + 1) : '');
  }).join('\n');
};

module.exports = {
  inspect: inspectMp4,
  textify: textifyMp4,
  parseType: parseType,
  findBox: findBox,
  parseTraf: parse.traf,
  parseTfdt: parse.tfdt,
  parseHdlr: parse.hdlr,
  parseTfhd: parse.tfhd,
  parseTrun: parse.trun,
  parseSidx: parse.sidx
};

},{"25":25,"29":29,"41":41,"42":42,"43":43,"44":44}],40:[function(require,module,exports){
var parseSampleFlags = function(flags) {
  return {
    isLeading: (flags[0] & 0x0c) >>> 2,
    dependsOn: flags[0] & 0x03,
    isDependedOn: (flags[1] & 0xc0) >>> 6,
    hasRedundancy: (flags[1] & 0x30) >>> 4,
    paddingValue: (flags[1] & 0x0e) >>> 1,
    isNonSyncSample: flags[1] & 0x01,
    degradationPriority: (flags[2] << 8) | flags[3]
  };
};

module.exports = parseSampleFlags;

},{}],41:[function(require,module,exports){
var MAX_UINT32 = Math.pow(2, 32);

var parseSidx = function(data) {
  var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
      result = {
        version: data[0],
        flags: new Uint8Array(data.subarray(1, 4)),
        references: [],
        referenceId: view.getUint32(4),
        timescale: view.getUint32(8)
      },
    i = 12;

  if (result.version === 0) {
    result.earliestPresentationTime = view.getUint32(i);
    result.firstOffset = view.getUint32(i + 4);
    i += 8;
  } else {
    // read 64 bits
    result.earliestPresentationTime = (view.getUint32(i) * MAX_UINT32) + view.getUint32(i + 4);
    result.firstOffset = (view.getUint32(i + 8) * MAX_UINT32) + view.getUint32(i + 12);
    i += 16;
  }

  i += 2; // reserved

  var referenceCount = view.getUint16(i);

  i += 2; // start of references

  for (; referenceCount > 0; i += 12, referenceCount--) {
    result.references.push({
      referenceType: (data[i] & 0x80) >>> 7,
      referencedSize: view.getUint32(i) & 0x7FFFFFFF,
      subsegmentDuration: view.getUint32(i + 4),
      startsWithSap: !!(data[i + 8] & 0x80),
      sapType: (data[i + 8] & 0x70) >>> 4,
      sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
    });
  }

  return result;
};


module.exports = parseSidx;

},{}],42:[function(require,module,exports){
var toUnsigned = require(46).toUnsigned;

var tfdt = function(data) {
  var result = {
    version: data[0],
    flags: new Uint8Array(data.subarray(1, 4)),
    baseMediaDecodeTime: toUnsigned(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
  };
  if (result.version === 1) {
    result.baseMediaDecodeTime *= Math.pow(2, 32);
    result.baseMediaDecodeTime += toUnsigned(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
  }
  return result;
};

module.exports = tfdt;


},{"46":46}],43:[function(require,module,exports){
var tfhd = function(data) {
  var
  view = new DataView(data.buffer, data.byteOffset, data.byteLength),
    result = {
      version: data[0],
      flags: new Uint8Array(data.subarray(1, 4)),
      trackId: view.getUint32(4)
    },
    baseDataOffsetPresent = result.flags[2] & 0x01,
    sampleDescriptionIndexPresent = result.flags[2] & 0x02,
    defaultSampleDurationPresent = result.flags[2] & 0x08,
    defaultSampleSizePresent = result.flags[2] & 0x10,
    defaultSampleFlagsPresent = result.flags[2] & 0x20,
    durationIsEmpty = result.flags[0] & 0x010000,
    defaultBaseIsMoof =  result.flags[0] & 0x020000,
    i;

  i = 8;
  if (baseDataOffsetPresent) {
    i += 4; // truncate top 4 bytes
    // FIXME: should we read the full 64 bits?
    result.baseDataOffset = view.getUint32(12);
    i += 4;
  }
  if (sampleDescriptionIndexPresent) {
    result.sampleDescriptionIndex = view.getUint32(i);
    i += 4;
  }
  if (defaultSampleDurationPresent) {
    result.defaultSampleDuration = view.getUint32(i);
    i += 4;
  }
  if (defaultSampleSizePresent) {
    result.defaultSampleSize = view.getUint32(i);
    i += 4;
  }
  if (defaultSampleFlagsPresent) {
    result.defaultSampleFlags = view.getUint32(i);
  }
  if (durationIsEmpty) {
    result.durationIsEmpty = true;
  }
  if (!baseDataOffsetPresent && defaultBaseIsMoof) {
    result.baseDataOffsetIsMoof = true;
  }
  return result;
};

module.exports = tfhd;

},{}],44:[function(require,module,exports){
var parseSampleFlags = require(40);

var trun = function(data) {
  var
  result = {
    version: data[0],
    flags: new Uint8Array(data.subarray(1, 4)),
    samples: []
  },
    view = new DataView(data.buffer, data.byteOffset, data.byteLength),
    // Flag interpretation
    dataOffsetPresent = result.flags[2] & 0x01, // compare with 2nd byte of 0x1
    firstSampleFlagsPresent = result.flags[2] & 0x04, // compare with 2nd byte of 0x4
    sampleDurationPresent = result.flags[1] & 0x01, // compare with 2nd byte of 0x100
    sampleSizePresent = result.flags[1] & 0x02, // compare with 2nd byte of 0x200
    sampleFlagsPresent = result.flags[1] & 0x04, // compare with 2nd byte of 0x400
    sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08, // compare with 2nd byte of 0x800
    sampleCount = view.getUint32(4),
    offset = 8,
    sample;

  if (dataOffsetPresent) {
    // 32 bit signed integer
    result.dataOffset = view.getInt32(offset);
    offset += 4;
  }

  // Overrides the flags for the first sample only. The order of
  // optional values will be: duration, size, compositionTimeOffset
  if (firstSampleFlagsPresent && sampleCount) {
    sample = {
      flags: parseSampleFlags(data.subarray(offset, offset + 4))
    };
    offset += 4;
    if (sampleDurationPresent) {
      sample.duration = view.getUint32(offset);
      offset += 4;
    }
    if (sampleSizePresent) {
      sample.size = view.getUint32(offset);
      offset += 4;
    }
    if (sampleCompositionTimeOffsetPresent) {
      if (result.version === 1) {
        sample.compositionTimeOffset = view.getInt32(offset);
      } else {
        sample.compositionTimeOffset = view.getUint32(offset);
      }
      offset += 4;
    }
    result.samples.push(sample);
    sampleCount--;
  }

  while (sampleCount--) {
    sample = {};
    if (sampleDurationPresent) {
      sample.duration = view.getUint32(offset);
      offset += 4;
    }
    if (sampleSizePresent) {
      sample.size = view.getUint32(offset);
      offset += 4;
    }
    if (sampleFlagsPresent) {
      sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
      offset += 4;
    }
    if (sampleCompositionTimeOffsetPresent) {
      if (result.version === 1) {
        sample.compositionTimeOffset = view.getInt32(offset);
      } else {
        sample.compositionTimeOffset = view.getUint32(offset);
      }
      offset += 4;
    }
    result.samples.push(sample);
  }
  return result;
};

module.exports = trun;

},{"40":40}],45:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * Parse mpeg2 transport stream packets to extract basic timing information
 */
'use strict';

var StreamTypes = require(21);
var handleRollover = require(22).handleRollover;
var probe = {};
probe.ts = require(20);
probe.aac = require(2);
var ONE_SECOND_IN_TS = require(47).ONE_SECOND_IN_TS;

var
  MP2T_PACKET_LENGTH = 188, // bytes
  SYNC_BYTE = 0x47;

/**
 * walks through segment data looking for pat and pmt packets to parse out
 * program map table information
 */
var parsePsi_ = function(bytes, pmt) {
  var
    startIndex = 0,
    endIndex = MP2T_PACKET_LENGTH,
    packet, type;

  while (endIndex < bytes.byteLength) {
    // Look for a pair of start and end sync bytes in the data..
    if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
      // We found a packet
      packet = bytes.subarray(startIndex, endIndex);
      type = probe.ts.parseType(packet, pmt.pid);

      switch (type) {
        case 'pat':
          if (!pmt.pid) {
            pmt.pid = probe.ts.parsePat(packet);
          }
          break;
        case 'pmt':
          if (!pmt.table) {
            pmt.table = probe.ts.parsePmt(packet);
          }
          break;
        default:
          break;
      }

      // Found the pat and pmt, we can stop walking the segment
      if (pmt.pid && pmt.table) {
        return;
      }

      startIndex += MP2T_PACKET_LENGTH;
      endIndex += MP2T_PACKET_LENGTH;
      continue;
    }

    // If we get here, we have somehow become de-synchronized and we need to step
    // forward one byte at a time until we find a pair of sync bytes that denote
    // a packet
    startIndex++;
    endIndex++;
  }
};

/**
 * walks through the segment data from the start and end to get timing information
 * for the first and last audio pes packets
 */
var parseAudioPes_ = function(bytes, pmt, result) {
  var
    startIndex = 0,
    endIndex = MP2T_PACKET_LENGTH,
    packet, type, pesType, pusi, parsed;

  var endLoop = false;

  // Start walking from start of segment to get first audio packet
  while (endIndex <= bytes.byteLength) {
    // Look for a pair of start and end sync bytes in the data..
    if (bytes[startIndex] === SYNC_BYTE &&
        (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
      // We found a packet
      packet = bytes.subarray(startIndex, endIndex);
      type = probe.ts.parseType(packet, pmt.pid);

      switch (type) {
        case 'pes':
          pesType = probe.ts.parsePesType(packet, pmt.table);
          pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
          if (pesType === 'audio' && pusi) {
            parsed = probe.ts.parsePesTime(packet);
            if (parsed) {
              parsed.type = 'audio';
              result.audio.push(parsed);
              endLoop = true;
            }
          }
          break;
        default:
          break;
      }

      if (endLoop) {
        break;
      }

      startIndex += MP2T_PACKET_LENGTH;
      endIndex += MP2T_PACKET_LENGTH;
      continue;
    }

    // If we get here, we have somehow become de-synchronized and we need to step
    // forward one byte at a time until we find a pair of sync bytes that denote
    // a packet
    startIndex++;
    endIndex++;
  }

  // Start walking from end of segment to get last audio packet
  endIndex = bytes.byteLength;
  startIndex = endIndex - MP2T_PACKET_LENGTH;
  endLoop = false;
  while (startIndex >= 0) {
    // Look for a pair of start and end sync bytes in the data..
    if (bytes[startIndex] === SYNC_BYTE &&
        (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
      // We found a packet
      packet = bytes.subarray(startIndex, endIndex);
      type = probe.ts.parseType(packet, pmt.pid);

      switch (type) {
        case 'pes':
          pesType = probe.ts.parsePesType(packet, pmt.table);
          pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
          if (pesType === 'audio' && pusi) {
            parsed = probe.ts.parsePesTime(packet);
            if (parsed) {
              parsed.type = 'audio';
              result.audio.push(parsed);
              endLoop = true;
            }
          }
          break;
        default:
          break;
      }

      if (endLoop) {
        break;
      }

      startIndex -= MP2T_PACKET_LENGTH;
      endIndex -= MP2T_PACKET_LENGTH;
      continue;
    }

    // If we get here, we have somehow become de-synchronized and we need to step
    // forward one byte at a time until we find a pair of sync bytes that denote
    // a packet
    startIndex--;
    endIndex--;
  }
};

/**
 * walks through the segment data from the start and end to get timing information
 * for the first and last video pes packets as well as timing information for the first
 * key frame.
 */
var parseVideoPes_ = function(bytes, pmt, result) {
  var
    startIndex = 0,
    endIndex = MP2T_PACKET_LENGTH,
    packet, type, pesType, pusi, parsed, frame, i, pes;

  var endLoop = false;

  var currentFrame = {
    data: [],
    size: 0
  };

  // Start walking from start of segment to get first video packet
  while (endIndex < bytes.byteLength) {
    // Look for a pair of start and end sync bytes in the data..
    if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
      // We found a packet
      packet = bytes.subarray(startIndex, endIndex);
      type = probe.ts.parseType(packet, pmt.pid);

      switch (type) {
        case 'pes':
          pesType = probe.ts.parsePesType(packet, pmt.table);
          pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
          if (pesType === 'video') {
            if (pusi && !endLoop) {
              parsed = probe.ts.parsePesTime(packet);
              if (parsed) {
                parsed.type = 'video';
                result.video.push(parsed);
                endLoop = true;
              }
            }
            if (!result.firstKeyFrame) {
              if (pusi) {
                if (currentFrame.size !== 0) {
                  frame = new Uint8Array(currentFrame.size);
                  i = 0;
                  while (currentFrame.data.length) {
                    pes = currentFrame.data.shift();
                    frame.set(pes, i);
                    i += pes.byteLength;
                  }
                  if (probe.ts.videoPacketContainsKeyFrame(frame)) {
                    var firstKeyFrame = probe.ts.parsePesTime(frame);

                    // PTS/DTS may not be available. Simply *not* setting
                    // the keyframe seems to work fine with HLS playback
                    // and definitely preferable to a crash with TypeError...
                    if (firstKeyFrame) {
                      result.firstKeyFrame = firstKeyFrame;
                      result.firstKeyFrame.type = 'video';
                    } else {
                      // eslint-disable-next-line
                      console.warn(
                        'Failed to extract PTS/DTS from PES at first keyframe. ' +
                        'This could be an unusual TS segment, or else mux.js did not ' +
                        'parse your TS segment correctly. If you know your TS ' +
                        'segments do contain PTS/DTS on keyframes please file a bug ' +
                        'report! You can try ffprobe to double check for yourself.'
                      );
                    }
                  }
                  currentFrame.size = 0;
                }
              }
              currentFrame.data.push(packet);
              currentFrame.size += packet.byteLength;
            }
          }
          break;
        default:
          break;
      }

      if (endLoop && result.firstKeyFrame) {
        break;
      }

      startIndex += MP2T_PACKET_LENGTH;
      endIndex += MP2T_PACKET_LENGTH;
      continue;
    }

    // If we get here, we have somehow become de-synchronized and we need to step
    // forward one byte at a time until we find a pair of sync bytes that denote
    // a packet
    startIndex++;
    endIndex++;
  }

  // Start walking from end of segment to get last video packet
  endIndex = bytes.byteLength;
  startIndex = endIndex - MP2T_PACKET_LENGTH;
  endLoop = false;
  while (startIndex >= 0) {
    // Look for a pair of start and end sync bytes in the data..
    if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
      // We found a packet
      packet = bytes.subarray(startIndex, endIndex);
      type = probe.ts.parseType(packet, pmt.pid);

      switch (type) {
        case 'pes':
          pesType = probe.ts.parsePesType(packet, pmt.table);
          pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
          if (pesType === 'video' && pusi) {
              parsed = probe.ts.parsePesTime(packet);
              if (parsed) {
                parsed.type = 'video';
                result.video.push(parsed);
                endLoop = true;
              }
          }
          break;
        default:
          break;
      }

      if (endLoop) {
        break;
      }

      startIndex -= MP2T_PACKET_LENGTH;
      endIndex -= MP2T_PACKET_LENGTH;
      continue;
    }

    // If we get here, we have somehow become de-synchronized and we need to step
    // forward one byte at a time until we find a pair of sync bytes that denote
    // a packet
    startIndex--;
    endIndex--;
  }
};

/**
 * Adjusts the timestamp information for the segment to account for
 * rollover and convert to seconds based on pes packet timescale (90khz clock)
 */
var adjustTimestamp_ = function(segmentInfo, baseTimestamp) {
  if (segmentInfo.audio && segmentInfo.audio.length) {
    var audioBaseTimestamp = baseTimestamp;
    if (typeof audioBaseTimestamp === 'undefined') {
      audioBaseTimestamp = segmentInfo.audio[0].dts;
    }
    segmentInfo.audio.forEach(function(info) {
      info.dts = handleRollover(info.dts, audioBaseTimestamp);
      info.pts = handleRollover(info.pts, audioBaseTimestamp);
      // time in seconds
      info.dtsTime = info.dts / ONE_SECOND_IN_TS;
      info.ptsTime = info.pts / ONE_SECOND_IN_TS;
    });
  }

  if (segmentInfo.video && segmentInfo.video.length) {
    var videoBaseTimestamp = baseTimestamp;
    if (typeof videoBaseTimestamp === 'undefined') {
      videoBaseTimestamp = segmentInfo.video[0].dts;
    }
    segmentInfo.video.forEach(function(info) {
      info.dts = handleRollover(info.dts, videoBaseTimestamp);
      info.pts = handleRollover(info.pts, videoBaseTimestamp);
      // time in seconds
      info.dtsTime = info.dts / ONE_SECOND_IN_TS;
      info.ptsTime = info.pts / ONE_SECOND_IN_TS;
    });
    if (segmentInfo.firstKeyFrame) {
      var frame = segmentInfo.firstKeyFrame;
      frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
      frame.pts = handleRollover(frame.pts, videoBaseTimestamp);
      // time in seconds
      frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
      frame.ptsTime = frame.dts / ONE_SECOND_IN_TS;
    }
  }
};

/**
 * inspects the aac data stream for start and end time information
 */
var inspectAac_ = function(bytes) {
  var
    endLoop = false,
    audioCount = 0,
    sampleRate = null,
    timestamp = null,
    frameSize = 0,
    byteIndex = 0,
    packet;

  while (bytes.length - byteIndex >= 3) {
    var type = probe.aac.parseType(bytes, byteIndex);
    switch (type) {
      case 'timed-metadata':
        // Exit early because we don't have enough to parse
        // the ID3 tag header
        if (bytes.length - byteIndex < 10) {
          endLoop = true;
          break;
        }

        frameSize = probe.aac.parseId3TagSize(bytes, byteIndex);

        // Exit early if we don't have enough in the buffer
        // to emit a full packet
        if (frameSize > bytes.length) {
          endLoop = true;
          break;
        }
        if (timestamp === null) {
          packet = bytes.subarray(byteIndex, byteIndex + frameSize);
          timestamp = probe.aac.parseAacTimestamp(packet);
        }
        byteIndex += frameSize;
        break;
      case 'audio':
        // Exit early because we don't have enough to parse
        // the ADTS frame header
        if (bytes.length - byteIndex < 7) {
          endLoop = true;
          break;
        }

        frameSize = probe.aac.parseAdtsSize(bytes, byteIndex);

        // Exit early if we don't have enough in the buffer
        // to emit a full packet
        if (frameSize > bytes.length) {
          endLoop = true;
          break;
        }
        if (sampleRate === null) {
          packet = bytes.subarray(byteIndex, byteIndex + frameSize);
          sampleRate = probe.aac.parseSampleRate(packet);
        }
        audioCount++;
        byteIndex += frameSize;
        break;
      default:
        byteIndex++;
        break;
    }
    if (endLoop) {
      return null;
    }
  }
  if (sampleRate === null || timestamp === null) {
    return null;
  }

  var audioTimescale = ONE_SECOND_IN_TS / sampleRate;

  var result = {
    audio: [
      {
        type: 'audio',
        dts: timestamp,
        pts: timestamp
      },
      {
        type: 'audio',
        dts: timestamp + (audioCount * 1024 * audioTimescale),
        pts: timestamp + (audioCount * 1024 * audioTimescale)
      }
    ]
  };

  return result;
};

/**
 * inspects the transport stream segment data for start and end time information
 * of the audio and video tracks (when present) as well as the first key frame's
 * start time.
 */
var inspectTs_ = function(bytes) {
  var pmt = {
    pid: null,
    table: null
  };

  var result = {};

  parsePsi_(bytes, pmt);

  for (var pid in pmt.table) {
    if (pmt.table.hasOwnProperty(pid)) {
      var type = pmt.table[pid];
      switch (type) {
        case StreamTypes.H264_STREAM_TYPE:
          result.video = [];
          parseVideoPes_(bytes, pmt, result);
          if (result.video.length === 0) {
            delete result.video;
          }
          break;
        case StreamTypes.ADTS_STREAM_TYPE:
          result.audio = [];
          parseAudioPes_(bytes, pmt, result);
          if (result.audio.length === 0) {
            delete result.audio;
          }
          break;
        default:
          break;
      }
    }
  }
  return result;
};

/**
 * Inspects segment byte data and returns an object with start and end timing information
 *
 * @param {Uint8Array} bytes The segment byte data
 * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
 *  timestamps for rollover. This value must be in 90khz clock.
 * @return {Object} Object containing start and end frame timing info of segment.
 */
var inspect = function(bytes, baseTimestamp) {
  var isAacData = probe.aac.isLikelyAacData(bytes);

  var result;

  if (isAacData) {
    result = inspectAac_(bytes);
  } else {
    result = inspectTs_(bytes);
  }

  if (!result || (!result.audio && !result.video)) {
    return null;
  }

  adjustTimestamp_(result, baseTimestamp);

  return result;
};

module.exports = {
  inspect: inspect,
  parseAudioPes_: parseAudioPes_
};

},{"2":2,"20":20,"21":21,"22":22,"47":47}],46:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
var toUnsigned = function(value) {
  return value >>> 0;
};

var toHexString = function(value) {
  return ('00' + value.toString(16)).slice(-2);
};

module.exports = {
  toUnsigned: toUnsigned,
  toHexString: toHexString
};

},{}],47:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
var
  ONE_SECOND_IN_TS = 90000, // 90kHz clock
  secondsToVideoTs,
  secondsToAudioTs,
  videoTsToSeconds,
  audioTsToSeconds,
  audioTsToVideoTs,
  videoTsToAudioTs,
  metadataTsToSeconds;

secondsToVideoTs = function(seconds) {
  return seconds * ONE_SECOND_IN_TS;
};

secondsToAudioTs = function(seconds, sampleRate) {
  return seconds * sampleRate;
};

videoTsToSeconds = function(timestamp) {
  return timestamp / ONE_SECOND_IN_TS;
};

audioTsToSeconds = function(timestamp, sampleRate) {
  return timestamp / sampleRate;
};

audioTsToVideoTs = function(timestamp, sampleRate) {
  return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
};

videoTsToAudioTs = function(timestamp, sampleRate) {
  return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
};

/**
 * Adjust ID3 tag or caption timing information by the timeline pts values
 * (if keepOriginalTimestamps is false) and convert to seconds
 */
metadataTsToSeconds = function(timestamp, timelineStartPts, keepOriginalTimestamps) {
  return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
};

module.exports = {
  ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  secondsToVideoTs: secondsToVideoTs,
  secondsToAudioTs: secondsToAudioTs,
  videoTsToSeconds: videoTsToSeconds,
  audioTsToSeconds: audioTsToSeconds,
  audioTsToVideoTs: audioTsToVideoTs,
  videoTsToAudioTs: videoTsToAudioTs,
  metadataTsToSeconds: metadataTsToSeconds
};

},{}],48:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 */
'use strict';

var ExpGolomb;

/**
 * Parser for exponential Golomb codes, a variable-bitwidth number encoding
 * scheme used by h264.
 */
ExpGolomb = function(workingData) {
  var
    // the number of bytes left to examine in workingData
    workingBytesAvailable = workingData.byteLength,

    // the current word being examined
    workingWord = 0, // :uint

    // the number of bits left to examine in the current word
    workingBitsAvailable = 0; // :uint;

  // ():uint
  this.length = function() {
    return (8 * workingBytesAvailable);
  };

  // ():uint
  this.bitsAvailable = function() {
    return (8 * workingBytesAvailable) + workingBitsAvailable;
  };

  // ():void
  this.loadWord = function() {
    var
      position = workingData.byteLength - workingBytesAvailable,
      workingBytes = new Uint8Array(4),
      availableBytes = Math.min(4, workingBytesAvailable);

    if (availableBytes === 0) {
      throw new Error('no bytes available');
    }

    workingBytes.set(workingData.subarray(position,
                                          position + availableBytes));
    workingWord = new DataView(workingBytes.buffer).getUint32(0);

    // track the amount of workingData that has been processed
    workingBitsAvailable = availableBytes * 8;
    workingBytesAvailable -= availableBytes;
  };

  // (count:int):void
  this.skipBits = function(count) {
    var skipBytes; // :int
    if (workingBitsAvailable > count) {
      workingWord          <<= count;
      workingBitsAvailable -= count;
    } else {
      count -= workingBitsAvailable;
      skipBytes = Math.floor(count / 8);

      count -= (skipBytes * 8);
      workingBytesAvailable -= skipBytes;

      this.loadWord();

      workingWord <<= count;
      workingBitsAvailable -= count;
    }
  };

  // (size:int):uint
  this.readBits = function(size) {
    var
      bits = Math.min(workingBitsAvailable, size), // :uint
      valu = workingWord >>> (32 - bits); // :uint
    // if size > 31, handle error
    workingBitsAvailable -= bits;
    if (workingBitsAvailable > 0) {
      workingWord <<= bits;
    } else if (workingBytesAvailable > 0) {
      this.loadWord();
    }

    bits = size - bits;
    if (bits > 0) {
      return valu << bits | this.readBits(bits);
    }
    return valu;
  };

  // ():uint
  this.skipLeadingZeros = function() {
    var leadingZeroCount; // :uint
    for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
      if ((workingWord & (0x80000000 >>> leadingZeroCount)) !== 0) {
        // the first bit of working word is 1
        workingWord <<= leadingZeroCount;
        workingBitsAvailable -= leadingZeroCount;
        return leadingZeroCount;
      }
    }

    // we exhausted workingWord and still have not found a 1
    this.loadWord();
    return leadingZeroCount + this.skipLeadingZeros();
  };

  // ():void
  this.skipUnsignedExpGolomb = function() {
    this.skipBits(1 + this.skipLeadingZeros());
  };

  // ():void
  this.skipExpGolomb = function() {
    this.skipBits(1 + this.skipLeadingZeros());
  };

  // ():uint
  this.readUnsignedExpGolomb = function() {
    var clz = this.skipLeadingZeros(); // :uint
    return this.readBits(clz + 1) - 1;
  };

  // ():int
  this.readExpGolomb = function() {
    var valu = this.readUnsignedExpGolomb(); // :int
    if (0x01 & valu) {
      // the number is odd if the low order bit is set
      return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
    }
    return -1 * (valu >>> 1); // divide by two then make it negative
  };

  // Some convenience functions
  // :Boolean
  this.readBoolean = function() {
    return this.readBits(1) === 1;
  };

  // ():int
  this.readUnsignedByte = function() {
    return this.readBits(8);
  };

  this.loadWord();
};

module.exports = ExpGolomb;

},{}],49:[function(require,module,exports){
/**
 * mux.js
 *
 * Copyright (c) Brightcove
 * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
 *
 * A lightweight readable stream implemention that handles event dispatching.
 * Objects that inherit from streams should call init in their constructors.
 */
'use strict';

var Stream = function() {
  this.init = function() {
    var listeners = {};
    /**
     * Add a listener for a specified event type.
     * @param type {string} the event name
     * @param listener {function} the callback to be invoked when an event of
     * the specified type occurs
     */
    this.on = function(type, listener) {
      if (!listeners[type]) {
        listeners[type] = [];
      }
      listeners[type] = listeners[type].concat(listener);
    };
    /**
     * Remove a listener for a specified event type.
     * @param type {string} the event name
     * @param listener {function} a function previously registered for this
     * type of event through `on`
     */
    this.off = function(type, listener) {
      var index;
      if (!listeners[type]) {
        return false;
      }
      index = listeners[type].indexOf(listener);
      listeners[type] = listeners[type].slice();
      listeners[type].splice(index, 1);
      return index > -1;
    };
    /**
     * Trigger an event of the specified type on this stream. Any additional
     * arguments to this function are passed as parameters to event listeners.
     * @param type {string} the event name
     */
    this.trigger = function(type) {
      var callbacks, i, length, args;
      callbacks = listeners[type];
      if (!callbacks) {
        return;
      }
      // Slicing the arguments on every invocation of this method
      // can add a significant amount of overhead. Avoid the
      // intermediate object creation for the common case of a
      // single callback argument
      if (arguments.length === 2) {
        length = callbacks.length;
        for (i = 0; i < length; ++i) {
          callbacks[i].call(this, arguments[1]);
        }
      } else {
        args = [];
        i = arguments.length;
        for (i = 1; i < arguments.length; ++i) {
          args.push(arguments[i]);
        }
        length = callbacks.length;
        for (i = 0; i < length; ++i) {
          callbacks[i].apply(this, args);
        }
      }
    };
    /**
     * Destroys the stream and cleans up.
     */
    this.dispose = function() {
      listeners = {};
    };
  };
};

/**
 * Forwards all `data` events on this stream to the destination stream. The
 * destination stream should provide a method `push` to receive the data
 * events as they arrive.
 * @param destination {stream} the stream that will receive all `data` events
 * @param autoFlush {boolean} if false, we will not call `flush` on the destination
 *                            when the current stream emits a 'done' event
 * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
 */
Stream.prototype.pipe = function(destination) {
  this.on('data', function(data) {
    destination.push(data);
  });

  this.on('done', function(flushSource) {
    destination.flush(flushSource);
  });

  this.on('partialdone', function(flushSource) {
    destination.partialFlush(flushSource);
  });

  this.on('endedtimeline', function(flushSource) {
    destination.endTimeline(flushSource);
  });

  this.on('reset', function(flushSource) {
    destination.reset(flushSource);
  });

  return destination;
};

// Default stream functions that are expected to be overridden to perform
// actual work. These are provided by the prototype as a sort of no-op
// implementation so that we don't have to check for their existence in the
// `pipe` function above.
Stream.prototype.push = function(data) {
  this.trigger('data', data);
};

Stream.prototype.flush = function(flushSource) {
  this.trigger('done', flushSource);
};

Stream.prototype.partialFlush = function(flushSource) {
  this.trigger('partialdone', flushSource);
};

Stream.prototype.endTimeline = function(flushSource) {
  this.trigger('endedtimeline', flushSource);
};

Stream.prototype.reset = function(flushSource) {
  this.trigger('reset', flushSource);
};

module.exports = Stream;

},{}]},{},[15])(15)
});
var _fakeGlobal={};var exportTo={};
/*
 @license
 Shaka Player
 Copyright 2016 Google LLC
 SPDX-License-Identifier: Apache-2.0
*/
(function(){var innerGlobal=typeof window!="undefined"?window:global;(function(window,global,module){/*

 Copyright The Closure Library Authors.
 SPDX-License-Identifier: Apache-2.0
*/
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.arrayIteratorImpl=function(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}};$jscomp.arrayIterator=function(a){return{next:$jscomp.arrayIteratorImpl(a)}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};$jscomp.getGlobal=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(a,b){var c=$jscomp.propertyToPolyfillSymbol[b];if(null==c)return a[b];c=a[c];return void 0!==c?c:a[b]};
$jscomp.polyfill=function(a,b,c,d){b&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(a,b,c,d):$jscomp.polyfillUnisolated(a,b,c,d))};$jscomp.polyfillUnisolated=function(a,b,c,d){c=$jscomp.global;a=a.split(".");for(d=0;d<a.length-1;d++){var e=a[d];if(!(e in c))return;c=c[e]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:b})};
$jscomp.polyfillIsolated=function(a,b,c,d){var e=a.split(".");a=1===e.length;d=e[0];d=!a&&d in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var f=0;f<e.length-1;f++){var g=e[f];if(!(g in d))return;d=d[g]}e=e[e.length-1];c=$jscomp.IS_SYMBOL_NATIVE&&"es6"===c?d[e]:null;b=b(c);null!=b&&(a?$jscomp.defineProperty($jscomp.polyfills,e,{configurable:!0,writable:!0,value:b}):b!==c&&(void 0===$jscomp.propertyToPolyfillSymbol[e]&&(c=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[e]=$jscomp.IS_SYMBOL_NATIVE?
$jscomp.global.Symbol(e):$jscomp.POLYFILL_PREFIX+c+"$"+e),$jscomp.defineProperty(d,$jscomp.propertyToPolyfillSymbol[e],{configurable:!0,writable:!0,value:b})))};$jscomp.initSymbol=function(){};
$jscomp.polyfill("Symbol",function(a){if(a)return a;var b=function(f,g){this.$jscomp$symbol$id_=f;$jscomp.defineProperty(this,"description",{configurable:!0,writable:!0,value:g})};b.prototype.toString=function(){return this.$jscomp$symbol$id_};var c="jscomp_symbol_"+(1E9*Math.random()>>>0)+"_",d=0,e=function(f){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new b(c+(f||"")+"_"+d++,f)};return e},"es6","es3");
$jscomp.polyfill("Symbol.iterator",function(a){if(a)return a;a=Symbol("Symbol.iterator");for(var b="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),c=0;c<b.length;c++){var d=$jscomp.global[b[c]];"function"===typeof d&&"function"!=typeof d.prototype[a]&&$jscomp.defineProperty(d.prototype,a,{configurable:!0,writable:!0,value:function(){return $jscomp.iteratorPrototype($jscomp.arrayIteratorImpl(this))}})}return a},"es6",
"es3");$jscomp.iteratorPrototype=function(a){a={next:a};a[Symbol.iterator]=function(){return this};return a};$jscomp.createTemplateTagFirstArg=function(a){return a.raw=a};$jscomp.createTemplateTagFirstArgWithRaw=function(a,b){a.raw=b;return a};$jscomp.makeIterator=function(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):$jscomp.arrayIterator(a)};$jscomp.arrayFromIterator=function(a){for(var b,c=[];!(b=a.next()).done;)c.push(b.value);return c};
$jscomp.arrayFromIterable=function(a){return a instanceof Array?a:$jscomp.arrayFromIterator($jscomp.makeIterator(a))};$jscomp.objectCreate=$jscomp.ASSUME_ES5||"function"==typeof Object.create?Object.create:function(a){var b=function(){};b.prototype=a;return new b};
$jscomp.getConstructImplementation=function(){function a(){function c(){}new c;Reflect.construct(c,[],function(){});return new c instanceof c}if($jscomp.TRUST_ES6_POLYFILLS&&"undefined"!=typeof Reflect&&Reflect.construct){if(a())return Reflect.construct;var b=Reflect.construct;return function(c,d,e){c=b(c,d);e&&Reflect.setPrototypeOf(c,e.prototype);return c}}return function(c,d,e){void 0===e&&(e=c);e=$jscomp.objectCreate(e.prototype||Object.prototype);return Function.prototype.apply.call(c,e,d)||
e}};$jscomp.construct={valueOf:$jscomp.getConstructImplementation}.valueOf();$jscomp.underscoreProtoCanBeSet=function(){var a={a:!0},b={};try{return b.__proto__=a,b.a}catch(c){}return!1};$jscomp.setPrototypeOf=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.setPrototypeOf?Object.setPrototypeOf:$jscomp.underscoreProtoCanBeSet()?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null;
$jscomp.inherits=function(a,b){a.prototype=$jscomp.objectCreate(b.prototype);a.prototype.constructor=a;if($jscomp.setPrototypeOf){var c=$jscomp.setPrototypeOf;c(a,b)}else for(c in b)if("prototype"!=c)if(Object.defineProperties){var d=Object.getOwnPropertyDescriptor(b,c);d&&Object.defineProperty(a,c,d)}else a[c]=b[c];a.superClass_=b.prototype};$jscomp.generator={};
$jscomp.generator.ensureIteratorResultIsObject_=function(a){if(!(a instanceof Object))throw new TypeError("Iterator result "+a+" is not an object");};$jscomp.generator.Context=function(){this.isRunning_=!1;this.yieldAllIterator_=null;this.yieldResult=void 0;this.nextAddress=1;this.finallyAddress_=this.catchAddress_=0;this.finallyContexts_=this.abruptCompletion_=null};
$jscomp.generator.Context.prototype.start_=function(){if(this.isRunning_)throw new TypeError("Generator is already running");this.isRunning_=!0};$jscomp.generator.Context.prototype.stop_=function(){this.isRunning_=!1};$jscomp.generator.Context.prototype.jumpToErrorHandler_=function(){this.nextAddress=this.catchAddress_||this.finallyAddress_};$jscomp.generator.Context.prototype.next_=function(a){this.yieldResult=a};
$jscomp.generator.Context.prototype.throw_=function(a){this.abruptCompletion_={exception:a,isException:!0};this.jumpToErrorHandler_()};$jscomp.generator.Context.prototype.return=function(a){this.abruptCompletion_={return:a};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.jumpThroughFinallyBlocks=function(a){this.abruptCompletion_={jumpTo:a};this.nextAddress=this.finallyAddress_};$jscomp.generator.Context.prototype.yield=function(a,b){this.nextAddress=b;return{value:a}};
$jscomp.generator.Context.prototype.yieldAll=function(a,b){a=$jscomp.makeIterator(a);var c=a.next();$jscomp.generator.ensureIteratorResultIsObject_(c);if(c.done)this.yieldResult=c.value,this.nextAddress=b;else return this.yieldAllIterator_=a,this.yield(c.value,b)};$jscomp.generator.Context.prototype.jumpTo=function(a){this.nextAddress=a};$jscomp.generator.Context.prototype.jumpToEnd=function(){this.nextAddress=0};
$jscomp.generator.Context.prototype.setCatchFinallyBlocks=function(a,b){this.catchAddress_=a;void 0!=b&&(this.finallyAddress_=b)};$jscomp.generator.Context.prototype.setFinallyBlock=function(a){this.catchAddress_=0;this.finallyAddress_=a||0};$jscomp.generator.Context.prototype.leaveTryBlock=function(a,b){this.nextAddress=a;this.catchAddress_=b||0};
$jscomp.generator.Context.prototype.enterCatchBlock=function(a){this.catchAddress_=a||0;a=this.abruptCompletion_.exception;this.abruptCompletion_=null;return a};$jscomp.generator.Context.prototype.enterFinallyBlock=function(a,b,c){c?this.finallyContexts_[c]=this.abruptCompletion_:this.finallyContexts_=[this.abruptCompletion_];this.catchAddress_=a||0;this.finallyAddress_=b||0};
$jscomp.generator.Context.prototype.leaveFinallyBlock=function(a,b){b=this.finallyContexts_.splice(b||0)[0];if(b=this.abruptCompletion_=this.abruptCompletion_||b){if(b.isException)return this.jumpToErrorHandler_();void 0!=b.jumpTo&&this.finallyAddress_<b.jumpTo?(this.nextAddress=b.jumpTo,this.abruptCompletion_=null):this.nextAddress=this.finallyAddress_}else this.nextAddress=a};$jscomp.generator.Context.prototype.forIn=function(a){return new $jscomp.generator.Context.PropertyIterator(a)};
$jscomp.generator.Context.PropertyIterator=function(a){this.object_=a;this.properties_=[];for(var b in a)this.properties_.push(b);this.properties_.reverse()};$jscomp.generator.Context.PropertyIterator.prototype.getNext=function(){for(;0<this.properties_.length;){var a=this.properties_.pop();if(a in this.object_)return a}return null};$jscomp.generator.Engine_=function(a){this.context_=new $jscomp.generator.Context;this.program_=a};
$jscomp.generator.Engine_.prototype.next_=function(a){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_.next,a,this.context_.next_);this.context_.next_(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.return_=function(a){this.context_.start_();var b=this.context_.yieldAllIterator_;if(b)return this.yieldAllStep_("return"in b?b["return"]:function(c){return{value:c,done:!0}},a,this.context_.return);this.context_.return(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.throw_=function(a){this.context_.start_();if(this.context_.yieldAllIterator_)return this.yieldAllStep_(this.context_.yieldAllIterator_["throw"],a,this.context_.next_);this.context_.throw_(a);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.yieldAllStep_=function(a,b,c){try{var d=a.call(this.context_.yieldAllIterator_,b);$jscomp.generator.ensureIteratorResultIsObject_(d);if(!d.done)return this.context_.stop_(),d;var e=d.value}catch(f){return this.context_.yieldAllIterator_=null,this.context_.throw_(f),this.nextStep_()}this.context_.yieldAllIterator_=null;c.call(this.context_,e);return this.nextStep_()};
$jscomp.generator.Engine_.prototype.nextStep_=function(){for(;this.context_.nextAddress;)try{var a=this.program_(this.context_);if(a)return this.context_.stop_(),{value:a.value,done:!1}}catch(b){this.context_.yieldResult=void 0,this.context_.throw_(b)}this.context_.stop_();if(this.context_.abruptCompletion_){a=this.context_.abruptCompletion_;this.context_.abruptCompletion_=null;if(a.isException)throw a.exception;return{value:a.return,done:!0}}return{value:void 0,done:!0}};
$jscomp.generator.Generator_=function(a){this.next=function(b){return a.next_(b)};this.throw=function(b){return a.throw_(b)};this.return=function(b){return a.return_(b)};this[Symbol.iterator]=function(){return this}};$jscomp.generator.createGenerator=function(a,b){b=new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(b));$jscomp.setPrototypeOf&&a.prototype&&$jscomp.setPrototypeOf(b,a.prototype);return b};
$jscomp.asyncExecutePromiseGenerator=function(a){function b(d){return a.next(d)}function c(d){return a.throw(d)}return new Promise(function(d,e){function f(g){g.done?d(g.value):Promise.resolve(g.value).then(b,c).then(f,e)}f(a.next())})};$jscomp.asyncExecutePromiseGeneratorFunction=function(a){return $jscomp.asyncExecutePromiseGenerator(a())};$jscomp.asyncExecutePromiseGeneratorProgram=function(a){return $jscomp.asyncExecutePromiseGenerator(new $jscomp.generator.Generator_(new $jscomp.generator.Engine_(a)))};
$jscomp.getRestArguments=function(){for(var a=Number(this),b=[],c=a;c<arguments.length;c++)b[c-a]=arguments[c];return b};$jscomp.polyfill("Reflect",function(a){return a?a:{}},"es6","es3");$jscomp.polyfill("Reflect.construct",function(a){return $jscomp.construct},"es6","es3");$jscomp.polyfill("Reflect.setPrototypeOf",function(a){if(a)return a;if($jscomp.setPrototypeOf){var b=$jscomp.setPrototypeOf;return function(c,d){try{return b(c,d),!0}catch(e){return!1}}}return null},"es6","es5");
$jscomp.polyfill("Promise",function(a){function b(){this.batch_=null}function c(g){return g instanceof e?g:new e(function(h,k){h(g)})}if(a&&(!($jscomp.FORCE_POLYFILL_PROMISE||$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION&&"undefined"===typeof $jscomp.global.PromiseRejectionEvent)||!$jscomp.global.Promise||-1===$jscomp.global.Promise.toString().indexOf("[native code]")))return a;b.prototype.asyncExecute=function(g){if(null==this.batch_){this.batch_=[];var h=this;this.asyncExecuteFunction(function(){h.executeBatch_()})}this.batch_.push(g)};
var d=$jscomp.global.setTimeout;b.prototype.asyncExecuteFunction=function(g){d(g,0)};b.prototype.executeBatch_=function(){for(;this.batch_&&this.batch_.length;){var g=this.batch_;this.batch_=[];for(var h=0;h<g.length;++h){var k=g[h];g[h]=null;try{k()}catch(l){this.asyncThrow_(l)}}}this.batch_=null};b.prototype.asyncThrow_=function(g){this.asyncExecuteFunction(function(){throw g;})};var e=function(g){this.state_=0;this.result_=void 0;this.onSettledCallbacks_=[];this.isRejectionHandled_=!1;var h=this.createResolveAndReject_();
try{g(h.resolve,h.reject)}catch(k){h.reject(k)}};e.prototype.createResolveAndReject_=function(){function g(l){return function(m){k||(k=!0,l.call(h,m))}}var h=this,k=!1;return{resolve:g(this.resolveTo_),reject:g(this.reject_)}};e.prototype.resolveTo_=function(g){if(g===this)this.reject_(new TypeError("A Promise cannot resolve to itself"));else if(g instanceof e)this.settleSameAsPromise_(g);else{a:switch(typeof g){case "object":var h=null!=g;break a;case "function":h=!0;break a;default:h=!1}h?this.resolveToNonPromiseObj_(g):
this.fulfill_(g)}};e.prototype.resolveToNonPromiseObj_=function(g){var h=void 0;try{h=g.then}catch(k){this.reject_(k);return}"function"==typeof h?this.settleSameAsThenable_(h,g):this.fulfill_(g)};e.prototype.reject_=function(g){this.settle_(2,g)};e.prototype.fulfill_=function(g){this.settle_(1,g)};e.prototype.settle_=function(g,h){if(0!=this.state_)throw Error("Cannot settle("+g+", "+h+"): Promise already settled in state"+this.state_);this.state_=g;this.result_=h;2===this.state_&&this.scheduleUnhandledRejectionCheck_();
this.executeOnSettledCallbacks_()};e.prototype.scheduleUnhandledRejectionCheck_=function(){var g=this;d(function(){if(g.notifyUnhandledRejection_()){var h=$jscomp.global.console;"undefined"!==typeof h&&h.error(g.result_)}},1)};e.prototype.notifyUnhandledRejection_=function(){if(this.isRejectionHandled_)return!1;var g=$jscomp.global.CustomEvent,h=$jscomp.global.Event,k=$jscomp.global.dispatchEvent;if("undefined"===typeof k)return!0;"function"===typeof g?g=new g("unhandledrejection",{cancelable:!0}):
"function"===typeof h?g=new h("unhandledrejection",{cancelable:!0}):(g=$jscomp.global.document.createEvent("CustomEvent"),g.initCustomEvent("unhandledrejection",!1,!0,g));g.promise=this;g.reason=this.result_;return k(g)};e.prototype.executeOnSettledCallbacks_=function(){if(null!=this.onSettledCallbacks_){for(var g=0;g<this.onSettledCallbacks_.length;++g)f.asyncExecute(this.onSettledCallbacks_[g]);this.onSettledCallbacks_=null}};var f=new b;e.prototype.settleSameAsPromise_=function(g){var h=this.createResolveAndReject_();
g.callWhenSettled_(h.resolve,h.reject)};e.prototype.settleSameAsThenable_=function(g,h){var k=this.createResolveAndReject_();try{g.call(h,k.resolve,k.reject)}catch(l){k.reject(l)}};e.prototype.then=function(g,h){function k(p,q){return"function"==typeof p?function(r){try{l(p(r))}catch(w){m(w)}}:q}var l,m,n=new e(function(p,q){l=p;m=q});this.callWhenSettled_(k(g,l),k(h,m));return n};e.prototype.catch=function(g){return this.then(void 0,g)};e.prototype.callWhenSettled_=function(g,h){function k(){switch(l.state_){case 1:g(l.result_);
break;case 2:h(l.result_);break;default:throw Error("Unexpected state: "+l.state_);}}var l=this;null==this.onSettledCallbacks_?f.asyncExecute(k):this.onSettledCallbacks_.push(k);this.isRejectionHandled_=!0};e.resolve=c;e.reject=function(g){return new e(function(h,k){k(g)})};e.race=function(g){return new e(function(h,k){for(var l=$jscomp.makeIterator(g),m=l.next();!m.done;m=l.next())c(m.value).callWhenSettled_(h,k)})};e.all=function(g){var h=$jscomp.makeIterator(g),k=h.next();return k.done?c([]):new e(function(l,
m){function n(r){return function(w){p[r]=w;q--;0==q&&l(p)}}var p=[],q=0;do p.push(void 0),q++,c(k.value).callWhenSettled_(n(p.length-1),m),k=h.next();while(!k.done)})};return e},"es6","es3");$jscomp.checkEs6ConformanceViaProxy=function(){try{var a={},b=Object.create(new $jscomp.global.Proxy(a,{get:function(c,d,e){return c==a&&"q"==d&&e==b}}));return!0===b.q}catch(c){return!1}};$jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS=!1;$jscomp.ES6_CONFORMANCE=$jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS&&$jscomp.checkEs6ConformanceViaProxy();
$jscomp.owns=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};
$jscomp.polyfill("WeakMap",function(a){function b(){if(!a||!Object.seal)return!1;try{var l=Object.seal({}),m=Object.seal({}),n=new a([[l,2],[m,3]]);if(2!=n.get(l)||3!=n.get(m))return!1;n.delete(l);n.set(m,4);return!n.has(l)&&4==n.get(m)}catch(p){return!1}}function c(){}function d(l){var m=typeof l;return"object"===m&&null!==l||"function"===m}function e(l){if(!$jscomp.owns(l,g)){var m=new c;$jscomp.defineProperty(l,g,{value:m})}}function f(l){if(!$jscomp.ISOLATE_POLYFILLS){var m=Object[l];m&&(Object[l]=
function(n){if(n instanceof c)return n;Object.isExtensible(n)&&e(n);return m(n)})}}if($jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS){if(a&&$jscomp.ES6_CONFORMANCE)return a}else if(b())return a;var g="$jscomp_hidden_"+Math.random();f("freeze");f("preventExtensions");f("seal");var h=0,k=function(l){this.id_=(h+=Math.random()+1).toString();if(l){l=$jscomp.makeIterator(l);for(var m;!(m=l.next()).done;)m=m.value,this.set(m[0],m[1])}};k.prototype.set=function(l,m){if(!d(l))throw Error("Invalid WeakMap key");
e(l);if(!$jscomp.owns(l,g))throw Error("WeakMap key fail: "+l);l[g][this.id_]=m;return this};k.prototype.get=function(l){return d(l)&&$jscomp.owns(l,g)?l[g][this.id_]:void 0};k.prototype.has=function(l){return d(l)&&$jscomp.owns(l,g)&&$jscomp.owns(l[g],this.id_)};k.prototype.delete=function(l){return d(l)&&$jscomp.owns(l,g)&&$jscomp.owns(l[g],this.id_)?delete l[g][this.id_]:!1};return k},"es6","es3");$jscomp.MapEntry=function(){};
$jscomp.polyfill("Map",function(a){function b(){if($jscomp.ASSUME_NO_NATIVE_MAP||!a||"function"!=typeof a||!a.prototype.entries||"function"!=typeof Object.seal)return!1;try{var k=Object.seal({x:4}),l=new a($jscomp.makeIterator([[k,"s"]]));if("s"!=l.get(k)||1!=l.size||l.get({x:4})||l.set({x:4},"t")!=l||2!=l.size)return!1;var m=l.entries(),n=m.next();if(n.done||n.value[0]!=k||"s"!=n.value[1])return!1;n=m.next();return n.done||4!=n.value[0].x||"t"!=n.value[1]||!m.next().done?!1:!0}catch(p){return!1}}
if($jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS){if(a&&$jscomp.ES6_CONFORMANCE)return a}else if(b())return a;var c=new WeakMap,d=function(k){this.data_={};this.head_=g();this.size=0;if(k){k=$jscomp.makeIterator(k);for(var l;!(l=k.next()).done;)l=l.value,this.set(l[0],l[1])}};d.prototype.set=function(k,l){k=0===k?0:k;var m=e(this,k);m.list||(m.list=this.data_[m.id]=[]);m.entry?m.entry.value=l:(m.entry={next:this.head_,previous:this.head_.previous,head:this.head_,key:k,value:l},m.list.push(m.entry),
this.head_.previous.next=m.entry,this.head_.previous=m.entry,this.size++);return this};d.prototype.delete=function(k){k=e(this,k);return k.entry&&k.list?(k.list.splice(k.index,1),k.list.length||delete this.data_[k.id],k.entry.previous.next=k.entry.next,k.entry.next.previous=k.entry.previous,k.entry.head=null,this.size--,!0):!1};d.prototype.clear=function(){this.data_={};this.head_=this.head_.previous=g();this.size=0};d.prototype.has=function(k){return!!e(this,k).entry};d.prototype.get=function(k){return(k=
e(this,k).entry)&&k.value};d.prototype.entries=function(){return f(this,function(k){return[k.key,k.value]})};d.prototype.keys=function(){return f(this,function(k){return k.key})};d.prototype.values=function(){return f(this,function(k){return k.value})};d.prototype.forEach=function(k,l){for(var m=this.entries(),n;!(n=m.next()).done;)n=n.value,k.call(l,n[1],n[0],this)};d.prototype[Symbol.iterator]=d.prototype.entries;var e=function(k,l){var m=l&&typeof l;"object"==m||"function"==m?c.has(l)?m=c.get(l):
(m=""+ ++h,c.set(l,m)):m="p_"+l;var n=k.data_[m];if(n&&$jscomp.owns(k.data_,m))for(k=0;k<n.length;k++){var p=n[k];if(l!==l&&p.key!==p.key||l===p.key)return{id:m,list:n,index:k,entry:p}}return{id:m,list:n,index:-1,entry:void 0}},f=function(k,l){var m=k.head_;return $jscomp.iteratorPrototype(function(){if(m){for(;m.head!=k.head_;)m=m.previous;for(;m.next!=m.head;)return m=m.next,{done:!1,value:l(m)};m=null}return{done:!0,value:void 0}})},g=function(){var k={};return k.previous=k.next=k.head=k},h=0;
return d},"es6","es3");
$jscomp.polyfill("Set",function(a){function b(){if($jscomp.ASSUME_NO_NATIVE_SET||!a||"function"!=typeof a||!a.prototype.entries||"function"!=typeof Object.seal)return!1;try{var d=Object.seal({x:4}),e=new a($jscomp.makeIterator([d]));if(!e.has(d)||1!=e.size||e.add(d)!=e||1!=e.size||e.add({x:4})!=e||2!=e.size)return!1;var f=e.entries(),g=f.next();if(g.done||g.value[0]!=d||g.value[1]!=d)return!1;g=f.next();return g.done||g.value[0]==d||4!=g.value[0].x||g.value[1]!=g.value[0]?!1:f.next().done}catch(h){return!1}}
if($jscomp.USE_PROXY_FOR_ES6_CONFORMANCE_CHECKS){if(a&&$jscomp.ES6_CONFORMANCE)return a}else if(b())return a;var c=function(d){this.map_=new Map;if(d){d=$jscomp.makeIterator(d);for(var e;!(e=d.next()).done;)this.add(e.value)}this.size=this.map_.size};c.prototype.add=function(d){d=0===d?0:d;this.map_.set(d,d);this.size=this.map_.size;return this};c.prototype.delete=function(d){d=this.map_.delete(d);this.size=this.map_.size;return d};c.prototype.clear=function(){this.map_.clear();this.size=0};c.prototype.has=
function(d){return this.map_.has(d)};c.prototype.entries=function(){return this.map_.entries()};c.prototype.values=function(){return this.map_.values()};c.prototype.keys=c.prototype.values;c.prototype[Symbol.iterator]=c.prototype.values;c.prototype.forEach=function(d,e){var f=this;this.map_.forEach(function(g){return d.call(e,g,g,f)})};return c},"es6","es3");
$jscomp.findInternal=function(a,b,c){a instanceof String&&(a=String(a));for(var d=a.length,e=0;e<d;e++){var f=a[e];if(b.call(c,f,e,a))return{i:e,v:f}}return{i:-1,v:void 0}};$jscomp.polyfill("Array.prototype.findIndex",function(a){return a?a:function(b,c){return $jscomp.findInternal(this,b,c).i}},"es6","es3");$jscomp.polyfill("Object.is",function(a){return a?a:function(b,c){return b===c?0!==b||1/b===1/c:b!==b&&c!==c}},"es6","es3");
$jscomp.polyfill("Array.prototype.includes",function(a){return a?a:function(b,c){var d=this;d instanceof String&&(d=String(d));var e=d.length;c=c||0;for(0>c&&(c=Math.max(c+e,0));c<e;c++){var f=d[c];if(f===b||Object.is(f,b))return!0}return!1}},"es7","es3");
$jscomp.checkStringArgs=function(a,b,c){if(null==a)throw new TypeError("The 'this' value for String.prototype."+c+" must not be null or undefined");if(b instanceof RegExp)throw new TypeError("First argument to String.prototype."+c+" must not be a regular expression");return a+""};$jscomp.polyfill("String.prototype.includes",function(a){return a?a:function(b,c){return-1!==$jscomp.checkStringArgs(this,b,"includes").indexOf(b,c||0)}},"es6","es3");
$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(b,c){return $jscomp.findInternal(this,b,c).v}},"es6","es3");$jscomp.polyfill("String.prototype.startsWith",function(a){return a?a:function(b,c){var d=$jscomp.checkStringArgs(this,b,"startsWith");b+="";var e=d.length,f=b.length;c=Math.max(0,Math.min(c|0,d.length));for(var g=0;g<f&&c<e;)if(d[c++]!=b[g++])return!1;return g>=f}},"es6","es3");
$jscomp.iteratorFromArray=function(a,b){a instanceof String&&(a+="");var c=0,d=!1,e={next:function(){if(!d&&c<a.length){var f=c++;return{value:b(f,a[f]),done:!1}}d=!0;return{done:!0,value:void 0}}};e[Symbol.iterator]=function(){return e};return e};$jscomp.polyfill("Array.prototype.keys",function(a){return a?a:function(){return $jscomp.iteratorFromArray(this,function(b){return b})}},"es6","es3");
$jscomp.assign=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.assign?Object.assign:function(a,b){for(var c=1;c<arguments.length;c++){var d=arguments[c];if(d)for(var e in d)$jscomp.owns(d,e)&&(a[e]=d[e])}return a};$jscomp.polyfill("Object.assign",function(a){return a||$jscomp.assign},"es6","es3");
$jscomp.polyfill("Array.from",function(a){return a?a:function(b,c,d){c=null!=c?c:function(h){return h};var e=[],f="undefined"!=typeof Symbol&&Symbol.iterator&&b[Symbol.iterator];if("function"==typeof f){b=f.call(b);for(var g=0;!(f=b.next()).done;)e.push(c.call(d,f.value,g++))}else for(f=b.length,g=0;g<f;g++)e.push(c.call(d,b[g],g));return e}},"es6","es3");
$jscomp.polyfill("Array.prototype.values",function(a){return a?a:function(){return $jscomp.iteratorFromArray(this,function(b,c){return c})}},"es8","es3");$jscomp.polyfill("Promise.prototype.finally",function(a){return a?a:function(b){return this.then(function(c){return Promise.resolve(b()).then(function(){return c})},function(c){return Promise.resolve(b()).then(function(){throw c;})})}},"es9","es3");
$jscomp.polyfill("Array.prototype.entries",function(a){return a?a:function(){return $jscomp.iteratorFromArray(this,function(b,c){return[b,c]})}},"es6","es3");$jscomp.polyfill("String.prototype.repeat",function(a){return a?a:function(b){var c=$jscomp.checkStringArgs(this,null,"repeat");if(0>b||1342177279<b)throw new RangeError("Invalid count value");b|=0;for(var d="";b;)if(b&1&&(d+=c),b>>>=1)c+=c;return d}},"es6","es3");
$jscomp.polyfill("Number.isNaN",function(a){return a?a:function(b){return"number"===typeof b&&isNaN(b)}},"es6","es3");$jscomp.polyfill("Object.values",function(a){return a?a:function(b){var c=[],d;for(d in b)$jscomp.owns(b,d)&&c.push(b[d]);return c}},"es8","es3");$jscomp.polyfill("Math.log2",function(a){return a?a:function(b){return Math.log(b)/Math.LN2}},"es6","es3");
$jscomp.polyfill("Math.trunc",function(a){return a?a:function(b){b=Number(b);if(isNaN(b)||Infinity===b||-Infinity===b||0===b)return b;var c=Math.floor(Math.abs(b));return 0>b?-c:c}},"es6","es3");$jscomp.polyfill("Object.entries",function(a){return a?a:function(b){var c=[],d;for(d in b)$jscomp.owns(b,d)&&c.push([d,b[d]]);return c}},"es8","es3");var COMPILED=!0,goog=goog||{};goog.global=this||self;
goog.exportPath_=function(a,b,c,d){a=a.split(".");d=d||goog.global;a[0]in d||"undefined"==typeof d.execScript||d.execScript("var "+a[0]);for(var e;a.length&&(e=a.shift());)if(a.length||void 0===b)d=d[e]&&d[e]!==Object.prototype[e]?d[e]:d[e]={};else if(!c&&goog.isObject(b)&&goog.isObject(d[e]))for(var f in b)b.hasOwnProperty(f)&&(d[e][f]=b[f]);else d[e]=b};
goog.define=function(a,b){if(!COMPILED){var c=goog.global.CLOSURE_UNCOMPILED_DEFINES,d=goog.global.CLOSURE_DEFINES;c&&void 0===c.nodeType&&Object.prototype.hasOwnProperty.call(c,a)?b=c[a]:d&&void 0===d.nodeType&&Object.prototype.hasOwnProperty.call(d,a)&&(b=d[a])}return b};goog.FEATURESET_YEAR=2012;goog.DEBUG=!0;goog.LOCALE="en";goog.getLocale=function(){return goog.LOCALE};goog.TRUSTED_SITE=!0;goog.DISALLOW_TEST_ONLY_CODE=COMPILED&&!goog.DEBUG;goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING=!1;
goog.provide=function(a){if(goog.isInModuleLoader_())throw Error("goog.provide cannot be used within a module.");if(!COMPILED&&goog.isProvided_(a))throw Error('Namespace "'+a+'" already declared.');goog.constructNamespace_(a)};goog.constructNamespace_=function(a,b,c){if(!COMPILED){delete goog.implicitNamespaces_[a];for(var d=a;(d=d.substring(0,d.lastIndexOf(".")))&&!goog.getObjectByName(d);)goog.implicitNamespaces_[d]=!0}goog.exportPath_(a,b,c)};goog.NONCE_PATTERN_=/^[\w+/_-]+[=]{0,2}$/;
goog.getScriptNonce_=function(a){a=(a||goog.global).document;return(a=a.querySelector&&a.querySelector("script[nonce]"))&&(a=a.nonce||a.getAttribute("nonce"))&&goog.NONCE_PATTERN_.test(a)?a:""};goog.VALID_MODULE_RE_=/^[a-zA-Z_$][a-zA-Z0-9._$]*$/;
goog.module=function(a){if("string"!==typeof a||!a||-1==a.search(goog.VALID_MODULE_RE_))throw Error("Invalid module identifier");if(!goog.isInGoogModuleLoader_())throw Error("Module "+a+" has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");if(goog.moduleLoaderState_.moduleName)throw Error("goog.module may only be called once per module.");
goog.moduleLoaderState_.moduleName=a;if(!COMPILED){if(goog.isProvided_(a))throw Error('Namespace "'+a+'" already declared.');delete goog.implicitNamespaces_[a]}};goog.module.get=function(a){return goog.module.getInternal_(a)};goog.module.getInternal_=function(a){if(!COMPILED){if(a in goog.loadedModules_)return goog.loadedModules_[a].exports;if(!goog.implicitNamespaces_[a])return a=goog.getObjectByName(a),null!=a?a:null}return null};goog.ModuleType={ES6:"es6",GOOG:"goog"};goog.moduleLoaderState_=null;
goog.isInModuleLoader_=function(){return goog.isInGoogModuleLoader_()||goog.isInEs6ModuleLoader_()};goog.isInGoogModuleLoader_=function(){return!!goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.GOOG};goog.isInEs6ModuleLoader_=function(){if(goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.ES6)return!0;var a=goog.global.$jscomp;return a?"function"!=typeof a.getCurrentModulePath?!1:!!a.getCurrentModulePath():!1};
goog.module.declareLegacyNamespace=function(){if(!COMPILED&&!goog.isInGoogModuleLoader_())throw Error("goog.module.declareLegacyNamespace must be called from within a goog.module");if(!COMPILED&&!goog.moduleLoaderState_.moduleName)throw Error("goog.module must be called prior to goog.module.declareLegacyNamespace.");goog.moduleLoaderState_.declareLegacyNamespace=!0};
goog.declareModuleId=function(a){if(!COMPILED){if(!goog.isInEs6ModuleLoader_())throw Error("goog.declareModuleId may only be called from within an ES6 module");if(goog.moduleLoaderState_&&goog.moduleLoaderState_.moduleName)throw Error("goog.declareModuleId may only be called once per module.");if(a in goog.loadedModules_)throw Error('Module with namespace "'+a+'" already exists.');}if(goog.moduleLoaderState_)goog.moduleLoaderState_.moduleName=a;else{var b=goog.global.$jscomp;if(!b||"function"!=typeof b.getCurrentModulePath)throw Error('Module with namespace "'+
a+'" has been loaded incorrectly.');b=b.require(b.getCurrentModulePath());goog.loadedModules_[a]={exports:b,type:goog.ModuleType.ES6,moduleId:a}}};goog.setTestOnly=function(a){if(goog.DISALLOW_TEST_ONLY_CODE)throw a=a||"",Error("Importing test-only code into non-debug environment"+(a?": "+a:"."));};goog.forwardDeclare=function(a){};COMPILED||(goog.isProvided_=function(a){return a in goog.loadedModules_||!goog.implicitNamespaces_[a]&&null!=goog.getObjectByName(a)},goog.implicitNamespaces_={"goog.module":!0});
goog.getObjectByName=function(a,b){a=a.split(".");b=b||goog.global;for(var c=0;c<a.length;c++)if(b=b[a[c]],null==b)return null;return b};goog.addDependency=function(a,b,c,d){!COMPILED&&goog.DEPENDENCIES_ENABLED&&goog.debugLoader_.addDependency(a,b,c,d)};goog.ENABLE_DEBUG_LOADER=!1;goog.logToConsole_=function(a){goog.global.console&&goog.global.console.error(a)};
goog.require=function(a){if(!COMPILED){goog.ENABLE_DEBUG_LOADER&&goog.debugLoader_.requested(a);if(goog.isProvided_(a)){if(goog.isInModuleLoader_())return goog.module.getInternal_(a)}else if(goog.ENABLE_DEBUG_LOADER){var b=goog.moduleLoaderState_;goog.moduleLoaderState_=null;try{goog.debugLoader_.load_(a)}finally{goog.moduleLoaderState_=b}}return null}};goog.requireType=function(a){return{}};goog.basePath="";goog.abstractMethod=function(){throw Error("unimplemented abstract method");};
goog.addSingletonGetter=function(a){a.instance_=void 0;a.getInstance=function(){if(a.instance_)return a.instance_;goog.DEBUG&&(goog.instantiatedSingletons_[goog.instantiatedSingletons_.length]=a);return a.instance_=new a}};goog.instantiatedSingletons_=[];goog.LOAD_MODULE_USING_EVAL=!0;goog.SEAL_MODULE_EXPORTS=goog.DEBUG;goog.loadedModules_={};goog.DEPENDENCIES_ENABLED=!COMPILED&&goog.ENABLE_DEBUG_LOADER;goog.TRANSPILE="detect";goog.ASSUME_ES_MODULES_TRANSPILED=!1;goog.TRUSTED_TYPES_POLICY_NAME="goog";
goog.hasBadLetScoping=null;
goog.loadModule=function(a){var b=goog.moduleLoaderState_;try{goog.moduleLoaderState_={moduleName:"",declareLegacyNamespace:!1,type:goog.ModuleType.GOOG};var c={},d=c;if("function"===typeof a)d=a.call(void 0,d);else if("string"===typeof a)d=goog.loadModuleFromSource_.call(void 0,d,a);else throw Error("Invalid module definition");var e=goog.moduleLoaderState_.moduleName;if("string"===typeof e&&e)goog.moduleLoaderState_.declareLegacyNamespace?goog.constructNamespace_(e,d,c!==d):goog.SEAL_MODULE_EXPORTS&&
Object.seal&&"object"==typeof d&&null!=d&&Object.seal(d),goog.loadedModules_[e]={exports:d,type:goog.ModuleType.GOOG,moduleId:goog.moduleLoaderState_.moduleName};else throw Error('Invalid module name "'+e+'"');}finally{goog.moduleLoaderState_=b}};goog.loadModuleFromSource_=function(a,b){eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(b));return a};goog.normalizePath_=function(a){a=a.split("/");for(var b=0;b<a.length;)"."==a[b]?a.splice(b,1):b&&".."==a[b]&&a[b-1]&&".."!=a[b-1]?a.splice(--b,2):b++;return a.join("/")};
goog.loadFileSync_=function(a){if(goog.global.CLOSURE_LOAD_FILE_SYNC)return goog.global.CLOSURE_LOAD_FILE_SYNC(a);try{var b=new XMLHttpRequest;b.open("get",a,!1);b.send();return 0==b.status||200==b.status?b.responseText:null}catch(c){return null}};goog.typeOf=function(a){var b=typeof a;return"object"!=b?b:a?Array.isArray(a)?"array":b:"null"};goog.isArrayLike=function(a){var b=goog.typeOf(a);return"array"==b||"object"==b&&"number"==typeof a.length};
goog.isDateLike=function(a){return goog.isObject(a)&&"function"==typeof a.getFullYear};goog.isObject=function(a){var b=typeof a;return"object"==b&&null!=a||"function"==b};goog.getUid=function(a){return Object.prototype.hasOwnProperty.call(a,goog.UID_PROPERTY_)&&a[goog.UID_PROPERTY_]||(a[goog.UID_PROPERTY_]=++goog.uidCounter_)};goog.hasUid=function(a){return!!a[goog.UID_PROPERTY_]};goog.removeUid=function(a){null!==a&&"removeAttribute"in a&&a.removeAttribute(goog.UID_PROPERTY_);try{delete a[goog.UID_PROPERTY_]}catch(b){}};
goog.UID_PROPERTY_="closure_uid_"+(1E9*Math.random()>>>0);goog.uidCounter_=0;goog.cloneObject=function(a){var b=goog.typeOf(a);if("object"==b||"array"==b){if("function"===typeof a.clone)return a.clone();if("undefined"!==typeof Map&&a instanceof Map)return new Map(a);if("undefined"!==typeof Set&&a instanceof Set)return new Set(a);b="array"==b?[]:{};for(var c in a)b[c]=goog.cloneObject(a[c]);return b}return a};goog.bindNative_=function(a,b,c){return a.call.apply(a.bind,arguments)};
goog.bindJs_=function(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(e,d);return a.apply(b,e)}}return function(){return a.apply(b,arguments)}};goog.bind=function(a,b,c){Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?goog.bind=goog.bindNative_:goog.bind=goog.bindJs_;return goog.bind.apply(null,arguments)};
goog.partial=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var d=c.slice();d.push.apply(d,arguments);return a.apply(this,d)}};goog.now=function(){return Date.now()};goog.globalEval=function(a){(0,eval)(a)};
goog.getCssName=function(a,b){if("."==String(a).charAt(0))throw Error('className passed in goog.getCssName must not start with ".". You passed: '+a);var c=function(e){return goog.cssNameMapping_[e]||e},d=function(e){e=e.split("-");for(var f=[],g=0;g<e.length;g++)f.push(c(e[g]));return f.join("-")};d=goog.cssNameMapping_?"BY_WHOLE"==goog.cssNameMappingStyle_?c:d:function(e){return e};a=b?a+"-"+d(b):d(a);return goog.global.CLOSURE_CSS_NAME_MAP_FN?goog.global.CLOSURE_CSS_NAME_MAP_FN(a):a};
goog.setCssNameMapping=function(a,b){goog.cssNameMapping_=a;goog.cssNameMappingStyle_=b};!COMPILED&&goog.global.CLOSURE_CSS_NAME_MAPPING&&(goog.cssNameMapping_=goog.global.CLOSURE_CSS_NAME_MAPPING);goog.GetMsgOptions=function(){};
goog.getMsg=function(a,b,c){c&&c.html&&(a=a.replace(/</g,"&lt;"));c&&c.unescapeHtmlEntities&&(a=a.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&amp;/g,"&"));b&&(a=a.replace(/\{\$([^}]+)}/g,function(d,e){return null!=b&&e in b?b[e]:d}));return a};goog.getMsgWithFallback=function(a,b){return a};goog.exportSymbol=function(a,b,c){goog.exportPath_(a,b,!0,c)};goog.exportProperty=function(a,b,c){a[b]=c};
goog.inherits=function(a,b){function c(){}c.prototype=b.prototype;a.superClass_=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.base=function(d,e,f){for(var g=Array(arguments.length-2),h=2;h<arguments.length;h++)g[h-2]=arguments[h];return b.prototype[e].apply(d,g)}};goog.scope=function(a){if(goog.isInModuleLoader_())throw Error("goog.scope is not supported within a module.");a.call(goog.global)};COMPILED||(goog.global.COMPILED=COMPILED);
goog.defineClass=function(a,b){var c=b.constructor,d=b.statics;c&&c!=Object.prototype.constructor||(c=function(){throw Error("cannot instantiate an interface (no constructor defined).");});c=goog.defineClass.createSealingConstructor_(c,a);a&&goog.inherits(c,a);delete b.constructor;delete b.statics;goog.defineClass.applyProperties_(c.prototype,b);null!=d&&(d instanceof Function?d(c):goog.defineClass.applyProperties_(c,d));return c};goog.defineClass.SEAL_CLASS_INSTANCES=goog.DEBUG;
goog.defineClass.createSealingConstructor_=function(a,b){return goog.defineClass.SEAL_CLASS_INSTANCES?function(){var c=a.apply(this,arguments)||this;c[goog.UID_PROPERTY_]=c[goog.UID_PROPERTY_];return c}:a};goog.defineClass.OBJECT_PROTOTYPE_FIELDS_="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
goog.defineClass.applyProperties_=function(a,b){for(var c in b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c]);for(var d=0;d<goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length;d++)c=goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[d],Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c])};goog.identity_=function(a){return a};
goog.createTrustedTypesPolicy=function(a){var b=null,c=goog.global.trustedTypes;if(!c||!c.createPolicy)return b;try{b=c.createPolicy(a,{createHTML:goog.identity_,createScript:goog.identity_,createScriptURL:goog.identity_})}catch(d){goog.logToConsole_(d.message)}return b};
!COMPILED&&goog.DEPENDENCIES_ENABLED&&(goog.isEdge_=function(){return!!(goog.global.navigator&&goog.global.navigator.userAgent?goog.global.navigator.userAgent:"").match(/Edge\/(\d+)(\.\d)*/i)},goog.inHtmlDocument_=function(){var a=goog.global.document;return null!=a&&"write"in a},goog.isDocumentLoading_=function(){var a=goog.global.document;return a.attachEvent?"complete"!=a.readyState:"loading"==a.readyState},goog.findBasePath_=function(){if(void 0!=goog.global.CLOSURE_BASE_PATH&&"string"===typeof goog.global.CLOSURE_BASE_PATH)goog.basePath=
goog.global.CLOSURE_BASE_PATH;else if(goog.inHtmlDocument_()){var a=goog.global.document,b=a.currentScript;a=b?[b]:a.getElementsByTagName("SCRIPT");for(b=a.length-1;0<=b;--b){var c=a[b].src,d=c.lastIndexOf("?");d=-1==d?c.length:d;if("base.js"==c.slice(d-7,d)){goog.basePath=c.slice(0,d-7);break}}}},goog.findBasePath_(),goog.protectScriptTag_=function(a){return a.replace(/<\/(SCRIPT)/ig,"\\x3c/$1")},goog.DebugLoader_=function(){this.dependencies_={};this.idToPath_={};this.written_={};this.loadingDeps_=
[];this.depsToLoad_=[];this.paused_=!1;this.factory_=new goog.DependencyFactory;this.deferredCallbacks_={};this.deferredQueue_=[]},goog.DebugLoader_.prototype.bootstrap=function(a,b){function c(){d&&(goog.global.setTimeout(d,0),d=null)}var d=b;if(a.length){b=[];for(var e=0;e<a.length;e++){var f=this.getPathFromDeps_(a[e]);if(!f)throw Error("Unregonized namespace: "+a[e]);b.push(this.dependencies_[f])}f=goog.require;var g=0;for(e=0;e<a.length;e++)f(a[e]),b[e].onLoad(function(){++g==a.length&&c()})}else c()},
goog.DebugLoader_.prototype.loadClosureDeps=function(){this.depsToLoad_.push(this.factory_.createDependency(goog.normalizePath_(goog.basePath+"deps.js"),"deps.js",[],[],{}));this.loadDeps_()},goog.DebugLoader_.prototype.requested=function(a,b){(a=this.getPathFromDeps_(a))&&(b||this.areDepsLoaded_(this.dependencies_[a].requires))&&(b=this.deferredCallbacks_[a])&&(delete this.deferredCallbacks_[a],b())},goog.DebugLoader_.prototype.setDependencyFactory=function(a){this.factory_=a},goog.DebugLoader_.prototype.load_=
function(a){if(this.getPathFromDeps_(a)){var b=this,c=[],d=function(e){var f=b.getPathFromDeps_(e);if(!f)throw Error("Bad dependency path or symbol: "+e);if(!b.written_[f]){b.written_[f]=!0;e=b.dependencies_[f];for(f=0;f<e.requires.length;f++)goog.isProvided_(e.requires[f])||d(e.requires[f]);c.push(e)}};d(a);a=!!this.depsToLoad_.length;this.depsToLoad_=this.depsToLoad_.concat(c);this.paused_||a||this.loadDeps_()}else goog.logToConsole_("goog.require could not find: "+a)},goog.DebugLoader_.prototype.loadDeps_=
function(){for(var a=this,b=this.paused_;this.depsToLoad_.length&&!b;)(function(){var c=!1,d=a.depsToLoad_.shift(),e=!1;a.loading_(d);var f={pause:function(){if(c)throw Error("Cannot call pause after the call to load.");b=!0},resume:function(){c?a.resume_():b=!1},loaded:function(){if(e)throw Error("Double call to loaded.");e=!0;a.loaded_(d)},pending:function(){for(var g=[],h=0;h<a.loadingDeps_.length;h++)g.push(a.loadingDeps_[h]);return g},setModuleState:function(g){goog.moduleLoaderState_={type:g,
moduleName:"",declareLegacyNamespace:!1}},registerEs6ModuleExports:function(g,h,k){k&&(goog.loadedModules_[k]={exports:h,type:goog.ModuleType.ES6,moduleId:k||""})},registerGoogModuleExports:function(g,h){goog.loadedModules_[g]={exports:h,type:goog.ModuleType.GOOG,moduleId:g}},clearModuleState:function(){goog.moduleLoaderState_=null},defer:function(g){if(c)throw Error("Cannot register with defer after the call to load.");a.defer_(d,g)},areDepsLoaded:function(){return a.areDepsLoaded_(d.requires)}};
try{d.load(f)}finally{c=!0}})();b&&this.pause_()},goog.DebugLoader_.prototype.pause_=function(){this.paused_=!0},goog.DebugLoader_.prototype.resume_=function(){this.paused_&&(this.paused_=!1,this.loadDeps_())},goog.DebugLoader_.prototype.loading_=function(a){this.loadingDeps_.push(a)},goog.DebugLoader_.prototype.loaded_=function(a){for(var b=0;b<this.loadingDeps_.length;b++)if(this.loadingDeps_[b]==a){this.loadingDeps_.splice(b,1);break}for(b=0;b<this.deferredQueue_.length;b++)if(this.deferredQueue_[b]==
a.path){this.deferredQueue_.splice(b,1);break}if(this.loadingDeps_.length==this.deferredQueue_.length&&!this.depsToLoad_.length)for(;this.deferredQueue_.length;)this.requested(this.deferredQueue_.shift(),!0);a.loaded()},goog.DebugLoader_.prototype.areDepsLoaded_=function(a){for(var b=0;b<a.length;b++){var c=this.getPathFromDeps_(a[b]);if(!c||!(c in this.deferredCallbacks_||goog.isProvided_(a[b])))return!1}return!0},goog.DebugLoader_.prototype.getPathFromDeps_=function(a){return a in this.idToPath_?
this.idToPath_[a]:a in this.dependencies_?a:null},goog.DebugLoader_.prototype.defer_=function(a,b){this.deferredCallbacks_[a.path]=b;this.deferredQueue_.push(a.path)},goog.LoadController=function(){},goog.LoadController.prototype.pause=function(){},goog.LoadController.prototype.resume=function(){},goog.LoadController.prototype.loaded=function(){},goog.LoadController.prototype.pending=function(){},goog.LoadController.prototype.registerEs6ModuleExports=function(a,b,c){},goog.LoadController.prototype.setModuleState=
function(a){},goog.LoadController.prototype.clearModuleState=function(){},goog.LoadController.prototype.defer=function(a){},goog.LoadController.prototype.areDepsLoaded=function(){},goog.Dependency=function(a,b,c,d,e){this.path=a;this.relativePath=b;this.provides=c;this.requires=d;this.loadFlags=e;this.loaded_=!1;this.loadCallbacks_=[]},goog.Dependency.prototype.getPathName=function(){var a=this.path,b=a.indexOf("://");0<=b&&(a=a.substring(b+3),b=a.indexOf("/"),0<=b&&(a=a.substring(b+1)));return a},
goog.Dependency.prototype.onLoad=function(a){this.loaded_?a():this.loadCallbacks_.push(a)},goog.Dependency.prototype.loaded=function(){this.loaded_=!0;var a=this.loadCallbacks_;this.loadCallbacks_=[];for(var b=0;b<a.length;b++)a[b]()},goog.Dependency.defer_=!1,goog.Dependency.callbackMap_={},goog.Dependency.registerCallback_=function(a){var b=Math.random().toString(32);goog.Dependency.callbackMap_[b]=a;return b},goog.Dependency.unregisterCallback_=function(a){delete goog.Dependency.callbackMap_[a]},
goog.Dependency.callback_=function(a,b){if(a in goog.Dependency.callbackMap_){for(var c=goog.Dependency.callbackMap_[a],d=[],e=1;e<arguments.length;e++)d.push(arguments[e]);c.apply(void 0,d)}else throw Error("Callback key "+a+" does not exist (was base.js loaded more than once?).");},goog.Dependency.prototype.load=function(a){if(goog.global.CLOSURE_IMPORT_SCRIPT)goog.global.CLOSURE_IMPORT_SCRIPT(this.path)?a.loaded():a.pause();else if(goog.inHtmlDocument_()){var b=goog.global.document;if("complete"==
b.readyState&&!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING){if(/\bdeps.js$/.test(this.path)){a.loaded();return}throw Error('Cannot write "'+this.path+'" after document load');}var c=goog.getScriptNonce_();if(!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING&&goog.isDocumentLoading_()){var d=function(h){h.readyState&&"complete"!=h.readyState?h.onload=d:(goog.Dependency.unregisterCallback_(e),a.loaded())};var e=goog.Dependency.registerCallback_(d);c=c?' nonce="'+c+'"':"";var f='<script src="'+this.path+'"'+
c+(goog.Dependency.defer_?" defer":"")+' id="script-'+e+'">\x3c/script>';f+="<script"+c+">";f=goog.Dependency.defer_?f+("document.getElementById('script-"+e+"').onload = function() {\n  goog.Dependency.callback_('"+e+"', this);\n};\n"):f+("goog.Dependency.callback_('"+e+"', document.getElementById('script-"+e+"'));");f+="\x3c/script>";b.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(f):f)}else{var g=b.createElement("script");g.defer=goog.Dependency.defer_;g.async=!1;c&&(g.nonce=
c);g.onload=function(){g.onload=null;a.loaded()};g.src=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path):this.path;b.head.appendChild(g)}}else goog.logToConsole_("Cannot use default debug loader outside of HTML documents."),"deps.js"==this.relativePath?(goog.logToConsole_("Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, or setting CLOSURE_NO_DEPS to true."),a.loaded()):a.pause()},goog.Es6ModuleDependency=function(a,b,c,d,e){goog.Dependency.call(this,a,
b,c,d,e)},goog.inherits(goog.Es6ModuleDependency,goog.Dependency),goog.Es6ModuleDependency.prototype.load=function(a){function b(l,m){var n="",p=goog.getScriptNonce_();p&&(n=' nonce="'+p+'"');l=m?'<script type="module" crossorigin'+n+">"+m+"\x3c/script>":'<script type="module" crossorigin src="'+l+'"'+n+">\x3c/script>";d.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(l):l)}function c(l,m){var n=d.createElement("script");n.defer=!0;n.async=!1;n.type="module";n.setAttribute("crossorigin",
!0);var p=goog.getScriptNonce_();p&&(n.nonce=p);m?n.text=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScript(m):m:n.src=goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createScriptURL(l):l;d.head.appendChild(n)}if(goog.global.CLOSURE_IMPORT_SCRIPT)goog.global.CLOSURE_IMPORT_SCRIPT(this.path)?a.loaded():a.pause();else if(goog.inHtmlDocument_()){var d=goog.global.document,e=this;if(goog.isDocumentLoading_()){var f=b;goog.Dependency.defer_=!0}else f=c;var g=goog.Dependency.registerCallback_(function(){goog.Dependency.unregisterCallback_(g);
a.setModuleState(goog.ModuleType.ES6)});f(void 0,'goog.Dependency.callback_("'+g+'")');f(this.path,void 0);var h=goog.Dependency.registerCallback_(function(l){goog.Dependency.unregisterCallback_(h);a.registerEs6ModuleExports(e.path,l,goog.moduleLoaderState_.moduleName)});f(void 0,'import * as m from "'+this.path+'"; goog.Dependency.callback_("'+h+'", m)');var k=goog.Dependency.registerCallback_(function(){goog.Dependency.unregisterCallback_(k);a.clearModuleState();a.loaded()});f(void 0,'goog.Dependency.callback_("'+
k+'")')}else goog.logToConsole_("Cannot use default debug loader outside of HTML documents."),a.pause()},goog.TransformedDependency=function(a,b,c,d,e){goog.Dependency.call(this,a,b,c,d,e);this.contents_=null;this.lazyFetch_=!goog.inHtmlDocument_()||!("noModule"in goog.global.document.createElement("script"))},goog.inherits(goog.TransformedDependency,goog.Dependency),goog.TransformedDependency.prototype.load=function(a){function b(){e.contents_=goog.loadFileSync_(e.path);e.contents_&&(e.contents_=
e.transform(e.contents_),e.contents_&&(e.contents_+="\n//# sourceURL="+e.path))}function c(){e.lazyFetch_&&b();if(e.contents_){f&&a.setModuleState(goog.ModuleType.ES6);try{var l=e.contents_;e.contents_=null;goog.globalEval(goog.CLOSURE_EVAL_PREFILTER_.createScript(l));if(f)var m=goog.moduleLoaderState_.moduleName}finally{f&&a.clearModuleState()}f&&goog.global.$jscomp.require.ensure([e.getPathName()],function(){a.registerEs6ModuleExports(e.path,goog.global.$jscomp.require(e.getPathName()),m)});a.loaded()}}
function d(){var l=goog.global.document,m=goog.Dependency.registerCallback_(function(){goog.Dependency.unregisterCallback_(m);c()}),n=goog.getScriptNonce_();n="<script"+(n?' nonce="'+n+'"':"")+">"+goog.protectScriptTag_('goog.Dependency.callback_("'+m+'");')+"\x3c/script>";l.write(goog.TRUSTED_TYPES_POLICY_?goog.TRUSTED_TYPES_POLICY_.createHTML(n):n)}var e=this;if(goog.global.CLOSURE_IMPORT_SCRIPT)b(),this.contents_&&goog.global.CLOSURE_IMPORT_SCRIPT("",this.contents_)?(this.contents_=null,a.loaded()):
a.pause();else{var f=this.loadFlags.module==goog.ModuleType.ES6;this.lazyFetch_||b();var g=1<a.pending().length;if(goog.Dependency.defer_&&(g||goog.isDocumentLoading_()))a.defer(function(){c()});else{var h=goog.global.document;g=goog.inHtmlDocument_()&&("ActiveXObject"in goog.global||goog.isEdge_());if(f&&goog.inHtmlDocument_()&&goog.isDocumentLoading_()&&!g){goog.Dependency.defer_=!0;a.pause();var k=h.onreadystatechange;h.onreadystatechange=function(){"interactive"==h.readyState&&(h.onreadystatechange=
k,c(),a.resume());"function"===typeof k&&k.apply(void 0,arguments)}}else goog.inHtmlDocument_()&&goog.isDocumentLoading_()?d():c()}}},goog.TransformedDependency.prototype.transform=function(a){},goog.PreTranspiledEs6ModuleDependency=function(a,b,c,d,e){goog.TransformedDependency.call(this,a,b,c,d,e)},goog.inherits(goog.PreTranspiledEs6ModuleDependency,goog.TransformedDependency),goog.PreTranspiledEs6ModuleDependency.prototype.transform=function(a){return a},goog.GoogModuleDependency=function(a,b,
c,d,e){goog.TransformedDependency.call(this,a,b,c,d,e)},goog.inherits(goog.GoogModuleDependency,goog.TransformedDependency),goog.GoogModuleDependency.prototype.transform=function(a){return goog.LOAD_MODULE_USING_EVAL&&void 0!==goog.global.JSON?"goog.loadModule("+goog.global.JSON.stringify(a+"\n//# sourceURL="+this.path+"\n")+");":'goog.loadModule(function(exports) {"use strict";'+a+"\n;return exports});\n//# sourceURL="+this.path+"\n"},goog.DebugLoader_.prototype.addDependency=function(a,b,c,d){b=
b||[];a=a.replace(/\\/g,"/");var e=goog.normalizePath_(goog.basePath+a);d&&"boolean"!==typeof d||(d=d?{module:goog.ModuleType.GOOG}:{});c=this.factory_.createDependency(e,a,b,c,d);this.dependencies_[e]=c;for(c=0;c<b.length;c++)this.idToPath_[b[c]]=e;this.idToPath_[a]=e},goog.DependencyFactory=function(){},goog.DependencyFactory.prototype.createDependency=function(a,b,c,d,e){return e.module==goog.ModuleType.GOOG?new goog.GoogModuleDependency(a,b,c,d,e):e.module==goog.ModuleType.ES6?goog.ASSUME_ES_MODULES_TRANSPILED?
new goog.PreTranspiledEs6ModuleDependency(a,b,c,d,e):new goog.Es6ModuleDependency(a,b,c,d,e):new goog.Dependency(a,b,c,d,e)},goog.debugLoader_=new goog.DebugLoader_,goog.loadClosureDeps=function(){goog.debugLoader_.loadClosureDeps()},goog.setDependencyFactory=function(a){goog.debugLoader_.setDependencyFactory(a)},goog.TRUSTED_TYPES_POLICY_=goog.TRUSTED_TYPES_POLICY_NAME?goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME+"#base"):null,goog.global.CLOSURE_NO_DEPS||goog.debugLoader_.loadClosureDeps(),
goog.bootstrap=function(a,b){goog.debugLoader_.bootstrap(a,b)});if(!COMPILED){var isChrome87=!1;try{isChrome87=eval(goog.global.trustedTypes.emptyScript)!==goog.global.trustedTypes.emptyScript}catch(a){}goog.CLOSURE_EVAL_PREFILTER_=goog.global.trustedTypes&&isChrome87&&goog.createTrustedTypesPolicy("goog#base#devonly#eval")||{createScript:goog.identity_}};/*
 @license
 Shaka Player
 Copyright 2016 Google LLC
 SPDX-License-Identifier: Apache-2.0
*/
goog.asserts=function(){};goog.asserts.assert=function(a,b){};goog.asserts.ENABLE_ASSERTS=!0;goog.asserts.ENABLE_ASSERTS&&console.assert&&console.assert.bind&&(goog.asserts.assert=console.assert.bind(console));var shaka={abr:{}};shaka.abr.Ewma=function(a){goog.asserts.assert(0<a,"expected halfLife to be positive");this.alpha_=Math.exp(Math.log(.5)/a);this.totalWeight_=this.estimate_=0};shaka.abr.Ewma.prototype.updateAlpha=function(a){goog.asserts.assert(0<a,"expected halfLife to be positive");this.alpha_=Math.exp(Math.log(.5)/a)};shaka.abr.Ewma.prototype.sample=function(a,b){var c=Math.pow(this.alpha_,a);b=b*(1-c)+c*this.estimate_;isNaN(b)||(this.estimate_=b,this.totalWeight_+=a)};
shaka.abr.Ewma.prototype.getEstimate=function(){return this.estimate_/(1-Math.pow(this.alpha_,this.totalWeight_))};shaka.abr.EwmaBandwidthEstimator=function(){this.fast_=new shaka.abr.Ewma(2);this.slow_=new shaka.abr.Ewma(5);this.bytesSampled_=0;this.minTotalBytes_=128E3;this.minBytes_=16E3};shaka.abr.EwmaBandwidthEstimator.prototype.configure=function(a){this.minTotalBytes_=a.minTotalBytes;this.minBytes_=a.minBytes;this.fast_.updateAlpha(a.fastHalfLife);this.slow_.updateAlpha(a.slowHalfLife)};
shaka.abr.EwmaBandwidthEstimator.prototype.sample=function(a,b){if(!(b<this.minBytes_)){var c=8E3*b/a;a/=1E3;this.bytesSampled_+=b;this.fast_.sample(a,c);this.slow_.sample(a,c)}};shaka.abr.EwmaBandwidthEstimator.prototype.getBandwidthEstimate=function(a){return this.bytesSampled_<this.minTotalBytes_?a:Math.min(this.fast_.getEstimate(),this.slow_.getEstimate())};shaka.abr.EwmaBandwidthEstimator.prototype.hasGoodEstimate=function(){return this.bytesSampled_>=this.minTotalBytes_};shaka.log=function(){};shaka.log.alwaysError=function(){};shaka.log.alwaysWarn=function(){};shaka.log.warnOnce=function(a){var b=$jscomp.getRestArguments.apply(1,arguments);shaka.log.oneTimeWarningIssued_.has(a)||(shaka.log.oneTimeWarningIssued_.add(a),shaka.log.alwaysWarn.apply(shaka.log,$jscomp.arrayFromIterable(b)))};shaka.log.error=function(){};shaka.log.warning=function(){};shaka.log.info=function(){};shaka.log.debug=function(){};shaka.log.v1=function(){};shaka.log.v2=function(){};
shaka.log.Level={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4,V1:5,V2:6};shaka.log.MAX_LOG_LEVEL=4;shaka.log.oneTimeWarningIssued_=new Set;
if(window.console&&window.console.log.bind){var $jscomp$compprop0={};shaka.log.logMap_=($jscomp$compprop0[shaka.log.Level.ERROR]=console.error.bind(console),$jscomp$compprop0[shaka.log.Level.WARNING]=console.warn.bind(console),$jscomp$compprop0[shaka.log.Level.INFO]=console.info.bind(console),$jscomp$compprop0[shaka.log.Level.DEBUG]=console.log.bind(console),$jscomp$compprop0[shaka.log.Level.V1]=console.debug.bind(console),$jscomp$compprop0[shaka.log.Level.V2]=console.debug.bind(console),$jscomp$compprop0);
shaka.log.alwaysWarn=shaka.log.logMap_[shaka.log.Level.WARNING];shaka.log.alwaysError=shaka.log.logMap_[shaka.log.Level.ERROR];goog.DEBUG?(goog.exportSymbol("shaka.log",shaka.log),shaka.log.setLevel=function(a){var b=function(c){return c<=a?(goog.asserts.assert(shaka.log.logMap_[c],"Unexpected log level"),shaka.log.logMap_[c]):function(){}};shaka.log.currentLevel=a;shaka.log.error=b(shaka.log.Level.ERROR);shaka.log.warning=b(shaka.log.Level.WARNING);shaka.log.info=b(shaka.log.Level.INFO);shaka.log.debug=
b(shaka.log.Level.DEBUG);shaka.log.v1=b(shaka.log.Level.V1);shaka.log.v2=b(shaka.log.Level.V2)},shaka.log.setLevel(shaka.log.MAX_LOG_LEVEL)):(shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.ERROR&&(shaka.log.error=shaka.log.logMap_[shaka.log.Level.ERROR]),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.WARNING&&(shaka.log.warning=shaka.log.logMap_[shaka.log.Level.WARNING]),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.INFO&&(shaka.log.info=shaka.log.logMap_[shaka.log.Level.INFO]),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.DEBUG&&
(shaka.log.debug=shaka.log.logMap_[shaka.log.Level.DEBUG]),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.V1&&(shaka.log.v1=shaka.log.logMap_[shaka.log.Level.V1]),shaka.log.MAX_LOG_LEVEL>=shaka.log.Level.V2&&(shaka.log.v2=shaka.log.logMap_[shaka.log.Level.V2]))};shaka.media={};shaka.media.Capabilities=function(){};shaka.media.Capabilities.isTypeSupported=function(a){var b=shaka.media.Capabilities.MediaSourceTypeSupportMap;if(b.has(a))return b.get(a);var c=MediaSource.isTypeSupported(a);b.set(a,c);return c};shaka.media.Capabilities.MediaSourceTypeSupportMap=new Map;shaka.util={};shaka.util.ArrayUtils=function(){};shaka.util.ArrayUtils.defaultEquals=function(a,b){return"number"===typeof a&&"number"===typeof b&&isNaN(a)&&isNaN(b)?!0:a===b};shaka.util.ArrayUtils.remove=function(a,b){b=a.indexOf(b);-1<b&&a.splice(b,1)};shaka.util.ArrayUtils.count=function(a,b){var c=0;a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())c+=b(d.value)?1:0;return c};
shaka.util.ArrayUtils.hasSameElements=function(a,b,c){c||(c=shaka.util.ArrayUtils.defaultEquals);if(a.length!=b.length)return!1;b=b.slice();var d={};a=$jscomp.makeIterator(a);for(var e=a.next();!e.done;d={$jscomp$loop$prop$item$626:d.$jscomp$loop$prop$item$626},e=a.next()){d.$jscomp$loop$prop$item$626=e.value;e=b.findIndex(function(f){return function(g){return c(f.$jscomp$loop$prop$item$626,g)}}(d));if(-1==e)return!1;b[e]=b[b.length-1];b.pop()}return 0==b.length};
shaka.util.ArrayUtils.equal=function(a,b,c){c||(c=shaka.util.ArrayUtils.defaultEquals);if(a.length!=b.length)return!1;for(var d=0;d<a.length;d++)if(!c(a[d],b[d]))return!1;return!0};shaka.text={};
shaka.text.Cue=function(a,b,c){var d=shaka.text.Cue;this.startTime=a;this.direction=d.direction.HORIZONTAL_LEFT_TO_RIGHT;this.endTime=b;this.payload=c;this.region=new shaka.text.CueRegion;this.position=null;this.positionAlign=d.positionAlign.AUTO;this.size=0;this.textAlign=d.textAlign.CENTER;this.writingMode=d.writingMode.HORIZONTAL_TOP_TO_BOTTOM;this.lineInterpretation=d.lineInterpretation.LINE_NUMBER;this.line=null;this.lineHeight="";this.lineAlign=d.lineAlign.START;this.displayAlign=d.displayAlign.AFTER;
this.fontSize=this.textStrokeWidth=this.textStrokeColor=this.textShadow=this.border=this.backgroundImage=this.backgroundColor=this.color="";this.fontWeight=d.fontWeight.NORMAL;this.fontStyle=d.fontStyle.NORMAL;this.linePadding=this.letterSpacing=this.fontFamily="";this.opacity=1;this.textDecoration=[];this.wrapLine=!0;this.id="";this.nestedCues=[];this.lineBreak=this.isContainer=!1;this.cellResolution={columns:32,rows:15}};
shaka.text.Cue.lineBreak=function(a,b){a=new shaka.text.Cue(a,b,"");a.lineBreak=!0;return a};shaka.text.Cue.prototype.clone=function(){var a=new shaka.text.Cue(0,0,""),b;for(b in this)a[b]=this[b],a[b]&&a[b].constructor==Array&&(a[b]=a[b].slice());return a};
shaka.text.Cue.equal=function(a,b){if(a.startTime!=b.startTime||a.endTime!=b.endTime||a.payload!=b.payload)return!1;for(var c in a)if("startTime"!=c&&"endTime"!=c&&"payload"!=c)if("nestedCues"==c){if(!shaka.util.ArrayUtils.equal(a.nestedCues,b.nestedCues,shaka.text.Cue.equal))return!1}else if("region"==c||"cellResolution"==c)for(var d in a[c]){if(a[c][d]!=b[c][d])return!1}else if(Array.isArray(a[c])){if(!shaka.util.ArrayUtils.equal(a[c],b[c]))return!1}else if(a[c]!=b[c])return!1;return!0};
goog.exportSymbol("shaka.text.Cue",shaka.text.Cue);shaka.text.Cue.positionAlign={LEFT:"line-left",RIGHT:"line-right",CENTER:"center",AUTO:"auto"};goog.exportProperty(shaka.text.Cue,"positionAlign",shaka.text.Cue.positionAlign);shaka.text.Cue.textAlign={LEFT:"left",RIGHT:"right",CENTER:"center",START:"start",END:"end"};goog.exportProperty(shaka.text.Cue,"textAlign",shaka.text.Cue.textAlign);shaka.text.Cue.displayAlign={BEFORE:"before",CENTER:"center",AFTER:"after"};
goog.exportProperty(shaka.text.Cue,"displayAlign",shaka.text.Cue.displayAlign);shaka.text.Cue.direction={HORIZONTAL_LEFT_TO_RIGHT:"ltr",HORIZONTAL_RIGHT_TO_LEFT:"rtl"};goog.exportProperty(shaka.text.Cue,"direction",shaka.text.Cue.direction);shaka.text.Cue.writingMode={HORIZONTAL_TOP_TO_BOTTOM:"horizontal-tb",VERTICAL_LEFT_TO_RIGHT:"vertical-lr",VERTICAL_RIGHT_TO_LEFT:"vertical-rl"};goog.exportProperty(shaka.text.Cue,"writingMode",shaka.text.Cue.writingMode);
shaka.text.Cue.lineInterpretation={LINE_NUMBER:0,PERCENTAGE:1};goog.exportProperty(shaka.text.Cue,"lineInterpretation",shaka.text.Cue.lineInterpretation);shaka.text.Cue.lineAlign={CENTER:"center",START:"start",END:"end"};goog.exportProperty(shaka.text.Cue,"lineAlign",shaka.text.Cue.lineAlign);shaka.text.Cue.defaultTextColor={white:"#FFF",lime:"#0F0",cyan:"#0FF",red:"#F00",yellow:"#FF0",magenta:"#F0F",blue:"#00F",black:"#000"};goog.exportProperty(shaka.text.Cue,"defaultTextColor",shaka.text.Cue.defaultTextColor);
shaka.text.Cue.defaultTextBackgroundColor={bg_white:"#FFF",bg_lime:"#0F0",bg_cyan:"#0FF",bg_red:"#F00",bg_yellow:"#FF0",bg_magenta:"#F0F",bg_blue:"#00F",bg_black:"#000"};goog.exportProperty(shaka.text.Cue,"defaultTextBackgroundColor",shaka.text.Cue.defaultTextBackgroundColor);shaka.text.Cue.fontWeight={NORMAL:400,BOLD:700};goog.exportProperty(shaka.text.Cue,"fontWeight",shaka.text.Cue.fontWeight);shaka.text.Cue.fontStyle={NORMAL:"normal",ITALIC:"italic",OBLIQUE:"oblique"};
goog.exportProperty(shaka.text.Cue,"fontStyle",shaka.text.Cue.fontStyle);shaka.text.Cue.textDecoration={UNDERLINE:"underline",LINE_THROUGH:"lineThrough",OVERLINE:"overline"};goog.exportProperty(shaka.text.Cue,"textDecoration",shaka.text.Cue.textDecoration);
shaka.text.CueRegion=function(){var a=shaka.text.CueRegion;this.id="";this.regionAnchorY=this.regionAnchorX=this.viewportAnchorY=this.viewportAnchorX=0;this.height=this.width=100;this.viewportAnchorUnits=this.widthUnits=this.heightUnits=a.units.PERCENTAGE;this.scroll=a.scrollMode.NONE};goog.exportSymbol("shaka.text.CueRegion",shaka.text.CueRegion);shaka.text.CueRegion.units={PX:0,PERCENTAGE:1,LINES:2};goog.exportProperty(shaka.text.CueRegion,"units",shaka.text.CueRegion.units);
shaka.text.CueRegion.scrollMode={NONE:"",UP:"up"};goog.exportProperty(shaka.text.CueRegion,"scrollMode",shaka.text.CueRegion.scrollMode);shaka.util.BufferUtils=function(){};shaka.util.BufferUtils.equal=function(a,b){var c=shaka.util.BufferUtils;if(!a&&!b)return!0;if(!a||!b||a.byteLength!=b.byteLength)return!1;if(c.unsafeGetArrayBuffer_(a)==c.unsafeGetArrayBuffer_(b)&&(a.byteOffset||0)==(b.byteOffset||0))return!0;c=shaka.util.BufferUtils.toUint8(a);b=shaka.util.BufferUtils.toUint8(b);for(var d=0;d<a.byteLength;d++)if(c[d]!=b[d])return!1;return!0};
shaka.util.BufferUtils.unsafeGetArrayBuffer_=function(a){return a instanceof ArrayBuffer?a:a.buffer};shaka.util.BufferUtils.toArrayBuffer=function(a){return a instanceof ArrayBuffer?a:0==a.byteOffset&&a.byteLength==a.buffer.byteLength?a.buffer:(new Uint8Array(a)).buffer};shaka.util.BufferUtils.toUint8=function(a,b,c){c=void 0===c?Infinity:c;return shaka.util.BufferUtils.view_(a,void 0===b?0:b,c,Uint8Array)};
shaka.util.BufferUtils.toDataView=function(a,b,c){c=void 0===c?Infinity:c;return shaka.util.BufferUtils.view_(a,void 0===b?0:b,c,DataView)};shaka.util.BufferUtils.view_=function(a,b,c,d){var e=shaka.util.BufferUtils.unsafeGetArrayBuffer_(a),f=(a.byteOffset||0)+a.byteLength;a=Math.max(0,Math.min((a.byteOffset||0)+b,f));return new d(e,a,Math.min(a+Math.max(c,0),f)-a)};goog.exportSymbol("shaka.util.BufferUtils",shaka.util.BufferUtils);goog.exportProperty(shaka.util.BufferUtils,"toDataView",shaka.util.BufferUtils.toDataView);
goog.exportProperty(shaka.util.BufferUtils,"toUint8",shaka.util.BufferUtils.toUint8);goog.exportProperty(shaka.util.BufferUtils,"toArrayBuffer",shaka.util.BufferUtils.toArrayBuffer);goog.exportProperty(shaka.util.BufferUtils,"equal",shaka.util.BufferUtils.equal);shaka.util.IDestroyable=function(){};shaka.util.IDestroyable.prototype.destroy=function(){};shaka.util.Error=function(a,b,c){var d=$jscomp.getRestArguments.apply(3,arguments);this.severity=a;this.category=b;this.code=c;this.data=d;this.handled=!1;if(goog.DEBUG){var e=d="UNKNOWN",f;for(f in shaka.util.Error.Category)shaka.util.Error.Category[f]==this.category&&(d=f);for(var g in shaka.util.Error.Code)shaka.util.Error.Code[g]==this.code&&(e=g);this.message="Shaka Error "+d+"."+e+" ("+this.data.toString()+")";if(shaka.util.Error.createStack)try{throw Error(this.message);}catch(h){this.stack=
h.stack}}};shaka.util.Error.prototype.toString=function(){return"shaka.util.Error "+JSON.stringify(this,null,"  ")};goog.exportSymbol("shaka.util.Error",shaka.util.Error);goog.DEBUG&&(shaka.util.Error.createStack=!0);shaka.util.Error.Severity={RECOVERABLE:1,CRITICAL:2};goog.exportProperty(shaka.util.Error,"Severity",shaka.util.Error.Severity);shaka.util.Error.Category={NETWORK:1,TEXT:2,MEDIA:3,MANIFEST:4,STREAMING:5,DRM:6,PLAYER:7,CAST:8,STORAGE:9,ADS:10};
goog.exportProperty(shaka.util.Error,"Category",shaka.util.Error.Category);
shaka.util.Error.Code={UNSUPPORTED_SCHEME:1E3,BAD_HTTP_STATUS:1001,HTTP_ERROR:1002,TIMEOUT:1003,MALFORMED_DATA_URI:1004,REQUEST_FILTER_ERROR:1006,RESPONSE_FILTER_ERROR:1007,MALFORMED_TEST_URI:1008,UNEXPECTED_TEST_REQUEST:1009,ATTEMPTS_EXHAUSTED:1010,SEGMENT_MISSING:1011,INVALID_TEXT_HEADER:2E3,INVALID_TEXT_CUE:2001,UNABLE_TO_DETECT_ENCODING:2003,BAD_ENCODING:2004,INVALID_XML:2005,INVALID_MP4_TTML:2007,INVALID_MP4_VTT:2008,UNABLE_TO_EXTRACT_CUE_START_TIME:2009,INVALID_MP4_CEA:2010,TEXT_COULD_NOT_GUESS_MIME_TYPE:2011,
CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS:2012,TEXT_ONLY_WEBVTT_SRC_EQUALS:2013,MISSING_TEXT_PLUGIN:2014,CHAPTERS_TRACK_FAILED:2015,CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_SRC_EQUALS:2016,UNSUPPORTED_EXTERNAL_THUMBNAILS_URI:2017,BUFFER_READ_OUT_OF_BOUNDS:3E3,JS_INTEGER_OVERFLOW:3001,EBML_OVERFLOW:3002,EBML_BAD_FLOATING_POINT_SIZE:3003,MP4_SIDX_WRONG_BOX_TYPE:3004,MP4_SIDX_INVALID_TIMESCALE:3005,MP4_SIDX_TYPE_NOT_SUPPORTED:3006,WEBM_CUES_ELEMENT_MISSING:3007,WEBM_EBML_HEADER_ELEMENT_MISSING:3008,WEBM_SEGMENT_ELEMENT_MISSING:3009,
WEBM_INFO_ELEMENT_MISSING:3010,WEBM_DURATION_ELEMENT_MISSING:3011,WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING:3012,WEBM_CUE_TIME_ELEMENT_MISSING:3013,MEDIA_SOURCE_OPERATION_FAILED:3014,MEDIA_SOURCE_OPERATION_THREW:3015,VIDEO_ERROR:3016,QUOTA_EXCEEDED_ERROR:3017,TRANSMUXING_FAILED:3018,CONTENT_TRANSFORMATION_FAILED:3019,UNABLE_TO_GUESS_MANIFEST_TYPE:4E3,DASH_INVALID_XML:4001,DASH_NO_SEGMENT_INFO:4002,DASH_EMPTY_ADAPTATION_SET:4003,DASH_EMPTY_PERIOD:4004,DASH_WEBM_MISSING_INIT:4005,DASH_UNSUPPORTED_CONTAINER:4006,
DASH_PSSH_BAD_ENCODING:4007,DASH_NO_COMMON_KEY_SYSTEM:4008,DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED:4009,DASH_CONFLICTING_KEY_IDS:4010,RESTRICTIONS_CANNOT_BE_MET:4012,HLS_PLAYLIST_HEADER_MISSING:4015,INVALID_HLS_TAG:4016,HLS_INVALID_PLAYLIST_HIERARCHY:4017,DASH_DUPLICATE_REPRESENTATION_ID:4018,HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND:4020,HLS_REQUIRED_ATTRIBUTE_MISSING:4023,HLS_REQUIRED_TAG_MISSING:4024,HLS_COULD_NOT_GUESS_CODECS:4025,HLS_KEYFORMATS_NOT_SUPPORTED:4026,DASH_UNSUPPORTED_XLINK_ACTUATE:4027,
DASH_XLINK_DEPTH_LIMIT:4028,CONTENT_UNSUPPORTED_BY_BROWSER:4032,CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM:4033,NO_VARIANTS:4036,PERIOD_FLATTENING_FAILED:4037,INCONSISTENT_DRM_ACROSS_PERIODS:4038,HLS_VARIABLE_NOT_FOUND:4039,HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED:4040,HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED:4041,NO_WEB_CRYPTO_API:4042,HLS_AES_128_INVALID_IV_LENGTH:4043,HLS_AES_128_INVALID_KEY_LENGTH:4044,CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM:4045,STREAMING_ENGINE_STARTUP_INVALID_STATE:5006,
NO_RECOGNIZED_KEY_SYSTEMS:6E3,REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE:6001,FAILED_TO_CREATE_CDM:6002,FAILED_TO_ATTACH_TO_VIDEO:6003,INVALID_SERVER_CERTIFICATE:6004,FAILED_TO_CREATE_SESSION:6005,FAILED_TO_GENERATE_LICENSE_REQUEST:6006,LICENSE_REQUEST_FAILED:6007,LICENSE_RESPONSE_REJECTED:6008,ENCRYPTED_CONTENT_WITHOUT_DRM_INFO:6010,NO_LICENSE_SERVER_GIVEN:6012,OFFLINE_SESSION_REMOVED:6013,EXPIRED:6014,SERVER_CERTIFICATE_REQUIRED:6015,INIT_DATA_TRANSFORM_ERROR:6016,SERVER_CERTIFICATE_REQUEST_FAILED:6017,
LOAD_INTERRUPTED:7E3,OPERATION_ABORTED:7001,NO_VIDEO_ELEMENT:7002,OBJECT_DESTROYED:7003,CONTENT_NOT_LOADED:7004,CAST_API_UNAVAILABLE:8E3,NO_CAST_RECEIVERS:8001,ALREADY_CASTING:8002,UNEXPECTED_CAST_ERROR:8003,CAST_CANCELED_BY_USER:8004,CAST_CONNECTION_TIMED_OUT:8005,CAST_RECEIVER_APP_UNAVAILABLE:8006,STORAGE_NOT_SUPPORTED:9E3,INDEXED_DB_ERROR:9001,DEPRECATED_OPERATION_ABORTED:9002,REQUESTED_ITEM_NOT_FOUND:9003,MALFORMED_OFFLINE_URI:9004,CANNOT_STORE_LIVE_OFFLINE:9005,NO_INIT_DATA_FOR_OFFLINE:9007,
LOCAL_PLAYER_INSTANCE_REQUIRED:9008,NEW_KEY_OPERATION_NOT_SUPPORTED:9011,KEY_NOT_FOUND:9012,MISSING_STORAGE_CELL:9013,STORAGE_LIMIT_REACHED:9014,DOWNLOAD_SIZE_CALLBACK_ERROR:9015,MODIFY_OPERATION_NOT_SUPPORTED:9016,INDEXED_DB_INIT_TIMED_OUT:9017,CS_IMA_SDK_MISSING:1E4,CS_AD_MANAGER_NOT_INITIALIZED:10001,SS_IMA_SDK_MISSING:10002,SS_AD_MANAGER_NOT_INITIALIZED:10003,CURRENT_DAI_REQUEST_NOT_FINISHED:10004};goog.exportProperty(shaka.util.Error,"Code",shaka.util.Error.Code);/*
 @license
 Copyright 2008 The Closure Library Authors
 SPDX-License-Identifier: Apache-2.0
*/
goog.uri={};goog.uri.utils={};goog.uri.utils.splitRe_=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$");goog.uri.utils.ComponentIndex={SCHEME:1,USER_INFO:2,DOMAIN:3,PORT:4,PATH:5,QUERY_DATA:6,FRAGMENT:7};goog.uri.utils.split=function(a){return a.match(goog.uri.utils.splitRe_)};/*
 @license
 Copyright 2006 The Closure Library Authors
 SPDX-License-Identifier: Apache-2.0
*/
goog.Uri=function(a){var b;a instanceof goog.Uri?(this.setScheme(a.getScheme()),this.setUserInfo(a.getUserInfo()),this.setDomain(a.getDomain()),this.setPort(a.getPort()),this.setPath(a.getPath()),this.setQueryData(a.getQueryData().clone()),this.setFragment(a.getFragment())):a&&(b=goog.uri.utils.split(String(a)))?(this.setScheme(b[goog.uri.utils.ComponentIndex.SCHEME]||"",!0),this.setUserInfo(b[goog.uri.utils.ComponentIndex.USER_INFO]||"",!0),this.setDomain(b[goog.uri.utils.ComponentIndex.DOMAIN]||
"",!0),this.setPort(b[goog.uri.utils.ComponentIndex.PORT]),this.setPath(b[goog.uri.utils.ComponentIndex.PATH]||"",!0),this.setQueryData(b[goog.uri.utils.ComponentIndex.QUERY_DATA]||"",!0),this.setFragment(b[goog.uri.utils.ComponentIndex.FRAGMENT]||"",!0)):this.queryData_=new goog.Uri.QueryData(null,null)};goog.Uri.prototype.scheme_="";goog.Uri.prototype.userInfo_="";goog.Uri.prototype.domain_="";goog.Uri.prototype.port_=null;goog.Uri.prototype.path_="";goog.Uri.prototype.fragment_="";
goog.Uri.prototype.toString=function(){var a=[],b=this.getScheme();b&&a.push(goog.Uri.encodeSpecialChars_(b,goog.Uri.reDisallowedInSchemeOrUserInfo_,!0),":");if(b=this.getDomain()){a.push("//");var c=this.getUserInfo();c&&a.push(goog.Uri.encodeSpecialChars_(c,goog.Uri.reDisallowedInSchemeOrUserInfo_,!0),"@");a.push(goog.Uri.removeDoubleEncoding_(encodeURIComponent(b)));b=this.getPort();null!=b&&a.push(":",String(b))}if(b=this.getPath())this.hasDomain()&&"/"!=b.charAt(0)&&a.push("/"),a.push(goog.Uri.encodeSpecialChars_(b,
"/"==b.charAt(0)?goog.Uri.reDisallowedInAbsolutePath_:goog.Uri.reDisallowedInRelativePath_,!0));(b=this.getEncodedQuery())&&a.push("?",b);(b=this.getFragment())&&a.push("#",goog.Uri.encodeSpecialChars_(b,goog.Uri.reDisallowedInFragment_));return a.join("")};
goog.Uri.prototype.resolve=function(a){var b=this.clone();"data"===b.scheme_&&(b=new goog.Uri);var c=a.hasScheme();c?b.setScheme(a.getScheme()):c=a.hasUserInfo();c?b.setUserInfo(a.getUserInfo()):c=a.hasDomain();c?b.setDomain(a.getDomain()):c=a.hasPort();var d=a.getPath();if(c)b.setPort(a.getPort());else if(c=a.hasPath()){if("/"!=d.charAt(0))if(this.hasDomain()&&!this.hasPath())d="/"+d;else{var e=b.getPath().lastIndexOf("/");-1!=e&&(d=b.getPath().substr(0,e+1)+d)}d=goog.Uri.removeDotSegments(d)}c?
b.setPath(d):c=a.hasQuery();c?b.setQueryData(a.getQueryData().clone()):c=a.hasFragment();c&&b.setFragment(a.getFragment());return b};goog.Uri.prototype.clone=function(){return new goog.Uri(this)};goog.Uri.prototype.getScheme=function(){return this.scheme_};goog.Uri.prototype.setScheme=function(a,b){if(this.scheme_=b?goog.Uri.decodeOrEmpty_(a,!0):a)this.scheme_=this.scheme_.replace(/:$/,"");return this};goog.Uri.prototype.hasScheme=function(){return!!this.scheme_};goog.Uri.prototype.getUserInfo=function(){return this.userInfo_};
goog.Uri.prototype.setUserInfo=function(a,b){this.userInfo_=b?goog.Uri.decodeOrEmpty_(a):a;return this};goog.Uri.prototype.hasUserInfo=function(){return!!this.userInfo_};goog.Uri.prototype.getDomain=function(){return this.domain_};goog.Uri.prototype.setDomain=function(a,b){this.domain_=b?goog.Uri.decodeOrEmpty_(a,!0):a;return this};goog.Uri.prototype.hasDomain=function(){return!!this.domain_};goog.Uri.prototype.getPort=function(){return this.port_};
goog.Uri.prototype.setPort=function(a){if(a){a=Number(a);if(isNaN(a)||0>a)throw Error("Bad port number "+a);this.port_=a}else this.port_=null;return this};goog.Uri.prototype.hasPort=function(){return null!=this.port_};goog.Uri.prototype.getPath=function(){return this.path_};goog.Uri.prototype.setPath=function(a,b){this.path_=b?goog.Uri.decodeOrEmpty_(a,!0):a;return this};goog.Uri.prototype.hasPath=function(){return!!this.path_};goog.Uri.prototype.hasQuery=function(){return""!==this.queryData_.toString()};
goog.Uri.prototype.setQueryData=function(a,b){a instanceof goog.Uri.QueryData?this.queryData_=a:(b||(a=goog.Uri.encodeSpecialChars_(a,goog.Uri.reDisallowedInQuery_)),this.queryData_=new goog.Uri.QueryData(a,null));return this};goog.Uri.prototype.getEncodedQuery=function(){return this.queryData_.toString()};goog.Uri.prototype.getDecodedQuery=function(){return this.queryData_.toDecodedString()};goog.Uri.prototype.getQueryData=function(){return this.queryData_};goog.Uri.prototype.getFragment=function(){return this.fragment_};
goog.Uri.prototype.setFragment=function(a,b){this.fragment_=b?goog.Uri.decodeOrEmpty_(a):a;return this};goog.Uri.prototype.hasFragment=function(){return!!this.fragment_};
goog.Uri.removeDotSegments=function(a){if(".."==a||"."==a)return"";if(-1==a.indexOf("./")&&-1==a.indexOf("/."))return a;var b=0==a.lastIndexOf("/",0);a=a.split("/");for(var c=[],d=0;d<a.length;){var e=a[d++];"."==e?b&&d==a.length&&c.push(""):".."==e?((1<c.length||1==c.length&&""!=c[0])&&c.pop(),b&&d==a.length&&c.push("")):(c.push(e),b=!0)}return c.join("/")};goog.Uri.decodeOrEmpty_=function(a,b){return a?b?decodeURI(a):decodeURIComponent(a):""};
goog.Uri.encodeSpecialChars_=function(a,b,c){return null!=a?(a=encodeURI(a).replace(b,goog.Uri.encodeChar_),c&&(a=goog.Uri.removeDoubleEncoding_(a)),a):null};goog.Uri.encodeChar_=function(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)};goog.Uri.removeDoubleEncoding_=function(a){return a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")};goog.Uri.reDisallowedInSchemeOrUserInfo_=/[#\/\?@]/g;goog.Uri.reDisallowedInRelativePath_=/[#\?:]/g;goog.Uri.reDisallowedInAbsolutePath_=/[#\?]/g;
goog.Uri.reDisallowedInQuery_=/[#\?@]/g;goog.Uri.reDisallowedInFragment_=/#/g;goog.Uri.QueryData=function(a,b){this.encodedQuery_=a||null};
goog.Uri.QueryData.prototype.ensureKeyMapInitialized_=function(){if(!this.keyMap_&&(this.keyMap_={},this.count_=0,this.encodedQuery_))for(var a=this.encodedQuery_.split("&"),b=0;b<a.length;b++){var c=a[b].indexOf("="),d=null;if(0<=c){var e=a[b].substring(0,c);d=a[b].substring(c+1)}else e=a[b];e=decodeURIComponent(e.replace(/\+/g," "));d=d||"";this.add(e,decodeURIComponent(d.replace(/\+/g," ")))}};goog.Uri.QueryData.prototype.keyMap_=null;goog.Uri.QueryData.prototype.count_=null;
goog.Uri.QueryData.prototype.getCount=function(){this.ensureKeyMapInitialized_();return this.count_};goog.Uri.QueryData.prototype.add=function(a,b){this.ensureKeyMapInitialized_();this.encodedQuery_=null;var c=this.keyMap_.hasOwnProperty(a)?this.keyMap_[a]:null;c||(this.keyMap_[a]=c=[]);c.push(b);goog.asserts.assert(null!=this.count_,"Should not be null.");this.count_++;return this};
goog.Uri.QueryData.prototype.set=function(a,b){this.ensureKeyMapInitialized_();this.encodedQuery_=null;this.keyMap_.hasOwnProperty(a)?this.keyMap_[a]=[b]:this.add(a,b);return this};goog.Uri.QueryData.prototype.toString=function(){if(this.encodedQuery_)return this.encodedQuery_;if(!this.keyMap_)return"";var a=[],b;for(b in this.keyMap_)for(var c=encodeURIComponent(b),d=this.keyMap_[b],e=0;e<d.length;e++){var f=c;""!==d[e]&&(f+="="+encodeURIComponent(d[e]));a.push(f)}return this.encodedQuery_=a.join("&")};
goog.Uri.QueryData.prototype.toDecodedString=function(){return goog.Uri.decodeOrEmpty_(this.toString())};goog.Uri.QueryData.prototype.clone=function(){var a=new goog.Uri.QueryData;a.encodedQuery_=this.encodedQuery_;if(this.keyMap_){var b={},c;for(c in this.keyMap_)b[c]=this.keyMap_[c].concat();a.keyMap_=b;a.count_=this.count_}return a};shaka.util.Functional=function(){};shaka.util.Functional.createFallbackPromiseChain=function(a,b){return a.reduce(function(c,d){return c.catch(function(){return b(d)})},Promise.reject())};shaka.util.Functional.collapseArrays=function(a,b){return a.concat(b)};shaka.util.Functional.ignored=function(){};shaka.util.Functional.noop=function(){};shaka.util.Functional.isNotNull=function(a){return null!=a};shaka.util.ManifestParserUtils=function(){};shaka.util.ManifestParserUtils.resolveUris=function(a,b){var c=shaka.util.Functional;if(0==b.length)return a;var d=b.map(function(e){return new goog.Uri(e)});return a.map(function(e){return new goog.Uri(e)}).map(function(e){return d.map(function(f){return e.resolve(f)})}).reduce(c.collapseArrays,[]).map(function(e){return e.toString()})};
shaka.util.ManifestParserUtils.createDrmInfo=function(a,b){return{keySystem:a,licenseServerUri:"",distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:b||[],keyIds:new Set}};
shaka.util.ManifestParserUtils.guessCodecs=function(a,b){if(1==b.length)return b[0];a=shaka.util.ManifestParserUtils.guessCodecsSafe(a,b);if(null!=a)return a;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_COULD_NOT_GUESS_CODECS,b);};
shaka.util.ManifestParserUtils.guessCodecsSafe=function(a,b){for(var c=$jscomp.makeIterator(shaka.util.ManifestParserUtils.CODEC_REGEXPS_BY_CONTENT_TYPE_[a]),d=c.next();!d.done;d=c.next()){d=d.value;for(var e=$jscomp.makeIterator(b),f=e.next();!f.done;f=e.next())if(f=f.value,d.test(f.trim()))return f.trim()}return a==shaka.util.ManifestParserUtils.ContentType.TEXT?"":null};shaka.util.ManifestParserUtils.ContentType={VIDEO:"video",AUDIO:"audio",TEXT:"text",IMAGE:"image",APPLICATION:"application"};
shaka.util.ManifestParserUtils.TextStreamKind={SUBTITLE:"subtitle",CLOSED_CAPTION:"caption"};shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS=1/15;shaka.util.ManifestParserUtils.VIDEO_CODEC_REGEXPS_=[/^avc/,/^hev/,/^hvc/,/^vp0?[89]/,/^av01/,/^dvhe/];shaka.util.ManifestParserUtils.AUDIO_CODEC_REGEXPS_=[/^vorbis$/,/^opus$/,/^flac$/,/^mp4a/,/^[ae]c-3$/,/^ac-4$/,/^dts[cx]$/,/^[du]dts$/];shaka.util.ManifestParserUtils.TEXT_CODEC_REGEXPS_=[/^vtt$/,/^wvtt/,/^stpp/];
shaka.util.ManifestParserUtils.CODEC_REGEXPS_BY_CONTENT_TYPE_={audio:shaka.util.ManifestParserUtils.AUDIO_CODEC_REGEXPS_,video:shaka.util.ManifestParserUtils.VIDEO_CODEC_REGEXPS_,text:shaka.util.ManifestParserUtils.TEXT_CODEC_REGEXPS_};shaka.util.PublicPromise=function(){var a,b,c=new Promise(function(d,e){a=d;b=e});c.resolve=a;c.reject=b;return c};shaka.util.PublicPromise.prototype.resolve=function(a){};shaka.util.PublicPromise.prototype.reject=function(a){};shaka.util.Lazy=function(a){this.gen_=a;this.value_=void 0};shaka.util.Lazy.prototype.value=function(){void 0==this.value_&&(this.value_=this.gen_(),goog.asserts.assert(void 0!=this.value_,"Unable to create lazy value"));return this.value_};shaka.util.Lazy.prototype.reset=function(){this.value_=void 0};shaka.util.DelayedTick=function(a){this.onTick_=a;this.cancelPending_=null};shaka.util.DelayedTick.prototype.tickAfter=function(a){var b=this;this.stop();var c=!0,d=null;this.cancelPending_=function(){window.clearTimeout(d);c=!1};d=window.setTimeout(function(){if(c)b.onTick_()},1E3*a);return this};shaka.util.DelayedTick.prototype.stop=function(){this.cancelPending_&&(this.cancelPending_(),this.cancelPending_=null)};shaka.util.Timer=function(a){this.onTick_=a;this.ticker_=null};shaka.util.Timer.prototype.tickNow=function(){this.stop();this.onTick_();return this};shaka.util.Timer.prototype.tickAfter=function(a){var b=this;this.stop();this.ticker_=(new shaka.util.DelayedTick(function(){b.onTick_()})).tickAfter(a);return this};
shaka.util.Timer.prototype.tickEvery=function(a){var b=this;this.stop();goog.DEBUG&&shaka.util.Timer.activeTimers.set(this,Error("Timer created").stack);this.ticker_=(new shaka.util.DelayedTick(function(){b.ticker_.tickAfter(a);b.onTick_()})).tickAfter(a);return this};shaka.util.Timer.prototype.stop=function(){this.ticker_&&(this.ticker_.stop(),this.ticker_=null);goog.DEBUG&&shaka.util.Timer.activeTimers.delete(this)};goog.exportSymbol("shaka.util.Timer",shaka.util.Timer);
goog.exportProperty(shaka.util.Timer.prototype,"stop",shaka.util.Timer.prototype.stop);goog.exportProperty(shaka.util.Timer.prototype,"tickEvery",shaka.util.Timer.prototype.tickEvery);goog.exportProperty(shaka.util.Timer.prototype,"tickAfter",shaka.util.Timer.prototype.tickAfter);goog.exportProperty(shaka.util.Timer.prototype,"tickNow",shaka.util.Timer.prototype.tickNow);goog.DEBUG&&(shaka.util.Timer.activeTimers=new Map);shaka.util.Platform=function(){};shaka.util.Platform.supportsMediaSource=function(){return window.MediaSource&&MediaSource.isTypeSupported?!0:!1};shaka.util.Platform.supportsMediaType=function(a){return""!=shaka.util.Platform.anyMediaElement().canPlayType(a)};shaka.util.Platform.isEdge=function(){return navigator.userAgent.match(/Edge?\//)?!0:!1};shaka.util.Platform.isLegacyEdge=function(){return navigator.userAgent.match(/Edge\//)?!0:!1};shaka.util.Platform.isIE=function(){return shaka.util.Platform.userAgentContains_("Trident/")};
shaka.util.Platform.isXboxOne=function(){return shaka.util.Platform.userAgentContains_("Xbox One")};shaka.util.Platform.isTizen=function(){return shaka.util.Platform.userAgentContains_("Tizen")};shaka.util.Platform.isTizen4=function(){return shaka.util.Platform.userAgentContains_("Tizen 4")};shaka.util.Platform.isTizen3=function(){return shaka.util.Platform.userAgentContains_("Tizen 3")};shaka.util.Platform.isTizen2=function(){return shaka.util.Platform.userAgentContains_("Tizen 2")};
shaka.util.Platform.isWebOS=function(){return shaka.util.Platform.userAgentContains_("Web0S")};shaka.util.Platform.isWebOS3=function(){return shaka.util.Platform.userAgentContains_("Web0S")&&shaka.util.Platform.userAgentContains_("Chrome/38.0.2125.122 Safari/537.36")};shaka.util.Platform.isChromecast=function(){return shaka.util.Platform.userAgentContains_("CrKey")};
shaka.util.Platform.chromeVersion=function(){if(!shaka.util.Platform.isChrome())return null;var a=navigator.userAgent.match(/Chrome\/(\d+)/);return a?parseInt(a[1],10):null};shaka.util.Platform.isChrome=function(){return shaka.util.Platform.userAgentContains_("Chrome")&&!shaka.util.Platform.isEdge()};
shaka.util.Platform.isApple=function(){return!!navigator.vendor&&navigator.vendor.includes("Apple")&&!shaka.util.Platform.isTizen()&&!shaka.util.Platform.isEOS()&&!shaka.util.Platform.isVirginMedia()&&!shaka.util.Platform.isPS4()&&!shaka.util.Platform.isAmazonFireTV()};shaka.util.Platform.isPS5=function(){return shaka.util.Platform.userAgentContains_("PlayStation 5")};shaka.util.Platform.isPS4=function(){return shaka.util.Platform.userAgentContains_("PlayStation 4")};
shaka.util.Platform.isHisense=function(){return shaka.util.Platform.userAgentContains_("Hisense")||shaka.util.Platform.userAgentContains_("VIDAA")};shaka.util.Platform.isVirginMedia=function(){return shaka.util.Platform.userAgentContains_("VirginMedia")};shaka.util.Platform.isAmazonFireTV=function(){return shaka.util.Platform.userAgentContains_("AFT")};
shaka.util.Platform.safariVersion=function(){if(!shaka.util.Platform.isApple())return null;var a=navigator.userAgent.match(/Version\/(\d+)/);return a?parseInt(a[1],10):(a=navigator.userAgent.match(/OS (\d+)(?:_\d+)?/))?parseInt(a[1],10):null};shaka.util.Platform.isSafari=function(){return!!shaka.util.Platform.safariVersion()};shaka.util.Platform.isEOS=function(){return shaka.util.Platform.userAgentContains_("PC=EOS")};
shaka.util.Platform.isMobile=function(){return/(?:iPhone|iPad|iPod|Android)/.test(navigator.userAgent)?!0:shaka.util.Platform.isApple()&&1<navigator.maxTouchPoints};shaka.util.Platform.userAgentContains_=function(a){return(navigator.userAgent||"").includes(a)};
shaka.util.Platform.anyMediaElement=function(){var a=shaka.util.Platform;if(a.cachedMediaElement_)return a.cachedMediaElement_;a.cacheExpirationTimer_||(a.cacheExpirationTimer_=new shaka.util.Timer(function(){a.cachedMediaElement_=null}));a.cachedMediaElement_=document.getElementsByTagName("video")[0]||document.getElementsByTagName("audio")[0];a.cachedMediaElement_||(a.cachedMediaElement_=document.createElement("video"));a.cacheExpirationTimer_.tickAfter(1);return a.cachedMediaElement_};
shaka.util.Platform.requiresEncryptionInfoInAllInitSegments=function(){var a=shaka.util.Platform;return a.isTizen()||a.isXboxOne()};shaka.util.Platform.isMediaKeysPolyfilled=function(){return window.shakaMediaKeysPolyfill?!0:!1};shaka.util.Platform.cacheExpirationTimer_=null;shaka.util.Platform.cachedMediaElement_=null;shaka.util.StringUtils=function(){};
shaka.util.StringUtils.fromUTF8=function(a){if(!a)return"";a=shaka.util.BufferUtils.toUint8(a);239==a[0]&&187==a[1]&&191==a[2]&&(a=a.subarray(3));if(window.TextDecoder&&!shaka.util.Platform.isPS4())return a=(new TextDecoder).decode(a),a.includes("\ufffd")&&shaka.log.alwaysError('Decoded string contains an "unknown character" codepoint.  That probably means the UTF8 encoding was incorrect!'),a;for(var b="",c=0;c<a.length;++c){var d=65533;0==(a[c]&128)?d=a[c]:a.length>=c+2&&192==(a[c]&224)&&128==(a[c+
1]&192)?(d=(a[c]&31)<<6|a[c+1]&63,c+=1):a.length>=c+3&&224==(a[c]&240)&&128==(a[c+1]&192)&&128==(a[c+2]&192)?(d=(a[c]&15)<<12|(a[c+1]&63)<<6|a[c+2]&63,c+=2):a.length>=c+4&&240==(a[c]&241)&&128==(a[c+1]&192)&&128==(a[c+2]&192)&&128==(a[c+3]&192)&&(d=(a[c]&7)<<18|(a[c+1]&63)<<12|(a[c+2]&63)<<6|a[c+3]&63,c+=3);if(65535>=d)b+=String.fromCharCode(d);else{d-=65536;var e=d&1023;b+=String.fromCharCode(55296+(d>>10));b+=String.fromCharCode(56320+e)}}return b};
shaka.util.StringUtils.fromUTF16=function(a,b,c){if(!a)return"";if(!c&&0!=a.byteLength%2)throw shaka.log.error("Data has an incorrect length, must be even."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.BAD_ENCODING);c=Math.floor(a.byteLength/2);var d=new Uint16Array(c);a=shaka.util.BufferUtils.toDataView(a);for(var e=0;e<c;e++)d[e]=a.getUint16(2*e,b);return shaka.util.StringUtils.fromCharCode(d)};
shaka.util.StringUtils.fromBytesAutoDetect=function(a){var b=shaka.util.StringUtils;if(!a)return"";var c=shaka.util.BufferUtils.toUint8(a);if(239==c[0]&&187==c[1]&&191==c[2])return b.fromUTF8(c);if(254==c[0]&&255==c[1])return b.fromUTF16(c.subarray(2),!1);if(255==c[0]&&254==c[1])return b.fromUTF16(c.subarray(2),!0);var d=function(e){return c.byteLength<=e||32<=c[e]&&126>=c[e]};shaka.log.debug("Unable to find byte-order-mark, making an educated guess.");if(0==c[0]&&0==c[2])return b.fromUTF16(a,!1);
if(0==c[1]&&0==c[3])return b.fromUTF16(a,!0);if(d(0)&&d(1)&&d(2)&&d(3))return b.fromUTF8(a);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.UNABLE_TO_DETECT_ENCODING);};
shaka.util.StringUtils.toUTF8=function(a){if(window.TextEncoder&&!shaka.util.Platform.isPS4()){var b=new TextEncoder;return shaka.util.BufferUtils.toArrayBuffer(b.encode(a))}a=encodeURIComponent(a);a=unescape(a);b=new Uint8Array(a.length);for(var c=0;c<a.length;c++)b[c]=a[c].charCodeAt(0);return shaka.util.BufferUtils.toArrayBuffer(b)};shaka.util.StringUtils.toUTF16=function(a,b){for(var c=new ArrayBuffer(2*a.length),d=new DataView(c),e=0;e<a.length;++e){var f=a.charCodeAt(e);d.setUint16(2*e,f,b)}return c};
shaka.util.StringUtils.fromCharCode=function(a){return shaka.util.StringUtils.fromCharCodeImpl_.value()(a)};shaka.util.StringUtils.resetFromCharCode=function(){shaka.util.StringUtils.fromCharCodeImpl_.reset()};goog.exportSymbol("shaka.util.StringUtils",shaka.util.StringUtils);goog.exportProperty(shaka.util.StringUtils,"resetFromCharCode",shaka.util.StringUtils.resetFromCharCode);goog.exportProperty(shaka.util.StringUtils,"toUTF16",shaka.util.StringUtils.toUTF16);
goog.exportProperty(shaka.util.StringUtils,"toUTF8",shaka.util.StringUtils.toUTF8);goog.exportProperty(shaka.util.StringUtils,"fromBytesAutoDetect",shaka.util.StringUtils.fromBytesAutoDetect);goog.exportProperty(shaka.util.StringUtils,"fromUTF16",shaka.util.StringUtils.fromUTF16);goog.exportProperty(shaka.util.StringUtils,"fromUTF8",shaka.util.StringUtils.fromUTF8);
shaka.util.StringUtils.fromCharCodeImpl_=new shaka.util.Lazy(function(){for(var a=function(c){try{var d=new Uint8Array(c),e=String.fromCharCode.apply(null,d);goog.asserts.assert(e,"Should get value");return 0<e.length}catch(f){return!1}},b={$jscomp$loop$prop$size$628:65536};0<b.$jscomp$loop$prop$size$628;b={$jscomp$loop$prop$size$628:b.$jscomp$loop$prop$size$628},b.$jscomp$loop$prop$size$628/=2)if(a(b.$jscomp$loop$prop$size$628))return function(c){return function(d){for(var e="",f=0;f<d.length;f+=
c.$jscomp$loop$prop$size$628){var g=d.subarray(f,f+c.$jscomp$loop$prop$size$628);e+=String.fromCharCode.apply(null,g)}return e}}(b);goog.asserts.assert(!1,"Unable to create a fromCharCode method");return null});shaka.util.Uint8ArrayUtils=function(){};shaka.util.Uint8ArrayUtils.toStandardBase64=function(a){a=shaka.util.StringUtils.fromCharCode(shaka.util.BufferUtils.toUint8(a));return btoa(a)};shaka.util.Uint8ArrayUtils.toBase64=function(a,b){b=void 0==b?!0:b;a=shaka.util.Uint8ArrayUtils.toStandardBase64(a).replace(/\+/g,"-").replace(/\//g,"_");return b?a:a.replace(/[=]*$/,"")};
shaka.util.Uint8ArrayUtils.fromBase64=function(a){a=window.atob(a.replace(/-/g,"+").replace(/_/g,"/"));for(var b=new Uint8Array(a.length),c=0;c<a.length;++c)b[c]=a.charCodeAt(c);return b};shaka.util.Uint8ArrayUtils.fromHex=function(a){for(var b=a.length/2,c=new Uint8Array(b),d=0;d<b;d++)c[d]=parseInt(a.substr(2*d,2),16);return c};
shaka.util.Uint8ArrayUtils.toHex=function(a){var b=shaka.util.BufferUtils.toUint8(a);a="";b=$jscomp.makeIterator(b);for(var c=b.next();!c.done;c=b.next())c=c.value,c=c.toString(16),1==c.length&&(c="0"+c),a+=c;return a};
shaka.util.Uint8ArrayUtils.concat=function(){for(var a=$jscomp.getRestArguments.apply(0,arguments),b=0,c=$jscomp.makeIterator(a),d=c.next();!d.done;d=c.next())b+=d.value.byteLength;b=new Uint8Array(b);c=0;a=$jscomp.makeIterator(a);for(d=a.next();!d.done;d=a.next())d=d.value,b.set(shaka.util.BufferUtils.toUint8(d),c),c+=d.byteLength;return b};goog.exportSymbol("shaka.util.Uint8ArrayUtils",shaka.util.Uint8ArrayUtils);goog.exportProperty(shaka.util.Uint8ArrayUtils,"concat",shaka.util.Uint8ArrayUtils.concat);
goog.exportProperty(shaka.util.Uint8ArrayUtils,"toHex",shaka.util.Uint8ArrayUtils.toHex);goog.exportProperty(shaka.util.Uint8ArrayUtils,"fromHex",shaka.util.Uint8ArrayUtils.fromHex);goog.exportProperty(shaka.util.Uint8ArrayUtils,"fromBase64",shaka.util.Uint8ArrayUtils.fromBase64);goog.exportProperty(shaka.util.Uint8ArrayUtils,"toBase64",shaka.util.Uint8ArrayUtils.toBase64);goog.exportProperty(shaka.util.Uint8ArrayUtils,"toStandardBase64",shaka.util.Uint8ArrayUtils.toStandardBase64);shaka.dependencies=function(){};shaka.dependencies.add=function(a,b){if(!shaka.dependencies.Allowed[a])throw Error(a+" is not supported");shaka.dependencies.dependencies_.set(a,function(){return b})};shaka.dependencies.has=function(a){return shaka.dependencies.dependencies_.has(a)};shaka.dependencies.muxjs=function(){return shaka.dependencies.dependencies_.get(shaka.dependencies.Allowed.muxjs)()};goog.exportSymbol("shaka.dependencies",shaka.dependencies);
goog.exportProperty(shaka.dependencies,"has",shaka.dependencies.has);goog.exportProperty(shaka.dependencies,"add",shaka.dependencies.add);shaka.dependencies.Allowed={muxjs:"muxjs"};goog.exportProperty(shaka.dependencies,"Allowed",shaka.dependencies.Allowed);shaka.dependencies.dependencies_=new Map([[shaka.dependencies.Allowed.muxjs,function(){return muxjs}]]);shaka.media.Transmuxer=function(a){var b=this;this.originalMimeType_=a;this.muxjs_=shaka.dependencies.muxjs();this.transmuxPromise_=this.muxTransmuxer_=null;this.transmuxedData_=[];this.captions_=[];this.isTransmuxing_=!1;this.muxjs_&&(this.muxTransmuxer_=new this.muxjs_.mp4.Transmuxer({keepOriginalTimestamps:!0}),this.muxTransmuxer_.on("data",function(c){return b.onTransmuxed_(c)}),this.muxTransmuxer_.on("done",function(){return b.onTransmuxDone_()}))};
shaka.media.Transmuxer.prototype.destroy=function(){this.muxTransmuxer_&&this.muxTransmuxer_.dispose();this.muxTransmuxer_=null;return Promise.resolve()};
shaka.media.Transmuxer.isSupported=function(a,b){var c=shaka.media.Transmuxer,d=shaka.media.Capabilities,e=c.isTsContainer_(a),f=c.isAacContainer_(a);if(!shaka.dependencies.muxjs()||!e&&!f)return!1;if(f)return d.isTypeSupported(c.convertAacCodecs_());if(b)return d.isTypeSupported(c.convertTsCodecs_(b,a));e=shaka.util.ManifestParserUtils.ContentType;b=c.convertTsCodecs_(e.AUDIO,a);a=c.convertTsCodecs_(e.VIDEO,a);return d.isTypeSupported(b)||d.isTypeSupported(a)};
shaka.media.Transmuxer.isAacContainer_=function(a){return"audio/aac"==a.toLowerCase().split(";")[0]};shaka.media.Transmuxer.isTsContainer_=function(a){return"mp2t"==a.toLowerCase().split(";")[0].split("/")[1]};shaka.media.Transmuxer.convertCodecs=function(a,b){var c=shaka.media.Transmuxer;return c.isAacContainer_(b)?c.convertAacCodecs_():c.isTsContainer_(b)?c.convertTsCodecs_(a,b):b};shaka.media.Transmuxer.convertAacCodecs_=function(){return'audio/mp4; codecs="mp4a.40.2"'};
shaka.media.Transmuxer.convertTsCodecs_=function(a,b){var c=shaka.util.ManifestParserUtils.ContentType;b=b.replace(/mp2t/i,"mp4");a==c.AUDIO&&(b=b.replace("video","audio"));if(a=/avc1\.(66|77|100)\.(\d+)/.exec(b)){c="avc1.";var d=a[1];"66"==d?c+="4200":"77"==d?c+="4d00":(goog.asserts.assert("100"==d,"Legacy avc1 parsing code out of sync with regex!"),c+="6400");d=Number(a[2]);goog.asserts.assert(256>d,"Invalid legacy avc1 level number!");c+=(d>>4).toString(16);c+=(d&15).toString(16);b=b.replace(a[0],
c)}return b};shaka.media.Transmuxer.prototype.getOrginalMimeType=function(){return this.originalMimeType_};
shaka.media.Transmuxer.prototype.transmux=function(a){goog.asserts.assert(this.muxTransmuxer_,"mux.js should be available.");goog.asserts.assert(!this.isTransmuxing_,"No transmuxing should be in progress.");this.isTransmuxing_=!0;this.transmuxPromise_=new shaka.util.PublicPromise;this.transmuxedData_=[];this.captions_=[];a=shaka.util.BufferUtils.toUint8(a);this.muxTransmuxer_.push(a);this.muxTransmuxer_.flush();this.isTransmuxing_&&this.transmuxPromise_.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.TRANSMUXING_FAILED));return this.transmuxPromise_};shaka.media.Transmuxer.prototype.resetCaptions=function(){this.muxTransmuxer_.resetCaptions()};shaka.media.Transmuxer.prototype.onTransmuxed_=function(a){this.captions_=a.captions;this.transmuxedData_.push(shaka.util.Uint8ArrayUtils.concat(a.initSegment,a.data))};
shaka.media.Transmuxer.prototype.onTransmuxDone_=function(){var a={data:shaka.util.Uint8ArrayUtils.concat.apply(shaka.util.Uint8ArrayUtils,$jscomp.arrayFromIterable(this.transmuxedData_)),captions:this.captions_};this.transmuxPromise_.resolve(a);this.isTransmuxing_=!1};shaka.util.MimeUtils=function(){};shaka.util.MimeUtils.getFullType=function(a,b){b&&(a+='; codecs="'+b+'"');return a};shaka.util.MimeUtils.getFullOrConvertedType=function(a,b,c){b=shaka.util.MimeUtils.getFullType(a,b);var d=shaka.util.ManifestParserUtils.ContentType;return shaka.media.Transmuxer.isSupported(b,c)?shaka.media.Transmuxer.convertCodecs(c,b):"video/mp2t"!=a&&c==d.AUDIO?b.replace("video","audio"):b};
shaka.util.MimeUtils.getExtendedType=function(a){var b=[a.mimeType];shaka.util.MimeUtils.EXTENDED_MIME_PARAMETERS_.forEach(function(c,d){(d=a[d])&&b.push(c+'="'+d+'"')});"PQ"==a.hdr&&b.push('eotf="smpte2084"');return b.join(";")};shaka.util.MimeUtils.getContainerType=function(a){return a.split(";")[0].split("/")[1]};shaka.util.MimeUtils.splitCodecs=function(a){return a.split(",")};
shaka.util.MimeUtils.getNormalizedCodec=function(a){var b=shaka.util.MimeUtils.getCodecParts_(a);a=b[0];b=b[1].toLowerCase();switch(!0){case "mp4a"===a&&"69"===b:case "mp4a"===a&&"6b"===b:return"mp3";case "mp4a"===a&&"66"===b:case "mp4a"===a&&"67"===b:case "mp4a"===a&&"68"===b:case "mp4a"===a&&"40.2"===b:case "mp4a"===a&&"40.02"===b:case "mp4a"===a&&"40.5"===b:case "mp4a"===a&&"40.05"===b:case "mp4a"===a&&"40.29"===b:case "mp4a"===a&&"40.42"===b:return"aac";case "mp4a"===a&&"a5"===b:return"ac-3";
case "mp4a"===a&&"a6"===b:return"ec-3";case "mp4a"===a&&"b2"===b:return"dtsx";case "mp4a"===a&&"a9"===b:return"dtsc";case "avc1"===a:case "avc3"===a:return"avc";case "hvc1"===a:case "hev1"===a:return"hevc";case "dvh1"===a:case "dvhe"===a:return"dovi"}return a};shaka.util.MimeUtils.getCodecBase=function(a){return shaka.util.MimeUtils.getCodecParts_(a)[0]};shaka.util.MimeUtils.getBasicType=function(a){return a.split(";")[0]};
shaka.util.MimeUtils.getCodecs=function(a){a=a.split(/ *; */);a.shift();return(a=a.find(function(b){return b.startsWith("codecs=")}))?a.split("=")[1].replace(/^"|"$/g,""):""};shaka.util.MimeUtils.getCodecParts_=function(a){var b=a.split(".");a=b[0];b.shift();b=b.join(".");return[a,b]};goog.exportSymbol("shaka.util.MimeUtils",shaka.util.MimeUtils);goog.exportProperty(shaka.util.MimeUtils,"getFullType",shaka.util.MimeUtils.getFullType);
shaka.util.MimeUtils.EXTENDED_MIME_PARAMETERS_=(new Map).set("codecs","codecs").set("frameRate","framerate").set("bandwidth","bitrate").set("width","width").set("height","height").set("channelsCount","channels");shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE="application/cea-608";shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE="application/cea-708";shaka.text.TextEngine=function(a){this.parser_=null;this.displayer_=a;this.segmentRelativeVttTiming_=!1;this.appendWindowStart_=this.timestampOffset_=0;this.appendWindowEnd_=Infinity;this.bufferEnd_=this.bufferStart_=null;this.selectedClosedCaptionId_="";this.closedCaptionsMap_=new Map};shaka.text.TextEngine.registerParser=function(a,b){shaka.text.TextEngine.parserMap_[a]=b};shaka.text.TextEngine.unregisterParser=function(a){delete shaka.text.TextEngine.parserMap_[a]};
shaka.text.TextEngine.findParser=function(a){return shaka.text.TextEngine.parserMap_[a]};shaka.text.TextEngine.isTypeSupported=function(a){return shaka.text.TextEngine.parserMap_[a]||a==shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE||a==shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE?!0:!1};shaka.text.TextEngine.prototype.destroy=function(){this.displayer_=this.parser_=null;this.closedCaptionsMap_.clear();return Promise.resolve()};
shaka.text.TextEngine.prototype.setDisplayer=function(a){this.displayer_=a};
shaka.text.TextEngine.prototype.initParser=function(a,b,c){a!=shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE&&a!=shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE&&(a=shaka.text.TextEngine.parserMap_[a],goog.asserts.assert(a,"Text type negotiation should have happened already"),this.parser_=a(),this.parser_.setSequenceMode?this.parser_.setSequenceMode(b):shaka.log.alwaysWarn('Text parsers should have a "setSequenceMode" method!'),this.segmentRelativeVttTiming_=c)};
shaka.text.TextEngine.prototype.appendBuffer=function(a,b,c){var d=this,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress)return goog.asserts.assert(d.parser_,"The parser should already be initialized"),k.yield(Promise.resolve(),2);if(!d.parser_||!d.displayer_)return k.return();if(null==b||null==c)return d.parser_.parseInit(shaka.util.BufferUtils.toUint8(a)),k.return();e=d.segmentRelativeVttTiming_?b:d.timestampOffset_;f={periodStart:d.timestampOffset_,segmentStart:b,
segmentEnd:c,vttOffset:e};g=d.parser_.parseMedia(shaka.util.BufferUtils.toUint8(a),f);h=g.filter(function(l){return l.startTime>=d.appendWindowStart_&&l.startTime<d.appendWindowEnd_});d.displayer_.append(h);null==d.bufferStart_?d.bufferStart_=Math.max(b,d.appendWindowStart_):(goog.asserts.assert(null!=d.bufferEnd_,"There should already be a buffered range end."),goog.asserts.assert(1>=b-d.bufferEnd_,"There should not be a gap in text references >1s"));d.bufferEnd_=Math.min(c,d.appendWindowEnd_);k.jumpToEnd()})};
shaka.text.TextEngine.prototype.remove=function(a,b){var c=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return d.yield(Promise.resolve(),2);c.displayer_&&c.displayer_.remove(a,b)&&(null==c.bufferStart_?goog.asserts.assert(null==c.bufferEnd_,"end must be null if startTime is null"):(goog.asserts.assert(null!=c.bufferEnd_,"end must be non-null if startTime is non-null"),b<=c.bufferStart_||a>=c.bufferEnd_||(a<=c.bufferStart_&&b>=c.bufferEnd_?c.bufferStart_=
c.bufferEnd_=null:a<=c.bufferStart_&&b<c.bufferEnd_?c.bufferStart_=b:a>c.bufferStart_&&b>=c.bufferEnd_?c.bufferEnd_=a:goog.asserts.assert(!1,"removal from the middle is not supported by TextEngine"))));d.jumpToEnd()})};shaka.text.TextEngine.prototype.setTimestampOffset=function(a){this.timestampOffset_=a};shaka.text.TextEngine.prototype.setAppendWindow=function(a,b){this.appendWindowStart_=a;this.appendWindowEnd_=b};shaka.text.TextEngine.prototype.bufferStart=function(){return this.bufferStart_};
shaka.text.TextEngine.prototype.bufferEnd=function(){return this.bufferEnd_};shaka.text.TextEngine.prototype.isBuffered=function(a){return null==this.bufferStart_||null==this.bufferEnd_?!1:a>=this.bufferStart_&&a<this.bufferEnd_};shaka.text.TextEngine.prototype.bufferedAheadOf=function(a){if(null==this.bufferEnd_||this.bufferEnd_<a)return 0;goog.asserts.assert(null!=this.bufferStart_,"start should not be null if end is not null");return this.bufferEnd_-Math.max(a,this.bufferStart_)};
shaka.text.TextEngine.prototype.setSelectedClosedCaptionId=function(a,b){this.selectedClosedCaptionId_=a;if(a=this.closedCaptionsMap_.get(a))for(var c=$jscomp.makeIterator(a.keys()),d=c.next();!d.done;d=c.next())(d=a.get(d.value).filter(function(e){return e.endTime<=b}))&&this.displayer_.append(d)};
shaka.text.TextEngine.prototype.convertMuxjsCaptionsToShakaCaptions=function(a){var b=[];a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){c=c.value;var d=new shaka.text.Cue(c.startTime,c.endTime,c.text);b.push({stream:c.stream,cue:d})}return b};shaka.text.TextEngine.prototype.applyVideoTimestampOffsetRecursive_=function(a,b){a.startTime+=b;a.endTime+=b;a=$jscomp.makeIterator(a.nestedCues);for(var c=a.next();!c.done;c=a.next())this.applyVideoTimestampOffsetRecursive_(c.value,b)};
shaka.text.TextEngine.prototype.storeAndAppendClosedCaptions=function(a,b,c,d){var e=b+" "+c,f=new Map;a=$jscomp.makeIterator(a);for(var g=a.next();!g.done;g=a.next()){var h=g.value;g=h.stream;h=h.cue;f.has(g)||f.set(g,new Map);f.get(g).has(e)||f.get(g).set(e,[]);this.applyVideoTimestampOffsetRecursive_(h,d);h.startTime>=this.appendWindowStart_&&h.startTime<this.appendWindowEnd_&&(f.get(g).get(e).push(h),g==this.selectedClosedCaptionId_&&this.displayer_.append([h]))}d=$jscomp.makeIterator(f.keys());
for(e=d.next();!e.done;e=d.next())for(e=e.value,this.closedCaptionsMap_.has(e)||this.closedCaptionsMap_.set(e,new Map),a=$jscomp.makeIterator(f.get(e).keys()),g=a.next();!g.done;g=a.next())g=g.value,h=f.get(e).get(g),this.closedCaptionsMap_.get(e).set(g,h);this.bufferStart_=null==this.bufferStart_?Math.max(b,this.appendWindowStart_):Math.min(this.bufferStart_,Math.max(b,this.appendWindowStart_));this.bufferEnd_=Math.max(this.bufferEnd_,Math.min(c,this.appendWindowEnd_))};
shaka.text.TextEngine.prototype.getNumberOfClosedCaptionChannels=function(){return this.closedCaptionsMap_.size};shaka.text.TextEngine.prototype.getNumberOfClosedCaptionsInChannel=function(a){return(a=this.closedCaptionsMap_.get(a))?a.size:0};goog.exportSymbol("shaka.text.TextEngine",shaka.text.TextEngine);goog.exportProperty(shaka.text.TextEngine.prototype,"destroy",shaka.text.TextEngine.prototype.destroy);goog.exportProperty(shaka.text.TextEngine,"findParser",shaka.text.TextEngine.findParser);
goog.exportProperty(shaka.text.TextEngine,"unregisterParser",shaka.text.TextEngine.unregisterParser);goog.exportProperty(shaka.text.TextEngine,"registerParser",shaka.text.TextEngine.registerParser);shaka.text.TextEngine.parserMap_={};shaka.util.LanguageUtils=function(){};shaka.util.LanguageUtils.areLocaleCompatible=function(a,b){var c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);return a==b};shaka.util.LanguageUtils.areLanguageCompatible=function(a,b){var c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);a=c.disassembleLocale_(a);b=c.disassembleLocale_(b);return a[0]==b[0]};
shaka.util.LanguageUtils.isParentOf=function(a,b){var c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);a=c.disassembleLocale_(a);b=c.disassembleLocale_(b);return a[0]==b[0]&&1==a.length&&2==b.length};shaka.util.LanguageUtils.isSiblingOf=function(a,b){var c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);a=c.disassembleLocale_(a);b=c.disassembleLocale_(b);return 2==a.length&&2==b.length&&a[0]==b[0]};
shaka.util.LanguageUtils.normalize=function(a){var b=shaka.util.LanguageUtils,c=a.split("-");a=c[0]||"";c=c[1]||"";a=a.toLowerCase();a=b.isoMap_.get(a)||a;return(c=c.toUpperCase())?a+"-"+c:a};shaka.util.LanguageUtils.areSiblings=function(a,b){var c=shaka.util.LanguageUtils,d=c.getBase(a);c=c.getBase(b);return a!=d&&b!=c&&d==c};
shaka.util.LanguageUtils.relatedness=function(a,b){var c=shaka.util.LanguageUtils;a=c.normalize(a);b=c.normalize(b);return b==a?4:c.isParentOf(b,a)?3:c.isSiblingOf(b,a)?2:c.isParentOf(a,b)?1:0};shaka.util.LanguageUtils.getBase=function(a){var b=shaka.util.LanguageUtils,c=a.indexOf("-");a=0<=c?a.substring(0,c):a;a=a.toLowerCase();return a=b.isoMap_.get(a)||a};
shaka.util.LanguageUtils.getLocaleForText=function(a){var b=shaka.util.LanguageUtils;goog.asserts.assert(a.type==shaka.util.ManifestParserUtils.ContentType.TEXT,"Can only get language from text streams");return b.normalize(a.language||"und")};shaka.util.LanguageUtils.getLocaleForVariant=function(a){var b=shaka.util.LanguageUtils;return a.language?b.normalize(a.language):a.audio&&a.audio.language?b.normalize(a.audio.language):a.video&&a.video.language?b.normalize(a.video.language):"und"};
shaka.util.LanguageUtils.findClosestLocale=function(a,b){var c=shaka.util.LanguageUtils;a=c.normalize(a);var d=new Set,e=$jscomp.makeIterator(b);for(b=e.next();!b.done;b=e.next())d.add(c.normalize(b.value));e=$jscomp.makeIterator(d);for(b=e.next();!b.done;b=e.next())if(b=b.value,b==a)return b;e=$jscomp.makeIterator(d);for(b=e.next();!b.done;b=e.next())if(b=b.value,c.isParentOf(b,a))return b;e=$jscomp.makeIterator(d);for(b=e.next();!b.done;b=e.next())if(b=b.value,c.isSiblingOf(b,a))return b;d=$jscomp.makeIterator(d);
for(b=d.next();!b.done;b=d.next())if(b=b.value,c.isParentOf(a,b))return b;return null};shaka.util.LanguageUtils.disassembleLocale_=function(a){var b=a.split("-");goog.asserts.assert(2>=b.length,["Locales should not have more than 2 components. ",a," has too many components."].join());return b};goog.exportSymbol("shaka.util.LanguageUtils",shaka.util.LanguageUtils);goog.exportProperty(shaka.util.LanguageUtils,"findClosestLocale",shaka.util.LanguageUtils.findClosestLocale);
goog.exportProperty(shaka.util.LanguageUtils,"getLocaleForVariant",shaka.util.LanguageUtils.getLocaleForVariant);goog.exportProperty(shaka.util.LanguageUtils,"getLocaleForText",shaka.util.LanguageUtils.getLocaleForText);goog.exportProperty(shaka.util.LanguageUtils,"getBase",shaka.util.LanguageUtils.getBase);goog.exportProperty(shaka.util.LanguageUtils,"relatedness",shaka.util.LanguageUtils.relatedness);goog.exportProperty(shaka.util.LanguageUtils,"areSiblings",shaka.util.LanguageUtils.areSiblings);
goog.exportProperty(shaka.util.LanguageUtils,"normalize",shaka.util.LanguageUtils.normalize);goog.exportProperty(shaka.util.LanguageUtils,"isSiblingOf",shaka.util.LanguageUtils.isSiblingOf);goog.exportProperty(shaka.util.LanguageUtils,"isParentOf",shaka.util.LanguageUtils.isParentOf);goog.exportProperty(shaka.util.LanguageUtils,"areLanguageCompatible",shaka.util.LanguageUtils.areLanguageCompatible);goog.exportProperty(shaka.util.LanguageUtils,"areLocaleCompatible",shaka.util.LanguageUtils.areLocaleCompatible);
shaka.util.LanguageUtils.isoMap_=new Map([["aar","aa"],["abk","ab"],["afr","af"],["aka","ak"],["alb","sq"],["amh","am"],["ara","ar"],["arg","an"],["arm","hy"],["asm","as"],["ava","av"],["ave","ae"],["aym","ay"],["aze","az"],["bak","ba"],["bam","bm"],["baq","eu"],["bel","be"],["ben","bn"],["bih","bh"],["bis","bi"],["bod","bo"],["bos","bs"],["bre","br"],["bul","bg"],["bur","my"],["cat","ca"],["ces","cs"],["cha","ch"],["che","ce"],["chi","zh"],["chu","cu"],["chv","cv"],["cor","kw"],["cos","co"],["cre",
"cr"],["cym","cy"],["cze","cs"],["dan","da"],["deu","de"],["div","dv"],["dut","nl"],["dzo","dz"],["ell","el"],["eng","en"],["epo","eo"],["est","et"],["eus","eu"],["ewe","ee"],["fao","fo"],["fas","fa"],["fij","fj"],["fin","fi"],["fra","fr"],["fre","fr"],["fry","fy"],["ful","ff"],["geo","ka"],["ger","de"],["gla","gd"],["gle","ga"],["glg","gl"],["glv","gv"],["gre","el"],["grn","gn"],["guj","gu"],["hat","ht"],["hau","ha"],["heb","he"],["her","hz"],["hin","hi"],["hmo","ho"],["hrv","hr"],["hun","hu"],["hye",
"hy"],["ibo","ig"],["ice","is"],["ido","io"],["iii","ii"],["iku","iu"],["ile","ie"],["ina","ia"],["ind","id"],["ipk","ik"],["isl","is"],["ita","it"],["jav","jv"],["jpn","ja"],["kal","kl"],["kan","kn"],["kas","ks"],["kat","ka"],["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"],["mah",
"mh"],["mal","ml"],["mao","mi"],["mar","mr"],["may","ms"],["mkd","mk"],["mlg","mg"],["mlt","mt"],["mon","mn"],["mri","mi"],["msa","ms"],["mya","my"],["nau","na"],["nav","nv"],["nbl","nr"],["nde","nd"],["ndo","ng"],["nep","ne"],["nld","nl"],["nno","nn"],["nob","nb"],["nor","no"],["nya","ny"],["oci","oc"],["oji","oj"],["ori","or"],["orm","om"],["oss","os"],["pan","pa"],["per","fa"],["pli","pi"],["pol","pl"],["por","pt"],["pus","ps"],["que","qu"],["roh","rm"],["ron","ro"],["rum","ro"],["run","rn"],["rus",
"ru"],["sag","sg"],["san","sa"],["sin","si"],["slk","sk"],["slo","sk"],["slv","sl"],["sme","se"],["smo","sm"],["sna","sn"],["snd","sd"],["som","so"],["sot","st"],["spa","es"],["sqi","sq"],["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"],["tib","bo"],["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"],["wel","cy"],["wln","wa"],["wol","wo"],["xho","xh"],["yid","yi"],["yor","yo"],["zha","za"],["zho","zh"],["zul","zu"]]);shaka.util.MultiMap=function(){this.map_={}};shaka.util.MultiMap.prototype.push=function(a,b){this.map_.hasOwnProperty(a)?this.map_[a].push(b):this.map_[a]=[b]};shaka.util.MultiMap.prototype.get=function(a){return(a=this.map_[a])?a.slice():null};shaka.util.MultiMap.prototype.getAll=function(){var a=[],b;for(b in this.map_)a.push.apply(a,$jscomp.arrayFromIterable(this.map_[b]));return a};
shaka.util.MultiMap.prototype.remove=function(a,b){a in this.map_&&(this.map_[a]=this.map_[a].filter(function(c){return c!=b}),0==this.map_[a].length&&delete this.map_[a])};shaka.util.MultiMap.prototype.clear=function(){this.map_={}};shaka.util.MultiMap.prototype.forEach=function(a){for(var b in this.map_)a(b,this.map_[b])};shaka.util.MultiMap.prototype.size=function(){return Object.keys(this.map_).length};shaka.util.MultiMap.prototype.keys=function(){return Object.keys(this.map_)};shaka.util.StreamUtils=function(){};shaka.util.StreamUtils.chooseCodecsAndFilterManifest=function(a,b,c,d,e){var f=shaka.util.StreamUtils,g=a.variants;if(b.length||c.length)g=f.choosePreferredCodecs(g,b,c);g=f.filterVariantsByAudioChannelCount(g,d);b=f.getVariantsByCodecs_(g);b=f.filterVariantsByDensity_(b);var h=f.chooseCodecsByDecodingAttributes_(b,e);a.variants=a.variants.filter(function(k){if(f.getVariantCodecs_(k)==h)return!0;shaka.log.debug("Dropping Variant (better codec available)",k);return!1})};
shaka.util.StreamUtils.getVariantsByCodecs_=function(a){var b=new shaka.util.MultiMap;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){c=c.value;var d=shaka.util.StreamUtils.getVariantCodecs_(c);b.push(d,c)}return b};
shaka.util.StreamUtils.filterVariantsByDensity_=function(a){var b=0,c=new Map,d=a.size();a.forEach(function(e,f){f=$jscomp.makeIterator(f);for(var g=f.next();!g.done;g=f.next()){g=g.value;var h=g.video;if(h&&h.width&&h.height){h=h.width*h.height*(h.frameRate||1);c.has(h)||c.set(h,new shaka.util.MultiMap);var k=c.get(h);k.push(e,g);k.size()===d&&(b=Math.max(b,h))}}});return b?c.get(b):a};
shaka.util.StreamUtils.choosePreferredCodecs=function(a,b,c){var d={};b=$jscomp.makeIterator(b);for(var e=b.next();!e.done;d={$jscomp$loop$prop$videoCodec$630:d.$jscomp$loop$prop$videoCodec$630},e=b.next())if(d.$jscomp$loop$prop$videoCodec$630=e.value,e=a.filter(function(f){return function(g){return g.video&&g.video.codecs.startsWith(f.$jscomp$loop$prop$videoCodec$630)}}(d)),e.length){a=e;break}d={};c=$jscomp.makeIterator(c);for(b=c.next();!b.done;d={$jscomp$loop$prop$audioCodec$632:d.$jscomp$loop$prop$audioCodec$632},
b=c.next())if(d.$jscomp$loop$prop$audioCodec$632=b.value,b=a.filter(function(f){return function(g){return g.audio&&g.audio.codecs.startsWith(f.$jscomp$loop$prop$audioCodec$632)}}(d)),b.length){a=b;break}return a};
shaka.util.StreamUtils.chooseCodecsByDecodingAttributes_=function(a,b){var c=shaka.util.StreamUtils;b=$jscomp.makeIterator(b);for(var d=b.next();!d.done;d=b.next())if(d=d.value,d==c.DecodingAttributes.SMOOTH||d==c.DecodingAttributes.POWER){if(a=c.chooseCodecsByMediaCapabilitiesInfo_(a,d),1==a.size())return a.keys()[0]}else if(d==c.DecodingAttributes.BANDWIDTH)break;return c.findCodecsByLowestBandwidth_(a)};
shaka.util.StreamUtils.chooseCodecsByMediaCapabilitiesInfo_=function(a,b){var c=0,d=new shaka.util.MultiMap;a.forEach(function(e,f){for(var g=0,h=0,k=$jscomp.makeIterator(f),l=k.next();!l.done;l=k.next())l=l.value,l.decodingInfos.length&&(g+=l.decodingInfos[0][b]?1:0,h++);g/=h;shaka.log.debug("codecs",e,"avg",b,g);g>c?(d.clear(),d.push(e,f),c=g):g==c&&d.push(e,f)});return d};
shaka.util.StreamUtils.findCodecsByLowestBandwidth_=function(a){var b="",c=Infinity;a.forEach(function(d,e){var f=0,g=0;e=$jscomp.makeIterator(e);for(var h=e.next();!h.done;h=e.next())f+=h.value.bandwidth||0,++g;f/=g;shaka.log.debug("codecs",d,"avg bandwidth",f);f<c&&(b=d,c=f)});goog.asserts.assert(""!==b,"Should have chosen codecs!");goog.asserts.assert(!isNaN(c),"Bandwidth should be a number!");return b};
shaka.util.StreamUtils.getVariantCodecs_=function(a){var b="";a.video&&(b=shaka.util.MimeUtils.getNormalizedCodec(a.video.codecs));var c="";a.audio&&(c=shaka.util.MimeUtils.getNormalizedCodec(a.audio.codecs));return b+"-"+c};shaka.util.StreamUtils.filterByRestrictions=function(a,b,c){a.variants=a.variants.filter(function(d){return shaka.util.StreamUtils.meetsRestrictions(d,b,c)})};
shaka.util.StreamUtils.meetsRestrictions=function(a,b,c){var d=function(f,g,h){return f>=g&&f<=h},e=a.video;if(0!=a.disabledUntilTime){if(a.disabledUntilTime>Date.now()/1E3)return!1;a.disabledUntilTime=0}return e&&e.width&&e.height&&(!d(e.width,b.minWidth,Math.min(b.maxWidth,c.width))||!d(e.height,b.minHeight,Math.min(b.maxHeight,c.height))||!d(e.width*e.height,b.minPixels,b.maxPixels))||a&&a.video&&a.video.frameRate&&!d(a.video.frameRate,b.minFrameRate,b.maxFrameRate)||!d(a.bandwidth,b.minBandwidth,
b.maxBandwidth)?!1:!0};shaka.util.StreamUtils.applyRestrictions=function(a,b,c){var d=!1;a=$jscomp.makeIterator(a);for(var e=a.next();!e.done;e=a.next()){e=e.value;var f=e.allowedByApplication;e.allowedByApplication=shaka.util.StreamUtils.meetsRestrictions(e,b,c);f!=e.allowedByApplication&&(d=!0)}return d};
shaka.util.StreamUtils.filterManifest=function(a,b,c){return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return d.yield(shaka.util.StreamUtils.filterManifestByMediaCapabilities(c,0<c.offlineSessionIds.length),2);shaka.util.StreamUtils.filterManifestByCurrentVariant(b,c);shaka.util.StreamUtils.filterTextStreams_(c);return d.yield(shaka.util.StreamUtils.filterImageStreams_(c),0)})};
shaka.util.StreamUtils.filterManifestByMediaCapabilities=function(a,b){return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return goog.asserts.assert(navigator.mediaCapabilities,"MediaCapabilities should be valid."),c.yield(shaka.util.StreamUtils.getDecodingInfosForVariants(a.variants,b,!1),2);a.variants=a.variants.filter(function(d){var e=d.video,f=shaka.util.ManifestParserUtils.ContentType,g=shaka.media.Capabilities;if(e){var h=shaka.util.StreamUtils.getCorrectVideoCodecs_(e.codecs);
if(e.codecs.includes(",")){var k=e.codecs.split(",");h=shaka.util.ManifestParserUtils.guessCodecs(f.VIDEO,k);h=shaka.util.StreamUtils.getCorrectVideoCodecs_(h);k=shaka.util.ManifestParserUtils.guessCodecs(f.AUDIO,k);k=shaka.util.StreamUtils.getCorrectAudioCodecs_(k);var l=shaka.util.MimeUtils.getFullOrConvertedType(e.mimeType,k,f.AUDIO);if(!g.isTypeSupported(l))return!1;h=[h,k].join()}k=shaka.util.MimeUtils.getFullOrConvertedType(e.mimeType,h,f.VIDEO);if(!g.isTypeSupported(k))return!1;e.codecs=h}if(h=
d.audio){k=shaka.util.StreamUtils.getCorrectAudioCodecs_(h.codecs);f=shaka.util.MimeUtils.getFullOrConvertedType(h.mimeType,k,f.AUDIO);if(!g.isTypeSupported(f))return!1;h.codecs=k}if(shaka.util.Platform.isXboxOne()&&e&&(e.width&&1920<e.width||e.height&&1080<e.height)&&(e.codecs.includes("avc1.")||e.codecs.includes("avc3.")))return shaka.log.debug("Dropping variant - not compatible with platform",shaka.util.StreamUtils.getVariantSummaryString_(d)),!1;(e=d.decodingInfos.some(function(m){return m.supported}))||
shaka.log.debug("Dropping variant - not compatible with platform",shaka.util.StreamUtils.getVariantSummaryString_(d));return e});c.jumpToEnd()})};
shaka.util.StreamUtils.getDecodingInfosForVariants=function(a,b,c){var d,e,f,g,h,k,l,m,n,p,q;return $jscomp.asyncExecutePromiseGeneratorProgram(function(r){if(d=a.some(function(w){return w.decodingInfos.length}))return shaka.log.debug("Already got the variants' decodingInfo."),r.return();e=navigator.mediaCapabilities;f=[];g=function(w,u){var v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){if(1==t.nextAddress)return t.setCatchFinallyBlocks(2),t.yield(e.decodingInfo(u),4);if(2!=t.nextAddress)return v=
t.yieldResult,w.decodingInfos.push(v),t.leaveTryBlock(0);x=t.enterCatchBlock();shaka.log.info("MediaCapabilities.decodingInfo() failed.",JSON.stringify(u),x);t.jumpToEnd()})};h=$jscomp.makeIterator(a);for(k=h.next();!k.done;k=h.next())for(l=k.value,m=shaka.util.StreamUtils.getDecodingConfigs_(l,b,c),n=$jscomp.makeIterator(m),p=n.next();!p.done;p=n.next())q=p.value,f.push(g(l,q));return r.yield(Promise.all(f),0)})};
shaka.util.StreamUtils.getDecodingConfigs_=function(a,b,c){var d=a.audio,e=a.video,f=shaka.util.ManifestParserUtils.ContentType;c={type:c?"file":"media-source"};if(e){var g=e.codecs;if(e.codecs.includes(",")){var h=e.codecs.split(",");g=shaka.util.ManifestParserUtils.guessCodecs(f.VIDEO,h);g=shaka.util.StreamUtils.getCorrectVideoCodecs_(g);h=shaka.util.ManifestParserUtils.guessCodecs(f.AUDIO,h);h=shaka.util.MimeUtils.getFullOrConvertedType(e.mimeType,h,f.AUDIO);c.audio={contentType:h,channels:2,bitrate:a.bandwidth||
1,samplerate:1,spatialRendering:!1}}g=shaka.util.StreamUtils.getCorrectVideoCodecs_(g);g=shaka.util.MimeUtils.getFullOrConvertedType(e.mimeType,g,f.VIDEO);c.video={contentType:g,width:e.width||64,height:e.height||64,bitrate:e.bandwidth||a.bandwidth||1,framerate:e.frameRate||1};if(e.hdr)switch(e.hdr){case "SDR":c.video.transferFunction="srgb";break;case "PQ":c.video.transferFunction="pq";break;case "HLG":c.video.transferFunction="hlg"}}d&&(g=shaka.util.StreamUtils.getCorrectAudioCodecs_(d.codecs),
f=shaka.util.MimeUtils.getFullOrConvertedType(d.mimeType,g,f.AUDIO),c.audio={contentType:f,channels:d.channelsCount||2,bitrate:d.bandwidth||a.bandwidth||1,samplerate:d.audioSamplingRate||1,spatialRendering:d.spatialAudio});g=(a.video?a.video.drmInfos:[]).concat(a.audio?a.audio.drmInfos:[]);if(!g.length)return[c];a=[];f=new Map;g=$jscomp.makeIterator(g);for(var k=g.next();!k.done;k=g.next())h=k.value,f.get(h.keySystem)||f.set(h.keySystem,[]),f.get(h.keySystem).push(h);g=b?"required":"optional";b=b?
["persistent-license"]:["temporary"];h=$jscomp.makeIterator(f.keys());for(var l=h.next();!l.done;l=h.next()){var m=l.value;l=Object.assign({},c);var n=f.get(m);m={keySystem:m,initDataType:"cenc",persistentState:g,distinctiveIdentifier:"optional",sessionTypes:b};n=$jscomp.makeIterator(n);for(k=n.next();!k.done;k=n.next()){k=k.value;if(k.initData&&k.initData.length){for(var p=new Set,q=$jscomp.makeIterator(k.initData),r=q.next();!r.done;r=q.next())p.add(r.value.initDataType);1<p.size&&shaka.log.v2("DrmInfo contains more than one initDataType,",
"and we use the initDataType of the first initData.",k);m.initDataType=k.initData[0].initDataType}k.distinctiveIdentifierRequired&&(m.distinctiveIdentifier="required");k.persistentStateRequired&&(m.persistentState="required");k.sessionType&&(m.sessionTypes=[k.sessionType]);d&&(""!=k.audioRobustness?m.audio?m.audio.robustness=m.audio.robustness||k.audioRobustness:m.audio={robustness:k.audioRobustness}:m.audio||(m.audio={}));e&&(""!=k.videoRobustness?m.video?m.video.robustness=m.video.robustness||k.videoRobustness:
m.video={robustness:k.videoRobustness}:m.video||(m.video={}))}l.keySystemConfiguration=m;a.push(l)}return a};shaka.util.StreamUtils.getCorrectAudioCodecs_=function(a){return shaka.util.Platform.isTizen()?"ac-3"==a.toLowerCase()?"ec-3":a:a};
shaka.util.StreamUtils.getCorrectVideoCodecs_=function(a){if(a.includes("avc1")){var b=a.split(".");if(3==b.length)return a=b.shift()+".",a+=parseInt(b.shift(),10).toString(16),a+=("000"+parseInt(b.shift(),10).toString(16)).slice(-4)}else if("vp9"==a)return"vp09.00.41.08";return a};
shaka.util.StreamUtils.filterManifestByCurrentVariant=function(a,b){var c=shaka.util.StreamUtils;b.variants=b.variants.filter(function(d){var e=d.audio;d=d.video;return e&&a&&a.audio&&!c.areStreamsCompatible_(e,a.audio)?(shaka.log.debug("Droping variant - not compatible with active audio","active audio",c.getStreamSummaryString_(a.audio),"variant.audio",c.getStreamSummaryString_(e)),!1):d&&a&&a.video&&!c.areStreamsCompatible_(d,a.video)?(shaka.log.debug("Droping variant - not compatible with active video",
"active video",c.getStreamSummaryString_(a.video),"variant.video",c.getStreamSummaryString_(d)),!1):!0})};shaka.util.StreamUtils.filterTextStreams_=function(a){a.textStreams=a.textStreams.filter(function(b){var c=shaka.util.MimeUtils.getFullType(b.mimeType,b.codecs);(c=shaka.text.TextEngine.isTypeSupported(c))||shaka.log.debug("Dropping text stream. Is not supported by the platform.",b);return c})};
shaka.util.StreamUtils.filterImageStreams_=function(a){var b,c,d,e,f,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){switch(l.nextAddress){case 1:b=[],c=$jscomp.makeIterator(a.imageStreams),d=c.next();case 2:if(d.done){l.jumpTo(4);break}e=d.value;f=e.mimeType;if(shaka.util.StreamUtils.supportedImageMimeTypes_.has(f)){l.jumpTo(5);break}g=shaka.util.StreamUtils.minImage_.get(f);if(!g){shaka.util.StreamUtils.supportedImageMimeTypes_.set(f,!1);l.jumpTo(5);break}return l.yield(shaka.util.StreamUtils.isImageSupported_(g),
7);case 7:h=l.yieldResult,shaka.util.StreamUtils.supportedImageMimeTypes_.set(f,h);case 5:(k=shaka.util.StreamUtils.supportedImageMimeTypes_.get(f))?b.push(e):shaka.log.debug("Dropping image stream. Is not supported by the platform.",e);d=c.next();l.jumpTo(2);break;case 4:a.imageStreams=b,l.jumpToEnd()}})};
shaka.util.StreamUtils.isImageSupported_=function(a){return new Promise(function(b){var c=new Image;c.src=a;"decode"in c?c.decode().then(function(){b(!0)}).catch(function(){b(!1)}):c.onload=c.onerror=function(){b(2===c.height)}})};shaka.util.StreamUtils.areStreamsCompatible_=function(a,b){return a.mimeType!=b.mimeType||a.codecs.split(".")[0]!=b.codecs.split(".")[0]?!1:!0};
shaka.util.StreamUtils.variantToTrack=function(a){var b=a.audio,c=a.video,d=b?b.mimeType:null,e=c?c.mimeType:null,f=b?b.codecs:null,g=c?c.codecs:null,h=[];g&&h.push(g);f&&h.push(f);var k=[];c&&k.push(c.mimeType);b&&k.push(b.mimeType);k=k[0]||null;var l=[];b&&l.push(b.kind);c&&l.push(c.kind);l=l[0]||null;var m=new Set;if(b)for(var n=$jscomp.makeIterator(b.roles),p=n.next();!p.done;p=n.next())m.add(p.value);if(c)for(n=$jscomp.makeIterator(c.roles),p=n.next();!p.done;p=n.next())m.add(p.value);a={id:a.id,
active:!1,type:"variant",bandwidth:a.bandwidth,language:a.language,label:null,kind:l,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,mimeType:k,audioMimeType:d,videoMimeType:e,codecs:h.join(", "),audioCodec:f,videoCodec:g,primary:a.primary,roles:Array.from(m),audioRoles:null,forced:!1,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,
originalImageId:null};c&&(a.videoId=c.id,a.originalVideoId=c.originalId,a.width=c.width||null,a.height=c.height||null,a.frameRate=c.frameRate||null,a.pixelAspectRatio=c.pixelAspectRatio||null,a.videoBandwidth=c.bandwidth||null);b&&(a.audioId=b.id,a.originalAudioId=b.originalId,a.channelsCount=b.channelsCount,a.audioSamplingRate=b.audioSamplingRate,a.audioBandwidth=b.bandwidth||null,a.spatialAudio=b.spatialAudio,a.label=b.label,a.audioRoles=b.roles);return a};
shaka.util.StreamUtils.textStreamToTrack=function(a){return{id:a.id,active:!1,type:shaka.util.ManifestParserUtils.ContentType.TEXT,bandwidth:0,language:a.language,label:a.label,kind:a.kind||null,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,mimeType:a.mimeType,audioMimeType:null,videoMimeType:null,codecs:a.codecs||null,audioCodec:null,videoCodec:null,primary:a.primary,roles:a.roles,audioRoles:null,forced:a.forced,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,
spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:a.originalId,originalImageId:null}};
shaka.util.StreamUtils.imageStreamToTrack=function(a){var b=shaka.util.ManifestParserUtils.ContentType,c=a.width||null,d=a.height||null,e=null;a.segmentIndex&&(e=a.segmentIndex.get(0));var f=a.tilesLayout;e&&(f=e.getTilesLayout()||f);f&&null!=c&&(c/=Number(f.split("x")[0]));f&&null!=d&&(d/=Number(f.split("x")[1]));return{id:a.id,active:!1,type:b.IMAGE,bandwidth:a.bandwidth||0,language:"",label:null,kind:null,width:c,height:d,frameRate:null,pixelAspectRatio:null,hdr:null,mimeType:a.mimeType,audioMimeType:null,
videoMimeType:null,codecs:null,audioCodec:null,videoCodec:null,primary:!1,roles:[],audioRoles:null,forced:!1,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:f||null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:a.originalId}};shaka.util.StreamUtils.html5TrackId=function(a){a.__shaka_id||(a.__shaka_id=shaka.util.StreamUtils.nextTrackId_++);return a.__shaka_id};
shaka.util.StreamUtils.html5TextTrackToTrack=function(a){var b=shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE,c=shaka.util.StreamUtils.html5TrackToGenericShakaTrack_(a);c.active="disabled"!=a.mode;c.type="text";c.originalTextId=a.id;"captions"==a.kind&&(c.mimeType=b);a.kind&&(c.roles=[a.kind]);"forced"==a.kind&&(c.forced=!0);return c};
shaka.util.StreamUtils.html5AudioTrackToTrack=function(a){var b=shaka.util.StreamUtils.html5TrackToGenericShakaTrack_(a);b.active=a.enabled;b.type="variant";b.originalAudioId=a.id;"main"==a.kind&&(b.primary=!0);a.kind&&(b.roles=[a.kind],b.audioRoles=[a.kind],b.label=a.label);return b};
shaka.util.StreamUtils.html5TrackToGenericShakaTrack_=function(a){return{id:shaka.util.StreamUtils.html5TrackId(a),active:!1,type:"",bandwidth:0,language:shaka.util.LanguageUtils.normalize(a.language),label:a.label,kind:a.kind,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,mimeType:null,audioMimeType:null,videoMimeType:null,codecs:null,audioCodec:null,videoCodec:null,primary:!1,roles:[],forced:!1,audioRoles:null,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,
spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:null}};shaka.util.StreamUtils.isPlayable=function(a){return a.allowedByApplication&&a.allowedByKeySystem};shaka.util.StreamUtils.getPlayableVariants=function(a){return a.filter(function(b){return shaka.util.StreamUtils.isPlayable(b)})};
shaka.util.StreamUtils.filterVariantsByAudioChannelCount=function(a,b){var c=a.filter(function(g){return g.audio&&g.audio.channelsCount}),d=new Map;c=$jscomp.makeIterator(c);for(var e=c.next();!e.done;e=c.next()){e=e.value;var f=e.audio.channelsCount;goog.asserts.assert(null!=f,"Must have count after filtering!");d.has(f)||d.set(f,[]);d.get(f).push(e)}c=Array.from(d.keys());if(0==c.length)return a;a=c.filter(function(g){return g<=b});return a.length?d.get(Math.max.apply(Math,$jscomp.arrayFromIterable(a))):
d.get(Math.min.apply(Math,$jscomp.arrayFromIterable(c)))};
shaka.util.StreamUtils.filterStreamsByLanguageAndRole=function(a,b,c,d){var e=shaka.util.LanguageUtils,f=a,g=a.filter(function(l){return l.primary});g.length&&(f=g);var h=f.length?f[0].language:"";f=f.filter(function(l){return l.language==h});if(b){var k=e.findClosestLocale(e.normalize(b),a.map(function(l){return l.language}));k&&(f=a.filter(function(l){return e.normalize(l.language)==k}))}f=f.filter(function(l){return l.forced==d});if(c){a=shaka.util.StreamUtils.filterTextStreamsByRole_(f,c);if(a.length)return a;
shaka.log.warning("No exact match for the text role could be found.")}else if(a=f.filter(function(l){return 0==l.roles.length}),a.length)return a;a=f.map(function(l){return l.roles}).reduce(shaka.util.Functional.collapseArrays,[]);return a.length?shaka.util.StreamUtils.filterTextStreamsByRole_(f,a[0]):f};shaka.util.StreamUtils.filterTextStreamsByRole_=function(a,b){return a.filter(function(c){return c.roles.includes(b)})};shaka.util.StreamUtils.isAudio=function(a){return a.type==shaka.util.ManifestParserUtils.ContentType.AUDIO};
shaka.util.StreamUtils.isVideo=function(a){return a.type==shaka.util.ManifestParserUtils.ContentType.VIDEO};shaka.util.StreamUtils.getVariantStreams=function(a){var b=[];a.audio&&b.push(a.audio);a.video&&b.push(a.video);return b};shaka.util.StreamUtils.getVariantSummaryString_=function(a){var b=[];a.audio&&b.push(shaka.util.StreamUtils.getStreamSummaryString_(a.audio));a.video&&b.push(shaka.util.StreamUtils.getStreamSummaryString_(a.video));return b.join(", ")};
shaka.util.StreamUtils.getStreamSummaryString_=function(a){return shaka.util.StreamUtils.isAudio(a)?"type=audio codecs="+a.codecs+" bandwidth="+a.bandwidth+" channelsCount="+a.channelsCount+" audioSamplingRate="+a.audioSamplingRate:shaka.util.StreamUtils.isVideo(a)?"type=video codecs="+a.codecs+" bandwidth="+a.bandwidth+" frameRate="+a.frameRate+" width="+a.width+" height="+a.height:"unexpected stream type"};shaka.util.StreamUtils.nextTrackId_=0;
shaka.util.StreamUtils.DecodingAttributes={SMOOTH:"smooth",POWER:"powerEfficient",BANDWIDTH:"bandwidth"};shaka.util.StreamUtils.supportedImageMimeTypes_=(new Map).set("image/svg+xml",!0).set("image/png",!0).set("image/jpeg",!0).set("image/jpg",!0);shaka.util.StreamUtils.minWebPImage_="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";shaka.util.StreamUtils.minAvifImage_="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=";
shaka.util.StreamUtils.minImage_=(new Map).set("image/webp",shaka.util.StreamUtils.minWebPImage_).set("image/avif",shaka.util.StreamUtils.minAvifImage_);shaka.abr.SimpleAbrManager=function(){var a=this;this.switch_=null;this.enabled_=!1;this.bandwidthEstimator_=new shaka.abr.EwmaBandwidthEstimator;navigator.connection&&navigator.connection.addEventListener("change",function(){if(a.config_.useNetworkInformation&&a.enabled_){a.bandwidthEstimator_=new shaka.abr.EwmaBandwidthEstimator;a.config_&&a.bandwidthEstimator_.configure(a.config_.advanced);var b=a.chooseVariant();b&&a.switch_(b)}});this.variants_=[];this.playbackRate_=1;this.startupComplete_=!1;
this.resizeObserver_=this.mediaElement_=this.config_=this.lastTimeChosenMs_=null;this.resizeObserverTimer_=new shaka.util.Timer(function(){if(a.config_.restrictToElementSize){var b=a.chooseVariant();b&&a.switch_(b)}})};shaka.abr.SimpleAbrManager.prototype.stop=function(){this.switch_=null;this.enabled_=!1;this.variants_=[];this.playbackRate_=1;this.mediaElement_=this.lastTimeChosenMs_=null;this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null);this.resizeObserverTimer_.stop()};
shaka.abr.SimpleAbrManager.prototype.init=function(a){this.switch_=a};
shaka.abr.SimpleAbrManager.prototype.chooseVariant=function(){var a=shaka.abr.SimpleAbrManager,b=Infinity,c=Infinity;this.config_.restrictToScreenSize&&(c=this.config_.ignoreDevicePixelRatio?1:window.devicePixelRatio,b=window.screen.height*c,c*=window.screen.width);this.resizeObserver_&&this.config_.restrictToElementSize&&(c=this.config_.ignoreDevicePixelRatio?1:window.devicePixelRatio,b=this.mediaElement_.clientWidth*c,c*=this.mediaElement_.clientHeight);b=a.filterAndSortVariants_(this.config_.restrictions,
this.variants_,b,c);c=this.getDefaultBandwidth_();c=this.bandwidthEstimator_.getBandwidthEstimate(c);this.variants_.length&&!b.length&&(shaka.log.warning("No variants met the ABR restrictions. Choosing a variant by lowest bandwidth."),b=a.filterAndSortVariants_(null,this.variants_,Infinity,Infinity),b=[b[0]]);a=b[0]||null;for(var d=0;d<b.length;d++){for(var e=b[d],f=isNaN(this.playbackRate_)?1:Math.abs(this.playbackRate_),g=f*e.bandwidth,h=g/this.config_.bandwidthDowngradeTarget,k={bandwidth:Infinity},
l=d+1;l<b.length;l++)if(e.bandwidth!=b[l].bandwidth){k=b[l];break}f=f*k.bandwidth/this.config_.bandwidthUpgradeTarget;shaka.log.v2("Bandwidth ranges:",(g/1E6).toFixed(3),(h/1E6).toFixed(3),(f/1E6).toFixed(3));c>=h&&c<=f&&a.bandwidth!=e.bandwidth&&(a=e)}this.lastTimeChosenMs_=Date.now();return a};shaka.abr.SimpleAbrManager.prototype.enable=function(){this.enabled_=!0};shaka.abr.SimpleAbrManager.prototype.disable=function(){this.enabled_=!1};
shaka.abr.SimpleAbrManager.prototype.segmentDownloaded=function(a,b){shaka.log.v2("Segment downloaded:","deltaTimeMs="+a,"numBytes="+b,"lastTimeChosenMs="+this.lastTimeChosenMs_,"enabled="+this.enabled_);goog.asserts.assert(0<=a,"expected a non-negative duration");this.bandwidthEstimator_.sample(a,b);null!=this.lastTimeChosenMs_&&this.enabled_&&this.suggestStreams_()};shaka.abr.SimpleAbrManager.prototype.getBandwidthEstimate=function(){var a=this.getDefaultBandwidth_();return this.bandwidthEstimator_.getBandwidthEstimate(a)};
shaka.abr.SimpleAbrManager.prototype.setVariants=function(a){this.variants_=a};shaka.abr.SimpleAbrManager.prototype.playbackRateChanged=function(a){this.playbackRate_=a};
shaka.abr.SimpleAbrManager.prototype.setMediaElement=function(a){var b=this;this.mediaElement_=a;this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null);this.mediaElement_&&"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver(function(){b.resizeObserverTimer_.tickAfter(shaka.abr.SimpleAbrManager.RESIZE_OBSERVER_BATCH_TIME)}),this.resizeObserver_.observe(this.mediaElement_))};
shaka.abr.SimpleAbrManager.prototype.configure=function(a){this.config_=a;this.bandwidthEstimator_&&this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced)};
shaka.abr.SimpleAbrManager.prototype.suggestStreams_=function(){shaka.log.v2("Suggesting Streams...");goog.asserts.assert(null!=this.lastTimeChosenMs_,"lastTimeChosenMs_ should not be null");if(!this.startupComplete_){if(!this.bandwidthEstimator_.hasGoodEstimate()){shaka.log.v2("Still waiting for a good estimate...");return}this.startupComplete_=!0}else if(Date.now()-this.lastTimeChosenMs_<1E3*this.config_.switchInterval){shaka.log.v2("Still within switch interval...");return}var a=this.chooseVariant(),
b=this.getDefaultBandwidth_();b=this.bandwidthEstimator_.getBandwidthEstimate(b);b=Math.round(b/1E3);a&&(shaka.log.debug("Calling switch_(), bandwidth="+b+" kbps"),this.switch_(a))};shaka.abr.SimpleAbrManager.prototype.getDefaultBandwidth_=function(){var a=this.config_.defaultBandwidthEstimate;navigator.connection&&navigator.connection.downlink&&this.config_.useNetworkInformation&&(a=1E6*navigator.connection.downlink);return a};
shaka.abr.SimpleAbrManager.filterAndSortVariants_=function(a,b,c,d){a&&(b=b.filter(function(e){goog.asserts.assert(a,"Restrictions should exist!");return shaka.util.StreamUtils.meetsRestrictions(e,a,{width:d,height:c})}));return b.sort(function(e,f){return e.bandwidth-f.bandwidth})};goog.exportSymbol("shaka.abr.SimpleAbrManager",shaka.abr.SimpleAbrManager);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"configure",shaka.abr.SimpleAbrManager.prototype.configure);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"setMediaElement",shaka.abr.SimpleAbrManager.prototype.setMediaElement);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"playbackRateChanged",shaka.abr.SimpleAbrManager.prototype.playbackRateChanged);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"setVariants",shaka.abr.SimpleAbrManager.prototype.setVariants);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"getBandwidthEstimate",shaka.abr.SimpleAbrManager.prototype.getBandwidthEstimate);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"segmentDownloaded",shaka.abr.SimpleAbrManager.prototype.segmentDownloaded);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"disable",shaka.abr.SimpleAbrManager.prototype.disable);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"enable",shaka.abr.SimpleAbrManager.prototype.enable);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"chooseVariant",shaka.abr.SimpleAbrManager.prototype.chooseVariant);
goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"init",shaka.abr.SimpleAbrManager.prototype.init);goog.exportProperty(shaka.abr.SimpleAbrManager.prototype,"stop",shaka.abr.SimpleAbrManager.prototype.stop);shaka.abr.SimpleAbrManager.RESIZE_OBSERVER_BATCH_TIME=1;shaka.deprecate={};shaka.deprecate.Version=function(a,b){this.major_=a;this.minor_=b};shaka.deprecate.Version.prototype.major=function(){return this.major_};shaka.deprecate.Version.prototype.minor=function(){return this.minor_};shaka.deprecate.Version.prototype.compareTo=function(a){var b=this.minor_-a.minor_;return this.major_-a.major_||b};shaka.deprecate.Version.prototype.toString=function(){return"v"+this.major_+"."+this.minor_};
shaka.deprecate.Version.parse=function(a){a=a.substring(1).split(".",2);return new shaka.deprecate.Version(Number(a[0]),Number(a[1]))};shaka.deprecate.Enforcer=function(a,b,c){this.libraryVersion_=a;this.onPending_=b;this.onExpired_=c};shaka.deprecate.Enforcer.prototype.enforce=function(a,b,c){(0<a.compareTo(this.libraryVersion_)?this.onPending_:this.onExpired_)(this.libraryVersion_,a,b,c)};shaka.Deprecate=function(){};shaka.Deprecate.init=function(a){goog.asserts.assert(null==shaka.Deprecate.enforcer_,"Deprecate.init should only be called once.");shaka.Deprecate.enforcer_=new shaka.deprecate.Enforcer(shaka.deprecate.Version.parse(a),shaka.Deprecate.onPending_,shaka.Deprecate.onExpired_)};
shaka.Deprecate.deprecateFeature=function(a,b,c){var d=shaka.Deprecate.enforcer_;goog.asserts.assert(d,"Missing deprecation enforcer. Was |init| called?");a=new shaka.deprecate.Version(a,0);d.enforce(a,b,c)};shaka.Deprecate.onPending_=function(a,b,c,d){shaka.log.alwaysWarn([c,"has been deprecated and will be removed in",b,". We are currently at version",a,". Additional information:",d].join(" "))};
shaka.Deprecate.onExpired_=function(a,b,c,d){a=[c,"has been deprecated and has been removed in",b,". We are now at version",a,". Additional information:",d].join("");shaka.log.alwaysError(a);goog.asserts.assert(!1,a)};shaka.Deprecate.enforcer_=null;shaka.config={};shaka.config.AutoShowText={NEVER:0,ALWAYS:1,IF_PREFERRED_TEXT_LANGUAGE:2,IF_SUBTITLES_MAY_BE_NEEDED:3};goog.exportSymbol("shaka.config.AutoShowText",shaka.config.AutoShowText);shaka.media.AdaptationSet=function(a,b){this.root_=a;this.variants_=new Set([a]);b=b||[];a=$jscomp.makeIterator(b);for(b=a.next();!b.done;b=a.next())this.add(b.value)};shaka.media.AdaptationSet.prototype.add=function(a){if(this.canInclude(a))return this.variants_.add(a),!0;shaka.log.warning("Rejecting variant - not compatible with root.");return!1};shaka.media.AdaptationSet.prototype.canInclude=function(a){return shaka.media.AdaptationSet.areAdaptable(this.root_,a)};
shaka.media.AdaptationSet.areAdaptable=function(a,b){var c=shaka.media.AdaptationSet;if(!!a.audio!=!!b.audio||!!a.video!=!!b.video||a.language!=b.language)return!1;goog.asserts.assert(!!a.audio==!!b.audio,"Both should either have audio or not have audio.");if(a.audio&&b.audio&&!c.areAudiosCompatible_(a.audio,b.audio))return!1;goog.asserts.assert(!!a.video==!!b.video,"Both should either have video or not have video.");return a.video&&b.video&&!c.areVideosCompatible_(a.video,b.video)?!1:!0};
shaka.media.AdaptationSet.prototype.values=function(){return this.variants_.values()};shaka.media.AdaptationSet.areAudiosCompatible_=function(a,b){var c=shaka.media.AdaptationSet;return(!a.channelsCount||!b.channelsCount||2<a.channelsCount||2<b.channelsCount)&&a.channelsCount!=b.channelsCount||!c.canTransitionBetween_(a,b)||!c.areRolesEqual_(a.roles,b.roles)?!1:!0};
shaka.media.AdaptationSet.areVideosCompatible_=function(a,b){var c=shaka.media.AdaptationSet;return c.canTransitionBetween_(a,b)&&c.areRolesEqual_(a.roles,b.roles)?!0:!1};
shaka.media.AdaptationSet.canTransitionBetween_=function(a,b){if(a.mimeType!=b.mimeType)return!1;a=shaka.util.MimeUtils.splitCodecs(a.codecs).map(function(d){return shaka.util.MimeUtils.getCodecBase(d)});b=shaka.util.MimeUtils.splitCodecs(b.codecs).map(function(d){return shaka.util.MimeUtils.getCodecBase(d)});if(a.length!=b.length)return!1;a.sort();b.sort();for(var c=0;c<a.length;c++)if(a[c]!=b[c])return!1;return!0};
shaka.media.AdaptationSet.areRolesEqual_=function(a,b){a=new Set(a);b=new Set(b);a.delete("main");b.delete("main");if(a.size!=b.size)return!1;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())if(!b.has(c.value))return!1;return!0};shaka.media.AdaptationSetCriteria=function(){};shaka.media.AdaptationSetCriteria.prototype.create=function(a){};shaka.media.ExampleBasedCriteria=function(a){this.example_=a;this.fallback_=new shaka.media.PreferenceBasedCriteria(a.language,"",a.audio&&a.audio.channelsCount?a.audio.channelsCount:0,"")};
shaka.media.ExampleBasedCriteria.prototype.create=function(a){var b=this,c=a.filter(function(d){return shaka.media.AdaptationSet.areAdaptable(b.example_,d)});return c.length?new shaka.media.AdaptationSet(c[0],c):this.fallback_.create(a)};shaka.media.PreferenceBasedCriteria=function(a,b,c,d){this.language_=a;this.role_=b;this.channelCount_=c;this.label_=void 0===d?"":d};
shaka.media.PreferenceBasedCriteria.prototype.create=function(a){var b=shaka.media.PreferenceBasedCriteria,c=shaka.util.StreamUtils,d=[];d=b.filterByLanguage_(a,this.language_);var e=a.filter(function(f){return f.primary});d=d.length?d:e.length?e:a;a=b.filterVariantsByRole_(d,this.role_);a.length?d=a:shaka.log.warning("No exact match for variant role could be found.");this.channelCount_&&(c=c.filterVariantsByAudioChannelCount(d,this.channelCount_),c.length?d=c:shaka.log.warning("No exact match for the channel count could be found."));
this.label_&&(b=b.filterVariantsByLabel_(d,this.label_),b.length?d=b:shaka.log.warning("No exact match for variant label could be found."));b=new shaka.media.AdaptationSet(d[0]);d=$jscomp.makeIterator(d);for(c=d.next();!c.done;c=d.next())c=c.value,b.canInclude(c)&&b.add(c);return b};
shaka.media.PreferenceBasedCriteria.filterByLanguage_=function(a,b){var c=shaka.util.LanguageUtils;b=c.normalize(b);var d=c.findClosestLocale(b,a.map(function(e){return c.getLocaleForVariant(e)}));return d?a.filter(function(e){return d==c.getLocaleForVariant(e)}):[]};shaka.media.PreferenceBasedCriteria.filterVariantsByRole_=function(a,b){return a.filter(function(c){return c.audio?b?c.audio.roles.includes(b):0==c.audio.roles.length:!1})};
shaka.media.PreferenceBasedCriteria.filterVariantsByLabel_=function(a,b){return a.filter(function(c){if(!c.audio)return!1;c=c.audio.label.toLowerCase();var d=b.toLowerCase();return c==d})};shaka.media.BufferingObserver=function(a,b){var c=shaka.media.BufferingObserver.State;this.previousState_=c.SATISFIED;this.thresholds_=(new Map).set(c.SATISFIED,b).set(c.STARVING,a)};shaka.media.BufferingObserver.prototype.setThresholds=function(a,b){var c=shaka.media.BufferingObserver.State;this.thresholds_.set(c.SATISFIED,b).set(c.STARVING,a)};
shaka.media.BufferingObserver.prototype.update=function(a,b){var c=shaka.media.BufferingObserver.State,d=this.thresholds_.get(this.previousState_),e=this.previousState_;this.previousState_=a=b||a>=d?c.SATISFIED:c.STARVING;return e!=a};shaka.media.BufferingObserver.prototype.setState=function(a){this.previousState_=a};shaka.media.BufferingObserver.prototype.getState=function(){return this.previousState_};shaka.media.BufferingObserver.State={STARVING:0,SATISFIED:1};shaka.net={};
shaka.net.Backoff=function(a,b){b=void 0===b?!1:b;var c=shaka.net.Backoff.defaultRetryParameters();this.maxAttempts_=null==a.maxAttempts?c.maxAttempts:a.maxAttempts;goog.asserts.assert(1<=this.maxAttempts_,"maxAttempts should be >= 1");this.baseDelay_=null==a.baseDelay?c.baseDelay:a.baseDelay;goog.asserts.assert(0<=this.baseDelay_,"baseDelay should be >= 0");this.fuzzFactor_=null==a.fuzzFactor?c.fuzzFactor:a.fuzzFactor;goog.asserts.assert(0<=this.fuzzFactor_,"fuzzFactor should be >= 0");this.backoffFactor_=
null==a.backoffFactor?c.backoffFactor:a.backoffFactor;goog.asserts.assert(0<=this.backoffFactor_,"backoffFactor should be >= 0");this.numAttempts_=0;this.nextUnfuzzedDelay_=this.baseDelay_;if(this.autoReset_=b)goog.asserts.assert(2<=this.maxAttempts_,"maxAttempts must be >= 2 for autoReset == true"),this.numAttempts_=1};
shaka.net.Backoff.prototype.attempt=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress){if(a.numAttempts_>=a.maxAttempts_)if(a.autoReset_)a.reset_();else throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.ATTEMPTS_EXHAUSTED);b=a.numAttempts_;a.numAttempts_++;if(0==b)return goog.asserts.assert(!a.autoReset_,"Failed to delay with auto-reset!"),d.return();c=shaka.net.Backoff.fuzz_(a.nextUnfuzzedDelay_,
a.fuzzFactor_);return d.yield(new Promise(function(e){shaka.net.Backoff.defer(c,e)}),2)}a.nextUnfuzzedDelay_*=a.backoffFactor_;d.jumpToEnd()})};shaka.net.Backoff.defaultRetryParameters=function(){return{maxAttempts:2,baseDelay:1E3,backoffFactor:2,fuzzFactor:.5,timeout:3E4,stallTimeout:5E3,connectionTimeout:1E4}};shaka.net.Backoff.fuzz_=function(a,b){return a*(1+(2*Math.random()-1)*b)};
shaka.net.Backoff.prototype.reset_=function(){goog.asserts.assert(this.autoReset_,"Should only be used for auto-reset!");this.numAttempts_=1;this.nextUnfuzzedDelay_=this.baseDelay_};shaka.net.Backoff.defer=function(a,b){(new shaka.util.Timer(b)).tickAfter(a/1E3)};shaka.util.AbortableOperation=function(a,b){this.promise=a;this.onAbort_=b;this.aborted_=!1};shaka.util.AbortableOperation.failed=function(a){return new shaka.util.AbortableOperation(Promise.reject(a),function(){return Promise.resolve()})};shaka.util.AbortableOperation.aborted=function(){var a=Promise.reject(shaka.util.AbortableOperation.abortError());a.catch(function(){});return new shaka.util.AbortableOperation(a,function(){return Promise.resolve()})};
shaka.util.AbortableOperation.abortError=function(){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED)};shaka.util.AbortableOperation.completed=function(a){return new shaka.util.AbortableOperation(Promise.resolve(a),function(){return Promise.resolve()})};shaka.util.AbortableOperation.notAbortable=function(a){return new shaka.util.AbortableOperation(a,function(){return a.catch(function(){})})};
shaka.util.AbortableOperation.prototype.abort=function(){this.aborted_=!0;return this.onAbort_()};shaka.util.AbortableOperation.all=function(a){return new shaka.util.AbortableOperation(Promise.all(a.map(function(b){return b.promise})),function(){return Promise.all(a.map(function(b){return b.abort()}))})};shaka.util.AbortableOperation.prototype.finally=function(a){this.promise.then(function(b){return a(!0)},function(b){return a(!1)});return this};
shaka.util.AbortableOperation.prototype.chain=function(a,b){var c=this,d=new shaka.util.PublicPromise,e=shaka.util.AbortableOperation.abortError(),f=function(){d.reject(e);return c.abort()},g=function(h){return function(k){if(c.aborted_&&h)d.reject(e);else{var l=h?a:b;l?f=shaka.util.AbortableOperation.wrapChainCallback_(l,k,d):(h?d.resolve:d.reject)(k)}}};this.promise.then(g(!0),g(!1));return new shaka.util.AbortableOperation(d,function(){return f()})};
shaka.util.AbortableOperation.wrapChainCallback_=function(a,b,c){try{var d=a(b);if(d&&d.promise&&d.abort)return c.resolve(d.promise),function(){return d.abort()};c.resolve(d);return function(){return Promise.resolve(d).then(function(){},function(){})}}catch(e){return c.reject(e),function(){return Promise.resolve()}}};goog.exportSymbol("shaka.util.AbortableOperation",shaka.util.AbortableOperation);goog.exportProperty(shaka.util.AbortableOperation.prototype,"chain",shaka.util.AbortableOperation.prototype.chain);
goog.exportProperty(shaka.util.AbortableOperation.prototype,"finally",shaka.util.AbortableOperation.prototype.finally);goog.exportProperty(shaka.util.AbortableOperation,"all",shaka.util.AbortableOperation.all);goog.exportProperty(shaka.util.AbortableOperation.prototype,"abort",shaka.util.AbortableOperation.prototype.abort);goog.exportProperty(shaka.util.AbortableOperation,"notAbortable",shaka.util.AbortableOperation.notAbortable);goog.exportProperty(shaka.util.AbortableOperation,"completed",shaka.util.AbortableOperation.completed);
goog.exportProperty(shaka.util.AbortableOperation,"aborted",shaka.util.AbortableOperation.aborted);goog.exportProperty(shaka.util.AbortableOperation,"failed",shaka.util.AbortableOperation.failed);shaka.util.FakeEvent=function(a,b){if(b)if(b instanceof Map)for(var c=$jscomp.makeIterator(b.keys()),d=c.next();!d.done;d=c.next())d=d.value,Object.defineProperty(this,d,{value:b.get(d),writable:!0,enumerable:!0});else for(c in b=shaka.util.FakeEvent.recastDictAsObject_(b),b)Object.defineProperty(this,c,{value:b[c],writable:!0,enumerable:!0});this.defaultPrevented=this.cancelable=this.bubbles=!1;this.timeStamp=window.performance&&window.performance.now?window.performance.now():Date.now();this.type=
a;this.isTrusted=!1;this.target=this.currentTarget=null;this.stopped=!1};shaka.util.FakeEvent.fromRealEvent=function(a){var b=new shaka.util.FakeEvent(a.type),c;for(c in a)Object.defineProperty(b,c,{value:a[c],writable:!0,enumerable:!0});return b};shaka.util.FakeEvent.recastDictAsObject_=function(a){goog.asserts.assert(!(a instanceof Map),"dict should not be a map");return a};shaka.util.FakeEvent.prototype.preventDefault=function(){this.cancelable&&(this.defaultPrevented=!0)};
shaka.util.FakeEvent.prototype.stopImmediatePropagation=function(){this.stopped=!0};shaka.util.FakeEvent.prototype.stopPropagation=function(){};goog.exportSymbol("shaka.util.FakeEvent",shaka.util.FakeEvent);
shaka.util.FakeEvent.EventName={AbrStatusChanged:"abrstatuschanged",Adaptation:"adaptation",Buffering:"buffering",DownloadFailed:"downloadfailed",DownloadHeadersReceived:"downloadheadersreceived",DrmSessionUpdate:"drmsessionupdate",Emsg:"emsg",Prft:"prft",Error:"error",ExpirationUpdated:"expirationupdated",GapJumped:"gapjumped",Loaded:"loaded",Loading:"loading",ManifestParsed:"manifestparsed",MediaQualityChanged:"mediaqualitychanged",Metadata:"metadata",OnStateChange:"onstatechange",OnStateIdle:"onstateidle",
RateChange:"ratechange",SegmentAppended:"segmentappended",SessionDataEvent:"sessiondata",StallDetected:"stalldetected",Streaming:"streaming",TextChanged:"textchanged",TextTrackVisibility:"texttrackvisibility",TimelineRegionAdded:"timelineregionadded",TimelineRegionEnter:"timelineregionenter",TimelineRegionExit:"timelineregionexit",TracksChanged:"trackschanged",Unloading:"unloading",VariantChanged:"variantchanged"};shaka.util.IReleasable=function(){};shaka.util.IReleasable.prototype.release=function(){};shaka.util.FakeEventTarget=function(){this.listeners_=new shaka.util.MultiMap;this.dispatchTarget=this};shaka.util.FakeEventTarget.prototype.addEventListener=function(a,b,c){this.listeners_&&this.listeners_.push(a,b)};shaka.util.FakeEventTarget.prototype.listenToAllEvents=function(a){this.addEventListener(shaka.util.FakeEventTarget.ALL_EVENTS_,a)};shaka.util.FakeEventTarget.prototype.removeEventListener=function(a,b,c){this.listeners_&&this.listeners_.remove(a,b)};
shaka.util.FakeEventTarget.prototype.dispatchEvent=function(a){goog.asserts.assert(a instanceof shaka.util.FakeEvent,"FakeEventTarget can only dispatch FakeEvents!");if(!this.listeners_)return!0;var b=this.listeners_.get(a.type)||[],c=this.listeners_.get(shaka.util.FakeEventTarget.ALL_EVENTS_);c&&(b=b.concat(c));b=$jscomp.makeIterator(b);for(c=b.next();!c.done;c=b.next()){c=c.value;a.target=this.dispatchTarget;a.currentTarget=this.dispatchTarget;try{c.handleEvent?c.handleEvent(a):c.call(this,a)}catch(d){shaka.log.error("Uncaught exception in event handler",
d,d?d.message:null,d?d.stack:null)}if(a.stopped)break}return a.defaultPrevented};shaka.util.FakeEventTarget.prototype.release=function(){this.listeners_=null};shaka.util.FakeEventTarget.ALL_EVENTS_="All";shaka.util.ObjectUtils=function(){};shaka.util.ObjectUtils.cloneObject=function(a){var b=new Set,c=function(d){switch(typeof d){case "undefined":case "boolean":case "number":case "string":case "symbol":case "function":return d;default:if(!d||d.buffer&&d.buffer.constructor==ArrayBuffer)return d;if(b.has(d))return null;var e=d.constructor==Array;if(d.constructor!=Object&&!e)return null;b.add(d);var f=e?[]:{},g;for(g in d)f[g]=c(d[g]);e&&(f.length=d.length);return f}};return c(a)};
shaka.util.ObjectUtils.shallowCloneObject=function(a){var b={},c;for(c in a)b[c]=a[c];return b};shaka.util.OperationManager=function(){this.operations_=[]};shaka.util.OperationManager.prototype.manage=function(a){var b=this;this.operations_.push(a.finally(function(){shaka.util.ArrayUtils.remove(b.operations_,a)}))};shaka.util.OperationManager.prototype.destroy=function(){for(var a=[],b=$jscomp.makeIterator(this.operations_),c=b.next();!c.done;c=b.next())c=c.value,c.promise.catch(function(){}),a.push(c.abort());this.operations_=[];return Promise.all(a)};shaka.net.NetworkingEngine=function(a,b,c){shaka.util.FakeEventTarget.call(this);this.destroyed_=!1;this.operationManager_=new shaka.util.OperationManager;this.requestFilters_=new Set;this.responseFilters_=new Set;this.onProgressUpdated_=a||null;this.onHeadersReceived_=b||null;this.onDownloadFailed_=c||null;this.forceHTTPS_=!1};$jscomp.inherits(shaka.net.NetworkingEngine,shaka.util.FakeEventTarget);shaka.net.NetworkingEngine.prototype.setForceHTTPS=function(a){this.forceHTTPS_=a};
shaka.net.NetworkingEngine.registerScheme=function(a,b,c,d){d=void 0===d?!1:d;goog.asserts.assert(void 0==c||0<c,"explicit priority must be > 0");c=c||shaka.net.NetworkingEngine.PluginPriority.APPLICATION;var e=shaka.net.NetworkingEngine.schemes_[a];if(!e||c>=e.priority)shaka.net.NetworkingEngine.schemes_[a]={priority:c,plugin:b,progressSupport:d}};shaka.net.NetworkingEngine.unregisterScheme=function(a){delete shaka.net.NetworkingEngine.schemes_[a]};
shaka.net.NetworkingEngine.prototype.registerRequestFilter=function(a){this.requestFilters_.add(a)};shaka.net.NetworkingEngine.prototype.unregisterRequestFilter=function(a){this.requestFilters_.delete(a)};shaka.net.NetworkingEngine.prototype.clearAllRequestFilters=function(){this.requestFilters_.clear()};shaka.net.NetworkingEngine.prototype.registerResponseFilter=function(a){this.responseFilters_.add(a)};shaka.net.NetworkingEngine.prototype.unregisterResponseFilter=function(a){this.responseFilters_.delete(a)};
shaka.net.NetworkingEngine.prototype.clearAllResponseFilters=function(){this.responseFilters_.clear()};shaka.net.NetworkingEngine.defaultRetryParameters=function(){return shaka.net.Backoff.defaultRetryParameters()};shaka.net.NetworkingEngine.makeRequest=function(a,b,c){return{uris:a,method:"GET",body:null,headers:{},allowCrossSiteCredentials:!1,retryParameters:b,licenseRequestType:null,sessionId:null,drmInfo:null,initData:null,initDataType:null,streamDataCallback:void 0===c?null:c}};
shaka.net.NetworkingEngine.prototype.destroy=function(){this.destroyed_=!0;this.requestFilters_.clear();this.responseFilters_.clear();shaka.util.FakeEventTarget.prototype.release.call(this);return this.operationManager_.destroy()};
shaka.net.NetworkingEngine.prototype.request=function(a,b){var c=this,d=shaka.util.ObjectUtils,e=new shaka.net.NetworkingEngine.NumBytesRemainingClass;if(this.destroyed_)return d=Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED)),d.catch(function(){}),new shaka.net.NetworkingEngine.PendingRequest(d,function(){return Promise.resolve()},e);goog.asserts.assert(b.uris&&b.uris.length,"Request without URIs!");
b.method=b.method||"GET";b.headers=b.headers||{};b.retryParameters=b.retryParameters?d.cloneObject(b.retryParameters):shaka.net.NetworkingEngine.defaultRetryParameters();b.uris=d.cloneObject(b.uris);d=this.filterRequest_(a,b);var f=d.chain(function(){return c.makeRequestWithRetry_(a,b,e)}),g=f.chain(function(n){return c.filterResponse_(a,n)}),h=Date.now(),k=0;d.promise.then(function(){k=Date.now()-h},function(){});var l=0;f.promise.then(function(){l=Date.now()},function(){});var m=g.chain(function(n){var p=
Date.now()-l,q=n.response;q.timeMs+=k;q.timeMs+=p;if(!n.gotProgress&&c.onProgressUpdated_&&!q.fromCache&&a==shaka.net.NetworkingEngine.RequestType.SEGMENT)c.onProgressUpdated_(q.timeMs,q.data.byteLength);return q},function(n){n&&(goog.asserts.assert(n instanceof shaka.util.Error,"Wrong error type"),n.severity=shaka.util.Error.Severity.CRITICAL);throw n;});d=new shaka.net.NetworkingEngine.PendingRequest(m.promise,function(){return m.abort()},e);this.operationManager_.manage(d);return d};
shaka.net.NetworkingEngine.prototype.filterRequest_=function(a,b){for(var c=shaka.util.AbortableOperation.completed(void 0),d={},e=$jscomp.makeIterator(this.requestFilters_),f=e.next();!f.done;d={$jscomp$loop$prop$requestFilter$634:d.$jscomp$loop$prop$requestFilter$634},f=e.next())d.$jscomp$loop$prop$requestFilter$634=f.value,c=c.chain(function(g){return function(){b.body&&(b.body=shaka.util.BufferUtils.toArrayBuffer(b.body));return g.$jscomp$loop$prop$requestFilter$634(a,b)}}(d));return c.chain(void 0,
function(g){if(g instanceof shaka.util.Error&&g.code==shaka.util.Error.Code.OPERATION_ABORTED)throw g;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.REQUEST_FILTER_ERROR,g);})};shaka.net.NetworkingEngine.prototype.makeRequestWithRetry_=function(a,b,c){var d=new shaka.net.Backoff(b.retryParameters,!1);return this.send_(a,b,d,0,null,c)};
shaka.net.NetworkingEngine.prototype.send_=function(a,b,c,d,e,f){var g=this;this.forceHTTPS_&&(b.uris[d]=b.uris[d].replace("http://","https://"));var h=new goog.Uri(b.uris[d]),k=h.getScheme(),l=!1;k||(k=shaka.net.NetworkingEngine.getLocationProtocol_(),goog.asserts.assert(":"==k[k.length-1],"location.protocol expected to end with a colon!"),k=k.slice(0,-1),h.setScheme(k),b.uris[d]=h.toString());k=k.toLowerCase();var m=(k=shaka.net.NetworkingEngine.schemes_[k])?k.plugin:null;if(!m)return shaka.util.AbortableOperation.failed(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.UNSUPPORTED_SCHEME,h));var n=k.progressSupport,p=null,q=null,r=!1,w=!1,u;return shaka.util.AbortableOperation.notAbortable(c.attempt()).chain(function(){if(g.destroyed_)return shaka.util.AbortableOperation.aborted();u=Date.now();var v=shaka.net.NetworkingEngine.RequestType.SEGMENT,x=m(b.uris[d],b,a,function(A,z,B){p&&p.stop();q&&q.tickAfter(y/1E3);g.onProgressUpdated_&&a==v&&(g.onProgressUpdated_(A,z),l=!0,f.setBytes(B))},function(A){if(g.onHeadersReceived_)g.onHeadersReceived_(A,
b,a);w=!0});if(!n)return x;var t=b.retryParameters.connectionTimeout;t&&(p=new shaka.util.Timer(function(){r=!0;x.abort()}),p.tickAfter(t/1E3));var y=b.retryParameters.stallTimeout;y&&(q=new shaka.util.Timer(function(){r=!0;x.abort()}));return x}).chain(function(v){p&&p.stop();q&&q.stop();void 0==v.timeMs&&(v.timeMs=Date.now()-u);var x={response:v,gotProgress:l};if(!w&&g.onHeadersReceived_)g.onHeadersReceived_(v.headers,b,a);return x},function(v){p&&p.stop();q&&q.stop();if(g.onDownloadFailed_){var x=
null,t=0;v instanceof shaka.util.Error&&(x=v,v.code==shaka.util.Error.Code.BAD_HTTP_STATUS&&(t=v.data[1]));g.onDownloadFailed_(b,x,t,r)}if(g.destroyed_)return shaka.util.AbortableOperation.aborted();r&&(v=new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.TIMEOUT,b.uris[d],a));if(v instanceof shaka.util.Error){if(v.code==shaka.util.Error.Code.OPERATION_ABORTED)throw v;if(v.code==shaka.util.Error.Code.ATTEMPTS_EXHAUSTED)throw goog.asserts.assert(e,
"Should have last error"),e;if(v.severity==shaka.util.Error.Severity.RECOVERABLE)return x=(new Map).set("error",v),x=new shaka.util.FakeEvent("retry",x),g.dispatchEvent(x),d=(d+1)%b.uris.length,g.send_(a,b,c,d,v,f)}throw v;})};
shaka.net.NetworkingEngine.prototype.filterResponse_=function(a,b){for(var c=shaka.util.AbortableOperation.completed(void 0),d={},e=$jscomp.makeIterator(this.responseFilters_),f=e.next();!f.done;d={$jscomp$loop$prop$responseFilter$636:d.$jscomp$loop$prop$responseFilter$636},f=e.next())d.$jscomp$loop$prop$responseFilter$636=f.value,c=c.chain(function(g){return function(){var h=b.response;h.data&&(h.data=shaka.util.BufferUtils.toArrayBuffer(h.data));return g.$jscomp$loop$prop$responseFilter$636(a,h)}}(d));
return c.chain(function(){return b},function(g){var h=shaka.util.Error.Severity.CRITICAL;if(g instanceof shaka.util.Error){if(g.code==shaka.util.Error.Code.OPERATION_ABORTED)throw g;h=g.severity}throw new shaka.util.Error(h,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.RESPONSE_FILTER_ERROR,g);})};shaka.net.NetworkingEngine.getLocationProtocol_=function(){return location.protocol};goog.exportSymbol("shaka.net.NetworkingEngine",shaka.net.NetworkingEngine);
goog.exportProperty(shaka.net.NetworkingEngine.prototype,"request",shaka.net.NetworkingEngine.prototype.request);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"destroy",shaka.net.NetworkingEngine.prototype.destroy);goog.exportProperty(shaka.net.NetworkingEngine,"makeRequest",shaka.net.NetworkingEngine.makeRequest);goog.exportProperty(shaka.net.NetworkingEngine,"defaultRetryParameters",shaka.net.NetworkingEngine.defaultRetryParameters);
goog.exportProperty(shaka.net.NetworkingEngine.prototype,"clearAllResponseFilters",shaka.net.NetworkingEngine.prototype.clearAllResponseFilters);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"unregisterResponseFilter",shaka.net.NetworkingEngine.prototype.unregisterResponseFilter);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"registerResponseFilter",shaka.net.NetworkingEngine.prototype.registerResponseFilter);
goog.exportProperty(shaka.net.NetworkingEngine.prototype,"clearAllRequestFilters",shaka.net.NetworkingEngine.prototype.clearAllRequestFilters);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"unregisterRequestFilter",shaka.net.NetworkingEngine.prototype.unregisterRequestFilter);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"registerRequestFilter",shaka.net.NetworkingEngine.prototype.registerRequestFilter);goog.exportProperty(shaka.net.NetworkingEngine,"unregisterScheme",shaka.net.NetworkingEngine.unregisterScheme);
goog.exportProperty(shaka.net.NetworkingEngine,"registerScheme",shaka.net.NetworkingEngine.registerScheme);goog.exportProperty(shaka.net.NetworkingEngine.prototype,"setForceHTTPS",shaka.net.NetworkingEngine.prototype.setForceHTTPS);shaka.net.NetworkingEngine.NumBytesRemainingClass=function(){this.bytesToLoad_=0};shaka.net.NetworkingEngine.NumBytesRemainingClass.prototype.setBytes=function(a){this.bytesToLoad_=a};shaka.net.NetworkingEngine.NumBytesRemainingClass.prototype.getBytes=function(){return this.bytesToLoad_};
goog.exportProperty(shaka.net.NetworkingEngine,"NumBytesRemainingClass",shaka.net.NetworkingEngine.NumBytesRemainingClass);shaka.net.NetworkingEngine.PendingRequest=function(a,b,c){shaka.util.AbortableOperation.call(this,a,b);this.bytesRemaining_=c};$jscomp.inherits(shaka.net.NetworkingEngine.PendingRequest,shaka.util.AbortableOperation);shaka.net.NetworkingEngine.PendingRequest.prototype.getBytesRemaining=function(){return this.bytesRemaining_.getBytes()};
goog.exportProperty(shaka.net.NetworkingEngine,"PendingRequest",shaka.net.NetworkingEngine.PendingRequest);shaka.net.NetworkingEngine.RequestType={MANIFEST:0,SEGMENT:1,LICENSE:2,APP:3,TIMING:4,SERVER_CERTIFICATE:5,KEY:6};goog.exportProperty(shaka.net.NetworkingEngine,"RequestType",shaka.net.NetworkingEngine.RequestType);shaka.net.NetworkingEngine.PluginPriority={FALLBACK:1,PREFERRED:2,APPLICATION:3};goog.exportProperty(shaka.net.NetworkingEngine,"PluginPriority",shaka.net.NetworkingEngine.PluginPriority);
shaka.net.NetworkingEngine.schemes_={};shaka.util.Destroyer=function(a){this.destroyed_=!1;this.waitOnDestroy_=new shaka.util.PublicPromise;this.onDestroy_=a};shaka.util.Destroyer.prototype.destroyed=function(){return this.destroyed_};shaka.util.Destroyer.prototype.destroy=function(){var a=this;if(this.destroyed_)return this.waitOnDestroy_;this.destroyed_=!0;return this.onDestroy_().then(function(){a.waitOnDestroy_.resolve()},function(){a.waitOnDestroy_.resolve()})};
shaka.util.Destroyer.prototype.ensureNotDestroyed=function(a){if(this.destroyed_){if(a instanceof shaka.util.Error&&a.code==shaka.util.Error.Code.OBJECT_DESTROYED)throw a;throw shaka.util.Destroyer.destroyedError(a);}};shaka.util.Destroyer.destroyedError=function(a){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OBJECT_DESTROYED,a)};shaka.util.EventManager=function(){this.bindingMap_=new shaka.util.MultiMap};shaka.util.EventManager.prototype.release=function(){this.removeAll();this.bindingMap_=null};shaka.util.EventManager.prototype.listen=function(a,b,c,d){this.bindingMap_&&(a=new shaka.util.EventManager.Binding_(a,b,c,d),this.bindingMap_.push(b,a))};shaka.util.EventManager.prototype.listenOnce=function(a,b,c,d){var e=this,f=function(g){e.unlisten(a,b,f);c(g)};this.listen(a,b,f,d)};
shaka.util.EventManager.prototype.unlisten=function(a,b,c){if(this.bindingMap_){var d=this.bindingMap_.get(b)||[];d=$jscomp.makeIterator(d);for(var e=d.next();!e.done;e=d.next())e=e.value,e.target!=a||c!=e.listener&&c||(e.unlisten(),this.bindingMap_.remove(b,e))}};shaka.util.EventManager.prototype.removeAll=function(){if(this.bindingMap_){var a=this.bindingMap_.getAll();a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next())b.value.unlisten();this.bindingMap_.clear()}};
goog.exportSymbol("shaka.util.EventManager",shaka.util.EventManager);goog.exportProperty(shaka.util.EventManager.prototype,"removeAll",shaka.util.EventManager.prototype.removeAll);goog.exportProperty(shaka.util.EventManager.prototype,"unlisten",shaka.util.EventManager.prototype.unlisten);goog.exportProperty(shaka.util.EventManager.prototype,"listenOnce",shaka.util.EventManager.prototype.listenOnce);goog.exportProperty(shaka.util.EventManager.prototype,"listen",shaka.util.EventManager.prototype.listen);
goog.exportProperty(shaka.util.EventManager.prototype,"release",shaka.util.EventManager.prototype.release);shaka.util.EventManager.Binding_=function(a,b,c,d){this.target=a;this.type=b;this.listener=c;this.options=shaka.util.EventManager.Binding_.convertOptions_(a,d);this.target.addEventListener(b,c,this.options)};
shaka.util.EventManager.Binding_.prototype.unlisten=function(){goog.asserts.assert(this.target,"Missing target");this.target.removeEventListener(this.type,this.listener,this.options);this.listener=this.target=null;this.options=!1};
shaka.util.EventManager.Binding_.convertOptions_=function(a,b){if(void 0==b)return!1;if("boolean"==typeof b)return b;var c=new Set(["passive","capture"]),d=Object.keys(b).filter(function(e){return!c.has(e)});goog.asserts.assert(0==d.length,"Unsupported flag(s) to addEventListener: "+d.join(","));return shaka.util.EventManager.Binding_.doesSupportObject_(a)?b:b.capture||!1};
shaka.util.EventManager.Binding_.doesSupportObject_=function(a){var b=shaka.util.EventManager.Binding_.supportsObject_;if(void 0==b){b=!1;try{var c={},d={get:function(){b=!0;return!1}};Object.defineProperty(c,"passive",d);Object.defineProperty(c,"capture",d);d=function(){};a.addEventListener("test",d,c);a.removeEventListener("test",d,c)}catch(e){b=!1}shaka.util.EventManager.Binding_.supportsObject_=b}return b||!1};shaka.util.EventManager.Binding_.supportsObject_=void 0;shaka.util.Iterables=function(){};shaka.util.Iterables.map=function(a,b){var c=[];a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())c.push(b(d.value));return c};shaka.util.Iterables.every=function(a,b){a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())if(!b(c.value))return!1;return!0};shaka.util.Iterables.some=function(a,b){a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())if(b(c.value))return!0;return!1};
shaka.util.Iterables.filter=function(a,b){var c=[];a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())d=d.value,b(d)&&c.push(d);return c};shaka.util.MapUtils=function(){};shaka.util.MapUtils.asMap=function(a){for(var b=new Map,c=$jscomp.makeIterator(Object.keys(a)),d=c.next();!d.done;d=c.next())d=d.value,b.set(d,a[d]);return b};shaka.util.MapUtils.asObject=function(a){var b={};a.forEach(function(c,d){b[d]=c});return b};
shaka.util.MapUtils.hasSameElements=function(a,b){if(a||b){if(a&&!b||b&&!a)return!1}else return!0;if(a.size!=b.size)return!1;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){var d=$jscomp.makeIterator(c.value);c=d.next().value;d=d.next().value;if(!b.has(c))return!1;c=b.get(c);if(c!=d||void 0==c)return!1}return!0};shaka.util.DataViewReader=function(a,b){this.dataView_=shaka.util.BufferUtils.toDataView(a);this.littleEndian_=b==shaka.util.DataViewReader.Endianness.LITTLE_ENDIAN;this.position_=0};shaka.util.DataViewReader.prototype.getDataView=function(){return this.dataView_};shaka.util.DataViewReader.prototype.hasMoreData=function(){return this.position_<this.dataView_.byteLength};shaka.util.DataViewReader.prototype.getPosition=function(){return this.position_};
shaka.util.DataViewReader.prototype.getLength=function(){return this.dataView_.byteLength};shaka.util.DataViewReader.prototype.readUint8=function(){try{var a=this.dataView_.getUint8(this.position_);this.position_+=1;return a}catch(b){throw this.outOfBounds_();}};shaka.util.DataViewReader.prototype.readUint16=function(){try{var a=this.dataView_.getUint16(this.position_,this.littleEndian_);this.position_+=2;return a}catch(b){throw this.outOfBounds_();}};
shaka.util.DataViewReader.prototype.readUint32=function(){try{var a=this.dataView_.getUint32(this.position_,this.littleEndian_);this.position_+=4;return a}catch(b){throw this.outOfBounds_();}};shaka.util.DataViewReader.prototype.readInt32=function(){try{var a=this.dataView_.getInt32(this.position_,this.littleEndian_);this.position_+=4;return a}catch(b){throw this.outOfBounds_();}};
shaka.util.DataViewReader.prototype.readUint64=function(){try{if(this.littleEndian_){var a=this.dataView_.getUint32(this.position_,!0);var b=this.dataView_.getUint32(this.position_+4,!0)}else b=this.dataView_.getUint32(this.position_,!1),a=this.dataView_.getUint32(this.position_+4,!1)}catch(c){throw this.outOfBounds_();}if(2097151<b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.JS_INTEGER_OVERFLOW);this.position_+=8;return b*Math.pow(2,
32)+a};shaka.util.DataViewReader.prototype.readBytes=function(a){goog.asserts.assert(0<=a,"Bad call to DataViewReader.readBytes");if(this.position_+a>this.dataView_.byteLength)throw this.outOfBounds_();var b=shaka.util.BufferUtils.toUint8(this.dataView_,this.position_,a);this.position_+=a;return b};
shaka.util.DataViewReader.prototype.skip=function(a){goog.asserts.assert(0<=a,"Bad call to DataViewReader.skip");if(this.position_+a>this.dataView_.byteLength)throw this.outOfBounds_();this.position_+=a};shaka.util.DataViewReader.prototype.rewind=function(a){goog.asserts.assert(0<=a,"Bad call to DataViewReader.rewind");if(this.position_<a)throw this.outOfBounds_();this.position_-=a};
shaka.util.DataViewReader.prototype.seek=function(a){goog.asserts.assert(0<=a,"Bad call to DataViewReader.seek");if(0>a||a>this.dataView_.byteLength)throw this.outOfBounds_();this.position_=a};shaka.util.DataViewReader.prototype.readTerminatedString=function(){for(var a=this.position_;this.hasMoreData()&&0!=this.dataView_.getUint8(this.position_);)this.position_+=1;a=shaka.util.BufferUtils.toUint8(this.dataView_,a,this.position_-a);this.position_+=1;return shaka.util.StringUtils.fromUTF8(a)};
shaka.util.DataViewReader.prototype.outOfBounds_=function(){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS)};goog.exportSymbol("shaka.util.DataViewReader",shaka.util.DataViewReader);goog.exportProperty(shaka.util.DataViewReader.prototype,"readTerminatedString",shaka.util.DataViewReader.prototype.readTerminatedString);goog.exportProperty(shaka.util.DataViewReader.prototype,"seek",shaka.util.DataViewReader.prototype.seek);
goog.exportProperty(shaka.util.DataViewReader.prototype,"rewind",shaka.util.DataViewReader.prototype.rewind);goog.exportProperty(shaka.util.DataViewReader.prototype,"skip",shaka.util.DataViewReader.prototype.skip);goog.exportProperty(shaka.util.DataViewReader.prototype,"readBytes",shaka.util.DataViewReader.prototype.readBytes);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint64",shaka.util.DataViewReader.prototype.readUint64);
goog.exportProperty(shaka.util.DataViewReader.prototype,"readInt32",shaka.util.DataViewReader.prototype.readInt32);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint32",shaka.util.DataViewReader.prototype.readUint32);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint16",shaka.util.DataViewReader.prototype.readUint16);goog.exportProperty(shaka.util.DataViewReader.prototype,"readUint8",shaka.util.DataViewReader.prototype.readUint8);
goog.exportProperty(shaka.util.DataViewReader.prototype,"getLength",shaka.util.DataViewReader.prototype.getLength);goog.exportProperty(shaka.util.DataViewReader.prototype,"getPosition",shaka.util.DataViewReader.prototype.getPosition);goog.exportProperty(shaka.util.DataViewReader.prototype,"hasMoreData",shaka.util.DataViewReader.prototype.hasMoreData);shaka.util.DataViewReader.Endianness={BIG_ENDIAN:0,LITTLE_ENDIAN:1};goog.exportProperty(shaka.util.DataViewReader,"Endianness",shaka.util.DataViewReader.Endianness);shaka.util.Mp4Parser=function(){this.headers_=[];this.boxDefinitions_=[];this.done_=!1};shaka.util.Mp4Parser.prototype.box=function(a,b){a=shaka.util.Mp4Parser.typeFromString_(a);this.headers_[a]=shaka.util.Mp4Parser.BoxType_.BASIC_BOX;this.boxDefinitions_[a]=b;return this};shaka.util.Mp4Parser.prototype.fullBox=function(a,b){a=shaka.util.Mp4Parser.typeFromString_(a);this.headers_[a]=shaka.util.Mp4Parser.BoxType_.FULL_BOX;this.boxDefinitions_[a]=b;return this};
shaka.util.Mp4Parser.prototype.stop=function(){this.done_=!0};shaka.util.Mp4Parser.prototype.parse=function(a,b,c){a=new shaka.util.DataViewReader(a,shaka.util.DataViewReader.Endianness.BIG_ENDIAN);for(this.done_=!1;a.hasMoreData()&&!this.done_;)this.parseNext(0,a,b,c)};
shaka.util.Mp4Parser.prototype.parseNext=function(a,b,c,d){var e=b.getPosition();if(d&&e+8>b.getLength())this.done_=!0;else{var f=b.readUint32(),g=b.readUint32(),h=shaka.util.Mp4Parser.typeToString(g),k=!1;shaka.log.v2("Parsing MP4 box",h);switch(f){case 0:f=b.getLength()-e;break;case 1:if(d&&b.getPosition()+8>b.getLength()){this.done_=!0;return}f=b.readUint64();k=!0}var l=this.boxDefinitions_[g];if(l){var m=null,n=null;if(this.headers_[g]==shaka.util.Mp4Parser.BoxType_.FULL_BOX){if(d&&b.getPosition()+
4>b.getLength()){this.done_=!0;return}n=b.readUint32();m=n>>>24;n&=16777215}g=e+f;c&&g>b.getLength()&&(g=b.getLength());d&&g>b.getLength()?this.done_=!0:(d=g-b.getPosition(),b=0<d?b.readBytes(d):new Uint8Array(0),b=new shaka.util.DataViewReader(b,shaka.util.DataViewReader.Endianness.BIG_ENDIAN),l({name:h,parser:this,partialOkay:c||!1,version:m,flags:n,reader:b,size:f,start:e+a,has64BitSize:k}))}else a=Math.min(e+f-b.getPosition(),b.getLength()-b.getPosition()),b.skip(a)}};
shaka.util.Mp4Parser.children=function(a){for(var b=shaka.util.Mp4Parser.headerSize(a);a.reader.hasMoreData()&&!a.parser.done_;)a.parser.parseNext(a.start+b,a.reader,a.partialOkay)};shaka.util.Mp4Parser.sampleDescription=function(a){for(var b=shaka.util.Mp4Parser.headerSize(a),c=a.reader.readUint32(),d=0;d<c&&(a.parser.parseNext(a.start+b,a.reader,a.partialOkay),!a.parser.done_);d++);};
shaka.util.Mp4Parser.visualSampleEntry=function(a){var b=shaka.util.Mp4Parser.headerSize(a);for(a.reader.skip(78);a.reader.hasMoreData()&&!a.parser.done_;)a.parser.parseNext(a.start+b,a.reader,a.partialOkay)};shaka.util.Mp4Parser.allData=function(a){return function(b){var c=b.reader.getLength()-b.reader.getPosition();a(b.reader.readBytes(c))}};
shaka.util.Mp4Parser.typeFromString_=function(a){goog.asserts.assert(4==a.length,"Mp4 box names must be 4 characters long");var b=0;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())b=b<<8|c.value.charCodeAt(0);return b};shaka.util.Mp4Parser.typeToString=function(a){return String.fromCharCode(a>>24&255,a>>16&255,a>>8&255,a&255)};shaka.util.Mp4Parser.headerSize=function(a){return 8+(a.has64BitSize?8:0)+(null!=a.flags?4:0)};goog.exportSymbol("shaka.util.Mp4Parser",shaka.util.Mp4Parser);
goog.exportProperty(shaka.util.Mp4Parser,"headerSize",shaka.util.Mp4Parser.headerSize);goog.exportProperty(shaka.util.Mp4Parser,"typeToString",shaka.util.Mp4Parser.typeToString);goog.exportProperty(shaka.util.Mp4Parser,"allData",shaka.util.Mp4Parser.allData);goog.exportProperty(shaka.util.Mp4Parser,"visualSampleEntry",shaka.util.Mp4Parser.visualSampleEntry);goog.exportProperty(shaka.util.Mp4Parser,"sampleDescription",shaka.util.Mp4Parser.sampleDescription);
goog.exportProperty(shaka.util.Mp4Parser,"children",shaka.util.Mp4Parser.children);goog.exportProperty(shaka.util.Mp4Parser.prototype,"parseNext",shaka.util.Mp4Parser.prototype.parseNext);goog.exportProperty(shaka.util.Mp4Parser.prototype,"parse",shaka.util.Mp4Parser.prototype.parse);goog.exportProperty(shaka.util.Mp4Parser.prototype,"stop",shaka.util.Mp4Parser.prototype.stop);goog.exportProperty(shaka.util.Mp4Parser.prototype,"fullBox",shaka.util.Mp4Parser.prototype.fullBox);
goog.exportProperty(shaka.util.Mp4Parser.prototype,"box",shaka.util.Mp4Parser.prototype.box);shaka.util.Mp4Parser.BoxType_={BASIC_BOX:0,FULL_BOX:1};shaka.util.Pssh=function(a){var b=this;this.systemIds=[];this.cencKeyIds=[];this.data=[];(new shaka.util.Mp4Parser).box("moov",shaka.util.Mp4Parser.children).box("moof",shaka.util.Mp4Parser.children).fullBox("pssh",function(c){return b.parsePsshBox_(c)}).parse(a);0==this.data.length&&shaka.log.v2("No pssh box found!")};
shaka.util.Pssh.prototype.parsePsshBox_=function(a){goog.asserts.assert(null!=a.version,"PSSH boxes are full boxes and must have a valid version");goog.asserts.assert(null!=a.flags,"PSSH boxes are full boxes and must have a valid flag");if(1<a.version)shaka.log.warning("Unrecognized PSSH version found!");else{var b=a.reader.getDataView();goog.asserts.assert(12<=b.byteOffset,"DataView at incorrect position");b=shaka.util.BufferUtils.toUint8(b,-12,a.size);this.data.push(b);this.systemIds.push(shaka.util.Uint8ArrayUtils.toHex(a.reader.readBytes(16)));
if(0<a.version){b=a.reader.readUint32();for(var c=0;c<b;c++){var d=shaka.util.Uint8ArrayUtils.toHex(a.reader.readBytes(16));this.cencKeyIds.push(d)}}}};
shaka.util.Pssh.createPssh=function(a,b,c,d){goog.asserts.assert(16==b.byteLength,"Invalid system ID length");var e=a.length,f=12+b.length+4+e;0<d&&(f+=4+16*c.size);var g=new Uint8Array(f),h=shaka.util.BufferUtils.toDataView(g),k=0;h.setUint32(k,f);k+=4;h.setUint32(k,1886614376);k+=4;1>d?h.setUint32(k,0):h.setUint32(k,16777216);k+=4;g.set(b,k);k+=b.length;if(0<d)for(h.setUint32(k,c.size),k+=4,b=shaka.util.Uint8ArrayUtils,c=$jscomp.makeIterator(c),d=c.next();!d.done;d=c.next())d=b.fromHex(d.value),
g.set(d,k),k+=d.length;h.setUint32(k,e);k+=4;g.set(a,k);goog.asserts.assert(k+e===f,"PSSH invalid length.");return g};
shaka.util.Pssh.normaliseInitData=function(a){if(!a)return a;var b=new shaka.util.Pssh(a);if(1>=b.data.length)return a;a=[];var c={};b=$jscomp.makeIterator(b.data);for(var d=b.next();!d.done;c={$jscomp$loop$prop$initData$428$638:c.$jscomp$loop$prop$initData$428$638},d=b.next())c.$jscomp$loop$prop$initData$428$638=d.value,a.some(function(e){return function(f){return shaka.util.BufferUtils.equal(f,e.$jscomp$loop$prop$initData$428$638)}}(c))||a.push(c.$jscomp$loop$prop$initData$428$638);return shaka.util.Uint8ArrayUtils.concat.apply(shaka.util.Uint8ArrayUtils,
$jscomp.arrayFromIterable(a))};shaka.util.XmlUtils=function(){};shaka.util.XmlUtils.findChild=function(a,b){a=shaka.util.XmlUtils.findChildren(a,b);return 1!=a.length?null:a[0]};shaka.util.XmlUtils.findChildNS=function(a,b,c){a=shaka.util.XmlUtils.findChildrenNS(a,b,c);return 1!=a.length?null:a[0]};shaka.util.XmlUtils.findChildren=function(a,b){var c=[];a=$jscomp.makeIterator(a.childNodes);for(var d=a.next();!d.done;d=a.next())d=d.value,d instanceof Element&&d.tagName==b&&c.push(d);return c};
shaka.util.XmlUtils.getChildren=function(a){return Array.from(a.childNodes).filter(function(b){return b instanceof Element})};shaka.util.XmlUtils.findChildrenNS=function(a,b,c){var d=[];a=$jscomp.makeIterator(a.childNodes);for(var e=a.next();!e.done;e=a.next())e=e.value,e instanceof Element&&e.localName==c&&e.namespaceURI==b&&d.push(e);return d};shaka.util.XmlUtils.getAttributeNS=function(a,b,c){return a.hasAttributeNS(b,c)?a.getAttributeNS(b,c):null};
shaka.util.XmlUtils.getAttributeNSList=function(a,b,c){b=$jscomp.makeIterator(b);for(var d=b.next();!d.done;d=b.next())if(d=d.value,a.hasAttributeNS(d,c))return a.getAttributeNS(d,c);return null};shaka.util.XmlUtils.getContents=function(a){var b=shaka.util.XmlUtils;return Array.from(a.childNodes).every(b.isText)?a.textContent.trim():null};shaka.util.XmlUtils.isText=function(a){return a.nodeType==Node.TEXT_NODE||a.nodeType==Node.CDATA_SECTION_NODE};
shaka.util.XmlUtils.parseAttr=function(a,b,c,d){d=void 0===d?null:d;var e=null;a=a.getAttribute(b);null!=a&&(e=c(a));return null==e?d:e};shaka.util.XmlUtils.parseDate=function(a){if(!a)return null;/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(a)&&(a+="Z");a=Date.parse(a);return isNaN(a)?null:a/1E3};
shaka.util.XmlUtils.parseDuration=function(a){if(!a)return null;var b=RegExp("^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?(?:T(?:([0-9]*)H)?(?:([0-9]*)M)?(?:([0-9.]*)S)?)?$").exec(a);if(!b)return shaka.log.warning("Invalid duration string:",a),null;a=31536E3*Number(b[1]||null)+2592E3*Number(b[2]||null)+86400*Number(b[3]||null)+3600*Number(b[4]||null)+60*Number(b[5]||null)+Number(b[6]||null);return isFinite(a)?a:null};
shaka.util.XmlUtils.parseRange=function(a){var b=/([0-9]+)-([0-9]+)/.exec(a);if(!b)return null;a=Number(b[1]);if(!isFinite(a))return null;b=Number(b[2]);return isFinite(b)?{start:a,end:b}:null};shaka.util.XmlUtils.parseInt=function(a){a=Number(a);return 0===a%1?a:null};shaka.util.XmlUtils.parsePositiveInt=function(a){a=Number(a);return 0===a%1&&0<a?a:null};shaka.util.XmlUtils.parseNonNegativeInt=function(a){a=Number(a);return 0===a%1&&0<=a?a:null};
shaka.util.XmlUtils.parseFloat=function(a){a=Number(a);return isNaN(a)?null:a};shaka.util.XmlUtils.evalDivision=function(a){var b;var c=(b=a.match(/^(\d+)\/(\d+)$/))?Number(b[1])/Number(b[2]):Number(a);return isNaN(c)?null:c};
shaka.util.XmlUtils.parseXmlString=function(a,b){var c=new DOMParser,d=shaka.util.XmlUtils.trustedHTMLFromString_.value()(a);a=null;try{a=c.parseFromString(d,"text/xml")}catch(e){return shaka.log.error("XML parsing exception:",e),null}goog.asserts.assert(a,"Parsed XML document cannot be null!");c=a.documentElement;if(!c)return shaka.log.error("XML document was empty!"),null;d=c.getElementsByTagName("parsererror");if(d.length)return shaka.log.error("XML parser error found:",d[0]),null;if(c.tagName!=
b)return shaka.log.error('XML tag name does not match expected "'+b+'":',c.tagName),null;for(b=document.createNodeIterator(a,NodeFilter.SHOW_ALL);a=b.nextNode();)if(a instanceof HTMLElement||a instanceof SVGElement)return shaka.log.error("XML document embeds unsafe content!"),null;return c};shaka.util.XmlUtils.parseXml=function(a,b){try{var c=shaka.util.StringUtils.fromUTF8(a);return shaka.util.XmlUtils.parseXmlString(c,b)}catch(d){return shaka.log.error("parseXmlString threw!",d),null}};
shaka.util.XmlUtils.trustedHTMLFromString_=new shaka.util.Lazy(function(){if("undefined"!==typeof trustedTypes){var a=trustedTypes.createPolicy("shaka-player#xml",{createHTML:function(b){return b}});return function(b){return a.createHTML(b)}}return function(b){return b}});shaka.media.DrmEngine=function(a,b){var c=this;b=void 0===b?1:b;this.playerInterface_=a;this.supportedTypes_=new Set;this.video_=this.mediaKeys_=null;this.initializedForStorage_=this.initialized_=!1;this.licenseTimeSeconds_=0;this.currentDrmInfo_=null;this.eventManager_=new shaka.util.EventManager;this.activeSessions_=new Map;this.offlineSessionIds_=[];this.allSessionsLoaded_=new shaka.util.PublicPromise;this.config_=null;this.onError_=function(d){c.allSessionsLoaded_.reject(d);a.onError(d)};this.keyStatusByKeyId_=
new Map;this.announcedKeyStatusByKeyId_=new Map;this.keyStatusTimer_=new shaka.util.Timer(function(){return c.processKeyStatusChanges_()});this.usePersistentLicenses_=!1;this.mediaKeyMessageEvents_=[];this.initialRequestsSent_=!1;this.expirationTimer_=(new shaka.util.Timer(function(){c.pollExpiration_()})).tickEvery(b);this.allSessionsLoaded_.catch(function(){});this.destroyer_=new shaka.util.Destroyer(function(){return c.destroyNow_()});this.srcEquals_=!1;this.mediaKeysAttached_=null};
shaka.media.DrmEngine.prototype.destroy=function(){return this.destroyer_.destroy()};
shaka.media.DrmEngine.prototype.destroyNow_=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){switch(b.nextAddress){case 1:return a.eventManager_.release(),a.eventManager_=null,a.allSessionsLoaded_.reject(),a.expirationTimer_.stop(),a.expirationTimer_=null,a.keyStatusTimer_.stop(),a.keyStatusTimer_=null,b.yield(a.closeOpenSessions_(),2);case 2:if(!a.video_){b.jumpTo(3);break}goog.asserts.assert(!a.video_.src,"video src must be removed first!");b.setCatchFinallyBlocks(4);
return b.yield(a.video_.setMediaKeys(null),6);case 6:b.leaveTryBlock(5);break;case 4:b.enterCatchBlock();case 5:a.video_=null;case 3:a.currentDrmInfo_=null,a.supportedTypes_.clear(),a.mediaKeys_=null,a.offlineSessionIds_=[],a.config_=null,a.onError_=function(){},a.playerInterface_=null,a.srcEquals_=!1,a.mediaKeysAttached_=null,b.jumpToEnd()}})};shaka.media.DrmEngine.prototype.configure=function(a){this.config_=a};shaka.media.DrmEngine.prototype.setSrcEquals=function(a){this.srcEquals_=a};
shaka.media.DrmEngine.prototype.initForStorage=function(a,b){this.initializedForStorage_=!0;this.offlineSessionIds_=[];this.usePersistentLicenses_=b;return this.init_(a)};shaka.media.DrmEngine.prototype.initForPlayback=function(a,b){this.offlineSessionIds_=b;this.usePersistentLicenses_=0<b.length;return this.init_(a)};
shaka.media.DrmEngine.prototype.initForRemoval=function(a,b,c,d,e){var f=new Map;d={audioCapabilities:d,videoCapabilities:e,distinctiveIdentifier:"optional",persistentState:"required",sessionTypes:["persistent-license"],label:a};d.drmInfos=[{keySystem:a,licenseServerUri:b,distinctiveIdentifierRequired:!1,persistentStateRequired:!0,audioRobustness:"",videoRobustness:"",serverCertificate:c,serverCertificateUri:"",initData:null,keyIds:null}];f.set(a,d);return this.queryMediaKeys_(f,[])};
shaka.media.DrmEngine.prototype.init_=function(a){var b=this,c,d,e,f,g,h,k,l,m,n,p,q,r,w;return $jscomp.asyncExecutePromiseGeneratorProgram(function(u){if(1==u.nextAddress){goog.asserts.assert(b.config_,"DrmEngine configure() must be called before init()!");if(c=b.configureClearKey_())for(d=$jscomp.makeIterator(a),e=d.next();!e.done;e=d.next())f=e.value,f.video&&(f.video.drmInfos=[c]),f.audio&&(f.audio.drmInfos=[c]);g=a.some(function(v){return v.video&&v.video.drmInfos.length||v.audio&&v.audio.drmInfos.length?
!0:!1});g||(h=shaka.util.MapUtils.asMap(b.config_.servers),shaka.media.DrmEngine.replaceDrmInfo_(a,h));k=$jscomp.makeIterator(a);for(e=k.next();!e.done;e=k.next())for(l=e.value,m=b.getVariantDrmInfos_(l),n=$jscomp.makeIterator(m),p=n.next();!p.done;p=n.next())q=p.value,shaka.media.DrmEngine.fillInDrmInfoDefaults_(q,shaka.util.MapUtils.asMap(b.config_.servers),shaka.util.MapUtils.asMap(b.config_.advanced||{}),b.config_.keySystemsMapping);return u.yield(shaka.util.StreamUtils.getDecodingInfosForVariants(a,
b.usePersistentLicenses_,b.srcEquals_),2)}r=g||Object.keys(b.config_.servers).length;if(!r)return b.initialized_=!0,u.return(Promise.resolve());w=b.queryMediaKeys_(void 0,a);return u.return(g?w:w.catch(function(){}))})};
shaka.media.DrmEngine.prototype.attachMediaKeys_=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){switch(c.nextAddress){case 1:if(a.video_.mediaKeys)return c.return();if(!a.mediaKeysAttached_){c.jumpTo(2);break}return c.yield(a.mediaKeysAttached_,3);case 3:return a.destroyer_.ensureNotDestroyed(),c.return();case 2:return c.setCatchFinallyBlocks(4),a.mediaKeysAttached_=a.video_.setMediaKeys(a.mediaKeys_),c.yield(a.mediaKeysAttached_,6);case 6:c.leaveTryBlock(5);
break;case 4:b=c.enterCatchBlock(),goog.asserts.assert(b instanceof Error,"Wrong error type!"),a.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_ATTACH_TO_VIDEO,b.message));case 5:a.destroyer_.ensureNotDestroyed(),c.jumpToEnd()}})};
shaka.media.DrmEngine.prototype.onEncryptedEvent_=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return c.yield(b.attachMediaKeys_(),2);b.newInitData(a.initDataType,shaka.util.BufferUtils.toUint8(a.initData));c.jumpToEnd()})};
shaka.media.DrmEngine.prototype.attach=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress){if(!b.mediaKeys_)return b.eventManager_.listenOnce(a,"encrypted",function(e){b.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.ENCRYPTED_CONTENT_WITHOUT_DRM_INFO))}),d.return();b.video_=a;b.eventManager_.listenOnce(b.video_,"play",function(){return b.onPlay_()});"webkitCurrentPlaybackTargetIsWireless"in
b.video_&&b.eventManager_.listen(b.video_,"webkitcurrentplaybacktargetiswirelesschanged",function(){return b.closeOpenSessions_()});return(c=b.currentDrmInfo_?b.currentDrmInfo_.initData.find(function(e){return 0<e.initData.length}):null)||"com.apple.fps"!==b.currentDrmInfo_.keySystem||b.offlineSessionIds_.length?d.yield(b.attachMediaKeys_(),2):d.jumpTo(2)}b.createOrLoad();c||b.offlineSessionIds_.length||b.config_.parseInbandPsshEnabled||b.eventManager_.listen(b.video_,"encrypted",function(e){return b.onEncryptedEvent_(e)});
d.jumpToEnd()})};
shaka.media.DrmEngine.prototype.setServerCertificate=function(){var a=this,b,c,d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){switch(h.nextAddress){case 1:goog.asserts.assert(a.initialized_,"Must call init() before setServerCertificate");if(!a.mediaKeys_||!a.currentDrmInfo_)return h.return();if(!a.currentDrmInfo_.serverCertificateUri||a.currentDrmInfo_.serverCertificate&&a.currentDrmInfo_.serverCertificate.length){h.jumpTo(2);break}b=shaka.net.NetworkingEngine.makeRequest([a.currentDrmInfo_.serverCertificateUri],a.config_.retryParameters);
h.setCatchFinallyBlocks(3);c=a.playerInterface_.netEngine.request(shaka.net.NetworkingEngine.RequestType.SERVER_CERTIFICATE,b);return h.yield(c.promise,5);case 5:d=h.yieldResult;a.currentDrmInfo_.serverCertificate=shaka.util.BufferUtils.toUint8(d.data);h.leaveTryBlock(4);break;case 3:throw e=h.enterCatchBlock(),goog.asserts.assert(e instanceof shaka.util.Error,"Wrong NetworkingEngine error type!"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.SERVER_CERTIFICATE_REQUEST_FAILED,
e);case 4:if(a.destroyer_.destroyed())return h.return();case 2:if(!a.currentDrmInfo_.serverCertificate||!a.currentDrmInfo_.serverCertificate.length)return h.return();h.setCatchFinallyBlocks(6);return h.yield(a.mediaKeys_.setServerCertificate(a.currentDrmInfo_.serverCertificate),8);case 8:(f=h.yieldResult)||shaka.log.warning("Server certificates are not supported by the key system.  The server certificate has been ignored.");h.leaveTryBlock(0);break;case 6:throw g=h.enterCatchBlock(),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,shaka.util.Error.Code.INVALID_SERVER_CERTIFICATE,g.message);}})};
shaka.media.DrmEngine.prototype.removeSession=function(a){var b=this,c,d,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress)return goog.asserts.assert(b.mediaKeys_,"Must call init() before removeSession"),f.yield(b.loadOfflineSession_(a),2);if(3!=f.nextAddress){c=f.yieldResult;if(!c)return shaka.log.v2("Ignoring attempt to remove missing session",a),f.return();d=[];if(e=b.activeSessions_.get(c))e.updatePromise=new shaka.util.PublicPromise,d.push(e.updatePromise);
shaka.log.v2("Attempting to remove session",a);d.push(c.remove());return f.yield(Promise.all(d),3)}b.activeSessions_.delete(c);f.jumpToEnd()})};
shaka.media.DrmEngine.prototype.createOrLoad=function(){for(var a=(this.currentDrmInfo_?this.currentDrmInfo_.initData:[])||[],b=$jscomp.makeIterator(a),c=b.next();!c.done;c=b.next())c=c.value,this.newInitData(c.initDataType,c.initData);b=$jscomp.makeIterator(this.offlineSessionIds_);for(c=b.next();!c.done;c=b.next())this.loadOfflineSession_(c.value);a.length||this.offlineSessionIds_.length||this.allSessionsLoaded_.resolve();return this.allSessionsLoaded_};
shaka.media.DrmEngine.prototype.newInitData=function(a,b){if(b.length){var c=this.activeSessions_.values();c=$jscomp.makeIterator(c);for(var d=c.next();!d.done;d=c.next())if(shaka.util.BufferUtils.equal(b,d.value.initData)&&!shaka.util.Platform.isTizen2()){shaka.log.debug("Ignoring duplicate init data.");return}0<this.activeSessions_.size&&this.areAllSessionsLoaded_()&&(this.allSessionsLoaded_.resolve(),this.allSessionsLoaded_=new shaka.util.PublicPromise,this.allSessionsLoaded_.catch(function(){}));
this.createSession(a,b,this.currentDrmInfo_.sessionType)}};shaka.media.DrmEngine.prototype.initialized=function(){return this.initialized_};shaka.media.DrmEngine.keySystem=function(a){return a?a.keySystem:""};shaka.media.DrmEngine.isPlayReadyKeySystem=function(a){return a?!!a.match(/^com\.(microsoft|chromecast)\.playready/):!1};shaka.media.DrmEngine.isFairPlayKeySystem=function(a){return a?!!a.match(/^com\.apple\.fps/):!1};
shaka.media.DrmEngine.prototype.willSupport=function(a){if(shaka.util.Platform.isLegacyEdge())return!0;a=a.toLowerCase();if(shaka.util.Platform.isTizen()&&a.includes('codecs="ac-3"')){var b=a.replace("ac-3","ec-3");return this.supportedTypes_.has(a)||this.supportedTypes_.has(b)}return this.supportedTypes_.has(a)};shaka.media.DrmEngine.prototype.getSessionIds=function(){var a=this.activeSessions_.keys();a=shaka.util.Iterables.map(a,function(b){return b.sessionId});return Array.from(a)};
shaka.media.DrmEngine.prototype.getExpiration=function(){var a=Infinity,b=this.activeSessions_.keys();b=$jscomp.makeIterator(b);for(var c=b.next();!c.done;c=b.next())c=c.value,isNaN(c.expiration)||(a=Math.min(a,c.expiration));return a};shaka.media.DrmEngine.prototype.getLicenseTime=function(){return this.licenseTimeSeconds_?this.licenseTimeSeconds_:NaN};shaka.media.DrmEngine.prototype.getDrmInfo=function(){return this.currentDrmInfo_};shaka.media.DrmEngine.prototype.getMediaKeys=function(){return this.mediaKeys_};
shaka.media.DrmEngine.prototype.getKeyStatuses=function(){return shaka.util.MapUtils.asObject(this.announcedKeyStatusByKeyId_)};shaka.media.DrmEngine.prototype.getMediaKeySessions=function(){return Array.from(this.activeSessions_.keys())};shaka.media.DrmEngine.computeMimeType_=function(a,b){b=shaka.util.MimeUtils.getFullType(a.mimeType,b||a.codecs);return shaka.media.Transmuxer.isSupported(b)?shaka.media.Transmuxer.convertCodecs(a.type,b):b};
shaka.media.DrmEngine.prototype.queryMediaKeys_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w;return $jscomp.asyncExecutePromiseGeneratorProgram(function(u){switch(u.nextAddress){case 1:d=new Map;if(b.length){e=c.getKeySystemAccessFromVariants_(b,d);u.jumpTo(2);break}return u.yield(c.getKeySystemAccessByConfigs_(a),3);case 3:e=u.yieldResult;case 2:f=e;if(!f)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE);
c.destroyer_.ensureNotDestroyed();u.setCatchFinallyBlocks(4);c.supportedTypes_.clear();g=f.getConfiguration();shaka.log.v2("Got MediaKeySystemAccess with configuration",g);h=g.audioCapabilities||[];k=g.videoCapabilities||[];l=$jscomp.makeIterator(h);for(m=l.next();!m.done;m=l.next())n=m.value,c.supportedTypes_.add(n.contentType.toLowerCase());p=$jscomp.makeIterator(k);for(m=p.next();!m.done;m=p.next())q=m.value,c.supportedTypes_.add(q.contentType.toLowerCase());goog.asserts.assert(c.supportedTypes_.size,
"We should get at least one supported MIME type");c.currentDrmInfo_=b.length?c.createDrmInfoByInfos_(f.keySystem,d.get(f.keySystem)):shaka.media.DrmEngine.createDrmInfoByConfigs_(f.keySystem,a.get(f.keySystem));if(!c.currentDrmInfo_.licenseServerUri)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.NO_LICENSE_SERVER_GIVEN,c.currentDrmInfo_.keySystem);return u.yield(f.createMediaKeys(),6);case 6:return r=u.yieldResult,c.destroyer_.ensureNotDestroyed(),
shaka.log.info("Created MediaKeys object for key system",c.currentDrmInfo_.keySystem),c.mediaKeys_=r,c.initialized_=!0,u.yield(c.setServerCertificate(),7);case 7:c.destroyer_.ensureNotDestroyed();u.leaveTryBlock(0);break;case 4:w=u.enterCatchBlock();c.destroyer_.ensureNotDestroyed(w);c.currentDrmInfo_=null;c.supportedTypes_.clear();if(w instanceof shaka.util.Error)throw w;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_CDM,
w.message);}})};
shaka.media.DrmEngine.prototype.getKeySystemAccessFromVariants_=function(a,b){for(var c=$jscomp.makeIterator(a),d=c.next();!d.done;d=c.next()){var e=this.getVariantDrmInfos_(d.value);e=$jscomp.makeIterator(e);for(d=e.next();!d.done;d=e.next()){var f=d.value;b.has(f.keySystem)||b.set(f.keySystem,[]);b.get(f.keySystem).push(f)}}if(1==b.size&&b.has(""))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS);c={};e=$jscomp.makeIterator(this.config_.preferredKeySystems);
for(f=e.next();!f.done;c={$jscomp$loop$prop$preferredKeySystem$640:c.$jscomp$loop$prop$preferredKeySystem$640},f=e.next())for(c.$jscomp$loop$prop$preferredKeySystem$640=f.value,f=$jscomp.makeIterator(a),d=f.next();!d.done;d=f.next())if(d=d.value.decodingInfos.find(function(l){return function(m){return m.supported&&null!=m.keySystemAccess&&m.keySystemAccess.keySystem==l.$jscomp$loop$prop$preferredKeySystem$640}}(c)))return d.keySystemAccess;c=$jscomp.makeIterator([!0,!1]);for(e=c.next();!e.done;e=
c.next())for(e=e.value,f=$jscomp.makeIterator(a),d=f.next();!d.done;d=f.next()){var g=$jscomp.makeIterator(d.value.decodingInfos);for(d=g.next();!d.done;d=g.next()){var h=d.value;if(h.supported&&h.keySystemAccess){d=b.get(h.keySystemAccess.keySystem);var k=$jscomp.makeIterator(d);for(d=k.next();!d.done;d=k.next())if(!!d.value.licenseServerUri==e)return h.keySystemAccess}}}return null};
shaka.media.DrmEngine.prototype.getKeySystemAccessByConfigs_=function(a){var b=this,c,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:if(1==a.size&&a.has(""))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.NO_RECOGNIZED_KEY_SYSTEMS);d=$jscomp.makeIterator(a.values());for(e=d.next();!e.done;e=d.next())f=e.value,0==f.audioCapabilities.length&&delete f.audioCapabilities,
0==f.videoCapabilities.length&&delete f.videoCapabilities;g=$jscomp.makeIterator(b.config_.preferredKeySystems);h=g.next();case 2:if(h.done){t.jumpTo(4);break}k=h.value;if(!a.has(k)){t.jumpTo(3);break}l=a.get(k);t.setCatchFinallyBlocks(6);return t.yield(navigator.requestMediaKeySystemAccess(k,[l]),8);case 8:return c=t.yieldResult,t.return(c);case 6:m=t.enterCatchBlock(),shaka.log.v2("Requesting",k,"failed with config",l,m);case 7:b.destroyer_.ensureNotDestroyed();case 3:h=g.next();t.jumpTo(2);break;
case 4:n=$jscomp.makeIterator([!0,!1]),p=n.next();case 9:if(p.done){t.jumpTo(11);break}q=p.value;r=$jscomp.makeIterator(a.keys());h=r.next();case 12:if(h.done){p=n.next();t.jumpTo(9);break}w=h.value;u=a.get(w);v=u.drmInfos.some(function(y){return!!y.licenseServerUri});if(v!=q){t.jumpTo(13);break}t.setCatchFinallyBlocks(15);return t.yield(navigator.requestMediaKeySystemAccess(w,[u]),17);case 17:return c=t.yieldResult,t.return(c);case 15:x=t.enterCatchBlock(),shaka.log.v2("Requesting",w,"failed with config",
u,x);case 16:b.destroyer_.ensureNotDestroyed();case 13:h=r.next();t.jumpTo(12);break;case 11:return t.return(c)}})};
shaka.media.DrmEngine.prototype.configureClearKey_=function(){var a=shaka.util.MapUtils.asMap(this.config_.clearKeys);if(0==a.size)return null;var b=shaka.util.StringUtils,c=shaka.util.Uint8ArrayUtils,d=[],e=[];a.forEach(function(g,h){var k=h;22!=k.length&&(k=c.toBase64(c.fromHex(h),!1));h=g;22!=h.length&&(h=c.toBase64(c.fromHex(g),!1));g={kty:"oct",kid:k,k:h};d.push(g);e.push(g.kid)});a=JSON.stringify({keys:d});var f=JSON.stringify({kids:e});b=[{initData:shaka.util.BufferUtils.toUint8(b.toUTF8(f)),
initDataType:"keyids"}];return{keySystem:"org.w3.clearkey",licenseServerUri:"data:application/json;base64,"+window.btoa(a),distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:b,keyIds:new Set(e)}};
shaka.media.DrmEngine.prototype.loadOfflineSession_=function(a){var b=this,c,d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){switch(h.nextAddress){case 1:try{shaka.log.v1("Attempting to load an offline session",a),c=b.mediaKeys_.createSession("persistent-license")}catch(k){return d=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,k.message),b.onError_(d),h.return(Promise.reject(d))}b.eventManager_.listen(c,
"message",function(k){return b.onSessionMessage_(k)});b.eventManager_.listen(c,"keystatuseschange",function(k){return b.onKeyStatusesChange_(k)});e={initData:null,initDataType:null,loaded:!1,oldExpiration:Infinity,updatePromise:null,type:"persistent-license"};b.activeSessions_.set(c,e);h.setCatchFinallyBlocks(2);return h.yield(c.load(a),4);case 4:f=h.yieldResult;b.destroyer_.ensureNotDestroyed();shaka.log.v2("Loaded offline session",a,f);if(!f)return b.activeSessions_.delete(c),b.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.DRM,shaka.util.Error.Code.OFFLINE_SESSION_REMOVED)),h.return(Promise.resolve());e.loaded=!0;b.areAllSessionsLoaded_()&&b.allSessionsLoaded_.resolve();return h.return(c);case 2:g=h.enterCatchBlock(),b.destroyer_.ensureNotDestroyed(g),b.activeSessions_.delete(c),b.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,g.message));case 3:return h.return(Promise.resolve())}})};
shaka.media.DrmEngine.prototype.createSession=function(a,b,c){var d=this;goog.asserts.assert(this.mediaKeys_,"mediaKeys_ should be valid when creating temporary session.");try{shaka.log.info("Creating new",c,"session");var e=this.mediaKeys_.createSession(c)}catch(f){this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_CREATE_SESSION,f.message));return}this.eventManager_.listen(e,"message",function(f){return d.onSessionMessage_(f)});
this.eventManager_.listen(e,"keystatuseschange",function(f){return d.onKeyStatusesChange_(f)});this.activeSessions_.set(e,{initData:b,initDataType:a,loaded:!1,oldExpiration:Infinity,updatePromise:null,type:c});try{b=this.config_.initDataTransform(b,a,this.currentDrmInfo_)}catch(f){a=f;f instanceof shaka.util.Error||(a=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.INIT_DATA_TRANSFORM_ERROR,f));this.onError_(a);return}this.config_.logLicenseExchange&&
(c=shaka.util.Uint8ArrayUtils.toBase64(b),shaka.log.info("EME init data: type=",a,"data=",c));e.generateRequest(a,b).catch(function(f){if(!d.destroyer_.destroyed()){goog.asserts.assert(f instanceof Error,"Wrong error type!");d.activeSessions_.delete(e);var g=f.errorCode;if(g&&g.systemCode){var h=g.systemCode;0>h&&(h+=Math.pow(2,32));h="0x"+h.toString(16)}d.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.FAILED_TO_GENERATE_LICENSE_REQUEST,
f.message,f,h))}})};shaka.media.DrmEngine.prototype.onSessionMessage_=function(a){this.delayLicenseRequest_()?this.mediaKeyMessageEvents_.push(a):this.sendLicenseRequest_(a)};shaka.media.DrmEngine.prototype.delayLicenseRequest_=function(){return this.video_?this.config_.delayLicenseRequestUntilPlayed&&this.video_.paused&&!this.initialRequestsSent_:!1};
shaka.media.DrmEngine.prototype.sendLicenseRequest_=function(a){var b=this,c,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:return c=a.target,shaka.log.v1("Sending license request for session",c.sessionId,"of type",a.messageType),b.config_.logLicenseExchange&&(d=shaka.util.Uint8ArrayUtils.toBase64(a.message),shaka.log.info("EME license request",d)),e=b.activeSessions_.get(c),f=b.currentDrmInfo_.licenseServerUri,g=b.config_.advanced[b.currentDrmInfo_.keySystem],
"individualization-request"==a.messageType&&g&&g.individualizationServer&&(f=g.individualizationServer),h=shaka.net.NetworkingEngine.RequestType.LICENSE,k=shaka.net.NetworkingEngine.makeRequest([f],b.config_.retryParameters),k.body=a.message,k.method="POST",k.licenseRequestType=a.messageType,k.sessionId=c.sessionId,k.drmInfo=b.currentDrmInfo_,e&&(k.initData=e.initData,k.initDataType=e.initDataType),shaka.media.DrmEngine.isPlayReadyKeySystem(b.currentDrmInfo_.keySystem)&&b.unpackPlayReadyRequest_(k),
l=Date.now(),t.setCatchFinallyBlocks(2),n=b.playerInterface_.netEngine.request(h,k),t.yield(n.promise,4);case 4:m=t.yieldResult;t.leaveTryBlock(3);break;case 2:return p=t.enterCatchBlock(),goog.asserts.assert(p instanceof shaka.util.Error,"Wrong NetworkingEngine error type!"),q=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.LICENSE_REQUEST_FAILED,p),b.onError_(q),e&&e.updatePromise&&e.updatePromise.reject(q),t.return();case 3:if(b.destroyer_.destroyed())return t.return();
b.licenseTimeSeconds_+=(Date.now()-l)/1E3;b.config_.logLicenseExchange&&(r=shaka.util.Uint8ArrayUtils.toBase64(m.data),shaka.log.info("EME license response",r));t.setCatchFinallyBlocks(5);shaka.log.v1("Updating session",c.sessionId);return t.yield(c.update(m.data),7);case 7:t.leaveTryBlock(6);break;case 5:return w=t.enterCatchBlock(),u=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.LICENSE_RESPONSE_REJECTED,w.message),b.onError_(u),e&&e.updatePromise&&
e.updatePromise.reject(u),t.return();case 6:if(b.destroyer_.destroyed())return t.return();v=new shaka.util.FakeEvent("drmsessionupdate");b.playerInterface_.onEvent(v);e&&(e.updatePromise&&e.updatePromise.resolve(),x=new shaka.util.Timer(function(){e.loaded=!0;b.areAllSessionsLoaded_()&&b.allSessionsLoaded_.resolve()}),x.tickAfter(shaka.media.DrmEngine.SESSION_LOAD_TIMEOUT_));t.jumpToEnd()}})};
shaka.media.DrmEngine.prototype.unpackPlayReadyRequest_=function(a){var b=shaka.util.StringUtils.fromUTF16(a.body,!0,!0);if(b.includes("PlayReadyKeyMessage")){shaka.log.debug("Unwrapping PlayReady request.");b=shaka.util.XmlUtils.parseXmlString(b,"PlayReadyKeyMessage");goog.asserts.assert(b,"Failed to parse PlayReady XML!");var c=b.getElementsByTagName("HttpHeader");c=$jscomp.makeIterator(c);for(var d=c.next();!d.done;d=c.next()){var e=d.value;d=e.getElementsByTagName("name")[0];e=e.getElementsByTagName("value")[0];
goog.asserts.assert(d&&e,"Malformed PlayReady headers!");a.headers[d.textContent]=e.textContent}b=b.getElementsByTagName("Challenge")[0];goog.asserts.assert(b,"Malformed PlayReady challenge!");goog.asserts.assert("base64encoded"==b.getAttribute("encoding"),"Unexpected PlayReady challenge encoding!");a.body=shaka.util.Uint8ArrayUtils.fromBase64(b.textContent)}else shaka.log.debug("PlayReady request is already unwrapped."),a.headers["Content-Type"]="text/xml; charset=utf-8"};
shaka.media.DrmEngine.prototype.onKeyStatusesChange_=function(a){var b=this;a=a.target;shaka.log.v2("Key status changed for session",a.sessionId);var c=this.activeSessions_.get(a),d=!1;a.keyStatuses.forEach(function(f,g){if("string"==typeof g){var h=g;g=f;f=h}if(shaka.media.DrmEngine.isPlayReadyKeySystem(b.currentDrmInfo_.keySystem)&&16==g.byteLength&&(shaka.util.Platform.isEdge()||shaka.util.Platform.isPS4())){h=shaka.util.BufferUtils.toDataView(g);var k=h.getUint32(0,!0),l=h.getUint16(4,!0),m=h.getUint16(6,
!0);h.setUint32(0,k,!1);h.setUint16(4,l,!1);h.setUint16(6,m,!1)}"status-pending"!=f&&(c.loaded=!0);c||goog.asserts.assert("usable"!=f,"Usable keys found in closed session");"expired"==f&&(d=!0);g=shaka.util.Uint8ArrayUtils.toHex(g).slice(0,32);b.keyStatusByKeyId_.set(g,f)});var e=a.expiration-Date.now();(0>e||d&&1E3>e)&&c&&!c.updatePromise&&(shaka.log.debug("Session has expired",a.sessionId),this.activeSessions_.delete(a),a.close().catch(function(){}));this.areAllSessionsLoaded_()&&(this.allSessionsLoaded_.resolve(),
this.keyStatusTimer_.tickAfter(shaka.media.DrmEngine.KEY_STATUS_BATCH_TIME))};shaka.media.DrmEngine.prototype.processKeyStatusChanges_=function(){var a=this.keyStatusByKeyId_,b=this.announcedKeyStatusByKeyId_;b.clear();a.forEach(function(c,d){return b.set(d,c)});a=Array.from(b.values());if(a.length&&a.every(function(c){return"expired"==c}))this.onError_(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.EXPIRED));this.playerInterface_.onKeyStatus(shaka.util.MapUtils.asObject(b))};
shaka.media.DrmEngine.isBrowserSupported=function(){return!!window.MediaKeys&&!!window.navigator&&!!window.navigator.requestMediaKeySystemAccess&&!!window.MediaKeySystemAccess&&!!window.MediaKeySystemAccess.prototype.getConfiguration};
shaka.media.DrmEngine.probeSupport=function(){var a,b,c,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){return 1==k.nextAddress?(goog.asserts.assert(shaka.media.DrmEngine.isBrowserSupported(),"Must have basic EME support"),a="org.w3.clearkey com.widevine.alpha com.microsoft.playready com.microsoft.playready.recommendation com.apple.fps.1_0 com.apple.fps com.adobe.primetime".split(" "),b=[{contentType:'video/mp4; codecs="avc1.42E01E"'},{contentType:'video/webm; codecs="vp8"'}],
c={initDataTypes:["cenc"],videoCapabilities:b},d={videoCapabilities:b,persistentState:"required",sessionTypes:["persistent-license"]},e=[d,c],f=new Map,g=function(l){var m,n,p;return $jscomp.asyncExecutePromiseGeneratorProgram(function(q){switch(q.nextAddress){case 1:q.setCatchFinallyBlocks(2);if("org.w3.clearkey"===l&&shaka.util.Platform.isSafari())throw Error("Unsupported keySystem");return q.yield(navigator.requestMediaKeySystemAccess(l,e),4);case 4:return m=q.yieldResult,p=(n=m.getConfiguration().sessionTypes)?
n.includes("persistent-license"):!1,shaka.util.Platform.isTizen3()&&(p=!1),f.set(l,{persistentState:p}),q.yield(m.createMediaKeys(),5);case 5:q.leaveTryBlock(0);break;case 2:q.enterCatchBlock(),f.set(l,null),q.jumpToEnd()}})},h=a.map(function(l){return g(l)}),k.yield(Promise.all(h),2)):k.return(shaka.util.MapUtils.asObject(f))})};
shaka.media.DrmEngine.prototype.onPlay_=function(){for(var a=$jscomp.makeIterator(this.mediaKeyMessageEvents_),b=a.next();!b.done;b=a.next())this.sendLicenseRequest_(b.value);this.initialRequestsSent_=!0;this.mediaKeyMessageEvents_=[]};
shaka.media.DrmEngine.prototype.closeSession_=function(a){var b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return b=shaka.media.DrmEngine,c=new Promise(function(e,f){(new shaka.util.Timer(f)).tickAfter(b.CLOSE_TIMEOUT_)}),d.setCatchFinallyBlocks(2),d.yield(Promise.race([Promise.all([a.close(),a.closed]),c]),4);if(2!=d.nextAddress)return d.leaveTryBlock(0);d.enterCatchBlock();shaka.log.warning("Timeout waiting for session close");d.jumpToEnd()})};
shaka.media.DrmEngine.prototype.closeOpenSessions_=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){b=Array.from(a.activeSessions_.entries());a.activeSessions_.clear();return c.yield(Promise.all(b.map(function(d){d=$jscomp.makeIterator(d);var e=d.next().value,f=d.next().value,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress){h.setCatchFinallyBlocks(2);if(!a.initializedForStorage_&&!a.offlineSessionIds_.includes(e.sessionId)&&
"persistent-license"===f.type)return shaka.log.v1("Removing session",e.sessionId),h.yield(e.remove(),5);shaka.log.v1("Closing session",e.sessionId,f);return h.yield(a.closeSession_(e),5)}if(2!=h.nextAddress)return h.leaveTryBlock(0);g=h.enterCatchBlock();shaka.log.error("Failed to close or remove the session",g);h.jumpToEnd()})})),0)})};
shaka.media.DrmEngine.prototype.supportsVariant=function(a){var b=a.audio,c=a.video;if(b&&b.encrypted&&(b=shaka.media.DrmEngine.computeMimeType_(b),!this.willSupport(b))||c&&c.encrypted&&(c=shaka.media.DrmEngine.computeMimeType_(c),!this.willSupport(c)))return!1;var d=shaka.media.DrmEngine.keySystem(this.currentDrmInfo_);a=this.getVariantDrmInfos_(a);return 0==a.length||a.some(function(e){return e.keySystem==d})};
shaka.media.DrmEngine.areDrmCompatible=function(a,b){return a.length&&b.length?0<shaka.media.DrmEngine.getCommonDrmInfos(a,b).length:!0};
shaka.media.DrmEngine.getCommonDrmInfos=function(a,b){if(!a.length)return b;if(!b.length)return a;var c=[];a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next()){d=d.value;for(var e={},f=$jscomp.makeIterator(b),g=f.next();!g.done;e={$jscomp$loop$prop$initData$642:e.$jscomp$loop$prop$initData$642},g=f.next())if(g=g.value,d.keySystem==g.keySystem){e.$jscomp$loop$prop$initData$642=[];e.$jscomp$loop$prop$initData$642=e.$jscomp$loop$prop$initData$642.concat(d.initData||[]);e.$jscomp$loop$prop$initData$642=
e.$jscomp$loop$prop$initData$642.concat(g.initData||[]);e.$jscomp$loop$prop$initData$642=e.$jscomp$loop$prop$initData$642.filter(function(h){return function(k,l){return void 0===k.keyId||l===h.$jscomp$loop$prop$initData$642.findIndex(function(m){return m.keyId===k.keyId})}}(e));f=d.keyIds&&g.keyIds?new Set([].concat($jscomp.arrayFromIterable(d.keyIds),$jscomp.arrayFromIterable(g.keyIds))):d.keyIds||g.keyIds;c.push({keySystem:d.keySystem,licenseServerUri:d.licenseServerUri||g.licenseServerUri,distinctiveIdentifierRequired:d.distinctiveIdentifierRequired||
g.distinctiveIdentifierRequired,persistentStateRequired:d.persistentStateRequired||g.persistentStateRequired,videoRobustness:d.videoRobustness||g.videoRobustness,audioRobustness:d.audioRobustness||g.audioRobustness,serverCertificate:d.serverCertificate||g.serverCertificate,serverCertificateUri:d.serverCertificateUri||g.serverCertificateUri,initData:e.$jscomp$loop$prop$initData$642,keyIds:f});break}}return c};
shaka.media.DrmEngine.prototype.getVariantDrmInfos_=function(a){return(a.video?a.video.drmInfos:[]).concat(a.audio?a.audio.drmInfos:[])};shaka.media.DrmEngine.prototype.pollExpiration_=function(){var a=this;this.activeSessions_.forEach(function(b,c){var d=b.oldExpiration,e=c.expiration;isNaN(e)&&(e=Infinity);e!=d&&(a.playerInterface_.onExpirationUpdated(c.sessionId,e),b.oldExpiration=e)})};
shaka.media.DrmEngine.prototype.areAllSessionsLoaded_=function(){var a=this.activeSessions_.values();return shaka.util.Iterables.every(a,function(b){return b.loaded})};
shaka.media.DrmEngine.replaceDrmInfo_=function(a,b){var c=[];b.forEach(function(d,e){c.push({keySystem:e,licenseServerUri:d,distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",initData:[],keyIds:new Set})});a=$jscomp.makeIterator(a);for(b=a.next();!b.done;b=a.next())b=b.value,b.video&&(b.video.drmInfos=c),b.audio&&(b.audio.drmInfos=c)};
shaka.media.DrmEngine.prototype.createDrmInfoByInfos_=function(a,b){var c=[],d=[],e=[],f=[],g=new Set;shaka.media.DrmEngine.processDrmInfos_(b,c,e,d,f,g);1<e.length&&shaka.log.warning("Multiple unique server certificates found! Only the first will be used.");1<c.length&&shaka.log.warning("Multiple unique license server URIs found! Only the first will be used.");1<d.length&&shaka.log.warning("Multiple unique server certificate URIs found! Only the first will be used.");var h=this.usePersistentLicenses_?
"persistent-license":"temporary";a={keySystem:a,licenseServerUri:c[0],distinctiveIdentifierRequired:b[0].distinctiveIdentifierRequired,persistentStateRequired:b[0].persistentStateRequired,sessionType:b[0].sessionType||h,audioRobustness:b[0].audioRobustness||"",videoRobustness:b[0].videoRobustness||"",serverCertificate:e[0],serverCertificateUri:d[0],initData:f,keyIds:g};b=$jscomp.makeIterator(b);for(c=b.next();!c.done;c=b.next())c=c.value,c.distinctiveIdentifierRequired&&(a.distinctiveIdentifierRequired=
c.distinctiveIdentifierRequired),c.persistentStateRequired&&(a.persistentStateRequired=c.persistentStateRequired);return a};
shaka.media.DrmEngine.createDrmInfoByConfigs_=function(a,b){var c=[],d=[],e=[],f=[],g=new Set;shaka.media.DrmEngine.processDrmInfos_(b.drmInfos,c,e,d,f,g);1<e.length&&shaka.log.warning("Multiple unique server certificates found! Only the first will be used.");1<d.length&&shaka.log.warning("Multiple unique server certificate URIs found! Only the first will be used.");1<c.length&&shaka.log.warning("Multiple unique license server URIs found! Only the first will be used.");return{keySystem:a,licenseServerUri:c[0],
distinctiveIdentifierRequired:"required"==b.distinctiveIdentifier,persistentStateRequired:"required"==b.persistentState,sessionType:b.sessionTypes[0]||"temporary",audioRobustness:(b.audioCapabilities?b.audioCapabilities[0].robustness:"")||"",videoRobustness:(b.videoCapabilities?b.videoCapabilities[0].robustness:"")||"",serverCertificate:e[0],serverCertificateUri:d[0],initData:f,keyIds:g}};
shaka.media.DrmEngine.processDrmInfos_=function(a,b,c,d,e,f){var g={};a=$jscomp.makeIterator(a);for(var h=a.next();!h.done;g={$jscomp$loop$prop$drmInfo$644:g.$jscomp$loop$prop$drmInfo$644},h=a.next()){g.$jscomp$loop$prop$drmInfo$644=h.value;b.includes(g.$jscomp$loop$prop$drmInfo$644.licenseServerUri)||b.push(g.$jscomp$loop$prop$drmInfo$644.licenseServerUri);d.includes(g.$jscomp$loop$prop$drmInfo$644.serverCertificateUri)||d.push(g.$jscomp$loop$prop$drmInfo$644.serverCertificateUri);g.$jscomp$loop$prop$drmInfo$644.serverCertificate&&
(c.some(function(m){return function(n){return shaka.util.BufferUtils.equal(n,m.$jscomp$loop$prop$drmInfo$644.serverCertificate)}}(g))||c.push(g.$jscomp$loop$prop$drmInfo$644.serverCertificate));if(g.$jscomp$loop$prop$drmInfo$644.initData){h={};for(var k=$jscomp.makeIterator(g.$jscomp$loop$prop$drmInfo$644.initData),l=k.next();!l.done;h={$jscomp$loop$prop$initDataOverride$646:h.$jscomp$loop$prop$initDataOverride$646},l=k.next())h.$jscomp$loop$prop$initDataOverride$646=l.value,e.some(function(m){return function(n){var p=
m.$jscomp$loop$prop$initDataOverride$646;n=n.keyId&&n.keyId==p.keyId?!0:n.initDataType==p.initDataType&&shaka.util.BufferUtils.equal(n.initData,p.initData);return n}}(h))||e.push(h.$jscomp$loop$prop$initDataOverride$646)}if(g.$jscomp$loop$prop$drmInfo$644.keyIds)for(h=$jscomp.makeIterator(g.$jscomp$loop$prop$drmInfo$644.keyIds),k=h.next();!k.done;k=h.next())f.add(k.value)}};
shaka.media.DrmEngine.fillInDrmInfoDefaults_=function(a,b,c,d){var e=a.keySystem;if(e&&("org.w3.clearkey"!=e||!a.licenseServerUri)){b.size&&(b=b.get(e)||"",a.licenseServerUri=b);a.keyIds||(a.keyIds=new Set);if(c=c.get(e))a.distinctiveIdentifierRequired||(a.distinctiveIdentifierRequired=c.distinctiveIdentifierRequired),a.persistentStateRequired||(a.persistentStateRequired=c.persistentStateRequired),a.videoRobustness||(a.videoRobustness=c.videoRobustness),a.audioRobustness||(a.audioRobustness=c.audioRobustness),
a.serverCertificate||(a.serverCertificate=c.serverCertificate),c.sessionType&&(a.sessionType=c.sessionType),a.serverCertificateUri||(a.serverCertificateUri=c.serverCertificateUri);d[e]&&(a.keySystem=d[e]);window.cast&&window.cast.__platform__&&"com.microsoft.playready"==e&&(a.keySystem="com.chromecast.playready")}};
shaka.media.DrmEngine.prototype.parseInbandPssh=function(a,b){if(!this.config_.parseInbandPsshEnabled)return Promise.resolve();var c=shaka.util.ManifestParserUtils.ContentType;if(![c.AUDIO,c.VIDEO].includes(a))return Promise.resolve();b=new shaka.util.Pssh(shaka.util.BufferUtils.toUint8(b));c=0;var d=$jscomp.makeIterator(b.data);for(a=d.next();!a.done;a=d.next())c+=a.value.length;if(0==c)return Promise.resolve();c=new Uint8Array(c);d=0;b=$jscomp.makeIterator(b.data);for(a=b.next();!a.done;a=b.next())a=
a.value,c.set(a,d),d+=a.length;this.newInitData("cenc",c);return this.allSessionsLoaded_};shaka.media.DrmEngine.CLOSE_TIMEOUT_=1;shaka.media.DrmEngine.SESSION_LOAD_TIMEOUT_=5;shaka.media.DrmEngine.KEY_STATUS_BATCH_TIME=.5;shaka.media.DrmEngine.DUMMY_KEY_ID=new shaka.util.Lazy(function(){return shaka.util.BufferUtils.toArrayBuffer(new Uint8Array([0]))});shaka.media.ManifestParser=function(){};shaka.media.ManifestParser.registerParserByExtension=function(a,b){shaka.media.ManifestParser.parsersByExtension[a]=b};shaka.media.ManifestParser.registerParserByMime=function(a,b){shaka.media.ManifestParser.parsersByMime[a]=b};shaka.media.ManifestParser.unregisterParserByMime=function(a){delete shaka.media.ManifestParser.parsersByMime[a]};
shaka.media.ManifestParser.probeSupport=function(){var a=shaka.media.ManifestParser,b={};if(shaka.util.Platform.supportsMediaSource()){for(var c in a.parsersByMime)b[c]=!0;for(var d in a.parsersByExtension)b[d]=!0}c={mpd:"application/dash+xml",m3u8:"application/x-mpegurl",ism:"application/vnd.ms-sstr+xml"};d=$jscomp.makeIterator(["application/dash+xml","application/x-mpegurl","application/vnd.apple.mpegurl","application/vnd.ms-sstr+xml"]);for(var e=d.next();!e.done;e=d.next())e=e.value,shaka.util.Platform.supportsMediaSource()?
b[e]=!!a.parsersByMime[e]:b[e]=shaka.util.Platform.supportsMediaType(e);for(var f in c)shaka.util.Platform.supportsMediaSource()?b[f]=!!a.parsersByExtension[f]:b[f]=shaka.util.Platform.supportsMediaType(c[f]);return b};
shaka.media.ManifestParser.getFactory=function(a,b,c,d){var e,f,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){if(1==l.nextAddress){e=shaka.media.ManifestParser;if(d){if(f=e.parsersByMime[d.toLowerCase()])return l.return(f);shaka.log.warning("Could not determine manifest type using MIME type ",d)}if(g=e.getExtension(a)){if(h=e.parsersByExtension[g])return l.return(h);shaka.log.warning("Could not determine manifest type for extension ",g)}else shaka.log.warning("Could not find extension for ",
a);return d?l.jumpTo(2):l.yield(e.getMimeType(a,b,c),3)}if(2!=l.nextAddress&&(d=l.yieldResult)){if(k=shaka.media.ManifestParser.parsersByMime[d])return l.return(k);shaka.log.warning("Could not determine manifest type using MIME type",d)}throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.UNABLE_TO_GUESS_MANIFEST_TYPE,a);})};
shaka.media.ManifestParser.getMimeType=function(a,b,c){var d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return d=shaka.net.NetworkingEngine.RequestType.MANIFEST,e=shaka.net.NetworkingEngine.makeRequest([a],c),e.method="HEAD",h.yield(b.request(d,e).promise,2);f=h.yieldResult;g=f.headers["content-type"];return h.return(g?g.toLowerCase().split(";").shift():"")})};
shaka.media.ManifestParser.getExtension=function(a){a=(new goog.Uri(a)).getPath().split("/").pop().split(".");return 1==a.length?"":a.pop().toLowerCase()};shaka.media.ManifestParser.isSupported=function(a,b){return shaka.util.Platform.supportsMediaSource()?b in shaka.media.ManifestParser.parsersByMime||shaka.media.ManifestParser.getExtension(a)in shaka.media.ManifestParser.parsersByExtension?!0:!1:!1};goog.exportSymbol("shaka.media.ManifestParser",shaka.media.ManifestParser);
goog.exportProperty(shaka.media.ManifestParser,"unregisterParserByMime",shaka.media.ManifestParser.unregisterParserByMime);goog.exportProperty(shaka.media.ManifestParser,"registerParserByMime",shaka.media.ManifestParser.registerParserByMime);goog.exportProperty(shaka.media.ManifestParser,"registerParserByExtension",shaka.media.ManifestParser.registerParserByExtension);shaka.media.ManifestParser.parsersByMime={};shaka.media.ManifestParser.parsersByExtension={};shaka.media.ContentWorkarounds=function(){};
shaka.media.ContentWorkarounds.fakeEncryption=function(a){var b=shaka.media.ContentWorkarounds;a=shaka.util.BufferUtils.toUint8(a);var c=!1,d,e=[],f=function(l){e.push(l);shaka.util.Mp4Parser.children(l)},g=function(l){c=!0},h=[];(new shaka.util.Mp4Parser).box("moov",f).box("trak",f).box("mdia",f).box("minf",f).box("stbl",f).fullBox("stsd",function(l){d=l;e.push(l);shaka.util.Mp4Parser.sampleDescription(l)}).fullBox("encv",g).fullBox("enca",g).fullBox("hev1",function(l){h.push({box:l,newType:b.BOX_TYPE_ENCV_})}).fullBox("hvc1",
function(l){h.push({box:l,newType:b.BOX_TYPE_ENCV_})}).fullBox("avc1",function(l){h.push({box:l,newType:b.BOX_TYPE_ENCV_})}).fullBox("avc3",function(l){h.push({box:l,newType:b.BOX_TYPE_ENCV_})}).fullBox("ac-3",function(l){h.push({box:l,newType:b.BOX_TYPE_ENCA_})}).fullBox("ec-3",function(l){h.push({box:l,newType:b.BOX_TYPE_ENCA_})}).fullBox("mp4a",function(l){h.push({box:l,newType:b.BOX_TYPE_ENCA_})}).parse(a);if(c)return shaka.log.debug("Init segment already indicates encryption."),a;if(0==h.length||
!d)throw shaka.log.error("Failed to find boxes needed to fake encryption!"),shaka.log.v2("Failed init segment (hex):",shaka.util.Uint8ArrayUtils.toHex(a)),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.CONTENT_TRANSFORMATION_FAILED);h.reverse();f=$jscomp.makeIterator(h);for(g=f.next();!g.done;g=f.next()){g=g.value;var k=shaka.util.Mp4Parser.typeToString(g.newType);shaka.log.debug('Inserting "'+k+'" box into init segment.');a=b.insertEncryptionMetadata_(a,
d,g.box,e,g.newType)}return a};
shaka.media.ContentWorkarounds.insertEncryptionMetadata_=function(a,b,c,d,e){var f=shaka.media.ContentWorkarounds,g=f.createEncryptionMetadata_(a,c,e);e=new Uint8Array(a.byteLength+g.byteLength);c=shaka.util.Platform.isXboxOne()?c.start:c.start+c.size;var h=a.subarray(0,c);a=a.subarray(c);e.set(h);e.set(g,c);e.set(a,c+g.byteLength);d=$jscomp.makeIterator(d);for(a=d.next();!a.done;a=d.next())a=a.value,goog.asserts.assert(a.start<c,"Ancestor MP4 box found in the wrong location!  Modified init segment will not make sense!"),f.updateBoxSize_(e,
a.start,a.size+g.byteLength);f=shaka.util.BufferUtils.toDataView(e,b.start);b=shaka.util.Mp4Parser.headerSize(b);g=f.getUint32(b);f.setUint32(b,g+1);return e};
shaka.media.ContentWorkarounds.createEncryptionMetadata_=function(a,b,c){var d=shaka.media.ContentWorkarounds,e=d.CANNED_SINF_BOX_.value(),f=a.subarray(b.start,b.start+b.size),g=shaka.util.BufferUtils.toDataView(f);a=new Uint8Array(b.size+e.byteLength);a.set(f,0);f=shaka.util.BufferUtils.toDataView(a);f.setUint32(d.BOX_TYPE_OFFSET_,c);a.set(e,b.size);c=g.getUint32(d.BOX_TYPE_OFFSET_);f.setUint32(b.size+d.CANNED_SINF_BOX_FORMAT_OFFSET_,c);d.updateBoxSize_(a,0,a.byteLength);return a};
shaka.media.ContentWorkarounds.updateBoxSize_=function(a,b,c){var d=shaka.media.ContentWorkarounds;a=shaka.util.BufferUtils.toDataView(a,b);b=a.getUint32(d.BOX_SIZE_OFFSET_);0!=b&&(1==b?(a.setUint32(d.BOX_SIZE_64_OFFSET_,c>>32),a.setUint32(d.BOX_SIZE_64_OFFSET_+4,c&4294967295)):a.setUint32(d.BOX_SIZE_OFFSET_,c))};
shaka.media.ContentWorkarounds.CANNED_SINF_BOX_=new shaka.util.Lazy(function(){return new Uint8Array([0,0,0,80,115,105,110,102,0,0,0,12,102,114,109,97,0,0,0,0,0,0,0,20,115,99,104,109,0,0,0,0,99,101,110,99,0,1,0,0,0,0,0,40,115,99,104,105,0,0,0,32,116,101,110,99,0,0,0,0,0,0,1,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])});shaka.media.ContentWorkarounds.CANNED_SINF_BOX_FORMAT_OFFSET_=16;shaka.media.ContentWorkarounds.BOX_SIZE_OFFSET_=0;shaka.media.ContentWorkarounds.BOX_TYPE_OFFSET_=4;
shaka.media.ContentWorkarounds.BOX_SIZE_64_OFFSET_=8;shaka.media.ContentWorkarounds.BOX_TYPE_ENCV_=1701733238;shaka.media.ContentWorkarounds.BOX_TYPE_ENCA_=1701733217;shaka.cea={};shaka.cea.ICaptionDecoder=function(){};shaka.cea.ICaptionDecoder.prototype.extract=function(a,b){};shaka.cea.ICaptionDecoder.prototype.decode=function(){};shaka.cea.ICaptionDecoder.prototype.clear=function(){};shaka.cea.CeaUtils=function(){};
shaka.cea.CeaUtils.getParsedCaption=function(a,b,c,d,e){if(d>=e)return null;for(var f=-1,g=-1,h=0;h<c.length;h++)if(c[h].some(function(y){return null!=y&&""!=y.getChar().trim()})){f=h;break}for(h=c.length-1;0<=h;h--)if(c[h].some(function(y){return null!=y&&""!=y.getChar().trim()})){g=h;break}if(-1===f||-1===g)return null;for(var k=h=!1,l=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR,m=shaka.cea.CeaUtils.DEFAULT_BG_COLOR,n=shaka.cea.CeaUtils.createStyledCue(d,e,h,k,l,m);f<=g;f++){for(var p=c[f],q=-1,r=-1,w=
0;w<p.length;w++)if(null!=p[w]&&""!==p[w].getChar().trim()){q=w;break}for(w=p.length-1;0<=w;w--)if(null!=p[w]&&""!==p[w].getChar().trim()){r=w;break}if(-1===q||-1===r)p=shaka.cea.CeaUtils.createLineBreakCue(d,e),a.nestedCues.push(p);else{for(;q<=r;q++)if(w=p[q]){var u=w.isUnderlined(),v=w.isItalicized(),x=w.getTextColor(),t=w.getBackgroundColor();if(u!=h||v!=k||x!=l||t!=m)n.payload&&a.nestedCues.push(n),n=shaka.cea.CeaUtils.createStyledCue(d,e,u,v,x,t),h=u,k=v,l=x,m=t;n.payload+=w.getChar()}else n.payload+=
" ";n.payload&&a.nestedCues.push(n);f!==g&&(n=shaka.cea.CeaUtils.createLineBreakCue(d,e),a.nestedCues.push(n));n=shaka.cea.CeaUtils.createStyledCue(d,e,h,k,l,m)}}return a.nestedCues.length?{cue:a,stream:b}:null};shaka.cea.CeaUtils.createStyledCue=function(a,b,c,d,e,f){a=new shaka.text.Cue(a,b,"");c&&a.textDecoration.push(shaka.text.Cue.textDecoration.UNDERLINE);d&&(a.fontStyle=shaka.text.Cue.fontStyle.ITALIC);a.color=e;a.backgroundColor=f;return a};
shaka.cea.CeaUtils.createLineBreakCue=function(a,b){a=new shaka.text.Cue(a,b,"");a.lineBreak=!0;return a};shaka.cea.CeaUtils.StyledChar=function(a,b,c,d,e){this.character_=a;this.underline_=b;this.italics_=c;this.backgroundColor_=d;this.textColor_=e};shaka.cea.CeaUtils.StyledChar.prototype.getChar=function(){return this.character_};shaka.cea.CeaUtils.StyledChar.prototype.isUnderlined=function(){return this.underline_};shaka.cea.CeaUtils.StyledChar.prototype.isItalicized=function(){return this.italics_};
shaka.cea.CeaUtils.StyledChar.prototype.getBackgroundColor=function(){return this.backgroundColor_};shaka.cea.CeaUtils.StyledChar.prototype.getTextColor=function(){return this.textColor_};shaka.cea.CeaUtils.DEFAULT_BG_COLOR="black";shaka.cea.CeaUtils.DEFAULT_TXT_COLOR="white";shaka.cea.Cea608Memory=function(a,b){this.rows_=[];this.row_=1;this.scrollRows_=0;this.fieldNum_=a;this.channelNum_=b;this.italics_=this.underline_=!1;this.textColor_=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;this.backgroundColor_=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;this.reset()};shaka.cea.Cea608Memory.prototype.forceEmit=function(a,b){var c="CC"+(this.fieldNum_<<1|this.channelNum_+1),d=new shaka.text.Cue(a,b,"");return shaka.cea.CeaUtils.getParsedCaption(d,c,this.rows_,a,b)};
shaka.cea.Cea608Memory.prototype.reset=function(){this.resetAllRows();this.row_=1};shaka.cea.Cea608Memory.prototype.getRow=function(){return this.row_};shaka.cea.Cea608Memory.prototype.setRow=function(a){this.row_=a};shaka.cea.Cea608Memory.prototype.getScrollSize=function(){return this.scrollRows_};shaka.cea.Cea608Memory.prototype.setScrollSize=function(a){this.scrollRows_=a};
shaka.cea.Cea608Memory.prototype.addChar=function(a,b){if(!(32>b||127<b)){var c="";switch(a){case shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN:c=shaka.cea.Cea608Memory.CharSet.BasicNorthAmericanChars.has(b)?shaka.cea.Cea608Memory.CharSet.BasicNorthAmericanChars.get(b):String.fromCharCode(b);break;case shaka.cea.Cea608Memory.CharSet.SPECIAL_NORTH_AMERICAN:c=shaka.cea.Cea608Memory.CharSet.SpecialNorthAmericanChars.get(b);break;case shaka.cea.Cea608Memory.CharSet.SPANISH_FRENCH:this.eraseChar();
c=shaka.cea.Cea608Memory.CharSet.ExtendedSpanishFrench.get(b);break;case shaka.cea.Cea608Memory.CharSet.PORTUGUESE_GERMAN:this.eraseChar(),c=shaka.cea.Cea608Memory.CharSet.ExtendedPortugueseGerman.get(b)}c&&(a=new shaka.cea.CeaUtils.StyledChar(c,this.underline_,this.italics_,this.backgroundColor_,this.textColor_),this.rows_[this.row_].push(a))}};shaka.cea.Cea608Memory.prototype.eraseChar=function(){this.rows_[this.row_].pop()};
shaka.cea.Cea608Memory.prototype.moveRows=function(a,b,c){if(!(0>b||0>a))if(a>=b)for(--c;0<=c;c--)this.rows_[a+c]=this.rows_[b+c].map(function(e){return e});else for(var d=0;d<c;d++)this.rows_[a+d]=this.rows_[b+d].map(function(e){return e})};shaka.cea.Cea608Memory.prototype.resetRows=function(a,b){for(var c=0;c<=b;c++)this.rows_[a+c]=[]};shaka.cea.Cea608Memory.prototype.resetAllRows=function(){this.resetRows(0,shaka.cea.Cea608Memory.CC_ROWS)};
shaka.cea.Cea608Memory.prototype.eraseBuffer=function(){this.row_=0<this.scrollRows_?this.scrollRows_:0;this.resetAllRows()};shaka.cea.Cea608Memory.prototype.setUnderline=function(a){this.underline_=a};shaka.cea.Cea608Memory.prototype.setItalics=function(a){this.italics_=a};shaka.cea.Cea608Memory.prototype.setTextColor=function(a){this.textColor_=a};shaka.cea.Cea608Memory.prototype.setBackgroundColor=function(a){this.backgroundColor_=a};shaka.cea.Cea608Memory.CC_ROWS=15;
shaka.cea.Cea608Memory.CharSet={BASIC_NORTH_AMERICAN:0,SPECIAL_NORTH_AMERICAN:1,SPANISH_FRENCH:2,PORTUGUESE_GERMAN:3};shaka.cea.Cea608Memory.CharSet.BasicNorthAmericanChars=new Map([[39,"\u2019"],[42,"\u00e1"],[92,"\u00e9"],[92,"\u00e9"],[94,"\u00ed"],[95,"\u00f3"],[96,"\u00fa"],[123,"\u00e7"],[124,"\u00f7"],[125,"\u00d1"],[126,"\u00f1"],[127,"\u2588"]]);
shaka.cea.Cea608Memory.CharSet.SpecialNorthAmericanChars=new Map([[48,"\u00ae"],[49,"\u00b0"],[50,"\u00bd"],[51,"\u00bf"],[52,"\u2122"],[53,"\u00a2"],[54,"\u00a3"],[55,"\u266a"],[56,"\u00e0"],[57,"\u2800"],[58,"\u00e8"],[59,"\u00e2"],[60,"\u00ea"],[61,"\u00ee"],[62,"\u00f4"],[63,"\u00fb"]]);
shaka.cea.Cea608Memory.CharSet.ExtendedSpanishFrench=new Map([[32,"\u00c1"],[33,"\u00c9"],[34,"\u00d3"],[35,"\u00da"],[36,"\u00dc"],[37,"\u00fc"],[38,"\u2018"],[39,"\u00a1"],[40,"*"],[41,"'"],[42,"\u2500"],[43,"\u00a9"],[44,"\u2120"],[45,"\u00b7"],[46,"\u201c"],[47,"\u201d"],[48,"\u00c0"],[49,"\u00c2"],[50,"\u00c7"],[51,"\u00c8"],[52,"\u00ca"],[53,"\u00cb"],[54,"\u00eb"],[55,"\u00ce"],[56,"\u00cf"],[57,"\u00ef"],[58,"\u00d4"],[59,"\u00d9"],[60,"\u00f9"],[61,"\u00db"],[62,"\u00ab"],[63,"\u00bb"]]);
shaka.cea.Cea608Memory.CharSet.ExtendedPortugueseGerman=new Map([[32,"\u00c3"],[33,"\u00e3"],[34,"\u00cd"],[35,"\u00cc"],[36,"\u00ec"],[37,"\u00d2"],[38,"\u00f2"],[39,"\u00d5"],[40,"\u00f5"],[41,"{"],[42,"}"],[43,"\\"],[44,"^"],[45,"_"],[46,"|"],[47,"~"],[48,"\u00c4"],[49,"\u00e4"],[50,"\u00d6"],[51,"\u00f6"],[52,"\u00df"],[53,"\u00a5"],[54,"\u00a4"],[55,"\u2502"],[56,"\u00c5"],[57,"\u00e5"],[58,"\u00d8"],[59,"\u00f8"],[60,"\u250c"],[61,"\u2510"],[62,"\u2514"],[63,"\u2518"]]);shaka.cea.Cea608DataChannel=function(a,b){this.type_=shaka.cea.Cea608DataChannel.CaptionType.NONE;this.text_=new shaka.cea.Cea608Memory(a,b);this.displayedMemory_=new shaka.cea.Cea608Memory(a,b);this.nonDisplayedMemory_=new shaka.cea.Cea608Memory(a,b);this.curbuf_=this.displayedMemory_;this.prevEndTime_=0;this.lastcp_=null};
shaka.cea.Cea608DataChannel.prototype.reset=function(){this.type_=shaka.cea.Cea608DataChannel.CaptionType.PAINTON;this.curbuf_=this.displayedMemory_;this.lastcp_=null;this.displayedMemory_.reset();this.nonDisplayedMemory_.reset();this.text_.reset()};shaka.cea.Cea608DataChannel.prototype.pacToRow_=function(a,b){return[11,11,1,2,3,4,12,13,14,15,5,6,7,8,9,10][(a&7)<<1|b>>5&1]};
shaka.cea.Cea608DataChannel.prototype.controlPac_=function(a,b){a=this.pacToRow_(a,b);var c=(b&30)>>1,d=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR,e=!1;7>c?d=shaka.cea.Cea608DataChannel.TEXT_COLORS[c]:7===c&&(e=!0);b=1===(b&1);if(this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT){c=this.curbuf_;if(this.type_===shaka.cea.Cea608DataChannel.CaptionType.ROLLUP&&a!==c.getRow()){var f=1+c.getRow()-c.getScrollSize(),g=1+a-c.getScrollSize();c.moveRows(g,f,c.getScrollSize());c.resetRows(0,g-1);c.resetRows(a+
1,shaka.cea.Cea608Memory.CC_ROWS-a)}c.setRow(a);this.curbuf_.setUnderline(b);this.curbuf_.setItalics(e);this.curbuf_.setTextColor(d);this.curbuf_.setBackgroundColor(shaka.cea.CeaUtils.DEFAULT_BG_COLOR)}};
shaka.cea.Cea608DataChannel.prototype.controlMidrow_=function(a){this.curbuf_.setUnderline(!1);this.curbuf_.setItalics(!1);this.curbuf_.setTextColor(shaka.cea.CeaUtils.DEFAULT_TXT_COLOR);this.curbuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,32);var b=!1;var c=shaka.cea.Cea608DataChannel.TEXT_COLORS[(a&14)>>1];"white_italics"===c&&(c="white",b=!0);this.curbuf_.setUnderline(1===(a&1));this.curbuf_.setItalics(b);this.curbuf_.setTextColor(c)};
shaka.cea.Cea608DataChannel.prototype.controlBackgroundAttribute_=function(a,b){var c=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;0===(a&7)&&(c=shaka.cea.Cea608DataChannel.BG_COLORS[(b&14)>>1]);this.curbuf_.setBackgroundColor(c)};
shaka.cea.Cea608DataChannel.prototype.controlMiscellaneous_=function(a){var b=shaka.cea.Cea608DataChannel.MiscCmd_,c=a.pts,d=null;switch(a.ccData2){case b.RCL:this.controlRcl_();break;case b.BS:this.controlBs_();break;case b.RU2:d=this.controlRu_(2,c);break;case b.RU3:d=this.controlRu_(3,c);break;case b.RU4:d=this.controlRu_(4,c);break;case b.FON:this.controlFon_();break;case b.RDC:this.controlRdc_(c);break;case b.TR:this.controlTr_();break;case b.RTD:this.controlRtd_();break;case b.EDM:d=this.controlEdm_(c);
break;case b.CR:d=this.controlCr_(c);break;case b.ENM:this.controlEnm_();break;case b.EOC:d=this.controlEoc_(c)}return d};shaka.cea.Cea608DataChannel.prototype.controlCr_=function(a){var b=this.curbuf_;if(this.type_!==shaka.cea.Cea608DataChannel.CaptionType.ROLLUP)return null;var c=b.forceEmit(this.prevEndTime_,a),d=b.getRow()-b.getScrollSize()+1;b.moveRows(d-1,d,b.getScrollSize());b.resetRows(0,d-1);b.resetRows(b.getRow(),shaka.cea.Cea608Memory.CC_ROWS-b.getRow());this.prevEndTime_=a;return c};
shaka.cea.Cea608DataChannel.prototype.controlRu_=function(a,b){var c=this.curbuf_=this.displayedMemory_,d=null;this.type_!==shaka.cea.Cea608DataChannel.CaptionType.ROLLUP&&this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT&&(d=c.forceEmit(this.prevEndTime_,b),this.displayedMemory_.eraseBuffer(),this.nonDisplayedMemory_.eraseBuffer(),c.setRow(shaka.cea.Cea608Memory.CC_ROWS));this.type_=shaka.cea.Cea608DataChannel.CaptionType.ROLLUP;c.setScrollSize(a);return d};
shaka.cea.Cea608DataChannel.prototype.controlFon_=function(){this.curbuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,32)};shaka.cea.Cea608DataChannel.prototype.controlEdm_=function(a){var b=this.displayedMemory_,c=null;this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT&&(c=b.forceEmit(this.prevEndTime_,a));b.resetAllRows();return c};
shaka.cea.Cea608DataChannel.prototype.controlRdc_=function(a){this.type_=shaka.cea.Cea608DataChannel.CaptionType.PAINTON;this.curbuf_=this.displayedMemory_;this.curbuf_.setScrollSize(0);this.prevEndTime_=a};shaka.cea.Cea608DataChannel.prototype.controlEnm_=function(){this.nonDisplayedMemory_.resetAllRows()};
shaka.cea.Cea608DataChannel.prototype.controlEoc_=function(a){var b=null;this.type_!==shaka.cea.Cea608DataChannel.CaptionType.TEXT&&(b=this.displayedMemory_.forceEmit(this.prevEndTime_,a));var c=this.nonDisplayedMemory_;this.nonDisplayedMemory_=this.displayedMemory_;this.displayedMemory_=c;this.controlRcl_();this.prevEndTime_=a;return b};shaka.cea.Cea608DataChannel.prototype.controlRcl_=function(){this.type_=shaka.cea.Cea608DataChannel.CaptionType.POPON;this.curbuf_=this.nonDisplayedMemory_;this.curbuf_.setScrollSize(0)};
shaka.cea.Cea608DataChannel.prototype.controlBs_=function(){this.curbuf_.eraseChar()};shaka.cea.Cea608DataChannel.prototype.controlTr_=function(){this.text_.reset();this.controlRtd_()};shaka.cea.Cea608DataChannel.prototype.controlRtd_=function(){shaka.log.warnOnce("Cea608DataChannel","CEA-608 text mode entered, but is unsupported");this.curbuf_=this.text_;this.type_=shaka.cea.Cea608DataChannel.CaptionType.TEXT};
shaka.cea.Cea608DataChannel.prototype.handleBasicNorthAmericanChar=function(a,b){this.curbuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,a);this.curbuf_.addChar(shaka.cea.Cea608Memory.CharSet.BASIC_NORTH_AMERICAN,b)};shaka.cea.Cea608DataChannel.prototype.handleExtendedWesternEuropeanChar_=function(a,b){this.curbuf_.addChar(a&1?shaka.cea.Cea608Memory.CharSet.PORTUGUESE_GERMAN:shaka.cea.Cea608Memory.CharSet.SPANISH_FRENCH,b)};
shaka.cea.Cea608DataChannel.prototype.handleControlCode=function(a){var b=a.ccData1,c=a.ccData2;if(this.lastcp_===(b<<8|c))return this.lastcp_=null;this.lastcp_=b<<8|c;if(this.isPAC_(b,c))this.controlPac_(b,c);else if(this.isMidrowStyleChange_(b,c))this.controlMidrow_(c);else if(this.isBackgroundAttribute_(b,c))this.controlBackgroundAttribute_(b,c);else if(this.isSpecialNorthAmericanChar_(b,c))this.curbuf_.addChar(shaka.cea.Cea608Memory.CharSet.SPECIAL_NORTH_AMERICAN,c);else if(this.isExtendedWesternEuropeanChar_(b,
c))this.handleExtendedWesternEuropeanChar_(b,c);else if(this.isMiscellaneous_(b,c))return this.controlMiscellaneous_(a);return null};shaka.cea.Cea608DataChannel.prototype.isMiscellaneous_=function(a,b){return 20===(a&246)&&32===(b&240)};shaka.cea.Cea608DataChannel.prototype.isPAC_=function(a,b){return 16===(a&240)&&64===(b&192)};shaka.cea.Cea608DataChannel.prototype.isMidrowStyleChange_=function(a,b){return 17===(a&247)&&32===(b&240)};
shaka.cea.Cea608DataChannel.prototype.isBackgroundAttribute_=function(a,b){return 16===(a&247)&&32===(b&240)||23===(a&247)&&45===(b&255)};shaka.cea.Cea608DataChannel.prototype.isSpecialNorthAmericanChar_=function(a,b){return 17===(a&247)&&48===(b&240)};shaka.cea.Cea608DataChannel.prototype.isExtendedWesternEuropeanChar_=function(a,b){return 18===(a&246)&&32===(b&224)};shaka.cea.Cea608DataChannel.isControlCode=function(a){return 16===(a&112)};
shaka.cea.Cea608DataChannel.MiscCmd_={RCL:32,BS:33,AOD:34,AON:35,DER:36,RU2:37,RU3:38,RU4:39,FON:40,RDC:41,TR:42,RTD:43,EDM:44,CR:45,ENM:46,EOC:47};shaka.cea.Cea608DataChannel.CaptionType={NONE:0,POPON:1,PAINTON:2,ROLLUP:3,TEXT:4};shaka.cea.Cea608DataChannel.BG_COLORS="black green blue cyan red yellow magenta black".split(" ");shaka.cea.Cea608DataChannel.TEXT_COLORS="white green blue cyan red yellow magenta white_italics".split(" ");shaka.cea.Cea708Window=function(a){this.windowNum_=a;this.relativeToggle_=this.visible_=!1;this.colCount_=this.rowCount_=this.anchorId_=this.verticalAnchor_=this.horizontalAnchor_=0;this.justification_=shaka.cea.Cea708Window.TextJustification.CENTER;this.memory_=[];this.col_=this.row_=this.startTime_=0;this.underline_=this.italics_=!1;this.textColor_=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;this.backgroundColor_=shaka.cea.CeaUtils.DEFAULT_BG_COLOR;this.resetMemory();shaka.util.Functional.ignored(this.verticalAnchor_,
this.relativeToggle_,this.horizontalAnchor_,this.anchorId_,this.windowNum_)};shaka.cea.Cea708Window.prototype.defineWindow=function(a,b,c,d,e,f,g){this.visible_=a;this.verticalAnchor_=b;this.horizontalAnchor_=c;this.anchorId_=d;this.relativeToggle_=e;this.rowCount_=f;this.colCount_=g};shaka.cea.Cea708Window.prototype.resetMemory=function(){this.memory_=[];for(var a=0;a<shaka.cea.Cea708Window.MAX_ROWS;a++)this.memory_.push(this.createNewRow_())};
shaka.cea.Cea708Window.prototype.createNewRow_=function(){for(var a=[],b=0;b<shaka.cea.Cea708Window.MAX_COLS;b++)a.push(null);return a};shaka.cea.Cea708Window.prototype.setCharacter=function(a){this.isPenInBounds_()&&(a=new shaka.cea.CeaUtils.StyledChar(a,this.underline_,this.italics_,this.backgroundColor_,this.textColor_),this.memory_[this.row_][this.col_]=a,this.col_++)};
shaka.cea.Cea708Window.prototype.backspace=function(){!this.isPenInBounds_()||0>=this.col_&&0>=this.row_||(0>=this.col_?(this.col_=this.colCount_-1,this.row_--):this.col_--,this.memory_[this.row_][this.col_]=null)};shaka.cea.Cea708Window.prototype.isPenInBounds_=function(){var a=this.col_<this.colCount_&&0<=this.col_;return this.row_<this.rowCount_&&0<=this.row_&&a};shaka.cea.Cea708Window.prototype.isVisible=function(){return this.visible_};
shaka.cea.Cea708Window.prototype.moveUpRows_=function(a){for(var b=0,c=a;c<shaka.cea.Cea708Window.MAX_ROWS;c++,b++)this.memory_[b]=this.memory_[c];for(c=0;c<a;c++,b++)this.memory_[b]=this.createNewRow_()};shaka.cea.Cea708Window.prototype.carriageReturn=function(){this.row_+1>=this.rowCount_?this.moveUpRows_(1):this.row_++;this.col_=0};shaka.cea.Cea708Window.prototype.horizontalCarriageReturn=function(){this.memory_[this.row_]=this.createNewRow_();this.col_=0};
shaka.cea.Cea708Window.prototype.forceEmit=function(a,b){b="svc"+b;var c=shaka.cea.Cea708Window.TextJustification,d=new shaka.text.Cue(this.startTime_,a,"");d.textAlign=this.justification_===c.LEFT?shaka.text.Cue.textAlign.LEFT:this.justification_===c.RIGHT?shaka.text.Cue.textAlign.RIGHT:shaka.text.Cue.textAlign.CENTER;(b=shaka.cea.CeaUtils.getParsedCaption(d,b,this.memory_,this.startTime_,a))&&this.setStartTime(a);return b};
shaka.cea.Cea708Window.prototype.setPenLocation=function(a,b){this.row_=a;this.col_=b};shaka.cea.Cea708Window.prototype.setPenBackgroundColor=function(a){this.backgroundColor_=a};shaka.cea.Cea708Window.prototype.setPenTextColor=function(a){this.textColor_=a};shaka.cea.Cea708Window.prototype.setPenUnderline=function(a){this.underline_=a};shaka.cea.Cea708Window.prototype.setPenItalics=function(a){this.italics_=a};
shaka.cea.Cea708Window.prototype.resetPen=function(){this.col_=this.row_=0;this.italics_=this.underline_=!1;this.textColor_=shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;this.backgroundColor_=shaka.cea.CeaUtils.DEFAULT_BG_COLOR};shaka.cea.Cea708Window.prototype.setJustification=function(a){this.justification_=a};shaka.cea.Cea708Window.prototype.display=function(){this.visible_=!0};shaka.cea.Cea708Window.prototype.hide=function(){this.visible_=!1};
shaka.cea.Cea708Window.prototype.toggle=function(){this.visible_=!this.visible_};shaka.cea.Cea708Window.prototype.setStartTime=function(a){this.startTime_=a};shaka.cea.Cea708Window.TextJustification={LEFT:0,RIGHT:1,CENTER:2,FULL:3};shaka.cea.Cea708Window.MAX_COLS=42;shaka.cea.Cea708Window.MAX_ROWS=16;shaka.cea.DtvccPacketBuilder=function(){this.builtPackets_=[];this.currentPacketBeingBuilt_=null;this.bytesLeftToAddInCurrentPacket_=0};
shaka.cea.DtvccPacketBuilder.prototype.addByte=function(a){a.type===shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_START?(this.bytesLeftToAddInCurrentPacket_=2*(a.value&63)-1,this.currentPacketBeingBuilt_=[]):this.currentPacketBeingBuilt_&&(0<this.bytesLeftToAddInCurrentPacket_&&(this.currentPacketBeingBuilt_.push(a),this.bytesLeftToAddInCurrentPacket_--),0===this.bytesLeftToAddInCurrentPacket_&&(a=new shaka.cea.DtvccPacket(this.currentPacketBeingBuilt_),this.builtPackets_.push(a),this.currentPacketBeingBuilt_=
null,this.bytesLeftToAddInCurrentPacket_=0))};shaka.cea.DtvccPacketBuilder.prototype.getBuiltPackets=function(){return this.builtPackets_};shaka.cea.DtvccPacketBuilder.prototype.clearBuiltPackets=function(){this.builtPackets_=[]};shaka.cea.DtvccPacketBuilder.prototype.clear=function(){this.builtPackets_=[];this.currentPacketBeingBuilt_=[];this.bytesLeftToAddInCurrentPacket_=0};shaka.cea.DtvccPacket=function(a){this.pos_=0;this.packetData_=a};
shaka.cea.DtvccPacket.prototype.hasMoreData=function(){return this.pos_<this.packetData_.length};shaka.cea.DtvccPacket.prototype.getPosition=function(){return this.pos_};shaka.cea.DtvccPacket.prototype.readByte=function(){if(!this.hasMoreData())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS);return this.packetData_[this.pos_++]};
shaka.cea.DtvccPacket.prototype.skip=function(a){if(this.pos_+a>this.packetData_.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS);this.pos_+=a};shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_DATA=2;shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_START=3;shaka.cea.Cea708Service=function(a){this.serviceNumber_=a;this.windows_=[null,null,null,null,null,null,null,null];this.currentWindow_=null};
shaka.cea.Cea708Service.prototype.handleCea708ControlCode=function(a){var b=a.readByte(),c=b.value;b=b.pts;if(c===shaka.cea.Cea708Service.EXT_CEA708_CTRL_CODE_BYTE1){var d=a.readByte();c=c<<16|d.value}if(0<=c&&31>=c)return this.handleC0_(c,b);if(128<=c&&159>=c)return this.handleC1_(a,c,b);4096<=c&&4127>=c?this.handleC2_(a,c&255):4224<=c&&4255>=c?this.handleC3_(a,c&255):32<=c&&127>=c?this.handleG0_(c):160<=c&&255>=c?this.handleG1_(c):4128<=c&&4223>=c?this.handleG2_(c&255):4256<=c&&4351>=c&&this.handleG3_(c&
255);return null};shaka.cea.Cea708Service.prototype.handleG0_=function(a){this.currentWindow_&&(127===a?this.currentWindow_.setCharacter("\u266a"):this.currentWindow_.setCharacter(String.fromCharCode(a)))};shaka.cea.Cea708Service.prototype.handleG1_=function(a){this.currentWindow_&&this.currentWindow_.setCharacter(String.fromCharCode(a))};
shaka.cea.Cea708Service.prototype.handleG2_=function(a){this.currentWindow_&&(shaka.cea.Cea708Service.G2Charset.has(a)?(a=shaka.cea.Cea708Service.G2Charset.get(a),this.currentWindow_.setCharacter(a)):this.currentWindow_.setCharacter("_"))};shaka.cea.Cea708Service.prototype.handleG3_=function(a){this.currentWindow_&&(160!=a?this.currentWindow_.setCharacter("_"):this.currentWindow_.setCharacter("[CC]"))};
shaka.cea.Cea708Service.prototype.handleC0_=function(a,b){if(!this.currentWindow_)return null;var c=this.currentWindow_,d=null;switch(a){case shaka.cea.Cea708Service.ASCII_BACKSPACE:c.backspace();break;case shaka.cea.Cea708Service.ASCII_CARRIAGE_RETURN:c.isVisible()&&(d=c.forceEmit(b,this.serviceNumber_));c.carriageReturn();break;case shaka.cea.Cea708Service.ASCII_HOR_CARRIAGE_RETURN:c.isVisible()&&(d=c.forceEmit(b,this.serviceNumber_));c.horizontalCarriageReturn();break;case shaka.cea.Cea708Service.ASCII_FORM_FEED:c.isVisible()&&
(d=c.forceEmit(b,this.serviceNumber_)),c.resetMemory(),c.setPenLocation(0,0)}return d};
shaka.cea.Cea708Service.prototype.handleC1_=function(a,b,c){if(128<=b&&135>=b)this.setCurrentWindow_(b&7);else{if(136===b)return a=a.readByte().value,this.clearWindows_(a,c);if(137===b)a=a.readByte().value,this.displayWindows_(a,c);else{if(138===b)return a=a.readByte().value,this.hideWindows_(a,c);if(139===b)return a=a.readByte().value,this.toggleWindows_(a,c);if(140===b)return a=a.readByte().value,this.deleteWindows_(a,c);if(143===b)return this.reset_(c);144===b?this.setPenAttributes_(a):145===b?
this.setPenColor_(a):146===b?this.setPenLocation_(a):151===b?this.setWindowAttributes_(a):152<=b&&159>=b&&this.defineWindow_(a,(b&15)-8,c)}}return null};shaka.cea.Cea708Service.prototype.handleC2_=function(a,b){8<=b&&15>=b?a.skip(1):16<=b&&23>=b?a.skip(2):24<=b&&31>=b&&a.skip(3)};shaka.cea.Cea708Service.prototype.handleC3_=function(a,b){128<=b&&135>=b?a.skip(4):136<=b&&143>=b&&a.skip(5)};shaka.cea.Cea708Service.prototype.setCurrentWindow_=function(a){this.windows_[a]&&(this.currentWindow_=this.windows_[a])};
shaka.cea.Cea708Service.prototype.getSpecifiedWindowIds_=function(a){for(var b=[],c=0;8>c;c++)1===(a&1)&&this.windows_[c]&&b.push(c),a>>=1;return b};shaka.cea.Cea708Service.prototype.clearWindows_=function(a,b){var c=null;a=$jscomp.makeIterator(this.getSpecifiedWindowIds_(a));for(var d=a.next();!d.done;d=a.next())d=this.windows_[d.value],d.isVisible()&&(c=d.forceEmit(b,this.serviceNumber_)),d.resetMemory();return c};
shaka.cea.Cea708Service.prototype.displayWindows_=function(a,b){a=$jscomp.makeIterator(this.getSpecifiedWindowIds_(a));for(var c=a.next();!c.done;c=a.next())c=this.windows_[c.value],c.isVisible()||c.setStartTime(b),c.display()};shaka.cea.Cea708Service.prototype.hideWindows_=function(a,b){var c=null;a=$jscomp.makeIterator(this.getSpecifiedWindowIds_(a));for(var d=a.next();!d.done;d=a.next())d=this.windows_[d.value],d.isVisible()&&(c=d.forceEmit(b,this.serviceNumber_)),d.hide();return c};
shaka.cea.Cea708Service.prototype.toggleWindows_=function(a,b){var c=null;a=$jscomp.makeIterator(this.getSpecifiedWindowIds_(a));for(var d=a.next();!d.done;d=a.next())d=this.windows_[d.value],d.isVisible()?c=d.forceEmit(b,this.serviceNumber_):d.setStartTime(b),d.toggle();return c};
shaka.cea.Cea708Service.prototype.deleteWindows_=function(a,b){var c=null;a=$jscomp.makeIterator(this.getSpecifiedWindowIds_(a));for(var d=a.next();!d.done;d=a.next()){d=d.value;var e=this.windows_[d];e.isVisible()&&(c=e.forceEmit(b,this.serviceNumber_));this.windows_[d]=null}return c};shaka.cea.Cea708Service.prototype.reset_=function(a){a=this.deleteWindows_(255,a);this.clear();return a};
shaka.cea.Cea708Service.prototype.clear=function(){this.currentWindow_=null;this.windows_=[null,null,null,null,null,null,null,null]};shaka.cea.Cea708Service.prototype.setPenAttributes_=function(a){a.skip(1);a=a.readByte().value;if(this.currentWindow_){var b=0<(a&64);this.currentWindow_.setPenItalics(0<(a&128));this.currentWindow_.setPenUnderline(b)}};
shaka.cea.Cea708Service.prototype.setPenColor_=function(a){var b=a.readByte().value,c=a.readByte().value;a.skip(1);if(this.currentWindow_){a=c&3;var d=(c&12)>>2;c=(c&48)>>4;b=this.rgbColorToHex_((b&48)>>4,(b&12)>>2,b&3);a=this.rgbColorToHex_(c,d,a);this.currentWindow_.setPenTextColor(b);this.currentWindow_.setPenBackgroundColor(a)}};
shaka.cea.Cea708Service.prototype.setPenLocation_=function(a){var b=a.readByte().value;a=a.readByte().value;this.currentWindow_&&this.currentWindow_.setPenLocation(b&15,a&63)};shaka.cea.Cea708Service.prototype.setWindowAttributes_=function(a){a.skip(1);a.skip(1);var b=a.readByte().value;a.skip(1);this.currentWindow_&&this.currentWindow_.setJustification(b&3)};
shaka.cea.Cea708Service.prototype.defineWindow_=function(a,b,c){var d=null!==this.windows_[b];if(!d){var e=new shaka.cea.Cea708Window(b);e.setStartTime(c);this.windows_[b]=e}var f=a.readByte().value,g=a.readByte().value;c=a.readByte().value;var h=a.readByte().value;e=a.readByte().value;a=a.readByte().value;f=0<(f&32);var k=g&127;g=0<(g&128);var l=(h&15)+1;h=(h&240)>>4;e=(e&63)+1;d&&0===(a&7)||this.windows_[b].resetPen();this.windows_[b].defineWindow(f,k,c,h,g,l,e);this.currentWindow_=this.windows_[b]};
shaka.cea.Cea708Service.prototype.rgbColorToHex_=function(a,b,c){var d={0:0,1:0,2:1,3:1};a=d[a];b=d[b];c=d[c];return shaka.cea.Cea708Service.Colors[a<<2|b<<1|c]};shaka.cea.Cea708Service.ASCII_BACKSPACE=8;shaka.cea.Cea708Service.ASCII_FORM_FEED=12;shaka.cea.Cea708Service.ASCII_CARRIAGE_RETURN=13;shaka.cea.Cea708Service.ASCII_HOR_CARRIAGE_RETURN=14;shaka.cea.Cea708Service.EXT_CEA708_CTRL_CODE_BYTE1=16;
shaka.cea.Cea708Service.G2Charset=new Map([[32," "],[33,"\u00a0"],[37,"\u2026"],[42,"\u0160"],[44,"\u0152"],[48,"\u2588"],[49,"\u2018"],[50,"\u2019"],[51,"\u201c"],[52,"\u201d"],[53,"\u2022"],[57,"\u2122"],[58,"\u0161"],[60,"\u0153"],[61,"\u2120"],[63,"\u0178"],[118,"\u215b"],[119,"\u215c"],[120,"\u215d"],[121,"\u215e"],[122,"\u2502"],[123,"\u2510"],[124,"\u2514"],[125,"\u2500"],[126,"\u2518"],[127,"\u250c"]]);shaka.cea.Cea708Service.Colors="black blue green cyan red magenta yellow white".split(" ");shaka.cea.CeaDecoder=function(){this.cea608DataArray_=[];this.cea708DataArray_=[];this.dtvccPacketBuilder_=new shaka.cea.DtvccPacketBuilder;this.badFrames_=0;this.cea608ModeToStream_=new Map([["CC1",new shaka.cea.Cea608DataChannel(0,0)],["CC2",new shaka.cea.Cea608DataChannel(0,1)],["CC3",new shaka.cea.Cea608DataChannel(1,0)],["CC4",new shaka.cea.Cea608DataChannel(1,1)]]);this.currentField2Channel_=this.currentField1Channel_=0;this.serviceNumberToService_=new Map;this.reset()};
shaka.cea.CeaDecoder.prototype.clear=function(){this.badFrames_=0;this.cea608DataArray_=[];this.cea708DataArray_=[];this.dtvccPacketBuilder_.clear();this.reset();for(var a=$jscomp.makeIterator(this.serviceNumberToService_.values()),b=a.next();!b.done;b=a.next())b.value.clear()};shaka.cea.CeaDecoder.prototype.reset=function(){this.currentField2Channel_=this.currentField1Channel_=0;for(var a=$jscomp.makeIterator(this.cea608ModeToStream_.values()),b=a.next();!b.done;b=a.next())b.value.reset()};
shaka.cea.CeaDecoder.prototype.extract=function(a,b){a=new shaka.util.DataViewReader(a,shaka.util.DataViewReader.Endianness.BIG_ENDIAN);if(a.readUint8()===shaka.cea.CeaDecoder.USA_COUNTRY_CODE&&a.readUint16()===shaka.cea.CeaDecoder.ATSC_PROVIDER_CODE&&a.readUint32()===shaka.cea.CeaDecoder.ATSC1_USER_IDENTIFIER&&3===a.readUint8()){var c=a.readUint8();if(0!==(c&64)){c&=31;a.skip(1);for(var d=0;d<c;d++){var e=a.readUint8(),f=(e&4)>>2,g=a.readUint8(),h=a.readUint8();f&&(e&=3,e===shaka.cea.CeaDecoder.NTSC_CC_FIELD_1||
e===shaka.cea.CeaDecoder.NTSC_CC_FIELD_2?this.cea608DataArray_.push({pts:b,type:e,ccData1:g,ccData2:h,order:this.cea608DataArray_.length}):(this.cea708DataArray_.push({pts:b,type:e,value:g,order:this.cea708DataArray_.length}),this.cea708DataArray_.push({pts:b,type:shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_DATA,value:h,order:this.cea708DataArray_.length})))}}}};
shaka.cea.CeaDecoder.prototype.decode=function(){var a=[],b=function(d,e){return d.pts-e.pts||d.order-e.order};this.cea608DataArray_.sort(b);this.cea708DataArray_.sort(b);b=$jscomp.makeIterator(this.cea608DataArray_);for(var c=b.next();!c.done;c=b.next())(c=this.decodeCea608_(c.value))&&a.push(c);b=$jscomp.makeIterator(this.cea708DataArray_);for(c=b.next();!c.done;c=b.next())this.dtvccPacketBuilder_.addByte(c.value);b=this.dtvccPacketBuilder_.getBuiltPackets();b=$jscomp.makeIterator(b);for(c=b.next();!c.done;c=
b.next())c=this.decodeCea708_(c.value),a.push.apply(a,$jscomp.arrayFromIterable(c));this.dtvccPacketBuilder_.clearBuiltPackets();this.cea608DataArray_=[];this.cea708DataArray_=[];return a};
shaka.cea.CeaDecoder.prototype.decodeCea608_=function(a){var b=a.type;if(shaka.cea.Cea608DataChannel.isControlCode(a.ccData1)){var c=a.ccData1>>3&1;0===b?this.currentField1Channel_=c:this.currentField2Channel_=c}b=this.cea608ModeToStream_.get("CC"+(b<<1|(b?this.currentField2Channel_:this.currentField1Channel_)+1));if(255===a.ccData1&&255===a.ccData2||!a.ccData1&&!a.ccData2||!this.isOddParity_(a.ccData1)||!this.isOddParity_(a.ccData2))return 45<=++this.badFrames_&&this.reset(),null;this.badFrames_=
0;a.ccData1&=127;a.ccData2&=127;if(!a.ccData1&&!a.ccData2)return null;c=null;shaka.cea.Cea608DataChannel.isControlCode(a.ccData1)?c=b.handleControlCode(a):b.handleBasicNorthAmericanChar(a.ccData1,a.ccData2);return c};
shaka.cea.CeaDecoder.prototype.decodeCea708_=function(a){var b=[];try{for(;a.hasMoreData();){var c=a.readByte().value,d=(c&224)>>5,e=c&31;7===d&&0!=e&&(d=a.readByte().value&63);if(0!=d){if(!this.serviceNumberToService_.has(d)){var f=new shaka.cea.Cea708Service(d);this.serviceNumberToService_.set(d,f)}for(var g=this.serviceNumberToService_.get(d),h=a.getPosition();a.getPosition()-h<e;){var k=g.handleCea708ControlCode(a);k&&b.push(k)}}}}catch(l){if(l instanceof shaka.util.Error&&l.code===shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS)shaka.log.warnOnce("CEA708_INVALID_DATA",
"Buffer read out of bounds / invalid CEA-708 Data.");else throw l;}return b};shaka.cea.CeaDecoder.prototype.isOddParity_=function(a){for(var b=0;a;)b^=a&1,a>>=1;return 1===b};shaka.cea.CeaDecoder.ATSC_PROVIDER_CODE=49;shaka.cea.CeaDecoder.ATSC1_USER_IDENTIFIER=1195456820;shaka.cea.CeaDecoder.NTSC_CC_FIELD_1=0;shaka.cea.CeaDecoder.NTSC_CC_FIELD_2=1;shaka.cea.CeaDecoder.USA_COUNTRY_CODE=181;shaka.cea.ICeaParser=function(){};shaka.cea.ICeaParser.prototype.init=function(a){};shaka.cea.ICeaParser.prototype.parse=function(a){};shaka.cea.ICeaParser.H264_NALU_TYPE_SEI=6;shaka.cea.ICeaParser.H265_PREFIX_NALU_TYPE_SEI=39;shaka.cea.ICeaParser.H265_SUFFIX_NALU_TYPE_SEI=40;shaka.cea.ICeaParser.DEFAULT_TIMESCALE_VALUE=9E4;shaka.cea.DummyCeaParser=function(){};shaka.cea.DummyCeaParser.prototype.init=function(a){};shaka.cea.DummyCeaParser.prototype.parse=function(a){return[]};shaka.cea.SeiProcessor=function(){};shaka.cea.SeiProcessor.prototype.process=function(a){var b=[];a=this.removeEmu(a);for(var c=0;c<a.length;){for(var d=0;255==a[c];)d+=255,c++;d+=a[c++];for(var e=0;255==a[c];)e+=255,c++;e+=a[c++];4==d&&b.push(a.subarray(c,c+e));c+=e}return b};shaka.cea.SeiProcessor.prototype.removeEmu=function(a){for(var b=a,c=a=0;c<b.length;)2==a&&3==b[c]?(a=0,b=[].concat($jscomp.arrayFromIterable(b)),b.splice(c,1),b=new Uint8Array(b)):0==b[c]?a++:a=0,c++;return b};shaka.util.Mp4BoxParsers=function(){};shaka.util.Mp4BoxParsers.parseTFHD=function(a,b){var c=null,d=null,e=null,f=a.readUint32();b&1&&(e=a.readUint64());b&2&&a.skip(4);b&8&&(c=a.readUint32());b&16&&(d=a.readUint32());return{trackId:f,defaultSampleDuration:c,defaultSampleSize:d,baseDataOffset:e}};shaka.util.Mp4BoxParsers.parseTFDT=function(a,b){return{baseMediaDecodeTime:1==b?a.readUint64():a.readUint32()}};
shaka.util.Mp4BoxParsers.parseMDHD=function(a,b){1==b?(a.skip(8),a.skip(8)):(a.skip(4),a.skip(4));return{timescale:a.readUint32()}};shaka.util.Mp4BoxParsers.parseTREX=function(a){a.skip(4);a.skip(4);var b=a.readUint32();a=a.readUint32();return{defaultSampleDuration:b,defaultSampleSize:a}};
shaka.util.Mp4BoxParsers.parseTRUN=function(a,b,c){var d=a.readUint32(),e=[],f=null;c&1&&(f=a.readUint32());c&4&&a.skip(4);for(var g=0;g<d;g++){var h={sampleDuration:null,sampleSize:null,sampleCompositionTimeOffset:null};c&256&&(h.sampleDuration=a.readUint32());c&512&&(h.sampleSize=a.readUint32());c&1024&&a.skip(4);c&2048&&(h.sampleCompositionTimeOffset=0==b?a.readUint32():a.readInt32());e.push(h)}return{sampleCount:d,sampleData:e,dataOffset:f}};
shaka.util.Mp4BoxParsers.parseTKHD=function(a,b){1==b?(a.skip(8),a.skip(8)):(a.skip(4),a.skip(4));return{trackId:a.readUint32()}};shaka.util.Mp4BoxParsers.parseFRMA=function(a){a=a.readUint32();return{codec:shaka.util.Mp4Parser.typeToString(a)}};shaka.cea.Mp4CeaParser=function(){this.seiProcessor_=new shaka.cea.SeiProcessor;this.trackIdToTimescale_=new Map;this.defaultSampleSize_=this.defaultSampleDuration_=0;this.bitstreamFormat_=shaka.cea.Mp4CeaParser.BitstreamFormat.UNKNOWN};
shaka.cea.Mp4CeaParser.prototype.init=function(a){var b=this,c=shaka.util.Mp4Parser,d=shaka.cea.Mp4CeaParser.BitstreamFormat,e=[],f=[],g=function(h){return b.setBitstreamFormat_(h.name)};(new c).box("moov",c.children).box("mvex",c.children).fullBox("trex",function(h){h=shaka.util.Mp4BoxParsers.parseTREX(h.reader);b.defaultSampleDuration_=h.defaultSampleDuration;b.defaultSampleSize_=h.defaultSampleSize}).box("trak",c.children).fullBox("tkhd",function(h){goog.asserts.assert(null!=h.version,"TKHD is a full box and should have a valid version.");
h=shaka.util.Mp4BoxParsers.parseTKHD(h.reader,h.version);e.push(h.trackId)}).box("mdia",c.children).fullBox("mdhd",function(h){goog.asserts.assert(null!=h.version,"MDHD is a full box and should have a valid version.");h=shaka.util.Mp4BoxParsers.parseMDHD(h.reader,h.version);f.push(h.timescale)}).box("minf",c.children).box("stbl",c.children).fullBox("stsd",c.sampleDescription).box("avc1",g).box("avc3",g).box("hev1",g).box("hvc1",g).box("dvh1",g).box("dvhe",g).box("encv",c.visualSampleEntry).box("sinf",
c.children).box("frma",function(h){h=shaka.util.Mp4BoxParsers.parseFRMA(h.reader).codec;b.setBitstreamFormat_(h)}).parse(a,!0);if(!e.length||!f.length||e.length!=f.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_CEA);this.bitstreamFormat_==d.UNKNOWN&&shaka.log.alwaysWarn("Unable to determine bitstream format for CEA parsing!");e.forEach(function(h,k){b.trackIdToTimescale_.set(h,f[k])})};
shaka.cea.Mp4CeaParser.prototype.parse=function(a){var b=this,c=shaka.util.Mp4Parser;if(this.bitstreamFormat_==shaka.cea.Mp4CeaParser.BitstreamFormat.UNKNOWN)return[];var d=[],e=this.defaultSampleDuration_,f=this.defaultSampleSize_,g=[],h=null,k=null,l=null,m=shaka.cea.ICeaParser.DEFAULT_TIMESCALE_VALUE;(new c).box("moof",function(n){h=n.start;c.children(n)}).box("traf",c.children).fullBox("trun",function(n){goog.asserts.assert(null!=n.version&&null!=n.flags,"TRUN is a full box and should have a valid version & flags.");
n=shaka.util.Mp4BoxParsers.parseTRUN(n.reader,n.version,n.flags);g=n.sampleData;k=n.dataOffset}).fullBox("tfhd",function(n){goog.asserts.assert(null!=n.flags,"TFHD is a full box and should have valid flags.");n=shaka.util.Mp4BoxParsers.parseTFHD(n.reader,n.flags);e=n.defaultSampleDuration||b.defaultSampleDuration_;f=n.defaultSampleSize||b.defaultSampleSize_;n=n.trackId;b.trackIdToTimescale_.has(n)&&(m=b.trackIdToTimescale_.get(n))}).fullBox("tfdt",function(n){goog.asserts.assert(null!=n.version,"TFDT is a full box and should have a valid version.");
l=shaka.util.Mp4BoxParsers.parseTFDT(n.reader,n.version).baseMediaDecodeTime}).box("mdat",function(n){if(null===l)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_CEA);b.parseMdat_(n.reader,l,m,e,f,(h||0)+(k||0)-n.start-8,g,d)}).parse(a,!1);return d};
shaka.cea.Mp4CeaParser.prototype.parseMdat_=function(a,b,c,d,e,f,g,h){var k=shaka.cea.Mp4CeaParser.BitstreamFormat,l=shaka.cea.ICeaParser,m=0,n=e;g.length&&(n=g[0].sampleSize||e);for(a.skip(f);a.hasMoreData();){f=a.readUint32();var p=a.readUint8();goog.asserts.assert(this.bitstreamFormat_!=k.UNKNOWN,"Bitstream format should have been checked before now!");switch(this.bitstreamFormat_){case k.H264:p&=31;p=p==l.H264_NALU_TYPE_SEI;break;case k.H265:p=p>>1&63;p=p==l.H265_PREFIX_NALU_TYPE_SEI||p==l.H265_SUFFIX_NALU_TYPE_SEI;
break;default:return}if(p){p=0;g.length>m&&(p=g[m].sampleCompositionTimeOffset||0);p=(b+p)/c;for(var q=$jscomp.makeIterator(this.seiProcessor_.process(a.readBytes(f-1))),r=q.next();!r.done;r=q.next())h.push({packet:r.value,pts:p})}else try{a.skip(f-1)}catch(w){break}n-=f+4;0==n&&(b=g.length>m?b+(g[m].sampleDuration||d):b+d,m++,n=g.length>m?g[m].sampleSize||e:e)}};
shaka.cea.Mp4CeaParser.prototype.setBitstreamFormat_=function(a){a in shaka.cea.Mp4CeaParser.CodecBitstreamMap_&&(this.bitstreamFormat_=shaka.cea.Mp4CeaParser.CodecBitstreamMap_[a])};shaka.cea.Mp4CeaParser.BitstreamFormat={UNKNOWN:0,H264:1,H265:2};
shaka.cea.Mp4CeaParser.CodecBitstreamMap_={avc1:shaka.cea.Mp4CeaParser.BitstreamFormat.H264,avc3:shaka.cea.Mp4CeaParser.BitstreamFormat.H264,hev1:shaka.cea.Mp4CeaParser.BitstreamFormat.H265,hvc1:shaka.cea.Mp4CeaParser.BitstreamFormat.H265,dvh1:shaka.cea.Mp4CeaParser.BitstreamFormat.H265,dvhe:shaka.cea.Mp4CeaParser.BitstreamFormat.H265};shaka.media.IClosedCaptionParser=function(){};shaka.media.IClosedCaptionParser.prototype.init=function(a){};shaka.media.IClosedCaptionParser.prototype.parseFrom=function(a){};shaka.media.IClosedCaptionParser.prototype.reset=function(){};shaka.media.ClosedCaptionParser=function(a){this.ceaParser_=new shaka.cea.DummyCeaParser;a.includes("video/mp4")&&(this.ceaParser_=new shaka.cea.Mp4CeaParser);this.ceaDecoder_=new shaka.cea.CeaDecoder};shaka.media.ClosedCaptionParser.prototype.init=function(a){this.ceaParser_.init(a)};
shaka.media.ClosedCaptionParser.prototype.parseFrom=function(a){a=this.ceaParser_.parse(a);a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next()){b=b.value;var c=shaka.util.BufferUtils.toUint8(b.packet);0<c.length&&this.ceaDecoder_.extract(c,b.pts)}return this.ceaDecoder_.decode()};shaka.media.ClosedCaptionParser.prototype.reset=function(){this.ceaDecoder_.clear()};shaka.media.InitSegmentReference=function(a,b,c,d,e){this.getUris=a;this.startByte=b;this.endByte=c;this.mediaQuality=void 0===d?null:d;this.timescale=e};shaka.media.InitSegmentReference.prototype.getStartByte=function(){return this.startByte};shaka.media.InitSegmentReference.prototype.getEndByte=function(){return this.endByte};shaka.media.InitSegmentReference.prototype.getSize=function(){return this.endByte?this.endByte-this.startByte:null};
shaka.media.InitSegmentReference.prototype.getMediaQuality=function(){return this.mediaQuality};shaka.media.InitSegmentReference.equal=function(a,b){var c=shaka.util.ArrayUtils;return a&&b?a.getStartByte()==b.getStartByte()&&a.getEndByte()==b.getEndByte()&&c.equal(a.getUris(),b.getUris()):a==b};goog.exportSymbol("shaka.media.InitSegmentReference",shaka.media.InitSegmentReference);goog.exportProperty(shaka.media.InitSegmentReference.prototype,"getEndByte",shaka.media.InitSegmentReference.prototype.getEndByte);
goog.exportProperty(shaka.media.InitSegmentReference.prototype,"getStartByte",shaka.media.InitSegmentReference.prototype.getStartByte);
shaka.media.SegmentReference=function(a,b,c,d,e,f,g,h,k,l,m,n,p,q,r){l=void 0===l?[]:l;m=void 0===m?"":m;n=void 0===n?null:n;p=void 0===p?null:p;q=void 0===q?shaka.media.SegmentReference.Status.AVAILABLE:q;r=void 0===r?null:r;goog.asserts.assert(a<=b,"startTime must be less than or equal to endTime");goog.asserts.assert(null==e||d<e,"startByte must be < endByte");this.startTime=a;this.trueEndTime=this.endTime=b;this.getUrisInner=c;this.startByte=d;this.endByte=e;this.initSegmentReference=f;this.timestampOffset=
g;this.appendWindowStart=h;this.appendWindowEnd=k;this.partialReferences=l;this.tilesLayout=m;this.tileDuration=n;this.syncTime=p;this.status=q;this.hlsAes128Key=r;this.thumbnailSprite=null;this.discontinuitySequence=0};shaka.media.SegmentReference.prototype.getUris=function(){return this.getUrisInner()};shaka.media.SegmentReference.prototype.getStartTime=function(){return this.startTime};shaka.media.SegmentReference.prototype.getEndTime=function(){return this.endTime};
shaka.media.SegmentReference.prototype.getStartByte=function(){return this.startByte};shaka.media.SegmentReference.prototype.getEndByte=function(){return this.endByte};shaka.media.SegmentReference.prototype.getSize=function(){return this.endByte?this.endByte-this.startByte:null};shaka.media.SegmentReference.prototype.hasPartialSegments=function(){return 0<this.partialReferences.length};shaka.media.SegmentReference.prototype.getTilesLayout=function(){return this.tilesLayout};
shaka.media.SegmentReference.prototype.getTileDuration=function(){return this.tileDuration};shaka.media.SegmentReference.prototype.getStatus=function(){return this.status};shaka.media.SegmentReference.prototype.markAsUnavailable=function(){this.status=shaka.media.SegmentReference.Status.UNAVAILABLE};shaka.media.SegmentReference.prototype.setThumbnailSprite=function(a){this.thumbnailSprite=a};shaka.media.SegmentReference.prototype.getThumbnailSprite=function(){return this.thumbnailSprite};
shaka.media.SegmentReference.prototype.offset=function(a){this.startTime+=a;this.endTime+=a;this.trueEndTime+=a;for(var b=$jscomp.makeIterator(this.partialReferences),c=b.next();!c.done;c=b.next())c=c.value,c.startTime+=a,c.endTime+=a,c.trueEndTime+=a};shaka.media.SegmentReference.prototype.syncAgainst=function(a){null==this.syncTime?shaka.log.alwaysError("Sync attempted without sync time!"):(a=this.syncTime-a-this.startTime,.001<=Math.abs(a)&&this.offset(a))};
goog.exportSymbol("shaka.media.SegmentReference",shaka.media.SegmentReference);goog.exportProperty(shaka.media.SegmentReference.prototype,"syncAgainst",shaka.media.SegmentReference.prototype.syncAgainst);goog.exportProperty(shaka.media.SegmentReference.prototype,"offset",shaka.media.SegmentReference.prototype.offset);goog.exportProperty(shaka.media.SegmentReference.prototype,"getThumbnailSprite",shaka.media.SegmentReference.prototype.getThumbnailSprite);
goog.exportProperty(shaka.media.SegmentReference.prototype,"setThumbnailSprite",shaka.media.SegmentReference.prototype.setThumbnailSprite);goog.exportProperty(shaka.media.SegmentReference.prototype,"markAsUnavailable",shaka.media.SegmentReference.prototype.markAsUnavailable);goog.exportProperty(shaka.media.SegmentReference.prototype,"getStatus",shaka.media.SegmentReference.prototype.getStatus);goog.exportProperty(shaka.media.SegmentReference.prototype,"getTileDuration",shaka.media.SegmentReference.prototype.getTileDuration);
goog.exportProperty(shaka.media.SegmentReference.prototype,"getTilesLayout",shaka.media.SegmentReference.prototype.getTilesLayout);goog.exportProperty(shaka.media.SegmentReference.prototype,"getEndByte",shaka.media.SegmentReference.prototype.getEndByte);goog.exportProperty(shaka.media.SegmentReference.prototype,"getStartByte",shaka.media.SegmentReference.prototype.getStartByte);goog.exportProperty(shaka.media.SegmentReference.prototype,"getEndTime",shaka.media.SegmentReference.prototype.getEndTime);
goog.exportProperty(shaka.media.SegmentReference.prototype,"getStartTime",shaka.media.SegmentReference.prototype.getStartTime);goog.exportProperty(shaka.media.SegmentReference.prototype,"getUris",shaka.media.SegmentReference.prototype.getUris);shaka.media.SegmentReference.Status={AVAILABLE:0,UNAVAILABLE:1,MISSING:2};goog.exportProperty(shaka.media.SegmentReference,"Status",shaka.media.SegmentReference.Status);shaka.media.TimeRangesUtils=function(){};shaka.media.TimeRangesUtils.bufferStart=function(a){return!a||1==a.length&&1E-6>a.end(0)-a.start(0)?null:1==a.length&&0>a.start(0)?0:a.length?a.start(0):null};shaka.media.TimeRangesUtils.bufferEnd=function(a){return!a||1==a.length&&1E-6>a.end(0)-a.start(0)?null:a.length?a.end(a.length-1):null};shaka.media.TimeRangesUtils.isBuffered=function(a,b){return!a||!a.length||1==a.length&&1E-6>a.end(0)-a.start(0)||b>a.end(a.length-1)?!1:b>=a.start(0)};
shaka.media.TimeRangesUtils.bufferedAheadOf=function(a,b){if(!a||!a.length||1==a.length&&1E-6>a.end(0)-a.start(0))return 0;var c=0;a=$jscomp.makeIterator(shaka.media.TimeRangesUtils.getBufferedInfo(a));for(var d=a.next();!d.done;d=a.next()){var e=d.value;d=e.start;e=e.end;e>b&&(c+=e-Math.max(d,b))}return c};
shaka.media.TimeRangesUtils.getGapIndex=function(a,b,c){var d=shaka.media.TimeRangesUtils;if(!a||!a.length||1==a.length&&1E-6>a.end(0)-a.start(0))return null;a=d.getBufferedInfo(a).findIndex(function(e,f,g){return e.start>b&&(0==f||g[f-1].end-b<=c)});return 0<=a?a:null};shaka.media.TimeRangesUtils.getBufferedInfo=function(a){if(!a)return[];for(var b=[],c=0;c<a.length;c++)b.push({start:a.start(c),end:a.end(c)});return b};
shaka.media.TimeRangesUtils.computeAddedRange=function(a,b){var c=shaka.media.TimeRangesUtils;if(!a||!a.length)return null;if(!b||!b.length)return c.getBufferedInfo(b).pop();b=c.getBufferedInfo(b).reverse();a=c.getBufferedInfo(a).reverse();c=$jscomp.makeIterator(b);for(b=c.next();!b.done;b=c.next()){b=b.value;for(var d=!1,e=$jscomp.makeIterator(a),f=e.next();!f.done;f=e.next())if(f=f.value,f.end>=b.start&&f.end<=b.end&&(d=!0,b.end>f.end))return{start:f.end,end:b.end};if(!d)return b}return null};/*
 @license
 Shaka Player
 Copyright 2022 Google LLC
 SPDX-License-Identifier: Apache-2.0
*/
shaka.util.Id3Utils=function(){};shaka.util.Id3Utils.isHeader_=function(a,b){return b+10<=a.length&&73===a[b]&&68===a[b+1]&&51===a[b+2]&&255>a[b+3]&&255>a[b+4]&&128>a[b+6]&&128>a[b+7]&&128>a[b+8]&&128>a[b+9]?!0:!1};shaka.util.Id3Utils.isFooter_=function(a,b){return b+10<=a.length&&51===a[b]&&68===a[b+1]&&73===a[b+2]&&255>a[b+3]&&255>a[b+4]&&128>a[b+6]&&128>a[b+7]&&128>a[b+8]&&128>a[b+9]?!0:!1};
shaka.util.Id3Utils.readSize_=function(a,b){var c=(a[b]&127)<<21;c|=(a[b+1]&127)<<14;c|=(a[b+2]&127)<<7;return c|=a[b+3]&127};shaka.util.Id3Utils.getFrameData_=function(a){var b=String.fromCharCode(a[0],a[1],a[2],a[3]),c=shaka.util.Id3Utils.readSize_(a,4);return{type:b,size:c,data:a.subarray(10,10+c)}};
shaka.util.Id3Utils.decodeFrame_=function(a){var b=shaka.util.BufferUtils,c=shaka.util.StringUtils,d={key:a.type,description:"",data:""};if("TXXX"===a.type){if(2>a.size)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),null;var e=a.data.subarray(1).indexOf(0);if(-1===e)return null;var f=c.fromUTF8(b.toUint8(a.data,1,e));a=c.fromUTF8(b.toUint8(a.data,2+e)).replace(/\0*$/,"");d.description=f;d.data=a;return d}if("WXXX"===
a.type){if(2>a.size)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),null;e=a.data.subarray(1).indexOf(0);if(-1===e)return null;f=c.fromUTF8(b.toUint8(a.data,1,e));a=c.fromUTF8(b.toUint8(a.data,2+e)).replace(/\0*$/,"");d.description=f;d.data=a;return d}if("PRIV"===a.type){if(2>a.size)return null;f=a.data.indexOf(0);if(-1===f)return null;c=c.fromUTF8(b.toUint8(a.data,0,f));a=b.toArrayBuffer(a.data.subarray(c.length+
1));d.description=c;d.data=a;return d}if("T"===a.type[0]){if(2>a.size)return null;if(a.data[0]!==shaka.util.Id3Utils.UTF8_encoding)return shaka.log.warning("Ignore frame with unrecognized character encoding"),null;a=c.fromUTF8(a.data.subarray(1)).replace(/\0*$/,"");d.data=a;return d}return"W"===a.type[0]?(a=c.fromUTF8(a.data).replace(/\0*$/,""),d.data=a,d):a.data?(shaka.log.warning("Unrecognized ID3 frame type:",a.type),d.data=b.toArrayBuffer(a.data),d):null};
shaka.util.Id3Utils.getID3Frames=function(a){for(var b=shaka.util.Id3Utils,c=0,d=[];b.isHeader_(a,c);){var e=b.readSize_(a,c+6);a[c+5]>>6&1&&(c+=10);c+=10;for(e=c+e;c+10<e;){var f=b.getFrameData_(a.subarray(c)),g=b.decodeFrame_(f);g&&d.push(g);c+=f.size+10}b.isFooter_(a,c)&&(c+=10)}return d};goog.exportSymbol("shaka.util.Id3Utils",shaka.util.Id3Utils);goog.exportProperty(shaka.util.Id3Utils,"getID3Frames",shaka.util.Id3Utils.getID3Frames);shaka.util.Id3Utils.UTF8_encoding=3;shaka.util.TsParser=function(){this.pmtId_=null;this.pmtParsed_=!1;this.videoCodec_=this.videoPid_=this.videoStartTime_=null;this.videoData_=[];this.audioCodec_=this.audioPid_=this.audioStartTime_=null;this.audioData_=[];this.id3Pid_=null;this.id3Data_=[]};
shaka.util.TsParser.prototype.parse=function(a){var b=shaka.util.TsParser.Timescale_,c=shaka.util.TsParser.PacketLength_;if(a.length<3*c)return this;for(var d=Math.max(0,shaka.util.TsParser.syncOffset(a)),e=a.length-(a.length+d)%c,f=!1,g=d;g<e;g+=c)if(71===a[g]){var h=!!(a[g+1]&64),k=((a[g+1]&31)<<8)+a[g+2];if(1<(a[g+3]&48)>>4){var l=g+5+a[g+4];if(l===g+c)continue}else l=g+4;switch(k){case 0:h&&(l+=a[l]+1);this.pmtId_=this.getPmtId_(a,l);break;case 17:case 8191:break;case this.pmtId_:h&&(l+=a[l]+
1);h=this.parsePMT(a,l);null==this.videoPid_&&(this.videoPid_=h.video,this.videoCodec_=h.videoCodec);null==this.audioPid_&&(this.audioPid_=h.audio,this.audioCodec_=h.audioCodec);null==this.id3Pid_&&(this.id3Pid_=h.id3);f&&!this.pmtParsed_&&(shaka.log.debug("reparse from beginning"),f=!1,g=d-c);this.pmtParsed_=!0;break;case this.videoPid_:h=a.subarray(l,g+c);null==this.videoStartTime_&&(k=this.parsePES(h))&&null!=k.pts&&(this.videoStartTime_=k.pts/b);this.videoData_.push(h);break;case this.audioPid_:h=
a.subarray(l,g+c);null==this.audioStartTime_&&(k=this.parsePES(h))&&null!=k.pts&&(this.audioStartTime_=k.pts/b);this.audioData_.push(h);break;case this.id3Pid_:this.id3Data_.push(a.subarray(l,g+c));break;default:f=!0}}else shaka.log.warning("Found TS packet that do not start with 0x47");return this};shaka.util.TsParser.prototype.getPmtId_=function(a,b){return(a[b+10]&31)<<8|a[b+11]};
shaka.util.TsParser.prototype.parsePMT=function(a,b){var c={audio:-1,video:-1,id3:-1,audioCodec:"",videoCodec:""},d=b+3+((a[b+1]&15)<<8|a[b+2])-4;for(b+=12+((a[b+10]&15)<<8|a[b+11]);b<d;){var e=(a[b+1]&31)<<8|a[b+2];switch(a[b]){case 15:-1===c.audio&&(c.audio=e,c.audioCodec="aac");break;case 21:-1===c.id3&&(c.id3=e);break;case 27:-1===c.video&&(c.video=e,c.videoCodec="avc");break;case 3:case 4:-1===c.audio&&(c.audio=e,c.audioCodec="mp3");break;case 36:-1===c.video&&(c.video=e,c.videoCodec="hvc")}b+=
((a[b+3]&15)<<8|a[b+4])+5}return c};shaka.util.TsParser.prototype.parsePES=function(a){if(1!==(a[0]<<16|a[1]<<8|a[2]))return null;var b={data:new Uint8Array(0),packetLength:6+(a[4]<<8|a[5]),pts:null,dts:null},c=a[7];c&192&&(b.pts=536870912*(a[9]&14)+4194304*(a[10]&255)+16384*(a[11]&254)+128*(a[12]&255)+(a[13]&254)/2,b.dts=b.pts,c&64&&(b.dts=536870912*(a[14]&14)+4194304*(a[15]&255)+16384*(a[16]&254)+128*(a[17]&255)+(a[18]&254)/2));b.data=a.subarray(9+a[8]);return b};
shaka.util.TsParser.prototype.getMetadata=function(){for(var a=shaka.util.TsParser.Timescale_,b=shaka.util.Uint8ArrayUtils,c=[],d=new Uint8Array(0),e=this.id3Data_.length-1;0<=e;e--){var f=this.id3Data_[e];goog.asserts.assert(f,"We should have a data");d=b.concat(f,d);if(f=this.parsePES(d))c.unshift({cueTime:f.pts?f.pts/a:null,data:f.data,frames:shaka.util.Id3Utils.getID3Frames(f.data),dts:f.dts,pts:f.pts}),d=new Uint8Array(0)}return c};
shaka.util.TsParser.prototype.getStartTime=function(){return{audio:this.audioStartTime_,video:this.videoStartTime_}};shaka.util.TsParser.prototype.getCodecs=function(){return{audio:this.audioCodec_,video:this.videoCodec_}};shaka.util.TsParser.probe=function(a){a=shaka.util.TsParser.syncOffset(a);if(0>a)return!1;0<a&&shaka.log.warning("MPEG2-TS detected but first sync word found @ offset "+a+", junk ahead ?");return!0};
shaka.util.TsParser.syncOffset=function(a){for(var b=shaka.util.TsParser.PacketLength_,c=Math.min(1E3,a.length-3*b),d=0;d<c;){if(71===a[d]&&71===a[d+b]&&71===a[d+2*b])return d;d++}return-1};goog.exportSymbol("shaka.util.TsParser",shaka.util.TsParser);shaka.util.TsParser.PacketLength_=188;shaka.util.TsParser.Timescale_=9E4;shaka.lcevc={};shaka.lcevc.Dil=function(a,b,c){this.dil_=null;this.variantId_=-1;this.media_=a;this.canvas_=b;this.dilConfig_=c;this.create_()};shaka.lcevc.Dil.prototype.appendBuffer=function(a){this.dil_&&this.dil_.appendBuffer(a,"video",this.variantId_)};shaka.lcevc.Dil.prototype.hideCanvas=function(){this.dil_&&this.canvas_.classList.add("shaka-hidden")};
shaka.lcevc.Dil.prototype.create_=function(){this.isSupported_()&&!this.dil_&&LcevcDil.SupportObject.webGLSupport(this.canvas_)&&(this.canvas_.classList.remove("shaka-hidden"),this.dil_=new LcevcDil.LcevcDil(this.media_,this.canvas_,this.dilConfig_))};shaka.lcevc.Dil.prototype.release=function(){this.dil_&&(this.dil_.close(),this.dil_=null)};
shaka.lcevc.Dil.prototype.isSupported_=function(){"undefined"===typeof libDPIModule&&shaka.log.alwaysWarn("Could not Find LCEVC Library dependencies on this page");"undefined"===typeof LcevcDil?shaka.log.alwaysWarn("Could not Find LCEVC Library on this page"):LcevcDil.SupportObject.SupportStatus||shaka.log.alwaysWarn(LcevcDil.SupportObject.SupportError);return"undefined"!==typeof LcevcDil&&"undefined"!==typeof libDPIModule&&this.canvas_ instanceof HTMLCanvasElement&&LcevcDil.SupportObject.SupportStatus};
shaka.lcevc.Dil.prototype.updateVariant=function(a){var b=shaka.lcevc.Dil.ContainerFormat.MPEG2_TS;switch(a.mimeType){case "video/webm":b=shaka.lcevc.Dil.ContainerFormat.WEBM;break;case "video/mp4":b=shaka.lcevc.Dil.ContainerFormat.MP4}this.dil_&&(this.variantId_=a.id,this.dil_.setLevelSwitching(a.id,!0),this.dil_.setContainerFormat(b))};goog.exportSymbol("shaka.lcevc.Dil",shaka.lcevc.Dil);goog.exportProperty(shaka.lcevc.Dil.prototype,"release",shaka.lcevc.Dil.prototype.release);
shaka.lcevc.Dil.ContainerFormat={MPEG2_TS:0,WEBM:1,MP4:2};shaka.media.MediaSourceEngine=function(a,b,c,d){var e=this;this.video_=a;this.config_=null;this.textDisplayer_=b;this.sourceBuffers_={};this.sourceBufferTypes_={};this.expectedEncryption_={};this.textEngine_=null;this.segmentRelativeVttTiming_=!1;a=function(f,g,h){};this.onMetadata_=c||a;this.lcevcDil_=d||null;this.queues_={};this.eventManager_=new shaka.util.EventManager;this.transmuxers_={};this.captionParser_=null;this.mediaSourceOpen_=new shaka.util.PublicPromise;this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_);
this.destroyer_=new shaka.util.Destroyer(function(){return e.doDestroy_()});this.url_="";this.sequenceMode_=!1;this.textSequenceModeOffset_=new shaka.util.PublicPromise};shaka.media.MediaSourceEngine.prototype.createMediaSource=function(a){var b=this,c=new MediaSource;this.eventManager_.listenOnce(c,"sourceopen",function(){return b.onSourceOpen_(a)});this.url_=shaka.media.MediaSourceEngine.createObjectURL(c);this.video_.src=this.url_;return c};
shaka.media.MediaSourceEngine.prototype.onSourceOpen_=function(a){URL.revokeObjectURL(this.url_);a.resolve()};shaka.media.MediaSourceEngine.isStreamSupported=function(a){var b=shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs),c=shaka.util.MimeUtils.getExtendedType(a);return shaka.text.TextEngine.isTypeSupported(b)||shaka.media.Capabilities.isTypeSupported(c)||shaka.media.Transmuxer.isSupported(b,a.type)};
shaka.media.MediaSourceEngine.probeSupport=function(){var a='video/mp4; codecs="avc1.42E01E",video/mp4; codecs="avc3.42E01E",video/mp4; codecs="hev1.1.6.L93.90",video/mp4; codecs="hvc1.1.6.L93.90",video/mp4; codecs="hev1.2.4.L153.B0"; eotf="smpte2084",video/mp4; codecs="hvc1.2.4.L153.B0"; eotf="smpte2084",video/mp4; codecs="vp9",video/mp4; codecs="vp09.00.10.08",video/mp4; codecs="av01.0.01M.08",audio/mp4; codecs="mp4a.40.2",audio/mp4; codecs="ac-3",audio/mp4; codecs="ec-3",audio/mp4; codecs="opus",audio/mp4; codecs="flac",video/webm; codecs="vp8",video/webm; codecs="vp9",video/webm; codecs="vp09.00.10.08",audio/webm; codecs="vorbis",audio/webm; codecs="opus",video/mp2t; codecs="avc1.42E01E",video/mp2t; codecs="avc3.42E01E",video/mp2t; codecs="hvc1.1.6.L93.90",video/mp2t; codecs="mp4a.40.2",video/mp2t; codecs="ac-3",video/mp2t; codecs="ec-3",text/vtt,application/mp4; codecs="wvtt",application/ttml+xml,application/mp4; codecs="stpp"'.split(",").concat($jscomp.arrayFromIterable(shaka.media.MediaSourceEngine.RAW_FORMATS)),b=
{};a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){c=c.value;shaka.util.Platform.supportsMediaSource()?shaka.text.TextEngine.isTypeSupported(c)?b[c]=!0:b[c]=shaka.media.Capabilities.isTypeSupported(c)||shaka.media.Transmuxer.isSupported(c):b[c]=shaka.util.Platform.supportsMediaType(c);var d=c.split(";")[0];b[d]=b[d]||b[c]}return b};shaka.media.MediaSourceEngine.prototype.destroy=function(){return this.destroyer_.destroy()};
shaka.media.MediaSourceEngine.prototype.doDestroy_=function(){var a=this,b,c,d,e,f,g,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){if(1==n.nextAddress){b=shaka.util.Functional;c=[];for(d in a.queues_)for(e=a.queues_[d],f=e[0],a.queues_[d]=e.slice(0,1),f&&c.push(f.p.catch(b.noop)),g=$jscomp.makeIterator(e.slice(1)),h=g.next();!h.done;h=g.next())k=h.value,k.p.reject(shaka.util.Destroyer.destroyedError());a.textEngine_&&c.push(a.textEngine_.destroy());a.textDisplayer_&&c.push(a.textDisplayer_.destroy());
for(l in a.transmuxers_)c.push(a.transmuxers_[l].destroy());return n.yield(Promise.all(c),2)}a.eventManager_&&(a.eventManager_.release(),a.eventManager_=null);a.video_&&(a.video_.removeAttribute("src"),a.video_.load(),a.video_=null);a.config_=null;a.mediaSource_=null;a.textEngine_=null;a.textDisplayer_=null;a.sourceBuffers_={};a.transmuxers_={};a.captionParser_=null;if(goog.DEBUG)for(m in a.queues_)goog.asserts.assert(0==a.queues_[m].length,m+" queue should be empty after destroy!");a.queues_={};
a.lcevcDil_=null;n.jumpToEnd()})};shaka.media.MediaSourceEngine.prototype.open=function(){return this.mediaSourceOpen_};
shaka.media.MediaSourceEngine.prototype.init=function(a,b,c){c=void 0===c?!1:c;var d=this,e,f,g,h,k,l,m,n;return $jscomp.asyncExecutePromiseGeneratorProgram(function(p){if(1==p.nextAddress)return e=shaka.util.ManifestParserUtils.ContentType,p.yield(d.mediaSourceOpen_,2);d.sequenceMode_=c;f={};g=$jscomp.makeIterator(a.keys());for(h=g.next();!h.done;f={$jscomp$loop$prop$contentType$649:f.$jscomp$loop$prop$contentType$649},h=g.next())f.$jscomp$loop$prop$contentType$649=h.value,k=a.get(f.$jscomp$loop$prop$contentType$649),
goog.asserts.assert(shaka.media.MediaSourceEngine.isStreamSupported(k),"Type negotiation should happen before MediaSourceEngine.init!"),l=shaka.util.MimeUtils.getFullType(k.mimeType,k.codecs),f.$jscomp$loop$prop$contentType$649==e.TEXT?d.reinitText(l,c):(!b&&shaka.media.Capabilities.isTypeSupported(l)||!shaka.media.Transmuxer.isSupported(l,f.$jscomp$loop$prop$contentType$649)||(d.transmuxers_[f.$jscomp$loop$prop$contentType$649]=new shaka.media.Transmuxer(l),l=shaka.media.Transmuxer.convertCodecs(f.$jscomp$loop$prop$contentType$649,
l)),m=l+d.config_.sourceBufferExtraFeatures,n=d.mediaSource_.addSourceBuffer(m),d.eventManager_.listen(n,"error",function(q){return function(){return d.onError_(q.$jscomp$loop$prop$contentType$649)}}(f)),d.eventManager_.listen(n,"updateend",function(q){return function(){return d.onUpdateEnd_(q.$jscomp$loop$prop$contentType$649)}}(f)),d.sourceBuffers_[f.$jscomp$loop$prop$contentType$649]=n,d.sourceBufferTypes_[f.$jscomp$loop$prop$contentType$649]=l,d.queues_[f.$jscomp$loop$prop$contentType$649]=[],
d.expectedEncryption_[f.$jscomp$loop$prop$contentType$649]=!!k.drmInfos.length);p.jumpToEnd()})};shaka.media.MediaSourceEngine.prototype.configure=function(a){this.config_=a};shaka.media.MediaSourceEngine.prototype.reinitText=function(a,b){this.textEngine_||(this.textEngine_=new shaka.text.TextEngine(this.textDisplayer_));this.textEngine_.initParser(a,b,this.segmentRelativeVttTiming_)};
shaka.media.MediaSourceEngine.prototype.ended=function(){return this.mediaSource_?"ended"==this.mediaSource_.readyState:!0};shaka.media.MediaSourceEngine.prototype.bufferStart=function(a){return a==shaka.util.ManifestParserUtils.ContentType.TEXT?this.textEngine_.bufferStart():shaka.media.TimeRangesUtils.bufferStart(this.getBuffered_(a))};shaka.media.MediaSourceEngine.prototype.bufferEnd=function(a){return a==shaka.util.ManifestParserUtils.ContentType.TEXT?this.textEngine_.bufferEnd():shaka.media.TimeRangesUtils.bufferEnd(this.getBuffered_(a))};
shaka.media.MediaSourceEngine.prototype.isBuffered=function(a,b){if(a==shaka.util.ManifestParserUtils.ContentType.TEXT)return this.textEngine_.isBuffered(b);a=this.getBuffered_(a);return shaka.media.TimeRangesUtils.isBuffered(a,b)};shaka.media.MediaSourceEngine.prototype.bufferedAheadOf=function(a,b){if(a==shaka.util.ManifestParserUtils.ContentType.TEXT)return this.textEngine_.bufferedAheadOf(b);a=this.getBuffered_(a);return shaka.media.TimeRangesUtils.bufferedAheadOf(a,b)};
shaka.media.MediaSourceEngine.prototype.getBufferedInfo=function(){var a=shaka.util.ManifestParserUtils.ContentType,b=shaka.media.TimeRangesUtils;a={total:b.getBufferedInfo(this.video_.buffered),audio:b.getBufferedInfo(this.getBuffered_(a.AUDIO)),video:b.getBufferedInfo(this.getBuffered_(a.VIDEO)),text:[]};if(this.textEngine_){b=this.textEngine_.bufferStart();var c=this.textEngine_.bufferEnd();null!=b&&null!=c&&a.text.push({start:b,end:c})}return a};
shaka.media.MediaSourceEngine.prototype.getBuffered_=function(a){try{return this.sourceBuffers_[a].buffered}catch(b){return a in this.sourceBuffers_&&shaka.log.error("failed to get buffered range for "+a,b),null}};shaka.media.MediaSourceEngine.prototype.getCaptionParser=function(a){return new shaka.media.ClosedCaptionParser(a)};
shaka.media.MediaSourceEngine.prototype.appendBuffer=function(a,b,c,d,e,f){e=void 0===e?!1:e;f=void 0===f?!1:f;var g=this,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G,C,E,F,I,H,K,J,M,N;return $jscomp.asyncExecutePromiseGeneratorProgram(function(L){switch(L.nextAddress){case 1:h=shaka.util.ManifestParserUtils.ContentType;if(a!=h.TEXT){L.jumpTo(2);break}if(!g.sequenceMode_){L.jumpTo(3);break}return L.yield(g.textSequenceModeOffset_,4);case 4:k=L.yieldResult,g.textEngine_.setTimestampOffset(k);case 3:return L.yield(g.textEngine_.appendBuffer(b,
c?c.startTime:null,c?c.endTime:null),5);case 5:return L.return();case 2:l=shaka.util.BufferUtils.toUint8(b);m=g.sourceBufferTypes_[a];g.transmuxers_[a]&&(m=g.transmuxers_[a].getOrginalMimeType());if(shaka.util.TsParser.probe(l)){if(n=(new shaka.util.TsParser).parse(l),p=c.startTime-(n.getStartTime()[a]||0),q=n.getMetadata(),q.length)g.onMetadata_(q,p,c?c.endTime:null)}else shaka.media.MediaSourceEngine.RAW_FORMATS.includes(m)&&(r=shaka.util.Id3Utils.getID3Frames(l),r.length&&c&&(w={cueTime:c.startTime,
data:l,frames:r,dts:c.startTime,pts:c.startTime},g.onMetadata_([w],0,c.endTime)));if(!g.transmuxers_[a]){d&&a==h.VIDEO&&(g.textEngine_||g.reinitText("text/vtt",g.sequenceMode_),g.captionParser_||(g.captionParser_=g.getCaptionParser(m)),c?(u=g.captionParser_.parseFrom(b),u.length&&(v=g.sourceBuffers_[h.VIDEO].timestampOffset,g.textEngine_.storeAndAppendClosedCaptions(u,c.startTime,c.endTime,v))):g.captionParser_.init(b));L.jumpTo(6);break}e&&g.transmuxers_[a].resetCaptions();return L.yield(g.transmuxers_[a].transmux(b),
7);case 7:x=L.yieldResult,g.textEngine_||g.reinitText("text/vtt",g.sequenceMode_),x.captions&&x.captions.length&&(t=g.sourceBuffers_[h.VIDEO].timestampOffset,y=g.textEngine_.convertMuxjsCaptionsToShakaCaptions(x.captions),g.textEngine_.storeAndAppendClosedCaptions(y,c?c.startTime:null,c?c.endTime:null,t)),b=x.data;case 6:b=g.workAroundBrokenPlatforms_(b,c?c.startTime:null,a);A=g.sourceBuffers_[a];z=shaka.media.MediaSourceEngine.SourceBufferMode_.SEQUENCE;if(!g.sequenceMode_||A.mode==z||!c){L.jumpTo(8);
break}B=g.mediaSource_.duration;D=a==h.VIDEO||!(h.VIDEO in g.sourceBuffers_);if(!D){L.jumpTo(9);break}G=[A.appendWindowStart,A.appendWindowEnd];A.appendWindowStart=0;A.appendWindowEnd=Infinity;C=A.timestampOffset;A.timestampOffset=0;return L.yield(g.enqueueOperation_(a,function(){return g.append_(a,b)}),10);case 10:return L.yield(g.enqueueOperation_(a,function(){return g.abort_(a)}),11);case 11:return A.timestampOffset=C,A.appendWindowStart=G[0],A.appendWindowEnd=G[1],E=shaka.media.TimeRangesUtils.bufferStart(g.getBuffered_(a)),
F=(c.startTime||0)-(E||0),g.textSequenceModeOffset_.resolve(F),L.yield(g.enqueueOperation_(a,function(){return g.remove_(a,0,B)}),12);case 12:if(a!=h.VIDEO){L.jumpTo(9);break}return L.yield(g.enqueueOperation_(a,function(){return g.flush_(a)}),9);case 9:return A.mode=z,L.yield(g.setDuration(B),8);case 8:return c&&g.sequenceMode_&&a!=h.TEXT&&(e||f)&&(I=c.startTime,g.enqueueOperation_(a,function(){return g.abort_(a)}),g.enqueueOperation_(a,function(){return g.setTimestampOffset_(a,I)})),H=null,L.yield(g.enqueueOperation_(a,
function(){goog.DEBUG&&c&&(H=g.getBuffered_(a));g.append_(a,b)}),16);case 16:goog.DEBUG&&c&&(K=g.getBuffered_(a),J=shaka.media.TimeRangesUtils.computeAddedRange(H,K))&&(M=c.endTime-c.startTime,N=Math.abs(J.end-c.endTime),.1<M&&N>M/2&&shaka.log.error("Possible encoding problem detected!","Unexpected buffered range for reference",c,"from URIs",c.getUris(),"should be",{start:c.startTime,end:c.endTime},"but got",J)),L.jumpToEnd()}})};
shaka.media.MediaSourceEngine.prototype.setSelectedClosedCaptionId=function(a){var b=this.bufferEnd(shaka.util.ManifestParserUtils.ContentType.VIDEO)||0;this.textEngine_.setSelectedClosedCaptionId(a,b)};shaka.media.MediaSourceEngine.prototype.clearSelectedClosedCaptionId=function(){this.textEngine_&&this.textEngine_.setSelectedClosedCaptionId("",0)};
shaka.media.MediaSourceEngine.prototype.remove=function(a,b,c){var d=this,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){e=shaka.util.ManifestParserUtils.ContentType;return a==e.TEXT?f.yield(d.textEngine_.remove(b,c),0):f.yield(d.enqueueOperation_(a,function(){return d.remove_(a,b,c)}),0)})};
shaka.media.MediaSourceEngine.prototype.clear=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){c=shaka.util.ManifestParserUtils.ContentType;return a==c.TEXT?b.textEngine_?d.yield(b.textEngine_.remove(0,Infinity),0):d.return():d.yield(b.enqueueOperation_(a,function(){return b.remove_(a,0,b.mediaSource_.duration)}),0)})};shaka.media.MediaSourceEngine.prototype.resetCaptionParser=function(){this.captionParser_&&this.captionParser_.reset()};
shaka.media.MediaSourceEngine.prototype.flush=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){c=shaka.util.ManifestParserUtils.ContentType;return a==c.TEXT?d.return():d.yield(b.enqueueOperation_(a,function(){return b.flush_(a)}),0)})};
shaka.media.MediaSourceEngine.prototype.setStreamProperties=function(a,b,c,d,e){var f=this,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){g=shaka.util.ManifestParserUtils.ContentType;return a==g.TEXT?(e||f.textEngine_.setTimestampOffset(b),f.textEngine_.setAppendWindow(c,d),h.return()):h.yield(Promise.all([f.enqueueOperation_(a,function(){return f.abort_(a)}),e?Promise.resolve():f.enqueueOperation_(a,function(){return f.setTimestampOffset_(a,b)}),f.enqueueOperation_(a,function(){return f.setAppendWindow_(a,
c,d)})]),0)})};shaka.media.MediaSourceEngine.prototype.resync=function(a,b){var c=this,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){d=shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(c.sequenceMode_,"resync only used with sequence mode!");if(a==d.TEXT)return e.return();c.enqueueOperation_(a,function(){return c.abort_(a)});return e.yield(c.enqueueOperation_(a,function(){return c.setTimestampOffset_(a,b)}),0)})};
shaka.media.MediaSourceEngine.prototype.endOfStream=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){return c.yield(b.enqueueBlockingOperation_(function(){b.ended()||(a?b.mediaSource_.endOfStream(a):b.mediaSource_.endOfStream())}),0)})};
shaka.media.MediaSourceEngine.prototype.setDuration=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){return c.yield(b.enqueueBlockingOperation_(function(){if(a<b.mediaSource_.duration)for(var d in b.sourceBuffers_){var e={start:function(){},p:new shaka.util.PublicPromise};b.queues_[d].unshift(e)}b.mediaSource_.duration=a}),0)})};shaka.media.MediaSourceEngine.prototype.getDuration=function(){return this.mediaSource_.duration};
shaka.media.MediaSourceEngine.prototype.append_=function(a,b){a==shaka.util.ManifestParserUtils.ContentType.VIDEO&&this.lcevcDil_&&this.lcevcDil_.appendBuffer(b);this.sourceBuffers_[a].appendBuffer(b)};shaka.media.MediaSourceEngine.prototype.remove_=function(a,b,c){if(c<=b)this.onUpdateEnd_(a);else this.sourceBuffers_[a].remove(b,c)};
shaka.media.MediaSourceEngine.prototype.abort_=function(a){var b=this.sourceBuffers_[a].appendWindowStart,c=this.sourceBuffers_[a].appendWindowEnd;this.sourceBuffers_[a].abort();this.sourceBuffers_[a].appendWindowStart=b;this.sourceBuffers_[a].appendWindowEnd=c;this.onUpdateEnd_(a)};shaka.media.MediaSourceEngine.prototype.flush_=function(a){goog.asserts.assert(0==this.video_.buffered.length,"MediaSourceEngine.flush_ should only be used after clearing all data!");this.video_.currentTime-=.001;this.onUpdateEnd_(a)};
shaka.media.MediaSourceEngine.prototype.setTimestampOffset_=function(a,b){0>b&&(b+=.001);this.sourceBuffers_[a].timestampOffset=b;this.onUpdateEnd_(a)};shaka.media.MediaSourceEngine.prototype.setAppendWindow_=function(a,b,c){this.sourceBuffers_[a].appendWindowStart=0;this.sourceBuffers_[a].appendWindowEnd=c;this.sourceBuffers_[a].appendWindowStart=b;this.onUpdateEnd_(a)};
shaka.media.MediaSourceEngine.prototype.onError_=function(a){var b=this.queues_[a][0];goog.asserts.assert(b,"Spurious error event!");goog.asserts.assert(!this.sourceBuffers_[a].updating,"SourceBuffer should not be updating on error!");b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_FAILED,this.video_.error?this.video_.error.code:0))};
shaka.media.MediaSourceEngine.prototype.onUpdateEnd_=function(a){var b=this.queues_[a][0];goog.asserts.assert(b,"Spurious updateend event!");b&&(goog.asserts.assert(!this.sourceBuffers_[a].updating,"SourceBuffer should not be updating on updateend!"),b.p.resolve(),this.popFromQueue_(a))};
shaka.media.MediaSourceEngine.prototype.enqueueOperation_=function(a,b){this.destroyer_.ensureNotDestroyed();b={start:b,p:new shaka.util.PublicPromise};this.queues_[a].push(b);1==this.queues_[a].length&&this.startOperation_(a);return b.p};
shaka.media.MediaSourceEngine.prototype.enqueueBlockingOperation_=function(a){var b=this,c,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){switch(m.nextAddress){case 1:b.destroyer_.ensureNotDestroyed();c=[];d={};for(e in b.sourceBuffers_)d.$jscomp$loop$prop$ready$651=new shaka.util.PublicPromise,f={start:function(n){return function(){return n.$jscomp$loop$prop$ready$651.resolve()}}(d),p:d.$jscomp$loop$prop$ready$651},b.queues_[e].push(f),c.push(d.$jscomp$loop$prop$ready$651),
1==b.queues_[e].length&&f.start(),d={$jscomp$loop$prop$ready$651:d.$jscomp$loop$prop$ready$651};m.setCatchFinallyBlocks(2);return m.yield(Promise.all(c),4);case 4:m.leaveTryBlock(3);break;case 2:g=m.enterCatchBlock();goog.asserts.assert(b.destroyer_.destroyed(),"Should be destroyed by now");if(goog.DEBUG)for(h in b.sourceBuffers_)b.queues_[h].length&&(goog.asserts.assert(1==b.queues_[h].length,"Should be at most one item in queue!"),goog.asserts.assert(c.includes(b.queues_[h][0].p),"The item in queue should be one of our waiters!"),
b.queues_[h].shift());throw g;case 3:if(goog.DEBUG)for(k in b.sourceBuffers_)goog.asserts.assert(0==b.sourceBuffers_[k].updating,"SourceBuffers should not be updating after a blocking op!");try{a()}catch(n){throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,n);}finally{for(l in b.sourceBuffers_)b.popFromQueue_(l)}m.jumpToEnd()}})};
shaka.media.MediaSourceEngine.prototype.popFromQueue_=function(a){this.queues_[a].shift();this.startOperation_(a)};
shaka.media.MediaSourceEngine.prototype.startOperation_=function(a){var b=this.queues_[a][0];if(b)try{b.start()}catch(c){"QuotaExceededError"==c.name?b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR,a)):b.p.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MEDIA_SOURCE_OPERATION_THREW,c)),this.popFromQueue_(a)}};
shaka.media.MediaSourceEngine.prototype.getTextDisplayer=function(){goog.asserts.assert(this.textDisplayer_,"TextDisplayer should only be null when this is destroyed");return this.textDisplayer_};shaka.media.MediaSourceEngine.prototype.setTextDisplayer=function(a){var b=this.textDisplayer_;this.textDisplayer_=a;b&&(a.setTextVisibility(b.isTextVisible()),b.destroy());this.textEngine_&&this.textEngine_.setDisplayer(a)};
shaka.media.MediaSourceEngine.prototype.setSegmentRelativeVttTiming=function(a){this.segmentRelativeVttTiming_=a};
shaka.media.MediaSourceEngine.prototype.workAroundBrokenPlatforms_=function(a,b,c){var d=this.expectedEncryption_[c];null==b&&d&&shaka.util.Platform.requiresEncryptionInfoInAllInitSegments()&&"mp4"==shaka.util.MimeUtils.getContainerType(this.sourceBufferTypes_[c])&&(shaka.log.debug("Forcing fake encryption information in init segment."),a=shaka.media.ContentWorkarounds.fakeEncryption(a));return a};shaka.media.MediaSourceEngine.prototype.updateLcevcDil=function(a){this.lcevcDil_=a};
shaka.media.MediaSourceEngine.createObjectURL=window.URL.createObjectURL;shaka.media.MediaSourceEngine.SourceBufferMode_={SEQUENCE:"sequence",SEGMENTS:"segments"};shaka.media.MediaSourceEngine.RAW_FORMATS=["audio/aac","audio/ac3","audio/ec3","audio/mpeg"];shaka.media.PresentationTimeline=function(a,b,c){this.presentationStartTime_=a;this.presentationDelay_=b;this.segmentAvailabilityDuration_=this.duration_=Infinity;this.maxSegmentDuration_=1;this.maxSegmentEndTime_=this.minSegmentStartTime_=null;this.clockOffset_=0;this.static_=!0;this.userSeekStart_=0;this.autoCorrectDrift_=void 0===c?!0:c;this.availabilityTimeOffset_=0;this.startTimeLocked_=!1};shaka.media.PresentationTimeline.prototype.getDuration=function(){return this.duration_};
shaka.media.PresentationTimeline.prototype.getMaxSegmentDuration=function(){return this.maxSegmentDuration_};shaka.media.PresentationTimeline.prototype.setPresentationStartTime=function(a){goog.asserts.assert(0<=a,"presentationStartTime must be >= 0");this.presentationStartTime_=a};shaka.media.PresentationTimeline.prototype.setDuration=function(a){goog.asserts.assert(0<a,"duration must be > 0");this.duration_=a};shaka.media.PresentationTimeline.prototype.getPresentationStartTime=function(){return this.presentationStartTime_};
shaka.media.PresentationTimeline.prototype.setClockOffset=function(a){this.clockOffset_=a};shaka.media.PresentationTimeline.prototype.setStatic=function(a){this.static_=a};shaka.media.PresentationTimeline.prototype.setSegmentAvailabilityDuration=function(a){goog.asserts.assert(0<=a,"segmentAvailabilityDuration must be >= 0");this.segmentAvailabilityDuration_=a};shaka.media.PresentationTimeline.prototype.setDelay=function(a){goog.asserts.assert(0<=a,"delay must be >= 0");this.presentationDelay_=a};
shaka.media.PresentationTimeline.prototype.getDelay=function(){return this.presentationDelay_};
shaka.media.PresentationTimeline.prototype.notifySegments=function(a){if(0!=a.length){var b=a[0].startTime,c=a[0].endTime;a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())d=d.value,b=Math.min(b,d.startTime),c=Math.max(c,d.endTime),this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,d.endTime-d.startTime);this.notifyMinSegmentStartTime(b);this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,c);null!=this.presentationStartTime_&&this.autoCorrectDrift_&&!this.startTimeLocked_&&
(this.presentationStartTime_=(Date.now()+this.clockOffset_)/1E3-this.maxSegmentEndTime_-this.maxSegmentDuration_);shaka.log.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}};shaka.media.PresentationTimeline.prototype.lockStartTime=function(){this.startTimeLocked_=!0};shaka.media.PresentationTimeline.prototype.notifyMinSegmentStartTime=function(a){this.minSegmentStartTime_=null==this.minSegmentStartTime_?a:Math.min(this.minSegmentStartTime_,a)};
shaka.media.PresentationTimeline.prototype.notifyMaxSegmentDuration=function(a){this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,a);shaka.log.v1("notifyNewSegmentDuration:","maxSegmentDuration="+this.maxSegmentDuration_)};shaka.media.PresentationTimeline.prototype.offset=function(a){null!=this.minSegmentStartTime_&&(this.minSegmentStartTime_+=a);null!=this.maxSegmentEndTime_&&(this.maxSegmentEndTime_+=a)};
shaka.media.PresentationTimeline.prototype.isLive=function(){return Infinity==this.duration_&&!this.static_};shaka.media.PresentationTimeline.prototype.isInProgress=function(){return Infinity!=this.duration_&&!this.static_};
shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityStart=function(){goog.asserts.assert(0<=this.segmentAvailabilityDuration_,"The availability duration should be positive");var a=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_;return Math.max(this.userSeekStart_,a)};shaka.media.PresentationTimeline.prototype.setUserSeekStart=function(a){this.userSeekStart_=a};
shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityEnd=function(){return this.isLive()||this.isInProgress()?Math.min(this.getLiveEdge_()+this.availabilityTimeOffset_,this.duration_):this.maxSegmentEndTime_?Math.min(this.maxSegmentEndTime_,this.duration_):this.duration_};
shaka.media.PresentationTimeline.prototype.getSafeSeekRangeStart=function(a){var b=Math.max(this.minSegmentStartTime_,this.userSeekStart_);if(Infinity==this.segmentAvailabilityDuration_)return Math.ceil(1E3*b)/1E3;var c=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_;a=Math.min(c+a,this.getSeekRangeEnd());return Math.max(b,a)};shaka.media.PresentationTimeline.prototype.getSeekRangeStart=function(){return this.getSafeSeekRangeStart(0)};
shaka.media.PresentationTimeline.prototype.getSeekRangeEnd=function(){var a=this.isLive()||this.isInProgress()?this.presentationDelay_:0;return Math.max(0,this.getSegmentAvailabilityEnd()-a)};shaka.media.PresentationTimeline.prototype.usingPresentationStartTime=function(){return null==this.presentationStartTime_||null!=this.maxSegmentEndTime_&&this.autoCorrectDrift_?!1:!0};
shaka.media.PresentationTimeline.prototype.getLiveEdge_=function(){goog.asserts.assert(null!=this.presentationStartTime_,"Cannot compute timeline live edge without start time");var a=(Date.now()+this.clockOffset_)/1E3;return Math.max(0,a-this.maxSegmentDuration_-this.presentationStartTime_)};shaka.media.PresentationTimeline.prototype.setAvailabilityTimeOffset=function(a){this.availabilityTimeOffset_=a};
shaka.media.PresentationTimeline.prototype.assertIsValid=function(){goog.DEBUG&&(this.isLive()?goog.asserts.assert(null!=this.presentationStartTime_,"Detected as live stream, but does not match our model of live!"):this.isInProgress()?goog.asserts.assert(null!=this.presentationStartTime_&&Infinity==this.segmentAvailabilityDuration_,"Detected as IPR stream, but does not match our model of IPR!"):goog.asserts.assert(Infinity==this.segmentAvailabilityDuration_&&Infinity!=this.duration_&&this.static_,
"Detected as VOD stream, but does not match our model of VOD!"))};goog.exportSymbol("shaka.media.PresentationTimeline",shaka.media.PresentationTimeline);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setAvailabilityTimeOffset",shaka.media.PresentationTimeline.prototype.setAvailabilityTimeOffset);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"usingPresentationStartTime",shaka.media.PresentationTimeline.prototype.usingPresentationStartTime);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSeekRangeEnd",shaka.media.PresentationTimeline.prototype.getSeekRangeEnd);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSeekRangeStart",shaka.media.PresentationTimeline.prototype.getSeekRangeStart);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSafeSeekRangeStart",shaka.media.PresentationTimeline.prototype.getSafeSeekRangeStart);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSegmentAvailabilityEnd",shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityEnd);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setUserSeekStart",shaka.media.PresentationTimeline.prototype.setUserSeekStart);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getSegmentAvailabilityStart",shaka.media.PresentationTimeline.prototype.getSegmentAvailabilityStart);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"isInProgress",shaka.media.PresentationTimeline.prototype.isInProgress);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"isLive",shaka.media.PresentationTimeline.prototype.isLive);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"offset",shaka.media.PresentationTimeline.prototype.offset);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifyMaxSegmentDuration",shaka.media.PresentationTimeline.prototype.notifyMaxSegmentDuration);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifyMinSegmentStartTime",shaka.media.PresentationTimeline.prototype.notifyMinSegmentStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"lockStartTime",shaka.media.PresentationTimeline.prototype.lockStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"notifySegments",shaka.media.PresentationTimeline.prototype.notifySegments);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getDelay",shaka.media.PresentationTimeline.prototype.getDelay);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setDelay",shaka.media.PresentationTimeline.prototype.setDelay);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setSegmentAvailabilityDuration",shaka.media.PresentationTimeline.prototype.setSegmentAvailabilityDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setStatic",shaka.media.PresentationTimeline.prototype.setStatic);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setClockOffset",shaka.media.PresentationTimeline.prototype.setClockOffset);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getPresentationStartTime",shaka.media.PresentationTimeline.prototype.getPresentationStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setDuration",shaka.media.PresentationTimeline.prototype.setDuration);
goog.exportProperty(shaka.media.PresentationTimeline.prototype,"setPresentationStartTime",shaka.media.PresentationTimeline.prototype.setPresentationStartTime);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getMaxSegmentDuration",shaka.media.PresentationTimeline.prototype.getMaxSegmentDuration);goog.exportProperty(shaka.media.PresentationTimeline.prototype,"getDuration",shaka.media.PresentationTimeline.prototype.getDuration);shaka.media.StallDetector=function(a,b,c){this.onEvent_=c;this.implementation_=a;this.wasMakingProgress_=a.shouldBeMakingProgress();this.value_=a.getPresentationSeconds();this.lastUpdateSeconds_=a.getWallSeconds();this.didJump_=!1;this.stallsDetected_=0;this.stallThresholdSeconds_=b;this.onStall_=function(){}};shaka.media.StallDetector.prototype.release=function(){this.onEvent_=this.implementation_=null;this.onStall_=function(){}};
shaka.media.StallDetector.prototype.onStall=function(a){this.onStall_=a};shaka.media.StallDetector.prototype.getStallsDetected=function(){return this.stallsDetected_};
shaka.media.StallDetector.prototype.poll=function(){var a=this.implementation_,b=a.shouldBeMakingProgress(),c=a.getPresentationSeconds(),d=a.getWallSeconds();if(this.value_!=c||this.wasMakingProgress_!=b)this.lastUpdateSeconds_=d,this.value_=c,this.wasMakingProgress_=b,this.didJump_=!1;c=d-this.lastUpdateSeconds_;if(b=c>=this.stallThresholdSeconds_&&b&&!this.didJump_)this.onStall_(this.value_,c),this.didJump_=!0,this.value_=a.getPresentationSeconds(),this.stallsDetected_++,this.onEvent_(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.StallDetected));
return b};shaka.media.StallDetector.Implementation=function(){};shaka.media.StallDetector.Implementation.prototype.shouldBeMakingProgress=function(){};shaka.media.StallDetector.Implementation.prototype.getPresentationSeconds=function(){};shaka.media.StallDetector.Implementation.prototype.getWallSeconds=function(){};shaka.media.StallDetector.MediaElementImplementation=function(a){this.mediaElement_=a};
shaka.media.StallDetector.MediaElementImplementation.prototype.shouldBeMakingProgress=function(){return this.mediaElement_.paused||0==this.mediaElement_.playbackRate||0==this.mediaElement_.buffered.length?!1:shaka.media.StallDetector.MediaElementImplementation.hasContentFor_(this.mediaElement_.buffered,this.mediaElement_.currentTime)};shaka.media.StallDetector.MediaElementImplementation.prototype.getPresentationSeconds=function(){return this.mediaElement_.currentTime};
shaka.media.StallDetector.MediaElementImplementation.prototype.getWallSeconds=function(){return Date.now()/1E3};shaka.media.StallDetector.MediaElementImplementation.hasContentFor_=function(a,b){a=$jscomp.makeIterator(shaka.media.TimeRangesUtils.getBufferedInfo(a));for(var c=a.next();!c.done;c=a.next())if(c=c.value,!(b<c.start-.1||b>c.end-.5))return!0;return!1};shaka.media.GapJumpingController=function(a,b,c,d,e){var f=this;this.onEvent_=e;this.video_=a;this.timeline_=b;this.config_=c;this.eventManager_=new shaka.util.EventManager;this.seekingEventReceived_=!1;this.prevReadyState_=a.readyState;this.gapsJumped_=0;this.stallDetector_=d;this.hadSegmentAppended_=!1;this.eventManager_.listen(a,"waiting",function(){return f.onPollGapJump_()});this.gapJumpTimer_=(new shaka.util.Timer(function(){f.onPollGapJump_()})).tickEvery(.25)};
shaka.media.GapJumpingController.prototype.release=function(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);null!=this.gapJumpTimer_&&(this.gapJumpTimer_.stop(),this.gapJumpTimer_=null);this.stallDetector_&&(this.stallDetector_.release(),this.stallDetector_=null);this.video_=this.timeline_=this.onEvent_=null};shaka.media.GapJumpingController.prototype.onSegmentAppended=function(){this.hadSegmentAppended_=!0;this.onPollGapJump_()};
shaka.media.GapJumpingController.prototype.onSeeking=function(){this.seekingEventReceived_=!0;this.hadSegmentAppended_=!1};shaka.media.GapJumpingController.prototype.getGapsJumped=function(){return this.gapsJumped_};
shaka.media.GapJumpingController.prototype.onPollGapJump_=function(){if(0!=this.video_.readyState){if(this.video_.seeking){if(!this.seekingEventReceived_)return}else this.seekingEventReceived_=!1;if(!this.video_.paused||0==this.video_.currentTime&&(this.video_.autoplay||0!=this.video_.currentTime))if(this.video_.readyState!=this.prevReadyState_&&(this.prevReadyState_=this.video_.readyState),!this.stallDetector_||!this.stallDetector_.poll()){var a=this.video_.currentTime,b=this.video_.buffered,c=shaka.media.TimeRangesUtils.getGapIndex(b,
a,this.config_.gapDetectionThreshold);if(null!=c&&(0!=c||this.hadSegmentAppended_)){var d=b.start(c),e=this.timeline_.getSeekRangeEnd();d>=e||(a=d-a,a<shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE||(0==c?shaka.log.info("Jumping forward",a,"seconds because of gap before start time of",d):shaka.log.info("Jumping forward",a,"seconds because of gap starting at",b.end(c-1),"and ending at",d),this.video_.currentTime=d,this.gapsJumped_++,this.onEvent_(new shaka.util.FakeEvent(shaka.util.FakeEvent.EventName.GapJumped))))}}}};
shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE=.001;shaka.util.MediaReadyState=function(){};shaka.util.MediaReadyState.waitForReadyState=function(a,b,c,d){b==HTMLMediaElement.HAVE_NOTHING||a.readyState>=b?d():(b=shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_.value().get(b),c.listenOnce(a,b,d))};
shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_=new shaka.util.Lazy(function(){return new Map([[HTMLMediaElement.HAVE_METADATA,"loadedmetadata"],[HTMLMediaElement.HAVE_CURRENT_DATA,"loadeddata"],[HTMLMediaElement.HAVE_FUTURE_DATA,"canplay"],[HTMLMediaElement.HAVE_ENOUGH_DATA,"canplaythrough"]])});shaka.media.VideoWrapper=function(a,b,c){var d=this;this.video_=a;this.onSeek_=b;this.startTime_=c;this.started_=!1;this.eventManager_=new shaka.util.EventManager;this.mover_=new shaka.media.VideoWrapper.PlayheadMover(a,10);shaka.util.MediaReadyState.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,function(){d.setStartTime_(d.startTime_)})};
shaka.media.VideoWrapper.prototype.release=function(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);null!=this.mover_&&(this.mover_.release(),this.mover_=null);this.onSeek_=function(){};this.video_=null};shaka.media.VideoWrapper.prototype.getTime=function(){return this.started_?this.video_.currentTime:this.startTime_};
shaka.media.VideoWrapper.prototype.setTime=function(a){var b=this;0<this.video_.readyState?this.mover_.moveTo(a):shaka.util.MediaReadyState.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,function(){b.setStartTime_(b.startTime_)})};
shaka.media.VideoWrapper.prototype.setStartTime_=function(a){var b=this;.001>Math.abs(this.video_.currentTime-a)?this.startListeningToSeeks_():(this.eventManager_.listenOnce(this.video_,"seeking",function(){b.startListeningToSeeks_()}),this.mover_.moveTo(this.video_.currentTime&&0!=this.video_.currentTime?this.video_.currentTime:a))};
shaka.media.VideoWrapper.prototype.startListeningToSeeks_=function(){var a=this;goog.asserts.assert(0<this.video_.readyState,"The media element should be ready before we listen for seeking.");this.started_=!0;this.eventManager_.listen(this.video_,"seeking",function(){return a.onSeek_()})};shaka.media.VideoWrapper.PlayheadMover=function(a,b){var c=this;this.mediaElement_=a;this.maxAttempts_=b;this.targetTime_=this.originTime_=this.remainingAttempts_=0;this.timer_=new shaka.util.Timer(function(){return c.onTick_()})};
shaka.media.VideoWrapper.PlayheadMover.prototype.release=function(){this.timer_&&(this.timer_.stop(),this.timer_=null);this.mediaElement_=null};shaka.media.VideoWrapper.PlayheadMover.prototype.moveTo=function(a){this.originTime_=this.mediaElement_.currentTime;this.targetTime_=a;this.remainingAttempts_=this.maxAttempts_;this.mediaElement_.currentTime=a;this.timer_.tickEvery(.1)};
shaka.media.VideoWrapper.PlayheadMover.prototype.onTick_=function(){0>=this.remainingAttempts_?(shaka.log.warning(["Failed to move playhead from",this.originTime_,"to",this.targetTime_].join(" ")),this.timer_.stop()):this.mediaElement_.currentTime!=this.originTime_?this.timer_.stop():(this.mediaElement_.currentTime=this.targetTime_,this.remainingAttempts_--)};shaka.media.Playhead=function(){};shaka.media.Playhead.prototype.ready=function(){};shaka.media.Playhead.prototype.setStartTime=function(a){};shaka.media.Playhead.prototype.getStallsDetected=function(){};shaka.media.Playhead.prototype.getGapsJumped=function(){};shaka.media.Playhead.prototype.getTime=function(){};shaka.media.Playhead.prototype.notifyOfBufferingChange=function(){};
shaka.media.SrcEqualsPlayhead=function(a){this.mediaElement_=a;this.started_=!1;this.startTime_=null;this.eventManager_=new shaka.util.EventManager};
shaka.media.SrcEqualsPlayhead.prototype.ready=function(){var a=this;goog.asserts.assert(null!=this.mediaElement_,"Playhead should not be released before calling ready()");var b=function(){null==a.startTime_||0==a.startTime_?a.started_=!0:(a.eventManager_.listenOnce(a.mediaElement_,"seeking",function(){a.started_=!0}),a.mediaElement_.currentTime=Math.max(0,a.mediaElement_.currentTime+a.startTime_))};shaka.util.MediaReadyState.waitForReadyState(this.mediaElement_,HTMLMediaElement.HAVE_CURRENT_DATA,
this.eventManager_,function(){b()})};shaka.media.SrcEqualsPlayhead.prototype.release=function(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);this.mediaElement_=null};shaka.media.SrcEqualsPlayhead.prototype.setStartTime=function(a){this.startTime_=this.started_?this.startTime_:a};shaka.media.SrcEqualsPlayhead.prototype.getTime=function(){return(this.started_?this.mediaElement_.currentTime:this.startTime_)||0};shaka.media.SrcEqualsPlayhead.prototype.getStallsDetected=function(){return 0};
shaka.media.SrcEqualsPlayhead.prototype.getGapsJumped=function(){return 0};shaka.media.SrcEqualsPlayhead.prototype.notifyOfBufferingChange=function(){};
shaka.media.MediaSourcePlayhead=function(a,b,c,d,e,f){var g=this;this.minSeekRange_=3;this.mediaElement_=a;this.timeline_=b.presentationTimeline;this.minBufferTime_=b.minBufferTime||0;this.config_=c;this.onSeek_=e;this.lastCorrectiveSeek_=null;this.stallDetector_=this.createStallDetector_(a,c,f);this.gapController_=new shaka.media.GapJumpingController(a,b.presentationTimeline,c,this.stallDetector_,f);this.videoWrapper_=new shaka.media.VideoWrapper(a,function(){return g.onSeeking_()},this.getStartTime_(d));
this.checkWindowTimer_=new shaka.util.Timer(function(){g.onPollWindow_()})};shaka.media.MediaSourcePlayhead.prototype.ready=function(){this.checkWindowTimer_.tickEvery(.25)};
shaka.media.MediaSourcePlayhead.prototype.release=function(){this.videoWrapper_&&(this.videoWrapper_.release(),this.videoWrapper_=null);this.gapController_&&(this.gapController_.release(),this.gapController_=null);this.checkWindowTimer_&&(this.checkWindowTimer_.stop(),this.checkWindowTimer_=null);this.mediaElement_=this.videoWrapper_=this.timeline_=this.config_=null;this.onSeek_=function(){}};shaka.media.MediaSourcePlayhead.prototype.setStartTime=function(a){this.videoWrapper_.setTime(a)};
shaka.media.MediaSourcePlayhead.prototype.getTime=function(){var a=this.videoWrapper_.getTime();return 0<this.mediaElement_.readyState&&!this.mediaElement_.paused?this.clampTime_(a):a};shaka.media.MediaSourcePlayhead.prototype.getStallsDetected=function(){return this.stallDetector_?this.stallDetector_.getStallsDetected():0};shaka.media.MediaSourcePlayhead.prototype.getGapsJumped=function(){return this.gapController_.getGapsJumped()};
shaka.media.MediaSourcePlayhead.prototype.getStartTime_=function(a){null==a?a=Infinity>this.timeline_.getDuration()?this.timeline_.getSeekRangeStart():this.timeline_.getSeekRangeEnd():0>a&&(a=this.timeline_.getSeekRangeEnd()+a);return this.clampSeekToDuration_(this.clampTime_(a))};shaka.media.MediaSourcePlayhead.prototype.notifyOfBufferingChange=function(){this.gapController_.onSegmentAppended()};
shaka.media.MediaSourcePlayhead.prototype.onPollWindow_=function(){if(0!=this.mediaElement_.readyState&&!this.mediaElement_.paused){var a=this.videoWrapper_.getTime(),b=this.timeline_.getSeekRangeStart(),c=this.timeline_.getSeekRangeEnd();c-b<this.minSeekRange_&&(b=c-this.minSeekRange_);a<b&&(b=this.reposition_(a),shaka.log.info("Jumping forward "+(b-a)+" seconds to catch up with the seek range."),this.mediaElement_.currentTime=b)}};
shaka.media.MediaSourcePlayhead.prototype.onSeeking_=function(){this.gapController_.onSeeking();var a=this.videoWrapper_.getTime(),b=this.reposition_(a);if(Math.abs(b-a)>shaka.media.GapJumpingController.BROWSER_GAP_TOLERANCE){var c=Date.now()/1E3;if(!this.lastCorrectiveSeek_||this.lastCorrectiveSeek_<c-1){this.lastCorrectiveSeek_=c;this.videoWrapper_.setTime(b);return}}shaka.log.v1("Seek to "+a);this.onSeek_()};
shaka.media.MediaSourcePlayhead.prototype.clampSeekToDuration_=function(a){var b=this.timeline_.getDuration();return a>=b?(goog.asserts.assert(0<=this.config_.durationBackoff,"Duration backoff must be non-negative!"),b-this.config_.durationBackoff):a};
shaka.media.MediaSourcePlayhead.prototype.reposition_=function(a){goog.asserts.assert(this.config_,"Cannot reposition playhead when it has beeen destroyed");var b=Math.max(this.minBufferTime_,this.config_.rebufferingGoal),c=this.config_.safeSeekOffset,d=this.timeline_.getSeekRangeStart(),e=this.timeline_.getSeekRangeEnd(),f=this.timeline_.getDuration();e-d<this.minSeekRange_&&(d=e-this.minSeekRange_);var g=this.timeline_.getSafeSeekRangeStart(b),h=this.timeline_.getSafeSeekRangeStart(c);b=this.timeline_.getSafeSeekRangeStart(b+
c);if(a>=f)return shaka.log.v1("Playhead past duration."),this.clampSeekToDuration_(a);if(a>e)return shaka.log.v1("Playhead past end."),e;if(a<d){if(shaka.media.TimeRangesUtils.isBuffered(this.mediaElement_.buffered,h))return shaka.log.v1("Playhead before start & start is buffered"),h;shaka.log.v1("Playhead before start & start is unbuffered");return b}if(a>=g||shaka.media.TimeRangesUtils.isBuffered(this.mediaElement_.buffered,a))return shaka.log.v1("Playhead in safe region or in buffered region."),
a;shaka.log.v1("Playhead outside safe region & in unbuffered region.");return b};shaka.media.MediaSourcePlayhead.prototype.clampTime_=function(a){var b=this.timeline_.getSeekRangeStart();if(a<b)return b;b=this.timeline_.getSeekRangeEnd();return a>b?b:a};
shaka.media.MediaSourcePlayhead.prototype.createStallDetector_=function(a,b,c){if(!b.stallEnabled)return null;var d=b.stallThreshold,e=b.stallSkip;b=new shaka.media.StallDetector(new shaka.media.StallDetector.MediaElementImplementation(a),d,c);b.onStall(function(f,g){shaka.log.debug("Stall detected at "+f+" for "+g+" seconds.");e?(shaka.log.debug("Seeking forward "+e+" seconds to break stall."),a.currentTime+=e):(shaka.log.debug("Pausing and unpausing to break stall."),a.pause(),a.play())});return b};shaka.media.SegmentIndex=function(a){goog.DEBUG&&shaka.media.SegmentIndex.assertCorrectReferences_(a);this.references=a;this.timer_=null;this.numEvicted=0;this.immutable_=!1};shaka.media.SegmentIndex.prototype.release=function(){this.immutable_||(this.references=[],this.timer_&&this.timer_.stop(),this.timer_=null)};shaka.media.SegmentIndex.prototype.markImmutable=function(){this.immutable_=!0};
shaka.media.SegmentIndex.prototype.forEachTopLevelReference=function(a){for(var b=$jscomp.makeIterator(this.references),c=b.next();!c.done;c=b.next())a(c.value)};shaka.media.SegmentIndex.prototype.earliestReference=function(){return this.references[0]||null};shaka.media.SegmentIndex.prototype.dropFirstReferences=function(a){this.references.splice(0,a)};
shaka.media.SegmentIndex.prototype.find=function(a){for(var b=this.references.length-1,c=b;0<=c;--c){var d=this.references[c],e=c<b?this.references[c+1].startTime:d.endTime;if(a>=d.startTime&&a<e)return c+this.numEvicted}return this.references.length&&a<this.references[0].startTime?this.numEvicted:null};shaka.media.SegmentIndex.prototype.get=function(a){if(0==this.references.length)return null;a-=this.numEvicted;return 0>a||a>=this.references.length?null:this.references[a]};
shaka.media.SegmentIndex.prototype.offset=function(a){if(!this.immutable_)for(var b=$jscomp.makeIterator(this.references),c=b.next();!c.done;c=b.next())c.value.offset(a)};
shaka.media.SegmentIndex.prototype.merge=function(a){goog.DEBUG&&shaka.media.SegmentIndex.assertCorrectReferences_(a);if(!this.immutable_&&a.length){var b=Math.round(1E3*a[0].startTime)/1E3;this.references=this.references.filter(function(c){return Math.round(1E3*c.startTime)/1E3<b});this.references.push.apply(this.references,$jscomp.arrayFromIterable(a));goog.DEBUG&&shaka.media.SegmentIndex.assertCorrectReferences_(this.references)}};
shaka.media.SegmentIndex.prototype.mergeAndEvict=function(a,b){var c=this;a=a.filter(function(e){return e.endTime>b&&(0==c.references.length||e.endTime>c.references[0].startTime)});var d=this.references[0];this.merge(a);a=this.references[0];d&&goog.asserts.assert(d.startTime==a.startTime,"SegmentIndex.merge should not change the first reference time!");this.evict(b)};
shaka.media.SegmentIndex.prototype.evict=function(a){if(!this.immutable_){var b=this.references.length;this.references=this.references.filter(function(c){return c.endTime>a});this.numEvicted+=b-this.references.length}};
shaka.media.SegmentIndex.prototype.fit=function(a,b,c){c=void 0===c?!1:c;goog.asserts.assert(null!=b,"Content duration must be known for static content!");goog.asserts.assert(Infinity!=b,"Content duration must be finite for static content!");if(!this.immutable_){for(;this.references.length;)if(this.references[this.references.length-1].startTime>=b)this.references.pop();else break;for(;this.references.length;)if(this.references[0].endTime<=a)this.references.shift(),c||this.numEvicted++;else break;
0!=this.references.length&&(a=this.references[this.references.length-1],this.references[this.references.length-1]=new shaka.media.SegmentReference(a.startTime,b,a.getUrisInner,a.startByte,a.endByte,a.initSegmentReference,a.timestampOffset,a.appendWindowStart,a.appendWindowEnd,a.partialReferences,a.tilesLayout,a.tileDuration,a.syncTime,a.status,a.hlsAes128Key))}};
shaka.media.SegmentIndex.prototype.updateEvery=function(a,b){var c=this;goog.asserts.assert(!this.timer_,"SegmentIndex timer already started!");this.immutable_||(this.timer_&&this.timer_.stop(),this.timer_=new shaka.util.Timer(function(){var d=b();d?c.references.push.apply(c.references,$jscomp.arrayFromIterable(d)):(c.timer_.stop(),c.timer_=null)}),this.timer_.tickEvery(a))};
shaka.media.SegmentIndex.prototype[Symbol.iterator]=function(){var a=this.getIteratorForTime(0);goog.asserts.assert(null!=a,"Iterator for 0 should never be null!");return a};
shaka.media.SegmentIndex.prototype.getIteratorForTime=function(a){var b=this.find(a);if(null==b)return null;b--;var c=this.get(b+1),d=-1;if(c&&c.hasPartialSegments())for(var e=c.partialReferences.length-1;0<=e;--e){var f=c.partialReferences[e];if(a>=f.startTime&&a<f.endTime){b++;d=e-1;break}}return new shaka.media.SegmentIterator(this,b,d)};shaka.media.SegmentIndex.prototype.isEmpty=function(){return 0==this.references.length};
shaka.media.SegmentIndex.forSingleSegment=function(a,b,c){a=new shaka.media.SegmentReference(a,a+b,function(){return c},0,null,null,a,a,a+b);return new shaka.media.SegmentIndex([a])};goog.exportSymbol("shaka.media.SegmentIndex",shaka.media.SegmentIndex);goog.exportProperty(shaka.media.SegmentIndex,"forSingleSegment",shaka.media.SegmentIndex.forSingleSegment);goog.exportProperty(shaka.media.SegmentIndex.prototype,"getIteratorForTime",shaka.media.SegmentIndex.prototype.getIteratorForTime);
goog.exportProperty(shaka.media.SegmentIndex.prototype,"updateEvery",shaka.media.SegmentIndex.prototype.updateEvery);goog.exportProperty(shaka.media.SegmentIndex.prototype,"fit",shaka.media.SegmentIndex.prototype.fit);goog.exportProperty(shaka.media.SegmentIndex.prototype,"evict",shaka.media.SegmentIndex.prototype.evict);goog.exportProperty(shaka.media.SegmentIndex.prototype,"mergeAndEvict",shaka.media.SegmentIndex.prototype.mergeAndEvict);
goog.exportProperty(shaka.media.SegmentIndex.prototype,"offset",shaka.media.SegmentIndex.prototype.offset);goog.exportProperty(shaka.media.SegmentIndex.prototype,"get",shaka.media.SegmentIndex.prototype.get);goog.exportProperty(shaka.media.SegmentIndex.prototype,"find",shaka.media.SegmentIndex.prototype.find);goog.exportProperty(shaka.media.SegmentIndex.prototype,"markImmutable",shaka.media.SegmentIndex.prototype.markImmutable);goog.exportProperty(shaka.media.SegmentIndex.prototype,"release",shaka.media.SegmentIndex.prototype.release);
goog.DEBUG&&(shaka.media.SegmentIndex.assertCorrectReferences_=function(a){goog.asserts.assert(a.every(function(b,c){if(0==c)return!0;c=a[c-1];return c.startTime<b.startTime?!0:c.startTime>b.startTime?!1:c.endTime<=b.endTime?!0:!1}),"SegmentReferences are incorrect")});shaka.media.SegmentIterator=function(a,b,c){this.segmentIndex_=a;this.currentPosition_=b;this.currentPartialPosition_=c};shaka.media.SegmentIterator.prototype.currentPosition=function(){return this.currentPosition_};
shaka.media.SegmentIterator.prototype.current=function(){var a=this.segmentIndex_.get(this.currentPosition_);a&&a.hasPartialSegments()&&a.getUris().length&&this.currentPartialPosition_>=a.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0,a=this.segmentIndex_.get(this.currentPosition_));return a&&a.hasPartialSegments()?a.partialReferences[this.currentPartialPosition_]:a};
shaka.media.SegmentIterator.prototype.next=function(){var a=this.segmentIndex_.get(this.currentPosition_);a&&a.hasPartialSegments()?(this.currentPartialPosition_++,a.getUris().length&&this.currentPartialPosition_==a.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0)):(this.currentPosition_++,this.currentPartialPosition_=0);a=this.current();return{value:a,done:!a}};goog.exportSymbol("shaka.media.SegmentIterator",shaka.media.SegmentIterator);
goog.exportProperty(shaka.media.SegmentIterator.prototype,"next",shaka.media.SegmentIterator.prototype.next);goog.exportProperty(shaka.media.SegmentIterator.prototype,"current",shaka.media.SegmentIterator.prototype.current);goog.exportProperty(shaka.media.SegmentIterator.prototype,"currentPosition",shaka.media.SegmentIterator.prototype.currentPosition);shaka.media.MetaSegmentIndex=function(){shaka.media.SegmentIndex.call(this,[]);this.indexes_=[]};$jscomp.inherits(shaka.media.MetaSegmentIndex,shaka.media.SegmentIndex);
shaka.media.MetaSegmentIndex.prototype.appendSegmentIndex=function(a){goog.asserts.assert(0==this.indexes_.length||0==a.numEvicted,"Should not append a new segment index with already-evicted segments");this.indexes_.push(a)};shaka.media.MetaSegmentIndex.prototype.clone=function(){var a=new shaka.media.MetaSegmentIndex;a.indexes_=this.indexes_.slice();return a};
shaka.media.MetaSegmentIndex.prototype.release=function(){for(var a=$jscomp.makeIterator(this.indexes_),b=a.next();!b.done;b=a.next())b.value.release();this.indexes_=[]};shaka.media.MetaSegmentIndex.prototype.find=function(a){for(var b=0,c=$jscomp.makeIterator(this.indexes_),d=c.next();!d.done;d=c.next()){d=d.value;var e=d.find(a);if(null!=e)return e+b;b+=d.numEvicted+d.references.length}return null};
shaka.media.MetaSegmentIndex.prototype.get=function(a){for(var b=0,c=!1,d=$jscomp.makeIterator(this.indexes_),e=d.next();!e.done;e=d.next()){e=e.value;goog.asserts.assert(!c||0==e.numEvicted,"Should not see evicted segments after available segments");var f=e.get(a-b);if(f)return f;b+=e.numEvicted+e.references.length;c=c||0!=e.references.length}return null};shaka.media.MetaSegmentIndex.prototype.offset=function(a){goog.asserts.assert(!1,"offset() should not be used in MetaSegmentIndex!")};
shaka.media.MetaSegmentIndex.prototype.merge=function(a){goog.asserts.assert(!1,"merge() should not be used in MetaSegmentIndex!")};shaka.media.MetaSegmentIndex.prototype.evict=function(a){goog.asserts.assert(!1,"evict() should not be used in MetaSegmentIndex!")};shaka.media.MetaSegmentIndex.prototype.mergeAndEvict=function(a,b){goog.asserts.assert(!1,"mergeAndEvict() should not be used in MetaSegmentIndex!")};shaka.media.MetaSegmentIndex.prototype.fit=function(a,b){goog.asserts.assert(!1,"fit() should not be used in MetaSegmentIndex!")};
shaka.media.MetaSegmentIndex.prototype.updateEvery=function(a,b){goog.asserts.assert(!1,"updateEvery() should not be used in MetaSegmentIndex!")};goog.exportSymbol("shaka.media.MetaSegmentIndex",shaka.media.MetaSegmentIndex);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"updateEvery",shaka.media.MetaSegmentIndex.prototype.updateEvery);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"fit",shaka.media.MetaSegmentIndex.prototype.fit);
goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"mergeAndEvict",shaka.media.MetaSegmentIndex.prototype.mergeAndEvict);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"evict",shaka.media.MetaSegmentIndex.prototype.evict);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"merge",shaka.media.MetaSegmentIndex.prototype.merge);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"offset",shaka.media.MetaSegmentIndex.prototype.offset);
goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"get",shaka.media.MetaSegmentIndex.prototype.get);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"find",shaka.media.MetaSegmentIndex.prototype.find);goog.exportProperty(shaka.media.MetaSegmentIndex.prototype,"release",shaka.media.MetaSegmentIndex.prototype.release);shaka.media.PlayRateController=function(a){var b=this;this.harness_=a;this.isBuffering_=!1;this.rate_=this.harness_.getRate();this.pollRate_=.25;this.timer_=new shaka.util.Timer(function(){b.harness_.movePlayhead(b.rate_*b.pollRate_)})};shaka.media.PlayRateController.prototype.release=function(){this.timer_&&(this.timer_.stop(),this.timer_=null);this.harness_=null};shaka.media.PlayRateController.prototype.setBuffering=function(a){this.isBuffering_=a;this.apply_()};
shaka.media.PlayRateController.prototype.set=function(a){goog.asserts.assert(0!=a,"Should never set rate of 0 explicitly!");this.rate_=a;this.apply_()};shaka.media.PlayRateController.prototype.getRealRate=function(){return this.rate_};shaka.media.PlayRateController.prototype.getDefaultRate=function(){return this.harness_.getDefaultRate()};
shaka.media.PlayRateController.prototype.apply_=function(){this.timer_.stop();var a=this.calculateCurrentRate_();shaka.log.v1("Changing effective playback rate to",a);if(0<=a)try{this.applyRate_(a);return}catch(b){}this.timer_.tickEvery(this.pollRate_);this.applyRate_(0)};shaka.media.PlayRateController.prototype.calculateCurrentRate_=function(){return this.isBuffering_?0:this.rate_};
shaka.media.PlayRateController.prototype.applyRate_=function(a){var b=this.harness_.getRate();b!=a&&this.harness_.setRate(a);return b!=a};shaka.media.IPlayheadObserver=function(){};shaka.media.IPlayheadObserver.prototype.poll=function(a,b){};shaka.media.PlayheadObserverManager=function(a){var b=this;this.mediaElement_=a;this.observers_=new Set;this.pollingLoop_=(new shaka.util.Timer(function(){b.pollAllObservers_(!1)})).tickEvery(.25)};shaka.media.PlayheadObserverManager.prototype.release=function(){this.pollingLoop_.stop();for(var a=$jscomp.makeIterator(this.observers_),b=a.next();!b.done;b=a.next())b.value.release();this.observers_.clear()};
shaka.media.PlayheadObserverManager.prototype.manage=function(a){this.observers_.add(a)};shaka.media.PlayheadObserverManager.prototype.notifyOfSeek=function(){this.pollAllObservers_(!0)};shaka.media.PlayheadObserverManager.prototype.pollAllObservers_=function(a){for(var b=$jscomp.makeIterator(this.observers_),c=b.next();!c.done;c=b.next())c.value.poll(this.mediaElement_.currentTime,a)};shaka.media.QualityObserver=function(a){shaka.util.FakeEventTarget.call(this);this.contentTypeStates_=new Map;this.getBufferedInfo_=a};$jscomp.inherits(shaka.media.QualityObserver,shaka.util.FakeEventTarget);shaka.media.QualityObserver.prototype.release=function(){this.contentTypeStates_.clear();shaka.util.FakeEventTarget.prototype.release.call(this)};
shaka.media.QualityObserver.prototype.getContentTypeState_=function(a){var b=this.contentTypeStates_.get(a);b||(b={qualityChangePositions:[],currentQuality:null,contentType:a},this.contentTypeStates_.set(a,b));return b};
shaka.media.QualityObserver.prototype.addMediaQualityChange=function(a,b){var c=this.getContentTypeState_(a.contentType);this.purgeQualityChangePositions_(c);a={mediaQuality:a,position:b};c=c.qualityChangePositions;var d=c.findIndex(function(e){return e.position>=b});0<=d?c.splice(d,c[d].position==b?1:0,a):c.push(a)};shaka.media.QualityObserver.getMediaQualityAtPosition_=function(a,b){b=b.qualityChangePositions;for(var c=b.length-1;0<=c;c--){var d=b[c];if(d.position<=a)return d.mediaQuality}return null};
shaka.media.QualityObserver.mediaQualitiesAreTheSame_=function(a,b){return a===b?!0:a&&b?a.bandwidth==b.bandwidth&&a.audioSamplingRate==b.audioSamplingRate&&a.codecs==b.codecs&&a.contentType==b.contentType&&a.frameRate==b.frameRate&&a.height==b.height&&a.mimeType==b.mimeType&&a.channelsCount==b.channelsCount&&a.pixelAspectRatio==b.pixelAspectRatio&&a.width==b.width:!1};
shaka.media.QualityObserver.prototype.poll=function(a,b){b=$jscomp.makeIterator(this.contentTypeStates_.values());for(var c=b.next();!c.done;c=b.next()){c=c.value;var d=shaka.media.QualityObserver.getMediaQualityAtPosition_(a,c);d&&!shaka.media.QualityObserver.mediaQualitiesAreTheSame_(c.currentQuality,d)&&this.positionIsBuffered_(a,d.contentType)&&(c.currentQuality=d,shaka.log.debug("Media quality changed at position "+a+" "+JSON.stringify(d)),c=new shaka.util.FakeEvent("qualitychange",new Map([["quality",
d],["position",a]])),this.dispatchEvent(c))}};shaka.media.QualityObserver.prototype.positionIsBuffered_=function(a,b){if((b=this.getBufferedInfo_()[b])&&0<b.length){var c=b[b.length-1].end;if(a>=b[0].start&&a<c)return!0}return!1};
shaka.media.QualityObserver.prototype.purgeQualityChangePositions_=function(a){var b=this.getBufferedInfo_()[a.contentType];if(b&&0<b.length){var c=b[0].start,d=b[b.length-1].end,e=a.qualityChangePositions;a.qualityChangePositions=e.filter(function(f,g){return f.position<=c&&g+1<e.length&&e[g+1].position<=c||f.position>=d?!1:!0})}else a.qualityChangePositions=[]};shaka.media.RegionTimeline=function(a){shaka.util.FakeEventTarget.call(this);var b=this;this.regions_=new Set;this.getSeekRange_=a;this.filterTimer_=(new shaka.util.Timer(function(){b.filterBySeekRange_()})).tickEvery(shaka.media.RegionTimeline.REGION_FILTER_INTERVAL)};$jscomp.inherits(shaka.media.RegionTimeline,shaka.util.FakeEventTarget);shaka.media.RegionTimeline.prototype.release=function(){this.regions_.clear();this.filterTimer_.stop();shaka.util.FakeEventTarget.prototype.release.call(this)};
shaka.media.RegionTimeline.prototype.addRegion=function(a){null==this.findSimilarRegion_(a)&&(this.regions_.add(a),a=new shaka.util.FakeEvent("regionadd",new Map([["region",a]])),this.dispatchEvent(a))};shaka.media.RegionTimeline.prototype.filterBySeekRange_=function(){for(var a=this.getSeekRange_(),b=$jscomp.makeIterator(this.regions_),c=b.next();!c.done;c=b.next())c=c.value,c.endTime<a.start&&(this.regions_.delete(c),c=new shaka.util.FakeEvent("regionremove",new Map([["region",c]])),this.dispatchEvent(c))};
shaka.media.RegionTimeline.prototype.findSimilarRegion_=function(a){for(var b=$jscomp.makeIterator(this.regions_),c=b.next();!c.done;c=b.next())if(c=c.value,c.schemeIdUri==a.schemeIdUri&&c.id==a.id&&c.startTime==a.startTime&&c.endTime==a.endTime)return c;return null};shaka.media.RegionTimeline.prototype.regions=function(){return this.regions_};shaka.media.RegionTimeline.REGION_FILTER_INTERVAL=2;shaka.media.RegionObserver=function(a){shaka.util.FakeEventTarget.call(this);var b=this;this.timeline_=a;this.oldPosition_=new Map;var c=shaka.media.RegionObserver.RelativePosition_;a=c.BEFORE_THE_REGION;var d=c.IN_THE_REGION;c=c.AFTER_THE_REGION;this.rules_=[{weWere:null,weAre:d,invoke:function(e,f){return b.onEvent_("enter",e,f)}},{weWere:a,weAre:d,invoke:function(e,f){return b.onEvent_("enter",e,f)}},{weWere:c,weAre:d,invoke:function(e,f){return b.onEvent_("enter",e,f)}},{weWere:d,weAre:a,invoke:function(e,
f){return b.onEvent_("exit",e,f)}},{weWere:d,weAre:c,invoke:function(e,f){return b.onEvent_("exit",e,f)}},{weWere:a,weAre:c,invoke:function(e,f){return b.onEvent_("skip",e,f)}},{weWere:c,weAre:a,invoke:function(e,f){return b.onEvent_("skip",e,f)}}];this.eventManager_=new shaka.util.EventManager;this.eventManager_.listen(this.timeline_,"regionremove",function(e){b.oldPosition_.delete(e.region)})};$jscomp.inherits(shaka.media.RegionObserver,shaka.util.FakeEventTarget);
shaka.media.RegionObserver.prototype.release=function(){this.timeline_=null;this.oldPosition_.clear();this.eventManager_.release();this.eventManager_=null;shaka.util.FakeEventTarget.prototype.release.call(this)};
shaka.media.RegionObserver.prototype.poll=function(a,b){for(var c=shaka.media.RegionObserver,d=$jscomp.makeIterator(this.timeline_.regions()),e=d.next();!e.done;e=d.next()){e=e.value;var f=this.oldPosition_.get(e),g=c.determinePositionRelativeTo_(e,a);this.oldPosition_.set(e,g);for(var h=$jscomp.makeIterator(this.rules_),k=h.next();!k.done;k=h.next())k=k.value,k.weWere==f&&k.weAre==g&&k.invoke(e,b)}};
shaka.media.RegionObserver.prototype.onEvent_=function(a,b,c){a=new shaka.util.FakeEvent(a,new Map([["region",b],["seeking",c]]));this.dispatchEvent(a)};shaka.media.RegionObserver.determinePositionRelativeTo_=function(a,b){var c=shaka.media.RegionObserver.RelativePosition_;return b<a.startTime?c.BEFORE_THE_REGION:b>a.endTime?c.AFTER_THE_REGION:c.IN_THE_REGION};shaka.media.RegionObserver.RelativePosition_={BEFORE_THE_REGION:1,IN_THE_REGION:2,AFTER_THE_REGION:3};shaka.util.Networking=function(){};shaka.util.Networking.createSegmentRequest=function(a,b,c,d,e){a=shaka.net.NetworkingEngine.makeRequest(a,d,e);if(0!=b||null!=c)a.headers.Range=c?"bytes="+b+"-"+c:"bytes="+b+"-";return a};shaka.media.StreamingEngine=function(a,b){var c=this;this.playerInterface_=b;this.manifest_=a;this.config_=null;this.bufferingGoalScale_=1;this.currentTextStream_=this.currentVariant_=null;this.parsedPrftEventRaised_=!1;this.mediaStates_=new Map;this.startupComplete_=!1;this.failureCallbackBackoff_=null;this.fatalError_=!1;this.destroyer_=new shaka.util.Destroyer(function(){return c.doDestroy_()})};shaka.media.StreamingEngine.prototype.destroy=function(){return this.destroyer_.destroy()};
shaka.media.StreamingEngine.prototype.doDestroy_=function(){var a=this,b,c,d,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress){b=[];c=$jscomp.makeIterator(a.mediaStates_.values());for(d=c.next();!d.done;d=c.next())e=d.value,a.cancelUpdate_(e),b.push(a.abortOperations_(e));return f.yield(Promise.all(b),2)}a.mediaStates_.clear();a.playerInterface_=null;a.manifest_=null;a.config_=null;f.jumpToEnd()})};
shaka.media.StreamingEngine.prototype.configure=function(a){this.config_=a;this.failureCallbackBackoff_=new shaka.net.Backoff({maxAttempts:Math.max(a.retryParameters.maxAttempts,2),baseDelay:a.retryParameters.baseDelay,backoffFactor:a.retryParameters.backoffFactor,fuzzFactor:a.retryParameters.fuzzFactor,timeout:0,stallTimeout:0,connectionTimeout:0},!0)};
shaka.media.StreamingEngine.prototype.start=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){if(1==b.nextAddress)return goog.asserts.assert(a.config_,"StreamingEngine configure() must be called before init()!"),b.yield(a.initStreams_(),2);a.destroyer_.ensureNotDestroyed();shaka.log.debug("init: completed initial Stream setup");a.startupComplete_=!0;b.jumpToEnd()})};shaka.media.StreamingEngine.prototype.getCurrentVariant=function(){return this.currentVariant_};
shaka.media.StreamingEngine.prototype.getCurrentTextStream=function(){return this.currentTextStream_};
shaka.media.StreamingEngine.prototype.loadNewTextStream_=function(a){var b=this,c,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){switch(k.nextAddress){case 1:return c=shaka.util.ManifestParserUtils.ContentType,goog.asserts.assert(!b.mediaStates_.has(c.TEXT),"Should not call loadNewTextStream_ while streaming text!"),k.setCatchFinallyBlocks(2),k.yield(b.playerInterface_.mediaSourceEngine.clear(c.TEXT),4);case 4:k.leaveTryBlock(3);break;case 2:if(d=k.enterCatchBlock(),b.playerInterface_)b.playerInterface_.onError(d);
case 3:e=shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs);b.playerInterface_.mediaSourceEngine.reinitText(e,b.manifest_.sequenceMode);f=b.playerInterface_.mediaSourceEngine.getTextDisplayer();if(g=f.isTextVisible()||b.config_.alwaysStreamText)h=b.createMediaState_(a),b.mediaStates_.set(c.TEXT,h),b.scheduleUpdate_(h,0);k.jumpToEnd()}})};
shaka.media.StreamingEngine.prototype.unloadTextStream=function(){var a=shaka.util.ManifestParserUtils.ContentType,b=this.mediaStates_.get(a.TEXT);b&&(this.cancelUpdate_(b),this.abortOperations_(b).catch(function(){}),this.mediaStates_.delete(a.TEXT));this.currentTextStream_=null};
shaka.media.StreamingEngine.prototype.setTrickPlay=function(a){var b=this.mediaStates_.get(shaka.util.ManifestParserUtils.ContentType.VIDEO);if(b){var c=b.stream;if(c)if(shaka.log.debug("setTrickPlay",a),a)(a=c.trickModeVideo)&&!b.restoreStreamAfterTrickPlay&&(shaka.log.debug("Engaging trick mode stream",a),this.switchInternal_(a,!1,0,!1),b.restoreStreamAfterTrickPlay=c);else if(c=b.restoreStreamAfterTrickPlay)shaka.log.debug("Restoring non-trick-mode stream",c),b.restoreStreamAfterTrickPlay=null,
this.switchInternal_(c,!0,0,!1)}};shaka.media.StreamingEngine.prototype.switchVariant=function(a,b,c,d,e){b=void 0===b?!1:b;c=void 0===c?0:c;d=void 0===d?!1:d;e=void 0===e?!1:e;this.currentVariant_=a;this.startupComplete_&&(a.video&&this.switchInternal_(a.video,b,c,d,e),a.audio&&this.switchInternal_(a.audio,b,c,d,e))};
shaka.media.StreamingEngine.prototype.switchTextStream=function(a){this.currentTextStream_=a;if(this.startupComplete_){var b=shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(a&&a.type==b.TEXT,"Wrong stream type passed to switchTextStream!");this.switchInternal_(a,!0,0,!1)}};shaka.media.StreamingEngine.prototype.reloadTextStream=function(){var a=this.mediaStates_.get(shaka.util.ManifestParserUtils.ContentType.TEXT);a&&this.switchInternal_(a.stream,!0,0,!0)};
shaka.media.StreamingEngine.prototype.switchInternal_=function(a,b,c,d,e){var f=this,g=shaka.util.ManifestParserUtils.ContentType,h=this.mediaStates_.get(a.type);h||a.type!=g.TEXT?(goog.asserts.assert(h,"switch: expected mediaState to exist"),h&&(h.restoreStreamAfterTrickPlay&&(shaka.log.debug("switch during trick play mode",a),a.trickModeVideo?(h.restoreStreamAfterTrickPlay=a,a=a.trickModeVideo,shaka.log.debug("switch found trick play stream",a)):(h.restoreStreamAfterTrickPlay=null,shaka.log.debug("switch found no special trick play stream"))),
h.stream!=a||d?(a.type==g.TEXT&&(d=shaka.util.MimeUtils.getFullType(a.mimeType,a.codecs),this.playerInterface_.mediaSourceEngine.reinitText(d,this.manifest_.sequenceMode)),h.stream.closeSegmentIndex&&h.stream.closeSegmentIndex(),h.stream=a,h.segmentIterator=null,h.adaptation=!!e,a=shaka.media.StreamingEngine.logPrefix_(h),shaka.log.debug("switch: switching to Stream "+a),b&&(h.clearingBuffer?h.waitingToFlushBuffer=!0:h.performingUpdate?(h.waitingToClearBuffer=!0,h.clearBufferSafeMargin=c,h.waitingToFlushBuffer=
!0):(this.cancelUpdate_(h),this.clearBuffer_(h,!0,c).catch(function(k){f.playerInterface_&&(goog.asserts.assert(k instanceof shaka.util.Error,"Wrong error type!"),f.playerInterface_.onError(k))}))),this.makeAbortDecision_(h).catch(function(k){f.playerInterface_&&(goog.asserts.assert(k instanceof shaka.util.Error,"Wrong error type!"),f.playerInterface_.onError(k))})):(b=shaka.media.StreamingEngine.logPrefix_(h),shaka.log.debug("switch: Stream "+b+" already active")))):this.loadNewTextStream_(a)};
shaka.media.StreamingEngine.prototype.makeAbortDecision_=function(a){var b=this,c,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress){if(!a.operation)return e.return();c=a.stream;d=a.operation;return c.segmentIndex?e.jumpTo(2):e.yield(c.createSegmentIndex(),2)}if(a.operation!=d||a.stream!=c)return e.return();goog.asserts.assert(a.stream.segmentIndex,"Segment index should exist by now!");b.shouldAbortCurrentRequest_(a)&&(shaka.log.info("Aborting current segment request."),
a.operation.abort());e.jumpToEnd()})};
shaka.media.StreamingEngine.prototype.shouldAbortCurrentRequest_=function(a){goog.asserts.assert(a.operation,"Abort logic requires an ongoing operation!");goog.asserts.assert(a.stream&&a.stream.segmentIndex,"Abort logic requires a segment index");var b=this.playerInterface_.getPresentationTime(),c=this.playerInterface_.mediaSourceEngine.bufferEnd(a.type),d=this.getTimeNeeded_(a,b);d=a.stream.segmentIndex.find(d);var e=null==d?null:a.stream.segmentIndex.get(d);d=e?e.getSize():null;e&&!d&&(d=(e.getEndTime()-
e.getStartTime())*(a.stream.bandwidth||0)/8);if(!d)return!1;(e=e.initSegmentReference)&&(d+=e.getSize()||0);e=this.playerInterface_.getBandwidthEstimate();return 8*d/e<(c||0)-b-Math.max(this.manifest_.minBufferTime||0,this.config_.rebufferingGoal)||a.operation.getBytesRemaining()>d?!0:!1};
shaka.media.StreamingEngine.prototype.seeked=function(){if(this.playerInterface_){for(var a=this.playerInterface_.getPresentationTime(),b=shaka.util.ManifestParserUtils.ContentType,c=!1,d=$jscomp.makeIterator(this.mediaStates_.keys()),e=d.next();!e.done;e=d.next()){e=e.value;var f=this.mediaStates_.get(e),g=shaka.media.StreamingEngine.logPrefix_(f);f.segmentIterator=null;if(!this.playerInterface_.mediaSourceEngine.isBuffered(e,a)){if(null!=this.playerInterface_.mediaSourceEngine.bufferEnd(e)||f.performingUpdate)this.forceClearBuffer_(f),
c=!0;f.operation&&(f.operation.abort(),shaka.log.debug(g,"Aborting operation due to seek"),f.operation=null);e===b.TEXT&&this.playerInterface_.mediaSourceEngine.resetCaptionParser();f.seeked=!0}}c||shaka.log.debug("(all): seeked: buffered seek: presentationTime="+a)}};
shaka.media.StreamingEngine.prototype.forceClearBuffer_=function(a){var b=this,c=shaka.media.StreamingEngine.logPrefix_(a);a.clearingBuffer?shaka.log.debug(c,"clear: already clearing the buffer"):a.waitingToClearBuffer?shaka.log.debug(c,"clear: already waiting"):a.performingUpdate?(shaka.log.debug(c,"clear: currently updating"),a.waitingToClearBuffer=!0,a.clearBufferSafeMargin=0):null==this.playerInterface_.mediaSourceEngine.bufferStart(a.type)?(shaka.log.debug(c,"clear: nothing buffered"),null==
a.updateTimer&&this.scheduleUpdate_(a,0)):(shaka.log.debug(c,"clear: handling right now"),this.cancelUpdate_(a),this.clearBuffer_(a,!1,0).catch(function(d){b.playerInterface_&&(goog.asserts.assert(d instanceof shaka.util.Error,"Wrong error type!"),b.playerInterface_.onError(d))}))};
shaka.media.StreamingEngine.prototype.initStreams_=function(){var a=this,b,c,d,e,f,g,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){if(1==n.nextAddress){b=shaka.util.ManifestParserUtils.ContentType;goog.asserts.assert(a.config_,"StreamingEngine configure() must be called before init()!");if(!a.currentVariant_)throw shaka.log.error("init: no Streams chosen"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STREAMING,shaka.util.Error.Code.STREAMING_ENGINE_STARTUP_INVALID_STATE);
c=new Map;d=new Set;a.currentVariant_.audio&&(c.set(b.AUDIO,a.currentVariant_.audio),d.add(a.currentVariant_.audio));a.currentVariant_.video&&(c.set(b.VIDEO,a.currentVariant_.video),d.add(a.currentVariant_.video));a.currentTextStream_&&(c.set(b.TEXT,a.currentTextStream_),d.add(a.currentTextStream_));e=a.playerInterface_.mediaSourceEngine;f=a.config_.forceTransmux;return n.yield(e.init(c,f,a.manifest_.sequenceMode),2)}a.destroyer_.ensureNotDestroyed();a.updateDuration();g=$jscomp.makeIterator(c.keys());
for(h=g.next();!h.done;h=g.next())k=h.value,l=c.get(k),a.mediaStates_.has(k)||(m=a.createMediaState_(l),a.mediaStates_.set(k,m),a.scheduleUpdate_(m,0));n.jumpToEnd()})};
shaka.media.StreamingEngine.prototype.createMediaState_=function(a){return{stream:a,type:a.type,segmentIterator:null,lastSegmentReference:null,lastInitSegmentReference:null,lastTimestampOffset:null,lastAppendWindowStart:null,lastAppendWindowEnd:null,restoreStreamAfterTrickPlay:null,endOfStream:!1,performingUpdate:!1,updateTimer:null,waitingToClearBuffer:!1,clearBufferSafeMargin:0,waitingToFlushBuffer:!1,clearingBuffer:!1,seeked:!0,needsResync:!1,recovering:!1,hasError:!1,operation:null}};
shaka.media.StreamingEngine.prototype.updateDuration=function(){var a=this.manifest_.presentationTimeline.getDuration();Infinity>a?this.playerInterface_.mediaSourceEngine.setDuration(a):this.playerInterface_.mediaSourceEngine.setDuration(Math.pow(2,32))};
shaka.media.StreamingEngine.prototype.onUpdate_=function(a){var b=this,c,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){switch(k.nextAddress){case 1:b.destroyer_.ensureNotDestroyed();c=shaka.media.StreamingEngine.logPrefix_(a);goog.asserts.assert(!a.performingUpdate&&null!=a.updateTimer,c+" unexpected call to onUpdate_()");if(a.performingUpdate||null==a.updateTimer)return k.return();goog.asserts.assert(!a.clearingBuffer,c+" onUpdate_() should not be called when clearing the buffer");
if(a.clearingBuffer)return k.return();a.updateTimer=null;if(!a.waitingToClearBuffer){k.jumpTo(2);break}shaka.log.debug(c,"skipping update and clearing the buffer");return k.yield(b.clearBuffer_(a,a.waitingToFlushBuffer,a.clearBufferSafeMargin),3);case 3:return k.return();case 2:if(a.stream.segmentIndex){k.jumpTo(4);break}d=a.stream;return k.yield(a.stream.createSegmentIndex(),5);case 5:if(d!=a.stream)return d.closeSegmentIndex&&(goog.asserts.assert(!a.stream.segmentIndex,"mediastate.stream should not have segmentIndex yet."),
d.closeSegmentIndex()),a.performingUpdate||a.updateTimer||b.scheduleUpdate_(a,0),k.return();case 4:k.setCatchFinallyBlocks(6);e=b.update_(a);null!=e&&(b.scheduleUpdate_(a,e),a.hasError=!1);k.leaveTryBlock(7);break;case 6:return f=k.enterCatchBlock(),k.yield(b.handleStreamingError_(f),8);case 8:return k.return();case 7:g=Array.from(b.mediaStates_.values());if(!b.startupComplete_||!g.every(function(l){return l.endOfStream})){k.jumpTo(0);break}shaka.log.v1(c,"calling endOfStream()...");return k.yield(b.playerInterface_.mediaSourceEngine.endOfStream(),
10);case 10:b.destroyer_.ensureNotDestroyed(),h=b.playerInterface_.mediaSourceEngine.getDuration(),0!=h&&h<b.manifest_.presentationTimeline.getDuration()&&b.manifest_.presentationTimeline.setDuration(h),k.jumpToEnd()}})};
shaka.media.StreamingEngine.prototype.update_=function(a){goog.asserts.assert(this.manifest_,"manifest_ should not be null");goog.asserts.assert(this.config_,"config_ should not be null");var b=shaka.util.ManifestParserUtils.ContentType;if(shaka.media.StreamingEngine.isEmbeddedText_(a))return this.playerInterface_.mediaSourceEngine.setSelectedClosedCaptionId(a.stream.originalId||""),null;a.type==b.TEXT&&this.playerInterface_.mediaSourceEngine.clearSelectedClosedCaptionId();var c=shaka.media.StreamingEngine.logPrefix_(a),
d=this.playerInterface_.getPresentationTime(),e=this.getTimeNeeded_(a,d);shaka.log.v2(c,"timeNeeded="+e);var f=this.playerInterface_.mediaSourceEngine.bufferedAheadOf(a.type,d);shaka.log.v2(c,"update_:","presentationTime="+d,"bufferedAhead="+f);var g=Math.max(this.manifest_.minBufferTime||0,this.config_.rebufferingGoal,this.config_.bufferingGoal)*this.bufferingGoalScale_,h=this.manifest_.presentationTimeline.getDuration()-e,k=this.playerInterface_.mediaSourceEngine.bufferEnd(a.type);if(1E-6>h&&k)return shaka.log.debug(c,
"buffered to end of presentation"),a.endOfStream=!0,a.type==b.VIDEO&&(a=this.mediaStates_.get(b.TEXT))&&shaka.media.StreamingEngine.isEmbeddedText_(a)&&(a.endOfStream=!0),null;a.endOfStream=!1;if(f>=g)return shaka.log.v2(c,"buffering goal met"),this.config_.updateIntervalSeconds/2;b=this.getSegmentReferenceNeeded_(a,d,k);if(!b)return this.config_.updateIntervalSeconds;f=Infinity;g=Array.from(this.mediaStates_.values());g=$jscomp.makeIterator(g);for(h=g.next();!h.done;h=g.next())h=h.value,shaka.media.StreamingEngine.isEmbeddedText_(h)||
h.segmentIterator&&!h.segmentIterator.current()||(h=this.getTimeNeeded_(h,d),f=Math.min(f,h));g=this.manifest_.presentationTimeline.getMaxSegmentDuration()*shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_;if(e>=f+g)return shaka.log.v2(c,"waiting for other streams to buffer"),this.config_.updateIntervalSeconds;this.fetchAndAppend_(a,d,b).catch(function(){});return null};
shaka.media.StreamingEngine.prototype.getTimeNeeded_=function(a,b){return a.lastSegmentReference?a.lastSegmentReference.endTime:b};
shaka.media.StreamingEngine.prototype.getSegmentReferenceNeeded_=function(a,b,c){var d=shaka.media.StreamingEngine.logPrefix_(a);goog.asserts.assert(a.stream.segmentIndex,"segment index should have been generated already");if(a.segmentIterator)return a.segmentIterator.current();if(a.lastSegmentReference||c)return b=a.lastSegmentReference?a.lastSegmentReference.endTime:c,goog.asserts.assert(null!=b,"Should have a time to search"),shaka.log.v1(d,"looking up segment from new stream endTime:",b),a.needsResync=
!0,a.segmentIterator=a.stream.segmentIndex.getIteratorForTime(b),a=a.segmentIterator&&a.segmentIterator.next().value,null==a&&shaka.log.warning(d,"cannot find segment","endTime:",b),a;c=this.config_.inaccurateManifestTolerance;var e=Math.max(b-c,0);shaka.log.v1(d,"looking up segment","lookupTime:",e,"presentationTime:",b);var f=null;c&&(a.segmentIterator=a.stream.segmentIndex.getIteratorForTime(e),f=a.segmentIterator&&a.segmentIterator.next().value);f||(a.segmentIterator=a.stream.segmentIndex.getIteratorForTime(b),
f=a.segmentIterator&&a.segmentIterator.next().value);null==f&&shaka.log.warning(d,"cannot find segment","lookupTime:",e,"presentationTime:",b);return f};
shaka.media.StreamingEngine.prototype.fetchAndAppend_=function(a,b,c){var d=this,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A;return $jscomp.asyncExecutePromiseGeneratorProgram(function(z){switch(z.nextAddress){case 1:e=shaka.util.ManifestParserUtils.ContentType;f=shaka.media.StreamingEngine;g=f.logPrefix_(a);shaka.log.v1(g,"fetchAndAppend_:","presentationTime="+b,"reference.startTime="+c.startTime,"reference.endTime="+c.endTime);h=a.stream;k=a.segmentIterator;a.performingUpdate=!0;z.setCatchFinallyBlocks(2);
if(c.getStatus()==shaka.media.SegmentReference.Status.MISSING)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.SEGMENT_MISSING);return z.yield(d.initSourceBuffer_(a,c),4);case 4:d.destroyer_.ensureNotDestroyed();if(d.fatalError_)return z.return();shaka.log.v2(g,"fetching segment");l="video/mp4"==h.mimeType||"audio/mp4"==h.mimeType;m=window.ReadableStream;if(d.config_.lowLatencyMode&&m&&l&&!c.hlsAes128Key)return q=new Uint8Array(0),
w=r=!1,u=function(B){var D,G,C;return $jscomp.asyncExecutePromiseGeneratorProgram(function(E){if(r)return E.return();w=!0;d.destroyer_.ensureNotDestroyed();if(d.fatalError_)return E.return();q=d.concatArray_(q,B);D=!1;G=0;(new shaka.util.Mp4Parser).box("mdat",function(F){G=F.size+F.start;D=!0}).parse(q,!1,!0);if(!D)return E.jumpTo(0);C=q.subarray(0,G);q=q.subarray(G);return E.yield(d.append_(a,b,h,c,C),0)})},z.yield(d.fetch_(a,c,u),11);d.config_.lowLatencyMode&&!m&&shaka.log.warning("Low latency streaming mode is enabled, but ReadableStream is not supported by the browser.");
n=d.fetch_(a,c);return z.yield(n,7);case 7:p=z.yieldResult;d.destroyer_.ensureNotDestroyed();if(d.fatalError_)return z.return();if(!c.hlsAes128Key){z.jumpTo(8);break}goog.asserts.assert(k,"mediaState.segmentIterator should exist");return z.yield(d.aes128Decrypt_(p,c,k),9);case 9:p=z.yieldResult;case 8:return d.destroyer_.ensureNotDestroyed(),a.waitingToClearBuffer?(shaka.log.info(g,"waitingToClearBuffer, skip append"),a.performingUpdate=!1,d.scheduleUpdate_(a,0),z.return()):z.yield(d.append_(a,b,
h,c,p),6);case 11:v=z.yieldResult;if(w){z.jumpTo(6);break}r=!0;d.destroyer_.ensureNotDestroyed();return d.fatalError_?z.return():a.waitingToClearBuffer?(shaka.log.info(g,"waitingToClearBuffer, skip append"),a.performingUpdate=!1,d.scheduleUpdate_(a,0),z.return()):z.yield(d.append_(a,b,h,c,v),6);case 6:d.destroyer_.ensureNotDestroyed();if(d.fatalError_)return z.return();a.lastSegmentReference=c;x=k.next().value;shaka.log.v2(g,"advancing to next segment",x);a.performingUpdate=!1;a.recovering=!1;t=d.playerInterface_.mediaSourceEngine.getBufferedInfo();
y=t[a.type];shaka.log.v1(g,"finished fetch and append",JSON.stringify(y));if(!a.waitingToClearBuffer)d.playerInterface_.onSegmentAppended(c.startTime,c.endTime,a.type);d.scheduleUpdate_(a,0);z.leaveTryBlock(0);break;case 2:A=z.enterCatchBlock();d.destroyer_.ensureNotDestroyed(A);if(d.fatalError_)return z.return();goog.asserts.assert(A instanceof shaka.util.Error,"Should only receive a Shaka error");a.performingUpdate=!1;if(A.code==shaka.util.Error.Code.OPERATION_ABORTED)a.performingUpdate=!1,d.cancelUpdate_(a),
d.scheduleUpdate_(a,0),z.jumpTo(0);else if(a.type==e.TEXT&&d.config_.ignoreTextStreamFailures)A.code==shaka.util.Error.Code.BAD_HTTP_STATUS?shaka.log.warning(g,"Text stream failed to download. Proceeding without it."):shaka.log.warning(g,"Text stream failed to parse. Proceeding without it."),d.mediaStates_.delete(e.TEXT),z.jumpTo(0);else if(A.code==shaka.util.Error.Code.QUOTA_EXCEEDED_ERROR)d.handleQuotaExceeded_(a,A),z.jumpTo(0);else return shaka.log.error(g,"failed fetch and append: code="+A.code),
a.hasError=!0,A.severity=shaka.util.Error.Severity.CRITICAL,z.yield(d.handleStreamingError_(A),0)}})};
shaka.media.StreamingEngine.prototype.aes128Decrypt_=function(a,b,c){var d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress){d=b.hlsAes128Key;if(d.cryptoKey)return h.jumpTo(2);goog.asserts.assert(d.fetchKey,"If AES-128 cryptoKey was not preloaded, fetchKey function should be provided");return h.yield(d.fetchKey(),3)}2!=h.nextAddress&&goog.asserts.assert(d.cryptoKey,"AES-128 cryptoKey should now be set");e=d.iv;if(!e)for(e=shaka.util.BufferUtils.toUint8(new ArrayBuffer(16)),
f=d.firstMediaSequenceNumber+c.currentPosition(),g=e.byteLength-1;0<=g;g--)e[g]=f&255,f>>=8;return h.return(window.crypto.subtle.decrypt({name:"AES-CBC",iv:e},d.cryptoKey,a))})};
shaka.media.StreamingEngine.prototype.retry=function(a){if(this.destroyer_.destroyed())return shaka.log.error("Unable to retry after StreamingEngine is destroyed!"),!1;if(this.fatalError_)return shaka.log.error("Unable to retry after StreamingEngine encountered a fatal error!"),!1;for(var b=$jscomp.makeIterator(this.mediaStates_.values()),c=b.next();!c.done;c=b.next()){c=c.value;var d=shaka.media.StreamingEngine.logPrefix_(c);!c.hasError||c.performingUpdate||c.updateTimer||(shaka.log.info(d,"Retrying after failure..."),
c.hasError=!1,this.scheduleUpdate_(c,a))}return!0};shaka.media.StreamingEngine.prototype.concatArray_=function(a,b){var c=new Uint8Array(a.length+b.length);c.set(a);c.set(b,a.length);return c};
shaka.media.StreamingEngine.prototype.handleQuotaExceeded_=function(a,b){var c=shaka.media.StreamingEngine.logPrefix_(a);if(Array.from(this.mediaStates_.values()).some(function(e){return e!=a&&e.recovering}))shaka.log.debug(c,"MediaSource threw QuotaExceededError:","waiting for another stream to recover...");else{var d=Math.round(100*this.bufferingGoalScale_);if(20<d)this.bufferingGoalScale_-=.2;else if(4<d)this.bufferingGoalScale_-=.04;else{shaka.log.error(c,"MediaSource threw QuotaExceededError too many times");
this.fatalError_=a.hasError=!0;this.playerInterface_.onError(b);return}shaka.log.warning(c,"MediaSource threw QuotaExceededError:","reducing buffering goals by "+(100-Math.round(100*this.bufferingGoalScale_))+"%");a.recovering=!0}this.scheduleUpdate_(a,4)};
shaka.media.StreamingEngine.prototype.initSourceBuffer_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p;return $jscomp.asyncExecutePromiseGeneratorProgram(function(q){d=shaka.media.StreamingEngine;e=d.logPrefix_(a);f=[];g=Math.max(0,b.appendWindowStart-d.APPEND_WINDOW_START_FUDGE_);h=b.appendWindowEnd+d.APPEND_WINDOW_END_FUDGE_;goog.asserts.assert(b.startTime<=h,e+" segment should start before append window end");k=b.timestampOffset;if(k!=a.lastTimestampOffset||g!=a.lastAppendWindowStart||h!=a.lastAppendWindowEnd)shaka.log.v1(e,
"setting timestamp offset to "+k),shaka.log.v1(e,"setting append window start to "+g),shaka.log.v1(e,"setting append window end to "+h),l=function(){var r;return $jscomp.asyncExecutePromiseGeneratorProgram(function(w){if(1==w.nextAddress)return w.setCatchFinallyBlocks(2),a.lastAppendWindowStart=g,a.lastAppendWindowEnd=h,a.lastTimestampOffset=k,w.yield(c.playerInterface_.mediaSourceEngine.setStreamProperties(a.type,k,g,h,c.manifest_.sequenceMode),4);if(2!=w.nextAddress)return w.leaveTryBlock(0);r=
w.enterCatchBlock();a.lastAppendWindowStart=null;a.lastAppendWindowEnd=null;a.lastTimestampOffset=null;throw r;})},f.push(l());!shaka.media.InitSegmentReference.equal(b.initSegmentReference,a.lastInitSegmentReference)&&(a.lastInitSegmentReference=b.initSegmentReference)&&(shaka.log.v1(e,"fetching init segment"),m=c.fetch_(a,b.initSegmentReference),n=function(){var r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:return t.setCatchFinallyBlocks(2),
t.yield(m,4);case 4:return r=t.yieldResult,c.destroyer_.ensureNotDestroyed(),w=new shaka.util.Mp4Parser,u=shaka.util.Mp4Parser,w.box("moov",u.children).box("trak",u.children).box("mdia",u.children).fullBox("mdhd",function(y){c.parseMDHD_(b,y)}).parse(r),shaka.log.v1(e,"appending init segment"),v=a.stream.closedCaptions&&0<a.stream.closedCaptions.size,t.yield(c.playerInterface_.beforeAppendSegment(a.type,r),5);case 5:return t.yield(c.playerInterface_.mediaSourceEngine.appendBuffer(a.type,r,null,v),
6);case 6:t.leaveTryBlock(0);break;case 2:throw x=t.enterCatchBlock(),a.lastInitSegmentReference=null,x;}})},c.playerInterface_.onInitSegmentAppended(b.startTime,b.initSegmentReference),f.push(n()));c.manifest_.sequenceMode&&(p=a.lastSegmentReference?a.lastSegmentReference.discontinuitySequence:null,b.discontinuitySequence!=p||a.needsResync)&&(a.needsResync=!1,f.push(c.playerInterface_.mediaSourceEngine.resync(a.type,b.startTime)));return q.yield(Promise.all(f),0)})};
shaka.media.StreamingEngine.prototype.append_=function(a,b,c,d,e){var f=this,g,h,k,l,m,n,p;return $jscomp.asyncExecutePromiseGeneratorProgram(function(q){switch(q.nextAddress){case 1:g=shaka.media.StreamingEngine.logPrefix_(a);h=c.closedCaptions&&0<c.closedCaptions.size;l=null!=c.emsgSchemeIdUris&&0<c.emsgSchemeIdUris.length||f.config_.dispatchAllEmsgBoxes;m=f.config_.parsePrftBox&&!f.parsedPrftEventRaised_;if(l||m)k=new shaka.util.Mp4Parser;l&&k.fullBox("emsg",function(r){return f.parseEMSG_(d,c.emsgSchemeIdUris,
r)});m&&k.fullBox("prft",function(r){return f.parsePrft_(d,r)});(l||m)&&k.parse(e);return q.yield(f.evict_(a,b),2);case 2:return f.destroyer_.ensureNotDestroyed(),n=a.seeked,a.seeked=!1,p=a.adaptation,a.adaptation=!1,q.yield(f.playerInterface_.beforeAppendSegment(a.type,e),3);case 3:return q.yield(f.playerInterface_.mediaSourceEngine.appendBuffer(a.type,e,d,h,n,p),4);case 4:f.destroyer_.ensureNotDestroyed(),shaka.log.v2(g,"appended media segment"),q.jumpToEnd()}})};
shaka.media.StreamingEngine.prototype.parseEMSG_=function(a,b,c){if(0===c.version){var d=c.reader.readTerminatedString();var e=c.reader.readTerminatedString();var f=c.reader.readUint32();var g=c.reader.readUint32();var h=c.reader.readUint32();var k=c.reader.readUint32();var l=a.startTime+g/f}else f=c.reader.readUint32(),l=c.reader.readUint64()/f+a.timestampOffset,g=l-a.startTime,h=c.reader.readUint32(),k=c.reader.readUint32(),d=c.reader.readTerminatedString(),e=c.reader.readTerminatedString();c=c.reader.readBytes(c.reader.getLength()-
c.reader.getPosition());if(b&&b.includes(d)||this.config_.dispatchAllEmsgBoxes)if("urn:mpeg:dash:event:2012"==d)this.playerInterface_.onManifestUpdate();else if("https://aomedia.org/emsg/ID3"==d){if(b=shaka.util.Id3Utils.getID3Frames(c),b.length&&a)this.playerInterface_.onMetadata([{cueTime:a.startTime,data:c,frames:b,dts:a.startTime,pts:a.startTime}],0,a.endTime)}else b={startTime:l,endTime:l+h/f,schemeIdUri:d,value:e,timescale:f,presentationTimeDelta:g,eventDuration:h,id:k,messageData:c},a=shaka.util.FakeEvent.EventName.Emsg,
b=(new Map).set("detail",b),a=new shaka.util.FakeEvent(a,b),this.playerInterface_.onEvent(a)};shaka.media.StreamingEngine.prototype.parseMDHD_=function(a,b){b=shaka.util.Mp4BoxParsers.parseMDHD(b.reader||0,b.version||0);a.initSegmentReference.timescale=b.timescale};
shaka.media.StreamingEngine.prototype.parsePrft_=function(a,b){if(!this.parsedPrftEventRaised_&&a.initSegmentReference.timescale){b.reader.readUint32();var c=b.reader.readUint32(),d=b.reader.readUint32();c=1E3*c+d/Math.pow(2,32)*1E3;if(0===b.version)var e=b.reader.readUint32();else try{e=b.reader.readUint64()}catch(f){shaka.log.warning("parsePrft_: parsing mediatime resulted in a MEDIA.JS_INTEGER_OVERFLOW exception");this.parsedPrftEventRaised_=!0;return}a=a.initSegmentReference.timescale;b=this.convertNtp(c);
a={wallClockTime:b,programStartDate:new Date(b-e/a*1E3)};e=shaka.util.FakeEvent.EventName.Prft;a=(new Map).set("detail",a);e=new shaka.util.FakeEvent(e,a);this.playerInterface_.onEvent(e);this.parsedPrftEventRaised_=!0}};shaka.media.StreamingEngine.prototype.convertNtp=function(a){var b=new Date(Date.UTC(1900,0,1,0,0,0));return(new Date(b.getTime()+a)).getTime()};
shaka.media.StreamingEngine.prototype.evict_=function(a,b){var c=this,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress){d=shaka.media.StreamingEngine.logPrefix_(a);shaka.log.v2(d,"checking buffer length");e=Math.max(c.config_.bufferBehind,c.manifest_.presentationTimeline.getMaxSegmentDuration());f=c.playerInterface_.mediaSourceEngine.bufferStart(a.type);if(null==f)return shaka.log.v2(d,"buffer behind okay because nothing buffered:","presentationTime="+b,
"bufferBehind="+e),k.return();g=b-f;h=g-e;if(.01>=h)return shaka.log.v2(d,"buffer behind okay:","presentationTime="+b,"bufferedBehind="+g,"bufferBehind="+e,"underflow="+Math.abs(h)),k.return();shaka.log.v1(d,"buffer behind too large:","presentationTime="+b,"bufferedBehind="+g,"bufferBehind="+e,"overflow="+h);return k.yield(c.playerInterface_.mediaSourceEngine.remove(a.type,f,f+h),2)}c.destroyer_.ensureNotDestroyed();shaka.log.v1(d,"evicted "+h+" seconds");k.jumpToEnd()})};
shaka.media.StreamingEngine.isEmbeddedText_=function(a){var b=shaka.util.MimeUtils,c=b.CEA608_CLOSED_CAPTION_MIMETYPE;b=b.CEA708_CLOSED_CAPTION_MIMETYPE;return a&&a.type==shaka.util.ManifestParserUtils.ContentType.TEXT&&(a.stream.mimeType==c||a.stream.mimeType==b)};
shaka.media.StreamingEngine.prototype.fetch_=function(a,b,c){var d=this,e,f,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){if(1==l.nextAddress)return e=shaka.net.NetworkingEngine.RequestType.SEGMENT,f=shaka.util.Networking.createSegmentRequest(b.getUris(),b.startByte,b.endByte,d.config_.retryParameters,c),shaka.log.v2("fetching: reference=",b),g=a.stream,d.playerInterface_.modifySegmentRequest(f,{type:g.type,init:b instanceof shaka.media.InitSegmentReference,duration:b.endTime-
b.startTime,mimeType:g.mimeType,codecs:g.codecs,bandwidth:g.bandwidth}),h=d.playerInterface_.netEngine.request(e,f),a.operation=h,l.yield(h.promise,2);k=l.yieldResult;a.operation=null;return l.return(k.data)})};
shaka.media.StreamingEngine.prototype.clearBuffer_=function(a,b,c){var d=this,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return e=shaka.media.StreamingEngine.logPrefix_(a),goog.asserts.assert(!a.performingUpdate&&null==a.updateTimer,e+" unexpected call to clearBuffer_()"),a.waitingToClearBuffer=!1,a.waitingToFlushBuffer=!1,a.clearBufferSafeMargin=0,a.clearingBuffer=!0,a.lastSegmentReference=null,a.lastInitSegmentReference=null,a.segmentIterator=null,shaka.log.debug(e,
"clearing buffer"),c?(f=d.playerInterface_.getPresentationTime(),g=d.playerInterface_.mediaSourceEngine.getDuration(),h.yield(d.playerInterface_.mediaSourceEngine.remove(a.type,f+c,g),3)):h.yield(d.playerInterface_.mediaSourceEngine.clear(a.type),4);if(3!=h.nextAddress)return d.destroyer_.ensureNotDestroyed(),b?h.yield(d.playerInterface_.mediaSourceEngine.flush(a.type),3):h.jumpTo(3);d.destroyer_.ensureNotDestroyed();shaka.log.debug(e,"cleared buffer");a.clearingBuffer=!1;a.endOfStream=!1;a.performingUpdate||
a.updateTimer||d.scheduleUpdate_(a,0);h.jumpToEnd()})};
shaka.media.StreamingEngine.prototype.scheduleUpdate_=function(a,b){var c=this,d=shaka.media.StreamingEngine.logPrefix_(a),e=a.type;e!=shaka.util.ManifestParserUtils.ContentType.TEXT||this.mediaStates_.has(e)?(shaka.log.v2(d,"updating in "+b+" seconds"),goog.asserts.assert(null==a.updateTimer,d+" did not expect update to be scheduled"),a.updateTimer=(new shaka.util.DelayedTick(function(){var f;return $jscomp.asyncExecutePromiseGeneratorProgram(function(g){if(1==g.nextAddress)return g.setCatchFinallyBlocks(2),
g.yield(c.onUpdate_(a),4);if(2!=g.nextAddress)return g.leaveTryBlock(0);f=g.enterCatchBlock();if(c.playerInterface_)c.playerInterface_.onError(f);g.jumpToEnd()})})).tickAfter(b)):shaka.log.v1(d,"Text stream is unloaded. No update is needed.")};shaka.media.StreamingEngine.prototype.cancelUpdate_=function(a){null!=a.updateTimer&&(a.updateTimer.stop(),a.updateTimer=null)};
shaka.media.StreamingEngine.prototype.abortOperations_=function(a){return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return a.operation?b.yield(a.operation.abort(),0):b.jumpTo(0)})};
shaka.media.StreamingEngine.prototype.handleStreamingError_=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return c.yield(b.failureCallbackBackoff_.attempt(),2);b.destroyer_.ensureNotDestroyed();b.playerInterface_.onError(a);a.handled||b.config_.failureCallback(a);c.jumpToEnd()})};shaka.media.StreamingEngine.logPrefix_=function(a){return"("+a.type+":"+a.stream.id+")"};shaka.media.StreamingEngine.APPEND_WINDOW_START_FUDGE_=.1;
shaka.media.StreamingEngine.APPEND_WINDOW_END_FUDGE_=.01;shaka.media.StreamingEngine.MAX_RUN_AHEAD_SEGMENTS_=1;shaka.routing={};shaka.routing.Node={};shaka.routing.Payload={};shaka.routing.Walker=function(a,b,c){var d=this;this.implementation_=c;this.currentlyAt_=a;this.currentlyWith_=b;this.waitForWork_=null;this.requests_=[];this.currentStep_=this.currentRoute_=null;this.mainLoopPromise_=Promise.resolve().then(function(){return d.mainLoop_()});this.destroyer_=new shaka.util.Destroyer(function(){return d.doDestroy_()})};shaka.routing.Walker.prototype.getCurrentPayload=function(){return this.currentlyWith_};shaka.routing.Walker.prototype.destroy=function(){return this.destroyer_.destroy()};
shaka.routing.Walker.prototype.doDestroy_=function(){var a=this,b,c,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return a.currentStep_&&a.currentStep_.abort(),a.unblockMainLoop_(),e.yield(a.mainLoopPromise_,2);if(a.currentRoute_)a.currentRoute_.listeners.onCancel();b=$jscomp.makeIterator(a.requests_);for(c=b.next();!c.done;c=b.next())d=c.value,d.listeners.onCancel();a.currentRoute_=null;a.requests_=[];a.implementation_=null;e.jumpToEnd()})};
shaka.routing.Walker.prototype.startNewRoute=function(a){var b={onStart:function(){},onEnd:function(){},onCancel:function(){},onError:function(c){},onSkip:function(){},onEnter:function(){}};this.requests_.push({create:a,listeners:b});this.currentStep_&&this.currentStep_.abort();this.unblockMainLoop_();return b};
shaka.routing.Walker.prototype.mainLoop_=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return a.destroyer_.destroyed()?b.jumpTo(0):b.yield(a.doOneThing_(),1)})};
shaka.routing.Walker.prototype.doOneThing_=function(){if(this.tryNewRoute_())return Promise.resolve();if(this.currentRoute_)return this.takeNextStep_();goog.asserts.assert(null==this.waitForWork_,"We should not have a promise yet.");this.implementation_.onIdle(this.currentlyAt_);return this.waitForWork_=new shaka.util.PublicPromise};
shaka.routing.Walker.prototype.tryNewRoute_=function(){goog.asserts.assert(null==this.currentStep_,"We should never have a current step between taking steps.");if(0==this.requests_.length||this.currentRoute_&&!this.currentRoute_.interruptible)return!1;this.currentRoute_&&(this.currentRoute_.listeners.onCancel(),this.currentRoute_=null);var a=this.requests_.shift(),b=a.create(this.currentlyWith_);if(b)a.listeners.onStart(),this.currentRoute_={node:b.node,payload:b.payload,interruptible:b.interruptible,
listeners:a.listeners};else a.listeners.onSkip();return!0};
shaka.routing.Walker.prototype.takeNextStep_=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){switch(d.nextAddress){case 1:return goog.asserts.assert(a.currentRoute_,"We need a current route to take the next step."),a.currentlyAt_=a.implementation_.getNext(a.currentlyAt_,a.currentlyWith_,a.currentRoute_.node,a.currentRoute_.payload),a.currentRoute_.listeners.onEnter(a.currentlyAt_),d.setCatchFinallyBlocks(2),a.currentStep_=a.implementation_.enterNode(a.currentlyAt_,
a.currentlyWith_,a.currentRoute_.payload),d.yield(a.currentStep_.promise,4);case 4:a.currentStep_=null;a.currentlyAt_==a.currentRoute_.node&&(a.currentRoute_.listeners.onEnd(),a.currentRoute_=null);d.leaveTryBlock(0);break;case 2:b=d.enterCatchBlock();if(b.code==shaka.util.Error.Code.OPERATION_ABORTED)goog.asserts.assert(a.currentRoute_.interruptible,"Do not put abortable steps in non-interruptible routes!"),a.currentRoute_.listeners.onCancel();else a.currentRoute_.listeners.onError(b);a.currentRoute_=
null;a.currentStep_=null;c=a;return d.yield(a.implementation_.handleError(a.currentlyWith_,b),5);case 5:c.currentlyAt_=d.yieldResult,d.jumpToEnd()}})};shaka.routing.Walker.prototype.unblockMainLoop_=function(){this.waitForWork_&&(this.waitForWork_.resolve(),this.waitForWork_=null)};shaka.text.Utils=function(){};
shaka.text.Utils.flattenPayload_=function(a){var b=[],c=a.fontWeight>=shaka.text.Cue.fontWeight.BOLD,d=a.fontStyle==shaka.text.Cue.fontStyle.ITALIC,e=a.textDecoration.includes(shaka.text.Cue.textDecoration.UNDERLINE);c&&b.push("b");d&&b.push("i");e&&b.push("u");c=b.reduce(function(f,g){return f+"<"+g+">"},"");b=b.reduceRight(function(f,g){return f+"</"+g+">"},"");return a.lineBreak?"\n":a.nestedCues.length?a.nestedCues.map(shaka.text.Utils.flattenPayload_).join(""):c+a.payload+b};
shaka.text.Utils.getCuesToFlatten=function(a,b){a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())if(c=c.value,c.isContainer)shaka.text.Utils.getCuesToFlatten(c.nestedCues,b);else{var d=c.clone();d.nestedCues=[];d.payload=shaka.text.Utils.flattenPayload_(c);b.push(d)}return b};shaka.text.SimpleTextDisplayer=function(a){this.textTrack_=null;for(var b=$jscomp.makeIterator(Array.from(a.textTracks)),c=b.next();!c.done;c=b.next())c=c.value,c.mode="disabled",c.label==shaka.Player.TextTrackLabel&&(this.textTrack_=c);this.textTrack_||(this.textTrack_=a.addTextTrack("subtitles",shaka.Player.TextTrackLabel));this.textTrack_.mode="hidden"};
shaka.text.SimpleTextDisplayer.prototype.remove=function(a,b){if(!this.textTrack_)return!1;shaka.text.SimpleTextDisplayer.removeWhere_(this.textTrack_,function(c){return c.startTime<b&&c.endTime>a});return!0};
shaka.text.SimpleTextDisplayer.prototype.append=function(a){var b=shaka.text.Utils.getCuesToFlatten(a,[]),c=[];a=this.textTrack_.cues?Array.from(this.textTrack_.cues):[];var d={};b=$jscomp.makeIterator(b);for(var e=b.next();!e.done;d={$jscomp$loop$prop$inCue$653:d.$jscomp$loop$prop$inCue$653},e=b.next())d.$jscomp$loop$prop$inCue$653=e.value,a.some(function(f){return function(g){return g.startTime==f.$jscomp$loop$prop$inCue$653.startTime&&g.endTime==f.$jscomp$loop$prop$inCue$653.endTime&&g.text==f.$jscomp$loop$prop$inCue$653.payload?
!0:!1}}(d))||(e=shaka.text.SimpleTextDisplayer.convertToTextTrackCue_(d.$jscomp$loop$prop$inCue$653))&&c.push(e);a=c.slice().sort(function(f,g){return f.startTime!=g.startTime?f.startTime-g.startTime:f.endTime!=g.endTime?f.endTime-g.startTime:"line"in VTTCue.prototype?c.indexOf(g)-c.indexOf(f):c.indexOf(f)-c.indexOf(g)});a=$jscomp.makeIterator(a);for(d=a.next();!d.done;d=a.next())this.textTrack_.addCue(d.value)};
shaka.text.SimpleTextDisplayer.prototype.destroy=function(){this.textTrack_&&(shaka.text.SimpleTextDisplayer.removeWhere_(this.textTrack_,function(a){return!0}),this.textTrack_.mode="disabled");this.textTrack_=null;return Promise.resolve()};shaka.text.SimpleTextDisplayer.prototype.isTextVisible=function(){return"showing"==this.textTrack_.mode};shaka.text.SimpleTextDisplayer.prototype.setTextVisibility=function(a){this.textTrack_.mode=a?"showing":"hidden"};
shaka.text.SimpleTextDisplayer.convertToTextTrackCue_=function(a){if(a.startTime>=a.endTime)return shaka.log.warning("Invalid cue times: "+a.startTime+" - "+a.endTime),null;var b=shaka.text.Cue,c=new VTTCue(a.startTime,a.endTime,a.payload);c.lineAlign=a.lineAlign;c.positionAlign=a.positionAlign;a.size&&(c.size=a.size);try{c.align=a.textAlign}catch(d){}"center"==a.textAlign&&"center"!=c.align&&(c.align="middle");a.writingMode==b.writingMode.VERTICAL_LEFT_TO_RIGHT?c.vertical="lr":a.writingMode==b.writingMode.VERTICAL_RIGHT_TO_LEFT&&
(c.vertical="rl");a.lineInterpretation==b.lineInterpretation.PERCENTAGE&&(c.snapToLines=!1);null!=a.line&&(c.line=a.line);null!=a.position&&(c.position=a.position);return c};shaka.text.SimpleTextDisplayer.removeWhere_=function(a,b){var c=a.mode,d="showing"==c?"showing":"hidden";a.mode=d;goog.asserts.assert(a.cues,'Cues should be accessible when mode is set to "'+d+'".');d=$jscomp.makeIterator(Array.from(a.cues));for(var e=d.next();!e.done;e=d.next())(e=e.value)&&b(e)&&a.removeCue(e);a.mode=c};
goog.exportSymbol("shaka.text.SimpleTextDisplayer",shaka.text.SimpleTextDisplayer);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"setTextVisibility",shaka.text.SimpleTextDisplayer.prototype.setTextVisibility);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"isTextVisible",shaka.text.SimpleTextDisplayer.prototype.isTextVisible);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"destroy",shaka.text.SimpleTextDisplayer.prototype.destroy);
goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"append",shaka.text.SimpleTextDisplayer.prototype.append);goog.exportProperty(shaka.text.SimpleTextDisplayer.prototype,"remove",shaka.text.SimpleTextDisplayer.prototype.remove);shaka.util.Dom=function(){};shaka.util.Dom.createHTMLElement=function(a){return document.createElement(a)};shaka.util.Dom.createButton=function(){var a=document.createElement("button");a.setAttribute("type","button");return a};shaka.util.Dom.asHTMLElement=function(a){return a};shaka.util.Dom.asHTMLMediaElement=function(a){return a};shaka.util.Dom.getElementByClassName=function(a,b){b=b.getElementsByClassName(a);goog.asserts.assert(1==b.length,"Should only be one element with class name "+a);return shaka.util.Dom.asHTMLElement(b[0])};
shaka.util.Dom.removeAllChildren=function(a){for(;a.firstChild;)a.removeChild(a.firstChild)};goog.exportSymbol("shaka.util.Dom",shaka.util.Dom);goog.exportProperty(shaka.util.Dom,"removeAllChildren",shaka.util.Dom.removeAllChildren);shaka.text.UITextDisplayer=function(a,b){var c=this;goog.asserts.assert(b,"videoContainer should be valid.");this.isTextVisible_=!1;this.cues_=[];this.video_=a;this.videoContainer_=b;this.textContainer_=shaka.util.Dom.createHTMLElement("div");this.textContainer_.classList.add("shaka-text-container");this.textContainer_.style.textAlign="center";this.textContainer_.style.display="flex";this.textContainer_.style.flexDirection="column";this.textContainer_.style.alignItems="center";this.textContainer_.style.justifyContent=
"flex-end";this.videoContainer_.appendChild(this.textContainer_);this.captionsTimer_=(new shaka.util.Timer(function(){c.updateCaptions_()})).tickEvery(.25);this.currentCuesMap_=new Map;this.eventManager_=new shaka.util.EventManager;this.eventManager_.listen(document,"fullscreenchange",function(){c.updateCaptions_(!0)});this.resizeObserver_=null;"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver(function(){c.updateCaptions_(!0)}),this.resizeObserver_.observe(this.textContainer_));
this.regionElements_=new Map};shaka.text.UITextDisplayer.prototype.append=function(a){var b=[].concat($jscomp.arrayFromIterable(this.cues_)),c={};a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;c={$jscomp$loop$prop$cue$655:c.$jscomp$loop$prop$cue$655},d=a.next())c.$jscomp$loop$prop$cue$655=d.value,b.some(function(e){return function(f){return shaka.text.Cue.equal(f,e.$jscomp$loop$prop$cue$655)}}(c))||this.cues_.push(c.$jscomp$loop$prop$cue$655);this.updateCaptions_()};
shaka.text.UITextDisplayer.prototype.destroy=function(){this.videoContainer_.removeChild(this.textContainer_);this.textContainer_=null;this.isTextVisible_=!1;this.cues_=[];this.captionsTimer_&&this.captionsTimer_.stop();this.currentCuesMap_.clear();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null)};
shaka.text.UITextDisplayer.prototype.remove=function(a,b){if(!this.textContainer_)return!1;var c=this.cues_.length;this.cues_=this.cues_.filter(function(d){return d.startTime<a||d.endTime>=b});this.updateCaptions_(c>this.cues_.length);return!0};shaka.text.UITextDisplayer.prototype.isTextVisible=function(){return this.isTextVisible_};shaka.text.UITextDisplayer.prototype.setTextVisibility=function(a){this.isTextVisible_=a};
shaka.text.UITextDisplayer.prototype.isElementUnderTextContainer_=function(a){for(;null!=a;){if(a==this.textContainer_)return!0;a=a.parentElement}return!1};
shaka.text.UITextDisplayer.prototype.updateCuesRecursive_=function(a,b,c,d){var e=!1,f=[],g=[];a=$jscomp.makeIterator(a);for(var h=a.next();!h.done;h=a.next()){h=h.value;d.push(h);var k=this.currentCuesMap_.get(h),l=h.startTime<=c&&h.endTime>c,m=k?k.wrapper:null;k&&(f.push(k.cueElement),k.regionElement&&f.push(k.regionElement),l||(e=!0,this.currentCuesMap_.delete(h),k=null));l&&(g.push(h),k?this.isElementUnderTextContainer_(m)||(e=!0):(this.createCue_(h,d),k=this.currentCuesMap_.get(h),m=k.wrapper,
e=!0));0<h.nestedCues.length&&m&&this.updateCuesRecursive_(h.nestedCues,m,c,d);k=d.pop();goog.asserts.assert(k==h,"Parent cues should be kept in order")}if(e){c=$jscomp.makeIterator(f);for(d=c.next();!d.done;d=c.next())d=d.value,d.parentElement&&d.parentElement.removeChild(d);g.sort(function(n,p){return n.startTime!=p.startTime?n.startTime-p.startTime:n.endTime-p.endTime});g=$jscomp.makeIterator(g);for(h=g.next();!h.done;h=g.next())c=this.currentCuesMap_.get(h.value),goog.asserts.assert(c,"cueRegistry should exist."),
c.regionElement?(b.appendChild(c.regionElement),c.regionElement.appendChild(c.cueElement)):b.appendChild(c.cueElement)}};
shaka.text.UITextDisplayer.prototype.updateCaptions_=function(a){if(this.textContainer_){var b=this.video_.currentTime;if(!this.isTextVisible_||(void 0===a?0:a)){a=$jscomp.makeIterator(this.regionElements_.values());for(var c=a.next();!c.done;c=a.next())shaka.util.Dom.removeAllChildren(c.value);shaka.util.Dom.removeAllChildren(this.textContainer_);this.currentCuesMap_.clear();this.regionElements_.clear()}if(this.isTextVisible_){a=new Map;c=$jscomp.makeIterator(this.currentCuesMap_.keys());for(var d=
c.next();!d.done;d=c.next())d=d.value,a.set(d,this.currentCuesMap_.get(d));this.updateCuesRecursive_(this.cues_,this.textContainer_,b,[]);if(goog.DEBUG)for(b=$jscomp.makeIterator(a.keys()),d=b.next();!d.done;d=b.next())c=d.value,this.currentCuesMap_.has(c)||(c=a.get(c).cueElement,goog.asserts.assert(!c.parentNode,"Cue was not properly removed!"))}}};
shaka.text.UITextDisplayer.prototype.generateRegionId_=function(a){var b=shaka.text.CueRegion.units.PERCENTAGE;return a.id+"_"+a.width+"x"+a.height+(a.heightUnits==b?"%":"px")+"-"+a.viewportAnchorX+"x"+a.viewportAnchorY+(a.viewportAnchorUnits==b?"%":"px")};
shaka.text.UITextDisplayer.prototype.getRegionElement_=function(a){var b=a.region,c=this.generateRegionId_(b);if(this.regionElements_.has(c))return this.regionElements_.get(c);var d=shaka.util.Dom.createHTMLElement("span"),e=shaka.text.CueRegion.units.PERCENTAGE,f=b.heightUnits==e?"%":"px",g=b.widthUnits==e?"%":"px";e=b.viewportAnchorUnits==e?"%":"px";d.id="shaka-text-region---"+c;d.classList.add("shaka-text-region");d.style.height=b.height+f;d.style.width=b.width+g;d.style.position="absolute";d.style.top=
b.viewportAnchorY+e;d.style.left=b.viewportAnchorX+e;d.style.display="flex";d.style.flexDirection="column";d.style.alignItems="center";d.style.justifyContent=a.displayAlign==shaka.text.Cue.displayAlign.BEFORE?"flex-start":a.displayAlign==shaka.text.Cue.displayAlign.CENTER?"center":"flex-end";this.regionElements_.set(c,d);return d};
shaka.text.UITextDisplayer.prototype.createCue_=function(a,b){var c=1<b.length,d=c?"span":"div";a.lineBreak&&(d="br");c=!c&&0<a.nestedCues.length;var e=shaka.util.Dom.createHTMLElement(d);"br"!=d&&this.setCaptionStyles_(e,a,b,c);b=null;a.region&&a.region.id&&(b=this.getRegionElement_(a));d=e;c&&(d=shaka.util.Dom.createHTMLElement("span"),d.classList.add("shaka-text-wrapper"),d.style.backgroundColor=a.backgroundColor,d.style.lineHeight="normal",e.appendChild(d));this.currentCuesMap_.set(a,{cueElement:e,
wrapper:d,regionElement:b})};
shaka.text.UITextDisplayer.prototype.setCaptionStyles_=function(a,b,c,d){var e=shaka.text.Cue,f=a.style,g=0==b.nestedCues.length,h=1<c.length;f.whiteSpace="pre-wrap";var k=b.payload.replace(/\s+$/g,function(m){return"\u00a0".repeat(m.length)});f.webkitTextStrokeColor=b.textStrokeColor;f.webkitTextStrokeWidth=b.textStrokeWidth;f.color=b.color;f.direction=b.direction;f.opacity=b.opacity;f.paddingLeft=shaka.text.UITextDisplayer.convertLengthValue_(b.linePadding,b,this.videoContainer_);f.paddingRight=
shaka.text.UITextDisplayer.convertLengthValue_(b.linePadding,b,this.videoContainer_);f.textShadow=b.textShadow;if(b.backgroundImage)f.backgroundImage="url('"+b.backgroundImage+"')",f.backgroundRepeat="no-repeat",f.backgroundSize="contain",f.backgroundPosition="center",f.width="100%",f.height="100%";else{if(b.nestedCues.length)var l=a;else l=shaka.util.Dom.createHTMLElement("span"),a.appendChild(l);b.border&&(l.style.border=b.border);d||((a=shaka.text.UITextDisplayer.inheritProperty_(c,function(m){return m.backgroundColor}))?
l.style.backgroundColor=a:k&&(l.style.backgroundColor="rgba(0, 0, 0, 0.8)"));k&&(l.textContent=k)}h&&!c[c.length-1].isContainer?f.display="inline":(f.display="flex",f.flexDirection="column",f.alignItems="center",f.justifyContent=b.displayAlign==e.displayAlign.BEFORE?"flex-start":b.displayAlign==e.displayAlign.CENTER?"center":"flex-end");g||(f.margin="0");f.fontFamily=b.fontFamily;f.fontWeight=b.fontWeight.toString();f.fontStyle=b.fontStyle;f.letterSpacing=b.letterSpacing;f.fontSize=shaka.text.UITextDisplayer.convertLengthValue_(b.fontSize,
b,this.videoContainer_);null!=b.line&&b.lineInterpretation==e.lineInterpretation.PERCENTAGE&&(f.position="absolute",b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?(f.width="100%",b.lineAlign==e.lineAlign.START?f.top=b.line+"%":b.lineAlign==e.lineAlign.END&&(f.bottom=100-b.line+"%")):b.writingMode==e.writingMode.VERTICAL_LEFT_TO_RIGHT?(f.height="100%",b.lineAlign==e.lineAlign.START?f.left=b.line+"%":b.lineAlign==e.lineAlign.END&&(f.right=100-b.line+"%")):(f.height="100%",b.lineAlign==e.lineAlign.START?
f.right=b.line+"%":b.lineAlign==e.lineAlign.END&&(f.left=100-b.line+"%")));f.lineHeight=b.lineHeight;null!=b.position&&(b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?f.paddingLeft=b.position:f.paddingTop=b.position);b.positionAlign==e.positionAlign.LEFT?f.cssFloat="left":b.positionAlign==e.positionAlign.RIGHT&&(f.cssFloat="right");f.textAlign=b.textAlign;f.textDecoration=b.textDecoration.join(" ");f.writingMode=b.writingMode;"writingMode"in document.documentElement.style&&f.writingMode==b.writingMode||
(f.webkitWritingMode=b.writingMode);b.size&&(b.writingMode==e.writingMode.HORIZONTAL_TOP_TO_BOTTOM?f.width=b.size+"%":f.height=b.size+"%")};shaka.text.UITextDisplayer.getLengthValueInfo_=function(a){return(a=(new RegExp(/(\d*\.?\d+)([a-z]+|%+)/)).exec(a))?{value:Number(a[1]),unit:a[2]}:null};
shaka.text.UITextDisplayer.convertLengthValue_=function(a,b,c){var d=shaka.text.UITextDisplayer.getLengthValueInfo_(a);if(!d)return a;var e=d.value;switch(d.unit){case "%":return shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_(e/100,b,c);case "c":return shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_(e,b,c);default:return a}};shaka.text.UITextDisplayer.getAbsoluteLengthInPixels_=function(a,b,c){return c.clientHeight*a/b.cellResolution.rows+"px"};
shaka.text.UITextDisplayer.inheritProperty_=function(a,b){for(var c=a.length-1;0<=c;c--){var d=b(a[c]);if(d||0===d)return d}return null};goog.exportSymbol("shaka.text.UITextDisplayer",shaka.text.UITextDisplayer);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"setTextVisibility",shaka.text.UITextDisplayer.prototype.setTextVisibility);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"isTextVisible",shaka.text.UITextDisplayer.prototype.isTextVisible);
goog.exportProperty(shaka.text.UITextDisplayer.prototype,"remove",shaka.text.UITextDisplayer.prototype.remove);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"destroy",shaka.text.UITextDisplayer.prototype.destroy);goog.exportProperty(shaka.text.UITextDisplayer.prototype,"append",shaka.text.UITextDisplayer.prototype.append);shaka.text.WebVttGenerator=function(){};
shaka.text.WebVttGenerator.convert=function(a,b){var c=function(f){for(var g=f,h=$jscomp.makeIterator(b),k=h.next();!k.done;k=h.next())k=k.value,k.end&&k.start<f&&(g+=k.end-k.start);f=Math.floor(g/3600);h=Math.floor(g/60%60);k=Math.floor(g%60);g=Math.floor(1E3*g%1E3);return(10>f?"0":"")+f+":"+(10>h?"0":"")+h+":"+(10>k?"0":"")+k+"."+(100>g?10>g?"00":"0":"")+g},d=shaka.text.Utils.getCuesToFlatten(a,[]);a="WEBVTT\n\n";d=$jscomp.makeIterator(d);for(var e=d.next();!e.done;e=d.next())e=e.value,a+=c(e.startTime)+
" --\x3e "+c(e.endTime)+function(f){var g=[],h=shaka.text.Cue;switch(f.textAlign){case h.textAlign.LEFT:g.push("align:left");break;case h.textAlign.RIGHT:g.push("align:right");break;case h.textAlign.CENTER:g.push("align:middle");break;case h.textAlign.START:g.push("align:start");break;case h.textAlign.END:g.push("align:end")}switch(f.writingMode){case h.writingMode.VERTICAL_LEFT_TO_RIGHT:g.push("vertical:lr");break;case h.writingMode.VERTICAL_RIGHT_TO_LEFT:g.push("vertical:rl")}return g.length?" "+
g.join(" "):""}(e)+"\n",a+=e.payload+"\n\n";return a};goog.exportSymbol("shaka.text.WebVttGenerator",shaka.text.WebVttGenerator);shaka.util.CmcdManager=function(a,b){this.playerInterface_=a;this.config_=b;this.sid_="";this.sf_=void 0;this.playbackStarted_=!1;this.buffering_=!0;this.starved_=!1};shaka.util.CmcdManager.prototype.setBuffering=function(a){a||this.playbackStarted_||(this.playbackStarted_=!0);this.playbackStarted_&&a&&(this.starved_=!0);this.buffering_=a};
shaka.util.CmcdManager.prototype.applyManifestData=function(a,b){try{this.config_.enabled&&(this.sf_=b.format,this.apply_(a,{ot:shaka.util.CmcdManager.ObjectType.MANIFEST,su:!this.playbackStarted_}))}catch(c){shaka.log.warnOnce("CMCD_MANIFEST_ERROR","Could not generate manifest CMCD data.",c)}};
shaka.util.CmcdManager.prototype.applySegmentData=function(a,b){try{if(this.config_.enabled){var c={d:1E3*b.duration,st:this.getStreamType_()};c.ot=this.getObjectType_(b);var d=shaka.util.CmcdManager.ObjectType,e=c.ot===d.VIDEO||c.ot===d.AUDIO||c.ot===d.MUXED||c.ot===d.TIMED_TEXT;e&&(c.bl=this.getBufferLength_(b.type));b.bandwidth&&(c.br=b.bandwidth/1E3);e&&c.ot!==d.TIMED_TEXT&&(c.tb=this.getTopBandwidth_(c.ot)/1E3);this.apply_(a,c)}}catch(f){shaka.log.warnOnce("CMCD_SEGMENT_ERROR","Could not generate segment CMCD data.",
f)}};shaka.util.CmcdManager.prototype.applyTextData=function(a){try{this.config_.enabled&&this.apply_(a,{ot:shaka.util.CmcdManager.ObjectType.CAPTION,su:!0})}catch(b){shaka.log.warnOnce("CMCD_TEXT_ERROR","Could not generate text CMCD data.",b)}};
shaka.util.CmcdManager.prototype.appendSrcData=function(a,b){try{if(!this.config_.enabled)return a;var c=this.createData_();c.ot=this.getObjectTypeFromMimeType_(b);c.su=!0;var d=shaka.util.CmcdManager.toQuery(c);return shaka.util.CmcdManager.appendQueryToUri(a,d)}catch(e){return shaka.log.warnOnce("CMCD_SRC_ERROR","Could not generate src CMCD data.",e),a}};
shaka.util.CmcdManager.prototype.appendTextTrackData=function(a){try{if(!this.config_.enabled)return a;var b=this.createData_();b.ot=shaka.util.CmcdManager.ObjectType.CAPTION;b.su=!0;var c=shaka.util.CmcdManager.toQuery(b);return shaka.util.CmcdManager.appendQueryToUri(a,c)}catch(d){return shaka.log.warnOnce("CMCD_TEXT_TRACK_ERROR","Could not generate text track CMCD data.",d),a}};
shaka.util.CmcdManager.prototype.createData_=function(){this.sid_||(this.sid_=this.config_.sessionId||window.crypto.randomUUID());return{v:shaka.util.CmcdManager.Version,sf:this.sf_,sid:this.sid_,cid:this.config_.contentId,mtp:this.playerInterface_.getBandwidthEstimate()/1E3}};
shaka.util.CmcdManager.prototype.apply_=function(a,b,c){b=void 0===b?{}:b;c=void 0===c?this.config_.useHeaders:c;if(this.config_.enabled){Object.assign(b,this.createData_());b.pr=this.playerInterface_.getPlaybackRate();var d=b.ot===shaka.util.CmcdManager.ObjectType.VIDEO||b.ot===shaka.util.CmcdManager.ObjectType.MUXED;this.starved_&&d&&(b.bs=!0,b.su=!0,this.starved_=!1);null==b.su&&(b.su=this.buffering_);if(c)b=shaka.util.CmcdManager.toHeaders(b),Object.keys(b).length&&Object.assign(a.headers,b);
else{var e=shaka.util.CmcdManager.toQuery(b);e&&(a.uris=a.uris.map(function(f){return shaka.util.CmcdManager.appendQueryToUri(f,e)}))}}};
shaka.util.CmcdManager.prototype.getObjectType_=function(a){var b=a.type;if(a.init)return shaka.util.CmcdManager.ObjectType.INIT;if("video"==b)return a.codecs.includes(",")?shaka.util.CmcdManager.ObjectType.MUXED:shaka.util.CmcdManager.ObjectType.VIDEO;if("audio"==b)return shaka.util.CmcdManager.ObjectType.AUDIO;if("text"==b)return"application/mp4"===a.mimeType?shaka.util.CmcdManager.ObjectType.TIMED_TEXT:shaka.util.CmcdManager.ObjectType.CAPTION};
shaka.util.CmcdManager.prototype.getObjectTypeFromMimeType_=function(a){switch(a){case "video/webm":case "video/mp4":return shaka.util.CmcdManager.ObjectType.MUXED;case "application/x-mpegurl":return shaka.util.CmcdManager.ObjectType.MANIFEST}};shaka.util.CmcdManager.prototype.getBufferLength_=function(a){a=this.playerInterface_.getBufferedInfo()[a];if(!a.length)return NaN;var b=this.playerInterface_.getCurrentTime();return(a=a.find(function(c){return c.start<=b&&c.end>=b}))?1E3*(a.end-b):NaN};
shaka.util.CmcdManager.prototype.getStreamType_=function(){return this.playerInterface_.isLive()?shaka.util.CmcdManager.StreamType.LIVE:shaka.util.CmcdManager.StreamType.VOD};
shaka.util.CmcdManager.prototype.getTopBandwidth_=function(a){var b=this.playerInterface_.getVariantTracks();if(!b.length)return NaN;var c=b[0];b=$jscomp.makeIterator(b);for(var d=b.next();!d.done;d=b.next())d=d.value,"variant"===d.type&&d.bandwidth>c.bandwidth&&(c=d);b=shaka.util.CmcdManager.ObjectType;switch(a){case b.VIDEO:return c.videoBandwidth||NaN;case b.AUDIO:return c.audioBandwidth||NaN;default:return c.bandwidth}};
shaka.util.CmcdManager.serialize=function(a){var b=[],c=function(m){return!Number.isNaN(m)&&null!=m&&""!==m&&!1!==m},d=function(m){return Math.round(m)},e=function(m){return 100*d(m/100)};e={br:d,d:d,bl:e,dl:e,mtp:e,nor:function(m){return encodeURIComponent(m)},rtp:e,tb:d};var f=Object.keys(a||{}).sort();f=$jscomp.makeIterator(f);for(var g=f.next();!g.done;g=f.next()){g=g.value;var h=a[g];if(c(h)&&("v"!==g||1!==h)&&("pr"!=g||1!==h)){var k=e[g];k&&(h=k(h));k=typeof h;var l=void 0;l="string"===k&&"ot"!==
g&&"sf"!==g&&"st"!==g?g+"="+JSON.stringify(h):"boolean"===k?g:"symbol"===k?g+"="+h.description:g+"="+h;b.push(l)}}return b.join(",")};
shaka.util.CmcdManager.toHeaders=function(a){var b=Object.keys(a),c={},d=["Object","Request","Session","Status"],e=[{},{},{},{}],f={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};b=$jscomp.makeIterator(b);for(var g=b.next();!g.done;g=b.next())g=g.value,e[null!=f[g]?f[g]:1][g]=a[g];for(a=0;a<e.length;a++)(f=shaka.util.CmcdManager.serialize(e[a]))&&(c["CMCD-"+d[a]]=f);return c};shaka.util.CmcdManager.toQuery=function(a){return shaka.util.CmcdManager.serialize(a)};
shaka.util.CmcdManager.appendQueryToUri=function(a,b){if(!b||a.includes("offline:"))return a;a=new goog.Uri(a);a.getQueryData().set("CMCD",b);return a.toString()};shaka.util.CmcdManager.ObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};shaka.util.CmcdManager.StreamType={VOD:"v",LIVE:"l"};shaka.util.CmcdManager.StreamingFormat={DASH:"d",HLS:"h",SMOOTH:"s",OTHER:"o"};goog.exportSymbol("shaka.util.CmcdManager.StreamingFormat",shaka.util.CmcdManager.StreamingFormat);
shaka.util.CmcdManager.Version=1;shaka.util.ConfigUtils=function(){};
shaka.util.ConfigUtils.mergeConfigObjects=function(a,b,c,d,e){goog.asserts.assert(a,"Destination config must not be null!");var f=e in d,g=!0,h;for(h in b){var k=e+"."+h,l=f?d[e]:c[h];f||h in c?void 0===b[h]?void 0===l||f?delete a[h]:a[h]=shaka.util.ObjectUtils.cloneObject(l):l.constructor==Object&&b[h]&&b[h].constructor==Object?(a[h]||(a[h]=shaka.util.ObjectUtils.cloneObject(l)),k=shaka.util.ConfigUtils.mergeConfigObjects(a[h],b[h],l,d,k),g=g&&k):typeof b[h]!=typeof l||null==b[h]||"function"!=typeof b[h]&&
b[h].constructor!=l.constructor?(shaka.log.alwaysError("Invalid config, wrong type for "+k),g=!1):("function"==typeof c[h]&&c[h].length!=b[h].length&&shaka.log.alwaysWarn("Unexpected number of arguments for "+k),a[h]=b[h]):(shaka.log.alwaysError("Invalid config, unrecognized key "+k),g=!1)}return g};
shaka.util.ConfigUtils.convertToConfigObject=function(a,b){for(var c={},d=c,e=0,f=0;;){e=a.indexOf(".",e);if(0>e)break;if(0==e||"\\"!=a[e-1])f=a.substring(f,e).replace(/\\\./g,"."),d[f]={},d=d[f],f=e+1;e+=1}d[a.substring(f).replace(/\\\./g,".")]=b;return c};shaka.util.ConfigUtils.referenceParametersAndReturn=function(a,b){return a&&b};goog.exportSymbol("shaka.util.ConfigUtils",shaka.util.ConfigUtils);goog.exportProperty(shaka.util.ConfigUtils,"convertToConfigObject",shaka.util.ConfigUtils.convertToConfigObject);
goog.exportProperty(shaka.util.ConfigUtils,"mergeConfigObjects",shaka.util.ConfigUtils.mergeConfigObjects);shaka.util.FairPlayUtils=function(){};shaka.util.FairPlayUtils.isFairPlaySupported=function(){var a;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){if(1==b.nextAddress)return a={initDataTypes:["cenc","sinf","skd"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}]},b.setCatchFinallyBlocks(2),b.yield(navigator.requestMediaKeySystemAccess("com.apple.fps",[a]),4);if(2!=b.nextAddress)return b.return(!0);b.enterCatchBlock();return b.return(!1)})};
shaka.util.FairPlayUtils.defaultGetContentId=function(a){a=shaka.util.StringUtils.fromBytesAutoDetect(a);return(new goog.Uri(a)).getDomain()};
shaka.util.FairPlayUtils.initDataTransform=function(a,b,c){if(!c||!c.byteLength)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.DRM,shaka.util.Error.Code.SERVER_CERTIFICATE_REQUIRED);b="string"==typeof b?shaka.util.StringUtils.toUTF16(b,!0):b;a=shaka.util.StringUtils.fromBytesAutoDetect(a);a=shaka.util.StringUtils.toUTF16(a,!0);var d=new Uint8Array(12+a.byteLength+b.byteLength+c.byteLength),e=0,f=function(g){shaka.util.BufferUtils.toDataView(d).setUint32(e,
g.byteLength,!0);e+=4;d.set(shaka.util.BufferUtils.toUint8(g),e);e+=g.byteLength};f(a);f(b);f(c);goog.asserts.assert(e==d.length,"Inconsistent init data length");return d};shaka.util.FairPlayUtils.verimatrixInitDataTransform=function(a,b,c){if("skd"!==b)return a;b=shaka.util.FairPlayUtils;c=c.serverCertificate;var d=shaka.util.StringUtils.fromBytesAutoDetect(a).split("skd://").pop();return b.initDataTransform(a,d,c)};
shaka.util.FairPlayUtils.ezdrmInitDataTransform=function(a,b,c){if("skd"!==b)return a;b=shaka.util.FairPlayUtils;c=c.serverCertificate;var d=shaka.util.StringUtils.fromBytesAutoDetect(a).split(";").pop();return b.initDataTransform(a,d,c)};
shaka.util.FairPlayUtils.conaxInitDataTransform=function(a,b,c){if("skd"!==b)return a;b=shaka.util.FairPlayUtils;c=c.serverCertificate;var d=shaka.util.StringUtils.fromBytesAutoDetect(a).split("skd://").pop().split("?").shift();d=window.atob(d);var e=new ArrayBuffer(2*d.length);e=new Uint16Array(e);for(var f=0,g=d.length;f<g;f++)e[f]=d.charCodeAt(f);return b.initDataTransform(a,e,c)};
shaka.util.FairPlayUtils.verimatrixFairPlayRequest=function(a,b){a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(a=shaka.util.BufferUtils.toUint8(b.body),a=shaka.util.Uint8ArrayUtils.toBase64(a),b.headers["Content-Type"]="application/x-www-form-urlencoded",b.body=shaka.util.StringUtils.toUTF8("spc="+a))};shaka.util.FairPlayUtils.ezdrmFairPlayRequest=function(a,b){a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(b.headers["Content-Type"]="application/octet-stream")};
shaka.util.FairPlayUtils.conaxFairPlayRequest=function(a,b){a===shaka.net.NetworkingEngine.RequestType.LICENSE&&(b.headers["Content-Type"]="application/octet-stream")};
shaka.util.FairPlayUtils.commonFairPlayResponse=function(a,b){if(a===shaka.net.NetworkingEngine.RequestType.LICENSE){try{var c=shaka.util.StringUtils.fromUTF8(b.data)}catch(e){return}a=!1;c=c.trim();"<ckc>"===c.substr(0,5)&&"</ckc>"===c.substr(-6)&&(c=c.slice(5,-6),a=!0);try{var d=JSON.parse(c);d.ckc&&(c=d.ckc,a=!0);d.CkcMessage&&(c=d.CkcMessage,a=!0);d.License&&(c=d.License,a=!0)}catch(e){}a&&(b.data=shaka.util.BufferUtils.toArrayBuffer(shaka.util.Uint8ArrayUtils.fromBase64(c)))}};
goog.exportSymbol("shaka.util.FairPlayUtils",shaka.util.FairPlayUtils);goog.exportProperty(shaka.util.FairPlayUtils,"commonFairPlayResponse",shaka.util.FairPlayUtils.commonFairPlayResponse);goog.exportProperty(shaka.util.FairPlayUtils,"conaxFairPlayRequest",shaka.util.FairPlayUtils.conaxFairPlayRequest);goog.exportProperty(shaka.util.FairPlayUtils,"ezdrmFairPlayRequest",shaka.util.FairPlayUtils.ezdrmFairPlayRequest);goog.exportProperty(shaka.util.FairPlayUtils,"verimatrixFairPlayRequest",shaka.util.FairPlayUtils.verimatrixFairPlayRequest);
goog.exportProperty(shaka.util.FairPlayUtils,"conaxInitDataTransform",shaka.util.FairPlayUtils.conaxInitDataTransform);goog.exportProperty(shaka.util.FairPlayUtils,"ezdrmInitDataTransform",shaka.util.FairPlayUtils.ezdrmInitDataTransform);goog.exportProperty(shaka.util.FairPlayUtils,"verimatrixInitDataTransform",shaka.util.FairPlayUtils.verimatrixInitDataTransform);goog.exportProperty(shaka.util.FairPlayUtils,"initDataTransform",shaka.util.FairPlayUtils.initDataTransform);
goog.exportProperty(shaka.util.FairPlayUtils,"defaultGetContentId",shaka.util.FairPlayUtils.defaultGetContentId);goog.exportProperty(shaka.util.FairPlayUtils,"isFairPlaySupported",shaka.util.FairPlayUtils.isFairPlaySupported);shaka.util.PlayerConfiguration=function(){};
shaka.util.PlayerConfiguration.createDefault=function(){var a=Infinity;navigator.connection&&navigator.connection.saveData&&(a=360);var b={retryParameters:shaka.net.NetworkingEngine.defaultRetryParameters(),servers:{},clearKeys:{},advanced:{},delayLicenseRequestUntilPlayed:!1,initDataTransform:function(g,h,k){"com.apple.fps.1_0"==k.keySystem&&"skd"==h&&(h=k.serverCertificate,k=shaka.util.FairPlayUtils.defaultGetContentId(g),g=shaka.util.FairPlayUtils.initDataTransform(g,k,h));return g},logLicenseExchange:!1,
updateExpirationTime:1,preferredKeySystems:[],keySystemsMapping:{},parseInbandPsshEnabled:shaka.util.Platform.isXboxOne()},c={retryParameters:shaka.net.NetworkingEngine.defaultRetryParameters(),availabilityWindowOverride:NaN,disableAudio:!1,disableVideo:!1,disableText:!1,disableThumbnails:!1,defaultPresentationDelay:0,segmentRelativeVttTiming:!1,dash:{clockSyncUri:"",ignoreDrmInfo:!1,disableXlinkProcessing:!1,xlinkFailGracefully:!1,ignoreMinBufferTime:!1,autoCorrectDrift:!0,initialSegmentLimit:1E3,
ignoreSuggestedPresentationDelay:!1,ignoreEmptyAdaptationSet:!1,ignoreMaxSegmentDuration:!1,keySystemsByURI:{"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb":"com.adobe.primetime"},
manifestPreprocessor:function(g){return shaka.util.ConfigUtils.referenceParametersAndReturn([g],g)},sequenceMode:!1},hls:{ignoreTextStreamFailures:!1,ignoreImageStreamFailures:!1,defaultAudioCodec:"mp4a.40.2",defaultVideoCodec:"avc1.42E01E",ignoreManifestProgramDateTime:!1,mediaPlaylistFullMimeType:'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',useSafariBehaviorForLive:!0,liveSegmentsDelay:3}},d={retryParameters:shaka.net.NetworkingEngine.defaultRetryParameters(),failureCallback:function(g){shaka.log.error("Unhandled streaming error",
g);return shaka.util.ConfigUtils.referenceParametersAndReturn([g],void 0)},rebufferingGoal:2,bufferingGoal:10,bufferBehind:30,ignoreTextStreamFailures:!1,alwaysStreamText:!1,startAtSegmentBoundary:!1,gapDetectionThreshold:.5,durationBackoff:1,forceTransmux:!1,safeSeekOffset:5,stallEnabled:!0,stallThreshold:1,stallSkip:.1,useNativeHlsOnSafari:!0,inaccurateManifestTolerance:2,lowLatencyMode:!1,autoLowLatencyMode:!1,forceHTTPS:!1,preferNativeHls:!1,updateIntervalSeconds:1,dispatchAllEmsgBoxes:!1,observeQualityChanges:!1,
maxDisabledTime:30,parsePrftBox:!1};if(shaka.util.Platform.isWebOS()||shaka.util.Platform.isTizen()||shaka.util.Platform.isChromecast())d.stallSkip=0;var e={trackSelectionCallback:function(g){return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){return h.return(g)})},downloadSizeCallback:function(g){var h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress)return navigator.storage&&navigator.storage.estimate?k.yield(navigator.storage.estimate(),3):k.return(!0);
h=k.yieldResult;return k.return(h.usage+g<.95*h.quota)})},progressCallback:function(g,h){return shaka.util.ConfigUtils.referenceParametersAndReturn([g,h],void 0)},usePersistentLicense:!0,numberOfParallelDownloads:5},f={drm:b,manifest:c,streaming:d,mediaSource:{sourceBufferExtraFeatures:""},offline:e,abrFactory:function(){return new shaka.abr.SimpleAbrManager},abr:{enabled:!0,useNetworkInformation:!0,defaultBandwidthEstimate:1E6,switchInterval:8,bandwidthUpgradeTarget:.85,bandwidthDowngradeTarget:.95,
restrictions:{minWidth:0,maxWidth:Infinity,minHeight:0,maxHeight:a,minPixels:0,maxPixels:Infinity,minFrameRate:0,maxFrameRate:Infinity,minBandwidth:0,maxBandwidth:Infinity},advanced:{minTotalBytes:128E3,minBytes:16E3,fastHalfLife:2,slowHalfLife:5},restrictToElementSize:!1,restrictToScreenSize:!1,ignoreDevicePixelRatio:!1},autoShowText:shaka.config.AutoShowText.IF_SUBTITLES_MAY_BE_NEEDED,preferredAudioLanguage:"",preferredTextLanguage:"",preferredVariantRole:"",preferredTextRole:"",preferredAudioChannelCount:2,
preferredVideoCodecs:[],preferredAudioCodecs:[],preferForcedSubs:!1,preferredDecodingAttributes:[],restrictions:{minWidth:0,maxWidth:Infinity,minHeight:0,maxHeight:Infinity,minPixels:0,maxPixels:Infinity,minFrameRate:0,maxFrameRate:Infinity,minBandwidth:0,maxBandwidth:Infinity},playRangeStart:0,playRangeEnd:Infinity,textDisplayFactory:function(){return null},cmcd:{enabled:!1,sessionId:"",contentId:"",useHeaders:!1},lcevc:{enabled:!1,dynamicPerformanceScaling:!0,logLevel:0,drawLogo:!1}};e.trackSelectionCallback=
function(g){return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){return h.return(shaka.util.PlayerConfiguration.defaultTrackSelect(g,f.preferredAudioLanguage))})};return f};
shaka.util.PlayerConfiguration.mergeConfigObjects=function(a,b,c){var d={".drm.keySystemsMapping":"",".drm.servers":"",".drm.clearKeys":"",".drm.advanced":{distinctiveIdentifierRequired:!1,persistentStateRequired:!1,videoRobustness:"",audioRobustness:"",sessionType:"",serverCertificate:new Uint8Array(0),serverCertificateUri:"",individualizationServer:""}};return shaka.util.ConfigUtils.mergeConfigObjects(a,b,c||shaka.util.PlayerConfiguration.createDefault(),d,"")};
shaka.util.PlayerConfiguration.defaultTrackSelect=function(a,b){var c=shaka.util.ManifestParserUtils.ContentType,d=shaka.util.LanguageUtils,e=a.filter(function(k){return"variant"==k.type}),f=[],g=d.findClosestLocale(b,e.map(function(k){return k.language}));g&&(f=e.filter(function(k){return d.normalize(k.language)==g}));0==f.length&&(f=e.filter(function(k){return k.primary}));0==f.length&&(1<(new Set(e.map(function(k){return k.language}))).size&&shaka.log.warning("Could not choose a good audio track based on language preferences or primary tracks.  An arbitrary language will be stored!"),
f=e);var h=f.filter(function(k){return k.height&&480>=k.height});h.length&&(h.sort(function(k,l){goog.asserts.assert(null!=k.height,"Null height");goog.asserts.assert(null!=l.height,"Null height");return l.height-k.height}),f=h.filter(function(k){return k.height==h[0].height}));b=[];f.length&&(e=Math.floor(f.length/2),f.sort(function(k,l){return k.bandwidth-l.bandwidth}),b.push(f[e]));a=$jscomp.makeIterator(a);for(f=a.next();!f.done;f=a.next())f=f.value,f.type!=c.TEXT&&f.type!=c.IMAGE||b.push(f);
return b};goog.exportSymbol("shaka.util.PlayerConfiguration",shaka.util.PlayerConfiguration);goog.exportProperty(shaka.util.PlayerConfiguration,"mergeConfigObjects",shaka.util.PlayerConfiguration.mergeConfigObjects);goog.exportProperty(shaka.util.PlayerConfiguration,"createDefault",shaka.util.PlayerConfiguration.createDefault);shaka.util.StateHistory=function(){this.open_=null;this.closed_=[]};shaka.util.StateHistory.prototype.update=function(a){null==this.open_?this.start_(a):this.update_(a)};shaka.util.StateHistory.prototype.getTimeSpentIn=function(a){var b=0;this.open_&&this.open_.state==a&&(b+=this.open_.duration);for(var c=$jscomp.makeIterator(this.closed_),d=c.next();!d.done;d=c.next())d=d.value,b+=d.state==a?d.duration:0;return b};
shaka.util.StateHistory.prototype.getCopy=function(){for(var a=function(e){return{timestamp:e.timestamp,state:e.state,duration:e.duration}},b=[],c=$jscomp.makeIterator(this.closed_),d=c.next();!d.done;d=c.next())b.push(a(d.value));this.open_&&b.push(a(this.open_));return b};
shaka.util.StateHistory.prototype.start_=function(a){goog.asserts.assert(null==this.open_,"There must be no open entry in order when we start");shaka.log.v1("Changing Player state to",a);this.open_={timestamp:this.getNowInSeconds_(),state:a,duration:0}};
shaka.util.StateHistory.prototype.update_=function(a){goog.asserts.assert(this.open_,"There must be an open entry in order to update it");var b=this.getNowInSeconds_();this.open_.duration=b-this.open_.timestamp;this.open_.state!=a&&(shaka.log.v1("Changing Player state to",a),this.closed_.push(this.open_),this.open_={timestamp:b,state:a,duration:0})};shaka.util.StateHistory.prototype.getNowInSeconds_=function(){return Date.now()/1E3};shaka.util.SwitchHistory=function(){this.currentText_=this.currentVariant_=null;this.history_=[]};shaka.util.SwitchHistory.prototype.updateCurrentVariant=function(a,b){this.currentVariant_!=a&&(this.currentVariant_=a,this.history_.push({timestamp:this.getNowInSeconds_(),id:a.id,type:"variant",fromAdaptation:b,bandwidth:a.bandwidth}))};
shaka.util.SwitchHistory.prototype.updateCurrentText=function(a,b){this.currentText_!=a&&(this.currentText_=a,this.history_.push({timestamp:this.getNowInSeconds_(),id:a.id,type:"text",fromAdaptation:b,bandwidth:null}))};shaka.util.SwitchHistory.prototype.getCopy=function(){for(var a=[],b=$jscomp.makeIterator(this.history_),c=b.next();!c.done;c=b.next())a.push(this.clone_(c.value));return a};shaka.util.SwitchHistory.prototype.getNowInSeconds_=function(){return Date.now()/1E3};
shaka.util.SwitchHistory.prototype.clone_=function(a){return{timestamp:a.timestamp,id:a.id,type:a.type,fromAdaptation:a.fromAdaptation,bandwidth:a.bandwidth}};shaka.util.Stats=function(){this.bandwidthEstimate_=this.currentStreamBandwidth_=this.maxSegmentDurationSeconds_=this.liveLatencySeconds_=this.licenseTimeSeconds_=this.drmTimeSeconds_=this.manifestTimeSeconds_=this.loadLatencySeconds_=this.completionPercent_=this.totalGapsJumped_=this.totalStallsDetected_=this.totalCorruptedFrames_=this.totalDecodedFrames_=this.totalDroppedFrames_=this.height_=this.width_=NaN;this.stateHistory_=new shaka.util.StateHistory;this.switchHistory_=new shaka.util.SwitchHistory};
shaka.util.Stats.prototype.setDroppedFrames=function(a,b){this.totalDroppedFrames_=a;this.totalDecodedFrames_=b};shaka.util.Stats.prototype.setCorruptedFrames=function(a){this.totalCorruptedFrames_=a};shaka.util.Stats.prototype.setStallsDetected=function(a){this.totalStallsDetected_=a};shaka.util.Stats.prototype.setGapsJumped=function(a){this.totalGapsJumped_=a};shaka.util.Stats.prototype.setResolution=function(a,b){this.width_=a;this.height_=b};
shaka.util.Stats.prototype.setLoadLatency=function(a){this.loadLatencySeconds_=a};shaka.util.Stats.prototype.setManifestTime=function(a){this.manifestTimeSeconds_=a};shaka.util.Stats.prototype.setCompletionPercent=function(a){isNaN(this.completionPercent_)?this.completionPercent_=a:this.completionPercent_=Math.max(this.completionPercent_,a)};shaka.util.Stats.prototype.setDrmTime=function(a){this.drmTimeSeconds_=a};shaka.util.Stats.prototype.setLicenseTime=function(a){this.licenseTimeSeconds_=a};
shaka.util.Stats.prototype.setLiveLatency=function(a){this.liveLatencySeconds_=a};shaka.util.Stats.prototype.setMaxSegmentDuration=function(a){this.maxSegmentDurationSeconds_=a};shaka.util.Stats.prototype.setCurrentStreamBandwidth=function(a){this.currentStreamBandwidth_=a};shaka.util.Stats.prototype.setBandwidthEstimate=function(a){this.bandwidthEstimate_=a};shaka.util.Stats.prototype.getStateHistory=function(){return this.stateHistory_};shaka.util.Stats.prototype.getSwitchHistory=function(){return this.switchHistory_};
shaka.util.Stats.prototype.getBlob=function(){return{width:this.width_,height:this.height_,streamBandwidth:this.currentStreamBandwidth_,decodedFrames:this.totalDecodedFrames_,droppedFrames:this.totalDroppedFrames_,corruptedFrames:this.totalCorruptedFrames_,stallsDetected:this.totalStallsDetected_,gapsJumped:this.totalGapsJumped_,estimatedBandwidth:this.bandwidthEstimate_,completionPercent:this.completionPercent_,loadLatency:this.loadLatencySeconds_,manifestTimeSeconds:this.manifestTimeSeconds_,drmTimeSeconds:this.drmTimeSeconds_,
playTime:this.stateHistory_.getTimeSpentIn("playing"),pauseTime:this.stateHistory_.getTimeSpentIn("paused"),bufferingTime:this.stateHistory_.getTimeSpentIn("buffering"),licenseTime:this.licenseTimeSeconds_,liveLatency:this.liveLatencySeconds_,maxSegmentDuration:this.maxSegmentDurationSeconds_,stateHistory:this.stateHistory_.getCopy(),switchHistory:this.switchHistory_.getCopy()}};
shaka.util.Stats.getEmptyBlob=function(){return{width:NaN,height:NaN,streamBandwidth:NaN,decodedFrames:NaN,droppedFrames:NaN,corruptedFrames:NaN,stallsDetected:NaN,gapsJumped:NaN,estimatedBandwidth:NaN,completionPercent:NaN,loadLatency:NaN,manifestTimeSeconds:NaN,drmTimeSeconds:NaN,playTime:NaN,pauseTime:NaN,bufferingTime:NaN,licenseTime:NaN,liveLatency:NaN,maxSegmentDuration:NaN,switchHistory:[],stateHistory:[]}};shaka.Player=function(a,b){shaka.util.FakeEventTarget.call(this);var c=this;this.loadMode_=shaka.Player.LoadMode.NOT_LOADED;this.videoContainer_=this.video_=null;this.isTextVisible_=!1;this.globalEventManager_=new shaka.util.EventManager;this.attachEventManager_=new shaka.util.EventManager;this.loadEventManager_=new shaka.util.EventManager;this.assetUri_=this.manifest_=this.parserFactory_=this.parser_=this.streamingEngine_=this.qualityObserver_=this.lcevcDil_=this.lcevcCanvas_=this.cmcdManager_=this.regionTimeline_=
this.bufferObserver_=this.bufferPoller_=this.playRateController_=this.playheadObservers_=this.playhead_=this.mediaSourceEngine_=this.drmEngine_=this.networkingEngine_=null;this.fullyLoaded_=!1;this.abrManagerFactory_=this.abrManager_=null;this.nextExternalStreamId_=1E9;this.config_=this.defaultConfig_();this.maxHwRes_={width:Infinity,height:Infinity};this.stats_=null;this.currentAdaptationSetCriteria_=new shaka.media.PreferenceBasedCriteria(this.config_.preferredAudioLanguage,this.config_.preferredVariantRole,
this.config_.preferredAudioChannelCount);this.currentTextLanguage_=this.config_.preferredTextLanguage;this.currentTextRole_=this.config_.preferredTextRole;this.currentTextForced_=this.config_.preferForcedSubs;this.cleanupOnUnload_=[];this.updatedStartTime_=null;b&&b(this);this.networkingEngine_=this.createNetworkingEngine();this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS);this.adManager_=null;shaka.Player.adManagerFactory_&&(this.adManager_=shaka.Player.adManagerFactory_());
this.globalEventManager_.listen(window,"online",function(){c.retryStreaming()});this.detachNode_={name:"detach"};this.attachNode_={name:"attach"};this.unloadNode_={name:"unload"};this.parserNode_={name:"manifest-parser"};this.manifestNode_={name:"manifest"};this.mediaSourceNode_={name:"media-source"};this.drmNode_={name:"drm-engine"};this.loadNode_={name:"load"};this.srcEqualsDrmNode_={name:"src-equals-drm-engine"};this.srcEqualsNode_={name:"src-equals"};var d=shaka.util.AbortableOperation,e=new Map;
e.set(this.attachNode_,function(f,g){return d.notAbortable(c.onAttach_(f,g))});e.set(this.detachNode_,function(f,g){return d.notAbortable(c.onDetach_(f,g))});e.set(this.unloadNode_,function(f,g){return d.notAbortable(c.onUnload_(f,g))});e.set(this.mediaSourceNode_,function(f,g){f=c.onInitializeMediaSourceEngine_(f,g);return d.notAbortable(f)});e.set(this.parserNode_,function(f,g){f=c.onInitializeParser_(f,g);return d.notAbortable(f)});e.set(this.manifestNode_,function(f,g){return c.onParseManifest_(f,
g)});e.set(this.drmNode_,function(f,g){f=c.onInitializeDrm_(f,g);return d.notAbortable(f)});e.set(this.loadNode_,function(f,g){return d.notAbortable(c.onLoad_(f,g))});e.set(this.srcEqualsDrmNode_,function(f,g){f=c.onInitializeSrcEqualsDrm_(f,g);return d.notAbortable(f)});e.set(this.srcEqualsNode_,function(f,g){return c.onSrcEquals_(f,g)});this.walker_=new shaka.routing.Walker(this.detachNode_,shaka.Player.createEmptyPayload_(),{getNext:function(f,g,h,k){return c.getNextStep_(f,g,h,k)},enterNode:function(f,
g,h){c.dispatchEvent(c.makeEvent_(shaka.util.FakeEvent.EventName.OnStateChange,(new Map).set("state",f.name)));return e.get(f)(g,h)},handleError:function(f,g){return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){return 1==h.nextAddress?(shaka.log.warning("The walker saw an error:"),g instanceof shaka.util.Error?shaka.log.warning("Error Code:",g.code):(shaka.log.warning("Error Message:",g.message),shaka.log.warning("Error Stack:",g.stack)),h.yield(c.onUnload_(f,shaka.Player.createEmptyPayload_()),
2)):h.return(f.mediaElement?c.attachNode_:c.detachNode_)})},onIdle:function(f){c.dispatchEvent(c.makeEvent_(shaka.util.FakeEvent.EventName.OnStateIdle,(new Map).set("state",f.name)))}});this.checkVariantsTimer_=new shaka.util.Timer(function(){return c.checkVariants_()});a&&this.attach(a,!0)};$jscomp.inherits(shaka.Player,shaka.util.FakeEventTarget);
shaka.Player.prototype.createLcevcDil_=function(a){null==this.lcevcDil_&&(this.lcevcDil_=new shaka.lcevc.Dil(this.video_,this.lcevcCanvas_,a),this.mediaSourceEngine_&&this.mediaSourceEngine_.updateLcevcDil(this.lcevcDil_))};shaka.Player.prototype.closeLcevcDil_=function(){null!=this.lcevcDil_&&(this.lcevcDil_.release(),this.lcevcDil_=null)};
shaka.Player.prototype.setupLcevc_=function(a){if(a.lcevc.enabled){var b=this.getVariantTracks();b&&b[0]&&b[0].videoMimeType==shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_.ts&&(shaka.util.Platform.isEdge()||shaka.util.Platform.isLegacyEdge())&&(a.streaming.forceTransmux||shaka.log.alwaysWarn("LCEVC Warning: For MPEG-2 TS decoding the config.streaming.forceTransmux must be enabled."));this.closeLcevcDil_();this.createLcevcDil_(a.lcevc)}else this.closeLcevcDil_()};
shaka.Player.prototype.makeEvent_=function(a,b){return new shaka.util.FakeEvent(a,b)};
shaka.Player.prototype.destroy=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){switch(c.nextAddress){case 1:if(a.loadMode_==shaka.Player.LoadMode.DESTROYED)return c.return();a.closeLcevcDil_();a.loadMode_=shaka.Player.LoadMode.DESTROYED;b=a.walker_.startNewRoute(function(d){return{node:a.detachNode_,payload:shaka.Player.createEmptyPayload_(),interruptible:!1}});return c.yield(new Promise(function(d){b.onStart=function(){shaka.log.info("Preparing to destroy walker...")};
b.onEnd=function(){d()};b.onCancel=function(){goog.asserts.assert(!1,"Our final detach call should never be cancelled.");d()};b.onError=function(){goog.asserts.assert(!1,"Our final detach call should never see an error");d()};b.onSkip=function(){goog.asserts.assert(!1,"Our final detach call should never be skipped");d()}}),2);case 2:return c.yield(a.walker_.destroy(),3);case 3:a.globalEventManager_&&(a.globalEventManager_.release(),a.globalEventManager_=null);a.attachEventManager_&&(a.attachEventManager_.release(),
a.attachEventManager_=null);a.loadEventManager_&&(a.loadEventManager_.release(),a.loadEventManager_=null);a.abrManagerFactory_=null;a.abrManager_=null;a.config_=null;a.stats_=null;a.videoContainer_=null;a.cmcdManager_=null;if(!a.networkingEngine_){c.jumpTo(4);break}return c.yield(a.networkingEngine_.destroy(),5);case 5:a.networkingEngine_=null;case 4:shaka.util.FakeEventTarget.prototype.release.call(a),c.jumpToEnd()}})};
shaka.Player.registerSupportPlugin=function(a,b){shaka.Player.supportPlugins_[a]=b};shaka.Player.setAdManagerFactory=function(a){shaka.Player.adManagerFactory_=a};
shaka.Player.isBrowserSupported=function(){window.Promise||shaka.log.alwaysWarn("A Promise implementation or polyfill is required");if(!(window.Promise&&window.Uint8Array&&Array.prototype.forEach)||shaka.util.Platform.isIE())return!1;var a=shaka.util.Platform.safariVersion();return a&&13>a||!shaka.media.DrmEngine.isBrowserSupported()?!1:shaka.util.Platform.supportsMediaSource()?!0:shaka.util.Platform.supportsMediaType("application/x-mpegurl")};
shaka.Player.probeSupport=function(a){a=void 0===a?!0:a;var b,c,d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return goog.asserts.assert(shaka.Player.isBrowserSupported(),"Must have basic support"),b={},a?h.yield(shaka.media.DrmEngine.probeSupport(),3):h.jumpTo(2);2!=h.nextAddress&&(b=h.yieldResult);c=shaka.media.ManifestParser.probeSupport();d=shaka.media.MediaSourceEngine.probeSupport();e={manifest:c,media:d,drm:b};f=shaka.Player.supportPlugins_;for(g in f)e[g]=
f[g]();return h.return(e)})};shaka.Player.prototype.attach=function(a,b){b=void 0===b?!0:b;if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)return Promise.reject(this.createAbortLoadError_());var c=shaka.Player.createEmptyPayload_();c.mediaElement=a;shaka.util.Platform.supportsMediaSource()||(b=!1);var d=b?this.mediaSourceNode_:this.attachNode_;a=this.walker_.startNewRoute(function(e){return{node:d,payload:c,interruptible:!1}});a.onStart=function(){return shaka.log.info("Starting attach...")};return this.wrapWalkerListenersWithPromise_(a)};
shaka.Player.prototype.attachCanvas=function(a){this.lcevcCanvas_=a};shaka.Player.prototype.detach=function(){var a=this;if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)return Promise.reject(this.createAbortLoadError_());var b=this.walker_.startNewRoute(function(c){return{node:a.detachNode_,payload:shaka.Player.createEmptyPayload_(),interruptible:!1}});b.onStart=function(){return shaka.log.info("Starting detach...")};return this.wrapWalkerListenersWithPromise_(b)};
shaka.Player.prototype.unload=function(a){var b=this;a=void 0===a?!0:a;if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)return Promise.reject(this.createAbortLoadError_());this.fullyLoaded_=!1;shaka.util.Platform.supportsMediaSource()||(a=!1);this.closeLcevcDil_();var c=shaka.Player.createEmptyPayload_(),d=this.walker_.startNewRoute(function(e){var f=e.mediaElement&&a?b.mediaSourceNode_:e.mediaElement?b.attachNode_:b.detachNode_;goog.asserts.assert(f,"We should have picked a destination.");c.mediaElement=
e.mediaElement;return{node:f,payload:c,interruptible:!1}});d.onStart=function(){return shaka.log.info("Starting unload...")};return this.wrapWalkerListenersWithPromise_(d)};shaka.Player.prototype.updateStartTime=function(a){this.updatedStartTime_=a};
shaka.Player.prototype.load=function(a,b,c){var d=this;this.updatedStartTime_=null;this.fullyLoaded_=!1;if(this.loadMode_==shaka.Player.LoadMode.DESTROYED)return Promise.reject(this.createAbortLoadError_());this.dispatchEvent(this.makeEvent_(shaka.util.FakeEvent.EventName.Loading));var e=shaka.Player.createEmptyPayload_();e.uri=a;e.startTimeOfLoad=Date.now()/1E3;c&&(e.mimeType=c);void 0!==b&&(e.startTime=b);var f=this.shouldUseSrcEquals_(e)?this.srcEqualsNode_:this.loadNode_,g=this.walker_.startNewRoute(function(h){if(null==
h.mediaElement)return null;e.mediaElement=h.mediaElement;return{node:f,payload:e,interruptible:!0}});this.stats_=new shaka.util.Stats;this.cmcdManager_=this.createCmcd_();g.onStart=function(){return shaka.log.info("Starting load of "+a+"...")};return new Promise(function(h,k){g.onSkip=function(){return k(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.NO_VIDEO_ELEMENT))};g.onEnd=function(){h();d.dispatchEvent(d.makeEvent_(shaka.util.FakeEvent.EventName.Loaded))};
g.onCancel=function(){return k(d.createAbortLoadError_())};g.onError=function(l){return k(l)}})};
shaka.Player.prototype.shouldUseSrcEquals_=function(a){var b=shaka.util.Platform;if(!b.supportsMediaSource())return!0;var c=a.mimeType,d=a.uri||"";c||(c=shaka.media.ManifestParser.getExtension(d),c=shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_[c]);if(c){a=""!=(a.mediaElement||b.anyMediaElement()).canPlayType(c);if(!a)return!1;d=shaka.media.ManifestParser.isSupported(d,c);if(!d)return!0;goog.asserts.assert(a&&d,"Both native and MSE playback should be possible!");if(this.config_.streaming.preferNativeHls)return!0;
if(b.isApple())return this.config_.streaming.useNativeHlsOnSafari}return!1};shaka.Player.prototype.onAttach_=function(a,b){var c=this;goog.asserts.assert(null==a.mediaElement||a.mediaElement==b.mediaElement,"The routing logic failed. MediaElement requirement failed.");null==a.mediaElement&&(a.mediaElement=b.mediaElement,this.attachEventManager_.listen(a.mediaElement,"error",function(d){return c.onVideoError_(d)}));this.video_=a.mediaElement;return Promise.resolve()};
shaka.Player.prototype.onDetach_=function(a,b){a.mediaElement&&(this.attachEventManager_.removeAll(),a.mediaElement=null);this.adManager_&&this.adManager_.release();this.video_=null;return Promise.resolve()};
shaka.Player.prototype.onUnload_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n;return $jscomp.asyncExecutePromiseGeneratorProgram(function(p){switch(p.nextAddress){case 1:return c.loadMode_!=shaka.Player.LoadMode.DESTROYED&&(c.loadMode_=shaka.Player.LoadMode.NOT_LOADED),d=c.cleanupOnUnload_.map(function(q){return q()}),c.cleanupOnUnload_=[],p.yield(Promise.all(d),2);case 2:c.dispatchEvent(c.makeEvent_(shaka.util.FakeEvent.EventName.Unloading));a.mimeType=null;a.startTime=null;a.uri=null;c.regionTimeline_&&
(c.regionTimeline_.release(),c.regionTimeline_=null);a.mediaElement&&c.loadEventManager_.removeAll();c.checkVariantsTimer_.stop();c.playheadObservers_&&(c.playheadObservers_.release(),c.playheadObservers_=null);c.bufferPoller_&&(c.bufferPoller_.stop(),c.bufferPoller_=null);if(!c.parser_){p.jumpTo(3);break}return p.yield(c.parser_.stop(),4);case 4:c.parser_=null,c.parserFactory_=null;case 3:if(!c.abrManager_){p.jumpTo(5);break}return p.yield(c.abrManager_.stop(),5);case 5:if(!c.streamingEngine_){p.jumpTo(7);
break}return p.yield(c.streamingEngine_.destroy(),8);case 8:c.streamingEngine_=null;case 7:c.playRateController_&&(c.playRateController_.release(),c.playRateController_=null);c.playhead_&&(c.playhead_.release(),c.playhead_=null);if(!c.mediaSourceEngine_){p.jumpTo(9);break}return p.yield(c.mediaSourceEngine_.destroy(),10);case 10:c.mediaSourceEngine_=null;case 9:if(c.adManager_)c.adManager_.onAssetUnload();if(!a.mediaElement||!a.mediaElement.src){p.jumpTo(11);break}return p.yield(new Promise(function(q){return(new shaka.util.Timer(q)).tickAfter(.1)}),
12);case 12:for(a.mediaElement.removeAttribute("src"),a.mediaElement.load();a.mediaElement.lastChild;)a.mediaElement.removeChild(a.mediaElement.firstChild);case 11:if(!c.drmEngine_){p.jumpTo(13);break}return p.yield(c.drmEngine_.destroy(),14);case 14:c.drmEngine_=null;case 13:c.assetUri_=null;c.bufferObserver_=null;if(c.manifest_){e=$jscomp.makeIterator(c.manifest_.variants);for(f=e.next();!f.done;f=e.next())for(g=f.value,h=$jscomp.makeIterator([g.audio,g.video]),k=h.next();!k.done;k=h.next())(l=
k.value)&&l.segmentIndex&&l.segmentIndex.release();m=$jscomp.makeIterator(c.manifest_.textStreams);for(k=m.next();!k.done;k=m.next())n=k.value,n.segmentIndex&&n.segmentIndex.release()}c.manifest_=null;c.stats_=new shaka.util.Stats;c.lastTextFactory_=null;c.updateBufferState_();p.jumpToEnd()}})};
shaka.Player.prototype.onInitializeMediaSourceEngine_=function(a,b){var c=this,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress)return goog.asserts.assert(shaka.util.Platform.supportsMediaSource(),"We should not be initializing media source on a platform that does not support media source."),goog.asserts.assert(a.mediaElement,"We should have a media element when initializing media source."),goog.asserts.assert(a.mediaElement==b.mediaElement,"|has| and |wants| should have the same media element when initializing media source."),
goog.asserts.assert(null==c.mediaSourceEngine_,"We should not have a media source engine yet."),d=c.config_.textDisplayFactory,e=d(),c.lastTextFactory_=d,f=c.createMediaSourceEngine(a.mediaElement,e,function(l,m,n){c.processTimedMetadataMediaSrc_(l,m,n)},c.lcevcDil_),f.configure(c.config_.mediaSource),g=c.config_.manifest,h=g.segmentRelativeVttTiming,f.setSegmentRelativeVttTiming(h),k.yield(f.open(),2);c.mediaSourceEngine_=f;k.jumpToEnd()})};
shaka.Player.prototype.onInitializeParser_=function(a,b){var c=this,d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return goog.asserts.assert(a.mediaElement,"We should have a media element when initializing the parser."),goog.asserts.assert(a.mediaElement==b.mediaElement,"|has| and |wants| should have the same media element when initializing the parser."),goog.asserts.assert(c.networkingEngine_,"Need networking engine when initializing the parser."),goog.asserts.assert(c.config_,
"Need player config when initializing the parser."),a.mimeType=b.mimeType,a.uri=b.uri,goog.asserts.assert(a.uri,"We should have an asset uri when initializing the parsing."),d=a.uri,e=c.networkingEngine_,c.assetUri_=d,f=c,h.yield(shaka.media.ManifestParser.getFactory(d,e,c.config_.manifest.retryParameters,a.mimeType),2);f.parserFactory_=h.yieldResult;goog.asserts.assert(c.parserFactory_,"Must have manifest parser");c.parser_=c.parserFactory_();g=shaka.util.ObjectUtils.cloneObject(c.config_.manifest);
b.mediaElement&&"AUDIO"===b.mediaElement.nodeName&&(g.disableVideo=!0);c.parser_.configure(g);h.jumpToEnd()})};
shaka.Player.prototype.onParseManifest_=function(a,b){var c=this;goog.asserts.assert(a.mimeType==b.mimeType,"|has| and |wants| should have the same mime type when parsing.");goog.asserts.assert(a.uri==b.uri,"|has| and |wants| should have the same uri when parsing.");goog.asserts.assert(a.uri,"|has| should have a valid uri when parsing.");goog.asserts.assert(a.uri==this.assetUri_,"|has.uri| should match the cached asset uri.");goog.asserts.assert(this.networkingEngine_,"Need networking engine to parse manifest.");
goog.asserts.assert(this.cmcdManager_,"Need CMCD manager to populate manifest request data.");goog.asserts.assert(this.config_,"Need player config to parse manifest.");goog.asserts.assert(this.parser_,"|this.parser_| should have been set in an earlier step.");var d=a.uri;a=this.networkingEngine_;this.regionTimeline_=new shaka.media.RegionTimeline(function(){return c.seekRange()});this.regionTimeline_.addEventListener("regionadd",function(g){g=g.region;c.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionAdded,
g);if(c.adManager_)c.adManager_.onDashTimedMetadata(g)});this.qualityObserver_=null;this.config_.streaming.observeQualityChanges&&(this.qualityObserver_=new shaka.media.QualityObserver(function(){return c.getBufferedInfo()}),this.qualityObserver_.addEventListener("qualitychange",function(g){c.onMediaQualityChange_(g.quality,g.position)}));var e={networkingEngine:a,modifyManifestRequest:function(g,h){c.cmcdManager_.applyManifestData(g,h)},modifySegmentRequest:function(g,h){c.cmcdManager_.applySegmentData(g,
h)},filter:function(g){return c.filterManifest_(g)},makeTextStreamsForClosedCaptions:function(g){return c.makeTextStreamsForClosedCaptions_(g)},onTimelineRegionAdded:function(g){return c.regionTimeline_.addRegion(g)},onEvent:function(g){return c.dispatchEvent(g)},onError:function(g){return c.onError_(g)},isLowLatencyMode:function(){return c.isLowLatencyMode_()},isAutoLowLatencyMode:function(){return c.isAutoLowLatencyMode_()},enableLowLatencyMode:function(){c.configure("streaming.lowLatencyMode",
!0)},updateDuration:function(){c.streamingEngine_&&c.streamingEngine_.updateDuration()},newDrmInfo:function(g){var h=c.drmEngine_?c.drmEngine_.getDrmInfo():null;h&&c.drmEngine_.getMediaKeys()&&c.processDrmInfos_(h.keySystem,g)}},f=Date.now()/1E3;return new shaka.util.AbortableOperation(function(){var g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==m.nextAddress)return g=c,m.yield(c.parser_.start(d,e),2);g.manifest_=m.yieldResult;h=c.makeEvent_(shaka.util.FakeEvent.EventName.ManifestParsed);
c.dispatchEvent(h);if(0==c.manifest_.variants.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.NO_VARIANTS);shaka.Player.filterForAVVariants_(c.manifest_);k=Date.now()/1E3;l=k-f;c.stats_.setManifestTime(l);m.jumpToEnd()})}(),function(){shaka.log.info("Aborting parser step...");return c.parser_.stop()})};
shaka.Player.prototype.onInitializeDrm_=function(a,b){var c=this,d,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){return 1==f.nextAddress?(goog.asserts.assert(a.mimeType==b.mimeType,"The load graph should have ensured the mime types matched."),goog.asserts.assert(a.uri==b.uri,"The load graph should have ensured the uris matched"),goog.asserts.assert(c.networkingEngine_,"|onInitializeDrm_| should never be called after |destroy|"),goog.asserts.assert(c.config_,"|onInitializeDrm_| should never be called after |destroy|"),
goog.asserts.assert(c.manifest_,"|this.manifest_| should have been set in an earlier step."),goog.asserts.assert(a.mediaElement,"We should have a media element when initializing the DRM Engine."),d=Date.now()/1E3,e=!0,c.drmEngine_=c.createDrmEngine({netEngine:c.networkingEngine_,onError:function(g){c.onError_(g)},onKeyStatus:function(g){c.onKeyStatus_(g)},onExpirationUpdated:function(g,h){c.onExpirationUpdated_(g,h)},onEvent:function(g){c.dispatchEvent(g);g.type==shaka.util.FakeEvent.EventName.DrmSessionUpdate&&
e&&(e=!1,g=Date.now()/1E3-d,c.stats_.setDrmTime(g),c.lcevcDil_&&c.lcevcDil_.hideCanvas())}}),c.drmEngine_.configure(c.config_.drm),f.yield(c.drmEngine_.initForPlayback(c.manifest_.variants,c.manifest_.offlineSessionIds),2)):3!=f.nextAddress?f.yield(c.drmEngine_.attach(a.mediaElement),3):f.yield(c.filterManifest_(c.manifest_),0)})};
shaka.Player.prototype.onLoad_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y;return $jscomp.asyncExecutePromiseGeneratorProgram(function(A){switch(A.nextAddress){case 1:goog.asserts.assert(a.mimeType==b.mimeType,"|has| and |wants| should have the same mime type when loading.");goog.asserts.assert(a.uri==b.uri,"|has| and |wants| should have the same uri when loading.");goog.asserts.assert(a.mediaElement,"We should have a media element when loading.");goog.asserts.assert(!isNaN(b.startTimeOfLoad),
"|wants| should tell us when the load was originally requested");a.startTime=b.startTime;null!=c.updatedStartTime_&&(a.startTime=c.updatedStartTime_,c.updatedStartTime_=null);d=a.mediaElement;e=a.uri;c.assetUri_=e;c.playRateController_=new shaka.media.PlayRateController({getRate:function(){return d.playbackRate},getDefaultRate:function(){return d.defaultPlaybackRate},setRate:function(z){d.playbackRate=z},movePlayhead:function(z){d.currentTime+=z}});f=function(){return c.updateStateHistory_()};g=function(){return c.onRateChange_()};
c.loadEventManager_.listen(d,"playing",f);c.loadEventManager_.listen(d,"pause",f);c.loadEventManager_.listen(d,"ended",f);c.loadEventManager_.listen(d,"ratechange",g);c.setupLcevc_(c.config_);h=c.config_.abrFactory;c.abrManager_&&c.abrManagerFactory_==h||(c.abrManagerFactory_=h,c.abrManager_=h(),"function"!=typeof c.abrManager_.setMediaElement&&(shaka.Deprecate.deprecateFeature(5,"AbrManager","Please use an AbrManager with setMediaElement function."),c.abrManager_.setMediaElement=function(){}),c.abrManager_.configure(c.config_.abr));
c.currentAdaptationSetCriteria_=new shaka.media.PreferenceBasedCriteria(c.config_.preferredAudioLanguage,c.config_.preferredVariantRole,c.config_.preferredAudioChannelCount);c.currentTextLanguage_=c.config_.preferredTextLanguage;c.currentTextRole_=c.config_.preferredTextRole;c.currentTextForced_=c.config_.preferForcedSubs;shaka.Player.applyPlayRange_(c.manifest_.presentationTimeline,c.config_.playRangeStart,c.config_.playRangeEnd);c.abrManager_.init(function(z,B,D){return c.switch_(z,B,D)});c.abrManager_.setMediaElement(d);
shaka.util.StreamUtils.chooseCodecsAndFilterManifest(c.manifest_,c.config_.preferredVideoCodecs,c.config_.preferredAudioCodecs,c.config_.preferredAudioChannelCount,c.config_.preferredDecodingAttributes);c.streamingEngine_=c.createStreamingEngine();c.streamingEngine_.configure(c.config_.streaming);c.loadMode_=shaka.Player.LoadMode.MEDIA_SOURCE;d.textTracks&&c.loadEventManager_.listen(d.textTracks,"addtrack",function(z){if(z.track)switch(z=z.track,goog.asserts.assert(z instanceof TextTrack,"Wrong track type!"),
z.kind){case "chapters":c.activateChaptersTrack_(z)}});c.dispatchEvent(c.makeEvent_(shaka.util.FakeEvent.EventName.Streaming));k=null;l=c.streamingEngine_.getCurrentVariant();l||(k=c.chooseVariant_(),goog.asserts.assert(k,"Must choose an initial variant!"));m=[];n=l||k;p=$jscomp.makeIterator([n.video,n.audio]);for(q=p.next();!q.done;q=p.next())(r=q.value)&&!r.segmentIndex&&m.push(r.createSegmentIndex());if(!(0<m.length)){A.jumpTo(2);break}return A.yield(Promise.all(m),2);case 2:c.playhead_=c.createPlayhead(a.startTime);
c.playheadObservers_=c.createPlayheadObserversForMSE_();w=Math.max(c.manifest_.minBufferTime,c.config_.streaming.rebufferingGoal);c.startBufferManagement_(w);if(l){A.jumpTo(4);break}goog.asserts.assert(k,"Must have choosen an initial variant!");c.switchVariant_(k,!0,!1,0);if(!c.config_.streaming.startAtSegmentBoundary){A.jumpTo(5);break}u=c.playhead_.getTime();return A.yield(c.adjustStartTime_(k,u),6);case 6:v=A.yieldResult,c.playhead_.setStartTime(v);case 5:c.onAdaptation_(null,shaka.util.StreamUtils.variantToTrack(k));
case 4:return c.playhead_.ready(),x=c.getTextTracks().find(function(z){return z.active}),x||((t=c.chooseTextStream_())&&c.addTextStreamToSwitchHistory_(t,!0),k&&c.setInitialTextState_(k,t),t&&c.shouldStreamText_()&&c.streamingEngine_.switchTextStream(t)),A.yield(c.streamingEngine_.start(),7);case 7:c.config_.abr.enabled&&(c.abrManager_.enable(),c.onAbrStatusChanged_()),c.filterManifestByCurrentVariant_(),c.onTracksChanged_(),c.updateAbrManagerVariants_(),y=c.manifest_.variants.some(function(z){return z.primary}),
c.config_.preferredAudioLanguage||y||shaka.log.warning("No preferred audio language set.  We have chosen an arbitrary language initially"),c.fullyLoaded_=!0,c.loadEventManager_.listenOnce(d,"loadedmetadata",function(){var z=Date.now()/1E3-b.startTimeOfLoad;c.stats_.setLoadLatency(z)}),A.jumpToEnd()}})};
shaka.Player.prototype.onInitializeSrcEqualsDrm_=function(a,b){var c=this,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){return 1==m.nextAddress?(d=shaka.util.ManifestParserUtils.ContentType,goog.asserts.assert(c.networkingEngine_,"|onInitializeSrcEqualsDrm_| should never be called after |destroy|"),goog.asserts.assert(c.config_,"|onInitializeSrcEqualsDrm_| should never be called after |destroy|"),e=Date.now()/1E3,f=!0,c.drmEngine_=c.createDrmEngine({netEngine:c.networkingEngine_,
onError:function(n){c.onError_(n)},onKeyStatus:function(n){c.onKeyStatus_(n)},onExpirationUpdated:function(n,p){c.onExpirationUpdated_(n,p)},onEvent:function(n){c.dispatchEvent(n);n.type==shaka.util.FakeEvent.EventName.DrmSessionUpdate&&f&&(f=!1,n=Date.now()/1E3-e,c.stats_.setDrmTime(n))}}),c.drmEngine_.configure(c.config_.drm),g=b.uri||"",h=shaka.media.ManifestParser.getExtension(g),k=shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_[h],"application/x-mpegurl"==k&&shaka.util.Platform.isApple()&&(k=
"application/vnd.apple.mpegurl"),k||(k="video/mp4"),l={id:0,language:"und",disabledUntilTime:0,primary:!1,audio:null,video:{id:0,originalId:null,createSegmentIndex:function(){return Promise.resolve()},segmentIndex:null,mimeType:b.mimeType?shaka.util.MimeUtils.getBasicType(b.mimeType):k,codecs:b.mimeType?shaka.util.MimeUtils.getCodecs(b.mimeType):"",encrypted:!0,drmInfos:[],keyIds:new Set,language:"und",label:null,type:d.VIDEO,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:!1,
channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null},bandwidth:100,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]},c.drmEngine_.setSrcEquals(!0),m.yield(c.drmEngine_.initForPlayback([l],[]),2)):m.yield(c.drmEngine_.attach(a.mediaElement),0)})};
shaka.Player.prototype.onSrcEquals_=function(a,b){var c=this;goog.asserts.assert(a.mediaElement,"We should have a media element when loading.");goog.asserts.assert(b.uri,"|has| should have a valid uri when loading.");goog.asserts.assert(!isNaN(b.startTimeOfLoad),"|wants| should tell us when the load was originally requested");goog.asserts.assert(this.video_==a.mediaElement,"The video element should match our media element");a.uri=b.uri;a.startTime=b.startTime;this.assetUri_=a.uri;var d=a.mediaElement;
this.playhead_=new shaka.media.SrcEqualsPlayhead(d);var e=!1;this.cleanupOnUnload_.push(function(){e=!0});null!=a.startTime&&this.playhead_.setStartTime(a.startTime);this.playRateController_=new shaka.media.PlayRateController({getRate:function(){return d.playbackRate},getDefaultRate:function(){return d.defaultPlaybackRate},setRate:function(h){d.playbackRate=h},movePlayhead:function(h){d.currentTime+=h}});this.startBufferManagement_(this.config_.streaming.rebufferingGoal);var f=function(){return c.updateStateHistory_()};
this.loadEventManager_.listen(d,"playing",f);this.loadEventManager_.listen(d,"pause",f);this.loadEventManager_.listen(d,"ended",f);this.loadEventManager_.listen(d,"ratechange",function(){return c.onRateChange_()});"none"!=d.preload&&this.loadEventManager_.listenOnce(d,"loadedmetadata",function(){var h=Date.now()/1E3-b.startTimeOfLoad;c.stats_.setLoadLatency(h)});d.audioTracks&&(this.loadEventManager_.listen(d.audioTracks,"addtrack",function(){return c.onTracksChanged_()}),this.loadEventManager_.listen(d.audioTracks,
"removetrack",function(){return c.onTracksChanged_()}),this.loadEventManager_.listen(d.audioTracks,"change",function(){return c.onTracksChanged_()}));d.textTracks&&(this.loadEventManager_.listen(d.textTracks,"addtrack",function(h){if(h.track)switch(h=h.track,goog.asserts.assert(h instanceof TextTrack,"Wrong track type!"),h.kind){case "metadata":c.processTimedMetadataSrcEqls_(h);break;case "chapters":c.activateChaptersTrack_(h);break;default:c.onTracksChanged_()}}),this.loadEventManager_.listen(d.textTracks,
"removetrack",function(){return c.onTracksChanged_()}),this.loadEventManager_.listen(d.textTracks,"change",function(){return c.onTracksChanged_()}));f=shaka.media.ManifestParser.getExtension(a.uri);d.src=this.cmcdManager_.appendSrcData(a.uri,shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_[f]);(shaka.util.Platform.isTizen()||shaka.util.Platform.isWebOS())&&d.load();this.loadMode_=shaka.Player.LoadMode.SRC_EQUALS;this.dispatchEvent(this.makeEvent_(shaka.util.FakeEvent.EventName.Streaming));var g=new shaka.util.PublicPromise;
shaka.util.MediaReadyState.waitForReadyState(d,HTMLMediaElement.HAVE_METADATA,this.loadEventManager_,function(){c.playhead_.ready();g.resolve()});shaka.util.MediaReadyState.waitForReadyState(d,HTMLMediaElement.HAVE_CURRENT_DATA,this.loadEventManager_,function(){var h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress)return c.setupPreferredAudioOnSrc_(),h=c.getFilteredTextTracks_(),h.find(function(l){return"disabled"!=l.mode})?(0<h.length&&(c.isTextVisible_=!0),k.jumpTo(2)):
k.yield(new Promise(function(l){c.loadEventManager_.listenOnce(d.textTracks,"change",l);(new shaka.util.Timer(l)).tickAfter(1)}),2);if(e)return k.return();c.setupPreferredTextOnSrc_();k.jumpToEnd()})});d.error?g.reject(this.videoErrorToShakaError_()):"none"==d.preload&&(shaka.log.alwaysWarn('With <video preload="none">, the browser will not load anything until play() is called. We are unable to measure load latency in a meaningful way, and we cannot provide track info yet. Please do not use preload="none" with Shaka Player.'),
g.resolve());this.loadEventManager_.listenOnce(d,"error",function(){g.reject(c.videoErrorToShakaError_())});return(new shaka.util.AbortableOperation(g,function(){var h=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);g.reject(h);return Promise.resolve()})).chain(function(){c.fullyLoaded_=!0})};
shaka.Player.prototype.setupPreferredAudioOnSrc_=function(){var a=this.config_.preferredAudioLanguage;if(""!=a){this.selectAudioLanguage(a);var b=this.config_.preferredVariantRole;""!=b&&this.selectAudioLanguage(a,b)}};shaka.Player.prototype.setupPreferredTextOnSrc_=function(){var a=this.config_.preferredTextLanguage,b=this.config_.preferForcedSubs;if(""!=a){this.selectTextLanguage(a,"",b);var c=this.config_.preferredTextRole;""!=c&&this.selectTextLanguage(a,c,b)}};
shaka.Player.prototype.processTimedMetadataSrcEqls_=function(a){var b=this;if("metadata"==a.kind){a.mode="hidden";this.loadEventManager_.listen(a,"cuechange",function(){if(a.activeCues)for(var d=$jscomp.makeIterator(a.activeCues),e=d.next();!e.done;e=d.next())if(e=e.value,b.dispatchMetadataEvent_(e.startTime,e.endTime,e.type,e.value),b.adManager_)b.adManager_.onCueMetadataChange(e.value)});var c=(new shaka.util.Timer(function(){var d=b.getMetadataTracks_();d=$jscomp.makeIterator(d);for(var e=d.next();!e.done;e=
d.next())e.value.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push(function(){c.stop()})}};shaka.Player.prototype.processTimedMetadataMediaSrc_=function(a,b,c){a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())if(d=d.value,d.data&&d.cueTime&&d.frames){var e=d.cueTime+b,f=c;f&&e>f&&(f=e);for(var g=$jscomp.makeIterator(d.frames),h=g.next();!h.done;h=g.next())this.dispatchMetadataEvent_(e,f,"org.id3",h.value);if(this.adManager_)this.adManager_.onHlsTimedMetadata(d,e)}};
shaka.Player.prototype.dispatchMetadataEvent_=function(a,b,c,d){goog.asserts.assert(!b||a<=b,"Metadata start time should be less or equal to the end time!");var e=shaka.util.FakeEvent.EventName.Metadata;a=(new Map).set("startTime",a).set("endTime",b).set("metadataType",c).set("payload",d);this.dispatchEvent(this.makeEvent_(e,a))};
shaka.Player.prototype.activateChaptersTrack_=function(a){if(a&&"chapters"==a.kind){a.mode="hidden";var b=(new shaka.util.Timer(function(){a.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push(function(){b.stop()})}};shaka.Player.filterForAVVariants_=function(a){var b=function(c){return c.video&&c.audio||c.video&&c.video.codecs.includes(",")};a.variants.some(b)&&(shaka.log.debug("Found variant with audio and video content, so filtering out audio-only content."),a.variants=a.variants.filter(b))};
shaka.Player.prototype.createDrmEngine=function(a){return new shaka.media.DrmEngine(a,this.config_.drm.updateExpirationTime)};
shaka.Player.prototype.createNetworkingEngine=function(){var a=this;return new shaka.net.NetworkingEngine(function(b,c){a.abrManager_&&a.abrManager_.segmentDownloaded(b,c)},function(b,c,d){var e=shaka.util.FakeEvent.EventName.DownloadHeadersReceived;b=(new Map).set("headers",b).set("request",c).set("requestType",d);a.dispatchEvent(a.makeEvent_(e,b))},function(b,c,d,e){var f=shaka.util.FakeEvent.EventName.DownloadFailed;b=(new Map).set("request",b).set("error",c).set("httpResponseCode",d).set("aborted",
e);a.dispatchEvent(a.makeEvent_(f,b))})};shaka.Player.prototype.createPlayhead=function(a){var b=this;goog.asserts.assert(this.manifest_,"Must have manifest");goog.asserts.assert(this.video_,"Must have video");return new shaka.media.MediaSourcePlayhead(this.video_,this.manifest_,this.config_.streaming,a,function(){return b.onSeek_()},function(c){return b.dispatchEvent(c)})};
shaka.Player.prototype.createPlayheadObserversForMSE_=function(){var a=this;goog.asserts.assert(this.manifest_,"Must have manifest");goog.asserts.assert(this.regionTimeline_,"Must have region timeline");goog.asserts.assert(this.video_,"Must have video element");var b=new shaka.media.RegionObserver(this.regionTimeline_);b.addEventListener("enter",function(d){a.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionEnter,d.region)});b.addEventListener("exit",function(d){a.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionExit,
d.region)});b.addEventListener("skip",function(d){var e=d.region;d.seeking||(a.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionEnter,e),a.onRegionEvent_(shaka.util.FakeEvent.EventName.TimelineRegionExit,e))});var c=new shaka.media.PlayheadObserverManager(this.video_);c.manage(b);this.qualityObserver_&&c.manage(this.qualityObserver_);return c};
shaka.Player.prototype.startBufferManagement_=function(a){var b=this;goog.asserts.assert(!this.bufferObserver_,"No buffering observer should exist before initialization.");goog.asserts.assert(!this.bufferPoller_,"No buffer timer should exist before initialization.");this.bufferObserver_=new shaka.media.BufferingObserver(1,2);this.bufferObserver_.setState(shaka.media.BufferingObserver.State.STARVING);this.updateBufferingSettings_(a);this.updateBufferState_();this.bufferPoller_=(new shaka.util.Timer(function(){b.pollBufferState_()})).tickEvery(.25)};
shaka.Player.prototype.updateBufferingSettings_=function(a){this.bufferObserver_.setThresholds(a,Math.min(shaka.Player.TYPICAL_BUFFERING_THRESHOLD_,a/2))};
shaka.Player.prototype.pollBufferState_=function(){goog.asserts.assert(this.video_,"Need a media element to update the buffering observer");goog.asserts.assert(this.bufferObserver_,"Need a buffering observer to update");switch(this.loadMode_){case shaka.Player.LoadMode.SRC_EQUALS:var a=this.isBufferedToEndSrc_();break;case shaka.Player.LoadMode.MEDIA_SOURCE:a=this.isBufferedToEndMS_();break;default:a=!1}var b=shaka.media.TimeRangesUtils.bufferedAheadOf(this.video_.buffered,this.video_.currentTime);
this.bufferObserver_.update(b,a)&&this.updateBufferState_()};shaka.Player.prototype.createMediaSourceEngine=function(a,b,c,d){return new shaka.media.MediaSourceEngine(a,b,c,d)};
shaka.Player.prototype.createCmcd_=function(){var a=this;return new shaka.util.CmcdManager({getBandwidthEstimate:function(){return a.abrManager_?a.abrManager_.getBandwidthEstimate():NaN},getBufferedInfo:function(){return a.getBufferedInfo()},getCurrentTime:function(){return a.video_?a.video_.currentTime:0},getVariantTracks:function(){return a.getVariantTracks()},getPlaybackRate:function(){return a.getPlaybackRate()},isLive:function(){return a.isLive()}},this.config_.cmcd)};
shaka.Player.prototype.createStreamingEngine=function(){var a=this;goog.asserts.assert(this.abrManager_&&this.mediaSourceEngine_&&this.cmcdManager_&&this.manifest_,"Must not be destroyed");return new shaka.media.StreamingEngine(this.manifest_,{getPresentationTime:function(){return a.playhead_?a.playhead_.getTime():0},getBandwidthEstimate:function(){return a.abrManager_.getBandwidthEstimate()},modifySegmentRequest:function(b,c){a.cmcdManager_.applySegmentData(b,c)},mediaSourceEngine:this.mediaSourceEngine_,
netEngine:this.networkingEngine_,onError:function(b){return a.onError_(b)},onEvent:function(b){return a.dispatchEvent(b)},onManifestUpdate:function(){return a.onManifestUpdate_()},onSegmentAppended:function(b,c,d){a.onSegmentAppended_(b,c,d)},onInitSegmentAppended:function(b,c){(c=c.getMediaQuality())&&a.qualityObserver_&&a.qualityObserver_.addMediaQualityChange(c,b)},beforeAppendSegment:function(b,c){return a.drmEngine_.parseInbandPssh(b,c)},onMetadata:function(b,c,d){a.processTimedMetadataMediaSrc_(b,
c,d)}})};
shaka.Player.prototype.configure=function(a,b){goog.asserts.assert(this.config_,"Config must not be null!");goog.asserts.assert("object"==typeof a||2==arguments.length,"String configs should have values!");2==arguments.length&&"string"==typeof a&&(a=shaka.util.ConfigUtils.convertToConfigObject(a,b));goog.asserts.assert("object"==typeof a,"Should be an object!");a.streaming&&"forceTransmuxTS"in a.streaming&&(shaka.Deprecate.deprecateFeature(5,"streaming.forceTransmuxTS configuration","Please Use streaming.forceTransmux instead."),a.streaming.forceTransmux=
a.streaming.forceTransmuxTS,delete a.streaming.forceTransmuxTS);a.streaming&&a.streaming.lowLatencyMode&&(void 0==a.streaming.inaccurateManifestTolerance&&(a.streaming.inaccurateManifestTolerance=0),void 0==a.streaming.rebufferingGoal&&(a.streaming.rebufferingGoal=.01));var c=shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,a,this.defaultConfig_());this.applyConfig_();return c};
shaka.Player.prototype.applyConfig_=function(){if(this.parser_){var a=shaka.util.ObjectUtils.cloneObject(this.config_.manifest);this.video_&&"AUDIO"===this.video_.nodeName&&(a.disableVideo=!0);this.parser_.configure(a)}this.drmEngine_&&this.drmEngine_.configure(this.config_.drm);if(this.streamingEngine_){this.streamingEngine_.configure(this.config_.streaming);try{this.filterManifestWithRestrictions_(this.manifest_)}catch(c){this.onError_(c)}this.abrManager_&&this.updateAbrManagerVariants_();!(a=this.streamingEngine_.getCurrentVariant())||
a.allowedByApplication&&a.allowedByKeySystem||(shaka.log.debug("Choosing new variant after changing configuration"),this.chooseVariantAndSwitch_())}this.networkingEngine_&&this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS);if(this.mediaSourceEngine_&&(this.mediaSourceEngine_.configure(this.config_.mediaSource),this.mediaSourceEngine_.setSegmentRelativeVttTiming(this.config_.manifest.segmentRelativeVttTiming),a=this.config_.textDisplayFactory,this.lastTextFactory_!=a)){var b=a();
this.mediaSourceEngine_.setTextDisplayer(b);this.lastTextFactory_=a;this.streamingEngine_&&this.streamingEngine_.reloadTextStream()}this.abrManager_&&(this.abrManager_.configure(this.config_.abr),this.config_.abr.enabled?this.abrManager_.enable():this.abrManager_.disable(),this.onAbrStatusChanged_());this.bufferObserver_&&(a=this.config_.streaming.rebufferingGoal,this.manifest_&&(a=Math.max(a,this.manifest_.minBufferTime)),this.updateBufferingSettings_(a));this.manifest_&&shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,
this.config_.playRangeStart,this.config_.playRangeEnd)};shaka.Player.prototype.getConfiguration=function(){goog.asserts.assert(this.config_,"Config must not be null!");var a=this.defaultConfig_();shaka.util.PlayerConfiguration.mergeConfigObjects(a,this.config_,this.defaultConfig_());return a};shaka.Player.prototype.getSharedConfiguration=function(){goog.asserts.assert(this.config_,"Cannot call getSharedConfiguration after call destroy!");return this.config_};
shaka.Player.prototype.getBufferFullness=function(){if(this.video_){var a=this.video_.buffered.length;a=a?this.video_.buffered.end(a-1):0;var b=this.getConfiguration().streaming.bufferingGoal;b=Math.min(this.video_.currentTime+b,this.seekRange().end);if(a>=b)return 1;if(!(a<=this.video_.currentTime)&&a<b)return(a-this.video_.currentTime)/(b-this.video_.currentTime)}return 0};
shaka.Player.prototype.resetConfiguration=function(){goog.asserts.assert(this.config_,"Cannot be destroyed");for(var a in this.config_)delete this.config_[a];shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,this.defaultConfig_(),this.defaultConfig_());this.applyConfig_()};shaka.Player.prototype.getLoadMode=function(){return this.loadMode_};shaka.Player.prototype.getMediaElement=function(){return this.video_};shaka.Player.prototype.getNetworkingEngine=function(){return this.networkingEngine_};
shaka.Player.prototype.getAssetUri=function(){return this.assetUri_};shaka.Player.prototype.getAdManager=function(){return this.adManager_?this.adManager_:null};shaka.Player.prototype.isLive=function(){return this.manifest_?this.manifest_.presentationTimeline.isLive():this.video_&&this.video_.src?Infinity==this.video_.duration:!1};shaka.Player.prototype.isInProgress=function(){return this.manifest_?this.manifest_.presentationTimeline.isInProgress():!1};
shaka.Player.prototype.isAudioOnly=function(){if(this.manifest_){var a=this.manifest_.variants;return a.length?!a[0].video:!1}return this.video_&&this.video_.src?this.video_.videoTracks?0==this.video_.videoTracks.length:0==this.video_.videoHeight:!1};shaka.Player.prototype.isLowLatencyMode_=function(){return this.config_.streaming.lowLatencyMode};shaka.Player.prototype.isAutoLowLatencyMode_=function(){return this.config_.streaming.autoLowLatencyMode};
shaka.Player.prototype.seekRange=function(){if(!this.fullyLoaded_)return{start:0,end:0};if(this.manifest_){var a=this.manifest_.presentationTimeline;return{start:a.getSeekRangeStart(),end:a.getSeekRangeEnd()}}return this.video_&&this.video_.src&&(a=this.video_.seekable,a.length)?{start:a.start(0),end:a.end(a.length-1)}:{start:0,end:0}};shaka.Player.prototype.goToLive=function(){this.isLive()?this.video_.currentTime=this.seekRange().end:shaka.log.warning("goToLive is for live streams!")};
shaka.Player.prototype.keySystem=function(){return shaka.media.DrmEngine.keySystem(this.drmInfo())};shaka.Player.prototype.drmInfo=function(){return this.drmEngine_?this.drmEngine_.getDrmInfo():null};shaka.Player.prototype.getDrmEngine=function(){return this.drmEngine_};shaka.Player.prototype.getExpiration=function(){return this.drmEngine_?this.drmEngine_.getExpiration():Infinity};shaka.Player.prototype.getKeyStatuses=function(){return this.drmEngine_?this.drmEngine_.getKeyStatuses():{}};
shaka.Player.prototype.isBuffering=function(){var a=shaka.media.BufferingObserver.State;return this.bufferObserver_?this.bufferObserver_.getState()==a.STARVING:!1};shaka.Player.prototype.getPlaybackRate=function(){return this.video_?this.playRateController_?this.playRateController_.getRealRate():1:0};
shaka.Player.prototype.trickPlay=function(a){goog.asserts.assert(0!=a,"Should never set a trick play rate of 0!");0==a?shaka.log.alwaysWarn("A trick play rate of 0 is unsupported!"):(this.video_.paused&&this.video_.play(),this.playRateController_.set(a),this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE&&(this.abrManager_.playbackRateChanged(a),this.streamingEngine_.setTrickPlay(1<Math.abs(a))))};
shaka.Player.prototype.cancelTrickPlay=function(){var a=this.playRateController_.getDefaultRate();this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS&&this.playRateController_.set(a);this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE&&(this.playRateController_.set(a),this.abrManager_.playbackRateChanged(a),this.streamingEngine_.setTrickPlay(!1))};
shaka.Player.prototype.getVariantTracks=function(){if(this.manifest_){for(var a=this.streamingEngine_?this.streamingEngine_.getCurrentVariant():null,b=[],c=0,d=$jscomp.makeIterator(this.manifest_.variants),e=d.next();!e.done;e=d.next())if(e=e.value,shaka.util.StreamUtils.isPlayable(e)){var f=shaka.util.StreamUtils.variantToTrack(e);f.active=e==a;f.active||1==c||null==a||e.video!=a.video||e.audio!=a.audio||(f.active=!0);f.active&&c++;b.push(f)}goog.asserts.assert(1>=c,"It should only have one active track");
return b}return this.video_&&this.video_.audioTracks?Array.from(this.video_.audioTracks).map(function(g){return shaka.util.StreamUtils.html5AudioTrackToTrack(g)}):[]};
shaka.Player.prototype.getTextTracks=function(){if(this.manifest_){for(var a=this.streamingEngine_?this.streamingEngine_.getCurrentTextStream():null,b=[],c=$jscomp.makeIterator(this.manifest_.textStreams),d=c.next();!d.done;d=c.next()){d=d.value;var e=shaka.util.StreamUtils.textStreamToTrack(d);e.active=d==a;b.push(e)}return b}if(this.video_&&this.video_.src&&this.video_.textTracks){a=this.getFilteredTextTracks_();var f=shaka.util.StreamUtils;return a.map(function(g){return f.html5TextTrackToTrack(g)})}return[]};
shaka.Player.prototype.getImageTracks=function(){if(this.manifest_){var a=shaka.util.StreamUtils;return this.manifest_.imageStreams.map(function(b){return a.imageStreamToTrack(b)})}return[]};
shaka.Player.prototype.getThumbnails=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z;return $jscomp.asyncExecutePromiseGeneratorProgram(function(B){if(1==B.nextAddress)return c.manifest_?(d=c.manifest_.imageStreams.find(function(D){return D.id==a}))?d.segmentIndex?B.jumpTo(3):B.yield(d.createSegmentIndex(),3):B.return(null):B.jumpTo(2);if(2!=B.nextAddress){e=d.segmentIndex.find(b);if(null==e)return B.return(null);f=d.segmentIndex.get(e);g=f.getTilesLayout()||d.tilesLayout;h=/(\d+)x(\d+)/.exec(g);
if(!h)return shaka.log.warning("Tiles layout does not contain a valid format  (columns x rows)"),B.return(null);k=d.width||0;l=d.height||0;m=parseInt(h[1],10);n=parseInt(h[2],10);p=k/m;q=l/n;r=m*n;w=f.trueEndTime-f.startTime;u=f.getTileDuration()||w/r;v=f.startTime;t=x=0;1<r&&(y=Math.floor((b-f.startTime)/u),v=f.startTime+y*u,x=y%m*p,t=Math.floor(y/m)*q);A=!1;if(z=f.getThumbnailSprite())A=!0,q=z.height,x=z.positionX,t=z.positionY,p=z.width;return B.return({imageHeight:l,imageWidth:k,height:q,positionX:x,
positionY:t,startTime:v,duration:u,uris:f.getUris(),width:p,sprite:A})}return B.return(null)})};
shaka.Player.prototype.selectTextTrack=function(a){if(this.manifest_&&this.streamingEngine_){var b=this.manifest_.textStreams.find(function(d){return d.id==a.id});b?b==this.streamingEngine_.getCurrentTextStream()?shaka.log.debug("Text track already selected."):(this.addTextStreamToSwitchHistory_(b,!1),this.streamingEngine_.switchTextStream(b),this.onTextChanged_(),this.currentTextLanguage_=b.language):shaka.log.error("No stream with id",a.id)}else if(this.video_&&this.video_.src&&this.video_.textTracks){b=
this.getFilteredTextTracks_();b=$jscomp.makeIterator(b);for(var c=b.next();!c.done;c=b.next())c=c.value,shaka.util.StreamUtils.html5TrackId(c)==a.id?c.mode=this.isTextVisible_?"showing":"hidden":c.mode="disabled";this.onTextChanged_()}};
shaka.Player.prototype.selectVariantTrack=function(a,b,c){b=void 0===b?!1:b;c=void 0===c?0:c;if(this.manifest_&&this.streamingEngine_){this.config_.abr.enabled&&shaka.log.alwaysWarn("Changing tracks while abr manager is enabled will likely result in the selected track being overriden. Consider disabling abr before calling selectVariantTrack().");var d=this.manifest_.variants.find(function(e){return e.id==a.id});d?shaka.util.StreamUtils.isPlayable(d)?(this.switchVariant_(d,!1,b,c),this.currentAdaptationSetCriteria_=
new shaka.media.ExampleBasedCriteria(d),this.updateAbrManagerVariants_()):shaka.log.error("Unable to switch to restricted track",a.id):shaka.log.error("No variant with id",a.id)}else if(this.video_&&this.video_.audioTracks)for(b=Array.from(this.video_.audioTracks),b=$jscomp.makeIterator(b),c=b.next();!c.done;c=b.next())if(c=c.value,shaka.util.StreamUtils.html5TrackId(c)==a.id){this.switchHtml5Track_(c);break}};shaka.Player.prototype.getAudioLanguagesAndRoles=function(){return shaka.Player.getLanguageAndRolesFrom_(this.getVariantTracks())};
shaka.Player.prototype.getTextLanguagesAndRoles=function(){return shaka.Player.getLanguageAndRolesFrom_(this.getTextTracks())};shaka.Player.prototype.getAudioLanguages=function(){return Array.from(shaka.Player.getLanguagesFrom_(this.getVariantTracks()))};shaka.Player.prototype.getTextLanguages=function(){return Array.from(shaka.Player.getLanguagesFrom_(this.getTextTracks()))};
shaka.Player.prototype.selectAudioLanguage=function(a,b,c){c=void 0===c?0:c;var d=shaka.util.LanguageUtils;if(this.manifest_&&this.playhead_){this.currentAdaptationSetCriteria_=new shaka.media.PreferenceBasedCriteria(a,b||"",c,"");b=function(k,l){return k.video||l.video?k.video&&l.video?Math.abs((k.video.height||0)-(l.video.height||0))+Math.abs((k.video.width||0)-(l.video.width||0)):Infinity:0};d=this.streamingEngine_.getCurrentVariant();c=this.currentAdaptationSetCriteria_.create(this.manifest_.variants);
a=null;c=$jscomp.makeIterator(c.values());for(var e=c.next();!e.done;e=c.next())if(e=e.value,!a||b(a,d)>b(e,d))a=e;a?(b=shaka.util.StreamUtils.variantToTrack(a),this.selectVariantTrack(b,!0)):this.chooseVariantAndSwitch_()}else if(this.video_&&this.video_.audioTracks){var f=Array.from(this.video_.audioTracks);a=d.normalize(a);e=c=null;f=$jscomp.makeIterator(f);for(var g=f.next();!g.done;g=f.next()){g=g.value;var h=shaka.util.StreamUtils.html5AudioTrackToTrack(g);d.normalize(h.language)==a&&(c=g,b?
h.roles.includes(b)&&(e=g):0==h.roles.length&&(e=g))}e?this.switchHtml5Track_(e):c&&this.switchHtml5Track_(c)}};
shaka.Player.prototype.selectTextLanguage=function(a,b,c){c=void 0===c?!1:c;var d=shaka.util.LanguageUtils;if(this.manifest_&&this.playhead_){if(this.currentTextLanguage_=a,this.currentTextRole_=b||"",this.currentTextForced_=c,a=this.chooseTextStream_())a==this.streamingEngine_.getCurrentTextStream()?shaka.log.debug("Text track already selected."):(this.addTextStreamToSwitchHistory_(a,!1),this.shouldStreamText_()&&(this.streamingEngine_.switchTextStream(a),this.onTextChanged_()))}else{var e=d.normalize(a);
(a=this.getTextTracks().find(function(f){return d.normalize(f.language)==e&&(!b||f.roles.includes(b))&&f.forced==c}))&&this.selectTextTrack(a)}};
shaka.Player.prototype.selectVariantsByLabel=function(a){if(this.manifest_&&this.playhead_){for(var b=null,c=$jscomp.makeIterator(this.manifest_.variants),d=c.next();!d.done;d=c.next())if(d=d.value,d.audio.label==a){b=d;break}null==b?shaka.log.warning("No variants were found with label: "+a+". Ignoring the request to switch."):(this.currentAdaptationSetCriteria_=new shaka.media.PreferenceBasedCriteria(b.language,"",0,a),this.chooseVariantAndSwitch_())}};
shaka.Player.prototype.isTextTrackVisible=function(){var a=this.isTextVisible_;if(this.mediaSourceEngine_){var b=this.mediaSourceEngine_.getTextDisplayer().isTextVisible();goog.asserts.assert(b==a,"text visibility has fallen out of sync");return b}return this.video_&&this.video_.src&&this.video_.textTracks?this.getFilteredTextTracks_().some(function(c){return"showing"==c.mode}):a};
shaka.Player.prototype.getChaptersTracks=function(){if(this.video_&&this.video_.src&&this.video_.textTracks){var a=this.getChaptersTracks_(),b=shaka.util.StreamUtils;return a.map(function(c){return b.html5TextTrackToTrack(c)})}return[]};
shaka.Player.prototype.getChapters=function(a){var b=shaka.util.LanguageUtils,c=b.normalize(a),d=this.getChaptersTracks_().filter(function(k){return b.normalize(k.language)==c});if(!d||!d.length)return[];a=[];var e=new Set;d=$jscomp.makeIterator(d);for(var f=d.next();!f.done;f=d.next())if((f=f.value)&&f.cues){f=$jscomp.makeIterator(f.cues);for(var g=f.next();!g.done;g=f.next()){var h=g.value;(g=h.id)&&""!=g||(g=h.startTime+"-"+h.endTime+"-"+h.text);h={id:g,title:h.text,startTime:h.startTime,endTime:h.endTime};
e.has(g)||(a.push(h),e.add(g))}}return a};shaka.Player.prototype.getFilteredTextTracks_=function(){goog.asserts.assert(this.video_.textTracks,"TextTracks should be valid.");return Array.from(this.video_.textTracks).filter(function(a){return"metadata"!=a.kind&&"chapters"!=a.kind&&a.label!=shaka.Player.TextTrackLabel})};
shaka.Player.prototype.getMetadataTracks_=function(){goog.asserts.assert(this.video_.textTracks,"TextTracks should be valid.");return Array.from(this.video_.textTracks).filter(function(a){return"metadata"==a.kind})};shaka.Player.prototype.getChaptersTracks_=function(){goog.asserts.assert(this.video_.textTracks,"TextTracks should be valid.");return Array.from(this.video_.textTracks).filter(function(a){return"chapters"==a.kind})};
shaka.Player.prototype.setTextTrackVisibility=function(a){a=!!a;if(this.isTextVisible_!=a){this.isTextVisible_=a;if(this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE)this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(a),this.config_.streaming.alwaysStreamText||(a?this.streamingEngine_.getCurrentTextStream()||(a=shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_),0<a.length&&(this.streamingEngine_.switchTextStream(a[0]),
this.onTextChanged_())):this.streamingEngine_.unloadTextStream());else if(this.video_&&this.video_.src&&this.video_.textTracks){var b=this.getFilteredTextTracks_();b=$jscomp.makeIterator(b);for(var c=b.next();!c.done;c=b.next())c=c.value,"disabled"!=c.mode&&(c.mode=a?"showing":"hidden")}this.onTextTrackVisibility_()}};
shaka.Player.prototype.getPlayheadTimeAsDate=function(){if(!this.isLive())return shaka.log.warning("getPlayheadTimeAsDate is for live streams!"),null;var a=this.walker_.getCurrentPayload(),b=0;if(this.playhead_)b=this.playhead_.getTime();else if(a){if(null==a.startTime)return new Date;b=a.startTime}if(this.manifest_)return a=this.manifest_.presentationTimeline.getPresentationStartTime(),new Date(1E3*(a+b));if(this.video_&&this.video_.getStartDate)return a=this.video_.getStartDate(),isNaN(a.getTime())?
(shaka.log.warning("EXT-X-PROGRAM-DATETIME required to get playhead time as Date!"),null):new Date(a.getTime()+1E3*b);shaka.log.warning("No way to get playhead time as Date!");return null};
shaka.Player.prototype.getPresentationStartTimeAsDate=function(){if(!this.isLive())return shaka.log.warning("getPresentationStartTimeAsDate is for live streams!"),null;if(this.manifest_){var a=this.manifest_.presentationTimeline.getPresentationStartTime();goog.asserts.assert(null!=a,"Presentation start time should not be null!");return new Date(1E3*a)}if(this.video_&&this.video_.getStartDate)return a=this.video_.getStartDate(),isNaN(a.getTime())?(shaka.log.warning("EXT-X-PROGRAM-DATETIME required to get presentation start time as Date!"),
null):a;shaka.log.warning("No way to get presentation start time as Date!");return null};shaka.Player.prototype.getBufferedInfo=function(){if(this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE)return this.mediaSourceEngine_.getBufferedInfo();var a={total:[],audio:[],video:[],text:[]};this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS&&(a.total=shaka.media.TimeRangesUtils.getBufferedInfo(this.video_.buffered));return a};
shaka.Player.prototype.getStats=function(){if(this.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&this.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)return shaka.util.Stats.getEmptyBlob();this.updateStateHistory_();goog.asserts.assert(this.video_,"If we have stats, we should have video_");var a=this.video_,b=a.currentTime/a.duration;isNaN(b)||this.stats_.setCompletionPercent(Math.round(100*b));this.playhead_&&(this.stats_.setGapsJumped(this.playhead_.getGapsJumped()),this.stats_.setStallsDetected(this.playhead_.getStallsDetected()));
a.getVideoPlaybackQuality&&(b=a.getVideoPlaybackQuality(),this.stats_.setDroppedFrames(Number(b.droppedVideoFrames),Number(b.totalVideoFrames)),this.stats_.setCorruptedFrames(Number(b.corruptedVideoFrames)));b=this.drmEngine_?this.drmEngine_.getLicenseTime():NaN;this.stats_.setLicenseTime(b);if(this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE){if(b=this.streamingEngine_.getCurrentVariant()){var c=(this.playRateController_?this.playRateController_.getRealRate():1)*b.bandwidth;this.stats_.setCurrentStreamBandwidth(c)}b&&
b.video&&this.stats_.setResolution(b.video.width||NaN,b.video.height||NaN);this.isLive()&&(b=this.getPresentationStartTimeAsDate().valueOf()+1E3*this.seekRange().end,b=(Date.now()-b)/1E3,this.stats_.setLiveLatency(b));this.manifest_&&this.manifest_.presentationTimeline&&(b=this.manifest_.presentationTimeline.getMaxSegmentDuration(),this.stats_.setMaxSegmentDuration(b));b=this.abrManager_.getBandwidthEstimate();this.stats_.setBandwidthEstimate(b)}this.loadMode_==shaka.Player.LoadMode.SRC_EQUALS&&this.stats_.setResolution(a.videoWidth||
NaN,a.videoHeight||NaN);return this.stats_.getBlob()};
shaka.Player.prototype.addTextTrackAsync=function(a,b,c,d,e,f,g){g=void 0===g?!1:g;var h=this,k,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:if(h.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&h.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Must call load() and wait for it to resolve before adding text tracks."),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.CONTENT_NOT_LOADED);
if(d){t.jumpTo(2);break}return t.yield(h.getTextMimetype_(a),3);case 3:d=t.yieldResult;case 2:k=[];if(h.adManager_)try{k=h.adManager_.getServerSideCuePoints()}catch(y){}if(h.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS){t.jumpTo(4);break}g&&(c="forced");return t.yield(h.addSrcTrackElement_(a,b,c,d,f||"",k),5);case 5:l=h.getTextTracks();if(m=l.find(function(y){return y.language==b&&y.label==(f||"")&&y.kind==c}))return h.onTracksChanged_(),t.return(m);shaka.log.error("Cannot add this text when loaded with src=");
throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);case 4:n=shaka.util.ManifestParserUtils.ContentType;p=h.manifest_.presentationTimeline.getDuration();if(Infinity==p)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM);if(!k.length){t.jumpTo(6);break}goog.asserts.assert(h.networkingEngine_,
"Need networking engine.");return t.yield(h.getTextData_(a,h.networkingEngine_,h.config_.streaming.retryParameters),7);case 7:q=t.yieldResult,r=h.convertToWebVTT_(q,d,k),w=new Blob([r],{type:"text/vtt"}),a=shaka.media.MediaSourceEngine.createObjectURL(w),d="text/vtt";case 6:u={id:h.nextExternalStreamId_++,originalId:null,createSegmentIndex:function(){return Promise.resolve()},segmentIndex:shaka.media.SegmentIndex.forSingleSegment(0,p,[a]),mimeType:d||"",codecs:e||"",kind:c,encrypted:!1,drmInfos:[],
keyIds:new Set,language:b,label:f||null,type:n.TEXT,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:!!g,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null};v=shaka.util.MimeUtils.getFullType(u.mimeType,u.codecs);x=shaka.text.TextEngine.isTypeSupported(v);if(!x)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.MISSING_TEXT_PLUGIN,d);h.manifest_.textStreams.push(u);h.onTracksChanged_();return t.return(shaka.util.StreamUtils.textStreamToTrack(u))}})};
shaka.Player.prototype.addThumbnailsTrack=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:if(c.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&c.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Must call load() and wait for it to resolve before adding image tracks."),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.CONTENT_NOT_LOADED);
if(c.loadMode_==shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Cannot add this thumbnail track when loaded with src="),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_SRC_EQUALS);if(b){t.jumpTo(2);break}return t.yield(c.getTextMimetype_(a),3);case 3:b=t.yieldResult;case 2:if("text/vtt"!=b)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,
a);d=shaka.util.ManifestParserUtils.ContentType;e=c.manifest_.presentationTimeline.getDuration();if(Infinity==e)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM);goog.asserts.assert(c.networkingEngine_,"Need networking engine.");return t.yield(c.getTextData_(a,c.networkingEngine_,c.config_.streaming.retryParameters),4);case 4:f=t.yieldResult;g=shaka.text.TextEngine.findParser(b);
if(!g)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.MISSING_TEXT_PLUGIN,b);h=g();k={periodStart:0,segmentStart:0,segmentEnd:e,vttOffset:0};l=shaka.util.BufferUtils.toUint8(f);m=h.parseMedia(l,k);n=[];p={};q=$jscomp.makeIterator(m);for(r=q.next();!r.done;p={$jscomp$loop$prop$imageUri$657:p.$jscomp$loop$prop$imageUri$657},r=q.next())w=r.value,p.$jscomp$loop$prop$imageUri$657=shaka.util.ManifestParserUtils.resolveUris([a],[w.payload])[0],
u=new shaka.media.SegmentReference(w.startTime,w.endTime,function(y){return function(){return[y.$jscomp$loop$prop$imageUri$657]}}(p),0,null,null,0,0,Infinity),p.$jscomp$loop$prop$imageUri$657.includes("#xywh")&&(v=p.$jscomp$loop$prop$imageUri$657.split("#xywh=")[1].split(","),4===v.length&&u.setThumbnailSprite({height:parseInt(v[3],10),positionX:parseInt(v[0],10),positionY:parseInt(v[1],10),width:parseInt(v[2],10)})),n.push(u);x={id:c.nextExternalStreamId_++,originalId:null,createSegmentIndex:function(){return Promise.resolve()},
segmentIndex:new shaka.media.SegmentIndex(n),mimeType:b||"",codecs:"",kind:"",encrypted:!1,drmInfos:[],keyIds:new Set,language:"und",label:null,type:d.IMAGE,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,tilesLayout:"1x1"};c.manifest_.imageStreams.push(x);c.onTracksChanged_();return t.return(shaka.util.StreamUtils.imageStreamToTrack(x))}})};
shaka.Player.prototype.addChaptersTrack=function(a,b,c){var d=this,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){switch(k.nextAddress){case 1:if(d.loadMode_!=shaka.Player.LoadMode.MEDIA_SOURCE&&d.loadMode_!=shaka.Player.LoadMode.SRC_EQUALS)throw shaka.log.error("Must call load() and wait for it to resolve before adding chapters tracks."),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.CONTENT_NOT_LOADED);if(c){k.jumpTo(2);
break}return k.yield(d.getTextMimetype_(a),3);case 3:c=k.yieldResult;case 2:e=[];if(d.adManager_)try{e=d.adManager_.getServerSideCuePoints()}catch(l){}return k.yield(d.addSrcTrackElement_(a,b,"chapters",c,"",e),4);case 4:f=k.yieldResult;g=d.getChaptersTracks();h=g.find(function(l){return l.language==b});if(!h){k.jumpTo(5);break}return k.yield(new Promise(function(l,m){d.loadEventManager_.listenOnce(f,"load",l);d.loadEventManager_.listenOnce(f,"error",function(n){m(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.CHAPTERS_TRACK_FAILED))})}),6);case 6:return k.return(h);case 5:throw shaka.log.error("Cannot add this text when loaded with src="),new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS);}})};
shaka.Player.prototype.getTextMimetype_=function(a){var b=this,c,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){switch(e.nextAddress){case 1:c=shaka.media.ManifestParser.getExtension(a);if(d=shaka.Player.TEXT_EXTENSIONS_TO_MIME_TYPES_[c])return e.return(d);e.setCatchFinallyBlocks(2);goog.asserts.assert(b.networkingEngine_,"Need networking engine.");return e.yield(shaka.media.ManifestParser.getMimeType(a,b.networkingEngine_,b.config_.streaming.retryParameters),4);case 4:d=e.yieldResult;
e.leaveTryBlock(3);break;case 2:e.enterCatchBlock();case 3:if(d)return e.return(d);shaka.log.error("The mimeType has not been provided and it could not be deduced from its extension.");throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,c);}})};
shaka.Player.prototype.addSrcTrackElement_=function(a,b,c,d,e,f){var g=this,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){if(1==n.nextAddress){if("text/vtt"==d&&!f.length)return n.jumpTo(2);goog.asserts.assert(g.networkingEngine_,"Need networking engine.");return n.yield(g.getTextData_(a,g.networkingEngine_,g.config_.streaming.retryParameters),3)}2!=n.nextAddress&&(h=n.yieldResult,k=g.convertToWebVTT_(h,d,f),l=new Blob([k],{type:"text/vtt"}),a=shaka.media.MediaSourceEngine.createObjectURL(l),
d="text/vtt");m=document.createElement("track");m.src=g.cmcdManager_.appendTextTrackData(a);m.label=e;m.kind=c;m.srclang=b;g.video_.getAttribute("crossorigin")||g.video_.setAttribute("crossorigin","anonymous");g.video_.appendChild(m);return n.return(m)})};
shaka.Player.prototype.getTextData_=function(a,b,c){var d=this,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return e=shaka.net.NetworkingEngine.RequestType.SEGMENT,f=shaka.net.NetworkingEngine.makeRequest([a],c),f.method="GET",d.cmcdManager_.applyTextData(f),h.yield(b.request(e,f).promise,2);g=h.yieldResult;return h.return(g.data)})};
shaka.Player.prototype.convertToWebVTT_=function(a,b,c){var d=shaka.text.TextEngine.findParser(b);if(d)return b=d(),d={periodStart:0,segmentStart:0,segmentEnd:this.video_.duration,vttOffset:0},a=shaka.util.BufferUtils.toUint8(a),a=b.parseMedia(a,d),shaka.text.WebVttGenerator.convert(a,c);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.MISSING_TEXT_PLUGIN,b);};
shaka.Player.prototype.setMaxHardwareResolution=function(a,b){this.maxHwRes_.width=a;this.maxHwRes_.height=b};shaka.Player.prototype.retryStreaming=function(a){return this.loadMode_==shaka.Player.LoadMode.MEDIA_SOURCE?this.streamingEngine_.retry(void 0===a?.1:a):!1};
shaka.Player.prototype.getManifest=function(){shaka.log.alwaysWarn("Shaka Player's internal Manifest structure is NOT covered by semantic versioning compatibility guarantees.  It may change at any time!  Please consider filing a feature request for whatever you use getManifest() for.");return this.manifest_};shaka.Player.prototype.getManifestParserFactory=function(){return this.parserFactory_};
shaka.Player.prototype.addVariantToSwitchHistory_=function(a,b){this.stats_.getSwitchHistory().updateCurrentVariant(a,b)};shaka.Player.prototype.addTextStreamToSwitchHistory_=function(a,b){this.stats_.getSwitchHistory().updateCurrentText(a,b)};
shaka.Player.prototype.defaultConfig_=function(){var a=this,b=shaka.util.PlayerConfiguration.createDefault();b.streaming.failureCallback=function(c){a.defaultStreamingFailureCallback_(c)};b.textDisplayFactory=function(){return a.videoContainer_?new shaka.text.UITextDisplayer(a.video_,a.videoContainer_):new shaka.text.SimpleTextDisplayer(a.video_)};return b};shaka.Player.prototype.setVideoContainer=function(a){this.videoContainer_=a};
shaka.Player.prototype.defaultStreamingFailureCallback_=function(a){if(this.isLive()){var b=null;a.code==shaka.util.Error.Code.BAD_HTTP_STATUS||a.code==shaka.util.Error.Code.HTTP_ERROR?b=1:a.code==shaka.util.Error.Code.TIMEOUT&&(b=.1);null!=b&&(a.severity=shaka.util.Error.Severity.RECOVERABLE,shaka.log.warning("Live streaming error.  Retrying automatically..."),this.retryStreaming(b))}};
shaka.Player.prototype.makeTextStreamsForClosedCaptions_=function(a){for(var b=shaka.util.ManifestParserUtils.ContentType,c=shaka.util.ManifestParserUtils.TextStreamKind,d=shaka.util.MimeUtils.CEA608_CLOSED_CAPTION_MIMETYPE,e=shaka.util.MimeUtils.CEA708_CLOSED_CAPTION_MIMETYPE,f=new Set,g=$jscomp.makeIterator(a.textStreams),h=g.next();!h.done;h=g.next())h=h.value,h.mimeType!=d&&h.mimeType!=e||f.add(h.originalId);g=$jscomp.makeIterator(a.variants);for(h=g.next();!h.done;h=g.next())if((h=h.value.video)&&
h.closedCaptions)for(var k=$jscomp.makeIterator(h.closedCaptions.keys()),l=k.next();!l.done;l=k.next())if(l=l.value,!f.has(l)){var m=l.startsWith("CC")?d:e,n=new shaka.media.MetaSegmentIndex;m={id:this.nextExternalStreamId_++,originalId:l,createSegmentIndex:function(){return Promise.resolve()},segmentIndex:n,mimeType:m,codecs:"",kind:c.CLOSED_CAPTION,encrypted:!1,drmInfos:[],keyIds:new Set,language:h.closedCaptions.get(l),label:null,type:b.TEXT,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,
roles:h.roles,forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null};a.textStreams.push(m);f.add(l)}};shaka.Player.prototype.filterManifest_=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return c.yield(b.filterManifestWithStreamUtils_(a),2);b.filterManifestWithRestrictions_(a);c.jumpToEnd()})};
shaka.Player.prototype.filterManifestWithStreamUtils_=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return goog.asserts.assert(a,"Manifest should exist!"),goog.asserts.assert(b.video_,"Must not be destroyed"),c=b.streamingEngine_?b.streamingEngine_.getCurrentVariant():null,d.yield(shaka.util.StreamUtils.filterManifest(b.drmEngine_,c,a),2);b.checkPlayableVariants_(a);d.jumpToEnd()})};
shaka.Player.prototype.filterManifestWithRestrictions_=function(a){if(this.loadMode_!=shaka.Player.LoadMode.DESTROYED){if(shaka.util.StreamUtils.applyRestrictions(a.variants,this.config_.restrictions,this.maxHwRes_)&&this.streamingEngine_)this.onTracksChanged_();var b=this.drmEngine_?this.drmEngine_.getDrmInfo():null;if(b&&this.drmEngine_.getMediaKeys())for(var c=$jscomp.makeIterator(a.variants),d=c.next();!d.done;d=c.next())d=d.value,this.processDrmInfos_(b.keySystem,d.video),this.processDrmInfos_(b.keySystem,
d.audio);this.checkRestrictedVariants_(a)}};shaka.Player.prototype.processDrmInfos_=function(a,b){if(b){b=$jscomp.makeIterator(b.drmInfos);for(var c=b.next();!c.done;c=b.next())if(c=c.value,c.keySystem==a){c=$jscomp.makeIterator(c.initData||[]);for(var d=c.next();!d.done;d=c.next())d=d.value,this.drmEngine_.newInitData(d.initDataType,d.initData)}}};
shaka.Player.prototype.filterManifestByCurrentVariant_=function(){goog.asserts.assert(this.manifest_,"Manifest should be valid");goog.asserts.assert(this.streamingEngine_,"StreamingEngine should be valid");var a=this.streamingEngine_?this.streamingEngine_.getCurrentVariant():null;shaka.util.StreamUtils.filterManifestByCurrentVariant(a,this.manifest_);this.checkPlayableVariants_(this.manifest_)};
shaka.Player.prototype.adjustStartTime_=function(a,b){var c,d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return c=a.audio,d=a.video,e=function(k,l){var m,n,p;return $jscomp.asyncExecutePromiseGeneratorProgram(function(q){if(1==q.nextAddress)return k?q.yield(k.createSegmentIndex(),2):q.return(null);n=(m=k.segmentIndex.getIteratorForTime(l))?m.next().value:null;if(!n)return q.return(null);p=n.startTime;goog.asserts.assert(p<=l,"Segment should start before target time!");
return q.return(p)})},h.yield(e(c,b),2);if(3!=h.nextAddress)return f=h.yieldResult,h.yield(e(d,b),3);g=h.yieldResult;return null!=g&&null!=f?h.return(Math.max(g,f)):null!=g?h.return(g):null!=f?h.return(f):h.return(b)})};
shaka.Player.prototype.updateBufferState_=function(){var a=this.isBuffering();shaka.log.v2("Player changing buffering state to",a);this.stats_&&this.bufferObserver_&&this.playhead_&&(this.playRateController_.setBuffering(a),this.cmcdManager_&&this.cmcdManager_.setBuffering(a),this.updateStateHistory_());var b=shaka.util.FakeEvent.EventName.Buffering;a=(new Map).set("buffering",a);this.dispatchEvent(this.makeEvent_(b,a))};
shaka.Player.prototype.onRateChange_=function(){var a=this.video_.playbackRate;0!=a&&(this.playRateController_&&this.playRateController_.set(a),a=this.makeEvent_(shaka.util.FakeEvent.EventName.RateChange),this.dispatchEvent(a))};
shaka.Player.prototype.updateStateHistory_=function(){if(this.stats_&&this.bufferObserver_){var a=shaka.media.BufferingObserver.State,b=this.stats_.getStateHistory();this.bufferObserver_.getState()==a.STARVING?b.update("buffering"):this.video_.paused?b.update("paused"):this.video_.ended?b.update("ended"):b.update("playing")}};
shaka.Player.prototype.onSeek_=function(){this.playheadObservers_&&this.playheadObservers_.notifyOfSeek();this.streamingEngine_&&this.streamingEngine_.seeked();this.bufferObserver_&&this.pollBufferState_()};
shaka.Player.prototype.updateAbrManagerVariants_=function(){try{goog.asserts.assert(this.manifest_,"Manifest should exist by now!"),this.checkRestrictedVariants_(this.manifest_)}catch(b){return this.onError_(b),!1}var a=this.manifest_.variants.filter(function(b){return shaka.util.StreamUtils.isPlayable(b)});a=this.currentAdaptationSetCriteria_.create(a);this.abrManager_.setVariants(Array.from(a.values()));return!0};
shaka.Player.prototype.chooseVariant_=function(){return this.updateAbrManagerVariants_()?this.abrManager_.chooseVariant():null};shaka.Player.prototype.checkVariants_=function(){shaka.util.StreamUtils.applyRestrictions(this.manifest_.variants,this.config_.restrictions,this.maxHwRes_)&&this.chooseVariant_()};
shaka.Player.prototype.chooseTextStream_=function(){return shaka.util.StreamUtils.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_)[0]||null};shaka.Player.prototype.chooseVariantAndSwitch_=function(){goog.asserts.assert(this.config_,"Must not be destroyed");var a=this.chooseVariant_();a&&this.switchVariant_(a,!0,!0,0)};
shaka.Player.prototype.switchVariant_=function(a,b,c,d){var e=this.streamingEngine_.getCurrentVariant();if(a==e)shaka.log.debug("Variant already selected."),c&&this.streamingEngine_.switchVariant(a,c,d,!0);else if(this.addVariantToSwitchHistory_(a,b),this.streamingEngine_.switchVariant(a,c,d,void 0,b),c=null,e&&(c=shaka.util.StreamUtils.variantToTrack(e)),a=shaka.util.StreamUtils.variantToTrack(a),b)this.onAdaptation_(c,a);else this.onVariantChanged_(c,a)};
shaka.Player.prototype.switchHtml5Track_=function(a){goog.asserts.assert(this.video_&&this.video_.audioTracks,"Video and video.audioTracks should not be null!");var b=Array.from(this.video_.audioTracks).find(function(c){return c.enabled});a.enabled=!0;a.id!==b.id&&(b.enabled=!1);b=shaka.util.StreamUtils.html5AudioTrackToTrack(b);a=shaka.util.StreamUtils.html5AudioTrackToTrack(a);this.onVariantChanged_(b,a)};
shaka.Player.prototype.setInitialTextState_=function(a,b){b?(a.audio&&this.shouldInitiallyShowText_(a.audio,b)&&(this.isTextVisible_=!0),this.isTextVisible_&&(this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(!0),goog.asserts.assert(this.shouldStreamText_(),"Should be streaming text")),this.onTextTrackVisibility_()):this.isTextVisible_=!1};
shaka.Player.prototype.shouldInitiallyShowText_=function(a,b){var c=shaka.config.AutoShowText;if(this.config_.autoShowText==c.NEVER)return!1;if(this.config_.autoShowText==c.ALWAYS)return!0;var d=shaka.util.LanguageUtils,e=d.normalize(this.config_.preferredTextLanguage);b=d.normalize(b.language);if(this.config_.autoShowText==c.IF_PREFERRED_TEXT_LANGUAGE)return d.areLanguageCompatible(b,e);if(this.config_.autoShowText==c.IF_SUBTITLES_MAY_BE_NEEDED)return a=d.normalize(a.language),d.areLanguageCompatible(b,
e)&&!d.areLanguageCompatible(a,b);shaka.log.alwaysWarn("Invalid autoShowText setting!");return!1};shaka.Player.prototype.onManifestUpdate_=function(){this.parser_&&this.parser_.update&&this.parser_.update()};shaka.Player.prototype.onSegmentAppended_=function(a,b,c){this.playhead_&&this.playhead_.notifyOfBufferingChange();this.pollBufferState_();a=(new Map).set("start",a).set("end",b).set("contentType",c);this.dispatchEvent(this.makeEvent_(shaka.util.FakeEvent.EventName.SegmentAppended,a))};
shaka.Player.prototype.switch_=function(a,b,c){b=void 0===b?!1:b;c=void 0===c?0:c;shaka.log.debug("switch_");goog.asserts.assert(this.config_.abr.enabled,"AbrManager should not call switch while disabled!");goog.asserts.assert(this.manifest_,"We need a manifest to switch variants.");this.streamingEngine_&&a!=this.streamingEngine_.getCurrentVariant()&&this.switchVariant_(a,!0,b,c)};
shaka.Player.prototype.onAdaptation_=function(a,b){a=(new Map).set("oldTrack",a).set("newTrack",b);this.lcevcDil_&&this.lcevcDil_.updateVariant(b);b=this.makeEvent_(shaka.util.FakeEvent.EventName.Adaptation,a);this.delayDispatchEvent_(b)};shaka.Player.prototype.onTracksChanged_=function(){var a=this.makeEvent_(shaka.util.FakeEvent.EventName.TracksChanged);this.delayDispatchEvent_(a)};
shaka.Player.prototype.onVariantChanged_=function(a,b){a=(new Map).set("oldTrack",a).set("newTrack",b);this.lcevcDil_&&this.lcevcDil_.updateVariant(b);b=this.makeEvent_(shaka.util.FakeEvent.EventName.VariantChanged,a);this.delayDispatchEvent_(b)};shaka.Player.prototype.onTextChanged_=function(){var a=this.makeEvent_(shaka.util.FakeEvent.EventName.TextChanged);this.delayDispatchEvent_(a)};
shaka.Player.prototype.onTextTrackVisibility_=function(){var a=this.makeEvent_(shaka.util.FakeEvent.EventName.TextTrackVisibility);this.delayDispatchEvent_(a)};shaka.Player.prototype.onAbrStatusChanged_=function(){var a=(new Map).set("newStatus",this.config_.abr.enabled);this.delayDispatchEvent_(this.makeEvent_(shaka.util.FakeEvent.EventName.AbrStatusChanged,a))};
shaka.Player.prototype.tryToRecoverFromError_=function(a){if(a.code!=shaka.util.Error.Code.HTTP_ERROR&&a.code!=shaka.util.Error.Code.SEGMENT_MISSING||a.category!=shaka.util.Error.Category.NETWORK||!navigator.onLine)return!1;var b=this.config_.streaming.maxDisabledTime;if(0==b)if(a.code==shaka.util.Error.Code.SEGMENT_MISSING)b=1;else return!1;a.code==shaka.util.Error.Code.HTTP_ERROR&&shaka.log.debug("Recoverable NETWORK HTTP_ERROR, trying to recover...");a=this.getVariantTracks().find(function(f){return f.active});
goog.asserts.assert(a,"Active variant should be found");for(var c=this.manifest_,d=$jscomp.makeIterator(c.variants),e=d.next();!e.done;e=d.next())e=e.value,e.id===a.id&&(e.disabledUntilTime=Date.now()/1E3+b);shaka.util.StreamUtils.applyRestrictions(c.variants,this.config_.restrictions,this.maxHwRes_);a=this.chooseVariant_();if(!a)return shaka.log.warning("Not enough variants to recover from error"),!1;c=this.getBufferedInfo().video.reduce(function(f,g){return f+g.end-g.start},0);this.switchVariant_(a,
!1,!0,c);this.checkVariantsTimer_.tickAfter(b);return!0};shaka.Player.prototype.onError_=function(a){goog.asserts.assert(a instanceof shaka.util.Error,"Wrong error type!");if(this.loadMode_!=shaka.Player.LoadMode.DESTROYED)if(this.tryToRecoverFromError_(a))a.handled=!0;else{var b=this.makeEvent_(shaka.util.FakeEvent.EventName.Error,(new Map).set("detail",a));this.dispatchEvent(b);b.defaultPrevented&&(a.handled=!0)}};
shaka.Player.prototype.onRegionEvent_=function(a,b){b={schemeIdUri:b.schemeIdUri,value:b.value,startTime:b.startTime,endTime:b.endTime,id:b.id,eventElement:b.eventElement};b=(new Map).set("detail",b);this.dispatchEvent(this.makeEvent_(a,b))};
shaka.Player.prototype.onMediaQualityChange_=function(a,b){a={bandwidth:a.bandwidth,audioSamplingRate:a.audioSamplingRate,codecs:a.codecs,contentType:a.contentType,frameRate:a.frameRate,height:a.height,mimeType:a.mimeType,channelsCount:a.channelsCount,pixelAspectRatio:a.pixelAspectRatio,width:a.width};b=(new Map).set("mediaQuality",a).set("position",b);this.dispatchEvent(this.makeEvent_(shaka.util.FakeEvent.EventName.MediaQualityChanged,b))};
shaka.Player.prototype.videoErrorToShakaError_=function(){goog.asserts.assert(this.video_.error,"Video error expected, but missing!");if(!this.video_.error)return null;var a=this.video_.error.code;if(1==a)return null;var b=this.video_.error.msExtendedCode;b&&(0>b&&(b+=Math.pow(2,32)),b=b.toString(16));return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.VIDEO_ERROR,a,b,this.video_.error.message)};
shaka.Player.prototype.onVideoError_=function(a){if(a=this.videoErrorToShakaError_())this.onError_(a)};
shaka.Player.prototype.onKeyStatus_=function(a){if(this.streamingEngine_){var b=Object.keys(a);0==b.length&&shaka.log.warning("Got a key status event without any key statuses, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks.");var c=1==b.length&&"00"==b[0];c&&shaka.log.warning("Got a synthetic key status event, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks.");var d=
shaka.Player.restrictedStatuses_,e=!1;if(b.length){b=$jscomp.makeIterator(this.manifest_.variants);for(var f=b.next();!f.done;f=b.next()){f=f.value;var g=shaka.util.StreamUtils.getVariantStreams(f);g=$jscomp.makeIterator(g);for(var h=g.next();!h.done;h=g.next()){var k=h.value;h=f.allowedByKeySystem;if(k.keyIds.size){f.allowedByKeySystem=!0;k=$jscomp.makeIterator(k.keyIds);for(var l=k.next();!l.done;l=k.next())l=l.value,l=a[c?"00":l],f.allowedByKeySystem=f.allowedByKeySystem&&!!l&&!d.includes(l)}h!=
f.allowedByKeySystem&&(e=!0)}}}if(!e||this.updateAbrManagerVariants_())if((a=this.streamingEngine_.getCurrentVariant())&&!a.allowedByKeySystem&&(shaka.log.debug("Choosing new streams after key status changed"),this.chooseVariantAndSwitch_()),e)this.onTracksChanged_()}};shaka.Player.prototype.onExpirationUpdated_=function(a,b){if(this.parser_&&this.parser_.onExpirationUpdated)this.parser_.onExpirationUpdated(a,b);a=this.makeEvent_(shaka.util.FakeEvent.EventName.ExpirationUpdated);this.dispatchEvent(a)};
shaka.Player.prototype.shouldStreamText_=function(){return this.config_.streaming.alwaysStreamText||this.isTextTrackVisible()};shaka.Player.applyPlayRange_=function(a,b,c){0<b&&(a.isLive()?shaka.log.warning("|playRangeStart| has been configured for live content. Ignoring the setting."):a.setUserSeekStart(b));b=a.getDuration();c<b&&(a.isLive()?shaka.log.warning("|playRangeEnd| has been configured for live content. Ignoring the setting."):a.setDuration(c))};
shaka.Player.prototype.checkRestrictedVariants_=function(a){var b=shaka.Player.restrictedStatuses_,c=this.drmEngine_?this.drmEngine_.getKeyStatuses():{},d=Object.keys(c);d=d.length&&"00"==d[0];var e=!1,f=!1,g=new Set,h=new Set;a=$jscomp.makeIterator(a.variants);for(var k=a.next();!k.done;k=a.next()){k=k.value;var l=[];k.audio&&l.push(k.audio);k.video&&l.push(k.video);l=$jscomp.makeIterator(l);for(var m=l.next();!m.done;m=l.next())if(m=m.value,m.keyIds.size){m=$jscomp.makeIterator(m.keyIds);for(var n=
m.next();!n.done;n=m.next()){n=n.value;var p=c[d?"00":n];p?b.includes(p)&&h.add(p):g.add(n)}}k.allowedByApplication?k.allowedByKeySystem&&(e=!0):f=!0}if(!e)throw b={hasAppRestrictions:f,missingKeys:Array.from(g),restrictedKeyStatuses:Array.from(h)},new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.RESTRICTIONS_CANNOT_BE_MET,b);};
shaka.Player.prototype.checkPlayableVariants_=function(a){if(!a.variants.some(shaka.util.StreamUtils.isPlayable))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.CONTENT_UNSUPPORTED_BY_BROWSER);};
shaka.Player.prototype.delayDispatchEvent_=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return c.yield(Promise.resolve(),2);b.loadMode_!=shaka.Player.LoadMode.DESTROYED&&b.dispatchEvent(a);c.jumpToEnd()})};shaka.Player.getLanguagesFrom_=function(a){var b=new Set;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())c=c.value,c.language?b.add(shaka.util.LanguageUtils.normalize(c.language)):b.add("und");return b};
shaka.Player.getLanguageAndRolesFrom_=function(a){var b=new Map,c=new Map;a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next()){d=d.value;var e="und",f=[];d.language&&(e=shaka.util.LanguageUtils.normalize(d.language));(f="variant"==d.type?d.audioRoles:d.roles)&&f.length||(f=[""]);b.has(e)||b.set(e,new Set);f=$jscomp.makeIterator(f);for(var g=f.next();!g.done;g=f.next())g=g.value,b.get(e).add(g),d.label&&(c.has(e)||c.set(e,new Map),c.get(e).set(g,d.label))}var h=[];b.forEach(function(k,
l){k=$jscomp.makeIterator(k);for(var m=k.next();!m.done;m=k.next()){m=m.value;var n=null;c.has(l)&&c.get(l).has(m)&&(n=c.get(l).get(m));h.push({language:l,role:m,label:n})}});return h};
shaka.Player.prototype.isBufferedToEndMS_=function(){goog.asserts.assert(this.video_,"We need a video element to get buffering information");goog.asserts.assert(this.mediaSourceEngine_,"We need a media source engine to get buffering information");goog.asserts.assert(this.manifest_,"We need a manifest to get buffering information");if(this.video_.ended||this.mediaSourceEngine_.ended())return!0;if(this.manifest_.presentationTimeline.isLive()){var a=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),
b=shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered);if(null!=b&&b>=a)return!0}return!1};shaka.Player.prototype.isBufferedToEndSrc_=function(){goog.asserts.assert(this.video_,"We need a video element to get buffering information");if(this.video_.ended)return!0;var a=shaka.media.TimeRangesUtils.bufferEnd(this.video_.buffered);return null!=a&&a>=this.video_.duration-1};
shaka.Player.prototype.createAbortLoadError_=function(){return new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.LOAD_INTERRUPTED)};
shaka.Player.prototype.getNextStep_=function(a,b,c,d){var e=null;a==this.detachNode_&&(e=c==this.detachNode_?this.detachNode_:this.attachNode_);a==this.attachNode_&&(e=this.getNextAfterAttach_(c,b,d));a==this.mediaSourceNode_&&(e=this.getNextAfterMediaSource_(c,b,d));a==this.parserNode_&&(e=this.getNextMatchingAllDependencies_(this.loadNode_,this.manifestNode_,this.unloadNode_,c,b,d));a==this.manifestNode_&&(e=this.getNextMatchingAllDependencies_(this.loadNode_,this.drmNode_,this.unloadNode_,c,b,
d));a==this.drmNode_&&(e=this.getNextMatchingAllDependencies_(this.loadNode_,this.loadNode_,this.unloadNode_,c,b,d));a==this.srcEqualsDrmNode_&&(e=c==this.srcEqualsNode_&&b.mediaElement==d.mediaElement?this.srcEqualsNode_:this.unloadNode_);if(a==this.loadNode_||a==this.srcEqualsNode_)e=this.unloadNode_;a==this.unloadNode_&&(e=this.getNextAfterUnload_(c,b,d));goog.asserts.assert(e,"Missing next step!");return e};
shaka.Player.prototype.getNextAfterAttach_=function(a,b,c){return a==this.detachNode_||b.mediaElement!=c.mediaElement?this.detachNode_:a==this.attachNode_?this.attachNode_:a==this.mediaSourceNode_||a==this.loadNode_?this.mediaSourceNode_:a==this.srcEqualsNode_?this.srcEqualsDrmNode_:null};shaka.Player.prototype.getNextAfterMediaSource_=function(a,b,c){return a==this.loadNode_&&b.mediaElement==c.mediaElement?this.parserNode_:this.unloadNode_};
shaka.Player.prototype.getNextAfterUnload_=function(a,b,c){return c.mediaElement&&b.mediaElement==c.mediaElement?this.attachNode_:this.detachNode_};shaka.Player.prototype.getNextMatchingAllDependencies_=function(a,b,c,d,e,f){return d==a&&e.mediaElement==f.mediaElement&&e.uri==f.uri&&e.mimeType==f.mimeType?b:c};shaka.Player.createEmptyPayload_=function(){return{mediaElement:null,mimeType:null,startTime:null,startTimeOfLoad:NaN,uri:null}};
shaka.Player.prototype.wrapWalkerListenersWithPromise_=function(a){var b=this;return new Promise(function(c,d){a.onCancel=function(){return d(b.createAbortLoadError_())};a.onEnd=function(){return c()};a.onError=function(e){return d(e)};a.onSkip=function(){return d(b.createAbortLoadError_())}})};goog.exportSymbol("shaka.Player",shaka.Player);goog.exportProperty(shaka.Player.prototype,"setVideoContainer",shaka.Player.prototype.setVideoContainer);
goog.exportProperty(shaka.Player.prototype,"getManifestParserFactory",shaka.Player.prototype.getManifestParserFactory);goog.exportProperty(shaka.Player.prototype,"getManifest",shaka.Player.prototype.getManifest);goog.exportProperty(shaka.Player.prototype,"retryStreaming",shaka.Player.prototype.retryStreaming);goog.exportProperty(shaka.Player.prototype,"setMaxHardwareResolution",shaka.Player.prototype.setMaxHardwareResolution);goog.exportProperty(shaka.Player.prototype,"addChaptersTrack",shaka.Player.prototype.addChaptersTrack);
goog.exportProperty(shaka.Player.prototype,"addThumbnailsTrack",shaka.Player.prototype.addThumbnailsTrack);goog.exportProperty(shaka.Player.prototype,"addTextTrackAsync",shaka.Player.prototype.addTextTrackAsync);goog.exportProperty(shaka.Player.prototype,"getStats",shaka.Player.prototype.getStats);goog.exportProperty(shaka.Player.prototype,"getBufferedInfo",shaka.Player.prototype.getBufferedInfo);goog.exportProperty(shaka.Player.prototype,"getPresentationStartTimeAsDate",shaka.Player.prototype.getPresentationStartTimeAsDate);
goog.exportProperty(shaka.Player.prototype,"getPlayheadTimeAsDate",shaka.Player.prototype.getPlayheadTimeAsDate);goog.exportProperty(shaka.Player.prototype,"setTextTrackVisibility",shaka.Player.prototype.setTextTrackVisibility);goog.exportProperty(shaka.Player.prototype,"getChapters",shaka.Player.prototype.getChapters);goog.exportProperty(shaka.Player.prototype,"getChaptersTracks",shaka.Player.prototype.getChaptersTracks);goog.exportProperty(shaka.Player.prototype,"isTextTrackVisible",shaka.Player.prototype.isTextTrackVisible);
goog.exportProperty(shaka.Player.prototype,"selectVariantsByLabel",shaka.Player.prototype.selectVariantsByLabel);goog.exportProperty(shaka.Player.prototype,"selectTextLanguage",shaka.Player.prototype.selectTextLanguage);goog.exportProperty(shaka.Player.prototype,"selectAudioLanguage",shaka.Player.prototype.selectAudioLanguage);goog.exportProperty(shaka.Player.prototype,"getTextLanguages",shaka.Player.prototype.getTextLanguages);goog.exportProperty(shaka.Player.prototype,"getAudioLanguages",shaka.Player.prototype.getAudioLanguages);
goog.exportProperty(shaka.Player.prototype,"getTextLanguagesAndRoles",shaka.Player.prototype.getTextLanguagesAndRoles);goog.exportProperty(shaka.Player.prototype,"getAudioLanguagesAndRoles",shaka.Player.prototype.getAudioLanguagesAndRoles);goog.exportProperty(shaka.Player.prototype,"selectVariantTrack",shaka.Player.prototype.selectVariantTrack);goog.exportProperty(shaka.Player.prototype,"selectTextTrack",shaka.Player.prototype.selectTextTrack);
goog.exportProperty(shaka.Player.prototype,"getThumbnails",shaka.Player.prototype.getThumbnails);goog.exportProperty(shaka.Player.prototype,"getImageTracks",shaka.Player.prototype.getImageTracks);goog.exportProperty(shaka.Player.prototype,"getTextTracks",shaka.Player.prototype.getTextTracks);goog.exportProperty(shaka.Player.prototype,"getVariantTracks",shaka.Player.prototype.getVariantTracks);goog.exportProperty(shaka.Player.prototype,"cancelTrickPlay",shaka.Player.prototype.cancelTrickPlay);
goog.exportProperty(shaka.Player.prototype,"trickPlay",shaka.Player.prototype.trickPlay);goog.exportProperty(shaka.Player.prototype,"getPlaybackRate",shaka.Player.prototype.getPlaybackRate);goog.exportProperty(shaka.Player.prototype,"isBuffering",shaka.Player.prototype.isBuffering);goog.exportProperty(shaka.Player.prototype,"getKeyStatuses",shaka.Player.prototype.getKeyStatuses);goog.exportProperty(shaka.Player.prototype,"getExpiration",shaka.Player.prototype.getExpiration);
goog.exportProperty(shaka.Player.prototype,"drmInfo",shaka.Player.prototype.drmInfo);goog.exportProperty(shaka.Player.prototype,"keySystem",shaka.Player.prototype.keySystem);goog.exportProperty(shaka.Player.prototype,"goToLive",shaka.Player.prototype.goToLive);goog.exportProperty(shaka.Player.prototype,"seekRange",shaka.Player.prototype.seekRange);goog.exportProperty(shaka.Player.prototype,"isAudioOnly",shaka.Player.prototype.isAudioOnly);
goog.exportProperty(shaka.Player.prototype,"isInProgress",shaka.Player.prototype.isInProgress);goog.exportProperty(shaka.Player.prototype,"isLive",shaka.Player.prototype.isLive);goog.exportProperty(shaka.Player.prototype,"getAdManager",shaka.Player.prototype.getAdManager);goog.exportProperty(shaka.Player.prototype,"getAssetUri",shaka.Player.prototype.getAssetUri);goog.exportProperty(shaka.Player.prototype,"getNetworkingEngine",shaka.Player.prototype.getNetworkingEngine);
goog.exportProperty(shaka.Player.prototype,"getMediaElement",shaka.Player.prototype.getMediaElement);goog.exportProperty(shaka.Player.prototype,"getLoadMode",shaka.Player.prototype.getLoadMode);goog.exportProperty(shaka.Player.prototype,"resetConfiguration",shaka.Player.prototype.resetConfiguration);goog.exportProperty(shaka.Player.prototype,"getBufferFullness",shaka.Player.prototype.getBufferFullness);goog.exportProperty(shaka.Player.prototype,"getConfiguration",shaka.Player.prototype.getConfiguration);
goog.exportProperty(shaka.Player.prototype,"configure",shaka.Player.prototype.configure);goog.exportProperty(shaka.Player.prototype,"load",shaka.Player.prototype.load);goog.exportProperty(shaka.Player.prototype,"updateStartTime",shaka.Player.prototype.updateStartTime);goog.exportProperty(shaka.Player.prototype,"unload",shaka.Player.prototype.unload);goog.exportProperty(shaka.Player.prototype,"detach",shaka.Player.prototype.detach);goog.exportProperty(shaka.Player.prototype,"attachCanvas",shaka.Player.prototype.attachCanvas);
goog.exportProperty(shaka.Player.prototype,"attach",shaka.Player.prototype.attach);goog.exportProperty(shaka.Player,"probeSupport",shaka.Player.probeSupport);goog.exportProperty(shaka.Player,"isBrowserSupported",shaka.Player.isBrowserSupported);goog.exportProperty(shaka.Player,"setAdManagerFactory",shaka.Player.setAdManagerFactory);goog.exportProperty(shaka.Player,"registerSupportPlugin",shaka.Player.registerSupportPlugin);goog.exportProperty(shaka.Player.prototype,"destroy",shaka.Player.prototype.destroy);
shaka.Player.LoadMode={DESTROYED:0,NOT_LOADED:1,MEDIA_SOURCE:2,SRC_EQUALS:3};goog.exportProperty(shaka.Player,"LoadMode",shaka.Player.LoadMode);shaka.Player.TYPICAL_BUFFERING_THRESHOLD_=.5;shaka.Player.version="v4.3.5-debug";goog.exportProperty(shaka.Player,"version",shaka.Player.version);shaka.Deprecate.init(shaka.Player.version);shaka.Player.restrictedStatuses_=["output-restricted","internal-error"];shaka.Player.supportPlugins_={};shaka.Player.adManagerFactory_=null;
shaka.Player.SRC_EQUAL_EXTENSIONS_TO_MIME_TYPES_={mp4:"video/mp4",m4v:"video/mp4",m4a:"audio/mp4",webm:"video/webm",weba:"audio/webm",mkv:"video/webm",ts:"video/mp2t",ogv:"video/ogg",ogg:"audio/ogg",mpg:"video/mpeg",mpeg:"video/mpeg",m3u8:"application/x-mpegurl",mpd:"application/dash+xml",mp3:"audio/mpeg",aac:"audio/aac",flac:"audio/flac",wav:"audio/wav"};
shaka.Player.TEXT_EXTENSIONS_TO_MIME_TYPES_={sbv:"text/x-subviewer",srt:"text/srt",vtt:"text/vtt",webvtt:"text/vtt",ttml:"application/ttml+xml",lrc:"application/x-subtitle-lrc",ssa:"text/x-ssa",ass:"text/x-ssa"};shaka.Player.TextTrackLabel="Shaka Player TextTrack";shaka.ads={};shaka.ads.AdsStats=function(){this.loadTimes_=[];this.skipped_=this.playedCompletely_=this.started_=0};shaka.ads.AdsStats.prototype.addLoadTime=function(a){this.loadTimes_.push(a)};shaka.ads.AdsStats.prototype.incrementStarted=function(){this.started_++};shaka.ads.AdsStats.prototype.incrementPlayedCompletely=function(){this.playedCompletely_++};shaka.ads.AdsStats.prototype.incrementSkipped=function(){this.skipped_++};
shaka.ads.AdsStats.prototype.getBlob=function(){return{loadTimes:this.loadTimes_,started:this.started_,playedCompletely:this.playedCompletely_,skipped:this.skipped_}};shaka.ads.ClientSideAd=function(a,b,c){var d=this;this.ad_=a;this.manager_=b;this.video_=c;this.isPaused_=!1;this.volume_=this.manager_.getVolume();this.eventManager_=new shaka.util.EventManager;this.eventManager_.listen(this.manager_,google.ima.AdEvent.Type.PAUSED,function(){d.isPaused_=!0});this.eventManager_.listen(this.manager_,google.ima.AdEvent.Type.RESUMED,function(){d.isPaused_=!1})};shaka.ads.ClientSideAd.prototype.getDuration=function(){return this.ad_.getDuration()};
shaka.ads.ClientSideAd.prototype.getMinSuggestedDuration=function(){return this.ad_.getMinSuggestedDuration()};shaka.ads.ClientSideAd.prototype.getRemainingTime=function(){return this.manager_.getRemainingTime()};shaka.ads.ClientSideAd.prototype.isPaused=function(){return this.isPaused_};shaka.ads.ClientSideAd.prototype.isSkippable=function(){return 0<=this.ad_.getSkipTimeOffset()};
shaka.ads.ClientSideAd.prototype.getTimeUntilSkippable=function(){var a=this.ad_.getSkipTimeOffset();a=this.getRemainingTime()-a;return Math.max(a,0)};shaka.ads.ClientSideAd.prototype.canSkipNow=function(){return this.manager_.getAdSkippableState()};shaka.ads.ClientSideAd.prototype.skip=function(){return this.manager_.skip()};shaka.ads.ClientSideAd.prototype.setPaused=function(a){this.isPaused_=a};shaka.ads.ClientSideAd.prototype.pause=function(){return this.manager_.pause()};
shaka.ads.ClientSideAd.prototype.play=function(){return this.manager_.resume()};shaka.ads.ClientSideAd.prototype.getVolume=function(){return this.manager_.getVolume()};shaka.ads.ClientSideAd.prototype.setVolume=function(a){return this.manager_.setVolume(a)};shaka.ads.ClientSideAd.prototype.isMuted=function(){return 0==this.manager_.getVolume()};shaka.ads.ClientSideAd.prototype.isLinear=function(){return this.ad_.isLinear()};
shaka.ads.ClientSideAd.prototype.resize=function(a,b){var c=!1,d=this.video_;document.fullscreenEnabled?c=!!document.fullscreenElement:d.webkitSupportsFullscreen&&(c=d.webkitDisplayingFullscreen);this.manager_.resize(a,b,c?google.ima.ViewMode.FULLSCREEN:google.ima.ViewMode.NORMAL)};shaka.ads.ClientSideAd.prototype.setMuted=function(a){a?(this.volume_=this.getVolume(),this.setVolume(0)):this.setVolume(this.volume_)};
shaka.ads.ClientSideAd.prototype.getSequenceLength=function(){var a=this.ad_.getAdPodInfo();return null==a?1:a.getTotalAds()};shaka.ads.ClientSideAd.prototype.getPositionInSequence=function(){var a=this.ad_.getAdPodInfo();return null==a?1:a.getAdPosition()};shaka.ads.ClientSideAd.prototype.getTitle=function(){return this.ad_.getTitle()};shaka.ads.ClientSideAd.prototype.getDescription=function(){return this.ad_.getDescription()};
shaka.ads.ClientSideAd.prototype.release=function(){this.manager_=this.ad_=null};goog.exportSymbol("shaka.ads.ClientSideAd",shaka.ads.ClientSideAd);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"release",shaka.ads.ClientSideAd.prototype.release);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getDescription",shaka.ads.ClientSideAd.prototype.getDescription);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getTitle",shaka.ads.ClientSideAd.prototype.getTitle);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getPositionInSequence",shaka.ads.ClientSideAd.prototype.getPositionInSequence);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getSequenceLength",shaka.ads.ClientSideAd.prototype.getSequenceLength);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"setMuted",shaka.ads.ClientSideAd.prototype.setMuted);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"resize",shaka.ads.ClientSideAd.prototype.resize);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isLinear",shaka.ads.ClientSideAd.prototype.isLinear);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isMuted",shaka.ads.ClientSideAd.prototype.isMuted);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"setVolume",shaka.ads.ClientSideAd.prototype.setVolume);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getVolume",shaka.ads.ClientSideAd.prototype.getVolume);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"play",shaka.ads.ClientSideAd.prototype.play);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"pause",shaka.ads.ClientSideAd.prototype.pause);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"skip",shaka.ads.ClientSideAd.prototype.skip);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"canSkipNow",shaka.ads.ClientSideAd.prototype.canSkipNow);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getTimeUntilSkippable",shaka.ads.ClientSideAd.prototype.getTimeUntilSkippable);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isSkippable",shaka.ads.ClientSideAd.prototype.isSkippable);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"isPaused",shaka.ads.ClientSideAd.prototype.isPaused);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getRemainingTime",shaka.ads.ClientSideAd.prototype.getRemainingTime);goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getMinSuggestedDuration",shaka.ads.ClientSideAd.prototype.getMinSuggestedDuration);
goog.exportProperty(shaka.ads.ClientSideAd.prototype,"getDuration",shaka.ads.ClientSideAd.prototype.getDuration);shaka.ads.ClientSideAdManager=function(a,b,c,d){var e=this;this.adContainer_=a;this.video_=b;this.resizeObserver_=null;this.requestAdsStartTime_=NaN;this.onEvent_=d;this.ad_=null;this.eventManager_=new shaka.util.EventManager;google.ima.settings.setLocale(c);a=new google.ima.AdDisplayContainer(this.adContainer_,this.video_);a.initialize();this.adsLoader_=new google.ima.AdsLoader(a);this.adsLoader_.getSettings().setPlayerType("shaka-player");this.adsLoader_.getSettings().setPlayerVersion(shaka.Player.version);
this.imaAdsManager_=null;this.eventManager_.listenOnce(this.adsLoader_,google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,function(f){e.onAdsManagerLoaded_(f)});this.eventManager_.listen(this.adsLoader_,google.ima.AdErrorEvent.Type.AD_ERROR,function(f){e.onAdError_(f)});this.eventManager_.listen(this.video_,"ended",function(){e.adsLoader_.contentComplete()})};
shaka.ads.ClientSideAdManager.prototype.requestAds=function(a){goog.asserts.assert(a.adTagUrl||a.adsResponse,"The ad tag needs to be set up before requesting ads, or adsResponse must be filled.");this.requestAdsStartTime_=Date.now()/1E3;this.adsLoader_.requestAds(a)};shaka.ads.ClientSideAdManager.prototype.stop=function(){this.imaAdsManager_&&this.imaAdsManager_.stop();this.adContainer_&&shaka.util.Dom.removeAllChildren(this.adContainer_)};
shaka.ads.ClientSideAdManager.prototype.release=function(){this.stop();this.resizeObserver_&&this.resizeObserver_.disconnect();this.eventManager_&&this.eventManager_.release();this.imaAdsManager_&&this.imaAdsManager_.destroy();this.adsLoader_.destroy()};
shaka.ads.ClientSideAdManager.prototype.onAdError_=function(a){shaka.log.warning("There was an ad error from the IMA SDK: "+a.getError());shaka.log.warning("Resuming playback.");this.onAdComplete_(null);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.CUEPOINTS_CHANGED,(new Map).set("cuepoints",[])))};
shaka.ads.ClientSideAdManager.prototype.onAdsManagerLoaded_=function(a){var b=this;goog.asserts.assert(null!=this.video_,"Video should not be null!");var c=Date.now()/1E3-this.requestAdsStartTime_;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.ADS_LOADED,(new Map).set("loadTime",c)));this.imaAdsManager_=a.getAdsManager(this.video_);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.IMA_AD_MANAGER_LOADED,(new Map).set("imaAdManager",this.imaAdsManager_)));c=this.imaAdsManager_.getCuePoints();
if(c.length){a=[];c=$jscomp.makeIterator(c);for(var d=c.next();!d.done;d=c.next())a.push({start:d.value,end:null});this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.CUEPOINTS_CHANGED,(new Map).set("cuepoints",a)))}this.addImaEventListeners_();try{var e=this.isFullScreenEnabled_()?google.ima.ViewMode.FULLSCREEN:google.ima.ViewMode.NORMAL;this.imaAdsManager_.init(this.video_.offsetWidth,this.video_.offsetHeight,e);this.eventManager_.listen(this.video_,"loadeddata",function(){var f=b.isFullScreenEnabled_()?
google.ima.ViewMode.FULLSCREEN:google.ima.ViewMode.NORMAL;b.imaAdsManager_.resize(b.video_.offsetWidth,b.video_.offsetHeight,f)});"ResizeObserver"in window?(this.resizeObserver_=new ResizeObserver(function(){var f=b.isFullScreenEnabled_()?google.ima.ViewMode.FULLSCREEN:google.ima.ViewMode.NORMAL;b.imaAdsManager_.resize(b.video_.offsetWidth,b.video_.offsetHeight,f)}),this.resizeObserver_.observe(this.video_)):this.eventManager_.listen(document,"fullscreenchange",function(){var f=b.isFullScreenEnabled_()?
google.ima.ViewMode.FULLSCREEN:google.ima.ViewMode.NORMAL;b.imaAdsManager_.resize(b.video_.offsetWidth,b.video_.offsetHeight,f)});this.video_.addEventListener("play",function(){b.imaAdsManager_.start()},{once:!0})}catch(f){this.onAdComplete_(null)}};shaka.ads.ClientSideAdManager.prototype.isFullScreenEnabled_=function(){if(document.fullscreenEnabled)return!!document.fullscreenElement;var a=this.video_;return a.webkitSupportsFullscreen?a.webkitDisplayingFullscreen:!1};
shaka.ads.ClientSideAdManager.prototype.addImaEventListeners_=function(){var a=this,b=function(c,d){c=(new Map).set("originalEvent",c);a.onEvent_(new shaka.util.FakeEvent(d,c))};this.eventManager_.listen(this.imaAdsManager_,google.ima.AdErrorEvent.Type.AD_ERROR,function(c){a.onAdError_(c)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,function(c){a.onAdStart_(c)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.STARTED,function(c){a.onAdStart_(c)});
this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.FIRST_QUARTILE,function(c){b(c,shaka.ads.AdManager.AD_FIRST_QUARTILE)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.MIDPOINT,function(c){b(c,shaka.ads.AdManager.AD_MIDPOINT)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.THIRD_QUARTILE,function(c){b(c,shaka.ads.AdManager.AD_THIRD_QUARTILE)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.COMPLETE,function(c){b(c,
shaka.ads.AdManager.AD_COMPLETE)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,function(c){a.onAdComplete_(c)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.ALL_ADS_COMPLETED,function(c){a.onAdComplete_(c)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.SKIPPED,function(c){b(c,shaka.ads.AdManager.AD_SKIPPED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.VOLUME_CHANGED,function(c){b(c,
shaka.ads.AdManager.AD_VOLUME_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.VOLUME_MUTED,function(c){b(c,shaka.ads.AdManager.AD_MUTED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.PAUSED,function(c){a.ad_&&(a.ad_.setPaused(!0),b(c,shaka.ads.AdManager.AD_PAUSED))});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.RESUMED,function(c){a.ad_&&(a.ad_.setPaused(!1),b(c,shaka.ads.AdManager.AD_RESUMED))});this.eventManager_.listen(this.imaAdsManager_,
google.ima.AdEvent.Type.SKIPPABLE_STATE_CHANGED,function(c){a.ad_&&b(c,shaka.ads.AdManager.AD_SKIP_STATE_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.CLICK,function(c){b(c,shaka.ads.AdManager.AD_CLICKED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_PROGRESS,function(c){b(c,shaka.ads.AdManager.AD_PROGRESS)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_BUFFERING,function(c){b(c,shaka.ads.AdManager.AD_BUFFERING)});
this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.IMPRESSION,function(c){b(c,shaka.ads.AdManager.AD_IMPRESSION)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.DURATION_CHANGE,function(c){b(c,shaka.ads.AdManager.AD_DURATION_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.USER_CLOSE,function(c){b(c,shaka.ads.AdManager.AD_CLOSED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.LOADED,function(c){b(c,
shaka.ads.AdManager.AD_LOADED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.ALL_ADS_COMPLETED,function(c){b(c,shaka.ads.AdManager.ALL_ADS_COMPLETED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.LINEAR_CHANGED,function(c){b(c,shaka.ads.AdManager.AD_LINEAR_CHANGED)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_METADATA,function(c){b(c,shaka.ads.AdManager.AD_METADATA)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.LOG,
function(c){b(c,shaka.ads.AdManager.AD_RECOVERABLE_ERROR)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.AD_BREAK_READY,function(c){b(c,shaka.ads.AdManager.AD_BREAK_READY)});this.eventManager_.listen(this.imaAdsManager_,google.ima.AdEvent.Type.INTERACTION,function(c){b(c,shaka.ads.AdManager.AD_INTERACTION)})};
shaka.ads.ClientSideAdManager.prototype.onAdStart_=function(a){goog.asserts.assert(this.imaAdsManager_,"Should have an ads manager at this point!");var b=a.getAd();b?(this.ad_=new shaka.ads.ClientSideAd(b,this.imaAdsManager_,this.video_),a=(new Map).set("ad",this.ad_).set("sdkAdObject",b).set("originalEvent",a),this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_STARTED,a)),this.ad_.isLinear()&&(this.adContainer_.setAttribute("ad-active","true"),this.video_.pause(),this.ad_.setVolume(this.video_.muted?
0:this.video_.volume))):shaka.log.alwaysWarn("The IMA SDK fired a "+a.type+" event with no associated ad. Unable to play ad!")};shaka.ads.ClientSideAdManager.prototype.onAdComplete_=function(a){this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_STOPPED,(new Map).set("originalEvent",a)));this.ad_&&this.ad_.isLinear()&&(this.adContainer_.removeAttribute("ad-active"),this.video_.ended||this.video_.play())};shaka.ads.ServerSideAd=function(a,b){this.ad_=a;this.adProgressData_=null;this.video_=b};shaka.ads.ServerSideAd.prototype.setProgressData=function(a){this.adProgressData_=a};shaka.ads.ServerSideAd.prototype.getDuration=function(){return this.adProgressData_?this.adProgressData_.duration:-1};shaka.ads.ServerSideAd.prototype.getMinSuggestedDuration=function(){return this.getDuration()};
shaka.ads.ServerSideAd.prototype.getRemainingTime=function(){return this.adProgressData_?this.adProgressData_.duration-this.adProgressData_.currentTime:-1};shaka.ads.ServerSideAd.prototype.isPaused=function(){return this.video_.paused};shaka.ads.ServerSideAd.prototype.isSkippable=function(){return this.ad_.isSkippable()};shaka.ads.ServerSideAd.prototype.getTimeUntilSkippable=function(){var a=this.ad_.getSkipTimeOffset();a=this.getRemainingTime()-a;return Math.max(a,0)};
shaka.ads.ServerSideAd.prototype.canSkipNow=function(){return 0==this.getTimeUntilSkippable()};shaka.ads.ServerSideAd.prototype.skip=function(){this.video_.currentTime+=this.getRemainingTime()};shaka.ads.ServerSideAd.prototype.pause=function(){return this.video_.pause()};shaka.ads.ServerSideAd.prototype.play=function(){return this.video_.play()};shaka.ads.ServerSideAd.prototype.getVolume=function(){return this.video_.volume};
shaka.ads.ServerSideAd.prototype.setVolume=function(a){this.video_.volume=a};shaka.ads.ServerSideAd.prototype.isMuted=function(){return this.video_.muted};shaka.ads.ServerSideAd.prototype.isLinear=function(){return!0};shaka.ads.ServerSideAd.prototype.resize=function(a,b){};shaka.ads.ServerSideAd.prototype.setMuted=function(a){this.video_.muted=a};shaka.ads.ServerSideAd.prototype.getSequenceLength=function(){var a=this.ad_.getAdPodInfo();return null==a?1:a.getTotalAds()};
shaka.ads.ServerSideAd.prototype.getPositionInSequence=function(){var a=this.ad_.getAdPodInfo();return null==a?1:a.getAdPosition()};shaka.ads.ServerSideAd.prototype.getTitle=function(){return this.ad_.getTitle()};shaka.ads.ServerSideAd.prototype.getDescription=function(){return this.ad_.getDescription()};shaka.ads.ServerSideAd.prototype.release=function(){this.video_=this.adProgressData_=this.ad_=null};goog.exportSymbol("shaka.ads.ServerSideAd",shaka.ads.ServerSideAd);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"release",shaka.ads.ServerSideAd.prototype.release);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getDescription",shaka.ads.ServerSideAd.prototype.getDescription);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getTitle",shaka.ads.ServerSideAd.prototype.getTitle);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getPositionInSequence",shaka.ads.ServerSideAd.prototype.getPositionInSequence);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getSequenceLength",shaka.ads.ServerSideAd.prototype.getSequenceLength);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"setMuted",shaka.ads.ServerSideAd.prototype.setMuted);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"resize",shaka.ads.ServerSideAd.prototype.resize);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isLinear",shaka.ads.ServerSideAd.prototype.isLinear);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isMuted",shaka.ads.ServerSideAd.prototype.isMuted);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"setVolume",shaka.ads.ServerSideAd.prototype.setVolume);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getVolume",shaka.ads.ServerSideAd.prototype.getVolume);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"play",shaka.ads.ServerSideAd.prototype.play);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"pause",shaka.ads.ServerSideAd.prototype.pause);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"skip",shaka.ads.ServerSideAd.prototype.skip);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"canSkipNow",shaka.ads.ServerSideAd.prototype.canSkipNow);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getTimeUntilSkippable",shaka.ads.ServerSideAd.prototype.getTimeUntilSkippable);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isSkippable",shaka.ads.ServerSideAd.prototype.isSkippable);
goog.exportProperty(shaka.ads.ServerSideAd.prototype,"isPaused",shaka.ads.ServerSideAd.prototype.isPaused);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getRemainingTime",shaka.ads.ServerSideAd.prototype.getRemainingTime);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getMinSuggestedDuration",shaka.ads.ServerSideAd.prototype.getMinSuggestedDuration);goog.exportProperty(shaka.ads.ServerSideAd.prototype,"getDuration",shaka.ads.ServerSideAd.prototype.getDuration);shaka.ads.ServerSideAdManager=function(a,b,c,d){var e=this;this.adContainer_=a;this.video_=b;this.streamPromise_=null;this.streamRequestStartTime_=NaN;this.onEvent_=d;this.isLiveContent_=!1;this.adProgressData_=this.ad_=this.snapForwardTime_=null;this.backupUrl_="";this.currentCuePoints_=[];this.eventManager_=new shaka.util.EventManager;a=new google.ima.dai.api.UiSettings;a.setLocale(c);this.streamManager_=new google.ima.dai.api.StreamManager(this.video_,this.adContainer_,a);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.IMA_STREAM_MANAGER_LOADED,
(new Map).set("imaStreamManager",this.streamManager_)));this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.LOADED,function(f){shaka.log.info("Ad SS Loaded");e.onLoaded_(f)});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.ERROR,function(){shaka.log.info("Ad SS Error");e.onError_()});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.AD_BREAK_STARTED,function(){shaka.log.info("Ad Break Started")});this.eventManager_.listen(this.streamManager_,
google.ima.dai.api.StreamEvent.Type.STARTED,function(f){shaka.log.info("Ad Started");e.onAdStart_(f)});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.AD_BREAK_ENDED,function(){shaka.log.info("Ad Break Ended");e.onAdBreakEnded_()});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.AD_PROGRESS,function(f){e.onAdProgress_(f)});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.FIRST_QUARTILE,function(){shaka.log.info("Ad event: First Quartile");
e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_FIRST_QUARTILE))});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.MIDPOINT,function(){shaka.log.info("Ad event: Midpoint");e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_MIDPOINT))});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.THIRD_QUARTILE,function(){shaka.log.info("Ad event: Third Quartile");e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_THIRD_QUARTILE))});
this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.COMPLETE,function(){shaka.log.info("Ad event: Complete");e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_COMPLETE));e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_STOPPED));e.adContainer_.removeAttribute("ad-active");e.ad_=null});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.SKIPPED,function(){shaka.log.info("Ad event: Skipped");e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_SKIPPED));
e.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_STOPPED))});this.eventManager_.listen(this.streamManager_,google.ima.dai.api.StreamEvent.Type.CUEPOINTS_CHANGED,function(f){shaka.log.info("Ad event: Cue points changed");e.onCuePointsChanged_(f)})};
shaka.ads.ServerSideAdManager.prototype.streamRequest=function(a,b){if(this.streamPromise_)return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CURRENT_DAI_REQUEST_NOT_FINISHED));a instanceof google.ima.dai.api.LiveStreamRequest&&(this.isLiveContent_=!0);this.streamPromise_=new shaka.util.PublicPromise;this.streamManager_.requestStream(a);this.backupUrl_=b||"";this.streamRequestStartTime_=Date.now()/1E3;return this.streamPromise_};
shaka.ads.ServerSideAdManager.prototype.replaceAdTagParameters=function(a){this.streamManager_.replaceAdTagParameters(a)};shaka.ads.ServerSideAdManager.prototype.stop=function(){this.backupUrl_="";this.snapForwardTime_=null;this.currentCuePoints_=[]};shaka.ads.ServerSideAdManager.prototype.release=function(){this.stop();this.eventManager_&&this.eventManager_.release()};shaka.ads.ServerSideAdManager.prototype.onTimedMetadata=function(a,b,c){this.streamManager_.processMetadata(a,b,c)};
shaka.ads.ServerSideAdManager.prototype.onCueMetadataChange=function(a){if(a.key&&a.data){var b={};b[a.key]=a.data;this.streamManager_.onTimedMetadata(b)}};shaka.ads.ServerSideAdManager.prototype.getCuePoints=function(){return this.currentCuePoints_};
shaka.ads.ServerSideAdManager.prototype.checkForSnapback_=function(){var a=this.video_.currentTime;if(0!=a){this.streamManager_.streamTimeForContentTime(a);var b=this.streamManager_.previousCuePointForStreamTime(a);b&&!b.played&&(shaka.log.info("Seeking back to the start of the ad break at "+b.start+" and will return to "+a),this.snapForwardTime_=a,this.video_.currentTime=b.start)}};
shaka.ads.ServerSideAdManager.prototype.onAdStart_=function(a){goog.asserts.assert(this.streamManager_,"Should have a stream manager at this point!");a=a.getAd();this.ad_=new shaka.ads.ServerSideAd(a,this.video_);this.adProgressData_&&this.ad_.setProgressData(this.adProgressData_);this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_STARTED,(new Map).set("ad",this.ad_)));this.adContainer_.setAttribute("ad-active","true")};
shaka.ads.ServerSideAdManager.prototype.onAdBreakEnded_=function(){this.adContainer_.removeAttribute("ad-active");var a=this.video_.currentTime;this.snapForwardTime_&&this.snapForwardTime_>a&&(this.video_.currentTime=this.snapForwardTime_,this.snapForwardTime_=null)};
shaka.ads.ServerSideAdManager.prototype.onLoaded_=function(a){var b=this,c=Date.now()/1E3-this.streamRequestStartTime_;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.ADS_LOADED,(new Map).set("loadTime",c)));a=a.getStreamData().url;this.streamPromise_.resolve(a);this.streamPromise_=null;this.isLiveContent_||this.eventManager_.listen(this.video_,"seeked",function(){b.checkForSnapback_()})};
shaka.ads.ServerSideAdManager.prototype.onError_=function(){this.backupUrl_.length?(shaka.log.warning("IMA stream request returned an error. Falling back to the backup asset uri."),this.streamPromise_.resolve(this.backupUrl_)):this.streamPromise_.reject("IMA Stream request returned an error and there was no backup asset uri provided.");this.streamPromise_=null};shaka.ads.ServerSideAdManager.prototype.onAdProgress_=function(a){this.adProgressData_=a.getStreamData().adProgressData;this.ad_&&this.ad_.setProgressData(this.adProgressData_)};
shaka.ads.ServerSideAdManager.prototype.onCuePointsChanged_=function(a){var b=a.getStreamData();a=[];b=$jscomp.makeIterator(b.cuepoints);for(var c=b.next();!c.done;c=b.next())c=c.value,a.push({start:c.start,end:c.end});this.currentCuePoints_=a;this.onEvent_(new shaka.util.FakeEvent(shaka.ads.AdManager.CUEPOINTS_CHANGED,(new Map).set("cuepoints",a)))};shaka.ads.AdManager=function(){shaka.util.FakeEventTarget.call(this);this.ssAdManager_=this.csAdManager_=null;this.stats_=new shaka.ads.AdsStats;this.locale_=navigator.language};$jscomp.inherits(shaka.ads.AdManager,shaka.util.FakeEventTarget);shaka.ads.AdManager.prototype.setLocale=function(a){this.locale_=a};
shaka.ads.AdManager.prototype.initClientSide=function(a,b){var c=this;if(!window.google||!google.ima||!google.ima.AdsLoader)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CS_IMA_SDK_MISSING);this.csAdManager_&&this.csAdManager_.release();this.csAdManager_=new shaka.ads.ClientSideAdManager(a,b,this.locale_,function(d){if(d&&d.type)switch(d.type){case shaka.ads.AdManager.ADS_LOADED:c.stats_.addLoadTime(d.loadTime);break;case shaka.ads.AdManager.AD_STARTED:c.stats_.incrementStarted();
break;case shaka.ads.AdManager.AD_COMPLETE:c.stats_.incrementPlayedCompletely();break;case shaka.ads.AdManager.AD_SKIPPED:c.stats_.incrementSkipped()}c.dispatchEvent(d)})};shaka.ads.AdManager.prototype.release=function(){this.csAdManager_&&(this.csAdManager_.release(),this.csAdManager_=null);this.ssAdManager_&&(this.ssAdManager_.release(),this.ssAdManager_=null);shaka.util.FakeEventTarget.prototype.release.call(this)};
shaka.ads.AdManager.prototype.onAssetUnload=function(){this.csAdManager_&&this.csAdManager_.stop();this.ssAdManager_&&this.ssAdManager_.stop();this.dispatchEvent(new shaka.util.FakeEvent(shaka.ads.AdManager.AD_STOPPED));this.stats_=new shaka.ads.AdsStats};shaka.ads.AdManager.prototype.requestClientSideAds=function(a){if(!this.csAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.CS_AD_MANAGER_NOT_INITIALIZED);this.csAdManager_.requestAds(a)};
shaka.ads.AdManager.prototype.initServerSide=function(a,b){var c=this;if(!window.google||!google.ima||!google.ima.dai)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_IMA_SDK_MISSING);this.ssAdManager_&&this.ssAdManager_.release();this.ssAdManager_=new shaka.ads.ServerSideAdManager(a,b,this.locale_,function(d){if(d&&d.type)switch(d.type){case shaka.ads.AdManager.ADS_LOADED:c.stats_.addLoadTime(d.loadTime);break;case shaka.ads.AdManager.AD_STARTED:c.stats_.incrementStarted();
break;case shaka.ads.AdManager.AD_COMPLETE:c.stats_.incrementPlayedCompletely();break;case shaka.ads.AdManager.AD_SKIPPED:c.stats_.incrementSkipped()}c.dispatchEvent(d)})};
shaka.ads.AdManager.prototype.requestServerSideStream=function(a,b){b=void 0===b?"":b;if(!this.ssAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_AD_MANAGER_NOT_INITIALIZED);a.adTagParameters||(a.adTagParameters={});var c=a.adTagParameters;(c.mpt||c.mpv)&&shaka.log.alwaysWarn('You have attempted to set "mpt" and/or "mpv" parameters of the ad tag. Please note that those parameters are used for Shaka adoption tracking and will be overriden.');
a.adTagParameters.mpt="shaka-player";a.adTagParameters.mpv=shaka.Player.version;return this.ssAdManager_.streamRequest(a,b)};
shaka.ads.AdManager.prototype.replaceServerSideAdTagParameters=function(a){if(!this.ssAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_AD_MANAGER_NOT_INITIALIZED);(a.mpt||a.mpv)&&shaka.log.alwaysWarn('You have attempted to set "mpt" and/or "mpv" parameters of the ad tag. Please note that those parameters are used for Shaka adoption tracking and will be overriden.');a.mpt="Shaka Player";a.mpv=shaka.Player.version;this.ssAdManager_.replaceAdTagParameters(a)};
shaka.ads.AdManager.prototype.getServerSideCuePoints=function(){if(!this.ssAdManager_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.ADS,shaka.util.Error.Code.SS_AD_MANAGER_NOT_INITIALIZED);return this.ssAdManager_.getCuePoints()};shaka.ads.AdManager.prototype.getStats=function(){return this.stats_.getBlob()};
shaka.ads.AdManager.prototype.onDashTimedMetadata=function(a){if(this.ssAdManager_&&"urn:google:dai:2018"==a.schemeIdUri){var b=a.schemeIdUri,c=a.eventElement?a.eventElement.getAttribute("messageData"):null;this.ssAdManager_.onTimedMetadata(b,c,a.startTime)}};shaka.ads.AdManager.prototype.onHlsTimedMetadata=function(a,b){if(this.ssAdManager_)this.ssAdManager_.onTimedMetadata("ID3",a.data,b)};shaka.ads.AdManager.prototype.onCueMetadataChange=function(a){if(this.ssAdManager_)this.ssAdManager_.onCueMetadataChange(a)};
goog.exportSymbol("shaka.ads.AdManager",shaka.ads.AdManager);goog.exportProperty(shaka.ads.AdManager.prototype,"onCueMetadataChange",shaka.ads.AdManager.prototype.onCueMetadataChange);goog.exportProperty(shaka.ads.AdManager.prototype,"onHlsTimedMetadata",shaka.ads.AdManager.prototype.onHlsTimedMetadata);goog.exportProperty(shaka.ads.AdManager.prototype,"onDashTimedMetadata",shaka.ads.AdManager.prototype.onDashTimedMetadata);goog.exportProperty(shaka.ads.AdManager.prototype,"getStats",shaka.ads.AdManager.prototype.getStats);
goog.exportProperty(shaka.ads.AdManager.prototype,"getServerSideCuePoints",shaka.ads.AdManager.prototype.getServerSideCuePoints);goog.exportProperty(shaka.ads.AdManager.prototype,"replaceServerSideAdTagParameters",shaka.ads.AdManager.prototype.replaceServerSideAdTagParameters);goog.exportProperty(shaka.ads.AdManager.prototype,"requestServerSideStream",shaka.ads.AdManager.prototype.requestServerSideStream);goog.exportProperty(shaka.ads.AdManager.prototype,"initServerSide",shaka.ads.AdManager.prototype.initServerSide);
goog.exportProperty(shaka.ads.AdManager.prototype,"requestClientSideAds",shaka.ads.AdManager.prototype.requestClientSideAds);goog.exportProperty(shaka.ads.AdManager.prototype,"onAssetUnload",shaka.ads.AdManager.prototype.onAssetUnload);goog.exportProperty(shaka.ads.AdManager.prototype,"release",shaka.ads.AdManager.prototype.release);goog.exportProperty(shaka.ads.AdManager.prototype,"initClientSide",shaka.ads.AdManager.prototype.initClientSide);
goog.exportProperty(shaka.ads.AdManager.prototype,"setLocale",shaka.ads.AdManager.prototype.setLocale);shaka.ads.AdManager.ADS_LOADED="ads-loaded";goog.exportProperty(shaka.ads.AdManager,"ADS_LOADED",shaka.ads.AdManager.ADS_LOADED);shaka.ads.AdManager.AD_STARTED="ad-started";goog.exportProperty(shaka.ads.AdManager,"AD_STARTED",shaka.ads.AdManager.AD_STARTED);shaka.ads.AdManager.AD_FIRST_QUARTILE="ad-first-quartile";goog.exportProperty(shaka.ads.AdManager,"AD_FIRST_QUARTILE",shaka.ads.AdManager.AD_FIRST_QUARTILE);
shaka.ads.AdManager.AD_MIDPOINT="ad-midpoint";goog.exportProperty(shaka.ads.AdManager,"AD_MIDPOINT",shaka.ads.AdManager.AD_MIDPOINT);shaka.ads.AdManager.AD_THIRD_QUARTILE="ad-third-quartile";goog.exportProperty(shaka.ads.AdManager,"AD_THIRD_QUARTILE",shaka.ads.AdManager.AD_THIRD_QUARTILE);shaka.ads.AdManager.AD_COMPLETE="ad-complete";goog.exportProperty(shaka.ads.AdManager,"AD_COMPLETE",shaka.ads.AdManager.AD_COMPLETE);shaka.ads.AdManager.AD_STOPPED="ad-stopped";
goog.exportProperty(shaka.ads.AdManager,"AD_STOPPED",shaka.ads.AdManager.AD_STOPPED);shaka.ads.AdManager.AD_SKIPPED="ad-skipped";goog.exportProperty(shaka.ads.AdManager,"AD_SKIPPED",shaka.ads.AdManager.AD_SKIPPED);shaka.ads.AdManager.AD_VOLUME_CHANGED="ad-volume-changed";goog.exportProperty(shaka.ads.AdManager,"AD_VOLUME_CHANGED",shaka.ads.AdManager.AD_VOLUME_CHANGED);shaka.ads.AdManager.AD_MUTED="ad-muted";goog.exportProperty(shaka.ads.AdManager,"AD_MUTED",shaka.ads.AdManager.AD_MUTED);
shaka.ads.AdManager.AD_PAUSED="ad-paused";goog.exportProperty(shaka.ads.AdManager,"AD_PAUSED",shaka.ads.AdManager.AD_PAUSED);shaka.ads.AdManager.AD_RESUMED="ad-resumed";goog.exportProperty(shaka.ads.AdManager,"AD_RESUMED",shaka.ads.AdManager.AD_RESUMED);shaka.ads.AdManager.AD_SKIP_STATE_CHANGED="ad-skip-state-changed";goog.exportProperty(shaka.ads.AdManager,"AD_SKIP_STATE_CHANGED",shaka.ads.AdManager.AD_SKIP_STATE_CHANGED);shaka.ads.AdManager.CUEPOINTS_CHANGED="ad-cue-points-changed";
goog.exportProperty(shaka.ads.AdManager,"CUEPOINTS_CHANGED",shaka.ads.AdManager.CUEPOINTS_CHANGED);shaka.ads.AdManager.IMA_AD_MANAGER_LOADED="ima-ad-manager-loaded";goog.exportProperty(shaka.ads.AdManager,"IMA_AD_MANAGER_LOADED",shaka.ads.AdManager.IMA_AD_MANAGER_LOADED);shaka.ads.AdManager.IMA_STREAM_MANAGER_LOADED="ima-stream-manager-loaded";goog.exportProperty(shaka.ads.AdManager,"IMA_STREAM_MANAGER_LOADED",shaka.ads.AdManager.IMA_STREAM_MANAGER_LOADED);shaka.ads.AdManager.AD_CLICKED="ad-clicked";
goog.exportProperty(shaka.ads.AdManager,"AD_CLICKED",shaka.ads.AdManager.AD_CLICKED);shaka.ads.AdManager.AD_PROGRESS="ad-progress";goog.exportProperty(shaka.ads.AdManager,"AD_PROGRESS",shaka.ads.AdManager.AD_PROGRESS);shaka.ads.AdManager.AD_BUFFERING="ad-buffering";goog.exportProperty(shaka.ads.AdManager,"AD_BUFFERING",shaka.ads.AdManager.AD_BUFFERING);shaka.ads.AdManager.AD_IMPRESSION="ad-impression";goog.exportProperty(shaka.ads.AdManager,"AD_IMPRESSION",shaka.ads.AdManager.AD_IMPRESSION);
shaka.ads.AdManager.AD_DURATION_CHANGED="ad-duration-changed";goog.exportProperty(shaka.ads.AdManager,"AD_DURATION_CHANGED",shaka.ads.AdManager.AD_DURATION_CHANGED);shaka.ads.AdManager.AD_CLOSED="ad-closed";goog.exportProperty(shaka.ads.AdManager,"AD_CLOSED",shaka.ads.AdManager.AD_CLOSED);shaka.ads.AdManager.AD_LOADED="ad-loaded";goog.exportProperty(shaka.ads.AdManager,"AD_LOADED",shaka.ads.AdManager.AD_LOADED);shaka.ads.AdManager.ALL_ADS_COMPLETED="all-ads-completed";
goog.exportProperty(shaka.ads.AdManager,"ALL_ADS_COMPLETED",shaka.ads.AdManager.ALL_ADS_COMPLETED);shaka.ads.AdManager.AD_LINEAR_CHANGED="ad-linear-changed";goog.exportProperty(shaka.ads.AdManager,"AD_LINEAR_CHANGED",shaka.ads.AdManager.AD_LINEAR_CHANGED);shaka.ads.AdManager.AD_METADATA="ad-metadata";goog.exportProperty(shaka.ads.AdManager,"AD_METADATA",shaka.ads.AdManager.AD_METADATA);shaka.ads.AdManager.AD_RECOVERABLE_ERROR="ad-recoverable-error";
goog.exportProperty(shaka.ads.AdManager,"AD_RECOVERABLE_ERROR",shaka.ads.AdManager.AD_RECOVERABLE_ERROR);shaka.ads.AdManager.AD_BREAK_READY="ad-break-ready";goog.exportProperty(shaka.ads.AdManager,"AD_BREAK_READY",shaka.ads.AdManager.AD_BREAK_READY);shaka.ads.AdManager.AD_INTERACTION="ad-interaction";goog.exportProperty(shaka.ads.AdManager,"AD_INTERACTION",shaka.ads.AdManager.AD_INTERACTION);shaka.Player.setAdManagerFactory(function(){return new shaka.ads.AdManager});shaka.cast={};shaka.cast.CastUtils=function(){};
shaka.cast.CastUtils.serialize=function(a){return JSON.stringify(a,function(b,c){if("function"!=typeof c){if(c instanceof Event||c instanceof shaka.util.FakeEvent){b={};for(var d in c){var e=c[d];e&&"object"==typeof e?"detail"==d&&(b[d]=e):d in Event||(b[d]=e)}return b}return c instanceof Error?shaka.cast.CastUtils.unpackError_(c):c instanceof TimeRanges?shaka.cast.CastUtils.unpackTimeRanges_(c):c instanceof Uint8Array?shaka.cast.CastUtils.unpackUint8Array_(c):"number"==typeof c?isNaN(c)?"NaN":isFinite(c)?
c:0>c?"-Infinity":"Infinity":c}})};shaka.cast.CastUtils.deserialize=function(a){return JSON.parse(a,function(b,c){return"NaN"==c?NaN:"-Infinity"==c?-Infinity:"Infinity"==c?Infinity:c&&"object"==typeof c&&"TimeRanges"==c.__type__?shaka.cast.CastUtils.simulateTimeRanges_(c):c&&"object"==typeof c&&"Uint8Array"==c.__type__?shaka.cast.CastUtils.makeUint8Array_(c):c&&"object"==typeof c&&"Error"==c.__type__?shaka.cast.CastUtils.makeError_(c):c})};
shaka.cast.CastUtils.unpackTimeRanges_=function(a){var b={__type__:"TimeRanges",length:a.length,start:[],end:[]};a=$jscomp.makeIterator(shaka.media.TimeRangesUtils.getBufferedInfo(a));for(var c=a.next();!c.done;c=a.next()){c=c.value;var d=c.end;b.start.push(c.start);b.end.push(d)}return b};shaka.cast.CastUtils.simulateTimeRanges_=function(a){return{length:a.length,start:function(b){return a.start[b]},end:function(b){return a.end[b]}}};
shaka.cast.CastUtils.unpackUint8Array_=function(a){return{__type__:"Uint8Array",entries:Array.from(a)}};shaka.cast.CastUtils.makeUint8Array_=function(a){return new Uint8Array(a.entries)};
shaka.cast.CastUtils.unpackError_=function(a){var b=new Set(["name","message","stack"]),c;for(c in a)b.add(c);var d=$jscomp.makeIterator(Object.getOwnPropertyNames(a));for(c=d.next();!c.done;c=d.next())b.add(c.value);d={};b=$jscomp.makeIterator(b);for(c=b.next();!c.done;c=b.next())c=c.value,d[c]=a[c];return{__type__:"Error",contents:d}};shaka.cast.CastUtils.makeError_=function(a){a=a.contents;var b=Error(a.message),c;for(c in a)b[c]=a[c];return b};shaka.cast.CastUtils.VideoEvents="ended play playing pause pausing ratechange seeked seeking timeupdate volumechange".split(" ");
shaka.cast.CastUtils.VideoAttributes="buffered currentTime duration ended loop muted paused playbackRate seeking videoHeight videoWidth volume".split(" ");shaka.cast.CastUtils.VideoInitStateAttributes=["loop","playbackRate"];shaka.cast.CastUtils.VideoVoidMethods=["pause","play"];
shaka.cast.CastUtils.PlayerGetterMethods={getAssetUri:2,getAudioLanguages:4,getAudioLanguagesAndRoles:4,getBufferFullness:1,getBufferedInfo:2,getExpiration:2,getKeyStatuses:2,getPlaybackRate:2,getTextLanguages:4,getTextLanguagesAndRoles:4,getImageTracks:2,getThumbnails:2,isAudioOnly:10,isBuffering:1,isInProgress:1,isLive:10,isTextTrackVisible:1,keySystem:10,seekRange:1,getLoadMode:10};shaka.cast.CastUtils.LargePlayerGetterMethods={getConfiguration:4,getStats:5,getTextTracks:2,getVariantTracks:2};
shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive={getPlayheadTimeAsDate:1,getPresentationStartTimeAsDate:20};shaka.cast.CastUtils.PlayerInitState=[["getConfiguration","configure"]];shaka.cast.CastUtils.PlayerInitAfterLoadState=[["isTextTrackVisible","setTextTrackVisibility"]];shaka.cast.CastUtils.PlayerVoidMethods="addChaptersTrack addTextTrackAsync addThumbnailsTrack cancelTrickPlay configure getChapters getChaptersTracks resetConfiguration retryStreaming selectAudioLanguage selectTextLanguage selectTextTrack selectVariantTrack selectVariantsByLabel setTextTrackVisibility trickPlay updateStartTime goToLive".split(" ");
shaka.cast.CastUtils.PlayerPromiseMethods=["attach","attachCanvas","detach","load","unload"];shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE="urn:x-cast:com.google.shaka.v2";shaka.cast.CastUtils.GENERIC_MESSAGE_NAMESPACE="urn:x-cast:com.google.cast.media";shaka.cast.CastSender=function(a,b,c,d,e,f,g){var h=this;this.receiverAppId_=a;this.androidReceiverCompatible_=g;this.statusChangeTimer_=new shaka.util.Timer(b);this.onFirstCastStateUpdate_=c;this.hasJoinedExistingSession_=!1;this.onRemoteEvent_=d;this.onResumeLocal_=e;this.onInitStateRequired_=f;this.isCasting_=this.apiReady_=!1;this.receiverName_="";this.appData_=null;this.onConnectionStatusChangedBound_=function(){return h.onConnectionStatusChanged_()};this.onMessageReceivedBound_=function(k,l){return h.onMessageReceived_(k,
l)};this.cachedProperties_={video:{},player:{}};this.nextAsyncCallId_=0;this.asyncCallPromises_={};this.castPromise_=null;shaka.cast.CastSender.instances_.add(this)};
shaka.cast.CastSender.prototype.destroy=function(){shaka.cast.CastSender.instances_.delete(this);this.rejectAllPromises_();shaka.cast.CastSender.session_&&this.removeListeners_();this.statusChangeTimer_&&(this.statusChangeTimer_.stop(),this.statusChangeTimer_=null);this.onResumeLocal_=this.onRemoteEvent_=null;this.isCasting_=this.apiReady_=!1;this.onMessageReceivedBound_=this.onConnectionStatusChangedBound_=this.castPromise_=this.asyncCallPromises_=this.cachedProperties_=this.appData_=null;return Promise.resolve()};
shaka.cast.CastSender.prototype.apiReady=function(){return this.apiReady_};shaka.cast.CastSender.prototype.hasReceivers=function(){return shaka.cast.CastSender.hasReceivers_};shaka.cast.CastSender.prototype.isCasting=function(){return this.isCasting_};shaka.cast.CastSender.prototype.receiverName=function(){return this.receiverName_};shaka.cast.CastSender.prototype.hasRemoteProperties=function(){return 0!=Object.keys(this.cachedProperties_.video).length};
shaka.cast.CastSender.prototype.init=function(){var a=shaka.cast.CastSender;if(this.receiverAppId_.length)if(window.chrome&&chrome.cast&&chrome.cast.isAvailable){this.apiReady_=!0;this.statusChangeTimer_.tickNow();var b=new chrome.cast.SessionRequest(this.receiverAppId_,[],null,this.androidReceiverCompatible_,null);b=new chrome.cast.ApiConfig(b,function(c){return a.onExistingSessionJoined_(c)},function(c){return a.onReceiverStatusChanged_(c)},"origin_scoped");chrome.cast.initialize(b,function(){shaka.log.debug("CastSender: init")},
function(c){shaka.log.error("CastSender: init error",c)});shaka.cast.CastSender.hasReceivers_&&this.statusChangeTimer_.tickAfter(shaka.cast.CastSender.STATUS_DELAY);(b=shaka.cast.CastSender.session_)&&b.status!=chrome.cast.SessionStatus.STOPPED?(shaka.log.debug("CastSender: re-using existing connection"),this.onExistingSessionJoined_(b)):shaka.cast.CastSender.session_=null}else window.__onGCastApiAvailable!==a.onGCastApiAvailable_&&(a.__onGCastApiAvailable_=window.__onGCastApiAvailable||null,window.__onGCastApiAvailable=
a.onGCastApiAvailable_)};shaka.cast.CastSender.prototype.setAppData=function(a){this.appData_=a;this.isCasting_&&this.sendMessage_({type:"appData",appData:this.appData_})};
shaka.cast.CastSender.prototype.cast=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(!b.apiReady_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.CAST,shaka.util.Error.Code.CAST_API_UNAVAILABLE);if(!shaka.cast.CastSender.hasReceivers_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.CAST,shaka.util.Error.Code.NO_CAST_RECEIVERS);if(b.isCasting_)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.CAST,shaka.util.Error.Code.ALREADY_CASTING);b.castPromise_=new shaka.util.PublicPromise;chrome.cast.requestSession(function(d){return b.onSessionInitiated_(a,d)},function(d){return b.onConnectionError_(d)});return c.yield(b.castPromise_,0)})};shaka.cast.CastSender.prototype.showDisconnectDialog=function(){var a=this;if(this.isCasting_){var b=this.onInitStateRequired_();chrome.cast.requestSession(function(c){return a.onSessionInitiated_(b,c)},function(c){return a.onConnectionError_(c)})}};
shaka.cast.CastSender.prototype.forceDisconnect=function(){if(this.isCasting_){this.rejectAllPromises_();if(shaka.cast.CastSender.session_){this.removeListeners_();try{shaka.cast.CastSender.session_.stop(function(){},function(){})}catch(a){}shaka.cast.CastSender.session_=null}this.onConnectionStatusChanged_()}};
shaka.cast.CastSender.prototype.get=function(a,b){var c=this;goog.asserts.assert("video"==a||"player"==a,"Unexpected target name");var d=shaka.cast.CastUtils;if("video"==a){if(d.VideoVoidMethods.includes(b))return function(){var f=$jscomp.getRestArguments.apply(0,arguments);return c.remoteCall_.apply(c,[a,b].concat($jscomp.arrayFromIterable(f)))}}else if("player"==a){if(d.PlayerGetterMethodsThatRequireLive[b]){var e=this.get("player","isLive")();goog.asserts.assert(e,b+" should be called on a live stream!");
if(!e)return function(){}}if(d.PlayerVoidMethods.includes(b))return function(){var f=$jscomp.getRestArguments.apply(0,arguments);return c.remoteCall_.apply(c,[a,b].concat($jscomp.arrayFromIterable(f)))};if(d.PlayerPromiseMethods.includes(b))return function(){var f=$jscomp.getRestArguments.apply(0,arguments);return c.remoteAsyncCall_.apply(c,[a,b].concat($jscomp.arrayFromIterable(f)))};if(d.PlayerGetterMethods[b]||d.LargePlayerGetterMethods[b])return function(){return c.propertyGetter_(a,b)}}return this.propertyGetter_(a,
b)};shaka.cast.CastSender.prototype.set=function(a,b,c){goog.asserts.assert("video"==a||"player"==a,"Unexpected target name");this.cachedProperties_[a][b]=c;this.sendMessage_({type:"set",targetName:a,property:b,value:c})};shaka.cast.CastSender.prototype.onSessionInitiated_=function(a,b){shaka.log.debug("CastSender: onSessionInitiated");this.onSessionCreated_(b);this.sendMessage_({type:"init",initState:a,appData:this.appData_});this.castPromise_.resolve()};
shaka.cast.CastSender.prototype.onConnectionError_=function(a){var b=shaka.util.Error.Code.UNEXPECTED_CAST_ERROR;switch(a.code){case "cancel":b=shaka.util.Error.Code.CAST_CANCELED_BY_USER;break;case "timeout":b=shaka.util.Error.Code.CAST_CONNECTION_TIMED_OUT;break;case "receiver_unavailable":b=shaka.util.Error.Code.CAST_RECEIVER_APP_UNAVAILABLE}this.castPromise_.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.CAST,b,a))};
shaka.cast.CastSender.prototype.propertyGetter_=function(a,b){goog.asserts.assert("video"==a||"player"==a,"Unexpected target name");return this.cachedProperties_[a][b]};shaka.cast.CastSender.prototype.remoteCall_=function(a,b){var c=$jscomp.getRestArguments.apply(2,arguments);goog.asserts.assert("video"==a||"player"==a,"Unexpected target name");this.sendMessage_({type:"call",targetName:a,methodName:b,args:c})};
shaka.cast.CastSender.prototype.remoteAsyncCall_=function(a,b){var c=$jscomp.getRestArguments.apply(2,arguments);goog.asserts.assert("video"==a||"player"==a,"Unexpected target name");var d=new shaka.util.PublicPromise,e=this.nextAsyncCallId_.toString();this.nextAsyncCallId_++;this.asyncCallPromises_[e]=d;try{this.sendMessage_({type:"asyncCall",targetName:a,methodName:b,args:c,id:e})}catch(f){d.reject(f)}return d};
shaka.cast.CastSender.onExistingSessionJoined_=function(a){for(var b=$jscomp.makeIterator(shaka.cast.CastSender.instances_),c=b.next();!c.done;c=b.next())c.value.onExistingSessionJoined_(a)};shaka.cast.CastSender.prototype.onExistingSessionJoined_=function(a){shaka.log.debug("CastSender: onExistingSessionJoined");var b=this.onInitStateRequired_();this.castPromise_=new shaka.util.PublicPromise;this.hasJoinedExistingSession_=!0;this.onSessionInitiated_(b,a)};
shaka.cast.CastSender.onReceiverStatusChanged_=function(a){for(var b=$jscomp.makeIterator(shaka.cast.CastSender.instances_),c=b.next();!c.done;c=b.next())c.value.onReceiverStatusChanged_(a)};shaka.cast.CastSender.prototype.onReceiverStatusChanged_=function(a){shaka.log.debug("CastSender: receiver status",a);shaka.cast.CastSender.hasReceivers_="available"==a;this.statusChangeTimer_.tickNow()};
shaka.cast.CastSender.prototype.onSessionCreated_=function(a){shaka.cast.CastSender.session_=a;a.addUpdateListener(this.onConnectionStatusChangedBound_);a.addMessageListener(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE,this.onMessageReceivedBound_);this.onConnectionStatusChanged_()};
shaka.cast.CastSender.prototype.removeListeners_=function(){var a=shaka.cast.CastSender.session_;a.removeUpdateListener(this.onConnectionStatusChangedBound_);a.removeMessageListener(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE,this.onMessageReceivedBound_)};
shaka.cast.CastSender.prototype.onConnectionStatusChanged_=function(){var a=shaka.cast.CastSender.session_?"connected"==shaka.cast.CastSender.session_.status:!1;shaka.log.debug("CastSender: connection status",a);if(this.isCasting_&&!a){this.onResumeLocal_();for(var b in this.cachedProperties_)this.cachedProperties_[b]={};this.rejectAllPromises_()}this.receiverName_=(this.isCasting_=a)?shaka.cast.CastSender.session_.receiver.friendlyName:"";this.statusChangeTimer_.tickNow()};
shaka.cast.CastSender.prototype.rejectAllPromises_=function(){for(var a in this.asyncCallPromises_){var b=this.asyncCallPromises_[a];delete this.asyncCallPromises_[a];b.reject(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.LOAD_INTERRUPTED))}};
shaka.cast.CastSender.prototype.onMessageReceived_=function(a,b){a=shaka.cast.CastUtils.deserialize(b);shaka.log.v2("CastSender: message",a);switch(a.type){case "event":var c=a.targetName,d=shaka.util.FakeEvent.fromRealEvent(a.event);this.onRemoteEvent_(c,d);break;case "update":c=a.update;for(d in c){a=this.cachedProperties_[d]||{};for(var e in c[d])a[e]=c[d][e]}this.hasJoinedExistingSession_&&(this.onFirstCastStateUpdate_(),this.hasJoinedExistingSession_=!1);break;case "asyncComplete":if(d=a.id,
e=a.error,a=this.asyncCallPromises_[d],delete this.asyncCallPromises_[d],goog.asserts.assert(a,"Unexpected async id"),a)if(e){d=new shaka.util.Error(e.severity,e.category,e.code);for(c in e)d[c]=e[c];a.reject(d)}else a.resolve()}};
shaka.cast.CastSender.prototype.sendMessage_=function(a){a=shaka.cast.CastUtils.serialize(a);var b=shaka.cast.CastSender.session_;try{b.sendMessage(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE,a,function(){},shaka.log.error)}catch(c){throw shaka.log.error("Cast session sendMessage threw",c),a=new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.CAST,shaka.util.Error.Code.CAST_CONNECTION_TIMED_OUT,c),b=new shaka.util.FakeEvent("error",(new Map).set("detail",a)),this.onRemoteEvent_("player",
b),this.forceDisconnect(),a;}};shaka.cast.CastSender.STATUS_DELAY=.02;shaka.cast.CastSender.hasReceivers_=!1;shaka.cast.CastSender.session_=null;shaka.cast.CastSender.__onGCastApiAvailable_=null;shaka.cast.CastSender.instances_=new Set;shaka.cast.CastSender.onSdkLoaded_=function(a){if(a){a=$jscomp.makeIterator(shaka.cast.CastSender.instances_);for(var b=a.next();!b.done;b=a.next())b.value.init()}};
shaka.cast.CastSender.onGCastApiAvailable_=function(a){shaka.cast.CastSender.__onGCastApiAvailable_?window.__onGCastApiAvailable=shaka.cast.CastSender.__onGCastApiAvailable_:delete window.__onGCastApiAvailable;shaka.cast.CastSender.__onGCastApiAvailable_=null;shaka.cast.CastSender.onSdkLoaded_(a);"function"===typeof window.__onGCastApiAvailable&&window.__onGCastApiAvailable(a)};shaka.cast.CastProxy=function(a,b,c,d){d=void 0===d?!1:d;shaka.util.FakeEventTarget.call(this);var e=this;this.localVideo_=a;this.localPlayer_=b;this.eventManager_=this.playerEventTarget_=this.videoEventTarget_=this.playerProxy_=this.videoProxy_=null;this.receiverAppId_=c;this.androidReceiverCompatible_=d;this.compiledToExternNames_=new Map;this.sender_=new shaka.cast.CastSender(c,function(){return e.onCastStatusChanged_()},function(){return e.onFirstCastStateUpdate_()},function(f,g){return e.onRemoteEvent_(f,
g)},function(){return e.onResumeLocal_()},function(){return e.getInitState_()},d);this.init_()};$jscomp.inherits(shaka.cast.CastProxy,shaka.util.FakeEventTarget);
shaka.cast.CastProxy.prototype.destroy=function(a){a&&this.sender_.forceDisconnect();this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null);a=[];this.localPlayer_&&(a.push(this.localPlayer_.destroy()),this.localPlayer_=null);this.sender_&&(a.push(this.sender_.destroy()),this.sender_=null);this.playerProxy_=this.videoProxy_=this.localVideo_=null;shaka.util.FakeEventTarget.prototype.release.call(this);return Promise.all(a)};shaka.cast.CastProxy.prototype.getVideo=function(){return this.videoProxy_};
shaka.cast.CastProxy.prototype.getPlayer=function(){return this.playerProxy_};shaka.cast.CastProxy.prototype.canCast=function(){return this.sender_.apiReady()&&this.sender_.hasReceivers()};shaka.cast.CastProxy.prototype.isCasting=function(){return this.sender_.isCasting()};shaka.cast.CastProxy.prototype.receiverName=function(){return this.sender_.receiverName()};
shaka.cast.CastProxy.prototype.cast=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){return 1==c.nextAddress?(b=a.getInitState_(),c.yield(a.sender_.cast(b),2)):a.localPlayer_?c.yield(a.localPlayer_.unload(),0):c.return()})};shaka.cast.CastProxy.prototype.setAppData=function(a){this.sender_.setAppData(a)};shaka.cast.CastProxy.prototype.suggestDisconnect=function(){this.sender_.showDisconnectDialog()};shaka.cast.CastProxy.prototype.forceDisconnect=function(){this.sender_.forceDisconnect()};
shaka.cast.CastProxy.prototype.changeReceiverId=function(a,b){b=void 0===b?!1:b;var c=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress){if(a==c.receiverAppId_&&b==c.androidReceiverCompatible_)return d.return();c.receiverAppId_=a;c.androidReceiverCompatible_=b;c.sender_.forceDisconnect();return d.yield(c.sender_.destroy(),2)}c.sender_=null;c.sender_=new shaka.cast.CastSender(a,function(){return c.onCastStatusChanged_()},function(){return c.onFirstCastStateUpdate_()},
function(e,f){return c.onRemoteEvent_(e,f)},function(){return c.onResumeLocal_()},function(){return c.getInitState_()},b);c.sender_.init();d.jumpToEnd()})};
shaka.cast.CastProxy.prototype.init_=function(){var a=this;this.sender_.init();this.eventManager_=new shaka.util.EventManager;for(var b=$jscomp.makeIterator(shaka.cast.CastUtils.VideoEvents),c=b.next();!c.done;c=b.next())this.eventManager_.listen(this.localVideo_,c.value,function(f){return a.videoProxyLocalEvent_(f)});for(var d in shaka.util.FakeEvent.EventName)this.eventManager_.listen(this.localPlayer_,shaka.util.FakeEvent.EventName[d],function(f){return a.playerProxyLocalEvent_(f)});this.videoProxy_=
{};b={};for(var e in this.localVideo_)b.$jscomp$loop$prop$k$660=e,Object.defineProperty(this.videoProxy_,b.$jscomp$loop$prop$k$660,{configurable:!1,enumerable:!0,get:function(f){return function(){return a.videoProxyGet_(f.$jscomp$loop$prop$k$660)}}(b),set:function(f){return function(g){a.videoProxySet_(f.$jscomp$loop$prop$k$660,g)}}(b)}),b={$jscomp$loop$prop$k$660:b.$jscomp$loop$prop$k$660};this.playerProxy_={};this.iterateOverPlayerMethods_(function(f,g){goog.asserts.assert(a.playerProxy_,"Must have player proxy!");
Object.defineProperty(a.playerProxy_,f,{configurable:!1,enumerable:!0,get:function(){return a.playerProxyGet_(f)}})});COMPILED&&this.mapCompiledToUncompiledPlayerMethodNames_();this.videoEventTarget_=new shaka.util.FakeEventTarget;this.videoEventTarget_.dispatchTarget=this.videoProxy_;this.playerEventTarget_=new shaka.util.FakeEventTarget;this.playerEventTarget_.dispatchTarget=this.playerProxy_};
shaka.cast.CastProxy.prototype.mapCompiledToUncompiledPlayerMethodNames_=function(){var a=this,b=new Map;this.iterateOverPlayerMethods_(function(c,d){b.has(d)?(d=b.get(d),c.length<d.length?a.compiledToExternNames_.set(c,d):a.compiledToExternNames_.set(d,c)):b.set(d,c)})};
shaka.cast.CastProxy.prototype.iterateOverPlayerMethods_=function(a){function b(k){return"constructor"==k||"function"!=typeof c[k]?!1:!d.has(k)}goog.asserts.assert(this.localPlayer_,"Must have player!");var c=this.localPlayer_,d=new Set;for(e in c)b(e)&&(d.add(e),a(e,c[e]));var e=Object.getPrototypeOf(c);for(var f=Object.getPrototypeOf({});e&&e!=f;){for(var g=$jscomp.makeIterator(Object.getOwnPropertyNames(e)),h=g.next();!h.done;h=g.next())h=h.value,b(h)&&(d.add(h),a(h,c[h]));e=Object.getPrototypeOf(e)}};
shaka.cast.CastProxy.prototype.getInitState_=function(){var a={video:{},player:{},playerAfterLoad:{},manifest:this.localPlayer_.getAssetUri(),startTime:null};this.localVideo_.pause();for(var b=$jscomp.makeIterator(shaka.cast.CastUtils.VideoInitStateAttributes),c=b.next();!c.done;c=b.next())c=c.value,a.video[c]=this.localVideo_[c];this.localVideo_.ended||(a.startTime=this.localVideo_.currentTime);b=$jscomp.makeIterator(shaka.cast.CastUtils.PlayerInitState);for(c=b.next();!c.done;c=b.next()){var d=
c.value;c=d[1];d=this.localPlayer_[d[0]]();a.player[c]=d}b=$jscomp.makeIterator(shaka.cast.CastUtils.PlayerInitAfterLoadState);for(c=b.next();!c.done;c=b.next())d=c.value,c=d[1],d=this.localPlayer_[d[0]](),a.playerAfterLoad[c]=d;return a};shaka.cast.CastProxy.prototype.onCastStatusChanged_=function(){var a=new shaka.util.FakeEvent("caststatuschanged");this.dispatchEvent(a)};
shaka.cast.CastProxy.prototype.onFirstCastStateUpdate_=function(){var a=new shaka.util.FakeEvent(this.videoProxy_.paused?"pause":"play");this.videoEventTarget_.dispatchEvent(a)};
shaka.cast.CastProxy.prototype.onResumeLocal_=function(){for(var a=this,b=$jscomp.makeIterator(shaka.cast.CastUtils.PlayerInitState),c=b.next();!c.done;c=b.next()){var d=c.value;c=d[1];d=this.sender_.get("player",d[0])();this.localPlayer_[c](d)}var e=this.sender_.get("player","getAssetUri")();c=this.sender_.get("video","ended");b=Promise.resolve();var f=this.localVideo_.autoplay;d=null;c||(d=this.sender_.get("video","currentTime"));e&&(this.localVideo_.autoplay=!1,b=this.localPlayer_.load(e,d));var g=
{};c=$jscomp.makeIterator(shaka.cast.CastUtils.VideoInitStateAttributes);for(d=c.next();!d.done;d=c.next())d=d.value,g[d]=this.sender_.get("video",d);b.then(function(){if(a.localVideo_){for(var h=$jscomp.makeIterator(shaka.cast.CastUtils.VideoInitStateAttributes),k=h.next();!k.done;k=h.next())k=k.value,a.localVideo_[k]=g[k];h=$jscomp.makeIterator(shaka.cast.CastUtils.PlayerInitAfterLoadState);for(k=h.next();!k.done;k=h.next()){var l=k.value;k=l[1];l=a.sender_.get("player",l[0])();a.localPlayer_[k](l)}a.localVideo_.autoplay=
f;e&&a.localVideo_.play()}},function(h){goog.asserts.assert(h instanceof shaka.util.Error,"Wrong error type!");var k=shaka.util.FakeEvent.EventName.Error;h=(new Map).set("detail",h);k=new shaka.util.FakeEvent(k,h);a.localPlayer_.dispatchEvent(k)})};
shaka.cast.CastProxy.prototype.videoProxyGet_=function(a){var b=this;if("addEventListener"==a)return function(d,e,f){return b.videoEventTarget_.addEventListener(d,e,f)};if("removeEventListener"==a)return function(d,e,f){return b.videoEventTarget_.removeEventListener(d,e,f)};if(this.sender_.isCasting()&&!this.sender_.hasRemoteProperties()){var c=this.localVideo_[a];if("function"!=typeof c)return c}return this.sender_.isCasting()?this.sender_.get("video",a):(a=this.localVideo_[a],"function"==typeof a&&
(a=a.bind(this.localVideo_)),a)};shaka.cast.CastProxy.prototype.videoProxySet_=function(a,b){this.sender_.isCasting()?this.sender_.set("video",a,b):this.localVideo_[a]=b};shaka.cast.CastProxy.prototype.videoProxyLocalEvent_=function(a){this.sender_.isCasting()||(a=shaka.util.FakeEvent.fromRealEvent(a),this.videoEventTarget_.dispatchEvent(a))};
shaka.cast.CastProxy.prototype.playerProxyGet_=function(a){var b=this;this.compiledToExternNames_.has(a)&&(a=this.compiledToExternNames_.get(a));if("addEventListener"==a)return function(d,e,f){return b.playerEventTarget_.addEventListener(d,e,f)};if("removeEventListener"==a)return function(d,e,f){return b.playerEventTarget_.removeEventListener(d,e,f)};if("getMediaElement"==a)return function(){return b.videoProxy_};if("getSharedConfiguration"==a)return shaka.log.warning("Can't share configuration across a network. Returning copy."),
this.sender_.get("player","getConfiguration");if("getNetworkingEngine"==a)return this.sender_.isCasting()&&shaka.log.warning("NOTE: getNetworkingEngine() is always local!"),function(){return b.localPlayer_.getNetworkingEngine()};if("getDrmEngine"==a)return this.sender_.isCasting()&&shaka.log.warning("NOTE: getDrmEngine() is always local!"),function(){return b.localPlayer_.getDrmEngine()};if("getAdManager"==a)return this.sender_.isCasting()&&shaka.log.warning("NOTE: getAdManager() is always local!"),
function(){return b.localPlayer_.getAdManager()};if("setVideoContainer"==a)return this.sender_.isCasting()&&shaka.log.warning("NOTE: setVideoContainer() is always local!"),function(d){return b.localPlayer_.setVideoContainer(d)};if(this.sender_.isCasting()){if("getManifest"==a||"drmInfo"==a)return function(){shaka.log.alwaysWarn(a+"() does not work while casting!");return null};if("attach"==a||"detach"==a)return function(){shaka.log.alwaysWarn(a+"() does not work while casting!");return Promise.resolve()}}if(this.sender_.isCasting()&&
!this.sender_.hasRemoteProperties()&&(shaka.cast.CastUtils.PlayerGetterMethods[a]||shaka.cast.CastUtils.LargePlayerGetterMethods[a])){var c=this.localPlayer_[a];goog.asserts.assert("function"==typeof c,"only methods on Player");return c.bind(this.localPlayer_)}return this.sender_.isCasting()?this.sender_.get("player",a):(c=this.localPlayer_[a],goog.asserts.assert("function"==typeof c,"only methods on Player"),c.bind(this.localPlayer_))};
shaka.cast.CastProxy.prototype.playerProxyLocalEvent_=function(a){this.sender_.isCasting()||this.playerEventTarget_.dispatchEvent(a)};shaka.cast.CastProxy.prototype.onRemoteEvent_=function(a,b){goog.asserts.assert(this.sender_.isCasting(),"Should only receive remote events while casting");this.sender_.isCasting()&&("video"==a?this.videoEventTarget_.dispatchEvent(b):"player"==a&&this.playerEventTarget_.dispatchEvent(b))};goog.exportSymbol("shaka.cast.CastProxy",shaka.cast.CastProxy);
goog.exportProperty(shaka.cast.CastProxy.prototype,"changeReceiverId",shaka.cast.CastProxy.prototype.changeReceiverId);goog.exportProperty(shaka.cast.CastProxy.prototype,"forceDisconnect",shaka.cast.CastProxy.prototype.forceDisconnect);goog.exportProperty(shaka.cast.CastProxy.prototype,"suggestDisconnect",shaka.cast.CastProxy.prototype.suggestDisconnect);goog.exportProperty(shaka.cast.CastProxy.prototype,"setAppData",shaka.cast.CastProxy.prototype.setAppData);
goog.exportProperty(shaka.cast.CastProxy.prototype,"cast",shaka.cast.CastProxy.prototype.cast);goog.exportProperty(shaka.cast.CastProxy.prototype,"receiverName",shaka.cast.CastProxy.prototype.receiverName);goog.exportProperty(shaka.cast.CastProxy.prototype,"isCasting",shaka.cast.CastProxy.prototype.isCasting);goog.exportProperty(shaka.cast.CastProxy.prototype,"canCast",shaka.cast.CastProxy.prototype.canCast);goog.exportProperty(shaka.cast.CastProxy.prototype,"getPlayer",shaka.cast.CastProxy.prototype.getPlayer);
goog.exportProperty(shaka.cast.CastProxy.prototype,"getVideo",shaka.cast.CastProxy.prototype.getVideo);goog.exportProperty(shaka.cast.CastProxy.prototype,"destroy",shaka.cast.CastProxy.prototype.destroy);shaka.cast.CastReceiver=function(a,b,c,d){shaka.util.FakeEventTarget.call(this);var e=this;this.video_=a;this.player_=b;this.eventManager_=new shaka.util.EventManager;this.targets_={video:a,player:b};this.appDataCallback_=c||function(){};this.contentIdCallback_=d||function(f){return f};this.metadata_=null;this.isConnected_=!1;this.isIdle_=!0;this.updateNumber_=0;this.startUpdatingUpdateNumber_=!1;this.initialStatusUpdatePending_=!0;this.genericBus_=this.shakaBus_=null;this.pollTimer_=new shaka.util.Timer(function(){e.pollAttributes_()});
this.init_()};$jscomp.inherits(shaka.cast.CastReceiver,shaka.util.FakeEventTarget);shaka.cast.CastReceiver.prototype.isConnected=function(){return this.isConnected_};shaka.cast.CastReceiver.prototype.isIdle=function(){return this.isIdle_};shaka.cast.CastReceiver.prototype.setContentMetadata=function(a){this.metadata_=a};shaka.cast.CastReceiver.prototype.clearContentMetadata=function(){this.metadata_=null};
shaka.cast.CastReceiver.prototype.setContentTitle=function(a){this.metadata_||(this.metadata_={metadataType:cast.receiver.media.MetadataType.GENERIC});this.metadata_.title=a};shaka.cast.CastReceiver.prototype.setContentImage=function(a){this.metadata_||(this.metadata_={metadataType:cast.receiver.media.MetadataType.GENERIC});this.metadata_.images=[{url:a}]};
shaka.cast.CastReceiver.prototype.setContentArtist=function(a){this.metadata_||(this.metadata_={});this.metadata_.artist=a;this.metadata_.metadataType=cast.receiver.media.MetadataType.MUSIC_TRACK};
shaka.cast.CastReceiver.prototype.destroy=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return a.eventManager_&&(a.eventManager_.release(),a.eventManager_=null),b=[],a.player_&&(b.push(a.player_.destroy()),a.player_=null),a.pollTimer_&&(a.pollTimer_.stop(),a.pollTimer_=null),a.video_=null,a.targets_=null,a.appDataCallback_=null,a.isConnected_=!1,a.isIdle_=!0,a.shakaBus_=null,a.genericBus_=null,shaka.util.FakeEventTarget.prototype.release.call(a),
d.yield(Promise.all(b),2);c=cast.receiver.CastReceiverManager.getInstance();c.stop();d.jumpToEnd()})};
shaka.cast.CastReceiver.prototype.init_=function(){var a=this,b=cast.receiver.CastReceiverManager.getInstance();b.onSenderConnected=function(){return a.onSendersChanged_()};b.onSenderDisconnected=function(){return a.onSendersChanged_()};b.onSystemVolumeChanged=function(){return a.fakeVolumeChangeEvent_()};this.genericBus_=b.getCastMessageBus(shaka.cast.CastUtils.GENERIC_MESSAGE_NAMESPACE);this.genericBus_.onMessage=function(e){return a.onGenericMessage_(e)};this.shakaBus_=b.getCastMessageBus(shaka.cast.CastUtils.SHAKA_MESSAGE_NAMESPACE);
this.shakaBus_.onMessage=function(e){return a.onShakaMessage_(e)};goog.DEBUG?shaka.util.Platform.isChromecast()&&b.start():b.start();b=$jscomp.makeIterator(shaka.cast.CastUtils.VideoEvents);for(var c=b.next();!c.done;c=b.next())this.eventManager_.listen(this.video_,c.value,function(e){return a.proxyEvent_("video",e)});for(var d in shaka.util.FakeEvent.EventName)this.eventManager_.listen(this.player_,shaka.util.FakeEvent.EventName[d],function(e){return a.proxyEvent_("player",e)});cast.__platform__&&
cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=3840; height=2160')?this.player_.setMaxHardwareResolution(3840,2160):this.player_.setMaxHardwareResolution(1920,1080);this.eventManager_.listen(this.video_,"loadeddata",function(){a.startUpdatingUpdateNumber_=!0});this.eventManager_.listen(this.player_,"loading",function(){a.isIdle_=!1;a.onCastStatusChanged_()});this.eventManager_.listen(this.video_,"playing",function(){a.isIdle_=!1;a.onCastStatusChanged_()});this.eventManager_.listen(this.video_,
"pause",function(){a.onCastStatusChanged_()});this.eventManager_.listen(this.player_,"unloading",function(){a.isIdle_=!0;a.onCastStatusChanged_()});this.eventManager_.listen(this.video_,"ended",function(){(new shaka.util.Timer(function(){a.video_&&a.video_.ended&&(a.isIdle_=!0,a.onCastStatusChanged_())})).tickAfter(shaka.cast.CastReceiver.IDLE_INTERVAL)})};
shaka.cast.CastReceiver.prototype.onSendersChanged_=function(){this.updateNumber_=0;this.initialStatusUpdatePending_=!0;this.isConnected_=0!=cast.receiver.CastReceiverManager.getInstance().getSenders().length;this.onCastStatusChanged_()};
shaka.cast.CastReceiver.prototype.onCastStatusChanged_=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return c.yield(Promise.resolve(),2);if(!a.player_)return c.return();b=new shaka.util.FakeEvent("caststatuschanged");a.dispatchEvent(b);a.maybeSendMediaInfoMessage_()||a.sendMediaStatus_();c.jumpToEnd()})};
shaka.cast.CastReceiver.prototype.initState_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q;return $jscomp.asyncExecutePromiseGeneratorProgram(function(r){switch(r.nextAddress){case 1:for(d in a.player)e=a.player[d],c.player_[d](e);c.appDataCallback_(b);f=c.video_.autoplay;return a.manifest?(c.video_.autoplay=!1,r.setCatchFinallyBlocks(5),r.yield(c.player_.load(a.manifest,a.startTime),7)):r.yield(Promise.resolve(),3);case 7:r.leaveTryBlock(3);break;case 5:return g=r.enterCatchBlock(),goog.asserts.assert(g instanceof
shaka.util.Error,"Wrong error type!"),h=shaka.util.FakeEvent.EventName.Error,k=(new Map).set("detail",g),l=new shaka.util.FakeEvent(h,k),c.player_&&c.player_.dispatchEvent(l),r.return();case 3:if(!c.player_)return r.return();for(m in a.video)n=a.video[m],c.video_[m]=n;for(p in a.playerAfterLoad)q=a.playerAfterLoad[p],c.player_[p](q);c.video_.autoplay=f;a.manifest&&(c.video_.play(),c.sendMediaStatus_());r.jumpToEnd()}})};
shaka.cast.CastReceiver.prototype.proxyEvent_=function(a,b){this.player_&&(this.pollAttributes_(),this.sendMessage_({type:"event",targetName:a,event:b},this.shakaBus_))};
shaka.cast.CastReceiver.prototype.pollAttributes_=function(){this.pollTimer_.tickAfter(shaka.cast.CastReceiver.POLL_INTERVAL);for(var a={video:{},player:{}},b=$jscomp.makeIterator(shaka.cast.CastUtils.VideoAttributes),c=b.next();!c.done;c=b.next())c=c.value,a.video[c]=this.video_[c];if(this.player_.isLive()){b=shaka.cast.CastUtils.PlayerGetterMethodsThatRequireLive;for(var d in b)0==this.updateNumber_%b[d]&&(a.player[d]=this.player_[d]())}for(var e in shaka.cast.CastUtils.PlayerGetterMethods)0==this.updateNumber_%
shaka.cast.CastUtils.PlayerGetterMethods[e]&&(a.player[e]=this.player_[e]());if(d=cast.receiver.CastReceiverManager.getInstance().getSystemVolume())a.video.volume=d.level,a.video.muted=d.muted;this.sendMessage_({type:"update",update:a},this.shakaBus_);for(var f in shaka.cast.CastUtils.LargePlayerGetterMethods)0==this.updateNumber_%shaka.cast.CastUtils.LargePlayerGetterMethods[f]&&(a={player:{}},a.player[f]=this.player_[f](),this.sendMessage_({type:"update",update:a},this.shakaBus_));this.startUpdatingUpdateNumber_&&
(this.updateNumber_+=1);this.maybeSendMediaInfoMessage_()};shaka.cast.CastReceiver.prototype.maybeSendMediaInfoMessage_=function(){return this.initialStatusUpdatePending_&&(this.video_.duration||this.player_.isLive())?(this.sendMediaInfoMessage_(),this.initialStatusUpdatePending_=!1,!0):!1};
shaka.cast.CastReceiver.prototype.sendMediaInfoMessage_=function(a){a=void 0===a?0:a;var b={contentId:this.player_.getAssetUri(),streamType:this.player_.isLive()?"LIVE":"BUFFERED",contentType:""};this.player_.isLive()||(b.duration=this.video_.duration);this.metadata_&&(b.metadata=this.metadata_);this.sendMediaStatus_(a,b)};
shaka.cast.CastReceiver.prototype.fakeVolumeChangeEvent_=function(){var a=cast.receiver.CastReceiverManager.getInstance().getSystemVolume();goog.asserts.assert(a,"System volume should not be null!");a&&this.sendMessage_({type:"update",update:{video:{volume:a.level,muted:a.muted}}},this.shakaBus_);this.sendMessage_({type:"event",targetName:"video",event:{type:"volumechange"}},this.shakaBus_)};
shaka.cast.CastReceiver.prototype.onShakaMessage_=function(a){var b=this,c=shaka.cast.CastUtils.deserialize(a.data);shaka.log.debug("CastReceiver: message",c);switch(c.type){case "init":this.updateNumber_=0;this.startUpdatingUpdateNumber_=!1;this.initialStatusUpdatePending_=!0;this.initState_(c.initState,c.appData);this.pollAttributes_();break;case "appData":this.appDataCallback_(c.appData);break;case "set":var d=c.targetName,e=c.property;c=c.value;if("video"==d)if(a=cast.receiver.CastReceiverManager.getInstance(),
"volume"==e){a.setSystemVolumeLevel(c);break}else if("muted"==e){a.setSystemVolumeMuted(c);break}this.targets_[d][e]=c;break;case "call":d=this.targets_[c.targetName];d[c.methodName].apply(d,c.args);break;case "asyncCall":d=c.targetName;e=c.methodName;"player"==d&&"load"==e&&(this.updateNumber_=0,this.startUpdatingUpdateNumber_=!1);var f=c.id,g=a.senderId;a=this.targets_[d];c=a[e].apply(a,c.args);"player"==d&&"load"==e&&(c=c.then(function(){b.initialStatusUpdatePending_=!0}));c.then(function(){return b.sendAsyncComplete_(g,
f,null)},function(h){return b.sendAsyncComplete_(g,f,h)})}};
shaka.cast.CastReceiver.prototype.onGenericMessage_=function(a){var b=this,c=shaka.cast.CastUtils.deserialize(a.data);shaka.log.debug("CastReceiver: message",c);switch(c.type){case "PLAY":this.video_.play();this.sendMediaStatus_();break;case "PAUSE":this.video_.pause();this.sendMediaStatus_();break;case "SEEK":a=c.currentTime;var d=c.resumeState;null!=a&&(this.video_.currentTime=Number(a));d&&"PLAYBACK_START"==d?(this.video_.play(),this.sendMediaStatus_()):d&&"PLAYBACK_PAUSE"==d&&(this.video_.pause(),
this.sendMediaStatus_());break;case "STOP":this.player_.unload().then(function(){b.player_&&b.sendMediaStatus_()});break;case "GET_STATUS":this.sendMediaInfoMessage_(Number(c.requestId));break;case "VOLUME":d=c.volume;a=d.level;d=d.muted;var e=this.video_.volume,f=this.video_.muted;null!=a&&(this.video_.volume=Number(a));null!=d&&(this.video_.muted=d);e==this.video_.volume&&f==this.video_.muted||this.sendMediaStatus_();break;case "LOAD":this.updateNumber_=0;this.initialStatusUpdatePending_=this.startUpdatingUpdateNumber_=
!1;a=c.media;d=c.currentTime;e=this.contentIdCallback_(a.contentId);f=c.autoplay||!0;this.appDataCallback_(a.customData);f&&(this.video_.autoplay=!0);this.player_.load(e,d).then(function(){b.player_&&b.sendMediaInfoMessage_()}).catch(function(g){goog.asserts.assert(g instanceof shaka.util.Error,"Wrong error type!");var h="LOAD_FAILED";g.category==shaka.util.Error.Category.PLAYER&&g.code==shaka.util.Error.Code.LOAD_INTERRUPTED&&(h="LOAD_CANCELLED");b.sendMessage_({requestId:Number(c.requestId),type:h},
b.genericBus_)});break;default:shaka.log.warning("Unrecognized message type from the generic Chromecast controller!",c.type),this.sendMessage_({requestId:Number(c.requestId),type:"INVALID_REQUEST",reason:"INVALID_COMMAND"},this.genericBus_)}};shaka.cast.CastReceiver.prototype.sendAsyncComplete_=function(a,b,c){this.player_&&this.sendMessage_({type:"asyncComplete",id:b,error:c},this.shakaBus_,a)};
shaka.cast.CastReceiver.prototype.sendMessage_=function(a,b,c){this.isConnected_&&(a=shaka.cast.CastUtils.serialize(a),c?b.getCastChannel(c).send(a):b.broadcast(a))};shaka.cast.CastReceiver.prototype.getPlayState_=function(){var a=shaka.cast.CastReceiver.PLAY_STATE;return this.isIdle_?a.IDLE:this.player_.isBuffering()?a.BUFFERING:this.video_.paused?a.PAUSED:a.PLAYING};
shaka.cast.CastReceiver.prototype.sendMediaStatus_=function(a,b){a=void 0===a?0:a;b=void 0===b?null:b;var c={mediaSessionId:0,playbackRate:this.video_.playbackRate,playerState:this.getPlayState_(),currentTime:this.video_.currentTime,supportedMediaCommands:63,volume:{level:this.video_.volume,muted:this.video_.muted}};b&&(c.media=b);this.sendMessage_({requestId:a,type:"MEDIA_STATUS",status:[c]},this.genericBus_)};goog.exportSymbol("shaka.cast.CastReceiver",shaka.cast.CastReceiver);
goog.exportProperty(shaka.cast.CastReceiver.prototype,"destroy",shaka.cast.CastReceiver.prototype.destroy);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentArtist",shaka.cast.CastReceiver.prototype.setContentArtist);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentImage",shaka.cast.CastReceiver.prototype.setContentImage);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentTitle",shaka.cast.CastReceiver.prototype.setContentTitle);
goog.exportProperty(shaka.cast.CastReceiver.prototype,"clearContentMetadata",shaka.cast.CastReceiver.prototype.clearContentMetadata);goog.exportProperty(shaka.cast.CastReceiver.prototype,"setContentMetadata",shaka.cast.CastReceiver.prototype.setContentMetadata);goog.exportProperty(shaka.cast.CastReceiver.prototype,"isIdle",shaka.cast.CastReceiver.prototype.isIdle);goog.exportProperty(shaka.cast.CastReceiver.prototype,"isConnected",shaka.cast.CastReceiver.prototype.isConnected);
shaka.cast.CastReceiver.POLL_INTERVAL=.5;shaka.cast.CastReceiver.IDLE_INTERVAL=5;shaka.cast.CastReceiver.PLAY_STATE={IDLE:"IDLE",PLAYING:"PLAYING",BUFFERING:"BUFFERING",PAUSED:"PAUSED"};shaka.dash={};shaka.dash.ContentProtection=function(){};
shaka.dash.ContentProtection.parseFromAdaptationSet=function(a,b,c){var d=shaka.dash.ContentProtection,e=shaka.util.ManifestParserUtils,f=d.parseElements_(a),g=null;a=[];var h=[],k=new Set(f.map(function(l){return l.keyId}));k.delete(null);if(1<k.size)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_CONFLICTING_KEY_IDS);b||(h=f.filter(function(l){return l.schemeUri==d.MP4Protection_?(goog.asserts.assert(!l.init||l.init.length,
"Init data must be null or non-empty."),g=l.init||g,!1):!0}),h.length&&(a=d.convertElements_(g,h,c,k),0==a.length&&(a=[e.createDrmInfo("",g)])));if(f.length&&(b||!h.length))for(a=[],b=$jscomp.makeIterator(Object.values(c)),c=b.next();!c.done;c=b.next())c=c.value,"org.w3.clearkey"!=c&&(c=e.createDrmInfo(c,g),a.push(c));if(e=Array.from(k)[0]||null)for(k=$jscomp.makeIterator(a),b=k.next();!b.done;b=k.next())for(b=$jscomp.makeIterator(b.value.initData),c=b.next();!c.done;c=b.next())c.value.keyId=e;return{defaultKeyId:e,
defaultInit:g,drmInfos:a,firstRepresentation:!0}};
shaka.dash.ContentProtection.parseFromRepresentation=function(a,b,c,d){var e=shaka.dash.ContentProtection.parseFromAdaptationSet(a,c,d);if(b.firstRepresentation){a=1==b.drmInfos.length&&!b.drmInfos[0].keySystem;c=0==e.drmInfos.length;if(0==b.drmInfos.length||a&&!c)b.drmInfos=e.drmInfos;b.firstRepresentation=!1}else if(0<e.drmInfos.length&&(b.drmInfos=b.drmInfos.filter(function(f){return e.drmInfos.some(function(g){return g.keySystem==f.keySystem})}),0==b.drmInfos.length))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_COMMON_KEY_SYSTEM);return e.defaultKeyId||b.defaultKeyId};shaka.dash.ContentProtection.getWidevineLicenseUrl=function(a){return(a=shaka.util.XmlUtils.findChildNS(a.node,"urn:microsoft","laurl"))?a.getAttribute("licenseUrl")||"":""};
shaka.dash.ContentProtection.getClearKeyLicenseUrl=function(a){return(a=shaka.util.XmlUtils.findChildNS(a.node,shaka.dash.ContentProtection.ClearKeyNamespaceUri_,"Laurl"))&&"EME-1.0"===a.getAttribute("Lic_type")&&a.textContent?a.textContent:""};
shaka.dash.ContentProtection.parseMsProRecords_=function(a,b){for(var c=[];b<a.byteLength-1;){var d=a.getUint16(b,!0);b+=2;var e=a.getUint16(b,!0);b+=2;if(0!=(e&1)||e+b>a.byteLength)return shaka.log.warning("Malformed MS PRO object"),[];var f=shaka.util.BufferUtils.toUint8(a,b,e);c.push({type:d,value:f});b+=e}return c};
shaka.dash.ContentProtection.parseMsPro_=function(a){var b=0,c=shaka.util.BufferUtils.toDataView(a),d=c.getUint32(b,!0);b+=4;return d!=a.byteLength?(shaka.log.warning("PlayReady Object with invalid length encountered."),[]):shaka.dash.ContentProtection.parseMsProRecords_(c,b+2)};
shaka.dash.ContentProtection.getLaurl_=function(a){a=$jscomp.makeIterator(a.getElementsByTagName("DATA"));for(var b=a.next();!b.done;b=a.next()){b=$jscomp.makeIterator(b.value.childNodes);for(var c=b.next();!c.done;c=b.next())if(c=c.value,c instanceof Element&&"LA_URL"==c.tagName)return c.textContent}return""};
shaka.dash.ContentProtection.getPlayReadyLicenseUrl=function(a){var b=shaka.util.XmlUtils.findChildNS(a.node,"urn:microsoft:playready","pro");if(!b)return"";a=shaka.dash.ContentProtection;var c=a.PLAYREADY_RECORD_TYPES;b=shaka.util.Uint8ArrayUtils.fromBase64(b.textContent);b=a.parseMsPro_(b).filter(function(d){return d.type===c.RIGHTS_MANAGEMENT})[0];if(!b)return"";b=shaka.util.StringUtils.fromUTF16(b.value,!0);return(b=shaka.util.XmlUtils.parseXmlString(b,"WRMHEADER"))?a.getLaurl_(b):""};
shaka.dash.ContentProtection.getInitDataFromPro_=function(a){var b=shaka.util.XmlUtils.findChildNS(a.node,"urn:microsoft:playready","pro");if(!b)return null;b=shaka.util.Uint8ArrayUtils.fromBase64(b.textContent);var c=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]),d=new Set;return[{initData:shaka.util.Pssh.createPssh(b,c,d,0),initDataType:"cenc",keyId:a.keyId}]};
shaka.dash.ContentProtection.getInitDataClearKey_=function(a,b){if(0==b.size)return null;var c=new Uint8Array([16,119,239,236,192,178,77,2,172,227,60,30,82,226,251,75]),d=new Uint8Array([]);return[{initData:shaka.util.Pssh.createPssh(d,c,b,1),initDataType:"cenc",keyId:a.keyId}]};
shaka.dash.ContentProtection.convertElements_=function(a,b,c,d){var e=shaka.dash.ContentProtection,f=shaka.util.ManifestParserUtils,g=e.licenseUrlParsers_,h=[];b=$jscomp.makeIterator(b);for(var k=b.next();!k.done;k=b.next()){k=k.value;var l=c[k.schemeUri];if(l){goog.asserts.assert(!k.init||k.init.length,"Init data must be null or non-empty.");var m=e.getInitDataFromPro_(k),n=null;k.schemeUri===shaka.dash.ContentProtection.ClearKeySchemeUri_&&(n=e.getInitDataClearKey_(k,d));m=f.createDrmInfo(l,k.init||
a||m||n);if(l=g.get(l))m.licenseServerUri=l(k);h.push(m)}}return h};shaka.dash.ContentProtection.parseElements_=function(a){var b=[];a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())(c=shaka.dash.ContentProtection.parseElement_(c.value))&&b.push(c);return b};
shaka.dash.ContentProtection.parseElement_=function(a){var b=shaka.dash.ContentProtection.CencNamespaceUri_,c=a.getAttribute("schemeIdUri"),d=shaka.util.XmlUtils.getAttributeNS(a,b,"default_KID");b=shaka.util.XmlUtils.findChildrenNS(a,b,"pssh").map(shaka.util.XmlUtils.getContents);if(!c)return shaka.log.error("Missing required schemeIdUri attribute on","ContentProtection element",a),null;c=c.toLowerCase();if(d&&(d=d.replace(/-/g,"").toLowerCase(),d.includes(" ")))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED);var e=[];try{e=b.map(function(f){return{initDataType:"cenc",initData:shaka.util.Uint8ArrayUtils.fromBase64(f),keyId:null}})}catch(f){throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_PSSH_BAD_ENCODING);}return{node:a,schemeUri:c,keyId:d,init:0<e.length?e:null}};
shaka.dash.ContentProtection.PLAYREADY_RECORD_TYPES={RIGHTS_MANAGEMENT:1,RESERVED:2,EMBEDDED_LICENSE:3};
shaka.dash.ContentProtection.licenseUrlParsers_=(new Map).set("com.widevine.alpha",shaka.dash.ContentProtection.getWidevineLicenseUrl).set("com.microsoft.playready",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.recommendation",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.software",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("com.microsoft.playready.hardware",shaka.dash.ContentProtection.getPlayReadyLicenseUrl).set("org.w3.clearkey",
shaka.dash.ContentProtection.getClearKeyLicenseUrl);shaka.dash.ContentProtection.MP4Protection_="urn:mpeg:dash:mp4protection:2011";shaka.dash.ContentProtection.CencNamespaceUri_="urn:mpeg:cenc:2013";shaka.dash.ContentProtection.ClearKeyNamespaceUri_="http://dashif.org/guidelines/clearKey";shaka.dash.ContentProtection.ClearKeySchemeUri_="urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e";shaka.dash.MpdUtils=function(){};
shaka.dash.MpdUtils.fillUriTemplate=function(a,b,c,d,e){var f={RepresentationID:b,Number:c,Bandwidth:d,Time:e};return a.replace(/\$(RepresentationID|Number|Bandwidth|Time)?(?:%0([0-9]+)([diouxX]))?\$/g,function(g,h,k,l){if("$$"==g)return"$";var m=f[h];goog.asserts.assert(void 0!==m,"Unrecognized identifier");if(null==m)return shaka.log.warning("URL template does not have an available substitution for ",'identifier "'+h+'":',a),g;"RepresentationID"==h&&k&&(shaka.log.warning("URL template should not contain a width specifier for identifier",'"RepresentationID":',
a),k=void 0);"Time"==h&&(goog.asserts.assert("number"==typeof m,"Time value should be a number!"),goog.asserts.assert(.2>Math.abs(m-Math.round(m)),"Calculated $Time$ values must be close to integers"),m=Math.round(m));switch(l){case void 0:case "d":case "i":case "u":g=m.toString();break;case "o":g=m.toString(8);break;case "x":g=m.toString(16);break;case "X":g=m.toString(16).toUpperCase();break;default:goog.asserts.assert(!1,"Unhandled format specifier"),g=m.toString()}k=parseInt(k,10)||1;return Array(Math.max(0,
k-g.length)+1).join("0")+g})};
shaka.dash.MpdUtils.createTimeline=function(a,b,c,d){goog.asserts.assert(0<b&&Infinity>b,"timescale must be a positive, finite integer");goog.asserts.assert(0<d,"period duration must be a positive integer");var e=shaka.util.XmlUtils;a=e.findChildren(a,"S");for(var f=[],g=-c,h=0;h<a.length;++h){var k=a[h],l=a[h+1],m=e.parseAttr(k,"t",e.parseNonNegativeInt),n=e.parseAttr(k,"d",e.parseNonNegativeInt),p=e.parseAttr(k,"r",e.parseInt);null!=m&&(m-=c);if(!n){shaka.log.warning('"S" element must have a duration:','ignoring the remaining "S" elements.',
k);break}m=null!=m?m:g;p=p||0;if(0>p)if(l){l=e.parseAttr(l,"t",e.parseNonNegativeInt);if(null==l){shaka.log.warning('An "S" element cannot have a negative repeat','if the next "S" element does not have a valid start time:','ignoring the remaining "S" elements.',k);break}else if(m>=l){shaka.log.warning('An "S" element cannot have a negative repeatif its start ','time exceeds the next "S" element\'s start time:','ignoring the remaining "S" elements.',k);break}p=Math.ceil((l-m)/n)-1}else{if(Infinity==
d){shaka.log.warning('The last "S" element cannot have a negative repeat',"if the Period has an infinite duration:",'ignoring the last "S" element.',k);break}else if(m/b>=d){shaka.log.warning('The last "S" element cannot have a negative repeat',"if its start time exceeds the Period's duration:",'igoring the last "S" element.',k);break}p=Math.ceil((d*b-m)/n)-1}0<f.length&&m!=g&&(Math.abs((m-g)/b)>=shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS&&shaka.log.warning("SegmentTimeline contains a large gap/overlap:",
"the content may have errors in it.",k),f[f.length-1].end=m/b);for(k=0;k<=p;++k)g=m+n,f.push({start:m/b,end:g/b,unscaledStart:m}),m=g}return f};
shaka.dash.MpdUtils.parseSegmentInfo=function(a,b){goog.asserts.assert(b(a.representation),"There must be at least one element of the given type.");var c=shaka.dash.MpdUtils,d=shaka.util.XmlUtils,e=c.inheritAttribute(a,b,"timescale"),f=1;e&&(f=d.parsePositiveInt(e)||1);var g=c.inheritAttribute(a,b,"duration");e=d.parsePositiveInt(g||"");a.representation.contentType==shaka.util.ManifestParserUtils.ContentType.IMAGE&&(e=d.parseFloat(g||""));e&&(e/=f);var h=c.inheritAttribute(a,b,"startNumber");g=Number(c.inheritAttribute(a,
b,"presentationTimeOffset"))||0;d=d.parseNonNegativeInt(h||"");if(null==h||null==d)d=1;b=c.inheritChild(a,b,"SegmentTimeline");h=null;b&&(h=c.createTimeline(b,f,g,a.periodInfo.duration||Infinity));return{timescale:f,segmentDuration:e,startNumber:d,scaledPresentationTimeOffset:g/f||0,unscaledPresentationTimeOffset:g,timeline:h}};
shaka.dash.MpdUtils.inheritAttribute=function(a,b,c){var d=shaka.util.Functional;goog.asserts.assert(b(a.representation),"There must be at least one element of the given type");return[b(a.representation),b(a.adaptationSet),b(a.period)].filter(d.isNotNull).map(function(e){return e.getAttribute(c)}).reduce(function(e,f){return e||f})};
shaka.dash.MpdUtils.inheritChild=function(a,b,c){var d=shaka.util.Functional;goog.asserts.assert(b(a.representation),"There must be at least one element of the given type");a=[b(a.representation),b(a.adaptationSet),b(a.period)].filter(d.isNotNull);var e=shaka.util.XmlUtils;return a.map(function(f){return e.findChild(f,c)}).reduce(function(f,g){return f||g})};
shaka.dash.MpdUtils.handleXlinkInElement_=function(a,b,c,d,e,f){var g=shaka.util.XmlUtils,h=shaka.util.Error,k=shaka.util.ManifestParserUtils,l=shaka.dash.MpdUtils.XlinkNamespaceUri_,m=g.getAttributeNS(a,l,"href");g=g.getAttributeNS(a,l,"actuate")||"onRequest";for(var n=$jscomp.makeIterator(Array.from(a.attributes)),p=n.next();!p.done;p=n.next())p=p.value,p.namespaceURI==l&&a.removeAttributeNS(p.namespaceURI,p.localName);if(5<=f)return shaka.util.AbortableOperation.failed(new h(h.Severity.CRITICAL,
h.Category.MANIFEST,h.Code.DASH_XLINK_DEPTH_LIMIT));if("onLoad"!=g)return shaka.util.AbortableOperation.failed(new h(h.Severity.CRITICAL,h.Category.MANIFEST,h.Code.DASH_UNSUPPORTED_XLINK_ACTUATE));var q=k.resolveUris([d],[m]);d=shaka.net.NetworkingEngine.RequestType.MANIFEST;k=shaka.net.NetworkingEngine.makeRequest(q,b);d=e.request(d,k);goog.asserts.assert(d instanceof shaka.util.AbortableOperation,"Unexpected implementation of IAbortableOperation!");return d.chain(function(r){r=shaka.util.XmlUtils.parseXml(r.data,
a.tagName);if(!r)return shaka.util.AbortableOperation.failed(new h(h.Severity.CRITICAL,h.Category.MANIFEST,h.Code.DASH_INVALID_XML,m));for(;a.childNodes.length;)a.removeChild(a.childNodes[0]);for(;r.childNodes.length;){var w=r.childNodes[0];r.removeChild(w);a.appendChild(w)}r=$jscomp.makeIterator(Array.from(r.attributes));for(w=r.next();!w.done;w=r.next())a.setAttributeNode(w.value.cloneNode(!1));return shaka.dash.MpdUtils.processXlinks(a,b,c,q[0],e,f+1)})};
shaka.dash.MpdUtils.processXlinks=function(a,b,c,d,e,f){f=void 0===f?0:f;var g=shaka.dash.MpdUtils,h=shaka.util.XmlUtils,k=g.XlinkNamespaceUri_;if(h.getAttributeNS(a,k,"href"))return h=g.handleXlinkInElement_(a,b,c,d,e,f),c&&(h=h.chain(void 0,function(p){return g.processXlinks(a,b,c,d,e,f)})),h;for(var l=[],m=$jscomp.makeIterator(Array.from(a.childNodes)),n=m.next();!n.done;n=m.next())n=n.value,n instanceof Element&&("urn:mpeg:dash:resolve-to-zero:2013"==h.getAttributeNS(n,k,"href")?a.removeChild(n):
"SegmentTimeline"!=n.tagName&&l.push(shaka.dash.MpdUtils.processXlinks(n,b,c,d,e,f)));return shaka.util.AbortableOperation.all(l).chain(function(){return a})};shaka.dash.MpdUtils.XlinkNamespaceUri_="http://www.w3.org/1999/xlink";shaka.media.Mp4SegmentIndexParser=function(){};shaka.media.Mp4SegmentIndexParser.parse=function(a,b,c,d,e,f,g){var h=shaka.media.Mp4SegmentIndexParser,k,l=(new shaka.util.Mp4Parser).fullBox("sidx",function(m){k=h.parseSIDX_(b,d,e,f,g,c,m)});a&&l.parse(a);if(k)return k;shaka.log.error('Invalid box type, expected "sidx".');throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MP4_SIDX_WRONG_BOX_TYPE);};
shaka.media.Mp4SegmentIndexParser.parseSIDX_=function(a,b,c,d,e,f,g){goog.asserts.assert(null!=g.version,"SIDX is a full box and should have a valid version.");var h=[];g.reader.skip(4);var k=g.reader.readUint32();if(0==k)throw shaka.log.error("Invalid timescale."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MP4_SIDX_INVALID_TIMESCALE);if(0==g.version){var l=g.reader.readUint32();var m=g.reader.readUint32()}else l=g.reader.readUint64(),
m=g.reader.readUint64();g.reader.skip(2);var n=g.reader.readUint16();a=a+g.size+m;for(m=0;m<n;m++){var p=g.reader.readUint32(),q=(p&2147483648)>>>31;p&=2147483647;var r=g.reader.readUint32();g.reader.skip(4);if(1==q)throw shaka.log.error("Heirarchical SIDXs are not supported."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.MP4_SIDX_TYPE_NOT_SUPPORTED);h.push(new shaka.media.SegmentReference(l/k+c,(l+r)/k+c,function(){return f},a,a+p-
1,b,c,d,e));l+=r;a+=p}g.parser.stop();return h};shaka.util.EbmlParser=function(a){this.dataView_=shaka.util.BufferUtils.toDataView(a);this.reader_=new shaka.util.DataViewReader(this.dataView_,shaka.util.DataViewReader.Endianness.BIG_ENDIAN)};shaka.util.EbmlParser.prototype.hasMoreData=function(){return this.reader_.hasMoreData()};
shaka.util.EbmlParser.prototype.parseElement=function(){var a=this.parseId_(),b=this.parseVint_();b=shaka.util.EbmlParser.isDynamicSizeValue_(b)?this.dataView_.byteLength-this.reader_.getPosition():shaka.util.EbmlParser.getVintValue_(b);b=this.reader_.getPosition()+b<=this.dataView_.byteLength?b:this.dataView_.byteLength-this.reader_.getPosition();var c=shaka.util.BufferUtils.toDataView(this.dataView_,this.reader_.getPosition(),b);this.reader_.skip(b);return new shaka.util.EbmlElement(a,c)};
shaka.util.EbmlParser.prototype.parseId_=function(){var a=this.parseVint_();if(7<a.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_OVERFLOW);var b=0;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())b=256*b+c.value;return b};
shaka.util.EbmlParser.prototype.parseVint_=function(){var a=this.reader_.getPosition(),b=this.reader_.readUint8();if(0==b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_OVERFLOW);b=8-Math.floor(Math.log2(b));goog.asserts.assert(8>=b&&1<=b,"Incorrect log2 value");this.reader_.skip(b-1);return shaka.util.BufferUtils.toUint8(this.dataView_,a,b)};
shaka.util.EbmlParser.getVintValue_=function(a){if(8==a.length&&a[1]&224)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.JS_INTEGER_OVERFLOW);for(var b=0,c=0;c<a.length;c++){var d=a[c];b=0==c?d&(1<<8-a.length)-1:256*b+d}return b};
shaka.util.EbmlParser.isDynamicSizeValue_=function(a){for(var b=shaka.util.BufferUtils,c=$jscomp.makeIterator(shaka.util.EbmlParser.DYNAMIC_SIZES),d=c.next();!d.done;d=c.next())if(b.equal(a,new Uint8Array(d.value)))return!0;return!1};shaka.util.EbmlParser.DYNAMIC_SIZES=[[255],[127,255],[63,255,255],[31,255,255,255],[15,255,255,255,255],[7,255,255,255,255,255],[3,255,255,255,255,255,255],[1,255,255,255,255,255,255,255]];shaka.util.EbmlElement=function(a,b){this.id=a;this.dataView_=b};
shaka.util.EbmlElement.prototype.getOffset=function(){return this.dataView_.byteOffset};shaka.util.EbmlElement.prototype.createParser=function(){return new shaka.util.EbmlParser(this.dataView_)};
shaka.util.EbmlElement.prototype.getUint=function(){if(8<this.dataView_.byteLength)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_OVERFLOW);if(8==this.dataView_.byteLength&&this.dataView_.getUint8(0)&224)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.JS_INTEGER_OVERFLOW);for(var a=0,b=0;b<this.dataView_.byteLength;b++){var c=this.dataView_.getUint8(b);a=256*
a+c}return a};shaka.util.EbmlElement.prototype.getFloat=function(){if(4==this.dataView_.byteLength)return this.dataView_.getFloat32(0);if(8==this.dataView_.byteLength)return this.dataView_.getFloat64(0);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.EBML_BAD_FLOATING_POINT_SIZE);};shaka.media.WebmSegmentIndexParser=function(){};
shaka.media.WebmSegmentIndexParser.parse=function(a,b,c,d,e,f,g){b=shaka.media.WebmSegmentIndexParser.parseWebmContainer_(b);a=(new shaka.util.EbmlParser(a)).parseElement();if(a.id!=shaka.media.WebmSegmentIndexParser.CUES_ID)throw shaka.log.error("Not a Cues element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_CUES_ELEMENT_MISSING);return shaka.media.WebmSegmentIndexParser.parseCues_(a,b.segmentOffset,b.timecodeScale,b.duration,
c,d,e,f,g)};
shaka.media.WebmSegmentIndexParser.parseWebmContainer_=function(a){a=new shaka.util.EbmlParser(a);if(a.parseElement().id!=shaka.media.WebmSegmentIndexParser.EBML_ID)throw shaka.log.error("Not an EBML element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_EBML_HEADER_ELEMENT_MISSING);var b=a.parseElement();if(b.id!=shaka.media.WebmSegmentIndexParser.SEGMENT_ID)throw shaka.log.error("Not a Segment element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,
shaka.util.Error.Code.WEBM_SEGMENT_ELEMENT_MISSING);a=b.getOffset();b=shaka.media.WebmSegmentIndexParser.parseSegment_(b);return{segmentOffset:a,timecodeScale:b.timecodeScale,duration:b.duration}};
shaka.media.WebmSegmentIndexParser.parseSegment_=function(a){a=a.createParser();for(var b=null;a.hasMoreData();){var c=a.parseElement();if(c.id==shaka.media.WebmSegmentIndexParser.INFO_ID){b=c;break}}if(!b)throw shaka.log.error("Not an Info element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_INFO_ELEMENT_MISSING);return shaka.media.WebmSegmentIndexParser.parseInfo_(b)};
shaka.media.WebmSegmentIndexParser.parseInfo_=function(a){var b=a.createParser(),c=1E6;for(a=null;b.hasMoreData();){var d=b.parseElement();d.id==shaka.media.WebmSegmentIndexParser.TIMECODE_SCALE_ID?c=d.getUint():d.id==shaka.media.WebmSegmentIndexParser.DURATION_ID&&(a=d.getFloat())}if(null==a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_DURATION_ELEMENT_MISSING);b=c/1E9;return{timecodeScale:b,duration:a*b}};
shaka.media.WebmSegmentIndexParser.parseCues_=function(a,b,c,d,e,f,g,h,k){var l=[],m=function(){return e};a=a.createParser();for(var n=null,p=null;a.hasMoreData();){var q=a.parseElement();if(q.id==shaka.media.WebmSegmentIndexParser.CUE_POINT_ID){var r=shaka.media.WebmSegmentIndexParser.parseCuePoint_(q);r&&(q=c*r.unscaledTime,r=b+r.relativeOffset,null!=n&&(goog.asserts.assert(null!=p,"last offset cannot be null"),l.push(new shaka.media.SegmentReference(n+g,q+g,m,p,r-1,f,g,h,k))),n=q,p=r)}}null!=n&&
(goog.asserts.assert(null!=p,"last offset cannot be null"),l.push(new shaka.media.SegmentReference(n+g,d+g,m,p,null,f,g,h,k)));return l};
shaka.media.WebmSegmentIndexParser.parseCuePoint_=function(a){var b=a.createParser();a=b.parseElement();if(a.id!=shaka.media.WebmSegmentIndexParser.CUE_TIME_ID)throw shaka.log.warning("Not a CueTime element."),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_CUE_TIME_ELEMENT_MISSING);a=a.getUint();b=b.parseElement();if(b.id!=shaka.media.WebmSegmentIndexParser.CUE_TRACK_POSITIONS_ID)throw shaka.log.warning("Not a CueTrackPositions element."),
new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MEDIA,shaka.util.Error.Code.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING);b=b.createParser();for(var c=0;b.hasMoreData();){var d=b.parseElement();if(d.id==shaka.media.WebmSegmentIndexParser.CUE_CLUSTER_POSITION){c=d.getUint();break}}return{unscaledTime:a,relativeOffset:c}};shaka.media.WebmSegmentIndexParser.EBML_ID=440786851;shaka.media.WebmSegmentIndexParser.SEGMENT_ID=408125543;
shaka.media.WebmSegmentIndexParser.INFO_ID=357149030;shaka.media.WebmSegmentIndexParser.TIMECODE_SCALE_ID=2807729;shaka.media.WebmSegmentIndexParser.DURATION_ID=17545;shaka.media.WebmSegmentIndexParser.CUES_ID=475249515;shaka.media.WebmSegmentIndexParser.CUE_POINT_ID=187;shaka.media.WebmSegmentIndexParser.CUE_TIME_ID=179;shaka.media.WebmSegmentIndexParser.CUE_TRACK_POSITIONS_ID=183;shaka.media.WebmSegmentIndexParser.CUE_CLUSTER_POSITION=241;shaka.dash.SegmentBase=function(){};
shaka.dash.SegmentBase.createInitSegment=function(a,b){var c=shaka.util.XmlUtils,d=shaka.util.ManifestParserUtils;b=shaka.dash.MpdUtils.inheritChild(a,b,"Initialization");if(!b)return null;var e=a.representation.baseUris,f=b.getAttribute("sourceURL");f&&(e=d.resolveUris(a.representation.baseUris,[f]));d=0;f=null;if(c=c.parseAttr(b,"range",c.parseRange))d=c.start,f=c.end;a=shaka.dash.SegmentBase.createQualityInfo(a);return new shaka.media.InitSegmentReference(function(){return e},d,f,a)};
shaka.dash.SegmentBase.createStreamInfo=function(a,b){goog.asserts.assert(a.representation.segmentBase,"Should only be called with SegmentBase");var c=shaka.dash.MpdUtils,d=shaka.dash.SegmentBase,e=shaka.util.XmlUtils,f=Number(c.inheritAttribute(a,d.fromInheritance_,"presentationTimeOffset"))||0;c=c.inheritAttribute(a,d.fromInheritance_,"timescale");var g=1;c&&(g=e.parsePositiveInt(c)||1);var h=f/g||0,k=d.createInitSegment(a,d.fromInheritance_);d.checkSegmentIndexRangeSupport_(a,k);var l=shaka.util.ObjectUtils.shallowCloneObject(a);
return{generateSegmentIndex:function(){return d.generateSegmentIndex_(l,b,k,h)}}};
shaka.dash.SegmentBase.generateSegmentIndexFromUris=function(a,b,c,d,e,f,g){var h,k,l,m,n,p,q,r,w,u,v,x,t,y,A;return $jscomp.asyncExecutePromiseGeneratorProgram(function(z){if(1==z.nextAddress)return h=a.presentationTimeline,k=!a.dynamic||!a.periodInfo.isLastPeriod,l=a.periodInfo.start,m=a.periodInfo.duration,n=a.representation.mimeType.split("/")[1],p=b,q=null,r=[p(d,e,f),"webm"==n?p(c.getUris(),c.startByte,c.endByte):null],p=null,z.yield(Promise.all(r),2);w=z.yieldResult;u=w[0];v=w[1]||null;x=null;
t=l-g;y=l;A=m?l+m:Infinity;"mp4"==n?x=shaka.media.Mp4SegmentIndexParser.parse(u,e,d,c,t,y,A):(goog.asserts.assert(v,"WebM requires init data"),x=shaka.media.WebmSegmentIndexParser.parse(u,v,d,c,t,y,A));h.notifySegments(x);goog.asserts.assert(!q,"Should not call generateSegmentIndex twice");q=new shaka.media.SegmentIndex(x);k&&q.fit(y,A,!0);return z.return(q)})};shaka.dash.SegmentBase.fromInheritance_=function(a){return a.segmentBase};
shaka.dash.SegmentBase.computeIndexRange_=function(a){var b=shaka.dash.MpdUtils,c=shaka.dash.SegmentBase,d=shaka.util.XmlUtils,e=b.inheritChild(a,c.fromInheritance_,"RepresentationIndex");a=b.inheritAttribute(a,c.fromInheritance_,"indexRange");a=d.parseRange(a||"");e&&(a=d.parseAttr(e,"range",d.parseRange,a));return a};
shaka.dash.SegmentBase.computeIndexUris_=function(a){var b=shaka.util.ManifestParserUtils,c=shaka.dash.MpdUtils.inheritChild(a,shaka.dash.SegmentBase.fromInheritance_,"RepresentationIndex"),d=a.representation.baseUris;c&&(c=c.getAttribute("sourceURL"))&&(d=b.resolveUris(a.representation.baseUris,[c]));return d};
shaka.dash.SegmentBase.checkSegmentIndexRangeSupport_=function(a,b){var c=shaka.dash.SegmentBase;c.checkSegmentIndexSupport(a,b);if(!c.computeIndexRange_(a))throw shaka.log.error("SegmentBase does not contain sufficient segment information:","the SegmentBase does not contain @indexRange","or a RepresentationIndex element.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);};
shaka.dash.SegmentBase.checkSegmentIndexSupport=function(a,b){var c=shaka.util.ManifestParserUtils.ContentType,d=a.representation.contentType,e=a.representation.mimeType.split("/")[1];if(d!=c.TEXT&&"mp4"!=e&&"webm"!=e)throw shaka.log.error("SegmentBase specifies an unsupported container type.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_UNSUPPORTED_CONTAINER);if("webm"==e&&!b)throw shaka.log.error("SegmentBase does not contain sufficient segment information:",
"the SegmentBase uses a WebM container,","but does not contain an Initialization element.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_WEBM_MISSING_INIT);};
shaka.dash.SegmentBase.generateSegmentIndex_=function(a,b,c,d){var e=shaka.dash.SegmentBase,f=e.computeIndexUris_(a);e=e.computeIndexRange_(a);goog.asserts.assert(e,"Index range should not be null!");return shaka.dash.SegmentBase.generateSegmentIndexFromUris(a,b,c,f,e.start,e.end,d)};
shaka.dash.SegmentBase.createQualityInfo=function(a){var b=a.representation;return{bandwidth:a.bandwidth,audioSamplingRate:b.audioSamplingRate,codecs:b.codecs,contentType:b.contentType,frameRate:b.frameRate||null,height:b.height||null,mimeType:b.mimeType,channelsCount:b.numChannels,pixelAspectRatio:b.pixelAspectRatio||null,width:b.width||null}};shaka.dash.SegmentList=function(){};
shaka.dash.SegmentList.createStreamInfo=function(a,b){goog.asserts.assert(a.representation.segmentList,"Should only be called with SegmentList");var c=shaka.dash.SegmentList,d=shaka.dash.SegmentBase.createInitSegment(a,c.fromInheritance_),e=c.parseSegmentListInfo_(a);c.checkSegmentListInfo_(a,e);var f=null,g=null;a.period.id&&a.representation.id&&(g=b[a.period.id+","+a.representation.id])&&(f=g.segmentIndex);var h=c.createSegmentReferences_(a.periodInfo.start,a.periodInfo.duration,e.startNumber,a.representation.baseUris,
e,d);b=!f;f?(c=a.presentationTimeline.getSegmentAvailabilityStart(),f.mergeAndEvict(h,c)):f=new shaka.media.SegmentIndex(h);a.presentationTimeline.notifySegments(h);a.dynamic&&a.periodInfo.isLastPeriod||f.fit(a.periodInfo.start,a.periodInfo.duration?a.periodInfo.start+a.periodInfo.duration:Infinity,b);g&&(g.segmentIndex=f);return{generateSegmentIndex:function(){f&&!f.isEmpty()||f.merge(h);return Promise.resolve(f)}}};shaka.dash.SegmentList.fromInheritance_=function(a){return a.segmentList};
shaka.dash.SegmentList.parseSegmentListInfo_=function(a){var b=shaka.dash.SegmentList,c=shaka.dash.MpdUtils,d=b.parseMediaSegments_(a);a=c.parseSegmentInfo(a,b.fromInheritance_);b=a.startNumber;0==b&&(shaka.log.warning("SegmentList@startNumber must be > 0"),b=1);c=0;a.segmentDuration?c=a.segmentDuration*(b-1):a.timeline&&0<a.timeline.length&&(c=a.timeline[0].start);return{segmentDuration:a.segmentDuration,startTime:c,startNumber:b,scaledPresentationTimeOffset:a.scaledPresentationTimeOffset,timeline:a.timeline,
mediaSegments:d}};
shaka.dash.SegmentList.checkSegmentListInfo_=function(a,b){if(!b.segmentDuration&&!b.timeline&&1<b.mediaSegments.length)throw shaka.log.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies multiple segments,","but does not specify a segment duration or timeline.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);if(!b.segmentDuration&&!a.periodInfo.duration&&
!b.timeline&&1==b.mediaSegments.length)throw shaka.log.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies one segment,","but does not specify a segment duration, period duration,","or timeline.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);if(b.timeline&&0==b.timeline.length)throw shaka.log.warning("SegmentList does not contain sufficient segment information:",
"the SegmentList has an empty timeline.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);};
shaka.dash.SegmentList.createSegmentReferences_=function(a,b,c,d,e,f){c=shaka.util.ManifestParserUtils;var g=e.mediaSegments.length;e.timeline&&e.timeline.length!=e.mediaSegments.length&&(g=Math.min(e.timeline.length,e.mediaSegments.length),shaka.log.warning("The number of items in the segment timeline and the number of ","segment URLs do not match, truncating",e.mediaSegments.length,"to",g));for(var h=a-e.scaledPresentationTimeOffset,k=b?a+b:Infinity,l=[],m=e.startTime,n={},p=0;p<g;n={$jscomp$loop$prop$mediaUri$662:n.$jscomp$loop$prop$mediaUri$662},
p++){var q=e.mediaSegments[p];n.$jscomp$loop$prop$mediaUri$662=c.resolveUris(d,[q.mediaUri]);var r=void 0;null!=e.segmentDuration?r=m+e.segmentDuration:e.timeline?r=e.timeline[p].end:(goog.asserts.assert(1==e.mediaSegments.length&&b,"There should be exactly one segment with a Period duration."),r=m+b);var w=function(u){return function(){return u.$jscomp$loop$prop$mediaUri$662}}(n);l.push(new shaka.media.SegmentReference(a+m,a+r,w,q.start,q.end,f,h,a,k));m=r}return l};
shaka.dash.SegmentList.parseMediaSegments_=function(a){var b=[a.representation.segmentList,a.adaptationSet.segmentList,a.period.segmentList].filter(shaka.util.Functional.isNotNull),c=shaka.util.XmlUtils;return b.map(function(d){return c.findChildren(d,"SegmentURL")}).reduce(function(d,e){return 0<d.length?d:e}).map(function(d){d.getAttribute("indexRange")&&!a.indexRangeWarningGiven&&(a.indexRangeWarningGiven=!0,shaka.log.warning("We do not support the SegmentURL@indexRange attribute on SegmentList.  We only use the SegmentList@duration attribute or SegmentTimeline, which must be accurate."));
var e=d.getAttribute("media");d=c.parseAttr(d,"mediaRange",c.parseRange,{start:0,end:null});return{mediaUri:e,start:d.start,end:d.end}})};shaka.dash.SegmentTemplate=function(){};
shaka.dash.SegmentTemplate.createStreamInfo=function(a,b,c,d,e,f){goog.asserts.assert(a.representation.segmentTemplate,"Should only be called with SegmentTemplate");var g=shaka.dash.SegmentTemplate,h=g.createInitSegment_(a),k=g.parseSegmentTemplateInfo_(a);g.checkSegmentTemplateInfo_(a,k);var l=shaka.util.ObjectUtils.shallowCloneObject(a);if(k.indexTemplate)return shaka.dash.SegmentBase.checkSegmentIndexSupport(a,h),{generateSegmentIndex:function(){return g.generateSegmentIndexFromIndexTemplate_(l,b,
h,k)}};if(k.segmentDuration)return d||"image"===a.adaptationSet.contentType||(a.presentationTimeline.notifyMaxSegmentDuration(k.segmentDuration),a.presentationTimeline.notifyMinSegmentStartTime(a.periodInfo.start)),{generateSegmentIndex:function(){return g.generateSegmentIndexFromDuration_(l,k,e,h,f)}};var m=null;d=d=null;a.period.id&&a.representation.id&&(d=a.period.id+","+a.representation.id,d=c[d])&&(m=d.segmentIndex);var n=g.createFromTimeline_(l,k,h);c=a.periodInfo.start;var p=a.periodInfo.duration?
a.periodInfo.start+a.periodInfo.duration:Infinity,q=!(a.dynamic&&a.periodInfo.isLastPeriod);m?(q&&(new shaka.media.SegmentIndex(n)).fit(c,p,!0),m.mergeAndEvict(n,a.presentationTimeline.getSegmentAvailabilityStart())):m=new shaka.media.SegmentIndex(n);a.presentationTimeline.notifySegments(n);q&&m.fit(c,p);d&&a.dynamic&&(d.segmentIndex=m);return{generateSegmentIndex:function(){m&&!m.isEmpty()||m.merge(n);return Promise.resolve(m)}}};shaka.dash.SegmentTemplate.fromInheritance_=function(a){return a.segmentTemplate};
shaka.dash.SegmentTemplate.parseSegmentTemplateInfo_=function(a){var b=shaka.dash.SegmentTemplate,c=shaka.dash.MpdUtils,d=c.parseSegmentInfo(a,b.fromInheritance_),e=c.inheritAttribute(a,b.fromInheritance_,"media");a=c.inheritAttribute(a,b.fromInheritance_,"index");return{segmentDuration:d.segmentDuration,timescale:d.timescale,startNumber:d.startNumber,scaledPresentationTimeOffset:d.scaledPresentationTimeOffset,unscaledPresentationTimeOffset:d.unscaledPresentationTimeOffset,timeline:d.timeline,mediaTemplate:e,
indexTemplate:a}};
shaka.dash.SegmentTemplate.checkSegmentTemplateInfo_=function(a,b){var c=b.indexTemplate?1:0;c+=b.timeline?1:0;c+=b.segmentDuration?1:0;if(0==c)throw shaka.log.error("SegmentTemplate does not contain any segment information:","the SegmentTemplate must contain either an index URL template","a SegmentTimeline, or a segment duration.",a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);1!=c&&(shaka.log.warning("SegmentTemplate containes multiple segment information sources:",
"the SegmentTemplate should only contain an index URL template,","a SegmentTimeline or a segment duration.",a.representation),b.indexTemplate?(shaka.log.info("Using the index URL template by default."),b.timeline=null):(goog.asserts.assert(b.timeline,"There should be a timeline"),shaka.log.info("Using the SegmentTimeline by default.")),b.segmentDuration=null);if(!b.indexTemplate&&!b.mediaTemplate)throw shaka.log.error("SegmentTemplate does not contain sufficient segment information:","the SegmentTemplate's media URL template is missing.",
a.representation),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_NO_SEGMENT_INFO);};
shaka.dash.SegmentTemplate.generateSegmentIndexFromIndexTemplate_=function(a,b,c,d){var e=shaka.dash.MpdUtils,f=shaka.util.ManifestParserUtils;goog.asserts.assert(d.indexTemplate,"must be using index template");e=e.fillUriTemplate(d.indexTemplate,a.representation.id,null,a.bandwidth||null,null);f=f.resolveUris(a.representation.baseUris,[e]);return shaka.dash.SegmentBase.generateSegmentIndexFromUris(a,b,c,f,0,null,d.scaledPresentationTimeOffset)};
shaka.dash.SegmentTemplate.generateSegmentIndexFromDuration_=function(a,b,c,d,e){goog.asserts.assert(b.mediaTemplate,"There should be a media template with duration");var f=shaka.dash.MpdUtils,g=shaka.util.ManifestParserUtils,h=a.presentationTimeline,k=a.periodInfo.start,l=a.period.id,m=a.periodInfo.duration,n=function(){var E=null!=l&&e[l]||m;return E?k+E:Infinity},p=b.segmentDuration;goog.asserts.assert(null!=p,"Segment duration must not be null!");var q=b.startNumber,r=b.timescale,w=b.mediaTemplate,
u=a.bandwidth||null,v=a.representation.id,x=a.representation.baseUris,t=k-b.scaledPresentationTimeOffset,y=function(){var E=[Math.max(h.getSegmentAvailabilityStart(),k),Math.min(h.getSegmentAvailabilityEnd(),n())];goog.asserts.assert(E.every(isFinite),"Available presentation times must be finite!");goog.asserts.assert(E.every(function(F){return 0<=F}),"Available presentation times must be positive!");goog.asserts.assert(null!=p,"Segment duration must not be null!");E=E.map(function(F){return F-k});
return[Math.ceil(E[0]/p),Math.ceil(E[1]/p)-1].map(function(F){return F+q})},A=y();a=a.dynamic?Math.max(A[0],A[1]-c+1):A[0];A=A[1];c=[];for(var z=function(E){goog.asserts.assert(null!=p,"Segment duration must not be null!");var F=(E-q)*p,I=F+b.scaledPresentationTimeOffset,H=F+k;F=H+p;var K=Math.min(F,n());goog.asserts.assert(H<K,"Generated a segment outside of the period!");H=new shaka.media.SegmentReference(H,K,function(){var J=f.fillUriTemplate(w,v,E,u,I*r);return g.resolveUris(x,[J])},0,null,d,
t,k,n());H.trueEndTime=F;return H},B=a;B<=A;++B){var D=z(B);c.push(D)}var G=new shaka.media.SegmentIndex(c);c=h.getSegmentAvailabilityEnd()<n();B=h.isLive();if(c||B){var C=Math.max(a,A+1);G.updateEvery(p,function(){var E=h.getSegmentAvailabilityStart();G.evict(E);var F=$jscomp.makeIterator(y());F.next();F=F.next().value;for(var I=[];C<=F;){var H=z(C);I.push(H);C++}return E>n()&&!I.length?null:I})}return Promise.resolve(G)};
shaka.dash.SegmentTemplate.createFromTimeline_=function(a,b,c){var d=shaka.dash.MpdUtils,e=shaka.util.ManifestParserUtils,f=a.periodInfo.start,g=a.periodInfo.duration,h=f-b.scaledPresentationTimeOffset;g=g?f+g:Infinity;for(var k=[],l={},m=0;m<b.timeline.length;l={$jscomp$loop$prop$mediaTemplate$664:l.$jscomp$loop$prop$mediaTemplate$664,$jscomp$loop$prop$repId$665:l.$jscomp$loop$prop$repId$665,$jscomp$loop$prop$segmentReplacement$666:l.$jscomp$loop$prop$segmentReplacement$666,$jscomp$loop$prop$bandwidth$667:l.$jscomp$loop$prop$bandwidth$667,
$jscomp$loop$prop$timeReplacement$668:l.$jscomp$loop$prop$timeReplacement$668,$jscomp$loop$prop$baseUris$669:l.$jscomp$loop$prop$baseUris$669},m++){var n=b.timeline[m],p=n.start,q=n.unscaledStart;n=n.end;l.$jscomp$loop$prop$segmentReplacement$666=m+b.startNumber;l.$jscomp$loop$prop$timeReplacement$668=q+b.unscaledPresentationTimeOffset;l.$jscomp$loop$prop$repId$665=a.representation.id;l.$jscomp$loop$prop$bandwidth$667=a.bandwidth||null;l.$jscomp$loop$prop$mediaTemplate$664=b.mediaTemplate;l.$jscomp$loop$prop$baseUris$669=
a.representation.baseUris;q=function(r){return function(){goog.asserts.assert(r.$jscomp$loop$prop$mediaTemplate$664,"There should be a media template with a timeline");var w=d.fillUriTemplate(r.$jscomp$loop$prop$mediaTemplate$664,r.$jscomp$loop$prop$repId$665,r.$jscomp$loop$prop$segmentReplacement$666,r.$jscomp$loop$prop$bandwidth$667||null,r.$jscomp$loop$prop$timeReplacement$668);return e.resolveUris(r.$jscomp$loop$prop$baseUris$669,[w]).map(function(u){return u.toString()})}}(l);k.push(new shaka.media.SegmentReference(f+
p,f+n,q,0,null,c,h,f,g))}return k};
shaka.dash.SegmentTemplate.createInitSegment_=function(a){var b=shaka.dash.MpdUtils,c=shaka.util.ManifestParserUtils,d=b.inheritAttribute(a,shaka.dash.SegmentTemplate.fromInheritance_,"initialization");if(!d)return null;var e=a.representation.id,f=a.bandwidth||null,g=a.representation.baseUris;a=shaka.dash.SegmentBase.createQualityInfo(a);return new shaka.media.InitSegmentReference(function(){goog.asserts.assert(d,"Should have returned earler");var h=b.fillUriTemplate(d,e,null,f,null);return c.resolveUris(g,
[h])},0,null,a)};shaka.util.PeriodCombiner=function(){this.variants_=[];this.audioStreams_=[];this.videoStreams_=[];this.textStreams_=[];this.imageStreams_=[];this.usedPeriodIds_=new Set};
shaka.util.PeriodCombiner.prototype.release=function(){var a=this.audioStreams_.concat(this.videoStreams_,this.textStreams_,this.imageStreams_);a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next())b=b.value,b.segmentIndex&&b.segmentIndex.release();this.audioStreams_=[];this.videoStreams_=[];this.textStreams_=[];this.imageStreams_=[];this.variants_=[]};shaka.util.PeriodCombiner.prototype.getVariants=function(){return this.variants_};shaka.util.PeriodCombiner.prototype.getTextStreams=function(){return this.textStreams_.slice()};
shaka.util.PeriodCombiner.prototype.getImageStreams=function(){return this.imageStreams_};
shaka.util.PeriodCombiner.prototype.combinePeriods=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G,C,E,F,I,H,K,J;return $jscomp.asyncExecutePromiseGeneratorProgram(function(M){switch(M.nextAddress){case 1:d=shaka.util.ManifestParserUtils.ContentType;shaka.util.PeriodCombiner.filterOutAudioStreamDuplicates_(a);shaka.util.PeriodCombiner.filterOutVideoStreamDuplicates_(a);shaka.util.PeriodCombiner.filterOutTextStreamDuplicates_(a);shaka.util.PeriodCombiner.filterOutImageStreamDuplicates_(a);
if(!b&&1==a.length){e=a[0];c.audioStreams_=e.audioStreams;c.videoStreams_=e.videoStreams;c.textStreams_=e.textStreams;c.imageStreams_=e.imageStreams;M.jumpTo(2);break}f=-1;for(g=0;g<a.length;g++)h=a[g],c.usedPeriodIds_.has(h.id)||(c.usedPeriodIds_.add(h.id),-1==f&&(f=g));if(-1==f)return M.return();k=a.map(function(N){return N.audioStreams});l=a.map(function(N){return N.videoStreams});m=a.map(function(N){return N.textStreams});n=a.map(function(N){return N.imageStreams});p=$jscomp.makeIterator(m);for(q=
p.next();!q.done;q=p.next())r=q.value,r.push(shaka.util.PeriodCombiner.dummyStream_(d.TEXT));w=$jscomp.makeIterator(n);for(u=w.next();!u.done;u=w.next())v=u.value,v.push(shaka.util.PeriodCombiner.dummyStream_(d.IMAGE));return M.yield(shaka.util.PeriodCombiner.combine_(c.audioStreams_,k,f,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_),3);case 3:return M.yield(shaka.util.PeriodCombiner.combine_(c.videoStreams_,l,f,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_),
4);case 4:return M.yield(shaka.util.PeriodCombiner.combine_(c.textStreams_,m,f,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_),5);case 5:return M.yield(shaka.util.PeriodCombiner.combine_(c.imageStreams_,n,f,shaka.util.PeriodCombiner.cloneStream_,shaka.util.PeriodCombiner.concatenateStreams_),2);case 2:x=0;t=[];if(c.videoStreams_.length&&c.audioStreams_.length)for(G=$jscomp.makeIterator(c.audioStreams_),C=G.next();!C.done;C=G.next())for(E=C.value,F=$jscomp.makeIterator(c.videoStreams_),
I=F.next();!I.done;I=F.next())H=I.value,K=shaka.media.DrmEngine.getCommonDrmInfos(E.drmInfos,H.drmInfos),E.drmInfos.length&&H.drmInfos.length&&!K.length?shaka.log.warning("Incompatible DRM in audio & video, skipping variant creation.",E,H):(J=x++,t.push({id:J,language:E.language,primary:E.primary,audio:E,video:H,bandwidth:(E.bandwidth||0)+(H.bandwidth||0),drmInfos:K,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]}));else for(y=c.videoStreams_.concat(c.audioStreams_),A=$jscomp.makeIterator(y),
z=A.next();!z.done;z=A.next())B=z.value,D=x++,t.push({id:D,language:B.language,primary:B.primary,audio:B.type==d.AUDIO?B:null,video:B.type==d.VIDEO?B:null,bandwidth:B.bandwidth||0,drmInfos:B.drmInfos,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]});c.variants_=t;M.jumpToEnd()}})};
shaka.util.PeriodCombiner.filterOutAudioStreamDuplicates_=function(a){var b=shaka.util.ArrayUtils;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){c=c.value;for(var d=[],e=$jscomp.makeIterator(c.audioStreams),f=e.next();!f.done;f=e.next()){f=f.value;for(var g=!1,h=$jscomp.makeIterator(d),k=h.next();!k.done;k=h.next())k=k.value,f.id!=k.id&&f.channelsCount==k.channelsCount&&f.language==k.language&&f.bandwidth==k.bandwidth&&f.label==k.label&&f.codecs==k.codecs&&f.mimeType==k.mimeType&&
b.hasSameElements(f.roles,k.roles)&&f.audioSamplingRate==k.audioSamplingRate&&f.primary==k.primary&&(g=!0);g||d.push(f)}c.audioStreams=d}};
shaka.util.PeriodCombiner.filterOutTextStreamDuplicates_=function(a){var b=shaka.util.ArrayUtils;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){c=c.value;for(var d=[],e=$jscomp.makeIterator(c.textStreams),f=e.next();!f.done;f=e.next()){f=f.value;for(var g=!1,h=$jscomp.makeIterator(d),k=h.next();!k.done;k=h.next())k=k.value,f.id!=k.id&&f.language==k.language&&f.label==k.label&&f.codecs==k.codecs&&f.mimeType==k.mimeType&&f.bandwidth==k.bandwidth&&b.hasSameElements(f.roles,k.roles)&&
(g=!0);g||d.push(f)}c.textStreams=d}};
shaka.util.PeriodCombiner.filterOutVideoStreamDuplicates_=function(a){var b=shaka.util.ArrayUtils,c=shaka.util.MapUtils;a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next()){d=d.value;for(var e=[],f=$jscomp.makeIterator(d.videoStreams),g=f.next();!g.done;g=f.next()){g=g.value;for(var h=!1,k=$jscomp.makeIterator(e),l=k.next();!l.done;l=k.next())l=l.value,g.id!=l.id&&g.width==l.width&&g.frameRate==l.frameRate&&g.codecs==l.codecs&&g.mimeType==l.mimeType&&g.label==l.label&&b.hasSameElements(g.roles,
l.roles)&&c.hasSameElements(g.closedCaptions,l.closedCaptions)&&g.bandwidth==l.bandwidth&&(h=!0);h||e.push(g)}d.videoStreams=e}};
shaka.util.PeriodCombiner.filterOutImageStreamDuplicates_=function(a){a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next()){b=b.value;for(var c=[],d=$jscomp.makeIterator(b.imageStreams),e=d.next();!e.done;e=d.next()){e=e.value;for(var f=!1,g=$jscomp.makeIterator(c),h=g.next();!h.done;h=g.next())h=h.value,e.id!=h.id&&e.width==h.width&&e.codecs==h.codecs&&e.mimeType==h.mimeType&&(f=!0);f||c.push(e)}b.imageStreams=c}};
shaka.util.PeriodCombiner.combineDbStreams=function(a){var b,c,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G,C,E;return $jscomp.asyncExecutePromiseGeneratorProgram(function(F){switch(F.nextAddress){case 1:b=shaka.util.ManifestParserUtils.ContentType;if(1==a.length)return F.return(a[0]);c=a.map(function(I){return I.filter(function(H){return H.type==b.AUDIO})});d=a.map(function(I){return I.filter(function(H){return H.type==b.VIDEO})});e=a.map(function(I){return I.filter(function(H){return H.type==b.TEXT})});
f=a.map(function(I){return I.filter(function(H){return H.type==b.IMAGE})});g=$jscomp.makeIterator(e);for(h=g.next();!h.done;h=g.next())k=h.value,k.push(shaka.util.PeriodCombiner.dummyStreamDB_(b.TEXT));l=$jscomp.makeIterator(f);for(m=l.next();!m.done;m=l.next())n=m.value,n.push(shaka.util.PeriodCombiner.dummyStreamDB_(b.IMAGE));return F.yield(shaka.util.PeriodCombiner.combine_([],c,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_),2);case 2:return p=F.yieldResult,
F.yield(shaka.util.PeriodCombiner.combine_([],d,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_),3);case 3:return q=F.yieldResult,F.yield(shaka.util.PeriodCombiner.combine_([],e,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_),4);case 4:return r=F.yieldResult,F.yield(shaka.util.PeriodCombiner.combine_([],f,0,shaka.util.PeriodCombiner.cloneStreamDB_,shaka.util.PeriodCombiner.concatenateStreamDBs_),5);case 5:w=F.yieldResult;
u=0;if(q.length&&p.length)for(A=$jscomp.makeIterator(p),z=A.next();!z.done;z=A.next())for(B=z.value,D=$jscomp.makeIterator(q),G=D.next();!G.done;G=D.next())C=G.value,E=u++,C.variantIds.push(E),B.variantIds.push(E);else for(v=q.concat(p),x=$jscomp.makeIterator(v),t=x.next();!t.done;t=x.next())y=t.value,y.variantIds=[u++];return F.return(q.concat(p).concat(r).concat(w))}})};
shaka.util.PeriodCombiner.combine_=function(a,b,c,d,e){var f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G;return $jscomp.asyncExecutePromiseGeneratorProgram(function(C){switch(C.nextAddress){case 1:f=shaka.util.ManifestParserUtils.ContentType;g=[];for(h=0;h<b.length;h++)h>=c?g.push(new Set(b[h])):g.push(new Set);k=$jscomp.makeIterator(a);l=k.next();case 2:if(l.done){C.jumpTo(4);break}m=l.value;return C.yield(shaka.util.PeriodCombiner.extendExistingOutputStream_(m,b,c,e,g),5);case 5:n=C.yieldResult;if(!n)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.PERIOD_FLATTENING_FAILED);l=k.next();C.jumpTo(2);break;case 4:p=$jscomp.makeIterator(g);for(q=p.next();!q.done;q=p.next())for(r=q.value,w=$jscomp.makeIterator(r),u=w.next();!u.done;u=w.next())v=u.value,(x=shaka.util.PeriodCombiner.createNewOutputStream_(v,b,d,e,g))&&a.push(x);t=$jscomp.makeIterator(g);for(q=t.next();!q.done;q=t.next())for(y=q.value,A={},z=$jscomp.makeIterator(y),u=z.next();!u.done;A={$jscomp$loop$prop$stream$540$671:A.$jscomp$loop$prop$stream$540$671},
u=z.next())if(A.$jscomp$loop$prop$stream$540$671=u.value,B=A.$jscomp$loop$prop$stream$540$671.type==f.TEXT&&!A.$jscomp$loop$prop$stream$540$671.language,D=A.$jscomp$loop$prop$stream$540$671.type==f.IMAGE&&!A.$jscomp$loop$prop$stream$540$671.tilesLayout,!B&&!D&&(G=a.some(function(E){return function(F){return F.mimeType==E.$jscomp$loop$prop$stream$540$671.mimeType&&shaka.util.MimeUtils.getNormalizedCodec(F.codecs)==shaka.util.MimeUtils.getNormalizedCodec(E.$jscomp$loop$prop$stream$540$671.codecs)}}(A))))throw shaka.log.error("Unused stream in period-flattening!",
A.$jscomp$loop$prop$stream$540$671,a),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.PERIOD_FLATTENING_FAILED);return C.return(a)}})};
shaka.util.PeriodCombiner.extendExistingOutputStream_=function(a,b,c,d,e){return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){if(1==f.nextAddress)return shaka.util.PeriodCombiner.findMatchesInAllPeriods_(b,a),goog.asserts.assert(a.createSegmentIndex,"outputStream should be a Stream type!"),a.matchedStreams?a.segmentIndex?f.yield(shaka.util.PeriodCombiner.extendOutputSegmentIndex_(a,c),2):f.jumpTo(2):(shaka.log.error("No matches extending output stream!",a,b),f.return(!1));shaka.util.PeriodCombiner.extendOutputStream_(a,
c,d,e);return f.return(!0)})};
shaka.util.PeriodCombiner.extendOutputSegmentIndex_=function(a,b){var c,d,e,f,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){if(1==l.nextAddress){c=[];d=a.matchedStreams;goog.asserts.assert(d,"matched streams should be valid");e=$jscomp.makeIterator(d);for(f=e.next();!f.done;f=e.next())g=f.value,c.push(g.createSegmentIndex()),g.trickModeVideo&&!g.trickModeVideo.segmentIndex&&c.push(g.trickModeVideo.createSegmentIndex());return l.yield(Promise.all(c),2)}if(a.segmentIndex instanceof
shaka.media.MetaSegmentIndex)for(h=0;h<d.length;h++)k=d[h],k.segmentIndex&&h>=b&&(goog.asserts.assert(k.segmentIndex,"stream should have a segmentIndex."),a.segmentIndex.appendSegmentIndex(k.segmentIndex));l.jumpToEnd()})};
shaka.util.PeriodCombiner.createNewOutputStream_=function(a,b,c,d,e){var f=c(a);shaka.util.PeriodCombiner.findMatchesInAllPeriods_(b,f);f.createSegmentIndex&&(f.createSegmentIndex=function(){return $jscomp.asyncExecutePromiseGeneratorProgram(function(g){if(f.segmentIndex)return g.jumpTo(0);f.segmentIndex=new shaka.media.MetaSegmentIndex;return g.yield(shaka.util.PeriodCombiner.extendOutputSegmentIndex_(f,0),0)})});if(!f.matchedStreams)return null;shaka.util.PeriodCombiner.extendOutputStream_(f,0,
d,e);return f};shaka.util.PeriodCombiner.extendOutputStream_=function(a,b,c,d){var e=shaka.util.ManifestParserUtils.ContentType,f=shaka.util.LanguageUtils,g=a.matchedStreams;goog.asserts.assert(a.matchedStreams,"matchedStreams should be non-null");for(var h=0;h<g.length;h++)if(h>=b){var k=g[h];c(a,k);var l=!0;a.type==e.AUDIO&&0==f.relatedness(a.language,k.language)&&(l=!1);l&&d[h].delete(k)}};
shaka.util.PeriodCombiner.cloneStream_=function(a){var b=Object.assign({},a);b.originalId=null;b.createSegmentIndex=function(){return Promise.resolve()};b.closeSegmentIndex=function(){b.segmentIndex&&(b.segmentIndex.release(),b.segmentIndex=null);if(b.matchedStreams)for(var c=$jscomp.makeIterator(b.matchedStreams),d=c.next();!d.done;d=c.next())d=d.value,d.segmentIndex&&(d.segmentIndex.release(),d.segmentIndex=null)};b.segmentIndex=null;b.emsgSchemeIdUris=[];b.keyIds=new Set;b.closedCaptions=null;
b.trickModeVideo=null;return b};shaka.util.PeriodCombiner.cloneStreamDB_=function(a){a=Object.assign({},a);a.keyIds=new Set;a.segments=[];a.variantIds=[];a.closedCaptions=null;return a};
shaka.util.PeriodCombiner.concatenateStreams_=function(a,b){a.roles=Array.from(new Set(a.roles.concat(b.roles)));b.emsgSchemeIdUris&&(a.emsgSchemeIdUris=Array.from(new Set(a.emsgSchemeIdUris.concat(b.emsgSchemeIdUris))));a.keyIds=function(f,g){return new Set([].concat($jscomp.arrayFromIterable(f),$jscomp.arrayFromIterable(g)))}(a.keyIds,b.keyIds);a.originalId=null==a.originalId?b.originalId:a.originalId+(","+(b.originalId||""));var c=shaka.media.DrmEngine.getCommonDrmInfos(a.drmInfos,b.drmInfos);
if(b.drmInfos.length&&a.drmInfos.length&&!c.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.INCONSISTENT_DRM_ACROSS_PERIODS);a.drmInfos=c;a.encrypted=a.encrypted||b.encrypted;if(b.closedCaptions){a.closedCaptions||(a.closedCaptions=new Map);c=$jscomp.makeIterator(b.closedCaptions);for(var d=c.next();!d.done;d=c.next()){var e=$jscomp.makeIterator(d.value);d=e.next().value;e=e.next().value;a.closedCaptions.set(d,e)}}b.trickModeVideo?
(a.trickModeVideo||(a.trickModeVideo=shaka.util.PeriodCombiner.cloneStream_(b.trickModeVideo),a.trickModeVideo.createSegmentIndex=function(){goog.asserts.assert(a.segmentIndex instanceof shaka.media.MetaSegmentIndex,"The stream should have a MetaSegmentIndex.");a.trickModeVideo.segmentIndex=a.segmentIndex.clone();return Promise.resolve()}),shaka.util.PeriodCombiner.concatenateStreams_(a.trickModeVideo,b.trickModeVideo)):a.trickModeVideo&&shaka.util.PeriodCombiner.concatenateStreams_(a.trickModeVideo,
b)};
shaka.util.PeriodCombiner.concatenateStreamDBs_=function(a,b){a.roles=Array.from(new Set(a.roles.concat(b.roles)));var c=b.keyIds;c=new Set([].concat($jscomp.arrayFromIterable(a.keyIds),$jscomp.arrayFromIterable(c)));a.keyIds=c;a.encrypted=a.encrypted&&b.encrypted;a.segments.push.apply(a.segments,$jscomp.arrayFromIterable(b.segments));if(b.closedCaptions)for(a.closedCaptions||(a.closedCaptions=new Map),b=$jscomp.makeIterator(b.closedCaptions),c=b.next();!c.done;c=b.next()){var d=$jscomp.makeIterator(c.value);c=
d.next().value;d=d.next().value;a.closedCaptions.set(c,d)}};shaka.util.PeriodCombiner.findMatchesInAllPeriods_=function(a,b){var c=[];a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next()){d=shaka.util.PeriodCombiner.findBestMatchInPeriod_(d.value,b);if(!d)return;c.push(d)}b.matchedStreams=c};
shaka.util.PeriodCombiner.findBestMatchInPeriod_=function(a,b){var c={audio:shaka.util.PeriodCombiner.areAVStreamsCompatible_,video:shaka.util.PeriodCombiner.areAVStreamsCompatible_,text:shaka.util.PeriodCombiner.areTextStreamsCompatible_,image:shaka.util.PeriodCombiner.areImageStreamsCompatible_}[b.type],d={audio:shaka.util.PeriodCombiner.isAudioStreamBetterMatch_,video:shaka.util.PeriodCombiner.isVideoStreamBetterMatch_,text:shaka.util.PeriodCombiner.isTextStreamBetterMatch_,image:shaka.util.PeriodCombiner.isImageStreamBetterMatch_}[b.type],
e=null;a=$jscomp.makeIterator(a);for(var f=a.next();!f.done;f=a.next())f=f.value,!c(b,f)||e&&!d(b,e,f)||(e=f);return e};shaka.util.PeriodCombiner.areAVStreamsCompatible_=function(a,b){return b.mimeType!=a.mimeType||shaka.util.MimeUtils.getNormalizedCodec(b.codecs)!=shaka.util.MimeUtils.getNormalizedCodec(a.codecs)||a.drmInfos&&!shaka.media.DrmEngine.areDrmCompatible(a.drmInfos,b.drmInfos)?!1:!0};
shaka.util.PeriodCombiner.areTextStreamsCompatible_=function(a,b){return a.language?b.language?0==shaka.util.LanguageUtils.relatedness(a.language,b.language)||b.kind!=a.kind?!1:!0:!0:!1};shaka.util.PeriodCombiner.areImageStreamsCompatible_=function(a,b){return a.tilesLayout?!0:!1};
shaka.util.PeriodCombiner.isAudioStreamBetterMatch_=function(a,b,c){var d=shaka.util.LanguageUtils,e=shaka.util.PeriodCombiner.BetterOrWorse,f=e.BETTER;e=e.WORSE;if(a.id==c.id)return!0;var g=d.relatedness(a.language,b.language);d=d.relatedness(a.language,c.language);if(d>g)return!0;if(d<g)return!1;if(a.roles.length)return f=b.roles.filter(function(h){return a.roles.includes(h)}),e=c.roles.filter(function(h){return a.roles.includes(h)}),e.length>f.length?!0:e.length<f.length?!1:c.roles.length<b.roles.length;
if(!c.roles.length&&b.roles.length)return!0;if(c.roles.length&&!b.roles.length)return!1;if(!b.primary&&c.primary)return!0;if(b.primary&&!c.primary)return!1;d=shaka.util.PeriodCombiner.compareClosestPreferLower(a.channelsCount,b.channelsCount,c.channelsCount);if(d==f)return!0;if(d==e)return!1;d=shaka.util.PeriodCombiner.compareClosestPreferLower(a.audioSamplingRate,b.audioSamplingRate,c.audioSamplingRate);return d==f?!0:d==e?!1:a.bandwidth&&shaka.util.PeriodCombiner.compareClosestPreferMinimalAbsDiff_(a.bandwidth,
b.bandwidth,c.bandwidth)==f?!0:!1};
shaka.util.PeriodCombiner.isVideoStreamBetterMatch_=function(a,b,c){var d=shaka.util.PeriodCombiner.BetterOrWorse,e=d.BETTER;d=d.WORSE;if(a.id==c.id)return!0;var f=shaka.util.PeriodCombiner.compareClosestPreferLower(a.width*a.height,b.width*b.height,c.width*c.height);if(f==e)return!0;if(f==d)return!1;if(a.frameRate){f=shaka.util.PeriodCombiner.compareClosestPreferLower(a.frameRate,b.frameRate,c.frameRate);if(f==e)return!0;if(f==d)return!1}return a.bandwidth&&shaka.util.PeriodCombiner.compareClosestPreferMinimalAbsDiff_(a.bandwidth,b.bandwidth,
c.bandwidth)==e?!0:!1};
shaka.util.PeriodCombiner.isTextStreamBetterMatch_=function(a,b,c){var d=shaka.util.LanguageUtils;if(a.id==c.id)return!0;var e=d.relatedness(a.language,b.language);d=d.relatedness(a.language,c.language);if(d>e)return!0;if(d<e)return!1;if(!b.primary&&c.primary)return!0;if(b.primary&&!c.primary)return!1;if(a.roles.length){e=b.roles.filter(function(f){return a.roles.includes(f)});d=c.roles.filter(function(f){return a.roles.includes(f)});if(d.length>e.length)return!0;if(d.length<e.length)return!1}else{if(!c.roles.length&&
b.roles.length)return!0;if(c.roles.length&&!b.roles.length)return!1}return c.mimeType!=a.mimeType||c.codecs!=a.codecs||b.mimeType==a.mimeType&&b.codecs==a.codecs?!1:!0};shaka.util.PeriodCombiner.isImageStreamBetterMatch_=function(a,b,c){var d=shaka.util.PeriodCombiner.BetterOrWorse.BETTER;return a.id==c.id?!0:shaka.util.PeriodCombiner.compareClosestPreferLower(a.width*a.height,b.width*b.height,c.width*c.height)==d?!0:!1};
shaka.util.PeriodCombiner.dummyStreamDB_=function(a){return{id:0,originalId:"",primary:!1,type:a,mimeType:"",codecs:"",language:"",label:null,width:null,height:null,encrypted:!1,keyIds:new Set,segments:[],variantIds:[],roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null}};
shaka.util.PeriodCombiner.dummyStream_=function(a){return{id:0,originalId:"",createSegmentIndex:function(){return Promise.resolve()},segmentIndex:new shaka.media.SegmentIndex([]),mimeType:"",codecs:"",encrypted:!1,drmInfos:[],keyIds:new Set,language:"",label:null,type:a,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null}};
shaka.util.PeriodCombiner.compareClosestPreferLower=function(a,b,c){var d=shaka.util.PeriodCombiner.BetterOrWorse,e=d.BETTER,f=d.WORSE;if(b==a&&a!=c)return f;if(c==a&&a!=b)return e;if(b>a){if(c<=a||c-a<b-a)return e;if(c-a>b-a)return f}else{if(c>a)return f;if(a-c<a-b)return e;if(a-c>a-b)return f}return d.EQUAL};
shaka.util.PeriodCombiner.compareClosestPreferMinimalAbsDiff_=function(a,b,c){var d=shaka.util.PeriodCombiner.BetterOrWorse,e=d.BETTER,f=d.WORSE;b=Math.abs(a-b);a=Math.abs(a-c);return a<b?e:b<a?f:d.EQUAL};shaka.util.PeriodCombiner.BetterOrWorse={BETTER:1,EQUAL:0,WORSE:-1};shaka.dash.DashParser=function(){var a=this;this.playerInterface_=this.config_=null;this.manifestUris_=[];this.manifest_=null;this.globalId_=1;this.streamMap_={};this.periodDurations_={};this.periodCombiner_=new shaka.util.PeriodCombiner;this.updatePeriod_=0;this.averageUpdateDuration_=new shaka.abr.Ewma(5);this.updateTimer_=new shaka.util.Timer(function(){a.onUpdate_()});this.operationManager_=new shaka.util.OperationManager;this.largestPeriodStartTime_=null;this.lastManifestUpdatePeriodIds_=[];
this.minTotalAvailabilityTimeOffset_=Infinity;this.lowLatencyMode_=!1};shaka.dash.DashParser.prototype.configure=function(a){goog.asserts.assert(null!=a.dash,"DashManifestConfiguration should not be null!");this.config_=a};
shaka.dash.DashParser.prototype.start=function(a,b){var c=this,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return goog.asserts.assert(c.config_,"Must call configure() before start()!"),c.lowLatencyMode_=b.isLowLatencyMode(),c.manifestUris_=[a],c.playerInterface_=b,e.yield(c.requestManifest_(),2);d=e.yieldResult;c.playerInterface_&&c.setUpdateTimer_(d);if(!c.playerInterface_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,
shaka.util.Error.Code.OPERATION_ABORTED);goog.asserts.assert(c.manifest_,"Manifest should be non-null!");return e.return(c.manifest_)})};
shaka.dash.DashParser.prototype.stop=function(){for(var a=$jscomp.makeIterator(Object.values(this.streamMap_)),b=a.next();!b.done;b=a.next())b=b.value,b.segmentIndex&&b.segmentIndex.release();this.periodCombiner_&&this.periodCombiner_.release();this.config_=this.playerInterface_=null;this.manifestUris_=[];this.manifest_=null;this.streamMap_={};this.periodCombiner_=null;null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null);return this.operationManager_.destroy()};
shaka.dash.DashParser.prototype.update=function(){var a=this,b;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return c.setCatchFinallyBlocks(2),c.yield(a.requestManifest_(),4);if(2!=c.nextAddress)return c.leaveTryBlock(0);b=c.enterCatchBlock();if(!a.playerInterface_||!b)return c.return();goog.asserts.assert(b instanceof shaka.util.Error,"Bad error type");a.playerInterface_.onError(b);c.jumpToEnd()})};
shaka.dash.DashParser.prototype.onExpirationUpdated=function(a,b){};
shaka.dash.DashParser.prototype.requestManifest_=function(){var a=this,b,c,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==m.nextAddress)return b=shaka.net.NetworkingEngine.RequestType.MANIFEST,c=shaka.net.NetworkingEngine.makeRequest(a.manifestUris_,a.config_.retryParameters),d=a.playerInterface_.networkingEngine,e=shaka.util.CmcdManager.StreamingFormat.DASH,a.playerInterface_.modifyManifestRequest(c,{format:e}),f=Date.now(),g=d.request(b,c),a.operationManager_.manage(g),
m.yield(g.promise,2);if(3!=m.nextAddress){h=m.yieldResult;if(!a.playerInterface_)return m.return(0);h.uri&&!a.manifestUris_.includes(h.uri)&&a.manifestUris_.unshift(h.uri);return m.yield(a.parseManifest_(h.data,h.uri),3)}k=Date.now();l=(k-f)/1E3;a.averageUpdateDuration_.sample(1,l);return m.return(l)})};
shaka.dash.DashParser.prototype.parseManifest_=function(a,b){var c=this,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==m.nextAddress){d=shaka.util.Error;e=shaka.dash.MpdUtils;f=shaka.util.XmlUtils.parseXml(a,"MPD");if(!f)throw new d(d.Severity.CRITICAL,d.Category.MANIFEST,d.Code.DASH_INVALID_XML,b);if(g=c.config_.dash.disableXlinkProcessing)return m.return(c.processManifest_(f,b));h=c.config_.dash.xlinkFailGracefully;k=e.processXlinks(f,c.config_.retryParameters,
h,b,c.playerInterface_.networkingEngine);c.operationManager_.manage(k);return m.yield(k.promise,2)}l=m.yieldResult;return m.return(c.processManifest_(l,b))})};
shaka.dash.DashParser.prototype.processManifest_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G,C,E,F,I,H,K,J,M,N,L,Q,O;return $jscomp.asyncExecutePromiseGeneratorProgram(function(P){switch(P.nextAddress){case 1:d=shaka.util.Functional;e=shaka.util.XmlUtils;(f=c.config_.dash.manifestPreprocessor)&&f(a);g=[b];h=e.findChildren(a,"Location").map(e.getContents).filter(d.isNotNull);0<h.length&&(k=shaka.util.ManifestParserUtils.resolveUris(g,h),g=c.manifestUris_=k);l=e.findChildren(a,
"BaseURL");m=l.map(e.getContents);n=shaka.util.ManifestParserUtils.resolveUris(g,m);p=0;l&&l.length&&(p=e.parseAttr(l[0],"availabilityTimeOffset",e.parseFloat)||0);q=c.config_.dash.ignoreMinBufferTime;r=0;q||(r=e.parseAttr(a,"minBufferTime",e.parseDuration)||0);c.updatePeriod_=e.parseAttr(a,"minimumUpdatePeriod",e.parseDuration,-1);w=e.parseAttr(a,"availabilityStartTime",e.parseDate);u=e.parseAttr(a,"timeShiftBufferDepth",e.parseDuration);v=c.config_.dash.ignoreSuggestedPresentationDelay;x=null;v||
(x=e.parseAttr(a,"suggestedPresentationDelay",e.parseDuration));t=c.config_.dash.ignoreMaxSegmentDuration;y=null;t||(y=e.parseAttr(a,"maxSegmentDuration",e.parseDuration));A=a.getAttribute("type")||"static";if(c.manifest_)for(z=c.manifest_.presentationTimeline,B=$jscomp.makeIterator(Object.values(c.streamMap_)),D=B.next();!D.done;D=B.next())G=D.value,G.segmentIndex&&G.segmentIndex.evict(z.getSegmentAvailabilityStart());else C=c.config_.defaultPresentationDelay||1.5*r,E=null!=x?x:C,z=new shaka.media.PresentationTimeline(w,
E,c.config_.dash.autoCorrectDrift);z.setStatic("static"==A);(F=z.isLive())&&!isNaN(c.config_.availabilityWindowOverride)&&(u=c.config_.availabilityWindowOverride);null==u&&(u=Infinity);z.setSegmentAvailabilityDuration(u);I=a.getAttribute("profiles")||"";H={dynamic:"static"!=A,presentationTimeline:z,period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:p,profiles:I.split(",")};K=c.parsePeriods_(H,n,a);J=K.duration;M=K.periods;
"static"!=A&&K.durationDerivedFromPeriods||z.setDuration(J||Infinity);c.minTotalAvailabilityTimeOffset_&&!c.lowLatencyMode_&&(N=c.playerInterface_.isAutoLowLatencyMode())&&(c.playerInterface_.enableLowLatencyMode(),c.lowLatencyMode_=c.playerInterface_.isLowLatencyMode());c.lowLatencyMode_?z.setAvailabilityTimeOffset(c.minTotalAvailabilityTimeOffset_):c.minTotalAvailabilityTimeOffset_&&shaka.log.alwaysWarn("Low-latency DASH live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details.");
z.notifyMaxSegmentDuration(y||1);goog.DEBUG&&z.assertIsValid();return P.yield(c.periodCombiner_.combinePeriods(M,H.dynamic),2);case 2:if(c.manifest_){c.manifest_.variants=c.periodCombiner_.getVariants();c.manifest_.textStreams=c.periodCombiner_.getTextStreams();c.manifest_.imageStreams=c.periodCombiner_.getImageStreams();c.playerInterface_.filter(c.manifest_);P.jumpTo(3);break}c.manifest_={presentationTimeline:z,variants:c.periodCombiner_.getVariants(),textStreams:c.periodCombiner_.getTextStreams(),
imageStreams:c.periodCombiner_.getImageStreams(),offlineSessionIds:[],minBufferTime:r||0,sequenceMode:c.config_.dash.sequenceMode};if(!z.usingPresentationStartTime()){P.jumpTo(4);break}L=shaka.util.XmlUtils;Q=L.findChildren(a,"UTCTiming");return P.yield(c.parseUtcTiming_(n,Q),5);case 5:O=P.yieldResult;if(!c.playerInterface_)return P.return();z.setClockOffset(O);case 4:z.lockStartTime();case 3:c.playerInterface_.makeTextStreamsForClosedCaptions(c.manifest_),P.jumpToEnd()}})};
shaka.dash.DashParser.prototype.parsePeriods_=function(a,b,c){var d=shaka.util.XmlUtils,e=d.parseAttr(c,"mediaPresentationDuration",d.parseDuration),f=[],g=0;c=d.findChildren(c,"Period");for(var h=0;h<c.length;h++){var k=c[h],l=c[h+1],m=d.parseAttr(k,"start",d.parseDuration,g),n=k.id,p=d.parseAttr(k,"duration",d.parseDuration),q=null;if(l){var r=d.parseAttr(l,"start",d.parseDuration);null!=r&&(q=r-m)}else null!=e&&(q=e-m);r=shaka.util.ManifestParserUtils.GAP_OVERLAP_TOLERANCE_SECONDS;q&&p&&Math.abs(q-
p)>r&&shaka.log.warning("There is a gap/overlap between Periods",k);null==q&&(q=p);if(null!==this.largestPeriodStartTime_&&null!==n&&null!==m&&m<this.largestPeriodStartTime_&&!this.lastManifestUpdatePeriodIds_.includes(n)&&h+1!=c.length)shaka.log.debug("Skipping Period with ID "+n+" as its start time is smaller than the largest period start time that has been seen, and ID is unseen before");else{null!==m&&(null===this.largestPeriodStartTime_||m>this.largestPeriodStartTime_)&&(this.largestPeriodStartTime_=
m);g=this.parsePeriod_(a,b,{start:m,duration:q,node:k,isLastPeriod:null==q||!l});f.push(g);a.period.id&&q&&(this.periodDurations_[a.period.id]=q);if(null==q){l&&shaka.log.warning("Skipping Period",h+1,"and any subsequent Periods:","Period",h+1,"does not have a valid start time.",l);g=null;break}g=m+q}}this.lastManifestUpdatePeriodIds_=f.map(function(w){return w.id});return null!=e?(g!=e&&shaka.log.warning("@mediaPresentationDuration does not match the total duration of ","all Periods."),{periods:f,
duration:e,durationDerivedFromPeriods:!1}):{periods:f,duration:g,durationDerivedFromPeriods:!0}};
shaka.dash.DashParser.prototype.parsePeriod_=function(a,b,c){var d=this,e=shaka.util.Functional,f=shaka.util.XmlUtils,g=shaka.util.ManifestParserUtils.ContentType;a.period=this.createFrame_(c.node,null,b);a.periodInfo=c;a.period.availabilityTimeOffset=a.availabilityTimeOffset;a.period.id||(shaka.log.info("No Period ID given for Period with start time "+c.start+",  Assigning a default"),a.period.id="__shaka_period_"+c.start);var h=f.findChildren(c.node,"EventStream");b=a.presentationTimeline.getSegmentAvailabilityStart();
h=$jscomp.makeIterator(h);for(var k=h.next();!k.done;k=h.next())this.parseEventStream_(c.start,c.duration,k.value,b);e=f.findChildren(c.node,"AdaptationSet").map(function(n){return d.parseAdaptationSet_(a,n)}).filter(e.isNotNull);if(a.dynamic){c=[];f=$jscomp.makeIterator(e);for(b=f.next();!b.done;b=f.next())for(b=$jscomp.makeIterator(b.value.representationIds),h=b.next();!h.done;h=b.next())c.push(h.value);f=new Set(c);if(c.length!=f.size)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_DUPLICATE_REPRESENTATION_ID);}c=e.filter(function(n){return!n.trickModeFor});e=e.filter(function(n){return n.trickModeFor});e=$jscomp.makeIterator(e);for(f=e.next();!f.done;f=e.next())for(f=f.value,b=f.trickModeFor.split(" "),h=$jscomp.makeIterator(c),k=h.next();!k.done;k=h.next()){var l=k.value;if(b.includes(l.id)){k={};l=$jscomp.makeIterator(l.streams);for(var m=l.next();!m.done;k={$jscomp$loop$prop$stream$673:k.$jscomp$loop$prop$stream$673},
m=l.next())k.$jscomp$loop$prop$stream$673=m.value,k.$jscomp$loop$prop$stream$673.trickModeVideo=f.streams.find(function(n){return function(p){return shaka.util.MimeUtils.getNormalizedCodec(n.$jscomp$loop$prop$stream$673.codecs)==shaka.util.MimeUtils.getNormalizedCodec(p.codecs)}}(k))}}f=this.config_.disableAudio?[]:this.getSetsOfType_(c,g.AUDIO);b=this.config_.disableVideo?[]:this.getSetsOfType_(c,g.VIDEO);e=this.config_.disableText?[]:this.getSetsOfType_(c,g.TEXT);c=this.config_.disableThumbnails?
[]:this.getSetsOfType_(c,g.IMAGE);if(!b.length&&!f.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_EMPTY_PERIOD);g=[];f=$jscomp.makeIterator(f);for(h=f.next();!h.done;h=f.next())g.push.apply(g,$jscomp.arrayFromIterable(h.value.streams));f=[];b=$jscomp.makeIterator(b);for(h=b.next();!h.done;h=b.next())f.push.apply(f,$jscomp.arrayFromIterable(h.value.streams));b=[];e=$jscomp.makeIterator(e);for(h=e.next();!h.done;h=e.next())b.push.apply(b,
$jscomp.arrayFromIterable(h.value.streams));e=[];c=$jscomp.makeIterator(c);for(h=c.next();!h.done;h=c.next())e.push.apply(e,$jscomp.arrayFromIterable(h.value.streams));return{id:a.period.id,audioStreams:g,videoStreams:f,textStreams:b,imageStreams:e}};shaka.dash.DashParser.prototype.getSetsOfType_=function(a,b){return a.filter(function(c){return c.contentType==b})};
shaka.dash.DashParser.prototype.parseAdaptationSet_=function(a,b){var c=this,d=shaka.util.XmlUtils,e=shaka.util.Functional,f=shaka.util.ManifestParserUtils,g=f.ContentType,h=shaka.dash.ContentProtection;a.adaptationSet=this.createFrame_(b,a.period,null);var k=!1,l=d.findChildren(b,"Role"),m=l.map(function(C){return C.getAttribute("value")}).filter(e.isNotNull),n=void 0;if(e=a.adaptationSet.contentType==g.TEXT)n=f.TextStreamKind.SUBTITLE;l=$jscomp.makeIterator(l);for(var p=l.next();!p.done;p=l.next()){p=
p.value;var q=p.getAttribute("schemeIdUri");if(null==q||"urn:mpeg:dash:role:2011"==q)switch(p=p.getAttribute("value"),p){case "main":k=!0;break;case "caption":case "subtitle":n=p}}var r;q=function(C){switch(C){case 1:case 6:case 13:case 14:case 15:return"SDR";case 16:return"PQ";case 18:return"HLG"}};var w=d.findChildren(b,"EssentialProperty");l=null;p=!1;w=$jscomp.makeIterator(w);for(var u=w.next();!u.done;u=w.next()){u=u.value;var v=u.getAttribute("schemeIdUri");"http://dashif.org/guidelines/trickmode"==
v?l=u.getAttribute("value"):"urn:mpeg:mpegB:cicp:TransferCharacteristics"==v?r=q(parseInt(u.getAttribute("value"),10)):p=!0}w=d.findChildren(b,"SupplementalProperty");w=$jscomp.makeIterator(w);for(u=w.next();!u.done;u=w.next())u=u.value,"urn:mpeg:mpegB:cicp:TransferCharacteristics"==u.getAttribute("schemeIdUri")&&(r=q(parseInt(u.getAttribute("value"),10)));w=d.findChildren(b,"Accessibility");q=shaka.util.LanguageUtils;var x=new Map;w=$jscomp.makeIterator(w);for(u=w.next();!u.done;u=w.next())if(v=
u.value,u=v.getAttribute("schemeIdUri"),v=v.getAttribute("value"),"urn:scte:dash:cc:cea-608:2015"==u)if(u=1,null!=v){v=v.split(";");for(var t=$jscomp.makeIterator(v),y=t.next();!y.done;y=t.next()){var A=y.value,z=y=void 0;A.includes("=")?(A=A.split("="),y=A[0].startsWith("CC")?A[0]:"CC"+A[0],z=A[1]||"und"):(y="CC"+u,2==v.length?u+=2:u++,z=A);x.set(y,q.normalize(z))}}else x.set("CC1","und");else if("urn:scte:dash:cc:cea-708:2015"==u)if(u=1,null!=v)for(v=$jscomp.makeIterator(v.split(";")),y=v.next();!y.done;y=
v.next())y=y.value,A=t=void 0,y.includes("=")?(y=y.split("="),t="svc"+y[0],A=y[1].split(",")[0].split(":").pop()):(t="svc"+u,u++,A=y),x.set(t,q.normalize(A));else x.set("svc1","und");else"urn:mpeg:dash:role:2011"==u&&null!=v&&(m.push(v),"captions"==v&&(n=f.TextStreamKind.CLOSED_CAPTION));if(p)return null;f=d.findChildren(b,"ContentProtection");var B=h.parseFromAdaptationSet(f,this.config_.dash.ignoreDrmInfo,this.config_.dash.keySystemsByURI),D=shaka.util.LanguageUtils.normalize(b.getAttribute("lang")||
"und"),G=b.getAttribute("label");(h=d.findChildren(b,"Label"))&&h.length&&(h=h[0],h.textContent&&(G=h.textContent));d=d.findChildren(b,"Representation");b=d.map(function(C){if(C=c.parseRepresentation_(a,B,n,D,G,k,m,x,C))C.hdr=C.hdr||r;return C}).filter(function(C){return!!C});if(0==b.length){l=a.adaptationSet.contentType==g.IMAGE;if(this.config_.dash.ignoreEmptyAdaptationSet||e||l)return null;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.DASH_EMPTY_ADAPTATION_SET);
}if(!a.adaptationSet.contentType||a.adaptationSet.contentType==g.APPLICATION)for(a.adaptationSet.contentType=shaka.dash.DashParser.guessContentType_(b[0].mimeType,b[0].codecs),g=$jscomp.makeIterator(b),e=g.next();!e.done;e=g.next())e.value.type=a.adaptationSet.contentType;g=$jscomp.makeIterator(b);for(e=g.next();!e.done;e=g.next())for(e=e.value,h=$jscomp.makeIterator(B.drmInfos),f=h.next();!f.done;f=h.next())f=f.value,f.keyIds=f.keyIds&&e.keyIds?new Set([].concat($jscomp.arrayFromIterable(f.keyIds),
$jscomp.arrayFromIterable(e.keyIds))):f.keyIds||e.keyIds;g=d.map(function(C){return C.getAttribute("id")}).filter(shaka.util.Functional.isNotNull);return{id:a.adaptationSet.id||"__fake__"+this.globalId_++,contentType:a.adaptationSet.contentType,language:D,main:k,streams:b,drmInfos:B.drmInfos,trickModeFor:l,representationIds:g}};
shaka.dash.DashParser.prototype.parseRepresentation_=function(a,b,c,d,e,f,g,h,k){var l=this,m=shaka.util.XmlUtils,n=shaka.util.ManifestParserUtils.ContentType;a.representation=this.createFrame_(k,a.adaptationSet,null);this.minTotalAvailabilityTimeOffset_=Math.min(this.minTotalAvailabilityTimeOffset_,a.representation.availabilityTimeOffset);if(!this.verifyRepresentation_(a.representation))return shaka.log.warning("Skipping Representation",a.representation),null;var p=a.periodInfo.start;a.bandwidth=
m.parseAttr(k,"bandwidth",m.parsePositiveInt)||0;var q=a.representation.contentType,r=q==n.TEXT||q==n.APPLICATION;n=q==n.IMAGE;try{if(q=function(D,G,C){return l.requestInitSegment_(D,G,C)},a.representation.segmentBase)var w=shaka.dash.SegmentBase.createStreamInfo(a,q);else if(a.representation.segmentList)w=shaka.dash.SegmentList.createStreamInfo(a,this.streamMap_);else if(a.representation.segmentTemplate)w=shaka.dash.SegmentTemplate.createStreamInfo(a,q,this.streamMap_,!!this.manifest_,this.config_.dash.initialSegmentLimit,
this.periodDurations_);else{goog.asserts.assert(r,"Must have Segment* with non-text streams.");var u=a.representation.baseUris,v=a.periodInfo.duration||0;w={generateSegmentIndex:function(){return Promise.resolve(shaka.media.SegmentIndex.forSingleSegment(p,v,u))}}}}catch(D){if((r||n)&&D.code==shaka.util.Error.Code.DASH_NO_SEGMENT_INFO)return null;throw D;}q=m.findChildren(k,"ContentProtection");q=shaka.dash.ContentProtection.parseFromRepresentation(q,b,this.config_.dash.ignoreDrmInfo,this.config_.dash.keySystemsByURI);
q=new Set(q?[q]:[]);var x=!1;m.findChildren(k,"SupplementalProperty").some(function(D){return"tag:dolby.com,2018:dash:EC3_ExtensionType:2018"==D.getAttribute("schemeIdUri")&&"JOC"==D.getAttribute("value")})&&(x=!0);var t=!1;r&&(t=g.includes("forced_subtitle")||g.includes("forced-subtitle"));var y;if(n&&((k=m.findChildren(k,"EssentialProperty").find(function(D){return["http://dashif.org/thumbnail_tile","http://dashif.org/guidelines/thumbnail_tile"].includes(D.getAttribute("schemeIdUri"))}))&&(y=k.getAttribute("value")),
!y))return null;var A;k=a.representation.codecs;a.profiles.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")&&(k.includes("hvc1.2.4.L153.B0")||k.includes("hev1.2.4.L153.B0"))&&(A="PQ");var z=a.representation.id?a.period.id+","+a.representation.id:"",B={id:this.globalId_++,originalId:a.representation.id,createSegmentIndex:function(){var D,G,C;return $jscomp.asyncExecutePromiseGeneratorProgram(function(E){if(1==E.nextAddress){G=(D=z&&a.dynamic&&l.streamMap_[z])?l.streamMap_[z]:B;if(G.segmentIndex)return E.jumpTo(0);
C=G;return E.yield(w.generateSegmentIndex(),3)}C.segmentIndex=E.yieldResult;E.jumpToEnd()})},closeSegmentIndex:function(){B.segmentIndex&&(B.segmentIndex.release(),B.segmentIndex=null)},segmentIndex:null,mimeType:a.representation.mimeType,codecs:a.representation.codecs,frameRate:a.representation.frameRate,pixelAspectRatio:a.representation.pixelAspectRatio,bandwidth:a.bandwidth,width:a.representation.width,height:a.representation.height,kind:c,encrypted:0<b.drmInfos.length,drmInfos:b.drmInfos,keyIds:q,
language:d,label:e,type:a.adaptationSet.contentType,primary:f,trickModeVideo:null,emsgSchemeIdUris:a.representation.emsgSchemeIdUris,roles:g,forced:t,channelsCount:a.representation.numChannels,audioSamplingRate:a.representation.audioSamplingRate,spatialAudio:x,closedCaptions:h,hdr:A,tilesLayout:y,matchedStreams:[]};z&&a.dynamic&&!this.streamMap_[z]&&(this.streamMap_[z]=B);return B};
shaka.dash.DashParser.prototype.onUpdate_=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){switch(d.nextAddress){case 1:return goog.asserts.assert(0<=a.updatePeriod_,"There should be an update period"),shaka.log.info("Updating manifest..."),b=0,d.setCatchFinallyBlocks(2),d.yield(a.requestManifest_(),4);case 4:b=d.yieldResult;d.leaveTryBlock(3);break;case 2:c=d.enterCatchBlock(),goog.asserts.assert(c instanceof shaka.util.Error,"Should only receive a Shaka error"),
a.playerInterface_&&(c.severity=shaka.util.Error.Severity.RECOVERABLE,a.playerInterface_.onError(c));case 3:if(!a.playerInterface_)return d.return();a.setUpdateTimer_(b);d.jumpToEnd()}})};shaka.dash.DashParser.prototype.setUpdateTimer_=function(a){0>this.updatePeriod_||(a=Math.max(shaka.dash.DashParser.MIN_UPDATE_PERIOD_,this.updatePeriod_-a,this.averageUpdateDuration_.getEstimate()),this.updateTimer_.tickAfter(a))};
shaka.dash.DashParser.prototype.createFrame_=function(a,b,c){goog.asserts.assert(b||c,"Must provide either parent or baseUris");var d=shaka.util.ManifestParserUtils,e=shaka.util.XmlUtils;b=b||{contentType:"",mimeType:"",codecs:"",emsgSchemeIdUris:[],frameRate:void 0,pixelAspectRatio:void 0,numChannels:null,audioSamplingRate:null,availabilityTimeOffset:0};c=c||b.baseUris;var f=e.parseNonNegativeInt,g=e.evalDivision,h=e.findChildren(a,"BaseURL"),k=h.map(e.getContents),l=a.getAttribute("contentType")||
b.contentType,m=a.getAttribute("mimeType")||b.mimeType,n=a.getAttribute("codecs")||b.codecs;g=e.parseAttr(a,"frameRate",g)||b.frameRate;var p=a.getAttribute("sar")||b.pixelAspectRatio,q=this.emsgSchemeIdUris_(e.findChildren(a,"InbandEventStream"),b.emsgSchemeIdUris),r=e.findChildren(a,"AudioChannelConfiguration");r=this.parseAudioChannels_(r)||b.numChannels;var w=e.parseAttr(a,"audioSamplingRate",f)||b.audioSamplingRate;l||(l=shaka.dash.DashParser.guessContentType_(m,n));var u=e.findChild(a,"SegmentBase"),
v=e.findChild(a,"SegmentTemplate"),x=u?e.parseAttr(u,"availabilityTimeOffset",e.parseFloat)||0:0,t=v?e.parseAttr(v,"availabilityTimeOffset",e.parseFloat)||0:0;h=h&&h.length?e.parseAttr(h[0],"availabilityTimeOffset",e.parseFloat)||0:0;h=b.availabilityTimeOffset+h+x+t;return{baseUris:d.resolveUris(c,k),segmentBase:u||b.segmentBase,segmentList:e.findChild(a,"SegmentList")||b.segmentList,segmentTemplate:v||b.segmentTemplate,width:e.parseAttr(a,"width",f)||b.width,height:e.parseAttr(a,"height",f)||b.height,
contentType:l,mimeType:m,codecs:n,frameRate:g,pixelAspectRatio:p,emsgSchemeIdUris:q,id:a.getAttribute("id"),numChannels:r,audioSamplingRate:w,availabilityTimeOffset:h}};shaka.dash.DashParser.prototype.emsgSchemeIdUris_=function(a,b){b=b.slice();a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())c=c.value.getAttribute("schemeIdUri"),b.includes(c)||b.push(c);return b};
shaka.dash.DashParser.prototype.parseAudioChannels_=function(a){a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next()){var c=b.value;if(b=c.getAttribute("schemeIdUri"))if(c=c.getAttribute("value"))switch(b){case "urn:mpeg:dash:outputChannelPositionList:2012":return c.trim().split(/ +/).length;case "urn:mpeg:dash:23003:3:audio_channel_configuration:2011":case "urn:dts:dash:audio_channel_configuration:2012":var d=parseInt(c,10);if(!d){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",
b,c);continue}return d;case "tag:dolby.com,2014:dash:audio_channel_configuration:2011":case "urn:dolby:dash:audio_channel_configuration:2011":d=parseInt(c,16);if(!d){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",b,c);continue}for(a=0;d;)d&1&&++a,d>>=1;return a;case "urn:mpeg:mpegB:cicp:ChannelConfiguration":d=[0,1,2,3,4,5,6,8,2,3,4,7,8,24,8,12,10,12,14,12,14];var e=parseInt(c,10);if(!e){shaka.log.warning("Channel parsing failure! Ignoring scheme and value",b,c);continue}if(0<
e&&e<d.length)return d[e];continue;default:shaka.log.warning("Unrecognized audio channel scheme:",b,c)}}return null};
shaka.dash.DashParser.prototype.verifyRepresentation_=function(a){var b=shaka.util.ManifestParserUtils.ContentType;var c=a.segmentBase?1:0;c+=a.segmentList?1:0;c+=a.segmentTemplate?1:0;if(0==c){if(a.contentType==b.TEXT||a.contentType==b.APPLICATION)return!0;shaka.log.warning("Representation does not contain a segment information source:","the Representation must contain one of SegmentBase, SegmentList,",'SegmentTemplate, or explicitly indicate that it is "text".',a);return!1}1!=c&&(shaka.log.warning("Representation contains multiple segment information sources:",
"the Representation should only contain one of SegmentBase,","SegmentList, or SegmentTemplate.",a),a.segmentBase?(shaka.log.info("Using SegmentBase by default."),a.segmentList=null):(goog.asserts.assert(a.segmentList,"There should be a SegmentList"),shaka.log.info("Using SegmentList by default.")),a.segmentTemplate=null);return!0};
shaka.dash.DashParser.prototype.requestForTiming_=function(a,b,c){var d=this,e,f,g,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){if(1==n.nextAddress)return e=shaka.util.ManifestParserUtils.resolveUris(a,[b]),f=shaka.net.NetworkingEngine.makeRequest(e,d.config_.retryParameters),f.method=c,g=shaka.net.NetworkingEngine.RequestType.TIMING,h=d.playerInterface_.networkingEngine.request(g,f),d.operationManager_.manage(h),n.yield(h.promise,2);k=n.yieldResult;if("HEAD"==c){if(!k.headers||
!k.headers.date)return shaka.log.warning("UTC timing response is missing","expected date header"),n.return(0);l=k.headers.date}else l=shaka.util.StringUtils.fromUTF8(k.data);m=Date.parse(l);return isNaN(m)?(shaka.log.warning("Unable to parse date from UTC timing response"),n.return(0)):n.return(m-Date.now())})};
shaka.dash.DashParser.prototype.parseUtcTiming_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n;return $jscomp.asyncExecutePromiseGeneratorProgram(function(p){switch(p.nextAddress){case 1:d=b.map(function(q){return{scheme:q.getAttribute("schemeIdUri"),value:q.getAttribute("value")}}),e=c.config_.dash.clockSyncUri,!d.length&&e&&d.push({scheme:"urn:mpeg:dash:utc:http-head:2014",value:e}),f=$jscomp.makeIterator(d),g=f.next();case 2:if(g.done){p.jumpTo(4);break}h=g.value;p.setCatchFinallyBlocks(5);k=h.scheme;
l=h.value;switch(k){case "urn:mpeg:dash:utc:http-head:2014":case "urn:mpeg:dash:utc:http-head:2012":return p.jumpTo(7);case "urn:mpeg:dash:utc:http-xsdate:2014":case "urn:mpeg:dash:utc:http-iso:2014":case "urn:mpeg:dash:utc:http-xsdate:2012":case "urn:mpeg:dash:utc:http-iso:2012":return p.jumpTo(8);case "urn:mpeg:dash:utc:direct:2014":case "urn:mpeg:dash:utc:direct:2012":return m=Date.parse(l),p.return(isNaN(m)?0:m-Date.now());case "urn:mpeg:dash:utc:http-ntp:2014":case "urn:mpeg:dash:utc:ntp:2014":case "urn:mpeg:dash:utc:sntp:2014":shaka.log.alwaysWarn("NTP UTCTiming scheme is not supported");
break;default:shaka.log.alwaysWarn("Unrecognized scheme in UTCTiming element",k)}p.jumpTo(9);break;case 7:return p.yield(c.requestForTiming_(a,l,"HEAD"),10);case 10:return p.return(p.yieldResult);case 8:return p.yield(c.requestForTiming_(a,l,"GET"),11);case 11:return p.return(p.yieldResult);case 9:p.leaveTryBlock(3);break;case 5:n=p.enterCatchBlock(),shaka.log.warning("Error fetching time from UTCTiming elem",n.message);case 3:g=f.next();p.jumpTo(2);break;case 4:return shaka.log.alwaysWarn("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!"),
p.return(0)}})};
shaka.dash.DashParser.prototype.parseEventStream_=function(a,b,c,d){var e=shaka.util.XmlUtils,f=e.parseNonNegativeInt,g=c.getAttribute("schemeIdUri")||"",h=c.getAttribute("value")||"",k=e.parseAttr(c,"timescale",f)||1;c=$jscomp.makeIterator(e.findChildren(c,"Event"));for(var l=c.next();!l.done;l=c.next()){l=l.value;var m=e.parseAttr(l,"presentationTime",f)||0,n=e.parseAttr(l,"duration",f)||0;m=m/k+a;n=m+n/k;null!=b&&(m=Math.min(m,a+b),n=Math.min(n,a+b));n<d||(l={schemeIdUri:g,value:h,startTime:m,
endTime:n,id:l.getAttribute("id")||"",eventElement:l},this.playerInterface_.onTimelineRegionAdded(l))}};
shaka.dash.DashParser.prototype.requestInitSegment_=function(a,b,c){var d=this,e,f,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){if(1==l.nextAddress)return e=shaka.net.NetworkingEngine.RequestType.SEGMENT,f=shaka.util.Networking.createSegmentRequest(a,b,c,d.config_.retryParameters),g=d.playerInterface_.networkingEngine,h=g.request(e,f),d.operationManager_.manage(h),l.yield(h.promise,2);k=l.yieldResult;return l.return(k.data)})};
shaka.dash.DashParser.guessContentType_=function(a,b){b=shaka.util.MimeUtils.getFullType(a,b);return shaka.text.TextEngine.isTypeSupported(b)?shaka.util.ManifestParserUtils.ContentType.TEXT:a.split("/")[0]};goog.exportSymbol("shaka.dash.DashParser",shaka.dash.DashParser);shaka.dash.DashParser.MIN_UPDATE_PERIOD_=3;shaka.media.ManifestParser.registerParserByExtension("mpd",function(){return new shaka.dash.DashParser});shaka.media.ManifestParser.registerParserByMime("application/dash+xml",function(){return new shaka.dash.DashParser});
shaka.media.ManifestParser.registerParserByMime("video/vnd.mpeg.dash.mpd",function(){return new shaka.dash.DashParser});shaka.hls={};shaka.hls.Playlist=function(a,b,c,d){this.absoluteUri=a;this.type=b;this.tags=c;this.segments=d||null};shaka.hls.PlaylistType={MASTER:0,MEDIA:1};shaka.hls.Tag=function(a,b,c,d){this.id=a;this.name=b;this.attributes=c;this.value=void 0===d?null:d};
shaka.hls.Tag.prototype.toString=function(){var a=function(c){var d=isNaN(Number(c.value))?'"'+c.value+'"':c.value;return c.name+"="+d},b="#"+this.name;a=this.attributes?this.attributes.map(a):[];this.value&&a.unshift(this.value);0<a.length&&(b+=":"+a.join(","));return b};shaka.hls.Tag.prototype.addAttribute=function(a){this.attributes.push(a)};
shaka.hls.Tag.prototype.getAttribute=function(a){var b=this.attributes.filter(function(c){return c.name==a});goog.asserts.assert(2>b.length,"A tag should not have multiple attributes with the same name!");return b.length?b[0]:null};shaka.hls.Tag.prototype.getAttributeValue=function(a,b){return(a=this.getAttribute(a))?a.value:b||null};
shaka.hls.Tag.prototype.getRequiredAttrValue=function(a){var b=this.getAttribute(a);if(!b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_REQUIRED_ATTRIBUTE_MISSING,a);return b.value};shaka.hls.Tag.prototype.setName=function(a){this.name=a};shaka.hls.Segment=function(a,b,c){c=void 0===c?[]:c;this.tags=b;this.absoluteUri=a;this.partialSegments=c};shaka.hls.Attribute=function(a,b){this.name=a;this.value=b};shaka.hls.Utils=function(){};shaka.hls.Utils.filterTagsByName=function(a,b){return a.filter(function(c){return c.name==b})};shaka.hls.Utils.filterTagsByType=function(a,b){return a.filter(function(c){return c.getRequiredAttrValue("TYPE")==b})};shaka.hls.Utils.getFirstTagWithName=function(a,b){a=shaka.hls.Utils.filterTagsByName(a,b);return a.length?a[0]:null};
shaka.hls.Utils.getFirstTagWithNameAsNumber=function(a,b,c){c=void 0===c?0:c;return(a=shaka.hls.Utils.getFirstTagWithName(a,b))?Number(a.value):c};shaka.hls.Utils.constructAbsoluteUri=function(a,b){return shaka.util.ManifestParserUtils.resolveUris([a],[b])[0]};shaka.hls.Utils.isComment=function(a){return/^#(?!EXT)/m.test(a)};shaka.util.TextParser=function(a){this.data_=a;this.position_=0};shaka.util.TextParser.prototype.atEnd=function(){return this.position_==this.data_.length};shaka.util.TextParser.prototype.readLine=function(){return this.readRegexReturnCapture_(/(.*?)(\n|$)/gm,1)};shaka.util.TextParser.prototype.readWord=function(){return this.readRegexReturnCapture_(/[^ \t\n]*/gm,0)};shaka.util.TextParser.prototype.skipWhitespace=function(){this.readRegex(/[ \t]+/gm)};
shaka.util.TextParser.prototype.readRegex=function(a){a=this.indexOf_(a);if(this.atEnd()||null==a||a.position!=this.position_)return null;this.position_+=a.length;return a.results};shaka.util.TextParser.prototype.readRegexReturnCapture_=function(a,b){return this.atEnd()?null:(a=this.readRegex(a))?a[b]:null};
shaka.util.TextParser.prototype.indexOf_=function(a){goog.asserts.assert(a.global,"global flag should be set");a.lastIndex=this.position_;a=a.exec(this.data_);return null==a?null:{position:a.index,length:a[0].length,results:a}};shaka.hls.ManifestTextParser=function(){this.globalId_=0};
shaka.hls.ManifestTextParser.prototype.parsePlaylist=function(a,b){var c=shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS,d=shaka.hls.ManifestTextParser.SEGMENT_TAGS;a=shaka.util.StringUtils.fromUTF8(a);a=a.replace(/\r\n|\r(?=[^\n]|$)/gm,"\n").trim();var e=a.split(/\n+/m);if(!/^#EXTM3U($|[ \t\n])/m.test(e[0]))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_PLAYLIST_HEADER_MISSING);a=shaka.hls.PlaylistType.MASTER;for(var f=
!0,g=$jscomp.makeIterator(e),h=g.next();!h.done;h=g.next())if(h=h.value,shaka.hls.Utils.isComment(h)||f)f=!1;else if(h=this.parseTag_(h),--this.globalId_,c.includes(h.name)){a=shaka.hls.PlaylistType.MEDIA;break}else"EXT-X-STREAM-INF"==h.name&&(f=!0);c=[];f=!0;for(g=0;g<e.length;g++){var k=e[g];h=e[g+1];if(shaka.hls.Utils.isComment(k)||f)f=!1;else{k=this.parseTag_(k);if(d.includes(k.name)){if(a!=shaka.hls.PlaylistType.MEDIA)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);d=e.splice(g,e.length-g);d=this.parseSegments_(b,d,c);return new shaka.hls.Playlist(b,a,c,d)}c.push(k);"EXT-X-STREAM-INF"==k.name&&(f=new shaka.hls.Attribute("URI",h),k.addAttribute(f),f=!0)}}return new shaka.hls.Playlist(b,a,c)};
shaka.hls.ManifestTextParser.prototype.parseSegments_=function(a,b,c){var d=[],e=[],f=[],g=null;b=$jscomp.makeIterator(b);for(var h=b.next();!h.done;h=b.next())h=h.value,/^(#EXT)/.test(h)?(h=this.parseTag_(h),shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS.includes(h.name)?c.push(h):"EXT-X-MAP"==h.name?g=h:"EXT-X-PART"==h.name?f.push(h):"EXT-X-PRELOAD-HINT"==h.name?"PART"==h.getAttributeValue("TYPE")?f.push(h):"MAP"==h.getAttributeValue("TYPE")&&(h.setName("EXT-X-MAP"),g=h):e.push(h)):shaka.hls.Utils.isComment(h)||
(h=h.trim(),h=shaka.hls.Utils.constructAbsoluteUri(a,h),g&&e.push(g),e=new shaka.hls.Segment(h,e,f),d.push(e),e=[],f=[]);f.length&&(g&&e.push(g),a=new shaka.hls.Segment("",e,f),d.push(a));return d};shaka.hls.ManifestTextParser.prototype.parseTag_=function(a){return shaka.hls.ManifestTextParser.parseTag(this.globalId_++,a)};
shaka.hls.ManifestTextParser.parseTag=function(a,b){var c=b.match(/^#(EXT[^:]*)(?::(.*))?$/);if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.INVALID_HLS_TAG,b);b=c[1];var d=c[2];c=[];var e;if(d){d=new shaka.util.TextParser(d);var f,g=d.readRegex(/^([^,=]+)(?:,|$)/g);g&&(e=g[1]);for(g=/([^=]+)=(?:"([^"]*)"|([^",]*))(?:,|$)/g;f=d.readRegex(g);)f=new shaka.hls.Attribute(f[1],f[2]||f[3]),c.push(f),d.skipWhitespace()}return new shaka.hls.Tag(a,
b,c,e)};shaka.hls.ManifestTextParser.MEDIA_PLAYLIST_TAGS="EXT-X-TARGETDURATION EXT-X-MEDIA-SEQUENCE EXT-X-DISCONTINUITY-SEQUENCE EXT-X-PLAYLIST-TYPE EXT-X-I-FRAMES-ONLY EXT-X-ENDLIST EXT-X-SERVER-CONTROL EXT-X-SKIP".split(" ");shaka.hls.ManifestTextParser.SEGMENT_TAGS="EXTINF EXT-X-BYTERANGE EXT-X-DISCONTINUITY EXT-X-PROGRAM-DATE-TIME EXT-X-KEY EXT-X-DATERANGE EXT-X-MAP".split(" ");shaka.net.DataUriPlugin=function(){};shaka.net.DataUriPlugin.parse=function(a,b,c,d){try{var e=shaka.net.DataUriPlugin.parseRaw(a);return shaka.util.AbortableOperation.completed({uri:a,originalUri:a,data:e.data,headers:{"content-type":e.contentType}})}catch(f){return shaka.util.AbortableOperation.failed(f)}};
shaka.net.DataUriPlugin.parseRaw=function(a){var b=a.split(":");if(2>b.length||"data"!=b[0])throw shaka.log.error("Bad data URI, failed to parse scheme"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_DATA_URI,a);b=b.slice(1).join(":").split(",");if(2>b.length)throw shaka.log.error("Bad data URI, failed to extract encoding and MIME type"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,
shaka.util.Error.Code.MALFORMED_DATA_URI,a);var c=b[0];a=decodeURIComponent(b.slice(1).join(","));b=c.split(";");c=b[0];var d=!1;1<b.length&&"base64"==b[b.length-1]&&(d=!0,b.pop());return{data:d?shaka.util.Uint8ArrayUtils.fromBase64(a):shaka.util.StringUtils.toUTF8(a),contentType:c}};goog.exportSymbol("shaka.net.DataUriPlugin",shaka.net.DataUriPlugin);goog.exportProperty(shaka.net.DataUriPlugin,"parse",shaka.net.DataUriPlugin.parse);shaka.net.NetworkingEngine.registerScheme("data",shaka.net.DataUriPlugin.parse);shaka.hls.HlsParser=function(){var a=this;this.config_=this.playerInterface_=null;this.globalId_=1;this.globalVariables_=new Map;this.groupIdToStreamInfosMap_=new Map;this.mediaSequenceToStartTimeByType_=new Map;var b=shaka.util.ManifestParserUtils.ContentType;this.mediaSequenceToStartTimeByType_.set(b.VIDEO,new Map);this.mediaSequenceToStartTimeByType_.set(b.AUDIO,new Map);this.mediaSequenceToStartTimeByType_.set(b.TEXT,new Map);this.mediaSequenceToStartTimeByType_.set(b.IMAGE,new Map);this.variantUriSet_=
new Set;this.uriToStreamInfosMap_=new Map;this.presentationTimeline_=null;this.masterPlaylistUri_="";this.manifestTextParser_=new shaka.hls.ManifestTextParser;this.updatePlaylistDelay_=0;this.minSequenceNumber_=-1;this.lowestSyncTime_=Infinity;this.streamsFinalized_=!1;this.updatePlaylistTimer_=new shaka.util.Timer(function(){a.onUpdate_()});this.presentationType_=shaka.hls.HlsParser.PresentationType_.VOD;this.manifest_=null;this.maxTargetDuration_=0;this.minTargetDuration_=Infinity;this.lowLatencyPresentationDelay_=
this.partialTargetDuration_=0;this.operationManager_=new shaka.util.OperationManager;this.groupIdToClosedCaptionsMap_=new Map;this.groupIdToCodecsMap_=new Map;this.mapTagToInitSegmentRefMap_=new Map;this.lowLatencyMode_=!1};shaka.hls.HlsParser.prototype.configure=function(a){this.config_=a};
shaka.hls.HlsParser.prototype.start=function(a,b){var c=this,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return goog.asserts.assert(c.config_,"Must call configure() before start()!"),c.playerInterface_=b,c.lowLatencyMode_=b.isLowLatencyMode(),e.yield(c.requestManifest_(a),2);if(3!=e.nextAddress)return d=e.yieldResult,c.masterPlaylistUri_=d.uri,goog.asserts.assert(d.data,"Response data should be non-null!"),e.yield(c.parseManifest_(d.data,a),3);goog.asserts.assert(c.manifest_,
"Manifest should be non-null");return e.return(c.manifest_)})};
shaka.hls.HlsParser.prototype.stop=function(){this.updatePlaylistTimer_&&(this.updatePlaylistTimer_.stop(),this.updatePlaylistTimer_=null);var a=[];this.operationManager_&&(a.push(this.operationManager_.destroy()),this.operationManager_=null);this.config_=this.playerInterface_=null;this.variantUriSet_.clear();this.manifest_=null;this.uriToStreamInfosMap_.clear();this.groupIdToStreamInfosMap_.clear();this.groupIdToCodecsMap_.clear();this.globalVariables_.clear();return Promise.all(a)};
shaka.hls.HlsParser.prototype.update=function(){var a=this,b,c,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==m.nextAddress){if(!a.isLive_())return m.return();b=[];c=Array.from(a.uriToStreamInfosMap_.values());d=c.filter(function(n){return n.stream.segmentIndex});e=$jscomp.makeIterator(d);for(f=e.next();!f.done;f=e.next())g=f.value,b.push(a.updateStream_(g));return m.yield(Promise.all(b),2)}a.notifySegmentsForStreams_(d.map(function(n){return n.stream}));h=d.some(function(n){return 0==
n.hasEndList});d.length&&!h&&(k=shaka.hls.HlsParser.PresentationType_,a.setPresentationType_(k.VOD),l=d.map(function(n){return n.maxTimestamp}),a.presentationTimeline_.setDuration(Math.min.apply(Math,$jscomp.arrayFromIterable(l))),a.playerInterface_.updateDuration());m.jumpToEnd()})};shaka.hls.HlsParser.prototype.getMediaSequenceToStartTimeFor_=function(a){return this.isLive_()?this.mediaSequenceToStartTimeByType_.get(a.type):a.mediaSequenceToStartTime};
shaka.hls.HlsParser.prototype.updateStream_=function(a){var b=this,c,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){if(1==t.nextAddress)return c=a.absoluteMediaPlaylistUri,d=new goog.Uri(c),b.lowLatencyMode_&&a.canSkipSegments&&d.setQueryData(new goog.Uri.QueryData("_HLS_skip=YES")),t.yield(b.requestManifest_(d.toString()),2);e=t.yieldResult;if(!a.stream.segmentIndex)return t.return();f=b.manifestTextParser_.parsePlaylist(e.data,e.uri);if(f.type!=shaka.hls.PlaylistType.MEDIA)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);g=shaka.hls.Utils.filterTagsByName(f.tags,"EXT-X-DEFINE");h=b.parseMediaVariables_(g);k=a.stream;l=b.getMediaSequenceToStartTimeFor_(a);m=b.parseDrmInfo_(f,k.mimeType);n=m.keyIds;p=m.drmInfos;q=function(y,A){return y.size===A.size&&[].concat($jscomp.arrayFromIterable(y)).every(function(z){return A.has(z)})};q(k.keyIds,n)||(k.keyIds=n,k.drmInfos=p,b.playerInterface_.newDrmInfo(k));r=b.createSegments_(a.verbatimMediaPlaylistUri,
f,k.type,k.mimeType,l,h);k.segmentIndex.mergeAndEvict(r,b.presentationTimeline_.getSegmentAvailabilityStart());r.length&&(w=shaka.hls.Utils.getFirstTagWithNameAsNumber(f.tags,"EXT-X-MEDIA-SEQUENCE",0),u=l.get(w),k.segmentIndex.evict(u));v=r[r.length-1];goog.asserts.assert(v,"Should have segments!");if(x=shaka.hls.Utils.getFirstTagWithName(f.tags,"EXT-X-ENDLIST"))a.hasEndList=!0,a.maxTimestamp=v.endTime;t.jumpToEnd()})};shaka.hls.HlsParser.prototype.onExpirationUpdated=function(a,b){};
shaka.hls.HlsParser.prototype.syncStreamsWithSequenceNumber_=function(a){for(var b=-1==this.minSequenceNumber_,c=$jscomp.makeIterator(a),d=c.next();!d.done;d=c.next()){d=d.value;var e=d.stream.segmentIndex;goog.asserts.assert(e,"Only loaded streams should be synced");var f=this.getMediaSequenceToStartTimeFor_(d);if(e=e.earliestReference()){if(goog.DEBUG){var g=f.values().next().value;goog.asserts.assert(g==e.startTime,"Sequence number map is not ordered as expected!")}f=$jscomp.makeIterator(f);for(g=
f.next();!g.done;g=f.next()){g=$jscomp.makeIterator(g.value);var h=g.next().value;if(g.next().value==e.startTime){b&&(this.minSequenceNumber_=Math.max(this.minSequenceNumber_,h));d.firstSequenceNumber=h;break}}}}if(!(0>this.minSequenceNumber_))for(shaka.log.debug("Syncing HLS streams against base sequence number:",this.minSequenceNumber_),a=$jscomp.makeIterator(a),d=a.next();!d.done;d=a.next())if(b=d.value,c=b.stream.segmentIndex)if(c.dropFirstReferences(this.minSequenceNumber_-b.firstSequenceNumber),
c=c.earliestReference())c=-c.startTime,b.stream.segmentIndex.offset(c),this.offsetStreamInfo_(b,c)};
shaka.hls.HlsParser.prototype.syncStreamsWithProgramDateTime_=function(a){if(Infinity==this.lowestSyncTime_){a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next()){var c=b.value.stream.segmentIndex;goog.asserts.assert(c,"Only loaded streams should be synced");c=c.earliestReference();null!=c&&null!=c.syncTime&&(this.lowestSyncTime_=Math.min(this.lowestSyncTime_,c.syncTime))}}a=this.lowestSyncTime_;if(Infinity!=a)for(shaka.log.debug("Syncing HLS streams against base time:",a),c=$jscomp.makeIterator(this.uriToStreamInfosMap_.values()),
b=c.next();!b.done;b=c.next()){b=b.value;var d=b.stream.segmentIndex;if(null!=d){var e=d.earliestReference();if(null==e.syncTime)shaka.log.alwaysError("Missing EXT-X-PROGRAM-DATE-TIME for stream",b.verbatimMediaPlaylistUri,"Expect AV sync issues!");else for(this.offsetStreamInfo_(b,e.syncTime-a-e.startTime),b=$jscomp.makeIterator(d),d=b.next();!d.done;d=b.next())d.value.syncAgainst(a)}}};
shaka.hls.HlsParser.prototype.offsetStreamInfo_=function(a,b){a.maxTimestamp+=b;goog.asserts.assert(0<=a.maxTimestamp,"Negative maxTimestamp after adjustment!");for(var c=this.getMediaSequenceToStartTimeFor_(a),d=$jscomp.makeIterator(c),e=d.next();!e.done;e=d.next()){var f=$jscomp.makeIterator(e.value);e=f.next().value;f=f.next().value;c.set(e,f+b)}shaka.log.debug("Offset",b,"applied to",a.verbatimMediaPlaylistUri)};
shaka.hls.HlsParser.prototype.parseManifest_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G,C,E,F,I,H,K,J,M,N,L,Q;return $jscomp.asyncExecutePromiseGeneratorProgram(function(O){switch(O.nextAddress){case 1:d=shaka.hls.HlsParser;e=shaka.hls.Utils;goog.asserts.assert(c.masterPlaylistUri_,"Master playlist URI must be set before calling parseManifest_!");f=c.manifestTextParser_.parsePlaylist(a,c.masterPlaylistUri_);g=e.filterTagsByName(f.tags,"EXT-X-DEFINE");c.parseMasterVariables_(g);
h=[];k=[];l=[];if(f.type==shaka.hls.PlaylistType.MEDIA)return D=c.config_.hls.mediaPlaylistFullMimeType,f.segments.length&&(G=new goog.Uri(f.segments[0].absoluteUri),C=G.getPath().split(".").pop(),(E=d.RAW_FORMATS_TO_MIME_TYPES_[C])?D=E:"ts"!==C&&"mp4"!==C&&(d.AUDIO_EXTENSIONS_TO_MIME_TYPES_[C]?(E=d.AUDIO_EXTENSIONS_TO_MIME_TYPES_[C],F=c.config_.hls.defaultAudioCodec,D=E+'; codecs="'+F+'"'):d.VIDEO_EXTENSIONS_TO_MIME_TYPES_[C]&&(E=d.VIDEO_EXTENSIONS_TO_MIME_TYPES_[C],I=c.config_.hls.defaultVideoCodec,
D=E+'; codecs="'+I+'"'))),H=shaka.util.MimeUtils.getBasicType(D),K=H.split("/")[0],J=shaka.util.MimeUtils.getCodecs(D),M=new Map,O.yield(c.convertParsedPlaylistIntoStreamInfo_(f,b,b,J,K,"",!0,"Media Playlist",null,M,null,!1,!1,H),5);m=e.filterTagsByName(f.tags,"EXT-X-MEDIA");n=e.filterTagsByName(f.tags,"EXT-X-STREAM-INF");p=e.filterTagsByName(f.tags,"EXT-X-IMAGE-STREAM-INF");q=e.filterTagsByName(f.tags,"EXT-X-SESSION-KEY");c.parseCodecs_(n);r=e.filterTagsByName(f.tags,"EXT-X-SESSION-DATA");w=$jscomp.makeIterator(r);
for(u=w.next();!u.done;u=w.next())if(v=u.value,x=v.getAttributeValue("DATA-ID"),t=v.getAttributeValue("URI"),y=v.getAttributeValue("LANGUAGE"),A=v.getAttributeValue("VALUE"),z=(new Map).set("id",x),t&&z.set("uri",shaka.hls.Utils.constructAbsoluteUri(c.masterPlaylistUri_,t)),y&&z.set("language",y),A&&z.set("value",A),B=new shaka.util.FakeEvent("sessiondata",z),c.playerInterface_)c.playerInterface_.onEvent(B);c.createStreamInfosFromMediaTags_(m);c.parseClosedCaptions_(m);h=c.createVariantsForTags_(n,
q);k=c.parseTexts_(m);return O.yield(c.parseImages_(p),4);case 4:l=O.yieldResult;O.jumpTo(3);break;case 5:N=O.yieldResult,c.uriToStreamInfosMap_.set(b,N),h.push({id:0,language:"und",disabledUntilTime:0,primary:!0,audio:"audio"==K?N.stream:null,video:"video"==K?N.stream:null,bandwidth:0,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]});case 3:if(!c.playerInterface_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);
goog.asserts.assert(null==c.presentationTimeline_,"Presentation timeline created early!");c.presentationTimeline_=new shaka.media.PresentationTimeline(null,0);c.presentationTimeline_.setStatic(!0);f.type==shaka.hls.PlaylistType.MEDIA&&(c.isLive_()&&(c.changePresentationTimelineToLive_(),L=c.updatePlaylistDelay_,c.updatePlaylistTimer_.tickAfter(L)),Q=Array.from(c.uriToStreamInfosMap_.values()),c.finalizeStreams_(Q),c.determineDuration_());c.manifest_={presentationTimeline:c.presentationTimeline_,variants:h,
textStreams:k,imageStreams:l,offlineSessionIds:[],minBufferTime:0,sequenceMode:!0};c.playerInterface_.makeTextStreamsForClosedCaptions(c.manifest_);O.jumpToEnd()}})};
shaka.hls.HlsParser.prototype.determineDuration_=function(){goog.asserts.assert(this.presentationTimeline_,"Presentation timeline not created!");if(this.isLive_()){if(this.updatePlaylistDelay_=this.minTargetDuration_,this.presentationType_==shaka.hls.HlsParser.PresentationType_.LIVE){var a=this.getMinDuration_();this.config_.hls.useSafariBehaviorForLive&&(a=this.presentationTimeline_.getDelay());isNaN(this.config_.availabilityWindowOverride)||(a=this.config_.availabilityWindowOverride);this.presentationTimeline_.setSegmentAvailabilityDuration(a)}}else this.presentationTimeline_.setDuration(this.getMinDuration_());
this.presentationTimeline_.lockStartTime();goog.asserts.assert(!this.presentationTimeline_.usingPresentationStartTime(),"We should not be using the presentation start time in HLS!")};shaka.hls.HlsParser.prototype.parseMasterVariables_=function(a){a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next()){var c=b.value;b=c.getAttributeValue("NAME");c=c.getAttributeValue("VALUE");b&&c&&(this.globalVariables_.has(b)||this.globalVariables_.set(b,c))}};
shaka.hls.HlsParser.prototype.parseMediaVariables_=function(a){var b=new Map;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){var d=c.value;c=d.getAttributeValue("NAME");var e=d.getAttributeValue("VALUE");d=d.getAttributeValue("IMPORT");c&&e&&b.set(c,e);d&&(c=this.globalVariables_.get(d))&&b.set(d,c)}return b};
shaka.hls.HlsParser.prototype.parseCodecs_=function(a){var b=shaka.util.ManifestParserUtils.ContentType;a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next()){var d=c.value,e=d.getAttributeValue("AUDIO");c=d.getAttributeValue("VIDEO");var f=d.getAttributeValue("SUBTITLES");d=this.getCodecsForVariantTag_(d);if(f){var g=shaka.util.ManifestParserUtils.guessCodecsSafe(b.TEXT,d);goog.asserts.assert(null!=g,"Text codecs should be valid.");this.groupIdToCodecsMap_.set(f,g);shaka.util.ArrayUtils.remove(d,
g)}e&&(f=shaka.util.ManifestParserUtils.guessCodecsSafe(b.AUDIO,d),f||(f=this.config_.hls.defaultAudioCodec),this.groupIdToCodecsMap_.set(e,f));c&&(e=shaka.util.ManifestParserUtils.guessCodecsSafe(b.VIDEO,d),e||(e=this.config_.hls.defaultVideoCodec),this.groupIdToCodecsMap_.set(c,e))}};
shaka.hls.HlsParser.prototype.parseTexts_=function(a){var b=this,c=shaka.hls.Utils.filterTagsByType(a,"SUBTITLES");a=c.map(function(h){if(b.config_.disableText)return null;try{return b.createStreamInfoFromMediaTag_(h).stream}catch(k){if(b.config_.hls.ignoreTextStreamFailures)return null;throw k;}});var d=shaka.util.ManifestParserUtils.ContentType.TEXT;c=$jscomp.makeIterator(c);for(var e=c.next();!e.done;e=c.next()){var f=e.value.getRequiredAttrValue("GROUP-ID");if(e=this.groupIdToCodecsMap_.get(f))if(f=
this.groupIdToStreamInfosMap_.get(f)){f=$jscomp.makeIterator(f);for(var g=f.next();!g.done;g=f.next())g=g.value,g.stream.codecs=e,g.stream.mimeType=this.guessMimeTypeBeforeLoading_(d,e)||this.guessMimeTypeFallback_(d)}}return a.filter(function(h){return h})};
shaka.hls.HlsParser.prototype.parseImages_=function(a){var b=this,c,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return c=a.map(function(f){var g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){if(1==l.nextAddress){if(g=b.config_.disableThumbnails)return l.return(null);l.setCatchFinallyBlocks(2);return l.yield(b.createStreamInfoFromImageTag_(f),4)}if(2!=l.nextAddress)return h=l.yieldResult,l.return(h.stream);k=l.enterCatchBlock();if(b.config_.hls.ignoreImageStreamFailures)return l.return(null);
throw k;})}),e.yield(Promise.all(c),2);d=e.yieldResult;return e.return(d.filter(function(f){return f}))})};shaka.hls.HlsParser.prototype.createStreamInfosFromMediaTags_=function(a){a=a.filter(function(c){var d=c.getAttributeValue("URI")||"";return"SUBTITLES"!=c.getAttributeValue("TYPE")&&""!=d});a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next())this.createStreamInfoFromMediaTag_(b.value)};
shaka.hls.HlsParser.prototype.createVariantsForTags_=function(a,b){var c=this,d=[],e=new Set;if(0<b.length){b=$jscomp.makeIterator(b);for(var f=b.next();!f.done;f=b.next()){f=f.value;var g=f.getRequiredAttrValue("METHOD");if("NONE"!=g&&"AES-128"!=g){g=f.getAttributeValue("KEYFORMAT")||"identity";var h=shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_[g];if(f=h?h(f,""):null){if(f.keyIds)for(g=$jscomp.makeIterator(f.keyIds),h=g.next();!h.done;h=g.next())e.add(h.value);d.push(f)}else shaka.log.warning("Unsupported HLS KEYFORMAT",
g)}}}a=a.map(function(k){var l=k.getAttributeValue("FRAME-RATE"),m=Number(k.getAttributeValue("AVERAGE-BANDWIDTH"))||Number(k.getRequiredAttrValue("BANDWIDTH")),n=k.getAttributeValue("RESOLUTION"),p=$jscomp.makeIterator(n?n.split("x"):[null,null]),q=p.next().value;p=p.next().value;var r=k.getAttributeValue("VIDEO-RANGE");k=c.createStreamInfosForVariantTag_(k,n,l);goog.asserts.assert(k.audio.length||k.video.length,"We should have created a stream!");return c.createVariants_(k.audio,k.video,m,q,p,l,
r,d,e)}).reduce(shaka.util.Functional.collapseArrays,[]);return a=a.filter(function(k){return null!=k})};
shaka.hls.HlsParser.prototype.createStreamInfosForVariantTag_=function(a,b,c){c=shaka.util.ManifestParserUtils.ContentType;b=this.getCodecsForVariantTag_(a);var d=a.getAttributeValue("AUDIO"),e=a.getAttributeValue("VIDEO");goog.asserts.assert(null==d||null==e,"Unexpected: both video and audio described by media tags!");var f=d||e;f=f&&this.groupIdToStreamInfosMap_.has(f)?this.groupIdToStreamInfosMap_.get(f):[];d={audio:d?f:[],video:e?f:[]};shaka.log.debug("Guessing stream type for",a.toString());
e=!1;var g=a.getRequiredAttrValue("URI"),h=d.audio.find(function(m){return m&&m.verbatimMediaPlaylistUri==g}),k=shaka.util.ManifestParserUtils.guessCodecsSafe(c.VIDEO,b),l=shaka.util.ManifestParserUtils.guessCodecsSafe(c.AUDIO,b);l&&!k?(c=c.AUDIO,shaka.log.debug("Guessing audio-only.")):!f.length&&l&&k?(shaka.log.debug("Guessing multiplexed audio+video."),c=c.VIDEO,b=[[k,l].join()]):d.audio.length&&h?(shaka.log.debug("Guessing audio-only."),c=c.AUDIO,e=!0):d.video.length&&!d.audio.length?(shaka.log.debug("Guessing audio-only."),
c=c.AUDIO):(shaka.log.debug("Guessing video-only."),c=c.VIDEO);e||(a=this.createStreamInfoFromVariantTag_(a,b,c),d[a.stream.type]=[a]);return d};
shaka.hls.HlsParser.prototype.getCodecsForVariantTag_=function(a){var b=[];this.config_.disableVideo||b.push(this.config_.hls.defaultVideoCodec);this.config_.disableAudio||b.push(this.config_.hls.defaultAudioCodec);b=b.join(",");var c=a.getAttributeValue("CODECS",b).split(/\s*,\s*/);a=new Set;b=[];c=$jscomp.makeIterator(c);for(var d=c.next();!d.done;d=c.next()){d=d.value;var e=shaka.util.MimeUtils.getCodecBase(d);a.has(e)?shaka.log.debug("Ignoring duplicate codec"):(b.push(d),a.add(e))}return b};
shaka.hls.HlsParser.prototype.getChannelsCount_=function(a){a=a.getAttributeValue("CHANNELS");if(!a)return null;a=a.split("/")[0];return parseInt(a,10)};shaka.hls.HlsParser.prototype.isSpatialAudio_=function(a){return(a=a.getAttributeValue("CHANNELS"))?a.includes("/JOC"):!1};
shaka.hls.HlsParser.prototype.getClosedCaptions_=function(a,b){var c=shaka.util.ManifestParserUtils.ContentType;a=a.getAttributeValue("CLOSED-CAPTIONS");return b==c.VIDEO&&a&&"NONE"!=a?this.groupIdToClosedCaptionsMap_.get(a):null};shaka.hls.HlsParser.prototype.getLanguage_=function(a){var b=shaka.util.LanguageUtils;a=a.getAttributeValue("LANGUAGE")||"und";return b.normalize(a)};
shaka.hls.HlsParser.prototype.getType_=function(a){a=a.getRequiredAttrValue("TYPE").toLowerCase();"subtitles"==a&&(a=shaka.util.ManifestParserUtils.ContentType.TEXT);return a};
shaka.hls.HlsParser.prototype.createVariants_=function(a,b,c,d,e,f,g,h,k){for(var l=shaka.util.ManifestParserUtils.ContentType,m=shaka.media.DrmEngine,n=$jscomp.makeIterator(b),p=n.next();!p.done;p=n.next())this.addVideoAttributes_(p.value.stream,d,e,f,g);d=this.config_.disableAudio;if(!a.length||d)a=[null];d=this.config_.disableVideo;if(!b.length||d)b=[null];d=[];a=$jscomp.makeIterator(a);for(e=a.next();!e.done;e=a.next())for(e=e.value,f=$jscomp.makeIterator(b),g=f.next();!g.done;g=f.next()){var q=
g.value;if(g=e?e.stream:null)g.drmInfos=h,g.keyIds=k;if(n=q?q.stream:null)n.drmInfos=h,n.keyIds=k;p=e?e.stream.drmInfos:null;var r=q?q.stream.drmInfos:null;q=(q?q.verbatimMediaPlaylistUri:"")+" - "+(e?e.verbatimMediaPlaylistUri:"");g&&n&&!m.areDrmCompatible(p,r)?shaka.log.warning("Incompatible DRM info in HLS variant.  Skipping."):this.variantUriSet_.has(q)?shaka.log.debug("Skipping variant which only differs in text streams."):(goog.asserts.assert(!g||g.type==l.AUDIO,"Audio parameter mismatch!"),
goog.asserts.assert(!n||n.type==l.VIDEO,"Video parameter mismatch!"),g={id:this.globalId_++,language:g?g.language:"und",primary:!!g&&g.primary||!!n&&n.primary,audio:g,video:n,bandwidth:c,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]},d.push(g),this.variantUriSet_.add(q))}return d};
shaka.hls.HlsParser.prototype.parseClosedCaptions_=function(a){a=shaka.hls.Utils.filterTagsByType(a,"CLOSED-CAPTIONS");a=$jscomp.makeIterator(a);for(var b=a.next();!b.done;b=a.next()){var c=b.value;goog.asserts.assert("EXT-X-MEDIA"==c.name,"Should only be called on media tags!");b=this.getLanguage_(c);var d=c.getRequiredAttrValue("GROUP-ID");c=c.getRequiredAttrValue("INSTREAM-ID");this.groupIdToClosedCaptionsMap_.get(d)||this.groupIdToClosedCaptionsMap_.set(d,new Map);this.groupIdToClosedCaptionsMap_.get(d).set(c,
b)}};
shaka.hls.HlsParser.prototype.createStreamInfoFromMediaTag_=function(a){goog.asserts.assert("EXT-X-MEDIA"==a.name,"Should only be called on media tags!");var b=a.getRequiredAttrValue("GROUP-ID"),c="",d=this.getType_(a);d!=shaka.util.ManifestParserUtils.ContentType.TEXT&&b&&this.groupIdToCodecsMap_.has(b)&&(c=this.groupIdToCodecsMap_.get(b));var e=this.variableSubstitution_(a.getRequiredAttrValue("URI"),this.globalVariables_);if(this.uriToStreamInfosMap_.has(e))return this.uriToStreamInfosMap_.get(e);var f=
this.getLanguage_(a),g=a.getAttributeValue("NAME"),h="YES"==a.getAttributeValue("DEFAULT"),k="audio"==d?this.getChannelsCount_(a):null,l="audio"==d?this.isSpatialAudio_(a):!1,m=a.getAttributeValue("CHARACTERISTICS");a=a.getAttributeValue("FORCED");c=this.createStreamInfo_(e,c,d,f,h,g,k,null,m,"YES"==a,l);this.groupIdToStreamInfosMap_.has(b)?this.groupIdToStreamInfosMap_.get(b).push(c):this.groupIdToStreamInfosMap_.set(b,[c]);if(this.uriToStreamInfosMap_.has(e))return this.uriToStreamInfosMap_.get(e);
this.uriToStreamInfosMap_.set(e,c);return c};
shaka.hls.HlsParser.prototype.createStreamInfoFromImageTag_=function(a){var b=this,c,d,e,f,g,h,k,l,m,n,p;return $jscomp.asyncExecutePromiseGeneratorProgram(function(q){if(1==q.nextAddress){goog.asserts.assert("EXT-X-IMAGE-STREAM-INF"==a.name,"Should only be called on image tags!");c=shaka.util.ManifestParserUtils.ContentType.IMAGE;d=b.variableSubstitution_(a.getRequiredAttrValue("URI"),b.globalVariables_);e=a.getAttributeValue("CODECS","jpeg")||"";if(b.uriToStreamInfosMap_.has(d))return q.return(b.uriToStreamInfosMap_.get(d));f=
b.getLanguage_(a);g=a.getAttributeValue("NAME");h=a.getAttributeValue("CHARACTERISTICS");k=b.createStreamInfo_(d,e,c,f,!1,g,null,null,h,!1,!1);return b.uriToStreamInfosMap_.has(d)?q.return(b.uriToStreamInfosMap_.get(d)):(l=a.getAttributeValue("RESOLUTION"))?q.yield(k.stream.createSegmentIndex(),3):q.jumpTo(2)}2!=q.nextAddress&&(m=k.stream.segmentIndex.get(0),n=m.getTilesLayout())&&(k.stream.width=Number(l.split("x")[0])*Number(n.split("x")[0]),k.stream.height=Number(l.split("x")[1])*Number(n.split("x")[1]));
if(p=a.getAttributeValue("BANDWIDTH"))k.stream.bandwidth=Number(p);b.uriToStreamInfosMap_.set(d,k);return q.return(k)})};
shaka.hls.HlsParser.prototype.createStreamInfoFromVariantTag_=function(a,b,c){goog.asserts.assert("EXT-X-STREAM-INF"==a.name,"Should only be called on variant tags!");var d=this.variableSubstitution_(a.getRequiredAttrValue("URI"),this.globalVariables_);if(this.uriToStreamInfosMap_.has(d))return this.uriToStreamInfosMap_.get(d);a=this.getClosedCaptions_(a,c);b=shaka.util.ManifestParserUtils.guessCodecs(c,b);c=this.createStreamInfo_(d,b,c,"und",!1,null,null,a,null,!1,!1);if(this.uriToStreamInfosMap_.has(d))return this.uriToStreamInfosMap_.get(d);
this.uriToStreamInfosMap_.set(d,c);return c};
shaka.hls.HlsParser.prototype.createStreamInfo_=function(a,b,c,d,e,f,g,h,k,l,m){var n=this,p=shaka.hls.Utils.constructAbsoluteUri(this.masterPlaylistUri_,a),q=this.makeStreamObject_(b,c,d,e,f,g,h,k,l,m);shaka.media.MediaSourceEngine.RAW_FORMATS.includes(q.mimeType)&&(q.codecs="");var r={stream:q,type:c,verbatimMediaPlaylistUri:a,absoluteMediaPlaylistUri:p,maxTimestamp:0,mediaSequenceToStartTime:new Map,canSkipSegments:!1,hasEndList:!1,firstSequenceNumber:-1,loadedOnce:!1},w=function(x){var t,y,A,
z,B,D,G,C,E,F,I,H,K;return $jscomp.asyncExecutePromiseGeneratorProgram(function(J){if(1==J.nextAddress)return J.yield(n.requestManifest_(r.absoluteMediaPlaylistUri),2);if(3!=J.nextAddress){t=J.yieldResult;if(x.aborted)return J.return();y=t.uri;A=n.manifestTextParser_.parsePlaylist(t.data,y);z=n.isLive_();return J.yield(n.convertParsedPlaylistIntoStreamInfo_(A,a,y,b,c,d,e,f,g,h,k,l,m),3)}B=J.yieldResult;if(x.aborted)return J.return();D=B.stream;n.isLive_()&&!z&&n.changePresentationTimelineToLive_();
r.absoluteMediaPlaylistUri=y;r.maxTimestamp=B.maxTimestamp;r.canSkipSegments=B.canSkipSegments;r.hasEndList=B.hasEndList;r.mediaSequenceToStartTime=B.mediaSequenceToStartTime;r.loadedOnce=!0;q.segmentIndex=D.segmentIndex;q.encrypted=D.encrypted;q.drmInfos=D.drmInfos;q.keyIds=D.keyIds;q.mimeType=D.mimeType;shaka.media.MediaSourceEngine.RAW_FORMATS.includes(q.mimeType)&&(q.codecs="");q.drmInfos.length&&n.playerInterface_.newDrmInfo(q);G=shaka.util.ManifestParserUtils.ContentType;if(c==G.VIDEO||c==G.AUDIO)for(C=
$jscomp.makeIterator(n.uriToStreamInfosMap_.values()),E=C.next();!E.done;E=C.next())F=E.value,F.loadedOnce||F.type!=c||(F.stream.mimeType=D.mimeType,shaka.media.MediaSourceEngine.RAW_FORMATS.includes(F.stream.mimeType)&&(F.stream.codecs=""));n.hasEnoughInfoToFinalizeStreams_()&&(n.streamsFinalized_?n.finalizeStreams_([r]):(n.streamsFinalized_=!0,I=Array.from(n.uriToStreamInfosMap_.values()),H=I.filter(function(M){return M.stream.segmentIndex}),n.finalizeStreams_(H),n.determineDuration_(),K=n.updatePlaylistDelay_,
0<K&&n.updatePlaylistTimer_.tickAfter(K)));J.jumpToEnd()})},u=null,v=new AbortController;q.createSegmentIndex=function(){if(u)return u;v=new AbortController;return u=new Promise(function(x){x(w(v.signal))})};q.closeSegmentIndex=function(){u&&!q.segmentIndex&&v.abort();q.segmentIndex&&(q.segmentIndex.release(),q.segmentIndex=null);u=null};return r};
shaka.hls.HlsParser.prototype.getMinDuration_=function(){for(var a=Infinity,b=$jscomp.makeIterator(this.uriToStreamInfosMap_.values()),c=b.next();!c.done;c=b.next())c=c.value,c.stream.segmentIndex&&"text"!=c.stream.type&&(a=Math.min(a,c.maxTimestamp));return a};shaka.hls.HlsParser.prototype.notifySegmentsForStreams_=function(a){var b=[];a=$jscomp.makeIterator(a);for(var c=a.next();!c.done;c=a.next())c=c.value,c.segmentIndex&&c.segmentIndex.forEachTopLevelReference(function(d){b.push(d)});this.presentationTimeline_.notifySegments(b)};
shaka.hls.HlsParser.prototype.finalizeStreams_=function(a){if(!this.isLive_())for(var b=this.getMinDuration_(),c=$jscomp.makeIterator(a),d=c.next();!d.done;d=c.next())d.value.stream.segmentIndex.fit(0,b);b=$jscomp.makeIterator(a);for(d=b.next();!d.done;d=b.next())d=d.value.stream,shaka.media.MediaSourceEngine.RAW_FORMATS.includes(d.mimeType)&&(d.codecs="");this.notifySegmentsForStreams_(a.map(function(e){return e.stream}));this.config_.hls.ignoreManifestProgramDateTime?this.syncStreamsWithSequenceNumber_(a):
this.syncStreamsWithProgramDateTime_(a)};shaka.hls.HlsParser.prototype.hasEnoughInfoToFinalizeStreams_=function(){if(!this.manifest_)return!1;for(var a=[],b=[],c=$jscomp.makeIterator(this.manifest_.variants),d=c.next();!d.done;d=c.next())d=d.value,d.video&&a.push(d.video),d.audio&&b.push(d.audio);return 0<a.length&&!a.some(function(e){return e.segmentIndex})||0<b.length&&!b.some(function(e){return e.segmentIndex})?!1:!0};
shaka.hls.HlsParser.prototype.convertParsedPlaylistIntoStreamInfo_=function(a,b,c,d,e,f,g,h,k,l,m,n,p,q){var r=this,w,u,v,x,t,y,A,z,B,D,G,C,E,F,I;return $jscomp.asyncExecutePromiseGeneratorProgram(function(H){if(1==H.nextAddress){if(a.type!=shaka.hls.PlaylistType.MEDIA)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_INVALID_PLAYLIST_HIERARCHY);w=shaka.hls.Utils.filterTagsByName(a.tags,"EXT-X-DEFINE");u=r.parseMediaVariables_(w);
goog.asserts.assert(null!=a.segments,"Media playlist should have segments!");r.determinePresentationType_(a);return q?H.jumpTo(2):H.yield(r.guessMimeType_(e,d,a,u),3)}2!=H.nextAddress&&(q=H.yieldResult);v=r.parseDrmInfo_(a,q);x=v.drmInfos;t=v.keyIds;y=v.encrypted;A=v.aesEncrypted;if(y&&!x.length&&!A)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_KEYFORMATS_NOT_SUPPORTED);z=r.isLive_()?r.mediaSequenceToStartTimeByType_.get(e):
new Map;B=r.lowLatencyMode_;D=r.createSegments_(b,a,e,q,z,u);B!=r.lowLatencyMode_&&r.determinePresentationType_(a);G=D[D.length-1].endTime;C=new shaka.media.SegmentIndex(D);F=(E=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-SERVER-CONTROL"))?null!=E.getAttribute("CAN-SKIP-UNTIL"):!1;I=r.makeStreamObject_(d,e,f,g,h,k,l,m,n,p);I.segmentIndex=C;I.encrypted=y;I.drmInfos=x;I.keyIds=t;I.mimeType=q;return H.return({stream:I,type:e,verbatimMediaPlaylistUri:b,absoluteMediaPlaylistUri:c,maxTimestamp:G,
canSkipSegments:F,hasEndList:!1,firstSequenceNumber:-1,mediaSequenceToStartTime:z,loadedOnce:!1})})};
shaka.hls.HlsParser.prototype.makeStreamObject_=function(a,b,c,d,e,f,g,h,k,l){var m=this.guessMimeTypeBeforeLoading_(b,a)||this.guessMimeTypeFallback_(b);return{id:this.globalId_++,originalId:e,createSegmentIndex:function(){return Promise.resolve()},segmentIndex:null,mimeType:m,codecs:a,kind:b==shaka.util.ManifestParserUtils.ContentType.TEXT?shaka.util.ManifestParserUtils.TextStreamKind.SUBTITLE:void 0,encrypted:!1,drmInfos:[],keyIds:new Set,language:c,label:e,type:b,primary:d,trickModeVideo:null,
emsgSchemeIdUris:null,frameRate:void 0,pixelAspectRatio:void 0,width:void 0,height:void 0,bandwidth:void 0,roles:h?h.split(","):[],forced:k,channelsCount:f,audioSamplingRate:null,spatialAudio:l,closedCaptions:g,hdr:void 0,tilesLayout:void 0}};
shaka.hls.HlsParser.prototype.parseDrmInfo_=function(a,b){var c=[];if(a.segments){a=$jscomp.makeIterator(a.segments);for(var d=a.next();!d.done;d=a.next())d=shaka.hls.Utils.filterTagsByName(d.value.tags,"EXT-X-KEY"),c.push.apply(c,$jscomp.arrayFromIterable(d))}d=a=!1;var e=[],f=new Set;c=$jscomp.makeIterator(c);for(var g=c.next();!g.done;g=c.next()){g=g.value;var h=g.getRequiredAttrValue("METHOD");if("NONE"!=h)if(a=!0,"AES-128"==h)d=!0;else{h=g.getAttributeValue("KEYFORMAT")||"identity";var k=shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_[h];
if(g=k?k(g,b):null){if(g.keyIds)for(h=$jscomp.makeIterator(g.keyIds),k=h.next();!k.done;k=h.next())f.add(k.value);e.push(g)}else shaka.log.warning("Unsupported HLS KEYFORMAT",h)}}return{drmInfos:e,keyIds:f,encrypted:a,aesEncrypted:d}};
shaka.hls.HlsParser.prototype.parseAES128DrmTag_=function(a,b){var c=this;if(!window.crypto||!window.crypto.subtle)throw shaka.log.alwaysWarn("Web Crypto API is not available to decrypt AES-128. (Web Crypto only exists in secure origins like https)"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.NO_WEB_CRYPTO_API);var d=0,e=a.getAttributeValue("IV","");if(e){var f=shaka.util.Uint8ArrayUtils.fromHex(e.substr(2));if(16!=f.byteLength)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_AES_128_INVALID_IV_LENGTH);}else d=shaka.hls.Utils.getFirstTagWithNameAsNumber(b.tags,"EXT-X-MEDIA-SEQUENCE",0);a=shaka.hls.Utils.constructAbsoluteUri(b.absoluteUri,a.getRequiredAttrValue("URI"));var g=shaka.net.NetworkingEngine.RequestType.KEY,h=shaka.net.NetworkingEngine.makeRequest([a],this.config_.retryParameters),k={method:"AES-128",iv:f,firstMediaSequenceNumber:d,fetchKey:function(){var l,m,n;return $jscomp.asyncExecutePromiseGeneratorProgram(function(p){if(1==
p.nextAddress)return p.yield(c.makeNetworkRequest_(h,g),2);if(3!=p.nextAddress){l=p.yieldResult;if(!l.data||16!=l.data.byteLength)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_AES_128_INVALID_KEY_LENGTH);m={name:"AES-CBC"};n=k;return p.yield(window.crypto.subtle.importKey("raw",l.data,m,!0,["decrypt"]),3)}n.cryptoKey=p.yieldResult;k.fetchKey=void 0;p.jumpToEnd()})}};return k};
shaka.hls.HlsParser.prototype.determinePresentationType_=function(a){var b=shaka.hls.HlsParser.PresentationType_,c=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-PLAYLIST-TYPE"),d=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-ENDLIST");d=c&&"VOD"==c.value||d;c=c&&"EVENT"==c.value&&!d;c=!d&&!c;d?this.setPresentationType_(b.VOD):(c?this.setPresentationType_(b.LIVE):this.setPresentationType_(b.EVENT),b=this.getRequiredTag_(a.tags,"EXT-X-TARGETDURATION"),b=Number(b.value),d=shaka.hls.Utils.getFirstTagWithName(a.tags,
"EXT-X-PART-INF"),this.lowLatencyMode_&&d?(this.partialTargetDuration_=Number(d.getRequiredAttrValue("PART-TARGET")),this.minTargetDuration_=Math.min(this.partialTargetDuration_,this.minTargetDuration_),this.lowLatencyPresentationDelay_=(a=shaka.hls.Utils.getFirstTagWithName(a.tags,"EXT-X-SERVER-CONTROL"))?Number(a.getRequiredAttrValue("PART-HOLD-BACK")):0):this.minTargetDuration_=Math.min(b,this.minTargetDuration_),this.maxTargetDuration_=Math.max(b,this.maxTargetDuration_))};
shaka.hls.HlsParser.prototype.changePresentationTimelineToLive_=function(){var a=this.config_.defaultPresentationDelay?this.config_.defaultPresentationDelay:this.lowLatencyPresentationDelay_?this.lowLatencyPresentationDelay_:this.maxTargetDuration_*this.config_.hls.liveSegmentsDelay;this.presentationTimeline_.setPresentationStartTime(0);this.presentationTimeline_.setDelay(a);this.presentationTimeline_.setStatic(!1)};
shaka.hls.HlsParser.prototype.getInitSegmentReference_=function(a,b,c){b=shaka.hls.Utils.getFirstTagWithName(b,"EXT-X-MAP");if(!b)return null;var d=b.getRequiredAttrValue("URI");c=this.variableSubstitution_(shaka.hls.Utils.constructAbsoluteUri(a,d),c);a=[c,b.getAttributeValue("BYTERANGE","")].join("-");this.mapTagToInitSegmentRefMap_.has(a)||(b=this.createInitSegmentReference_(c,b),this.mapTagToInitSegmentRefMap_.set(a,b));return this.mapTagToInitSegmentRefMap_.get(a)};
shaka.hls.HlsParser.prototype.createInitSegmentReference_=function(a,b){var c=0,d=null;if(b=b.getAttributeValue("BYTERANGE"))c=b.split("@"),d=Number(c[0]),c=Number(c[1]),d=c+d-1;return new shaka.media.InitSegmentReference(function(){return[a]},c,d)};
shaka.hls.HlsParser.prototype.createSegmentReference_=function(a,b,c,d,e,f,g,h){var k=c.tags,l=this.variableSubstitution_(c.absoluteUri,e),m=shaka.hls.Utils.getFirstTagWithName(k,"EXTINF"),n=0;e=0;var p=null;c.partialSegments.length&&!this.lowLatencyMode_&&shaka.log.alwaysWarn("Low-latency HLS live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details.");var q=null;if(!this.config_.hls.ignoreManifestProgramDateTime){var r=
shaka.hls.Utils.getFirstTagWithName(k,"EXT-X-PROGRAM-DATE-TIME");r&&r.value&&(q=shaka.util.XmlUtils.parseDate(r.value),goog.asserts.assert(null!=q,"EXT-X-PROGRAM-DATE-TIME format not valid"))}r=shaka.media.SegmentReference.Status.AVAILABLE;shaka.hls.Utils.getFirstTagWithName(k,"EXT-X-GAP")&&(r=shaka.media.SegmentReference.Status.MISSING);if(!m){if(0==c.partialSegments.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_REQUIRED_TAG_MISSING,
"EXTINF");if(!this.lowLatencyMode_)return null}var w=[];if(this.lowLatencyMode_){n={};for(var u=0;u<c.partialSegments.length;n={$jscomp$loop$prop$pAbsoluteUri$675:n.$jscomp$loop$prop$pAbsoluteUri$675},u++){var v=c.partialSegments[u],x=0==u?b:w[w.length-1],t=0==u?d:x.endTime,y=Number(v.getAttributeValue("DURATION"))||this.partialTargetDuration_;if(y){y=t+y;var A=0,z=null;"EXT-X-PRELOAD-HINT"==v.name?A=(A=v.getAttributeValue("BYTERANGE-START"))?Number(A):0:(A=v.getAttributeValue("BYTERANGE"),z=$jscomp.makeIterator(this.parseByteRange_(x,
A)),A=z.next().value,z=z.next().value);if(x=v.getAttributeValue("URI"))n.$jscomp$loop$prop$pAbsoluteUri$675=shaka.hls.Utils.constructAbsoluteUri(f,x),x=shaka.media.SegmentReference.Status.AVAILABLE,"YES"==v.getAttributeValue("GAP")&&(x=shaka.media.SegmentReference.Status.MISSING),v=new shaka.media.SegmentReference(t,y,function(B){return function(){return[B.$jscomp$loop$prop$pAbsoluteUri$675]}}(n),A,z,a,0,0,Infinity,[],"",null,null,x),w.push(v)}}}m?(c=m.value.split(","),n=d+Number(c[0])):n=w[w.length-
1].endTime;(c=shaka.hls.Utils.getFirstTagWithName(k,"EXT-X-BYTERANGE"))?(p=$jscomp.makeIterator(this.parseByteRange_(b,c.value)),e=p.next().value,p=p.next().value):w.length&&(e=w[0].startByte,p=w[w.length-1].endByte);b="";c=null;g==shaka.util.ManifestParserUtils.ContentType.IMAGE&&(b="1x1",g=shaka.hls.Utils.getFirstTagWithName(k,"EXT-X-TILES"))&&(b=g.getRequiredAttrValue("LAYOUT"),(g=g.getAttributeValue("DURATION"))&&(c=Number(g)));return new shaka.media.SegmentReference(d,n,function(){return l.length?
[l]:[]},e,p,a,0,0,Infinity,w,b,c,q,r,h)};shaka.hls.HlsParser.prototype.parseByteRange_=function(a,b){var c=0,d=null;b&&(c=b.split("@"),b=Number(c[0]),c[1]?c=Number(c[1]):(goog.asserts.assert(a,"Cannot refer back to previous HLS segment!"),c=a.endByte+1),d=c+b-1);return[c,d]};
shaka.hls.HlsParser.prototype.createSegments_=function(a,b,c,d,e,f){a=b.segments;goog.asserts.assert(a.length,"Playlist should have segments!");d=void 0;var g=shaka.hls.Utils.getFirstTagWithNameAsNumber(b.tags,"EXT-X-DISCONTINUITY-SEQUENCE",0),h=shaka.hls.Utils.getFirstTagWithNameAsNumber(b.tags,"EXT-X-MEDIA-SEQUENCE",0),k=shaka.hls.Utils.getFirstTagWithName(b.tags,"EXT-X-SKIP");k=k?Number(k.getAttributeValue("SKIPPED-SEGMENTS")):0;var l=h+k,m=0;this.isLive_()&&e.has(l)&&(m=e.get(l));for(var n=[],
p=null,q=0;q<a.length;q++){var r=a[q],w=0==q?m:p.endTime;l=h+k+q;shaka.hls.Utils.getFirstTagWithName(r.tags,"EXT-X-DISCONTINUITY")&&g++;var u=$jscomp.makeIterator(r.tags);for(var v=u.next();!v.done;v=u.next())v=v.value,"EXT-X-KEY"==v.name&&(d="AES-128"==v.getRequiredAttrValue("METHOD")?this.parseAES128DrmTag_(v,b):void 0);e.set(l,w);u=this.getInitSegmentReference_(b.absoluteUri,r.tags,f);!this.lowLatencyMode_&&this.playerInterface_.isAutoLowLatencyMode()&&(this.playerInterface_.enableLowLatencyMode(),
this.lowLatencyMode_=this.playerInterface_.isLowLatencyMode());if(p=r=this.createSegmentReference_(u,p,r,w,f,b.absoluteUri,c,d))r.discontinuitySequence=g,this.config_.hls.ignoreManifestProgramDateTime&&null!=this.minSequenceNumber_&&l<this.minSequenceNumber_||n.push(r)}if(b=n.some(function(x){return null!=x.syncTime}))for(c={},e=0;e<n.length;c={$jscomp$loop$prop$forwardI$677:c.$jscomp$loop$prop$forwardI$677,$jscomp$loop$prop$forwardAdd$678:c.$jscomp$loop$prop$forwardAdd$678,$jscomp$loop$prop$backwardI$679:c.$jscomp$loop$prop$backwardI$679,
$jscomp$loop$prop$reference$568$680:c.$jscomp$loop$prop$reference$568$680,$jscomp$loop$prop$backwardAdd$681:c.$jscomp$loop$prop$backwardAdd$681},e++)if(c.$jscomp$loop$prop$reference$568$680=n[e],null==c.$jscomp$loop$prop$reference$568$680.syncTime)for(c.$jscomp$loop$prop$forwardAdd$678=0,c.$jscomp$loop$prop$forwardI$677=e,f=function(x){return function(){var t=n[x.$jscomp$loop$prop$forwardI$677];if(t){if(null!=t.syncTime)return t.syncTime+x.$jscomp$loop$prop$forwardAdd$678;x.$jscomp$loop$prop$forwardAdd$678-=
t.endTime-t.startTime;x.$jscomp$loop$prop$forwardI$677+=1}return null}}(c),c.$jscomp$loop$prop$backwardAdd$681=0,c.$jscomp$loop$prop$backwardI$679=e,a=function(x){return function(){var t=n[x.$jscomp$loop$prop$backwardI$679];if(t){t!=x.$jscomp$loop$prop$reference$568$680&&(x.$jscomp$loop$prop$backwardAdd$681+=t.endTime-t.startTime);if(null!=t.syncTime)return t.syncTime+x.$jscomp$loop$prop$backwardAdd$681;--x.$jscomp$loop$prop$backwardI$679}return null}}(c);null==c.$jscomp$loop$prop$reference$568$680.syncTime;)c.$jscomp$loop$prop$reference$568$680.syncTime=
a(),null==c.$jscomp$loop$prop$reference$568$680.syncTime&&(c.$jscomp$loop$prop$reference$568$680.syncTime=f());if(b)for(c=$jscomp.makeIterator(n),e=c.next();!e.done;e=c.next())for(f=e.value,e=f.syncTime,f=$jscomp.makeIterator(f.partialReferences),a=f.next();!a.done;a=f.next())a=a.value,a.syncTime=e,e+=a.endTime-a.startTime;c=this.lowestSyncTime_;if(b&&Infinity!=c)for(b=$jscomp.makeIterator(n),e=b.next();!e.done;e=b.next())e.value.syncAgainst(c);return n};
shaka.hls.HlsParser.prototype.variableSubstitution_=function(a,b){a=String(a).replace(/%7B/g,"{").replace(/%7D/g,"}");var c=a.match(/{\$\w*}/g);if(c){c=$jscomp.makeIterator(c);for(var d=c.next();!d.done;d=c.next()){d=d.value;var e=d.slice(2,d.length-1),f=b.get(e);if(f)a=a.replace(d,f);else throw shaka.log.error("A variable has been found that is not declared",e),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_VARIABLE_NOT_FOUND,
e);}}return a};shaka.hls.HlsParser.prototype.guessMimeTypeBeforeLoading_=function(a,b){if(a==shaka.util.ManifestParserUtils.ContentType.TEXT){if("vtt"==b||"wvtt"==b)return"text/vtt";if(b&&""!==b)return"application/mp4"}return a!=shaka.util.ManifestParserUtils.ContentType.IMAGE||b&&"jpeg"!=b?a==shaka.util.ManifestParserUtils.ContentType.AUDIO&&"mp4a.40.34"==b?"audio/mpeg":null:"image/jpeg"};
shaka.hls.HlsParser.prototype.guessMimeTypeFallback_=function(a){return a==shaka.util.ManifestParserUtils.ContentType.TEXT?"text/vtt":shaka.hls.HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_[a].mp4};
shaka.hls.HlsParser.prototype.guessMimeType_=function(a,b,c,d){var e=this,f,g,h,k,l,m,n,p,q,r,w;return $jscomp.asyncExecutePromiseGeneratorProgram(function(u){if(1==u.nextAddress){f=shaka.hls.HlsParser;g=shaka.net.NetworkingEngine.RequestType.SEGMENT;goog.asserts.assert(c.segments.length,"Playlist should have segments!");h=Math.trunc((c.segments.length-1)/2);k=e.variableSubstitution_(c.segments[h].absoluteUri,d);l=new goog.Uri(k);m=l.getPath().split(".").pop();n=f.EXTENSION_MAP_BY_CONTENT_TYPE_[a];
if((p=n[m])||(p=f.RAW_FORMATS_TO_MIME_TYPES_[m])||(p=e.guessMimeTypeBeforeLoading_(a,b)))return u.return(p);q=shaka.net.NetworkingEngine.makeRequest([k],e.config_.retryParameters);q.method="HEAD";return u.yield(e.makeNetworkRequest_(q,g),2)}r=u.yieldResult;return(w=r.headers["content-type"])?u.return(w.split(";")[0]):u.return(e.guessMimeTypeFallback_(a))})};
shaka.hls.HlsParser.prototype.getRequiredTag_=function(a,b){a=shaka.hls.Utils.getFirstTagWithName(a,b);if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_REQUIRED_TAG_MISSING,b);return a};shaka.hls.HlsParser.prototype.addVideoAttributes_=function(a,b,c,d,e){a&&(a.width=Number(b)||void 0,a.height=Number(c)||void 0,a.frameRate=Number(d)||void 0,a.hdr=e||void 0)};
shaka.hls.HlsParser.prototype.requestManifest_=function(a){var b=shaka.net.NetworkingEngine.RequestType.MANIFEST;a=shaka.net.NetworkingEngine.makeRequest([a],this.config_.retryParameters);this.playerInterface_.modifyManifestRequest(a,{format:shaka.util.CmcdManager.StreamingFormat.HLS});return this.makeNetworkRequest_(a,b)};
shaka.hls.HlsParser.prototype.onUpdate_=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress){shaka.log.info("Updating manifest...");goog.asserts.assert(0<a.updatePlaylistDelay_,"We should only call |onUpdate_| when we are suppose to be updating.");if(!a.playerInterface_)return d.return();d.setCatchFinallyBlocks(2);return d.yield(a.update(),4)}if(2!=d.nextAddress)return a.isLive_()&&(b=a.updatePlaylistDelay_,a.updatePlaylistTimer_.tickAfter(b)),
d.leaveTryBlock(0);c=d.enterCatchBlock();if(!a.playerInterface_)return d.return();goog.asserts.assert(c instanceof shaka.util.Error,"Should only receive a Shaka error");c.severity=shaka.util.Error.Severity.RECOVERABLE;a.playerInterface_.onError(c);a.updatePlaylistTimer_.tickAfter(.1);d.jumpToEnd()})};shaka.hls.HlsParser.prototype.isLive_=function(){return this.presentationType_!=shaka.hls.HlsParser.PresentationType_.VOD};
shaka.hls.HlsParser.prototype.setPresentationType_=function(a){this.presentationType_=a;this.presentationTimeline_&&this.presentationTimeline_.setStatic(!this.isLive_());this.isLive_()||this.updatePlaylistTimer_.stop()};
shaka.hls.HlsParser.prototype.makeNetworkRequest_=function(a,b){if(!this.operationManager_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.PLAYER,shaka.util.Error.Code.OPERATION_ABORTED);a=this.playerInterface_.networkingEngine.request(b,a);this.operationManager_.manage(a);return a.promise};
shaka.hls.HlsParser.fairplayDrmParser_=function(a,b){if("video/mp2t"==b)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED);if(shaka.util.Platform.isMediaKeysPolyfilled())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.MANIFEST,shaka.util.Error.Code.HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED);return shaka.util.ManifestParserUtils.createDrmInfo("com.apple.fps",
[{initDataType:"sinf",initData:new Uint8Array(0),keyId:null}])};
shaka.hls.HlsParser.widevineDrmParser_=function(a){var b=a.getRequiredAttrValue("METHOD"),c=["SAMPLE-AES","SAMPLE-AES-CTR"];if(!c.includes(b))return shaka.log.error("Widevine in HLS is only supported with [",c.join(", "),"], not",b),null;b=a.getRequiredAttrValue("URI");b=shaka.net.DataUriPlugin.parseRaw(b);b=shaka.util.BufferUtils.toUint8(b.data);b=shaka.util.ManifestParserUtils.createDrmInfo("com.widevine.alpha",[{initDataType:"cenc",initData:b}]);if(a=a.getAttributeValue("KEYID"))a=a.toLowerCase(),
goog.asserts.assert(a.startsWith("0x"),"Incorrect KEYID format!"),b.keyIds=new Set([a.substr(2)]);return b};
shaka.hls.HlsParser.playreadyDrmParser_=function(a){var b=a.getRequiredAttrValue("METHOD"),c=["SAMPLE-AES","SAMPLE-AES-CTR"];if(!c.includes(b))return shaka.log.error("PlayReady in HLS is only supported with [",c.join(", "),"], not",b),null;a=a.getRequiredAttrValue("URI");a=shaka.net.DataUriPlugin.parseRaw(a);a=shaka.util.BufferUtils.toUint8(a.data);b=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);c=new Set;a=shaka.util.Pssh.createPssh(a,b,c,0);return shaka.util.ManifestParserUtils.createDrmInfo("com.microsoft.playready",
[{initDataType:"cenc",initData:a}])};shaka.hls.HlsParser.identityDrmParser_=function(a){a=a.getRequiredAttrValue("METHOD");var b=["SAMPLE-AES","SAMPLE-AES-CTR"];return b.includes(a)?shaka.util.ManifestParserUtils.createDrmInfo("org.w3.clearkey",null):(shaka.log.error("Identity (ClearKey) in HLS is only supported with [",b.join(", "),"], not",a),null)};goog.exportSymbol("shaka.hls.HlsParser",shaka.hls.HlsParser);
shaka.hls.HlsParser.RAW_FORMATS_TO_MIME_TYPES_={aac:"audio/aac",ac3:"audio/ac3",ec3:"audio/ec3",mp3:"audio/mpeg"};shaka.hls.HlsParser.AUDIO_EXTENSIONS_TO_MIME_TYPES_={mp4:"audio/mp4",mp4a:"audio/mp4",m4s:"audio/mp4",m4i:"audio/mp4",m4a:"audio/mp4",m4f:"audio/mp4",cmfa:"audio/mp4",ts:"video/mp2t",tsa:"video/mp2t"};shaka.hls.HlsParser.VIDEO_EXTENSIONS_TO_MIME_TYPES_={mp4:"video/mp4",mp4v:"video/mp4",m4s:"video/mp4",m4i:"video/mp4",m4v:"video/mp4",m4f:"video/mp4",cmfv:"video/mp4",ts:"video/mp2t",tsv:"video/mp2t"};
shaka.hls.HlsParser.TEXT_EXTENSIONS_TO_MIME_TYPES_={mp4:"application/mp4",m4s:"application/mp4",m4i:"application/mp4",m4f:"application/mp4",cmft:"application/mp4",vtt:"text/vtt",webvtt:"text/vtt",ttml:"application/ttml+xml"};shaka.hls.HlsParser.IMAGE_EXTENSIONS_TO_MIME_TYPES_={jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",avif:"image/avif"};
shaka.hls.HlsParser.EXTENSION_MAP_BY_CONTENT_TYPE_={audio:shaka.hls.HlsParser.AUDIO_EXTENSIONS_TO_MIME_TYPES_,video:shaka.hls.HlsParser.VIDEO_EXTENSIONS_TO_MIME_TYPES_,text:shaka.hls.HlsParser.TEXT_EXTENSIONS_TO_MIME_TYPES_,image:shaka.hls.HlsParser.IMAGE_EXTENSIONS_TO_MIME_TYPES_};
shaka.hls.HlsParser.KEYFORMATS_TO_DRM_PARSERS_={"com.apple.streamingkeydelivery":shaka.hls.HlsParser.fairplayDrmParser_,"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":shaka.hls.HlsParser.widevineDrmParser_,"com.microsoft.playready":shaka.hls.HlsParser.playreadyDrmParser_,identity:shaka.hls.HlsParser.identityDrmParser_};shaka.hls.HlsParser.PresentationType_={VOD:"VOD",EVENT:"EVENT",LIVE:"LIVE"};
shaka.util.Platform.isTizen3()||shaka.util.Platform.isTizen2()||shaka.util.Platform.isWebOS3()||(shaka.media.ManifestParser.registerParserByExtension("m3u8",function(){return new shaka.hls.HlsParser}),shaka.media.ManifestParser.registerParserByMime("application/x-mpegurl",function(){return new shaka.hls.HlsParser}),shaka.media.ManifestParser.registerParserByMime("application/vnd.apple.mpegurl",function(){return new shaka.hls.HlsParser}));shaka.net.HttpPluginUtils=function(){};
shaka.net.HttpPluginUtils.makeResponse=function(a,b,c,d,e,f){if(200<=c&&299>=c&&202!=c)return{uri:e||d,originalUri:d,data:b,status:c,headers:a,fromCache:!!a["x-shaka-from-cache"]};e=null;try{e=shaka.util.StringUtils.fromBytesAutoDetect(b)}catch(g){}shaka.log.debug("HTTP error text:",e);throw new shaka.util.Error(401==c||403==c?shaka.util.Error.Severity.CRITICAL:shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.BAD_HTTP_STATUS,d,c,e,a,f);};shaka.net.HttpFetchPlugin=function(){};
shaka.net.HttpFetchPlugin.parse=function(a,b,c,d,e){var f=new shaka.net.HttpFetchPlugin.Headers_;shaka.util.MapUtils.asMap(b.headers).forEach(function(l,m){f.append(m,l)});var g=new shaka.net.HttpFetchPlugin.AbortController_,h={canceled:!1,timedOut:!1};a=shaka.net.HttpFetchPlugin.request_(a,c,{body:b.body||void 0,headers:f,method:b.method,signal:g.signal,credentials:b.allowCrossSiteCredentials?"include":void 0},h,d,e,b.streamDataCallback);a=new shaka.util.AbortableOperation(a,function(){h.canceled=
!0;g.abort();return Promise.resolve()});if(b=b.retryParameters.timeout){var k=new shaka.util.Timer(function(){h.timedOut=!0;g.abort()});k.tickAfter(b/1E3);a.finally(function(){k.stop()})}return a};
shaka.net.HttpFetchPlugin.request_=function(a,b,c,d,e,f,g){var h,k,l,m,n,p,q,r,w,u,v,x,t;return $jscomp.asyncExecutePromiseGeneratorProgram(function(y){switch(y.nextAddress){case 1:return h=shaka.net.HttpFetchPlugin.fetch_,k=shaka.net.HttpFetchPlugin.ReadableStream_,p=n=0,q=Date.now(),y.setCatchFinallyBlocks(2),y.yield(h(a,c),4);case 4:return l=y.yieldResult,f(shaka.net.HttpFetchPlugin.headersToGenericObject_(l.headers)),r=l.clone().body.getReader(),u=(w=l.headers.get("Content-Length"))?parseInt(w,
10):0,v=function(A){var z=function(){var B,D,G;return $jscomp.asyncExecutePromiseGeneratorProgram(function(C){switch(C.nextAddress){case 1:return C.setCatchFinallyBlocks(2),C.yield(r.read(),4);case 4:B=C.yieldResult;C.leaveTryBlock(3);break;case 2:return D=C.enterCatchBlock(),shaka.log.v1("error reading from stream",D.message),C.return();case 3:if(B.done){C.jumpTo(5);break}n+=B.value.byteLength;if(!g){C.jumpTo(5);break}return C.yield(g(B.value),5);case 5:G=Date.now();if(100<G-q||B.done)e(G-q,n-p,
u-n),p=n,q=G;B.done?(goog.asserts.assert(!B.value,'readObj should be unset when "done" is true.'),A.close()):(A.enqueue(B.value),z());C.jumpToEnd()}})};z()},new k({start:v}),y.yield(l.arrayBuffer(),5);case 5:m=y.yieldResult;y.leaveTryBlock(3);break;case 2:x=y.enterCatchBlock();if(d.canceled)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.OPERATION_ABORTED,a,b);if(d.timedOut)throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,
shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.TIMEOUT,a,b);throw new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.HTTP_ERROR,a,x,b);case 3:return t=shaka.net.HttpFetchPlugin.headersToGenericObject_(l.headers),y.return(shaka.net.HttpPluginUtils.makeResponse(t,m,l.status,a,l.url,b))}})};shaka.net.HttpFetchPlugin.headersToGenericObject_=function(a){var b={};a.forEach(function(c,d){b[d.trim()]=c});return b};
shaka.net.HttpFetchPlugin.isSupported=function(){return false;if(window.ReadableStream)try{new ReadableStream({})}catch(a){return!1}else return!1;return!(!window.fetch||!window.AbortController)};goog.exportSymbol("shaka.net.HttpFetchPlugin",shaka.net.HttpFetchPlugin);goog.exportProperty(shaka.net.HttpFetchPlugin,"isSupported",shaka.net.HttpFetchPlugin.isSupported);goog.exportProperty(shaka.net.HttpFetchPlugin,"parse",shaka.net.HttpFetchPlugin.parse);shaka.net.HttpFetchPlugin.fetch_=window.fetch;
shaka.net.HttpFetchPlugin.AbortController_=window.AbortController;shaka.net.HttpFetchPlugin.ReadableStream_=window.ReadableStream;shaka.net.HttpFetchPlugin.Headers_=window.Headers;
shaka.net.HttpFetchPlugin.isSupported()&&(shaka.net.NetworkingEngine.registerScheme("http",shaka.net.HttpFetchPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.PREFERRED,!0),shaka.net.NetworkingEngine.registerScheme("https",shaka.net.HttpFetchPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.PREFERRED,!0),shaka.net.NetworkingEngine.registerScheme("blob",shaka.net.HttpFetchPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.PREFERRED,!0));shaka.net.HttpXHRPlugin=function(){};
shaka.net.HttpXHRPlugin.parse=function(a,b,c,d,e){var f=new shaka.net.HttpXHRPlugin.Xhr_,g=Date.now(),h=0,k=new Promise(function(l,m){f.open(b.method,a,!0);f.responseType="arraybuffer";f.timeout=b.retryParameters.timeout;f.withCredentials=b.allowCrossSiteCredentials;f.onabort=function(){m(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.OPERATION_ABORTED,a,c))};var n=!1;f.onreadystatechange=function(r){2!=f.readyState||n||(r=shaka.net.HttpXHRPlugin.headersToGenericObject_(f),
e(r),n=!0)};f.onload=function(r){r=shaka.net.HttpXHRPlugin.headersToGenericObject_(f);goog.asserts.assert(f.response instanceof ArrayBuffer,"XHR should have a response by now!");var w=f.response;try{var u=shaka.net.HttpPluginUtils.makeResponse(r,w,f.status,a,f.responseURL,c);l(u)}catch(v){goog.asserts.assert(v instanceof shaka.util.Error,"Wrong error type!"),m(v)}};f.onerror=function(r){m(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.HTTP_ERROR,
a,r,c))};f.ontimeout=function(r){m(new shaka.util.Error(shaka.util.Error.Severity.RECOVERABLE,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.TIMEOUT,a,c))};f.onprogress=function(r){var w=Date.now();if(100<w-g||r.lengthComputable&&r.loaded==r.total)d(w-g,r.loaded-h,r.total-r.loaded),h=r.loaded,g=w};for(var p in b.headers){var q=p.toLowerCase();f.setRequestHeader(q,b.headers[p])}f.send(b.body)});return new shaka.util.AbortableOperation(k,function(){f.abort();return Promise.resolve()})};
shaka.net.HttpXHRPlugin.headersToGenericObject_=function(a){var b=a.getAllResponseHeaders().trim().split("\r\n");a={};b=$jscomp.makeIterator(b);for(var c=b.next();!c.done;c=b.next())c=c.value.split(": "),a[c[0].toLowerCase()]=c.slice(1).join(": ");return a};goog.exportSymbol("shaka.net.HttpXHRPlugin",shaka.net.HttpXHRPlugin);goog.exportProperty(shaka.net.HttpXHRPlugin,"parse",shaka.net.HttpXHRPlugin.parse);shaka.net.HttpXHRPlugin.Xhr_=XMLHttpRequest;
shaka.net.NetworkingEngine.registerScheme("http",shaka.net.HttpXHRPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.FALLBACK,!0);shaka.net.NetworkingEngine.registerScheme("https",shaka.net.HttpXHRPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.FALLBACK,!0);shaka.net.NetworkingEngine.registerScheme("blob",shaka.net.HttpXHRPlugin.parse,shaka.net.NetworkingEngine.PluginPriority.FALLBACK,!0);shaka.offline={};shaka.offline.DownloadInfo=function(a,b,c,d){this.ref=a;this.estimateId=b;this.groupId=c;this.isInitSegment=d};shaka.offline.DownloadInfo.idForSegmentRef=function(a){return a.getUris().map(function(b){return"{"+encodeURI(b)+"}"}).join("")+":"+a.startByte+":"+a.endByte};shaka.offline.DownloadInfo.prototype.getRefId=function(){return shaka.offline.DownloadInfo.idForSegmentRef(this.ref)};
shaka.offline.DownloadInfo.prototype.makeSegmentRequest=function(a){return shaka.util.Networking.createSegmentRequest(this.ref.getUris(),this.ref.startByte,this.ref.endByte,a.streaming.retryParameters)};shaka.offline.DownloadProgressEstimator=function(){this.actualDownloaded_=this.estimatedDownloaded_=this.estimatedTotal_=0;this.pending_=new Map;this.nextId_=0};shaka.offline.DownloadProgressEstimator.prototype.open=function(a){this.estimatedTotal_+=a;var b=this.nextId_;this.nextId_++;this.pending_.set(b,a);return b};
shaka.offline.DownloadProgressEstimator.prototype.close=function(a,b){if(this.pending_.has(a)){var c=this.pending_.get(a);this.pending_.delete(a);this.estimatedDownloaded_+=c;this.actualDownloaded_+=b}};shaka.offline.DownloadProgressEstimator.prototype.getEstimatedProgress=function(){return 0==this.estimatedTotal_?0:this.estimatedDownloaded_/this.estimatedTotal_};shaka.offline.DownloadProgressEstimator.prototype.getTotalDownloaded=function(){return this.actualDownloaded_};shaka.offline.DownloadManager=function(a){var b=this;this.networkingEngine_=a;this.groups_=new Map;this.destroyer_=new shaka.util.Destroyer(function(){return b.abortAll().catch(function(){})});this.abortCallbacks_=[];this.onProgress_=function(c,d){};this.onInitData_=function(c,d){};this.estimator_=new shaka.offline.DownloadProgressEstimator};shaka.offline.DownloadManager.prototype.destroy=function(){return this.destroyer_.destroy()};
shaka.offline.DownloadManager.prototype.setCallbacks=function(a,b){this.onProgress_=a;this.onInitData_=b};shaka.offline.DownloadManager.prototype.abortAll=function(){var a=this.abortCallbacks_.map(function(b){return b()});this.abortCallbacks_=[];return Promise.all(a)};shaka.offline.DownloadManager.prototype.addDownloadEstimate=function(a){return this.estimator_.open(a)};
shaka.offline.DownloadManager.prototype.queue=function(a,b,c,d,e){var f=this;this.destroyer_.ensureNotDestroyed();var g=(this.groups_.get(a)||Promise.resolve()).then(function(){var h,k,l,m,n,p,q;return $jscomp.asyncExecutePromiseGeneratorProgram(function(r){if(1==r.nextAddress)return r.yield(f.fetchSegment_(b),2);h=r.yieldResult;if(f.destroyer_.destroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.OPERATION_ABORTED);if(d)for(m in k=
shaka.util.BufferUtils.toUint8(h),l=new shaka.util.Pssh(k),l.data)n=Number(m),p=l.data[n],q=l.systemIds[n],f.onInitData_(p,q);f.estimator_.close(c,h.byteLength);f.onProgress_(f.estimator_.getEstimatedProgress(),f.estimator_.getTotalDownloaded());return r.return(e(h))})});this.groups_.set(a,g);return g};
shaka.offline.DownloadManager.prototype.queueWork=function(a,b){this.destroyer_.ensureNotDestroyed();var c=(this.groups_.get(a)||Promise.resolve()).then(function(){return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return d.yield(b(),0)})});this.groups_.set(a,c);return c};shaka.offline.DownloadManager.prototype.waitToFinish=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return 1==b.nextAddress?b.yield(Promise.all(a.groups_.values()),2):b.return(a.estimator_.getTotalDownloaded())})};
shaka.offline.DownloadManager.prototype.fetchSegment_=function(a){var b=this,c,d,e,f;return $jscomp.asyncExecutePromiseGeneratorProgram(function(g){if(1==g.nextAddress)return c=shaka.net.NetworkingEngine.RequestType.SEGMENT,d=b.networkingEngine_.request(c,a),e=function(){return d.abort()},b.abortCallbacks_.push(e),g.yield(d.promise,2);f=g.yieldResult;shaka.util.ArrayUtils.remove(b.abortCallbacks_,e);return g.return(f.data)})};shaka.offline.indexeddb={};shaka.offline.indexeddb.DBOperation=function(a,b){var c=this;this.transaction_=a;this.store_=a.objectStore(b);this.promise_=new shaka.util.PublicPromise;a.onabort=function(d){d.preventDefault();c.promise_.reject()};a.onerror=function(d){d.preventDefault();c.promise_.reject()};a.oncomplete=function(d){c.promise_.resolve()}};
shaka.offline.indexeddb.DBOperation.prototype.abort=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){if(1==b.nextAddress){try{a.transaction_.abort()}catch(c){}b.setCatchFinallyBlocks(2);return b.yield(a.promise_,4)}if(2!=b.nextAddress)return b.leaveTryBlock(0);b.enterCatchBlock();b.jumpToEnd()})};
shaka.offline.indexeddb.DBOperation.prototype.forEachEntry=function(a){var b=this;return new Promise(function(c,d){var e=b.store_.openCursor();e.onerror=d;e.onsuccess=function(f){var g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress){if(null==e.result)return c(),h.return();g=e.result;return h.yield(a(g.key,g.value,g),2)}g.continue();h.jumpToEnd()})}})};shaka.offline.indexeddb.DBOperation.prototype.store=function(){return this.store_};
shaka.offline.indexeddb.DBOperation.prototype.promise=function(){return this.promise_};shaka.offline.indexeddb.DBConnection=function(a){this.connection_=a;this.pending_=[]};shaka.offline.indexeddb.DBConnection.prototype.destroy=function(){return Promise.all(this.pending_.map(function(a){return a.abort()}))};shaka.offline.indexeddb.DBConnection.prototype.startReadOnlyOperation=function(a){return this.startOperation_(a,"readonly")};shaka.offline.indexeddb.DBConnection.prototype.startReadWriteOperation=function(a){return this.startOperation_(a,"readwrite")};
shaka.offline.indexeddb.DBConnection.prototype.startOperation_=function(a,b){var c=this;b=this.connection_.transaction([a],b);var d=new shaka.offline.indexeddb.DBOperation(b,a);this.pending_.push(d);d.promise().then(function(){return c.stopTracking_(d)},function(){return c.stopTracking_(d)});return d};shaka.offline.indexeddb.DBConnection.prototype.stopTracking_=function(a){shaka.util.ArrayUtils.remove(this.pending_,a)};shaka.offline.indexeddb.BaseStorageCell=function(a,b,c){this.connection_=new shaka.offline.indexeddb.DBConnection(a);this.segmentStore_=b;this.manifestStore_=c};shaka.offline.indexeddb.BaseStorageCell.prototype.destroy=function(){return this.connection_.destroy()};shaka.offline.indexeddb.BaseStorageCell.prototype.hasFixedKeySpace=function(){return!0};shaka.offline.indexeddb.BaseStorageCell.prototype.addSegments=function(a){return this.rejectAdd(this.segmentStore_)};
shaka.offline.indexeddb.BaseStorageCell.prototype.removeSegments=function(a,b){return this.remove_(this.segmentStore_,a,b)};shaka.offline.indexeddb.BaseStorageCell.prototype.getSegments=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return d.yield(b.get_(b.segmentStore_,a),2);c=d.yieldResult;return d.return(c.map(function(e){return b.convertSegmentData(e)}))})};shaka.offline.indexeddb.BaseStorageCell.prototype.addManifests=function(a){return this.rejectAdd(this.manifestStore_)};
shaka.offline.indexeddb.BaseStorageCell.prototype.updateManifest=function(a,b){return this.rejectUpdate(this.manifestStore_)};shaka.offline.indexeddb.BaseStorageCell.prototype.updateManifestImplementation=function(a,b){var c=this.connection_.startReadWriteOperation(this.manifestStore_),d=c.store();d.get(a).onsuccess=function(e){d.put(b,a)};return c.promise()};
shaka.offline.indexeddb.BaseStorageCell.prototype.updateManifestExpiration=function(a,b){var c=this.connection_.startReadWriteOperation(this.manifestStore_),d=c.store();d.get(a).onsuccess=function(e){if(e=e.target.result)e.expiration=b,d.put(e,a)};return c.promise()};shaka.offline.indexeddb.BaseStorageCell.prototype.removeManifests=function(a,b){return this.remove_(this.manifestStore_,a,b)};
shaka.offline.indexeddb.BaseStorageCell.prototype.getManifests=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return d.yield(b.get_(b.manifestStore_,a),2);c=d.yieldResult;return d.return(Promise.all(c.map(function(e){return b.convertManifest(e)})))})};
shaka.offline.indexeddb.BaseStorageCell.prototype.getAllManifests=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(b=a.connection_.startReadOnlyOperation(a.manifestStore_),c=new Map,d.yield(b.forEachEntry(function(e,f){var g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return h.yield(a.convertManifest(f),2);g=h.yieldResult;c.set(e,g);h.jumpToEnd()})}),2)):3!=d.nextAddress?d.yield(b.promise(),3):
d.return(c)})};shaka.offline.indexeddb.BaseStorageCell.prototype.convertSegmentData=function(a){return a};shaka.offline.indexeddb.BaseStorageCell.prototype.convertManifest=function(a){return Promise.resolve(a)};shaka.offline.indexeddb.BaseStorageCell.prototype.rejectAdd=function(a){return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.NEW_KEY_OPERATION_NOT_SUPPORTED,"Cannot add new value to "+a))};
shaka.offline.indexeddb.BaseStorageCell.prototype.rejectUpdate=function(a){return Promise.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MODIFY_OPERATION_NOT_SUPPORTED,"Cannot modify values in "+a))};
shaka.offline.indexeddb.BaseStorageCell.prototype.add=function(a,b){var c=this,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==m.nextAddress){d=c.connection_.startReadWriteOperation(a);e=d.store();f=[];g={};h=$jscomp.makeIterator(b);for(k=h.next();!k.done;g={$jscomp$loop$prop$request$683:g.$jscomp$loop$prop$request$683},k=h.next())l=k.value,g.$jscomp$loop$prop$request$683=e.add(l),g.$jscomp$loop$prop$request$683.onsuccess=function(n){return function(p){f.push(n.$jscomp$loop$prop$request$683.result)}}(g);
return m.yield(d.promise(),2)}return m.return(f)})};shaka.offline.indexeddb.BaseStorageCell.prototype.remove_=function(a,b,c){a=this.connection_.startReadWriteOperation(a);var d=a.store(),e={};b=$jscomp.makeIterator(b);for(var f=b.next();!f.done;e={$jscomp$loop$prop$key$685:e.$jscomp$loop$prop$key$685},f=b.next())e.$jscomp$loop$prop$key$685=f.value,d.delete(e.$jscomp$loop$prop$key$685).onsuccess=function(g){return function(){return c(g.$jscomp$loop$prop$key$685)}}(e);return a.promise()};
shaka.offline.indexeddb.BaseStorageCell.prototype.get_=function(a,b){var c=this,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==m.nextAddress){d=c.connection_.startReadOnlyOperation(a);e=d.store();f={};g=[];h={};k=$jscomp.makeIterator(b);for(l=k.next();!l.done;h={$jscomp$loop$prop$request$687:h.$jscomp$loop$prop$request$687,$jscomp$loop$prop$key$688:h.$jscomp$loop$prop$key$688},l=k.next())h.$jscomp$loop$prop$key$688=l.value,h.$jscomp$loop$prop$request$687=e.get(h.$jscomp$loop$prop$key$688),
h.$jscomp$loop$prop$request$687.onsuccess=function(n){return function(){void 0==n.$jscomp$loop$prop$request$687.result&&g.push(n.$jscomp$loop$prop$key$688);f[n.$jscomp$loop$prop$key$688]=n.$jscomp$loop$prop$request$687.result}}(h);return m.yield(d.promise(),2)}if(g.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.KEY_NOT_FOUND,"Could not find values for "+g);return m.return(b.map(function(n){return f[n]}))})};shaka.offline.indexeddb.EmeSessionStorageCell=function(a,b){this.connection_=new shaka.offline.indexeddb.DBConnection(a);this.store_=b};shaka.offline.indexeddb.EmeSessionStorageCell.prototype.destroy=function(){return this.connection_.destroy()};
shaka.offline.indexeddb.EmeSessionStorageCell.prototype.getAll=function(){var a=this,b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(b=a.connection_.startReadOnlyOperation(a.store_),c=[],d.yield(b.forEachEntry(function(e,f){c.push(f)}),2)):3!=d.nextAddress?d.yield(b.promise(),3):d.return(c)})};
shaka.offline.indexeddb.EmeSessionStorageCell.prototype.add=function(a){var b=this.connection_.startReadWriteOperation(this.store_),c=b.store();a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())c.add(d.value);return b.promise()};
shaka.offline.indexeddb.EmeSessionStorageCell.prototype.remove=function(a){var b=this,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){return 1==d.nextAddress?(c=b.connection_.startReadWriteOperation(b.store_),d.yield(c.forEachEntry(function(e,f,g){a.includes(f.sessionId)&&g.delete()}),2)):d.yield(c.promise(),0)})};shaka.offline.StorageCellHandle={};shaka.offline.StorageCellPath={};shaka.offline.StorageMuxer=function(){this.mechanisms_=new Map};shaka.offline.StorageMuxer.prototype.destroy=function(){for(var a=[],b=$jscomp.makeIterator(this.mechanisms_.values()),c=b.next();!c.done;c=b.next())a.push(c.value.destroy());this.mechanisms_.clear();return Promise.all(a)};
shaka.offline.StorageMuxer.prototype.init=function(){var a=this;shaka.offline.StorageMuxer.getRegistry_().forEach(function(e,f){(e=e())?a.mechanisms_.set(f,e):shaka.log.info("Skipping "+f+" as it is not supported on this platform")});for(var b=[],c=$jscomp.makeIterator(this.mechanisms_.values()),d=c.next();!d.done;d=c.next())b.push(d.value.init());return Promise.all(b)};
shaka.offline.StorageMuxer.prototype.getActive=function(){var a=null;this.mechanisms_.forEach(function(b,c){b.getCells().forEach(function(d,e){d.hasFixedKeySpace()||a||(a={path:{mechanism:c,cell:e},cell:d})})});if(a)return a;throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MISSING_STORAGE_CELL,"Could not find a cell that supports add-operations");};
shaka.offline.StorageMuxer.prototype.forEachCell=function(a){this.mechanisms_.forEach(function(b,c){b.getCells().forEach(function(d,e){a({mechanism:c,cell:e},d)})})};
shaka.offline.StorageMuxer.prototype.getCell=function(a,b){var c=this.mechanisms_.get(a);if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MISSING_STORAGE_CELL,"Could not find mechanism with name "+a);a=c.getCells().get(b);if(!a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MISSING_STORAGE_CELL,"Could not find cell with name "+b);return a};
shaka.offline.StorageMuxer.prototype.forEachEmeSessionCell=function(a){this.mechanisms_.forEach(function(b,c){a(b.getEmeSessionCell())})};shaka.offline.StorageMuxer.prototype.getEmeSessionCell=function(){var a=Array.from(this.mechanisms_.keys());if(!a.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.STORAGE_NOT_SUPPORTED,"No supported storage mechanisms found");return this.mechanisms_.get(a[0]).getEmeSessionCell()};
shaka.offline.StorageMuxer.prototype.resolvePath=function(a){var b=this.mechanisms_.get(a.mechanism);return b?b.getCells().get(a.cell):null};
shaka.offline.StorageMuxer.prototype.erase=function(){var a=this,b,c,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){return 1==e.nextAddress?(b=Array.from(a.mechanisms_.values()),c=0<b.length,c||(d=shaka.offline.StorageMuxer.getRegistry_(),d.forEach(function(f,g){(f=f())&&b.push(f)})),e.yield(Promise.all(b.map(function(f){return f.erase()})),2)):c?e.jumpTo(0):e.yield(Promise.all(b.map(function(f){return f.destroy()})),0)})};
shaka.offline.StorageMuxer.register=function(a,b){shaka.offline.StorageMuxer.registry_.set(a,b)};shaka.offline.StorageMuxer.unregister=function(a){shaka.offline.StorageMuxer.registry_.delete(a)};shaka.offline.StorageMuxer.support=function(){var a=shaka.offline.StorageMuxer.getRegistry_();a=$jscomp.makeIterator(a.values());for(var b=a.next();!b.done;b=a.next())if(b=b.value,b=b())return b.destroy(),!0;return!1};
shaka.offline.StorageMuxer.overrideSupport=function(a){shaka.offline.StorageMuxer.override_=a};shaka.offline.StorageMuxer.clearOverride=function(){shaka.offline.StorageMuxer.override_=null};shaka.offline.StorageMuxer.getRegistry_=function(){var a=shaka.offline.StorageMuxer.override_,b=shaka.offline.StorageMuxer.registry_;return COMPILED?b:a||b};goog.exportSymbol("shaka.offline.StorageMuxer",shaka.offline.StorageMuxer);goog.exportProperty(shaka.offline.StorageMuxer,"unregister",shaka.offline.StorageMuxer.unregister);
goog.exportProperty(shaka.offline.StorageMuxer,"register",shaka.offline.StorageMuxer.register);goog.exportProperty(shaka.offline.StorageMuxer.prototype,"destroy",shaka.offline.StorageMuxer.prototype.destroy);shaka.offline.StorageMuxer.override_=null;shaka.offline.StorageMuxer.registry_=new Map;shaka.offline.indexeddb.V1StorageCell=function(){shaka.offline.indexeddb.BaseStorageCell.apply(this,arguments)};$jscomp.inherits(shaka.offline.indexeddb.V1StorageCell,shaka.offline.indexeddb.BaseStorageCell);
shaka.offline.indexeddb.V1StorageCell.prototype.updateManifestExpiration=function(a,b){var c=this,d,e,f;return $jscomp.asyncExecutePromiseGeneratorProgram(function(g){d=c.connection_.startReadWriteOperation(c.manifestStore_);e=d.store();f=new shaka.util.PublicPromise;e.get(a).onsuccess=function(h){(h=h.target.result)?(goog.asserts.assert(h.key==a,"With in-line keys, the keys should match"),h.expiration=b,e.put(h),f.resolve()):f.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.KEY_NOT_FOUND,"Could not find values for "+a))};return g.yield(Promise.all([d.promise(),f]),0)})};
shaka.offline.indexeddb.V1StorageCell.prototype.convertManifest=function(a){var b,c,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress){b=shaka.offline.indexeddb.V1StorageCell;c=[];for(d=0;d<a.periods.length;++d)e=d==a.periods.length-1?a.duration:a.periods[d+1].startTime,f=e-a.periods[d].startTime,g=b.convertPeriod_(a.periods[d],f),c.push(g);return k.yield(shaka.util.PeriodCombiner.combineDbStreams(c),2)}h=k.yieldResult;return k.return({creationTime:0,originalManifestUri:a.originalManifestUri,
duration:a.duration,size:a.size,expiration:null==a.expiration?Infinity:a.expiration,streams:h,sessionIds:a.sessionIds,drmInfo:a.drmInfo,appMetadata:a.appMetadata,sequenceMode:!1})})};
shaka.offline.indexeddb.V1StorageCell.convertPeriod_=function(a,b){var c=shaka.offline.indexeddb.V1StorageCell;c.fillMissingVariants_(a);for(var d=$jscomp.makeIterator(a.streams),e=d.next();!e.done;e=d.next())goog.asserts.assert(e.value.variantIds,"After filling in missing variants, each stream should have variant ids");return a.streams.map(function(f){return c.convertStream_(f,a.startTime,b)})};
shaka.offline.indexeddb.V1StorageCell.convertStream_=function(a,b,c){var d=shaka.offline.indexeddb.V1StorageCell,e=a.initSegmentUri?d.getKeyFromSegmentUri_(a.initSegmentUri):null,f=b+a.presentationTimeOffset,g=b+c;return{id:a.id,originalId:null,primary:a.primary,type:a.contentType,mimeType:a.mimeType,codecs:a.codecs,frameRate:a.frameRate,pixelAspectRatio:void 0,hdr:void 0,kind:a.kind,language:a.language,label:a.label,width:a.width,height:a.height,initSegmentKey:e,encrypted:a.encrypted,keyIds:new Set([a.keyId]),
segments:a.segments.map(function(h){return d.convertSegment_(h,e,b,g,f)}),variantIds:a.variantIds,roles:[],forced:!1,audioSamplingRate:null,channelsCount:null,spatialAudio:!1,closedCaptions:null,tilesLayout:void 0}};shaka.offline.indexeddb.V1StorageCell.convertSegment_=function(a,b,c,d,e){var f=shaka.offline.indexeddb.V1StorageCell.getKeyFromSegmentUri_(a.uri);return{startTime:c+a.startTime,endTime:c+a.endTime,dataKey:f,initSegmentKey:b,appendWindowStart:c,appendWindowEnd:d,timestampOffset:e,tilesLayout:""}};
shaka.offline.indexeddb.V1StorageCell.prototype.convertSegmentData=function(a){return{data:a.data}};shaka.offline.indexeddb.V1StorageCell.getKeyFromSegmentUri_=function(a){var b;if((b=/^offline:[0-9]+\/[0-9]+\/([0-9]+)$/.exec(a))||(b=/^offline:segment\/([0-9]+)$/.exec(a)))return Number(b[1]);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,"Could not parse uri "+a);};
shaka.offline.indexeddb.V1StorageCell.fillMissingVariants_=function(a){var b=shaka.util.ManifestParserUtils.ContentType.AUDIO,c=shaka.util.ManifestParserUtils.ContentType.VIDEO,d=a.streams.filter(function(l){return l.contentType==b});a=a.streams.filter(function(l){return l.contentType==c});if(!d.every(function(l){return l.variantIds})||!a.every(function(l){return l.variantIds})){goog.asserts.assert(d.every(function(l){return!l.variantIds}),"Some audio streams have variant ids and some do not.");goog.asserts.assert(a.every(function(l){return!l.variantIds}),
"Some video streams have variant ids and some do not.");for(var e=$jscomp.makeIterator(d),f=e.next();!f.done;f=e.next())f.value.variantIds=[];e=$jscomp.makeIterator(a);for(f=e.next();!f.done;f=e.next())f.value.variantIds=[];e=0;if(a.length&&!d.length){shaka.log.debug("Found video-only content. Creating variants for video.");var g=e++,h=$jscomp.makeIterator(a);for(f=h.next();!f.done;f=h.next())f.value.variantIds.push(g)}if(!a.length&&d.length)for(shaka.log.debug("Found audio-only content. Creating variants for audio."),
g=e++,h=$jscomp.makeIterator(d),f=h.next();!f.done;f=h.next())f.value.variantIds.push(g);if(a.length&&d.length)for(shaka.log.debug("Found audio-video content. Creating variants."),d=$jscomp.makeIterator(d),f=d.next();!f.done;f=d.next())for(f=f.value,g=$jscomp.makeIterator(a),h=g.next();!h.done;h=g.next()){h=h.value;var k=e++;f.variantIds.push(k);h.variantIds.push(k)}}};shaka.offline.indexeddb.V2StorageCell=function(){shaka.offline.indexeddb.BaseStorageCell.apply(this,arguments)};$jscomp.inherits(shaka.offline.indexeddb.V2StorageCell,shaka.offline.indexeddb.BaseStorageCell);
shaka.offline.indexeddb.V2StorageCell.prototype.convertManifest=function(a){var b=this,c,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress){c=[];for(d=0;d<a.periods.length;++d)e=d==a.periods.length-1?a.duration:a.periods[d+1].startTime,f=e-a.periods[d].startTime,g=b.convertPeriod_(a.periods[d],f),c.push(g);return k.yield(shaka.util.PeriodCombiner.combineDbStreams(c),2)}h=k.yieldResult;return k.return({appMetadata:a.appMetadata,creationTime:0,drmInfo:a.drmInfo,
duration:a.duration,expiration:null==a.expiration?Infinity:a.expiration,originalManifestUri:a.originalManifestUri,sessionIds:a.sessionIds,size:a.size,streams:h,sequenceMode:!1})})};shaka.offline.indexeddb.V2StorageCell.prototype.convertPeriod_=function(a,b){for(var c=[],d=$jscomp.makeIterator(a.streams),e=d.next();!e.done;e=d.next())e=e.value,0!=e.variantIds.length&&c.push(this.convertStream_(e,a.startTime,a.startTime+b));return c};
shaka.offline.indexeddb.V2StorageCell.prototype.convertStream_=function(a,b,c){var d=this;return{id:a.id,originalId:a.originalId,primary:a.primary,type:a.contentType,mimeType:a.mimeType,codecs:a.codecs,frameRate:a.frameRate,pixelAspectRatio:a.pixelAspectRatio,hdr:void 0,kind:a.kind,language:a.language,label:a.label,width:a.width,height:a.height,encrypted:a.encrypted,keyIds:new Set([a.keyId]),segments:a.segments.map(function(e){return d.convertSegment_(e,a.initSegmentKey,b,c,a.presentationTimeOffset)}),
variantIds:a.variantIds,roles:[],forced:!1,audioSamplingRate:null,channelsCount:null,spatialAudio:!1,closedCaptions:null,tilesLayout:void 0}};shaka.offline.indexeddb.V2StorageCell.prototype.convertSegment_=function(a,b,c,d,e){return{startTime:c+a.startTime,endTime:c+a.endTime,initSegmentKey:b,appendWindowStart:c,appendWindowEnd:d,timestampOffset:c-e,dataKey:a.dataKey,tilesLayout:""}};shaka.offline.indexeddb.V5StorageCell=function(){shaka.offline.indexeddb.BaseStorageCell.apply(this,arguments)};$jscomp.inherits(shaka.offline.indexeddb.V5StorageCell,shaka.offline.indexeddb.BaseStorageCell);shaka.offline.indexeddb.V5StorageCell.prototype.hasFixedKeySpace=function(){return!1};shaka.offline.indexeddb.V5StorageCell.prototype.addSegments=function(a){return this.add(this.segmentStore_,a)};
shaka.offline.indexeddb.V5StorageCell.prototype.addManifests=function(a){return this.add(this.manifestStore_,a)};shaka.offline.indexeddb.V5StorageCell.prototype.updateManifest=function(a,b){return this.updateManifestImplementation(a,b)};shaka.offline.indexeddb.V5StorageCell.prototype.convertManifest=function(a){null==a.expiration&&(a.expiration=Infinity);return Promise.resolve(a)};shaka.offline.indexeddb.StorageMechanism=function(){this.sessions_=this.v5_=this.v3_=this.v2_=this.v1_=this.db_=null};
shaka.offline.indexeddb.StorageMechanism.prototype.init=function(){var a=this,b=shaka.offline.indexeddb.StorageMechanism.DB_NAME,c=shaka.offline.indexeddb.StorageMechanism.VERSION,d=new shaka.util.PublicPromise,e=!1,f=new shaka.util.Timer(function(){e=!0;d.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.INDEXED_DB_INIT_TIMED_OUT))});f.tickAfter(5);var g=window.indexedDB.open(b,c);g.onsuccess=function(h){e||(h=g.result,a.db_=h,
a.v1_=shaka.offline.indexeddb.StorageMechanism.createV1_(h),a.v2_=shaka.offline.indexeddb.StorageMechanism.createV2_(h),a.v3_=shaka.offline.indexeddb.StorageMechanism.createV3_(h),a.v5_=shaka.offline.indexeddb.StorageMechanism.createV5_(h),a.sessions_=shaka.offline.indexeddb.StorageMechanism.createEmeSessionCell_(h),f.stop(),d.resolve())};g.onupgradeneeded=function(h){a.createStores_(g.result)};g.onerror=function(h){e||(d.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.INDEXED_DB_ERROR,g.error)),f.stop(),h.preventDefault())};return d};
shaka.offline.indexeddb.StorageMechanism.prototype.destroy=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){switch(b.nextAddress){case 1:if(!a.v1_){b.jumpTo(2);break}return b.yield(a.v1_.destroy(),2);case 2:if(!a.v2_){b.jumpTo(4);break}return b.yield(a.v2_.destroy(),4);case 4:if(!a.v3_){b.jumpTo(6);break}return b.yield(a.v3_.destroy(),6);case 6:if(!a.v5_){b.jumpTo(8);break}return b.yield(a.v5_.destroy(),8);case 8:if(!a.sessions_){b.jumpTo(10);break}return b.yield(a.sessions_.destroy(),
10);case 10:a.db_&&a.db_.close(),b.jumpToEnd()}})};shaka.offline.indexeddb.StorageMechanism.prototype.getCells=function(){var a=new Map;this.v1_&&a.set("v1",this.v1_);this.v2_&&a.set("v2",this.v2_);this.v3_&&a.set("v3",this.v3_);this.v5_&&a.set("v5",this.v5_);return a};shaka.offline.indexeddb.StorageMechanism.prototype.getEmeSessionCell=function(){goog.asserts.assert(this.sessions_,"Cannot be destroyed.");return this.sessions_};
shaka.offline.indexeddb.StorageMechanism.prototype.erase=function(){var a=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){switch(b.nextAddress){case 1:if(!a.v1_){b.jumpTo(2);break}return b.yield(a.v1_.destroy(),2);case 2:if(!a.v2_){b.jumpTo(4);break}return b.yield(a.v2_.destroy(),4);case 4:if(!a.v3_){b.jumpTo(6);break}return b.yield(a.v3_.destroy(),6);case 6:if(!a.v5_){b.jumpTo(8);break}return b.yield(a.v5_.destroy(),8);case 8:return a.db_&&a.db_.close(),b.yield(shaka.offline.indexeddb.StorageMechanism.deleteAll_(),
10);case 10:return a.db_=null,a.v1_=null,a.v2_=null,a.v3_=null,a.v5_=null,b.yield(a.init(),0)}})};shaka.offline.indexeddb.StorageMechanism.createV1_=function(a){var b=shaka.offline.indexeddb.StorageMechanism,c=b.V1_SEGMENT_STORE;b=b.V1_MANIFEST_STORE;var d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v1 idb storage cell"),new shaka.offline.indexeddb.V1StorageCell(a,c,b)):null};
shaka.offline.indexeddb.StorageMechanism.createV2_=function(a){var b=shaka.offline.indexeddb.StorageMechanism,c=b.V2_SEGMENT_STORE;b=b.V2_MANIFEST_STORE;var d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v2 idb storage cell"),new shaka.offline.indexeddb.V2StorageCell(a,c,b)):null};
shaka.offline.indexeddb.StorageMechanism.createV3_=function(a){var b=shaka.offline.indexeddb.StorageMechanism,c=b.V3_SEGMENT_STORE;b=b.V3_MANIFEST_STORE;var d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v3 idb storage cell"),new shaka.offline.indexeddb.V2StorageCell(a,c,b)):null};
shaka.offline.indexeddb.StorageMechanism.createV5_=function(a){var b=shaka.offline.indexeddb.StorageMechanism,c=b.V5_SEGMENT_STORE;b=b.V5_MANIFEST_STORE;var d=a.objectStoreNames;return d.contains(b)&&d.contains(c)?(shaka.log.debug("Mounting v5 idb storage cell"),new shaka.offline.indexeddb.V5StorageCell(a,c,b)):null};
shaka.offline.indexeddb.StorageMechanism.createEmeSessionCell_=function(a){var b=shaka.offline.indexeddb.StorageMechanism.SESSION_ID_STORE;return a.objectStoreNames.contains(b)?(shaka.log.debug("Mounting session ID idb storage cell"),new shaka.offline.indexeddb.EmeSessionStorageCell(a,b)):null};
shaka.offline.indexeddb.StorageMechanism.prototype.createStores_=function(a){for(var b=$jscomp.makeIterator([shaka.offline.indexeddb.StorageMechanism.V5_SEGMENT_STORE,shaka.offline.indexeddb.StorageMechanism.V5_MANIFEST_STORE,shaka.offline.indexeddb.StorageMechanism.SESSION_ID_STORE]),c=b.next();!c.done;c=b.next())c=c.value,a.objectStoreNames.contains(c)||a.createObjectStore(c,{autoIncrement:!0})};
shaka.offline.indexeddb.StorageMechanism.deleteAll_=function(){var a=shaka.offline.indexeddb.StorageMechanism.DB_NAME,b=new shaka.util.PublicPromise,c=window.indexedDB.deleteDatabase(a);c.onblocked=function(d){shaka.log.warning("Deleting",a,"is being blocked",d)};c.onsuccess=function(d){b.resolve()};c.onerror=function(d){b.reject(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.INDEXED_DB_ERROR,c.error));d.preventDefault()};return b};
shaka.offline.indexeddb.StorageMechanism.DB_NAME="shaka_offline_db";shaka.offline.indexeddb.StorageMechanism.VERSION=5;shaka.offline.indexeddb.StorageMechanism.V1_SEGMENT_STORE="segment";shaka.offline.indexeddb.StorageMechanism.V2_SEGMENT_STORE="segment-v2";shaka.offline.indexeddb.StorageMechanism.V3_SEGMENT_STORE="segment-v3";shaka.offline.indexeddb.StorageMechanism.V5_SEGMENT_STORE="segment-v5";shaka.offline.indexeddb.StorageMechanism.V1_MANIFEST_STORE="manifest";
shaka.offline.indexeddb.StorageMechanism.V2_MANIFEST_STORE="manifest-v2";shaka.offline.indexeddb.StorageMechanism.V3_MANIFEST_STORE="manifest-v3";shaka.offline.indexeddb.StorageMechanism.V5_MANIFEST_STORE="manifest-v5";shaka.offline.indexeddb.StorageMechanism.SESSION_ID_STORE="session-ids";shaka.offline.StorageMuxer.register("idb",function(){return shaka.util.Platform.isChromecast()||shaka.util.Platform.isXboxOne()||!window.indexedDB?null:new shaka.offline.indexeddb.StorageMechanism});shaka.offline.OfflineUri=function(a,b,c,d){this.type_=a;this.mechanism_=b;this.cell_=c;this.key_=d;this.asString_=["offline:",a,"/",b,"/",c,"/",d].join("")};shaka.offline.OfflineUri.prototype.isManifest=function(){return"manifest"==this.type_};shaka.offline.OfflineUri.prototype.isSegment=function(){return"segment"==this.type_};shaka.offline.OfflineUri.prototype.mechanism=function(){return this.mechanism_};shaka.offline.OfflineUri.prototype.cell=function(){return this.cell_};
shaka.offline.OfflineUri.prototype.key=function(){return this.key_};shaka.offline.OfflineUri.prototype.toString=function(){return this.asString_};shaka.offline.OfflineUri.parse=function(a){a=/^offline:([a-z]+)\/([^/]+)\/([^/]+)\/([0-9]+)$/.exec(a);if(null==a)return null;var b=a[1];if("manifest"!=b&&"segment"!=b)return null;var c=a[2];if(!c)return null;var d=a[3];return d&&null!=b?new shaka.offline.OfflineUri(b,c,d,Number(a[4])):null};
shaka.offline.OfflineUri.manifest=function(a,b,c){return new shaka.offline.OfflineUri("manifest",a,b,c)};shaka.offline.OfflineUri.segment=function(a,b,c){return new shaka.offline.OfflineUri("segment",a,b,c)};shaka.offline.ManifestConverter=function(a,b){this.mechanism_=a;this.cell_=b};
shaka.offline.ManifestConverter.prototype.fromManifestDB=function(a){var b=this,c=new shaka.media.PresentationTimeline(null,0);c.setDuration(a.duration);var d=a.streams.filter(function(l){return b.isAudio_(l)}),e=a.streams.filter(function(l){return b.isVideo_(l)});d=this.createVariants(d,e,c);e=a.streams.filter(function(l){return b.isText_(l)}).map(function(l){return b.fromStreamDB_(l,c)});var f=a.streams.filter(function(l){return b.isImage_(l)}).map(function(l){return b.fromStreamDB_(l,c)}),g=a.drmInfo?
[a.drmInfo]:[];if(a.drmInfo)for(var h=$jscomp.makeIterator(d.values()),k=h.next();!k.done;k=h.next())k=k.value,k.audio&&k.audio.encrypted&&(k.audio.drmInfos=g),k.video&&k.video.encrypted&&(k.video.drmInfos=g);return{presentationTimeline:c,minBufferTime:2,offlineSessionIds:a.sessionIds,variants:Array.from(d.values()),textStreams:e,imageStreams:f,sequenceMode:a.sequenceMode||!1}};
shaka.offline.ManifestConverter.prototype.createVariants=function(a,b,c){for(var d=new Set,e=$jscomp.makeIterator(a),f=e.next();!f.done;f=e.next()){var g=$jscomp.makeIterator(f.value.variantIds);for(f=g.next();!f.done;f=g.next())d.add(f.value)}e=$jscomp.makeIterator(b);for(f=e.next();!f.done;f=e.next())for(g=$jscomp.makeIterator(f.value.variantIds),f=g.next();!f.done;f=g.next())d.add(f.value);e=new Map;d=$jscomp.makeIterator(d);for(f=d.next();!f.done;f=d.next())f=f.value,e.set(f,this.createEmptyVariant_(f));
a=$jscomp.makeIterator(a);for(d=a.next();!d.done;d=a.next())for(d=d.value,f=this.fromStreamDB_(d,c),g=$jscomp.makeIterator(d.variantIds),d=g.next();!d.done;d=g.next())d=e.get(d.value),goog.asserts.assert(!d.audio,"A variant should only have one audio stream"),d.language=f.language,d.primary=d.primary||f.primary,d.audio=f;b=$jscomp.makeIterator(b);for(a=b.next();!a.done;a=b.next())for(d=a.value,a=this.fromStreamDB_(d,c),f=$jscomp.makeIterator(d.variantIds),d=f.next();!d.done;d=f.next())d=e.get(d.value),
goog.asserts.assert(!d.video,"A variant should only have one video stream"),d.primary=d.primary||a.primary,d.video=a;return e};
shaka.offline.ManifestConverter.prototype.fromStreamDB_=function(a,b){var c=this,d=a.segments.map(function(e,f){return c.fromSegmentDB_(f,e)});b.notifySegments(d);b=new shaka.media.SegmentIndex(d);return{id:a.id,originalId:a.originalId,createSegmentIndex:function(){return Promise.resolve()},segmentIndex:b,mimeType:a.mimeType,codecs:a.codecs,width:a.width||void 0,height:a.height||void 0,frameRate:a.frameRate,pixelAspectRatio:a.pixelAspectRatio,hdr:a.hdr,kind:a.kind,encrypted:a.encrypted,drmInfos:[],
keyIds:a.keyIds,language:a.language,label:a.label,type:a.type,primary:a.primary,trickModeVideo:null,emsgSchemeIdUris:null,roles:a.roles,forced:a.forced,channelsCount:a.channelsCount,audioSamplingRate:a.audioSamplingRate,spatialAudio:a.spatialAudio,closedCaptions:a.closedCaptions,tilesLayout:a.tilesLayout}};
shaka.offline.ManifestConverter.prototype.fromSegmentDB_=function(a,b){var c=shaka.offline.OfflineUri.segment(this.mechanism_,this.cell_,b.dataKey);a=null!=b.initSegmentKey?this.fromInitSegmentDB_(b.initSegmentKey):null;return new shaka.media.SegmentReference(b.startTime,b.endTime,function(){return[c.toString()]},0,null,a,b.timestampOffset,b.appendWindowStart,b.appendWindowEnd,[],b.tilesLayout||"")};
shaka.offline.ManifestConverter.prototype.fromInitSegmentDB_=function(a){var b=shaka.offline.OfflineUri.segment(this.mechanism_,this.cell_,a);return new shaka.media.InitSegmentReference(function(){return[b.toString()]},0,null)};shaka.offline.ManifestConverter.prototype.isAudio_=function(a){return a.type==shaka.util.ManifestParserUtils.ContentType.AUDIO};shaka.offline.ManifestConverter.prototype.isVideo_=function(a){return a.type==shaka.util.ManifestParserUtils.ContentType.VIDEO};
shaka.offline.ManifestConverter.prototype.isText_=function(a){return a.type==shaka.util.ManifestParserUtils.ContentType.TEXT};shaka.offline.ManifestConverter.prototype.isImage_=function(a){return a.type==shaka.util.ManifestParserUtils.ContentType.IMAGE};shaka.offline.ManifestConverter.prototype.createEmptyVariant_=function(a){return{id:a,language:"",disabledUntilTime:0,primary:!1,audio:null,video:null,bandwidth:0,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]}};shaka.offline.OfflineManifestParser=function(){this.uri_=null};shaka.offline.OfflineManifestParser.prototype.configure=function(a){};
shaka.offline.OfflineManifestParser.prototype.start=function(a,b){var c=this,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){switch(m.nextAddress){case 1:d=shaka.offline.OfflineUri.parse(a);c.uri_=d;if(null==d||!d.isManifest())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,a);e=new shaka.offline.StorageMuxer;m.setFinallyBlock(2);return m.yield(e.init(),4);case 4:return m.yield(e.getCell(d.mechanism(),
d.cell()),5);case 5:return f=m.yieldResult,m.yield(f.getManifests([d.key()]),6);case 6:return g=m.yieldResult,h=g[0],k=new shaka.offline.ManifestConverter(d.mechanism(),d.cell()),l=k.fromManifestDB(h),b.makeTextStreamsForClosedCaptions(l),m.return(l);case 2:return m.enterFinallyBlock(),m.yield(e.destroy(),7);case 7:m.leaveFinallyBlock(0)}})};shaka.offline.OfflineManifestParser.prototype.stop=function(){return Promise.resolve()};shaka.offline.OfflineManifestParser.prototype.update=function(){};
shaka.offline.OfflineManifestParser.prototype.onExpirationUpdated=function(a,b){var c=this,d,e,f,g,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){switch(n.nextAddress){case 1:return goog.asserts.assert(c.uri_,"Should not get update event before start has been called"),d=c.uri_,e=new shaka.offline.StorageMuxer,n.setCatchFinallyBlocks(2,3),n.yield(e.init(),5);case 5:return n.yield(e.getCell(d.mechanism(),d.cell()),6);case 6:return f=n.yieldResult,n.yield(f.getManifests([d.key()]),
7);case 7:g=n.yieldResult;h=g[0];k=h.sessionIds.includes(a);l=void 0==h.expiration||h.expiration>b;if(!k||!l){n.jumpTo(3);break}shaka.log.debug("Updating expiration for stored content");return n.yield(f.updateManifestExpiration(d.key(),b),3);case 3:return n.enterFinallyBlock(),n.yield(e.destroy(),10);case 10:n.leaveFinallyBlock(0);break;case 2:m=n.enterCatchBlock(),shaka.log.error("There was an error updating",d,m),n.jumpTo(3)}})};
shaka.media.ManifestParser.registerParserByMime("application/x-offline-manifest",function(){return new shaka.offline.OfflineManifestParser});shaka.offline.OfflineScheme=function(){};shaka.offline.OfflineScheme.plugin=function(a,b,c,d){return(b=shaka.offline.OfflineUri.parse(a))&&b.isManifest()?shaka.offline.OfflineScheme.getManifest_(a):b&&b.isSegment()?shaka.offline.OfflineScheme.getSegment_(b.key(),b):shaka.util.AbortableOperation.failed(new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.NETWORK,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,a))};
shaka.offline.OfflineScheme.getManifest_=function(a){a={uri:a,originalUri:a,data:new ArrayBuffer(0),headers:{"content-type":"application/x-offline-manifest"}};return shaka.util.AbortableOperation.completed(a)};
shaka.offline.OfflineScheme.getSegment_=function(a,b){goog.asserts.assert(b.isSegment(),"Only segment uri's should be given to getSegment");var c=new shaka.offline.StorageMuxer;return shaka.util.AbortableOperation.completed(void 0).chain(function(){return c.init()}).chain(function(){return c.getCell(b.mechanism(),b.cell())}).chain(function(d){return d.getSegments([b.key()])}).chain(function(d){return{uri:b,data:d[0].data,headers:{}}}).finally(function(){return c.destroy()})};
goog.exportSymbol("shaka.offline.OfflineScheme",shaka.offline.OfflineScheme);goog.exportProperty(shaka.offline.OfflineScheme,"plugin",shaka.offline.OfflineScheme.plugin);shaka.net.NetworkingEngine.registerScheme("offline",shaka.offline.OfflineScheme.plugin);shaka.offline.SessionDeleter=function(){};shaka.offline.SessionDeleter.prototype.delete=function(a,b,c){var d=this,e,f,g,h,k,l,m;return $jscomp.asyncExecutePromiseGeneratorProgram(function(n){switch(n.nextAddress){case 1:e=shaka.offline.SessionDeleter,f=[],g=$jscomp.makeIterator(e.createBuckets_(c)),h=g.next();case 2:if(h.done){n.jumpTo(4);break}k=h.value;l=d.doDelete_(a,b,k);return n.yield(l,5);case 5:m=n.yieldResult;f=f.concat(m);h=g.next();n.jumpTo(2);break;case 4:return n.return(f)}})};
shaka.offline.SessionDeleter.prototype.doDelete_=function(a,b,c){var d,e,f,g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){switch(h.nextAddress){case 1:return d=new shaka.media.DrmEngine({netEngine:b,onError:function(){},onKeyStatus:function(){},onExpirationUpdated:function(){},onEvent:function(){}}),h.setCatchFinallyBlocks(2),d.configure(a),h.yield(d.initForRemoval(c.info.keySystem,c.info.licenseUri,c.info.serverCertificate,c.info.audioCapabilities,c.info.videoCapabilities),4);case 4:h.leaveTryBlock(3);
break;case 2:return e=h.enterCatchBlock(),shaka.log.warning("Error initializing EME",e),h.yield(d.destroy(),5);case 5:return h.return([]);case 3:return h.setCatchFinallyBlocks(6),h.yield(d.setServerCertificate(),8);case 8:h.leaveTryBlock(7);break;case 6:return f=h.enterCatchBlock(),shaka.log.warning("Error setting server certificate",f),h.yield(d.destroy(),9);case 9:return h.return([]);case 7:return g=[],h.yield(Promise.all(c.sessionIds.map(function(k){var l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){if(1==
m.nextAddress)return m.setCatchFinallyBlocks(2),m.yield(d.removeSession(k),4);if(2!=m.nextAddress)return g.push(k),m.leaveTryBlock(0);l=m.enterCatchBlock();shaka.log.warning("Error deleting offline session",l);m.jumpToEnd()})})),10);case 10:return h.yield(d.destroy(),11);case 11:return h.return(g)}})};
shaka.offline.SessionDeleter.createBuckets_=function(a){var b=shaka.offline.SessionDeleter,c=[];a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next()){d=d.value;for(var e=!1,f=$jscomp.makeIterator(c),g=f.next();!g.done;g=f.next())if(g=g.value,b.isCompatible_(g.info,d)){g.sessionIds.push(d.sessionId);e=!0;break}e||c.push({info:d,sessionIds:[d.sessionId]})}return c};
shaka.offline.SessionDeleter.isCompatible_=function(a,b){var c=shaka.util.ArrayUtils,d=function(e,f){return e.robustness==f.robustness&&e.contentType==f.contentType};return a.keySystem==b.keySystem&&a.licenseUri==b.licenseUri&&c.hasSameElements(a.audioCapabilities,b.audioCapabilities,d)&&c.hasSameElements(a.videoCapabilities,b.videoCapabilities,d)};shaka.offline.StoredContentUtils=function(){};shaka.offline.StoredContentUtils.fromManifest=function(a,b,c,d){goog.asserts.assert(b.variants.length,"Cannot create stored content from manifest with no variants.");var e=b.presentationTimeline.getDuration();b=shaka.offline.StoredContentUtils.getTracks_(b);return{offlineUri:null,originalManifestUri:a,duration:e,size:c,expiration:Infinity,tracks:b,appMetadata:d,isIncomplete:!1}};
shaka.offline.StoredContentUtils.fromManifestDB=function(a,b){goog.asserts.assert(b.streams.length,"Cannot create stored content from manifestDB with no streams.");var c=(new shaka.offline.ManifestConverter(a.mechanism(),a.cell())).fromManifestDB(b),d=b.appMetadata||{};c=shaka.offline.StoredContentUtils.getTracks_(c);goog.asserts.assert(null!=b.expiration,"Manifest expiration must be set by now!");return{offlineUri:a.toString(),originalManifestUri:b.originalManifestUri,duration:b.duration,size:b.size,
expiration:b.expiration,tracks:c,appMetadata:d,isIncomplete:b.isIncomplete||!1}};shaka.offline.StoredContentUtils.getTracks_=function(a){var b=shaka.util.StreamUtils,c=[],d=b.getPlayableVariants(a.variants);d=$jscomp.makeIterator(d);for(var e=d.next();!e.done;e=d.next())c.push(b.variantToTrack(e.value));a=$jscomp.makeIterator(a.textStreams);for(d=a.next();!d.done;d=a.next())c.push(b.textStreamToTrack(d.value));return c};shaka.offline.StreamBandwidthEstimator=function(){this.estimateByStreamId_={}};
shaka.offline.StreamBandwidthEstimator.prototype.addVariant=function(a){var b=a.audio,c=a.video;b&&!c&&this.setBitrate_(b.id,b.bandwidth||a.bandwidth);!b&&c&&this.setBitrate_(c.id,c.bandwidth||a.bandwidth);if(b&&c){var d=b.bandwidth||shaka.offline.StreamBandwidthEstimator.DEFAULT_AUDIO_BITRATE_,e=c.bandwidth||a.bandwidth-d;0>=e&&(shaka.log.warning("Audio bit rate consumes variants bandwidth. Setting video bandwidth to match variant's bandwidth."),e=a.bandwidth);this.setBitrate_(b.id,d);this.setBitrate_(c.id,
e)}};shaka.offline.StreamBandwidthEstimator.prototype.setBitrate_=function(a,b){this.estimateByStreamId_[a]=b};shaka.offline.StreamBandwidthEstimator.prototype.addText=function(a){this.estimateByStreamId_[a.id]=shaka.offline.StreamBandwidthEstimator.DEFAULT_TEXT_BITRATE_};shaka.offline.StreamBandwidthEstimator.prototype.addImage=function(a){this.estimateByStreamId_[a.id]=a.bandwidth||shaka.offline.StreamBandwidthEstimator.DEFAULT_IMAGE_BITRATE_};
shaka.offline.StreamBandwidthEstimator.prototype.getSegmentEstimate=function(a,b){b=b.endTime-b.startTime;return this.getEstimate_(a)*b};shaka.offline.StreamBandwidthEstimator.prototype.getInitSegmentEstimate=function(a){return.5*this.getEstimate_(a)};
shaka.offline.StreamBandwidthEstimator.prototype.getEstimate_=function(a){a=this.estimateByStreamId_[a];null==a&&(a=0,shaka.log.error("Asking for bitrate of stream not given to the estimator"));0==a&&shaka.log.warning("Using bitrate of 0, this stream won't affect progress");return a};shaka.offline.StreamBandwidthEstimator.DEFAULT_AUDIO_BITRATE_=393216;shaka.offline.StreamBandwidthEstimator.DEFAULT_TEXT_BITRATE_=52;shaka.offline.StreamBandwidthEstimator.DEFAULT_IMAGE_BITRATE_=2048;shaka.offline.Storage=function(a){var b=this;if(a&&a.constructor!=shaka.Player)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.LOCAL_PLAYER_INSTANCE_REQUIRED);this.networkingEngine_=this.config_=null;a?(this.config_=a.getSharedConfiguration(),this.networkingEngine_=a.getNetworkingEngine(),goog.asserts.assert(this.networkingEngine_,"Storage should not be initialized with a player that had |destroy| called on it.")):(this.config_=
shaka.util.PlayerConfiguration.createDefault(),this.networkingEngine_=new shaka.net.NetworkingEngine);this.openOperations_=[];this.openDownloadManagers_=[];var c=!a;this.destroyer_=new shaka.util.Destroyer(function(){var d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){switch(k.nextAddress){case 1:return k.yield(Promise.all(b.openDownloadManagers_.map(function(l){return l.abortAll()})),2);case 2:d=function(){};e=[];f=$jscomp.makeIterator(b.openOperations_);for(g=f.next();!g.done;g=
f.next())h=g.value,e.push(h.then(d,d));return k.yield(Promise.all(e),3);case 3:if(!c){k.jumpTo(4);break}return k.yield(b.networkingEngine_.destroy(),4);case 4:b.config_=null,b.networkingEngine_=null,k.jumpToEnd()}})})};shaka.offline.Storage.support=function(){return shaka.util.Platform.supportsMediaSource()?shaka.offline.StorageMuxer.support():!1};shaka.offline.Storage.prototype.destroy=function(){return this.destroyer_.destroy()};
shaka.offline.Storage.prototype.configure=function(a,b){goog.asserts.assert("object"==typeof a||2==arguments.length,"String configs should have values!");2==arguments.length&&"string"==typeof a&&(a=shaka.util.ConfigUtils.convertToConfigObject(a,b));goog.asserts.assert("object"==typeof a,"Should be an object!");goog.asserts.assert(this.config_,"Cannot reconfigure storage after calling destroy.");return shaka.util.PlayerConfiguration.mergeConfigObjects(this.config_,a)};
shaka.offline.Storage.prototype.getConfiguration=function(){goog.asserts.assert(this.config_,"Config must not be null!");var a=shaka.util.PlayerConfiguration.createDefault();shaka.util.PlayerConfiguration.mergeConfigObjects(a,this.config_,shaka.util.PlayerConfiguration.createDefault());return a};shaka.offline.Storage.prototype.getNetworkingEngine=function(){return this.networkingEngine_};
shaka.offline.Storage.prototype.store=function(a,b,c){var d=this;goog.asserts.assert(this.networkingEngine_,"Cannot call |store| after calling |destroy|.");var e=this.getConfiguration(),f=new shaka.offline.DownloadManager(this.networkingEngine_);this.openDownloadManagers_.push(f);b=this.store_(a,b||{},function(){var g;return $jscomp.asyncExecutePromiseGeneratorProgram(function(h){if(1==h.nextAddress)return goog.asserts.assert(d.networkingEngine_,"Should not call |store| after |destroy|"),h.yield(shaka.media.ManifestParser.getFactory(a,
d.networkingEngine_,e.manifest.retryParameters,c||null),2);g=h.yieldResult;return h.return(g())})},e,f);b=new shaka.util.AbortableOperation(b,function(){return f.abortAll()});b.finally(function(){shaka.util.ArrayUtils.remove(d.openDownloadManagers_,f)});return this.startAbortableOperation_(b)};
shaka.offline.Storage.prototype.store_=function(a,b,c,d,e){var f=this,g,h,k,l,m,n,p,q,r,w,u,v,x,t;return $jscomp.asyncExecutePromiseGeneratorProgram(function(y){switch(y.nextAddress){case 1:return f.requireSupport_(),h=g=null,k=new shaka.offline.StorageMuxer,n=m=l=null,y.setCatchFinallyBlocks(2,3),y.yield(c(),5);case 5:return g=y.yieldResult,y.yield(f.parseManifest(a,g,d),6);case 6:p=y.yieldResult;f.ensureNotDestroyed_();q=!p.presentationTimeline.isLive()&&!p.presentationTimeline.isInProgress();if(!q)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.CANNOT_STORE_LIVE_OFFLINE,a);return y.yield(f.createDrmEngine(p,function(A){n=n||A},d),7);case 7:h=y.yieldResult;f.ensureNotDestroyed_();if(n)throw n;return y.yield(f.filterManifest_(p,h,d),8);case 8:return y.yield(k.init(),9);case 9:return f.ensureNotDestroyed_(),y.yield(k.getActive(),10);case 10:return l=y.yieldResult,f.ensureNotDestroyed_(),goog.asserts.assert(h,"drmEngine should be non-null here."),r=f.makeManifestDB_(h,p,a,b,d,e),w=r.manifestDB,
u=r.toDownload,y.yield(l.cell.addManifests([w]),11);case 11:v=y.yieldResult;f.ensureNotDestroyed_();m=v[0];goog.asserts.assert(h,"drmEngine should be non-null here.");f.ensureNotDestroyed_();if(n)throw n;return y.yield(f.downloadSegments_(u,m,w,e,d,l.cell,p,h),12);case 12:return f.ensureNotDestroyed_(),x=shaka.offline.OfflineUri.manifest(l.path.mechanism,l.path.cell,m),y.return(shaka.offline.StoredContentUtils.fromManifestDB(x,w));case 3:return y.enterFinallyBlock(),y.yield(k.destroy(),13);case 13:if(!g){y.jumpTo(14);
break}return y.yield(g.stop(),14);case 14:if(!h){y.jumpTo(16);break}return y.yield(h.destroy(),16);case 16:y.leaveFinallyBlock(0);break;case 2:t=y.enterCatchBlock();if(null==m){y.jumpTo(18);break}return y.yield(shaka.offline.Storage.cleanStoredManifest(m),18);case 18:throw n||t;}})};
shaka.offline.Storage.prototype.downloadSegments_=function(a,b,c,d,e,f,g,h){var k=this,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:l={};m=0;n=function(y,A){var z,B,D,G,C,E,F;return $jscomp.asyncExecutePromiseGeneratorProgram(function(I){if(1==I.nextAddress){z={};B=$jscomp.makeIterator(y);for(D=B.next();!D.done;z={$jscomp$loop$prop$download$589$690:z.$jscomp$loop$prop$download$589$690},D=B.next())z.$jscomp$loop$prop$download$589$690=
D.value,G=z.$jscomp$loop$prop$download$589$690.makeSegmentRequest(e),C=z.$jscomp$loop$prop$download$589$690.estimateId,E=z.$jscomp$loop$prop$download$589$690.isInitSegment,F=function(H){return function(K){var J,M,N;return $jscomp.asyncExecutePromiseGeneratorProgram(function(L){if(1==L.nextAddress)return L.yield(f.addSegments([{data:K}]),2);J=L.yieldResult;k.ensureNotDestroyed_();M=H.$jscomp$loop$prop$download$589$690.ref;N=shaka.offline.DownloadInfo.idForSegmentRef(M);l[N]=J[0];m+=K.byteLength;L.jumpToEnd()})}}(z),
d.queue(z.$jscomp$loop$prop$download$589$690.groupId,G,C,E,F);return I.yield(d.waitToFinish(),2)}if(!A)return I.jumpTo(0);k.ensureNotDestroyed_();k.setManifestDrmFields_(g,c,h,e);return I.yield(f.updateManifest(b,c),0)})};p=!1;t.setCatchFinallyBlocks(2);if(!k.getManifestIsEncrypted_(g)||!p||k.getManifestIncludesInitData_(g)){t.jumpTo(4);break}return t.yield(n(a.filter(function(y){return y.isInitSegment}),!0),5);case 5:return k.ensureNotDestroyed_(),a=a.filter(function(y){return!y.isInitSegment}),
q=l,r=m,l={},m=0,t.yield(shaka.offline.Storage.assignSegmentsToManifest(f,b,c,q,r,function(){return k.ensureNotDestroyed_()}),6);case 6:k.ensureNotDestroyed_();case 4:if(p){t.jumpTo(7);break}return t.yield(n(a,!1),8);case 8:return k.ensureNotDestroyed_(),w=l,u=m,l={},m=0,t.yield(shaka.offline.Storage.assignSegmentsToManifest(f,b,c,w,u,function(){return k.ensureNotDestroyed_()}),9);case 9:k.ensureNotDestroyed_(),goog.asserts.assert(!c.isIncomplete,"The manifest should be complete by now");case 7:t.leaveTryBlock(0);
break;case 2:return v=t.enterCatchBlock(),x=Object.values(l),t.yield(f.removeSegments(x,function(y){}),10);case 10:throw v;}})};
shaka.offline.Storage.cleanStoredManifest=function(a){var b,c,d,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return b=new shaka.offline.StorageMuxer,f.yield(b.init(),2);case 2:return f.yield(b.getActive(),3);case 3:return c=f.yieldResult,d=shaka.offline.OfflineUri.manifest(c.path.mechanism,c.path.cell,a),f.yield(b.destroy(),4);case 4:return e=new shaka.offline.Storage,f.yield(e.remove(d.toString()),0)}})};
shaka.offline.Storage.assignSegmentsToManifest=function(a,b,c,d,e,f){var g,h,k,l,m,n,p,q,r,w,u;return $jscomp.asyncExecutePromiseGeneratorProgram(function(v){switch(v.nextAddress){case 1:g=!1;v.setCatchFinallyBlocks(2);h=!0;k=$jscomp.makeIterator(c.streams);for(l=k.next();!l.done;l=k.next())for(m=l.value,n=$jscomp.makeIterator(m.segments),p=n.next();!p.done;p=n.next())q=p.value,r=q.pendingSegmentRefId?d[q.pendingSegmentRefId]:null,null!=r&&(q.dataKey=r,q.pendingSegmentRefId=void 0),r=q.pendingInitSegmentRefId?
d[q.pendingInitSegmentRefId]:null,null!=r&&(q.initSegmentKey=r,q.pendingInitSegmentRefId=void 0),q.pendingSegmentRefId&&(h=!1),q.pendingInitSegmentRefId&&(h=!1);c.size+=e;h&&(c.isIncomplete=!1);return v.yield(a.updateManifest(b,c),4);case 4:g=!0;f();v.leaveTryBlock(0);break;case 2:return w=v.enterCatchBlock(),v.yield(shaka.offline.Storage.cleanStoredManifest(b),5);case 5:if(g){v.jumpTo(6);break}u=Object.values(d);return v.yield(a.removeSegments(u,function(x){}),6);case 6:throw w;}})};
shaka.offline.Storage.prototype.filterManifest_=function(a,b,c){var d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x,t,y,A,z,B,D,G,C,E,F,I,H,K;return $jscomp.asyncExecutePromiseGeneratorProgram(function(J){switch(J.nextAddress){case 1:return d={width:Infinity,height:Infinity},shaka.util.StreamUtils.filterByRestrictions(a,c.restrictions,d),J.yield(shaka.util.StreamUtils.filterManifestByMediaCapabilities(a,c.offline.usePersistentLicense),2);case 2:e=[];f=c.preferredAudioChannelCount;g=c.preferredDecodingAttributes;
h=c.preferredVideoCodecs;k=c.preferredAudioCodecs;shaka.util.StreamUtils.chooseCodecsAndFilterManifest(a,h,k,f,g);l=$jscomp.makeIterator(a.variants);for(m=l.next();!m.done;m=l.next())n=m.value,goog.asserts.assert(shaka.util.StreamUtils.isPlayable(n),'We should have already filtered by "is playable"'),e.push(shaka.util.StreamUtils.variantToTrack(n));p=$jscomp.makeIterator(a.textStreams);for(q=p.next();!q.done;q=p.next())r=q.value,e.push(shaka.util.StreamUtils.textStreamToTrack(r));w=$jscomp.makeIterator(a.imageStreams);
for(u=w.next();!u.done;u=w.next())v=u.value,e.push(shaka.util.StreamUtils.imageStreamToTrack(v));return J.yield(c.offline.trackSelectionCallback(e),3);case 3:x=J.yieldResult;t=a.presentationTimeline.getDuration();y=0;A=$jscomp.makeIterator(x);for(z=A.next();!z.done;z=A.next())B=z.value,D=B.bandwidth*t/8,y+=D;J.setCatchFinallyBlocks(4);return J.yield(c.offline.downloadSizeCallback(y),6);case 6:G=J.yieldResult;if(!G)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,
shaka.util.Error.Code.STORAGE_LIMIT_REACHED);J.leaveTryBlock(5);break;case 4:C=J.enterCatchBlock();if(C instanceof shaka.util.Error)throw C;shaka.log.warning("downloadSizeCallback has produced an unexpected error",C);throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.DOWNLOAD_SIZE_CALLBACK_ERROR);case 5:E=new Set;F=new Set;I=new Set;H=$jscomp.makeIterator(x);for(z=H.next();!z.done;z=H.next())K=z.value,"variant"==K.type&&E.add(K.id),
"text"==K.type&&F.add(K.id),"image"==K.type&&I.add(K.id);a.variants=a.variants.filter(function(M){return E.has(M.id)});a.textStreams=a.textStreams.filter(function(M){return F.has(M.id)});a.imageStreams=a.imageStreams.filter(function(M){return I.has(M.id)});shaka.offline.Storage.validateManifest_(a);J.jumpToEnd()}})};
shaka.offline.Storage.prototype.makeManifestDB_=function(a,b,c,d,e,f){var g=shaka.offline.StoredContentUtils.fromManifest(c,b,0,d),h=e.offline.progressCallback;f.setCallbacks(function(q,r){g.size=r;h(g,q)},function(q,r){k&&e.offline.usePersistentLicense&&l==r&&a.newInitData("cenc",q)});var k=this.getManifestIsEncrypted_(b)&&!this.getManifestIncludesInitData_(b),l=null;if(k){var m=a.getDrmInfo();l=shaka.offline.Storage.defaultSystemIds_.get(m.keySystem)}m=new shaka.offline.StreamBandwidthEstimator;
for(var n=$jscomp.makeIterator(b.textStreams),p=n.next();!p.done;p=n.next())m.addText(p.value);n=$jscomp.makeIterator(b.imageStreams);for(p=n.next();!p.done;p=n.next())m.addImage(p.value);p=$jscomp.makeIterator(b.variants);for(n=p.next();!n.done;n=p.next())m.addVariant(n.value);m=this.createStreams_(f,m,a,b,e);f=m.streams;m=m.toDownload;p=a.getDrmInfo();n=e.offline.usePersistentLicense;p&&n&&(p.initData=[]);return{manifestDB:{creationTime:Date.now(),originalManifestUri:c,duration:b.presentationTimeline.getDuration(),
size:0,expiration:a.getExpiration(),streams:f,sessionIds:n?a.getSessionIds():[],drmInfo:p,appMetadata:d,isIncomplete:!0,sequenceMode:b.sequenceMode},toDownload:m}};shaka.offline.Storage.prototype.getManifestIsEncrypted_=function(a){return a.variants.some(function(b){var c=b.audio&&b.audio.encrypted;return b.video&&b.video.encrypted||c})};
shaka.offline.Storage.prototype.getManifestIncludesInitData_=function(a){return a.variants.some(function(b){return(b.video?b.video.drmInfos:[]).concat(b.audio?b.audio.drmInfos:[]).some(function(c){return c.initData&&c.initData.length})})};
shaka.offline.Storage.prototype.setManifestDrmFields_=function(a,b,c,d){b.expiration=c.getExpiration();c=c.getSessionIds();b.sessionIds=d.offline.usePersistentLicense?c:[];if(this.getManifestIsEncrypted_(a)&&d.offline.usePersistentLicense&&!c.length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.NO_INIT_DATA_FOR_OFFLINE);};shaka.offline.Storage.prototype.remove=function(a){return this.startOperation_(this.remove_(a))};
shaka.offline.Storage.prototype.remove_=function(a){var b=this,c,d,e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){switch(k.nextAddress){case 1:b.requireSupport_();c=shaka.offline.OfflineUri.parse(a);if(null==c||!c.isManifest())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.MALFORMED_OFFLINE_URI,a);d=c;e=new shaka.offline.StorageMuxer;k.setFinallyBlock(2);return k.yield(e.init(),4);case 4:return k.yield(e.getCell(d.mechanism(),
d.cell()),5);case 5:return f=k.yieldResult,k.yield(f.getManifests([d.key()]),6);case 6:return g=k.yieldResult,h=g[0],k.yield(Promise.all([b.removeFromDRM_(d,h,e),b.removeFromStorage_(f,d,h)]),2);case 2:return k.enterFinallyBlock(),k.yield(e.destroy(),8);case 8:k.leaveFinallyBlock(0)}})};
shaka.offline.Storage.getCapabilities_=function(a,b){for(var c=shaka.util.MimeUtils,d=[],e=$jscomp.makeIterator(a.streams),f=e.next();!f.done;f=e.next())f=f.value,b&&"video"==f.type?d.push({contentType:c.getFullType(f.mimeType,f.codecs),robustness:a.drmInfo.videoRobustness}):b||"audio"!=f.type||d.push({contentType:c.getFullType(f.mimeType,f.codecs),robustness:a.drmInfo.audioRobustness});return d};
shaka.offline.Storage.prototype.removeFromDRM_=function(a,b,c){var d=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){goog.asserts.assert(d.networkingEngine_,"Cannot be destroyed");return e.yield(shaka.offline.Storage.deleteLicenseFor_(d.networkingEngine_,d.config_.drm,c,b),0)})};
shaka.offline.Storage.prototype.removeFromStorage_=function(a,b,c){var d=this,e=shaka.offline.Storage.getAllSegmentIds_(c),f=e.length+1,g=0,h=shaka.offline.StoredContentUtils.fromManifestDB(b,c);c=function(k){g+=1;d.config_.offline.progressCallback(h,g/f)};return Promise.all([a.removeSegments(e,c),a.removeManifests([b.key()],c)])};shaka.offline.Storage.prototype.removeEmeSessions=function(){return this.startOperation_(this.removeEmeSessions_())};
shaka.offline.Storage.prototype.removeEmeSessions_=function(){var a=this,b,c,d,e,f,g,h,k,l,m,n;return $jscomp.asyncExecutePromiseGeneratorProgram(function(p){switch(p.nextAddress){case 1:return a.requireSupport_(),goog.asserts.assert(a.networkingEngine_,"Cannot be destroyed"),b=a.networkingEngine_,c=a.config_.drm,d=new shaka.offline.StorageMuxer,e=new shaka.offline.SessionDeleter,f=!1,p.setFinallyBlock(2),p.yield(d.init(),4);case 4:g=[],d.forEachEmeSessionCell(function(q){return g.push(q)}),h=$jscomp.makeIterator(g),
k=h.next();case 5:if(k.done){p.jumpTo(2);break}l=k.value;return p.yield(l.getAll(),8);case 8:return m=p.yieldResult,p.yield(e.delete(c,b,m),9);case 9:return n=p.yieldResult,p.yield(l.remove(n),10);case 10:n.length!=m.length&&(f=!0);k=h.next();p.jumpTo(5);break;case 2:return p.enterFinallyBlock(),p.yield(d.destroy(),11);case 11:p.leaveFinallyBlock(3);break;case 3:return p.return(!f)}})};shaka.offline.Storage.prototype.list=function(){return this.startOperation_(this.list_())};
shaka.offline.Storage.prototype.list_=function(){var a=this,b,c,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){switch(e.nextAddress){case 1:return a.requireSupport_(),b=[],c=new shaka.offline.StorageMuxer,e.setFinallyBlock(2),e.yield(c.init(),4);case 4:return d=Promise.resolve(),c.forEachCell(function(f,g){d=d.then(function(){var h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress)return k.yield(g.getAllManifests(),2);h=k.yieldResult;h.forEach(function(l,
m){m=shaka.offline.OfflineUri.manifest(f.mechanism,f.cell,m);l=shaka.offline.StoredContentUtils.fromManifestDB(m,l);b.push(l)});k.jumpToEnd()})})}),e.yield(d,2);case 2:return e.enterFinallyBlock(),e.yield(c.destroy(),6);case 6:e.leaveFinallyBlock(3);break;case 3:return e.return(b)}})};
shaka.offline.Storage.prototype.parseManifest=function(a,b,c){var d=this,e,f,g,h,k;return $jscomp.asyncExecutePromiseGeneratorProgram(function(l){if(1==l.nextAddress)return e=null,f=d.networkingEngine_,goog.asserts.assert(f,"Should be initialized!"),g={networkingEngine:f,modifyManifestRequest:function(m,n){},modifySegmentRequest:function(m,n){},filter:function(){return Promise.resolve()},makeTextStreamsForClosedCaptions:function(m){},onTimelineRegionAdded:function(){},onEvent:function(){},onError:function(m){e=
m},isLowLatencyMode:function(){return!1},isAutoLowLatencyMode:function(){return!1},enableLowLatencyMode:function(){},updateDuration:function(){},newDrmInfo:function(m){}},b.configure(c.manifest),d.ensureNotDestroyed_(),l.yield(b.start(a,g),2);if(3!=l.nextAddress)return h=l.yieldResult,d.ensureNotDestroyed_(),k=shaka.offline.Storage.getAllStreamsFromManifest_(h),l.yield(Promise.all(shaka.util.Iterables.map(k,function(m){return m.createSegmentIndex()})),3);d.ensureNotDestroyed_();if(e)throw e;return l.return(h)})};
shaka.offline.Storage.prototype.createDrmEngine=function(a,b,c){var d=this,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return goog.asserts.assert(d.networkingEngine_,"Cannot call |createDrmEngine| after |destroy|"),e=new shaka.media.DrmEngine({netEngine:d.networkingEngine_,onError:b,onKeyStatus:function(){},onExpirationUpdated:function(){},onEvent:function(){}}),e.configure(c.drm),f.yield(e.initForStorage(a.variants,c.offline.usePersistentLicense),
2);case 2:return f.yield(e.setServerCertificate(),3);case 3:return f.yield(e.createOrLoad(),4);case 4:return f.return(e)}})};
shaka.offline.Storage.prototype.createStreams_=function(a,b,c,d,e){c=new Map;var f=shaka.offline.Storage.getAllStreamsFromManifest_(d),g=new Map;f=$jscomp.makeIterator(f);for(var h=f.next();!h.done;h=f.next()){h=h.value;var k=this.createStream_(a,b,d,h,e,c);g.set(h.id,k)}a=$jscomp.makeIterator(d.variants);for(b=a.next();!b.done;b=a.next())b=b.value,b.audio&&g.get(b.audio.id).variantIds.push(b.id),b.video&&g.get(b.video.id).variantIds.push(b.id);return{streams:Array.from(g.values()),toDownload:Array.from(c.values())}};
shaka.offline.Storage.prototype.createStream_=function(a,b,c,d,e,f){var g={id:d.id,originalId:d.originalId,primary:d.primary,type:d.type,mimeType:d.mimeType,codecs:d.codecs,frameRate:d.frameRate,pixelAspectRatio:d.pixelAspectRatio,hdr:d.hdr,kind:d.kind,language:d.language,label:d.label,width:d.width||null,height:d.height||null,encrypted:d.encrypted,keyIds:d.keyIds,segments:[],variantIds:[],roles:d.roles,forced:d.forced,channelsCount:d.channelsCount,audioSamplingRate:d.audioSamplingRate,spatialAudio:d.spatialAudio,
closedCaptions:d.closedCaptions,tilesLayout:d.tilesLayout};c=c.presentationTimeline.getSegmentAvailabilityStart();var h=e.offline.numberOfParallelDownloads,k=0;shaka.offline.Storage.forEachSegment_(d,c,function(l){var m=shaka.offline.DownloadInfo.idForSegmentRef(l),n=void 0;if(!f.has(m)){var p=a.addDownloadEstimate(b.getSegmentEstimate(d.id,l));p=new shaka.offline.DownloadInfo(l,p,k,!1);f.set(m,p)}l.initSegmentReference&&(n=shaka.offline.DownloadInfo.idForSegmentRef(l.initSegmentReference),f.has(n)||
(p=a.addDownloadEstimate(b.getInitSegmentEstimate(d.id)),p=new shaka.offline.DownloadInfo(l.initSegmentReference,p,k,!0),f.set(n,p)));g.segments.push({pendingInitSegmentRefId:n,initSegmentKey:n?0:null,startTime:l.startTime,endTime:l.endTime,appendWindowStart:l.appendWindowStart,appendWindowEnd:l.appendWindowEnd,timestampOffset:l.timestampOffset,tilesLayout:l.tilesLayout,pendingSegmentRefId:m,dataKey:0});k=(k+1)%h});return g};
shaka.offline.Storage.forEachSegment_=function(a,b,c){b=a.segmentIndex.find(b);if(null!=b)for(var d=a.segmentIndex.get(b);d;)c(d),d=a.segmentIndex.get(++b)};shaka.offline.Storage.prototype.ensureNotDestroyed_=function(){if(this.destroyer_.destroyed())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.OPERATION_ABORTED);};
shaka.offline.Storage.prototype.requireSupport_=function(){if(!shaka.offline.Storage.support())throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.STORAGE,shaka.util.Error.Code.STORAGE_NOT_SUPPORTED);};
shaka.offline.Storage.prototype.startOperation_=function(a){var b=this;return $jscomp.asyncExecutePromiseGeneratorProgram(function(c){if(1==c.nextAddress)return b.openOperations_.push(a),c.setFinallyBlock(2),c.yield(a,4);if(2!=c.nextAddress)return c.return(c.yieldResult);c.enterFinallyBlock();shaka.util.ArrayUtils.remove(b.openOperations_,a);return c.leaveFinallyBlock(0)})};
shaka.offline.Storage.prototype.startAbortableOperation_=function(a){var b=this,c=a.promise;this.openOperations_.push(c);return a.finally(function(){shaka.util.ArrayUtils.remove(b.openOperations_,c)})};shaka.offline.Storage.getAllSegmentIds_=function(a){var b=new Set;a=$jscomp.makeIterator(a.streams);for(var c=a.next();!c.done;c=a.next()){c=$jscomp.makeIterator(c.value.segments);for(var d=c.next();!d.done;d=c.next())d=d.value,null!=d.initSegmentKey&&b.add(d.initSegmentKey),b.add(d.dataKey)}return Array.from(b)};
shaka.offline.Storage.deleteAll=function(){var a;return $jscomp.asyncExecutePromiseGeneratorProgram(function(b){return 1==b.nextAddress?(a=new shaka.offline.StorageMuxer,b.setFinallyBlock(2),b.yield(a.erase(),2)):5!=b.nextAddress?(b.enterFinallyBlock(),b.yield(a.destroy(),5)):b.leaveFinallyBlock(0)})};
shaka.offline.Storage.deleteLicenseFor_=function(a,b,c,d){var e,f,g,h;return $jscomp.asyncExecutePromiseGeneratorProgram(function(k){if(1==k.nextAddress){if(!d.drmInfo)return k.return();e=c.getEmeSessionCell();f=d.sessionIds.map(function(l){return{sessionId:l,keySystem:d.drmInfo.keySystem,licenseUri:d.drmInfo.licenseServerUri,serverCertificate:d.drmInfo.serverCertificate,audioCapabilities:shaka.offline.Storage.getCapabilities_(d,!1),videoCapabilities:shaka.offline.Storage.getCapabilities_(d,!0)}});
g=new shaka.offline.SessionDeleter;return k.yield(g.delete(b,a,f),2)}return 3!=k.nextAddress?(h=k.yieldResult,k.yield(e.remove(h),3)):k.yield(e.add(f.filter(function(l){return!h.includes(l.sessionId)})),0)})};
shaka.offline.Storage.getAllStreamsFromManifest_=function(a){for(var b=new Set,c=$jscomp.makeIterator(a.textStreams),d=c.next();!d.done;d=c.next())b.add(d.value);c=$jscomp.makeIterator(a.imageStreams);for(d=c.next();!d.done;d=c.next())b.add(d.value);a=$jscomp.makeIterator(a.variants);for(c=a.next();!c.done;c=a.next())c=c.value,c.audio&&b.add(c.audio),c.video&&b.add(c.video);return b};
shaka.offline.Storage.validateManifest_=function(a){var b=new Set(a.variants.map(function(g){return g.video})),c=new Set(a.variants.map(function(g){return g.audio}));a=a.textStreams;1<b.size&&shaka.log.warning("Multiple video tracks selected to be stored");b=$jscomp.makeIterator(c);for(var d=b.next();!d.done;d=b.next()){d=d.value;for(var e=$jscomp.makeIterator(c),f=e.next();!f.done;f=e.next())f=f.value,d!=f&&d.language==f.language&&shaka.log.warning("Similar audio tracks were selected to be stored",
d.id,f.id)}c=$jscomp.makeIterator(a);for(b=c.next();!b.done;b=c.next())for(b=b.value,d=$jscomp.makeIterator(a),e=d.next();!e.done;e=d.next())e=e.value,b!=e&&b.language==e.language&&shaka.log.warning("Similar text tracks were selected to be stored",b.id,e.id)};goog.exportSymbol("shaka.offline.Storage",shaka.offline.Storage);goog.exportProperty(shaka.offline.Storage,"deleteAll",shaka.offline.Storage.deleteAll);goog.exportProperty(shaka.offline.Storage.prototype,"list",shaka.offline.Storage.prototype.list);
goog.exportProperty(shaka.offline.Storage.prototype,"removeEmeSessions",shaka.offline.Storage.prototype.removeEmeSessions);goog.exportProperty(shaka.offline.Storage.prototype,"remove",shaka.offline.Storage.prototype.remove);goog.exportProperty(shaka.offline.Storage.prototype,"store",shaka.offline.Storage.prototype.store);goog.exportProperty(shaka.offline.Storage.prototype,"getNetworkingEngine",shaka.offline.Storage.prototype.getNetworkingEngine);
goog.exportProperty(shaka.offline.Storage.prototype,"getConfiguration",shaka.offline.Storage.prototype.getConfiguration);goog.exportProperty(shaka.offline.Storage.prototype,"configure",shaka.offline.Storage.prototype.configure);goog.exportProperty(shaka.offline.Storage.prototype,"destroy",shaka.offline.Storage.prototype.destroy);goog.exportProperty(shaka.offline.Storage,"support",shaka.offline.Storage.support);
shaka.offline.Storage.defaultSystemIds_=(new Map).set("org.w3.clearkey","1077efecc0b24d02ace33c1e52e2fb4b").set("com.widevine.alpha","edef8ba979d64acea3c827dcd51d21ed").set("com.microsoft.playready","9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.recommendation","9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.software","9a04f07998404286ab92e65be0885f95").set("com.microsoft.playready.hardware","9a04f07998404286ab92e65be0885f95").set("com.adobe.primetime","f239e769efa348509c16a903c6932efb");
shaka.Player.registerSupportPlugin("offline",shaka.offline.Storage.support);shaka.polyfill=function(){};shaka.polyfill.installAll=function(){for(var a=$jscomp.makeIterator(shaka.polyfill.polyfills_),b=a.next();!b.done;b=a.next()){b=b.value;try{b.callback()}catch(c){shaka.log.alwaysWarn("Error installing polyfill!",c)}}};shaka.polyfill.register=function(a,b){a={priority:b||0,callback:a};for(b=0;b<shaka.polyfill.polyfills_.length;b++)if(shaka.polyfill.polyfills_[b].priority<a.priority){shaka.polyfill.polyfills_.splice(b,0,a);return}shaka.polyfill.polyfills_.push(a)};
goog.exportSymbol("shaka.polyfill",shaka.polyfill);goog.exportProperty(shaka.polyfill,"register",shaka.polyfill.register);goog.exportProperty(shaka.polyfill,"installAll",shaka.polyfill.installAll);shaka.polyfill.polyfills_=[];shaka.polyfill.AbortController=function(){this.signal_=new shaka.polyfill.AbortController.AbortSignal};shaka.polyfill.AbortController.install=function(){window.AbortController||(window.AbortController=shaka.polyfill.AbortController,window.AbortSignal=shaka.polyfill.AbortController.AbortSignal)};shaka.polyfill.AbortController.prototype.abort=function(a){this.signal_.doAbort_(a)};$jscomp.global.Object.defineProperties(shaka.polyfill.AbortController.prototype,{signal:{configurable:!0,enumerable:!0,get:function(){return this.signal_}}});
goog.exportProperty(shaka.polyfill,"AbortController",shaka.polyfill.AbortController);goog.exportProperty(shaka.polyfill.AbortController,"install",shaka.polyfill.AbortController.install);shaka.polyfill.AbortController.AbortSignal=function(){shaka.util.FakeEventTarget.call(this);this.aborted_=!1;this.reason_=void 0;this.onabort=null};$jscomp.inherits(shaka.polyfill.AbortController.AbortSignal,shaka.util.FakeEventTarget);
shaka.polyfill.AbortController.AbortSignal.prototype.doAbort_=function(a){if(!this.aborted_){this.aborted_=!0;this.reason_=a;void 0===this.reason_&&(this.reason_=new DOMException("signal is aborted without reason","AbortError"));a=new shaka.util.FakeEvent("abort");if(this.onabort)this.onabort(a);this.dispatchEvent(a)}};shaka.polyfill.AbortController.AbortSignal.abort=function(a){var b=new shaka.polyfill.AbortController.AbortSignal;b.doAbort_(a);return b};
shaka.polyfill.AbortController.AbortSignal.timeout=function(a){var b=new shaka.polyfill.AbortController.AbortSignal;window.setTimeout(function(){b.doAbort_(new DOMException("signal timed out","TimeoutError"))},a);return b};$jscomp.global.Object.defineProperties(shaka.polyfill.AbortController.AbortSignal.prototype,{aborted:{configurable:!0,enumerable:!0,get:function(){return this.aborted_}},reason:{configurable:!0,enumerable:!0,get:function(){return this.reason_}}});shaka.polyfill.register(shaka.polyfill.AbortController.install);shaka.polyfill.Aria=function(){};shaka.polyfill.Aria.install=function(){if(Object.getOwnPropertyDescriptor(Element.prototype,"ariaHidden"))shaka.log.info("Using native ARIAMixin interface.");else{shaka.log.info("ARIAMixin interface not detected. Installing polyfill.");for(var a=$jscomp.makeIterator(["ariaHidden","ariaLabel","ariaPressed","ariaSelected"]),b=a.next();!b.done;b=a.next())shaka.polyfill.Aria.addARIAMixinAttribute_(b.value)}};
shaka.polyfill.Aria.addARIAMixinAttribute_=function(a){var b="aria-"+a.toLowerCase().replace(/^aria/,"");Object.defineProperty(Element.prototype,a,{get:function(){return this.getAttribute(b)},set:function(c){null==c||void 0==c?this.removeAttribute(b):this.setAttribute(b,c)}})};goog.exportProperty(shaka.polyfill,"Aria",shaka.polyfill.Aria);goog.exportProperty(shaka.polyfill.Aria,"install",shaka.polyfill.Aria.install);shaka.polyfill.register(shaka.polyfill.Aria.install);shaka.polyfill.EncryptionScheme=function(){};shaka.polyfill.EncryptionScheme.install=function(){EncryptionSchemePolyfills.install()};goog.exportProperty(shaka.polyfill,"EncryptionScheme",shaka.polyfill.EncryptionScheme);goog.exportProperty(shaka.polyfill.EncryptionScheme,"install",shaka.polyfill.EncryptionScheme.install);shaka.polyfill.register(shaka.polyfill.EncryptionScheme.install,-2);shaka.polyfill.Fullscreen=function(){};
shaka.polyfill.Fullscreen.install=function(){if(window.Document){var a=Element.prototype;a.requestFullscreen=a.requestFullscreen||a.mozRequestFullScreen||a.msRequestFullscreen||a.webkitRequestFullscreen;a=Document.prototype;a.exitFullscreen=a.exitFullscreen||a.mozCancelFullScreen||a.msExitFullscreen||a.webkitCancelFullScreen;"fullscreenElement"in document||(Object.defineProperty(document,"fullscreenElement",{get:function(){return document.mozFullScreenElement||document.msFullscreenElement||document.webkitCurrentFullScreenElement||
document.webkitFullscreenElement}}),Object.defineProperty(document,"fullscreenEnabled",{get:function(){return document.mozFullScreenEnabled||document.msFullscreenEnabled||document.webkitFullscreenEnabled}}));a=shaka.polyfill.Fullscreen.proxyEvent_;document.addEventListener("webkitfullscreenchange",a);document.addEventListener("webkitfullscreenerror",a);document.addEventListener("mozfullscreenchange",a);document.addEventListener("mozfullscreenerror",a);document.addEventListener("MSFullscreenChange",
a);document.addEventListener("MSFullscreenError",a)}};shaka.polyfill.Fullscreen.proxyEvent_=function(a){var b=a.type.replace(/^(webkit|moz|MS)/,"").toLowerCase(),c=document.createEvent("Event");c.initEvent(b,a.bubbles,a.cancelable);a.target.dispatchEvent(c)};goog.exportProperty(shaka.polyfill,"Fullscreen",shaka.polyfill.Fullscreen);goog.exportProperty(shaka.polyfill.Fullscreen,"install",shaka.polyfill.Fullscreen.install);shaka.polyfill.register(shaka.polyfill.Fullscreen.install);shaka.polyfill.MediaCapabilities=function(){};
shaka.polyfill.MediaCapabilities.install=function(){var a=!0;if(shaka.util.Platform.isApple()||shaka.util.Platform.isPS5()||shaka.util.Platform.isPS4()||shaka.util.Platform.isWebOS()||shaka.util.Platform.isTizen()||shaka.util.Platform.isChromecast()||shaka.util.Platform.isEOS()||shaka.util.Platform.isHisense())a=!1;a&&navigator.mediaCapabilities?shaka.log.info("MediaCapabilities: Native mediaCapabilities support found."):(shaka.log.info("MediaCapabilities: install"),navigator.mediaCapabilities||(navigator.mediaCapabilities=
{}),shaka.polyfill.MediaCapabilities.originalMcap=navigator.mediaCapabilities,navigator.mediaCapabilities.decodingInfo=shaka.polyfill.MediaCapabilities.decodingInfo_)};
shaka.polyfill.MediaCapabilities.decodingInfo_=function(a){var b,c,d,e,f,g,h,k,l,m,n,p,q,r,w,u,v,x;return $jscomp.asyncExecutePromiseGeneratorProgram(function(t){switch(t.nextAddress){case 1:b={supported:!1,powerEfficient:!0,smooth:!0,keySystemAccess:null,configuration:a};if(!a)return t.return(b);c=a.video;d=a.audio;e=shaka.media.Capabilities;if("media-source"==a.type){if(!shaka.util.Platform.supportsMediaSource()||c&&(f=shaka.util.Platform.isChromecast()?shaka.polyfill.MediaCapabilities.canCastDisplayType_(c):
e.isTypeSupported(c.contentType),!f)||d&&(g=d.contentType,h=e.isTypeSupported(g),!h))return t.return(b)}else if("file"==a.type){if(c&&(k=c.contentType,l=shaka.util.Platform.supportsMediaType(k),!l)||d&&(m=d.contentType,n=shaka.util.Platform.supportsMediaType(m),!n))return t.return(b)}else return t.return(b);if(!a.keySystemConfiguration)return b.supported=!0,t.return(Promise.resolve(b));p=a.keySystemConfiguration;q=[];r=[];p.audio&&(w={robustness:p.audio.robustness||"",contentType:a.audio.contentType},
q.push(w));p.video&&(u={robustness:p.video.robustness||"",contentType:a.video.contentType},r.push(u));v={initDataTypes:[p.initDataType],distinctiveIdentifier:p.distinctiveIdentifier,persistentState:p.persistentState,sessionTypes:p.sessionTypes};q.length&&(v.audioCapabilities=q);r.length&&(v.videoCapabilities=r);t.setCatchFinallyBlocks(3);return t.yield(navigator.requestMediaKeySystemAccess(p.keySystem,[v]),5);case 5:x=t.yieldResult;t.leaveTryBlock(4);break;case 3:t.enterCatchBlock(),shaka.log.info("navigator.requestMediaKeySystemAccess failed.");
case 4:x&&(b.supported=!0,b.keySystemAccess=x);case 2:return t.return(b)}})};
shaka.polyfill.MediaCapabilities.canCastDisplayType_=function(a){if(!(window.cast&&cast.__platform__&&cast.__platform__.canDisplayType))return shaka.log.warning("Expected cast APIs to be available! Falling back to shaka.media.Capabilities.isTypeSupported() for type support."),shaka.media.Capabilities.isTypeSupported(a.contentType);var b=a.contentType;a.width&&a.height&&(b+="; width="+a.width+"; height="+a.height);a.framerate&&(b+="; framerate="+a.framerate);"pq"===a.transferFunction&&(b+="; eotf=smpte2084");
return cast.__platform__.canDisplayType(b)};goog.exportProperty(shaka.polyfill,"MediaCapabilities",shaka.polyfill.MediaCapabilities);goog.exportProperty(shaka.polyfill.MediaCapabilities,"install",shaka.polyfill.MediaCapabilities.install);shaka.polyfill.MediaCapabilities.originalMcap=null;goog.exportProperty(shaka.polyfill.MediaCapabilities,"originalMcap",shaka.polyfill.MediaCapabilities.originalMcap);shaka.polyfill.register(shaka.polyfill.MediaCapabilities.install,-1);shaka.polyfill.MediaSource=function(){};
shaka.polyfill.MediaSource.install=function(){shaka.log.debug("MediaSource.install");var a=shaka.util.Platform.safariVersion();window.MediaSource?window.cast&&cast.__platform__&&cast.__platform__.canDisplayType?(shaka.log.info("Patching Chromecast MSE bugs."),shaka.polyfill.MediaSource.patchCastIsTypeSupported_()):a?12>=a?(shaka.log.info("Patching Safari 11 & 12 MSE bugs."),shaka.polyfill.MediaSource.stubAbort_(),shaka.polyfill.MediaSource.patchRemovalRange_()):15>=a&&(shaka.log.info("Patching Safari 13 & 14 & 15 MSE bugs."),
shaka.polyfill.MediaSource.stubAbort_()):shaka.util.Platform.isEdge()?(shaka.log.info("Rejecting TS container."),shaka.polyfill.MediaSource.rejectContainer_("mp2t")):shaka.util.Platform.isTizen2()||shaka.util.Platform.isTizen3()||shaka.util.Platform.isTizen4()?(shaka.log.info("Rejecting Opus."),shaka.polyfill.MediaSource.rejectCodec_("opus")):shaka.log.info("Using native MSE as-is."):shaka.log.info("No MSE implementation available.");window.MediaSource&&MediaSource.isTypeSupported('video/webm; codecs="vp9"')&&
!MediaSource.isTypeSupported('video/webm; codecs="vp09.00.10.08"')&&(shaka.log.info("Patching vp09 support queries."),shaka.polyfill.MediaSource.patchVp09_())};shaka.polyfill.MediaSource.stubAbort_=function(){var a=MediaSource.prototype.addSourceBuffer;MediaSource.prototype.addSourceBuffer=function(){var b=$jscomp.getRestArguments.apply(0,arguments);b=a.apply(this,b);b.abort=function(){};return b}};
shaka.polyfill.MediaSource.patchRemovalRange_=function(){var a=SourceBuffer.prototype.remove;SourceBuffer.prototype.remove=function(b,c){return a.call(this,b,c-.001)}};shaka.polyfill.MediaSource.rejectContainer_=function(a){var b=MediaSource.isTypeSupported;MediaSource.isTypeSupported=function(c){return shaka.util.MimeUtils.getContainerType(c)!=a&&b(c)}};
shaka.polyfill.MediaSource.rejectCodec_=function(a){var b=MediaSource.isTypeSupported;MediaSource.isTypeSupported=function(c){return shaka.util.MimeUtils.getCodecBase(c)!=a&&b(c)}};shaka.polyfill.MediaSource.patchCastIsTypeSupported_=function(){var a=MediaSource.isTypeSupported;MediaSource.isTypeSupported=function(b){var c=b.split(/ *; */);c.shift();return c.some(function(d){return d.startsWith("codecs=")})?cast.__platform__.canDisplayType(b):a(b)}};
shaka.polyfill.MediaSource.patchVp09_=function(){var a=MediaSource.isTypeSupported;shaka.util.Platform.isWebOS()||(MediaSource.isTypeSupported=function(b){var c=b.split(/ *; */),d=c.findIndex(function(g){return g.startsWith("codecs=")});if(0>d)return a(b);var e=c[d].replace("codecs=","").replace(/"/g,"").split(/\s*,\s*/),f=e.findIndex(function(g){return g.startsWith("vp09")});0<=f&&(e[f]="vp9",c[d]='codecs="'+e.join(",")+'"',b=c.join("; "));return a(b)})};
goog.exportProperty(shaka.polyfill,"MediaSource",shaka.polyfill.MediaSource);goog.exportProperty(shaka.polyfill.MediaSource,"install",shaka.polyfill.MediaSource.install);shaka.polyfill.register(shaka.polyfill.MediaSource.install);shaka.polyfill.Orientation=function(){};shaka.polyfill.Orientation.install=function(){screen.orientation||void 0!=window.orientation&&shaka.polyfill.Orientation.installBasedOnWindowMethods_()};
shaka.polyfill.Orientation.installBasedOnWindowMethods_=function(){var a=new shaka.polyfill.Orientation.FakeOrientation;screen.orientation=a;var b=function(){switch(window.orientation){case -90:a.type="landscape-secondary";a.angle=270;break;case 0:a.type="portrait-primary";a.angle=0;break;case 90:a.type="landscape-primary";a.angle=90;break;case 180:a.type="portrait-secondary",a.angle=180}};b();window.addEventListener("orientationchange",function(){b();a.dispatchChangeEvent()})};
goog.exportProperty(shaka.polyfill,"Orientation",shaka.polyfill.Orientation);goog.exportProperty(shaka.polyfill.Orientation,"install",shaka.polyfill.Orientation.install);shaka.polyfill.Orientation.FakeOrientation=function(){shaka.util.FakeEventTarget.call(this);this.type="";this.angle=0};$jscomp.inherits(shaka.polyfill.Orientation.FakeOrientation,shaka.util.FakeEventTarget);
shaka.polyfill.Orientation.FakeOrientation.prototype.dispatchChangeEvent=function(){var a=new shaka.util.FakeEvent("change");this.dispatchEvent(a)};
shaka.polyfill.Orientation.FakeOrientation.prototype.lock=function(a){var b=function(d){return screen.lockOrientation?screen.lockOrientation(d):screen.mozLockOrientation?screen.mozLockOrientation(d):screen.msLockOrientation?screen.msLockOrientation(d):!1},c=!1;switch(a){case "natural":c=b("default");break;case "any":c=!0;this.unlock();break;default:c=b(a)}if(c)return Promise.resolve();a=Error("screen.orientation.lock() is not available on this device");a.name="NotSupportedError";a.code=DOMException.NOT_SUPPORTED_ERR;
return Promise.reject(a)};shaka.polyfill.Orientation.FakeOrientation.prototype.unlock=function(){screen.unlockOrientation?screen.unlockOrientation():screen.mozUnlockOrientation?screen.mozUnlockOrientation():screen.msUnlockOrientation&&screen.msUnlockOrientation()};shaka.polyfill.register(shaka.polyfill.Orientation.install);shaka.polyfill.PatchedMediaKeysApple=function(){};
shaka.polyfill.PatchedMediaKeysApple.install=function(a){var b=shaka.polyfill.PatchedMediaKeysApple;if(window.HTMLVideoElement&&window.WebKitMediaKeys){if(void 0===a?0:a)b.enableUninstall=!0,b.originalHTMLMediaElementPrototypeMediaKeys=Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype,"mediaKeys"),b.originalHTMLMediaElementPrototypeSetMediaKeys=HTMLMediaElement.prototype.setMediaKeys,b.originalWindowMediaKeys=window.MediaKeys,b.originalWindowMediaKeySystemAccess=window.MediaKeySystemAccess,
b.originalNavigatorRequestMediaKeySystemAccess=navigator.requestMediaKeySystemAccess;shaka.log.info("Using Apple-prefixed EME");delete HTMLMediaElement.prototype.mediaKeys;HTMLMediaElement.prototype.mediaKeys=null;HTMLMediaElement.prototype.setMediaKeys=b.setMediaKeys;window.MediaKeys=b.MediaKeys;window.MediaKeySystemAccess=b.MediaKeySystemAccess;navigator.requestMediaKeySystemAccess=b.requestMediaKeySystemAccess;window.shakaMediaKeysPolyfill=!0}};
shaka.polyfill.PatchedMediaKeysApple.uninstall=function(){var a=shaka.polyfill.PatchedMediaKeysApple;a.enableUninstall&&(shaka.log.info("Un-installing Apple-prefixed EME"),a.enableUninstall=!1,Object.defineProperty(HTMLMediaElement.prototype,"mediaKeys",a.originalHTMLMediaElementPrototypeMediaKeys),HTMLMediaElement.prototype.setMediaKeys=a.originalHTMLMediaElementPrototypeSetMediaKeys,window.MediaKeys=a.originalWindowMediaKeys,window.MediaKeySystemAccess=a.originalWindowMediaKeySystemAccess,navigator.requestMediaKeySystemAccess=
a.originalNavigatorRequestMediaKeySystemAccess,a.originalWindowMediaKeys=null,a.originalWindowMediaKeySystemAccess=null,a.originalHTMLMediaElementPrototypeSetMediaKeys=null,a.originalNavigatorRequestMediaKeySystemAccess=null,a.originalHTMLMediaElementPrototypeMediaKeys=null,window.shakaMediaKeysPolyfill=!1)};
shaka.polyfill.PatchedMediaKeysApple.requestMediaKeySystemAccess=function(a,b){shaka.log.debug("PatchedMediaKeysApple.requestMediaKeySystemAccess");goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');var c=shaka.polyfill.PatchedMediaKeysApple;try{var d=new c.MediaKeySystemAccess(a,b);return Promise.resolve(d)}catch(e){return Promise.reject(e)}};
shaka.polyfill.PatchedMediaKeysApple.setMediaKeys=function(a){shaka.log.debug("PatchedMediaKeysApple.setMediaKeys");goog.asserts.assert(this instanceof HTMLMediaElement,'bad "this" for setMediaKeys');var b=shaka.polyfill.PatchedMediaKeysApple,c=this.mediaKeys;c&&c!=a&&(goog.asserts.assert(c instanceof b.MediaKeys,"non-polyfill instance of oldMediaKeys"),c.setMedia(null));delete this.mediaKeys;return(this.mediaKeys=a)?(goog.asserts.assert(a instanceof b.MediaKeys,"non-polyfill instance of newMediaKeys"),
a.setMedia(this)):Promise.resolve()};
shaka.polyfill.PatchedMediaKeysApple.onWebkitNeedKey_=function(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitNeedKey_",a);goog.asserts.assert(this.mediaKeys instanceof shaka.polyfill.PatchedMediaKeysApple.MediaKeys,"non-polyfill instance of newMediaKeys");goog.asserts.assert(null!=a.initData,"missing init data!");a=shaka.util.BufferUtils.toUint8(a.initData);if(shaka.util.BufferUtils.toDataView(a).getUint32(0,!0)+4!=a.byteLength)throw new RangeError("Malformed FairPlay init data");a=shaka.util.StringUtils.fromUTF16(a.subarray(4),
!0);a=shaka.util.StringUtils.toUTF8(a);var b=new Event("encrypted");b.initDataType="skd";b.initData=shaka.util.BufferUtils.toArrayBuffer(a);this.dispatchEvent(b)};goog.exportProperty(shaka.polyfill,"PatchedMediaKeysApple",shaka.polyfill.PatchedMediaKeysApple);goog.exportProperty(shaka.polyfill.PatchedMediaKeysApple,"uninstall",shaka.polyfill.PatchedMediaKeysApple.uninstall);goog.exportProperty(shaka.polyfill.PatchedMediaKeysApple,"install",shaka.polyfill.PatchedMediaKeysApple.install);
shaka.polyfill.PatchedMediaKeysApple.MediaKeySystemAccess=function(a,b){shaka.log.debug("PatchedMediaKeysApple.MediaKeySystemAccess");this.keySystem=a;if(a.startsWith("com.apple.fps"))for(a=$jscomp.makeIterator(b),b=a.next();!b.done;b=a.next())if(b=this.checkConfig_(b.value)){this.configuration_=b;return}a=Error("Unsupported keySystem");a.name="NotSupportedError";a.code=DOMException.NOT_SUPPORTED_ERR;throw a;};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySystemAccess.prototype.checkConfig_=function(a){if("required"==a.persistentState)return null;var b={audioCapabilities:[],videoCapabilities:[],persistentState:"optional",distinctiveIdentifier:"optional",initDataTypes:a.initDataTypes,sessionTypes:["temporary"],label:a.label},c=!1,d=!1;if(a.audioCapabilities)for(var e=$jscomp.makeIterator(a.audioCapabilities),f=e.next();!f.done;f=e.next())if(f=f.value,f.contentType){c=!0;var g=f.contentType.split(";")[0];
WebKitMediaKeys.isTypeSupported(this.keySystem,g)&&(b.audioCapabilities.push(f),d=!0)}if(a.videoCapabilities)for(a=$jscomp.makeIterator(a.videoCapabilities),f=a.next();!f.done;f=a.next())e=f.value,e.contentType&&(c=!0,f=e.contentType.split(";")[0],WebKitMediaKeys.isTypeSupported(this.keySystem,f)&&(b.videoCapabilities.push(e),d=!0));c||(d=WebKitMediaKeys.isTypeSupported(this.keySystem,"video/mp4"));return d?b:null};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySystemAccess.prototype.createMediaKeys=function(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySystemAccess.createMediaKeys");var a=new shaka.polyfill.PatchedMediaKeysApple.MediaKeys(this.keySystem);return Promise.resolve(a)};shaka.polyfill.PatchedMediaKeysApple.MediaKeySystemAccess.prototype.getConfiguration=function(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySystemAccess.getConfiguration");return this.configuration_};
shaka.polyfill.PatchedMediaKeysApple.MediaKeys=function(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeys");this.nativeMediaKeys_=new WebKitMediaKeys(a);this.eventManager_=new shaka.util.EventManager};
shaka.polyfill.PatchedMediaKeysApple.MediaKeys.prototype.createSession=function(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeys.createSession");a=a||"temporary";if("temporary"!=a)throw new TypeError("Session type "+a+" is unsupported on this platform.");return new shaka.polyfill.PatchedMediaKeysApple.MediaKeySession(this.nativeMediaKeys_,a)};
shaka.polyfill.PatchedMediaKeysApple.MediaKeys.prototype.setServerCertificate=function(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeys.setServerCertificate");return Promise.resolve(!1)};
shaka.polyfill.PatchedMediaKeysApple.MediaKeys.prototype.setMedia=function(a){var b=this,c=shaka.polyfill.PatchedMediaKeysApple;this.eventManager_.removeAll();if(!a)return Promise.resolve();this.eventManager_.listen(a,"webkitneedkey",c.onWebkitNeedKey_);try{return shaka.util.MediaReadyState.waitForReadyState(a,HTMLMediaElement.HAVE_METADATA,this.eventManager_,function(){a.webkitSetMediaKeys(b.nativeMediaKeys_)}),Promise.resolve()}catch(d){return Promise.reject(d)}};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession=function(a,b){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession");shaka.util.FakeEventTarget.call(this);this.nativeMediaKeySession_=null;this.nativeMediaKeys_=a;this.updatePromise_=this.generateRequestPromise_=null;this.eventManager_=new shaka.util.EventManager;this.sessionId="";this.expiration=NaN;this.closed=new shaka.util.PublicPromise;this.keyStatuses=new shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap};
$jscomp.inherits(shaka.polyfill.PatchedMediaKeysApple.MediaKeySession,shaka.util.FakeEventTarget);
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.generateRequest=function(a,b){var c=this;shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.generateRequest");this.generateRequestPromise_=new shaka.util.PublicPromise;try{var d=this.nativeMediaKeys_.createSession("video/mp4",shaka.util.BufferUtils.toUint8(b));this.nativeMediaKeySession_=d;this.sessionId=d.sessionId||"";this.eventManager_.listen(this.nativeMediaKeySession_,"webkitkeymessage",function(e){return c.onWebkitKeyMessage_(e)});
this.eventManager_.listen(d,"webkitkeyadded",function(e){return c.onWebkitKeyAdded_(e)});this.eventManager_.listen(d,"webkitkeyerror",function(e){return c.onWebkitKeyError_(e)});this.updateKeyStatus_("status-pending")}catch(e){this.generateRequestPromise_.reject(e)}return this.generateRequestPromise_};shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.load=function(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.load");return Promise.reject(Error("MediaKeySession.load not yet supported"))};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.update=function(a){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.update");this.updatePromise_=new shaka.util.PublicPromise;try{this.nativeMediaKeySession_.update(shaka.util.BufferUtils.toUint8(a))}catch(b){this.updatePromise_.reject(b)}return this.updatePromise_};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.close=function(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.close");try{this.nativeMediaKeySession_.close(),this.closed.resolve(),this.eventManager_.removeAll()}catch(a){this.closed.reject(a)}return this.closed};shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.remove=function(){shaka.log.debug("PatchedMediaKeysApple.MediaKeySession.remove");return Promise.reject(Error("MediaKeySession.remove is only applicable for persistent licenses, which are not supported on this platform"))};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.onWebkitKeyMessage_=function(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitKeyMessage_",a);goog.asserts.assert(this.generateRequestPromise_,"generateRequestPromise_ should be set before now!");this.generateRequestPromise_&&(this.generateRequestPromise_.resolve(),this.generateRequestPromise_=null);var b=void 0==this.keyStatuses.getStatus();a=(new Map).set("messageType",b?"license-request":"license-renewal").set("message",shaka.util.BufferUtils.toArrayBuffer(a.message));
a=new shaka.util.FakeEvent("message",a);this.dispatchEvent(a)};shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.onWebkitKeyAdded_=function(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitKeyAdded_",a);goog.asserts.assert(!this.generateRequestPromise_,"Key added during generate!");goog.asserts.assert(this.updatePromise_,"updatePromise_ should be set before now!");this.updatePromise_&&(this.updateKeyStatus_("usable"),this.updatePromise_.resolve(),this.updatePromise_=null)};
shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.onWebkitKeyError_=function(a){shaka.log.debug("PatchedMediaKeysApple.onWebkitKeyError_",a);a=Error("EME PatchedMediaKeysApple key error");a.errorCode=this.nativeMediaKeySession_.error;if(null!=this.generateRequestPromise_)this.generateRequestPromise_.reject(a),this.generateRequestPromise_=null;else if(null!=this.updatePromise_)this.updatePromise_.reject(a),this.updatePromise_=null;else switch(this.nativeMediaKeySession_.error.code){case WebKitMediaKeyError.MEDIA_KEYERR_OUTPUT:case WebKitMediaKeyError.MEDIA_KEYERR_HARDWARECHANGE:this.updateKeyStatus_("output-not-allowed");
break;default:this.updateKeyStatus_("internal-error")}};shaka.polyfill.PatchedMediaKeysApple.MediaKeySession.prototype.updateKeyStatus_=function(a){this.keyStatuses.setStatus(a);a=new shaka.util.FakeEvent("keystatuseschange");this.dispatchEvent(a)};shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap=function(){this.size=0;this.status_=void 0};shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.setStatus=function(a){this.size=void 0==a?0:1;this.status_=a};
shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.getStatus=function(){return this.status_};shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.forEach=function(a){this.status_&&a(this.status_,shaka.media.DrmEngine.DUMMY_KEY_ID.value())};shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.get=function(a){if(this.has(a))return this.status_};
shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.has=function(a){var b=shaka.media.DrmEngine.DUMMY_KEY_ID.value();return this.status_&&shaka.util.BufferUtils.equal(a,b)?!0:!1};shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.entries=function(){goog.asserts.assert(!1,"Not used!  Provided only for the compiler.")};shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.keys=function(){goog.asserts.assert(!1,"Not used!  Provided only for the compiler.")};
shaka.polyfill.PatchedMediaKeysApple.MediaKeyStatusMap.prototype.values=function(){goog.asserts.assert(!1,"Not used!  Provided only for the compiler.")};shaka.polyfill.PatchedMediaKeysNop=function(){};
shaka.polyfill.PatchedMediaKeysNop.install=function(){if(!(!window.HTMLVideoElement||navigator.requestMediaKeySystemAccess&&MediaKeySystemAccess.prototype.getConfiguration)){shaka.log.info("EME not available.");var a=shaka.polyfill.PatchedMediaKeysNop;navigator.requestMediaKeySystemAccess=a.requestMediaKeySystemAccess;delete HTMLMediaElement.prototype.mediaKeys;HTMLMediaElement.prototype.mediaKeys=null;HTMLMediaElement.prototype.setMediaKeys=a.setMediaKeys;window.MediaKeys=a.MediaKeys;window.MediaKeySystemAccess=
a.MediaKeySystemAccess;window.shakaMediaKeysPolyfill=!0}};shaka.polyfill.PatchedMediaKeysNop.requestMediaKeySystemAccess=function(a,b){shaka.log.debug("PatchedMediaKeysNop.requestMediaKeySystemAccess");goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');return Promise.reject(Error("The key system specified is not supported."))};
shaka.polyfill.PatchedMediaKeysNop.setMediaKeys=function(a){shaka.log.debug("PatchedMediaKeysNop.setMediaKeys");goog.asserts.assert(this instanceof HTMLMediaElement,'bad "this" for setMediaKeys');return null==a?Promise.resolve():Promise.reject(Error("MediaKeys not supported."))};goog.exportProperty(shaka.polyfill,"PatchedMediaKeysNop",shaka.polyfill.PatchedMediaKeysNop);goog.exportProperty(shaka.polyfill.PatchedMediaKeysNop,"install",shaka.polyfill.PatchedMediaKeysNop.install);
shaka.polyfill.PatchedMediaKeysNop.MediaKeys=function(){throw new TypeError("Illegal constructor.");};shaka.polyfill.PatchedMediaKeysNop.MediaKeys.prototype.createSession=function(){};shaka.polyfill.PatchedMediaKeysNop.MediaKeys.prototype.setServerCertificate=function(){};shaka.polyfill.PatchedMediaKeysNop.MediaKeySystemAccess=function(){this.keySystem="";throw new TypeError("Illegal constructor.");};shaka.polyfill.PatchedMediaKeysNop.MediaKeySystemAccess.prototype.getConfiguration=function(){};
shaka.polyfill.PatchedMediaKeysNop.MediaKeySystemAccess.prototype.createMediaKeys=function(){};shaka.polyfill.register(shaka.polyfill.PatchedMediaKeysNop.install,-10);shaka.polyfill.PatchedMediaKeysWebkit=function(){};
shaka.polyfill.PatchedMediaKeysWebkit.install=function(){var a=shaka.polyfill.PatchedMediaKeysWebkit;if(!(!window.HTMLVideoElement||navigator.requestMediaKeySystemAccess&&MediaKeySystemAccess.prototype.getConfiguration)){if(HTMLMediaElement.prototype.webkitGenerateKeyRequest)shaka.log.info("Using webkit-prefixed EME v0.1b"),a.prefix_="webkit";else if(HTMLMediaElement.prototype.generateKeyRequest)shaka.log.info("Using nonprefixed EME v0.1b");else return;goog.asserts.assert(HTMLMediaElement.prototype[a.prefixApi_("generateKeyRequest")],
"PatchedMediaKeysWebkit APIs not available!");navigator.requestMediaKeySystemAccess=a.requestMediaKeySystemAccess;delete HTMLMediaElement.prototype.mediaKeys;HTMLMediaElement.prototype.mediaKeys=null;HTMLMediaElement.prototype.setMediaKeys=a.setMediaKeys;window.MediaKeys=a.MediaKeys;window.MediaKeySystemAccess=a.MediaKeySystemAccess;window.shakaMediaKeysPolyfill=!0}};
shaka.polyfill.PatchedMediaKeysWebkit.prefixApi_=function(a){var b=shaka.polyfill.PatchedMediaKeysWebkit.prefix_;return b?b+a.charAt(0).toUpperCase()+a.slice(1):a};shaka.polyfill.PatchedMediaKeysWebkit.requestMediaKeySystemAccess=function(a,b){shaka.log.debug("PatchedMediaKeysWebkit.requestMediaKeySystemAccess");goog.asserts.assert(this==navigator,'bad "this" for requestMediaKeySystemAccess');var c=shaka.polyfill.PatchedMediaKeysWebkit;try{var d=new c.MediaKeySystemAccess(a,b);return Promise.resolve(d)}catch(e){return Promise.reject(e)}};
shaka.polyfill.PatchedMediaKeysWebkit.setMediaKeys=function(a){shaka.log.debug("PatchedMediaKeysWebkit.setMediaKeys");goog.asserts.assert(this instanceof HTMLMediaElement,'bad "this" for setMediaKeys');var b=shaka.polyfill.PatchedMediaKeysWebkit,c=this.mediaKeys;c&&c!=a&&(goog.asserts.assert(c instanceof b.MediaKeys,"non-polyfill instance of oldMediaKeys"),c.setMedia(null));delete this.mediaKeys;if(this.mediaKeys=a)goog.asserts.assert(a instanceof b.MediaKeys,"non-polyfill instance of newMediaKeys"),
a.setMedia(this);return Promise.resolve()};shaka.polyfill.PatchedMediaKeysWebkit.getVideoElement_=function(){var a=document.getElementsByTagName("video");return a.length?a[0]:document.createElement("video")};goog.exportProperty(shaka.polyfill,"PatchedMediaKeysWebkit",shaka.polyfill.PatchedMediaKeysWebkit);goog.exportProperty(shaka.polyfill.PatchedMediaKeysWebkit,"install",shaka.polyfill.PatchedMediaKeysWebkit.install);
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess=function(a,b){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySystemAccess");this.internalKeySystem_=this.keySystem=a;var c=!1;"org.w3.clearkey"==a&&(this.internalKeySystem_="webkit-org.w3.clearkey",c=!1);var d=!1,e=shaka.polyfill.PatchedMediaKeysWebkit.getVideoElement_();b=$jscomp.makeIterator(b);for(var f=b.next();!f.done;f=b.next()){f=f.value;var g={audioCapabilities:[],videoCapabilities:[],persistentState:"optional",distinctiveIdentifier:"optional",
initDataTypes:f.initDataTypes,sessionTypes:["temporary"],label:f.label},h=!1;if(f.audioCapabilities)for(var k=$jscomp.makeIterator(f.audioCapabilities),l=k.next();!l.done;l=k.next())if(l=l.value,l.contentType){h=!0;var m=l.contentType.split(";")[0];e.canPlayType(m,this.internalKeySystem_)&&(g.audioCapabilities.push(l),d=!0)}if(f.videoCapabilities)for(k=$jscomp.makeIterator(f.videoCapabilities),l=k.next();!l.done;l=k.next())l=l.value,l.contentType&&(h=!0,e.canPlayType(l.contentType,this.internalKeySystem_)&&
(g.videoCapabilities.push(l),d=!0));h||(d=e.canPlayType("video/mp4",this.internalKeySystem_)||e.canPlayType("video/webm",this.internalKeySystem_));"required"==f.persistentState&&(c?(g.persistentState="required",g.sessionTypes=["persistent-license"]):d=!1);if(d){this.configuration_=g;return}}c="Unsupported keySystem";if("org.w3.clearkey"==a||"com.widevine.alpha"==a)c="None of the requested configurations were supported.";a=Error(c);a.name="NotSupportedError";a.code=DOMException.NOT_SUPPORTED_ERR;throw a;
};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess.prototype.createMediaKeys=function(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySystemAccess.createMediaKeys");var a=new shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys(this.internalKeySystem_);return Promise.resolve(a)};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySystemAccess.prototype.getConfiguration=function(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySystemAccess.getConfiguration");return this.configuration_};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys=function(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys");this.keySystem_=a;this.media_=null;this.eventManager_=new shaka.util.EventManager;this.newSessions_=[];this.sessionMap_=new Map};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.setMedia=function(a){var b=this;this.media_=a;this.eventManager_.removeAll();var c=shaka.polyfill.PatchedMediaKeysWebkit.prefix_;a&&(this.eventManager_.listen(a,c+"needkey",function(d){return b.onWebkitNeedKey_(d)}),this.eventManager_.listen(a,c+"keymessage",function(d){return b.onWebkitKeyMessage_(d)}),this.eventManager_.listen(a,c+"keyadded",function(d){return b.onWebkitKeyAdded_(d)}),this.eventManager_.listen(a,c+"keyerror",function(d){return b.onWebkitKeyError_(d)}))};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.createSession=function(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.createSession");a=a||"temporary";if("temporary"!=a&&"persistent-license"!=a)throw new TypeError("Session type "+a+" is unsupported on this platform.");var b=shaka.polyfill.PatchedMediaKeysWebkit,c=this.media_||document.createElement("video");c.src||(c.src="about:blank");a=new b.MediaKeySession(c,this.keySystem_,a);this.newSessions_.push(a);return a};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.setServerCertificate=function(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.setServerCertificate");return Promise.resolve(!1)};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitNeedKey_=function(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitNeedKey_",a);goog.asserts.assert(this.media_,"media_ not set in onWebkitNeedKey_");var b=new CustomEvent("encrypted");b.initDataType="cenc";b.initData=shaka.util.BufferUtils.toArrayBuffer(a.initData);this.media_.dispatchEvent(b)};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitKeyMessage_=function(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitKeyMessage_",a);var b=this.findSession_(a.sessionId);if(b){var c=void 0==b.keyStatuses.getStatus();a=(new Map).set("messageType",c?"licenserequest":"licenserenewal").set("message",a.message);a=new shaka.util.FakeEvent("message",a);b.generated();b.dispatchEvent(a)}else shaka.log.error("Session not found",a.sessionId)};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitKeyAdded_=function(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitKeyAdded_",a);a=this.findSession_(a.sessionId);goog.asserts.assert(a,"unable to find session in onWebkitKeyAdded_");a&&a.ready()};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.onWebkitKeyError_=function(a){shaka.log.debug("PatchedMediaKeysWebkit.onWebkitKeyError_",a);var b=this.findSession_(a.sessionId);goog.asserts.assert(b,"unable to find session in onWebkitKeyError_");b&&b.handleError(a)};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeys.prototype.findSession_=function(a){var b=this.sessionMap_.get(a);return b?(shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.findSession_",b),b):(b=this.newSessions_.shift())?(b.sessionId=a,this.sessionMap_.set(a,b),shaka.log.debug("PatchedMediaKeysWebkit.MediaKeys.findSession_",b),b):null};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession=function(a,b,c){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession");shaka.util.FakeEventTarget.call(this);this.media_=a;this.initialized_=!1;this.updatePromise_=this.generatePromise_=null;this.keySystem_=b;this.type_=c;this.sessionId="";this.expiration=NaN;this.closed=new shaka.util.PublicPromise;this.keyStatuses=new shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap};
$jscomp.inherits(shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession,shaka.util.FakeEventTarget);shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.generated=function(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.generated");this.generatePromise_&&(this.generatePromise_.resolve(),this.generatePromise_=null)};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.ready=function(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.ready");this.updateKeyStatus_("usable");this.updatePromise_&&this.updatePromise_.resolve();this.updatePromise_=null};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.handleError=function(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.handleError",a);var b=Error("EME v0.1b key error"),c=a.errorCode;c.systemCode=a.systemCode;b.errorCode=c;!a.sessionId&&this.generatePromise_?(45==a.systemCode&&(b.message="Unsupported session type."),this.generatePromise_.reject(b),this.generatePromise_=null):a.sessionId&&this.updatePromise_?(this.updatePromise_.reject(b),this.updatePromise_=null):(b=a.systemCode,
a.errorCode.code==MediaKeyError.MEDIA_KEYERR_OUTPUT?this.updateKeyStatus_("output-restricted"):1==b?this.updateKeyStatus_("expired"):this.updateKeyStatus_("internal-error"))};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.generate_=function(a,b){var c=this,d=shaka.polyfill.PatchedMediaKeysWebkit;if(this.initialized_)return Promise.reject(Error("The session is already initialized."));this.initialized_=!0;try{if("persistent-license"==this.type_){var e=shaka.util.StringUtils;if(b)var f=shaka.util.BufferUtils.toUint8(e.toUTF8("LOAD_SESSION|"+b));else{goog.asserts.assert(a,"expecting init data");var g=e.toUTF8("PERSISTENT|");f=shaka.util.Uint8ArrayUtils.concat(g,
a)}}else goog.asserts.assert("temporary"==this.type_,"expected temporary session"),goog.asserts.assert(!b,"unexpected offline session ID"),goog.asserts.assert(a,"expecting init data"),f=shaka.util.BufferUtils.toUint8(a);goog.asserts.assert(f,"init data not set!")}catch(k){return Promise.reject(k)}goog.asserts.assert(null==this.generatePromise_,"generatePromise_ should be null");this.generatePromise_=new shaka.util.PublicPromise;var h=d.prefixApi_("generateKeyRequest");try{this.media_[h](this.keySystem_,
f)}catch(k){if("InvalidStateError"!=k.name)return this.generatePromise_=null,Promise.reject(k);(new shaka.util.Timer(function(){try{c.media_[h](c.keySystem_,f)}catch(l){c.generatePromise_.reject(l),c.generatePromise_=null}})).tickAfter(.01)}return this.generatePromise_};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.update_=function(a,b){var c=this,d=shaka.polyfill.PatchedMediaKeysWebkit;if(this.updatePromise_)this.updatePromise_.then(function(){return c.update_(a,b)}).catch(function(){return c.update_(a,b)});else{this.updatePromise_=a;if("webkit-org.w3.clearkey"==this.keySystem_){var e=shaka.util.Uint8ArrayUtils;var f=shaka.util.StringUtils.fromUTF8(b);var g=JSON.parse(f);"oct"!=g.keys[0].kty&&(this.updatePromise_.reject(Error("Response is not a valid JSON Web Key Set.")),
this.updatePromise_=null);f=e.fromBase64(g.keys[0].k);e=e.fromBase64(g.keys[0].kid)}else f=shaka.util.BufferUtils.toUint8(b),e=null;d=d.prefixApi_("addKey");try{this.media_[d](this.keySystem_,f,e,this.sessionId)}catch(h){this.updatePromise_.reject(h),this.updatePromise_=null}}};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.updateKeyStatus_=function(a){this.keyStatuses.setStatus(a);a=new shaka.util.FakeEvent("keystatuseschange");this.dispatchEvent(a)};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.generateRequest=function(a,b){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.generateRequest");return this.generate_(b,null)};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.load=function(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.load");return"persistent-license"==this.type_?this.generate_(null,a):Promise.reject(Error("Not a persistent session."))};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.update=function(a){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.update",a);goog.asserts.assert(this.sessionId,"update without session ID");var b=new shaka.util.PublicPromise;this.update_(b,a);return b};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.close=function(){var a=shaka.polyfill.PatchedMediaKeysWebkit;shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.close");if("persistent-license"!=this.type_){if(!this.sessionId)return this.closed.reject(Error("The session is not callable.")),this.closed;a=a.prefixApi_("cancelKeyRequest");try{this.media_[a](this.keySystem_,this.sessionId)}catch(b){}}this.closed.resolve();return this.closed};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeySession.prototype.remove=function(){shaka.log.debug("PatchedMediaKeysWebkit.MediaKeySession.remove");return"persistent-license"!=this.type_?Promise.reject(Error("Not a persistent session.")):this.close()};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap=function(){this.size=0;this.status_=void 0};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.setStatus=function(a){this.size=void 0==a?0:1;this.status_=a};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.getStatus=function(){return this.status_};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.forEach=function(a){this.status_&&a(this.status_,shaka.media.DrmEngine.DUMMY_KEY_ID.value())};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.get=function(a){if(this.has(a))return this.status_};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.has=function(a){var b=shaka.media.DrmEngine.DUMMY_KEY_ID.value();return this.status_&&shaka.util.BufferUtils.equal(a,b)?!0:!1};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.entries=function(){goog.asserts.assert(!1,"Not used!  Provided only for compiler.")};shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.keys=function(){goog.asserts.assert(!1,"Not used!  Provided only for compiler.")};
shaka.polyfill.PatchedMediaKeysWebkit.MediaKeyStatusMap.prototype.values=function(){goog.asserts.assert(!1,"Not used!  Provided only for compiler.")};shaka.polyfill.PatchedMediaKeysWebkit.prefix_="";shaka.polyfill.register(shaka.polyfill.PatchedMediaKeysWebkit.install);shaka.polyfill.PiPWebkit=function(){};
shaka.polyfill.PiPWebkit.install=function(){if(window.HTMLVideoElement){var a=HTMLVideoElement.prototype;if((!a.requestPictureInPicture||!document.exitPictureInPicture)&&a.webkitSupportsPresentationMode){var b=shaka.polyfill.PiPWebkit;shaka.log.debug("PiPWebkit.install");document.pictureInPictureEnabled=!0;document.pictureInPictureElement=null;a.requestPictureInPicture=b.requestPictureInPicture_;Object.defineProperty(a,"disablePictureInPicture",{get:b.getDisablePictureInPicture_,set:b.setDisablePictureInPicture_,
enumerable:!0,configurable:!0});document.exitPictureInPicture=b.exitPictureInPicture_;document.addEventListener("webkitpresentationmodechanged",b.proxyEvent_,!0)}}};
shaka.polyfill.PiPWebkit.proxyEvent_=function(a){a=a.target;if(a.webkitPresentationMode==shaka.polyfill.PiPWebkit.PIP_MODE_){document.pictureInPictureElement=a;var b=new Event("enterpictureinpicture");a.dispatchEvent(b)}else document.pictureInPictureElement==a&&(document.pictureInPictureElement=null),b=new Event("leavepictureinpicture"),a.dispatchEvent(b)};
shaka.polyfill.PiPWebkit.requestPictureInPicture_=function(){var a=shaka.polyfill.PiPWebkit;return this.webkitSupportsPresentationMode(a.PIP_MODE_)?(this.webkitSetPresentationMode(a.PIP_MODE_),document.pictureInPictureElement=this,Promise.resolve()):Promise.reject(Error("PiP not allowed by video element"))};
shaka.polyfill.PiPWebkit.exitPictureInPicture_=function(){var a=shaka.polyfill.PiPWebkit,b=document.pictureInPictureElement;return b?(b.webkitSetPresentationMode(a.INLINE_MODE_),document.pictureInPictureElement=null,Promise.resolve()):Promise.reject(Error("No picture in picture element found"))};shaka.polyfill.PiPWebkit.getDisablePictureInPicture_=function(){return this.hasAttribute("disablePictureInPicture")?!0:!this.webkitSupportsPresentationMode(shaka.polyfill.PiPWebkit.PIP_MODE_)};
shaka.polyfill.PiPWebkit.setDisablePictureInPicture_=function(a){a?this.setAttribute("disablePictureInPicture",""):this.removeAttribute("disablePictureInPicture")};goog.exportProperty(shaka.polyfill,"PiPWebkit",shaka.polyfill.PiPWebkit);goog.exportProperty(shaka.polyfill.PiPWebkit,"install",shaka.polyfill.PiPWebkit.install);shaka.polyfill.PiPWebkit.PIP_MODE_="picture-in-picture";shaka.polyfill.PiPWebkit.INLINE_MODE_="inline";shaka.polyfill.register(shaka.polyfill.PiPWebkit.install);shaka.polyfill.RandomUUID=function(){};shaka.polyfill.RandomUUID.install=function(){shaka.log.debug("randomUUID.install");window.crypto?"randomUUID"in window.crypto?shaka.log.debug("RandomUUID: Native window.crypto.randomUUID() support found."):window.crypto.randomUUID=shaka.polyfill.RandomUUID.randomUUID_:shaka.log.debug("window.crypto must be available to install randomUUID polyfill.")};
shaka.polyfill.RandomUUID.randomUUID_=function(){var a=URL.createObjectURL(new Blob),b=a.toString();URL.revokeObjectURL(a);return b.substr(b.lastIndexOf("/")+1)};goog.exportProperty(shaka.polyfill,"RandomUUID",shaka.polyfill.RandomUUID);goog.exportProperty(shaka.polyfill.RandomUUID,"install",shaka.polyfill.RandomUUID.install);shaka.polyfill.register(shaka.polyfill.RandomUUID.install);shaka.polyfill.StorageEstimate=function(){};shaka.polyfill.StorageEstimate.install=function(){navigator.storage&&navigator.storage.estimate||!navigator.webkitTemporaryStorage||!navigator.webkitTemporaryStorage.queryUsageAndQuota||("storage"in navigator||(navigator.storage={}),navigator.storage.estimate=shaka.polyfill.StorageEstimate.storageEstimate_)};
shaka.polyfill.StorageEstimate.storageEstimate_=function(){return new Promise(function(a,b){navigator.webkitTemporaryStorage.queryUsageAndQuota(function(c,d){a({usage:c,quota:d})},b)})};goog.exportProperty(shaka.polyfill,"StorageEstimate",shaka.polyfill.StorageEstimate);goog.exportProperty(shaka.polyfill.StorageEstimate,"install",shaka.polyfill.StorageEstimate.install);shaka.polyfill.register(shaka.polyfill.StorageEstimate.install);shaka.polyfill.Symbol=function(){};shaka.polyfill.Symbol.install=function(){shaka.log.debug("Symbol.install");var a=Symbol.prototype;"description"in a||Object.defineProperty(a,"description",{get:shaka.polyfill.Symbol.getSymbolDescription_})};shaka.polyfill.Symbol.getSymbolDescription_=function(){var a=/\((.*)\)/.exec(this.toString());return a?a[1]:void 0};goog.exportProperty(shaka.polyfill,"Symbol",shaka.polyfill.Symbol);goog.exportProperty(shaka.polyfill.Symbol,"install",shaka.polyfill.Symbol.install);
shaka.polyfill.register(shaka.polyfill.Symbol.install);shaka.polyfill.VideoPlayPromise=function(){};shaka.polyfill.VideoPlayPromise.install=function(){shaka.log.debug("VideoPlayPromise.install");if(window.HTMLMediaElement){var a=HTMLMediaElement.prototype.play;HTMLMediaElement.prototype.play=function(){var b=a.apply(this);b&&b.catch(function(){});return b}}};goog.exportProperty(shaka.polyfill,"VideoPlayPromise",shaka.polyfill.VideoPlayPromise);goog.exportProperty(shaka.polyfill.VideoPlayPromise,"install",shaka.polyfill.VideoPlayPromise.install);shaka.polyfill.register(shaka.polyfill.VideoPlayPromise.install);shaka.polyfill.VideoPlaybackQuality=function(){};shaka.polyfill.VideoPlaybackQuality.install=function(){if(window.HTMLVideoElement){var a=HTMLVideoElement.prototype;!a.getVideoPlaybackQuality&&("webkitDroppedFrameCount"in a||shaka.util.Platform.isWebOS3())&&(a.getVideoPlaybackQuality=shaka.polyfill.VideoPlaybackQuality.webkit_)}};
shaka.polyfill.VideoPlaybackQuality.webkit_=function(){return{droppedVideoFrames:this.webkitDroppedFrameCount,totalVideoFrames:this.webkitDecodedFrameCount,corruptedVideoFrames:0,creationTime:NaN,totalFrameDelay:0}};goog.exportProperty(shaka.polyfill,"VideoPlaybackQuality",shaka.polyfill.VideoPlaybackQuality);goog.exportProperty(shaka.polyfill.VideoPlaybackQuality,"install",shaka.polyfill.VideoPlaybackQuality.install);shaka.polyfill.register(shaka.polyfill.VideoPlaybackQuality.install);shaka.polyfill.VTTCue=function(){};
shaka.polyfill.VTTCue.install=function(){if(window.VTTCue)shaka.log.info("Using native VTTCue.");else if(window.TextTrackCue){var a=null,b=TextTrackCue.length;3==b?(shaka.log.info("Using VTTCue polyfill from 3 argument TextTrackCue."),a=shaka.polyfill.VTTCue.from3ArgsTextTrackCue_):6==b?(shaka.log.info("Using VTTCue polyfill from 6 argument TextTrackCue."),a=shaka.polyfill.VTTCue.from6ArgsTextTrackCue_):shaka.polyfill.VTTCue.canUse3ArgsTextTrackCue_()&&(shaka.log.info("Using VTTCue polyfill from 3 argument TextTrackCue."),a=
shaka.polyfill.VTTCue.from3ArgsTextTrackCue_);a?window.VTTCue=function(c,d,e){return a(c,d,e)}:shaka.log.error("No recognized signature for TextTrackCue found!")}else shaka.log.error("VTTCue not available.")};shaka.polyfill.VTTCue.from3ArgsTextTrackCue_=function(a,b,c){return new window.TextTrackCue(a,b,c)};shaka.polyfill.VTTCue.from6ArgsTextTrackCue_=function(a,b,c){return new window.TextTrackCue(a+"-"+b+"-"+c,a,b,c)};
shaka.polyfill.VTTCue.canUse3ArgsTextTrackCue_=function(){try{return!!shaka.polyfill.VTTCue.from3ArgsTextTrackCue_(1,2,"")}catch(a){return!1}};goog.exportProperty(shaka.polyfill,"VTTCue",shaka.polyfill.VTTCue);goog.exportProperty(shaka.polyfill.VTTCue,"install",shaka.polyfill.VTTCue.install);shaka.polyfill.register(shaka.polyfill.VTTCue.install);shaka.text.LrcTextParser=function(){};shaka.text.LrcTextParser.prototype.parseInit=function(a){goog.asserts.assert(!1,"LRC does not have init segments")};shaka.text.LrcTextParser.prototype.setSequenceMode=function(a){};
shaka.text.LrcTextParser.prototype.parseMedia=function(a,b){var c=shaka.text.LrcTextParser,d=null,e=[];a=shaka.util.StringUtils.fromUTF8(a).split(/\r?\n/);a=$jscomp.makeIterator(a);for(var f=a.next();!f.done;f=a.next()){var g=f.value;g&&!/^\s+$/.test(g)&&((f=c.lyricLine_.exec(g))?(g=c.parseTime_(f[1]),f=new shaka.text.Cue(g,b.segmentEnd?b.segmentEnd:g+2,f[2]),d&&(d.endTime=g,e.push(d)),d=f):shaka.log.warning("LrcTextParser encountered an unknown line.",g))}d&&e.push(d);return e};
shaka.text.LrcTextParser.parseTime_=function(a){var b=shaka.text.LrcTextParser.timeFormat_.exec(a);a=parseInt(b[1],10);b=parseFloat(b[2].replace(",","."));return 60*a+b};goog.exportSymbol("shaka.text.LrcTextParser",shaka.text.LrcTextParser);goog.exportProperty(shaka.text.LrcTextParser.prototype,"parseMedia",shaka.text.LrcTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.LrcTextParser.prototype,"setSequenceMode",shaka.text.LrcTextParser.prototype.setSequenceMode);
goog.exportProperty(shaka.text.LrcTextParser.prototype,"parseInit",shaka.text.LrcTextParser.prototype.parseInit);shaka.text.LrcTextParser.lyricLine_=/^\[(\d{1,2}:\d{1,2}(?:[.,]\d{1,3})?)\](.*)/;shaka.text.LrcTextParser.timeFormat_=/^(\d+):(\d{1,2}(?:[.,]\d{1,3})?)$/;shaka.text.TextEngine.registerParser("application/x-subtitle-lrc",function(){return new shaka.text.LrcTextParser});shaka.text.TtmlTextParser=function(){};shaka.text.TtmlTextParser.prototype.parseInit=function(a){goog.asserts.assert(!1,"TTML does not have init segments")};shaka.text.TtmlTextParser.prototype.setSequenceMode=function(a){};
shaka.text.TtmlTextParser.prototype.parseMedia=function(a,b){var c=shaka.text.TtmlTextParser,d=shaka.util.XmlUtils,e=c.parameterNs_,f=c.styleNs_,g=shaka.util.StringUtils.fromUTF8(a);a=[];if(""==g)return a;var h=d.parseXmlString(g,"tt");if(!h)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_XML,"Failed to parse TTML.");g=h.getElementsByTagName("body")[0];if(!g)return[];var k=d.getAttributeNSList(h,e,"frameRate"),l=d.getAttributeNSList(h,
e,"subFrameRate"),m=d.getAttributeNSList(h,e,"frameRateMultiplier"),n=d.getAttributeNSList(h,e,"tickRate"),p=d.getAttributeNSList(h,e,"cellResolution"),q=h.getAttribute("xml:space")||"default";e=d.getAttributeNSList(h,f,"extent");if("default"!=q&&"preserve"!=q)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_XML,"Invalid xml:space value: "+q);f="default"==q;k=new c.RateInfo_(k,l,m,n);l=c.getCellResolution_(p);m=(m=h.getElementsByTagName("metadata")[0])?
d.getChildren(m):[];n=Array.from(h.getElementsByTagName("style"));h=Array.from(h.getElementsByTagName("region"));p=[];q=$jscomp.makeIterator(h);for(var r=q.next();!r.done;r=q.next())(r=c.parseCueRegion_(r.value,n,e))&&p.push(r);if(d.findChildren(g,"p").length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_CUE,"<p> can only be inside <div> in TTML");e=$jscomp.makeIterator(d.findChildren(g,"div"));for(q=e.next();!q.done;q=
e.next())if(d.findChildren(q.value,"span").length)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_CUE,"<span> can only be inside <p> in TTML");if(b=c.parseCue_(g,b,k,m,n,h,p,f,l,null,!1))b.backgroundColor||(b.backgroundColor="transparent"),a.push(b);return a};
shaka.text.TtmlTextParser.parseCue_=function(a,b,c,d,e,f,g,h,k,l,m){var n=a.parentNode;if(a.nodeType==Node.COMMENT_NODE)return null;if(a.nodeType==Node.TEXT_NODE){if(!m)return null;var p=document.createElement("span");p.textContent=a.textContent}else goog.asserts.assert(a.nodeType==Node.ELEMENT_NODE,"nodeType should be ELEMENT_NODE!"),p=a;goog.asserts.assert(p,"cueElement should be non-null!");for(var q=null,r=$jscomp.makeIterator(shaka.text.TtmlTextParser.smpteNsList_),w=r.next();!w.done&&!(q=shaka.text.TtmlTextParser.getElementsFromCollection_(p,
"backgroundImage",d,"#",w.value)[0]);w=r.next());r=m;if("p"==a.nodeName||q)m=!0;h="default"==(p.getAttribute("xml:space")||(h?"default":"preserve"));w=Array.from(p.childNodes).every(function(y){return y.nodeType==Node.TEXT_NODE});a=[];if(!w)for(var u=$jscomp.makeIterator(p.childNodes),v=u.next();!v.done;v=u.next())(v=shaka.text.TtmlTextParser.parseCue_(v.value,b,c,d,e,f,g,h,k,p,m))&&a.push(v);d=null!=l;u=/\S/.test(p.textContent);var x=p.hasAttribute("begin")||p.hasAttribute("end")||p.hasAttribute("dur");
if(!(x||u||"br"==p.tagName||0!=a.length||d&&!h))return null;v=shaka.text.TtmlTextParser.parseTime_(p,c);u=v.start;for(v=v.end;n&&n.nodeType==Node.ELEMENT_NODE&&"tt"!=n.tagName;)v=shaka.text.TtmlTextParser.resolveTime_(n,c,u,v),u=v.start,v=v.end,n=n.parentNode;null==u&&(u=0);u+=b.periodStart;v=null==v?Infinity:v+b.periodStart;u=Math.max(u,b.segmentStart);v=Math.min(v,b.segmentEnd);if(!x&&0<a.length)for(u=Infinity,v=0,b=$jscomp.makeIterator(a),c=b.next();!c.done;c=b.next())c=c.value,u=Math.min(u,c.startTime),
v=Math.max(v,c.endTime);if("br"==p.tagName)return e=new shaka.text.Cue(u,v,""),e.lineBreak=!0,e;b="";w&&(b=p.textContent,h&&(b=b.trim(),b=b.replace(/\s+/g," ")));b=new shaka.text.Cue(u,v,b);b.nestedCues=a;m||(b.isContainer=!0);k&&(b.cellResolution=k);k=shaka.text.TtmlTextParser.getElementsFromCollection_(p,"region",f,"")[0];if(p.hasAttribute("region")&&k&&k.getAttribute("xml:id")){var t=k.getAttribute("xml:id");b.region=g.filter(function(y){return y.id==t})[0]}g=k;l&&d&&!p.getAttribute("region")&&
!p.getAttribute("style")&&(g=shaka.text.TtmlTextParser.getElementsFromCollection_(l,"region",f,"")[0]);shaka.text.TtmlTextParser.addStyle_(b,p,g,q,e,r,0==a.length);return b};
shaka.text.TtmlTextParser.parseCueRegion_=function(a,b,c){var d=shaka.text.TtmlTextParser,e=new shaka.text.CueRegion,f=a.getAttribute("xml:id");if(!f)return shaka.log.warning("TtmlTextParser parser encountered a region with no id. Region will be ignored."),null;e.id=f;f=null;c&&(f=d.percentValues_.exec(c)||d.pixelValues_.exec(c));c=f?Number(f[1]):null;f=f?Number(f[2]):null;var g,h;if(g=d.getStyleAttributeFromRegion_(a,b,"extent"))g=(h=d.percentValues_.exec(g))||d.pixelValues_.exec(g),null!=g&&(e.width=
Number(g[1]),e.height=Number(g[2]),h||(null!=c&&(e.width=100*e.width/c),null!=f&&(e.height=100*e.height/f)),e.widthUnits=h||null!=c?shaka.text.CueRegion.units.PERCENTAGE:shaka.text.CueRegion.units.PX,e.heightUnits=h||null!=f?shaka.text.CueRegion.units.PERCENTAGE:shaka.text.CueRegion.units.PX);if(a=d.getStyleAttributeFromRegion_(a,b,"origin"))g=(h=d.percentValues_.exec(a))||d.pixelValues_.exec(a),null!=g&&(e.viewportAnchorX=Number(g[1]),e.viewportAnchorY=Number(g[2]),h||(null!=f&&(e.viewportAnchorY=
100*e.viewportAnchorY/f),null!=c&&(e.viewportAnchorX=100*e.viewportAnchorX/c)),e.viewportAnchorUnits=h||null!=c?shaka.text.CueRegion.units.PERCENTAGE:shaka.text.CueRegion.units.PX);return e};
shaka.text.TtmlTextParser.addStyle_=function(a,b,c,d,e,f,g){var h=shaka.text.TtmlTextParser,k=shaka.text.Cue;f=f||g;"rtl"==h.getStyleAttribute_(b,c,e,"direction",f)&&(a.direction=k.direction.HORIZONTAL_RIGHT_TO_LEFT);g=h.getStyleAttribute_(b,c,e,"writingMode",f);"tb"==g||"tblr"==g?a.writingMode=k.writingMode.VERTICAL_LEFT_TO_RIGHT:"tbrl"==g?a.writingMode=k.writingMode.VERTICAL_RIGHT_TO_LEFT:"rltb"==g||"rl"==g?a.direction=k.direction.HORIZONTAL_RIGHT_TO_LEFT:g&&(a.direction=k.direction.HORIZONTAL_LEFT_TO_RIGHT);
(g=h.getStyleAttribute_(b,c,e,"textAlign",!0))?(a.positionAlign=h.textAlignToPositionAlign_[g],a.lineAlign=h.textAlignToLineAlign_[g],goog.asserts.assert(g.toUpperCase()in k.textAlign,g.toUpperCase()+" Should be in Cue.textAlign values!"),a.textAlign=k.textAlign[g.toUpperCase()]):a.textAlign=k.textAlign.CENTER;if(g=h.getStyleAttribute_(b,c,e,"displayAlign",!0))goog.asserts.assert(g.toUpperCase()in k.displayAlign,g.toUpperCase()+" Should be in Cue.displayAlign values!"),a.displayAlign=k.displayAlign[g.toUpperCase()];
if(g=h.getStyleAttribute_(b,c,e,"color",f))a.color=g;if(g=h.getStyleAttribute_(b,c,e,"backgroundColor",f))a.backgroundColor=g;if(g=h.getStyleAttribute_(b,c,e,"border",f))a.border=g;if(g=h.getStyleAttribute_(b,c,e,"fontFamily",f))switch(g){case "monospaceSerif":a.fontFamily="Courier New,Liberation Mono,Courier,monospace";break;case "proportionalSansSerif":a.fontFamily="Arial,Helvetica,Liberation Sans,sans-serif";break;case "sansSerif":a.fontFamily="sans-serif";break;case "monospaceSansSerif":a.fontFamily=
"Consolas,monospace";break;case "proportionalSerif":a.fontFamily="serif";break;default:a.fontFamily=g}(g=h.getStyleAttribute_(b,c,e,"fontWeight",f))&&"bold"==g&&(a.fontWeight=k.fontWeight.BOLD);g=h.getStyleAttribute_(b,c,e,"wrapOption",f);a.wrapLine=g&&"noWrap"==g?!1:!0;(g=h.getStyleAttribute_(b,c,e,"lineHeight",f))&&g.match(h.unitValues_)&&(a.lineHeight=g);(g=h.getStyleAttribute_(b,c,e,"fontSize",f))&&(g.match(h.unitValues_)||g.match(h.percentValue_))&&(a.fontSize=g);if(g=h.getStyleAttribute_(b,
c,e,"fontStyle",f))goog.asserts.assert(g.toUpperCase()in k.fontStyle,g.toUpperCase()+" Should be in Cue.fontStyle values!"),a.fontStyle=k.fontStyle[g.toUpperCase()];d&&(k=d.getAttribute("imageType")||d.getAttribute("imagetype"),g=d.getAttribute("encoding"),d=d.textContent.trim(),"PNG"==k&&"Base64"==g&&d&&(a.backgroundImage="data:image/png;base64,"+d));if(d=h.getStyleAttribute_(b,c,e,"textOutline",f))d=d.split(" "),d[0].match(h.unitValues_)?a.textStrokeColor=a.color:(a.textStrokeColor=d[0],d.shift()),
d[0]&&d[0].match(h.unitValues_)?a.textStrokeWidth=d[0]:a.textStrokeColor="";(d=h.getStyleAttribute_(b,c,e,"letterSpacing",f))&&d.match(h.unitValues_)&&(a.letterSpacing=d);(d=h.getStyleAttribute_(b,c,e,"linePadding",f))&&d.match(h.unitValues_)&&(a.linePadding=d);if(f=h.getStyleAttribute_(b,c,e,"opacity",f))a.opacity=parseFloat(f);(c=h.getStyleAttributeFromRegion_(c,e,"textDecoration"))&&h.addTextDecoration_(a,c);(b=h.getStyleAttributeFromElement_(b,e,"textDecoration"))&&h.addTextDecoration_(a,b)};
shaka.text.TtmlTextParser.addTextDecoration_=function(a,b){var c=shaka.text.Cue;b=$jscomp.makeIterator(b.split(" "));for(var d=b.next();!d.done;d=b.next())switch(d.value){case "underline":a.textDecoration.includes(c.textDecoration.UNDERLINE)||a.textDecoration.push(c.textDecoration.UNDERLINE);break;case "noUnderline":a.textDecoration.includes(c.textDecoration.UNDERLINE)&&shaka.util.ArrayUtils.remove(a.textDecoration,c.textDecoration.UNDERLINE);break;case "lineThrough":a.textDecoration.includes(c.textDecoration.LINE_THROUGH)||
a.textDecoration.push(c.textDecoration.LINE_THROUGH);break;case "noLineThrough":a.textDecoration.includes(c.textDecoration.LINE_THROUGH)&&shaka.util.ArrayUtils.remove(a.textDecoration,c.textDecoration.LINE_THROUGH);break;case "overline":a.textDecoration.includes(c.textDecoration.OVERLINE)||a.textDecoration.push(c.textDecoration.OVERLINE);break;case "noOverline":a.textDecoration.includes(c.textDecoration.OVERLINE)&&shaka.util.ArrayUtils.remove(a.textDecoration,c.textDecoration.OVERLINE)}};
shaka.text.TtmlTextParser.getStyleAttribute_=function(a,b,c,d,e){e=void 0===e?!0:e;var f=shaka.text.TtmlTextParser;return(a=f.getStyleAttributeFromElement_(a,c,d))?a:e?f.getStyleAttributeFromRegion_(b,c,d):null};shaka.text.TtmlTextParser.getStyleAttributeFromRegion_=function(a,b,c){if(!a)return null;var d=shaka.util.XmlUtils.getAttributeNSList(a,shaka.text.TtmlTextParser.styleNs_,c);return d?d:shaka.text.TtmlTextParser.getInheritedStyleAttribute_(a,b,c)};
shaka.text.TtmlTextParser.getStyleAttributeFromElement_=function(a,b,c){var d=shaka.util.XmlUtils.getAttributeNSList(a,shaka.text.TtmlTextParser.styleNs_,c);return d?d:shaka.text.TtmlTextParser.getInheritedStyleAttribute_(a,b,c)};
shaka.text.TtmlTextParser.getInheritedStyleAttribute_=function(a,b,c){var d=shaka.util.XmlUtils,e=shaka.text.TtmlTextParser.styleNs_,f=shaka.text.TtmlTextParser.styleEbuttsNs_;a=shaka.text.TtmlTextParser.getElementsFromCollection_(a,"style",b,"");for(var g=null,h=0;h<a.length;h++){var k=d.getAttributeNS(a[h],f,c);k||(k=d.getAttributeNSList(a[h],e,c));k||(k=shaka.text.TtmlTextParser.getStyleAttributeFromElement_(a[h],b,c));k&&(g=k)}return g};
shaka.text.TtmlTextParser.getElementsFromCollection_=function(a,b,c,d,e){var f=[];if(!a||1>c.length)return f;if(a=shaka.text.TtmlTextParser.getInheritedAttribute_(a,b,e))for(a=a.split(" "),a=$jscomp.makeIterator(a),b=a.next();!b.done;b=a.next()){b=b.value;e=$jscomp.makeIterator(c);for(var g=e.next();!g.done;g=e.next())if(g=g.value,d+g.getAttribute("xml:id")==b){f.push(g);break}}return f};
shaka.text.TtmlTextParser.getInheritedAttribute_=function(a,b,c){for(var d=null,e=shaka.util.XmlUtils;a&&!(d=c?e.getAttributeNS(a,c,b):a.getAttribute(b))&&(a=a.parentNode,a instanceof Element););return d};shaka.text.TtmlTextParser.resolveTime_=function(a,b,c,d){a=shaka.text.TtmlTextParser.parseTime_(a,b);null==c?c=a.start:null!=a.start&&(c+=a.start);null==d?d=a.end:null!=a.start&&(d+=a.start);return{start:c,end:d}};
shaka.text.TtmlTextParser.parseTime_=function(a,b){var c=shaka.text.TtmlTextParser.parseTimeAttribute_(a.getAttribute("begin"),b),d=shaka.text.TtmlTextParser.parseTimeAttribute_(a.getAttribute("end"),b);a=shaka.text.TtmlTextParser.parseTimeAttribute_(a.getAttribute("dur"),b);null==d&&null!=a&&(d=c+a);return{start:c,end:d}};
shaka.text.TtmlTextParser.parseTimeAttribute_=function(a,b){var c=null,d=shaka.text.TtmlTextParser;if(d.timeColonFormatFrames_.test(a))c=d.parseColonTimeWithFrames_(b,a);else if(d.timeColonFormat_.test(a))c=d.parseTimeFromRegex_(d.timeColonFormat_,a);else if(d.timeColonFormatMilliseconds_.test(a))c=d.parseTimeFromRegex_(d.timeColonFormatMilliseconds_,a);else if(d.timeFramesFormat_.test(a))c=d.parseFramesTime_(b,a);else if(d.timeTickFormat_.test(a))c=d.parseTickTime_(b,a);else if(d.timeHMSFormat_.test(a))c=
d.parseTimeFromRegex_(d.timeHMSFormat_,a);else if(a)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_CUE,"Could not parse cue time range in TTML");return c};shaka.text.TtmlTextParser.parseFramesTime_=function(a,b){b=shaka.text.TtmlTextParser.timeFramesFormat_.exec(b);return Number(b[1])/a.frameRate};
shaka.text.TtmlTextParser.parseTickTime_=function(a,b){b=shaka.text.TtmlTextParser.timeTickFormat_.exec(b);return Number(b[1])/a.tickRate};shaka.text.TtmlTextParser.parseColonTimeWithFrames_=function(a,b){b=shaka.text.TtmlTextParser.timeColonFormatFrames_.exec(b);var c=Number(b[1]),d=Number(b[2]),e=Number(b[3]),f=Number(b[4]);f+=(Number(b[5])||0)/a.subFrameRate;e+=f/a.frameRate;return e+60*d+3600*c};
shaka.text.TtmlTextParser.parseTimeFromRegex_=function(a,b){a=a.exec(b);return null==a||""==a[0]?null:(Number(a[4])||0)/1E3+(Number(a[3])||0)+60*(Number(a[2])||0)+3600*(Number(a[1])||0)};shaka.text.TtmlTextParser.getCellResolution_=function(a){if(!a)return null;var b=/^(\d+) (\d+)$/.exec(a);if(!b)return null;a=parseInt(b[1],10);b=parseInt(b[2],10);return{columns:a,rows:b}};goog.exportSymbol("shaka.text.TtmlTextParser",shaka.text.TtmlTextParser);
goog.exportProperty(shaka.text.TtmlTextParser.prototype,"parseMedia",shaka.text.TtmlTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.TtmlTextParser.prototype,"setSequenceMode",shaka.text.TtmlTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.TtmlTextParser.prototype,"parseInit",shaka.text.TtmlTextParser.prototype.parseInit);
shaka.text.TtmlTextParser.RateInfo_=function(a,b,c,d){this.frameRate=Number(a)||30;this.subFrameRate=Number(b)||1;this.tickRate=Number(d);0==this.tickRate&&(this.tickRate=a?this.frameRate*this.subFrameRate:1);c&&(a=/^(\d+) (\d+)$/g.exec(c))&&(this.frameRate*=Number(a[1])/Number(a[2]))};shaka.text.TtmlTextParser.percentValues_=/^(\d{1,2}(?:\.\d+)?|100(?:\.0+)?)% (\d{1,2}(?:\.\d+)?|100(?:\.0+)?)%$/;shaka.text.TtmlTextParser.percentValue_=/^(\d{1,2}(?:\.\d+)?|100)%$/;
shaka.text.TtmlTextParser.unitValues_=/^(\d+px|\d+em|\d*\.?\d+c)$/;shaka.text.TtmlTextParser.pixelValues_=/^(\d+)px (\d+)px$/;shaka.text.TtmlTextParser.timeColonFormatFrames_=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;shaka.text.TtmlTextParser.timeColonFormat_=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/;shaka.text.TtmlTextParser.timeColonFormatMilliseconds_=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/;shaka.text.TtmlTextParser.timeFramesFormat_=/^(\d*(?:\.\d*)?)f$/;
shaka.text.TtmlTextParser.timeTickFormat_=/^(\d*(?:\.\d*)?)t$/;shaka.text.TtmlTextParser.timeHMSFormat_=RegExp("^(?:(\\d*(?:\\.\\d*)?)h)?(?:(\\d*(?:\\.\\d*)?)m)?(?:(\\d*(?:\\.\\d*)?)s)?(?:(\\d*(?:\\.\\d*)?)ms)?$");shaka.text.TtmlTextParser.textAlignToLineAlign_={left:shaka.text.Cue.lineAlign.START,center:shaka.text.Cue.lineAlign.CENTER,right:shaka.text.Cue.lineAlign.END,start:shaka.text.Cue.lineAlign.START,end:shaka.text.Cue.lineAlign.END};
shaka.text.TtmlTextParser.textAlignToPositionAlign_={left:shaka.text.Cue.positionAlign.LEFT,center:shaka.text.Cue.positionAlign.CENTER,right:shaka.text.Cue.positionAlign.RIGHT};shaka.text.TtmlTextParser.parameterNs_=["http://www.w3.org/ns/ttml#parameter","http://www.w3.org/2006/10/ttaf1#parameter"];shaka.text.TtmlTextParser.styleNs_=["http://www.w3.org/ns/ttml#styling","http://www.w3.org/2006/10/ttaf1#styling"];shaka.text.TtmlTextParser.styleEbuttsNs_="urn:ebu:tt:style";
shaka.text.TtmlTextParser.smpteNsList_=["http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt","http://www.smpte-ra.org/schemas/2052-1/2013/smpte-tt"];shaka.text.TextEngine.registerParser("application/ttml+xml",function(){return new shaka.text.TtmlTextParser});shaka.text.Mp4TtmlParser=function(){this.parser_=new shaka.text.TtmlTextParser};
shaka.text.Mp4TtmlParser.prototype.parseInit=function(a){var b=shaka.util.Mp4Parser,c=!1;(new b).box("moov",b.children).box("trak",b.children).box("mdia",b.children).box("minf",b.children).box("stbl",b.children).fullBox("stsd",b.sampleDescription).box("stpp",function(d){c=!0;d.parser.stop()}).parse(a);if(!c)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_TTML);};shaka.text.Mp4TtmlParser.prototype.setSequenceMode=function(a){};
shaka.text.Mp4TtmlParser.prototype.parseMedia=function(a,b){var c=this,d=shaka.util.Mp4Parser,e=!1,f=[];(new d).box("mdat",d.allData(function(g){e=!0;f=f.concat(c.parser_.parseMedia(g,b))})).parse(a,!1);if(!e)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_TTML);return f};goog.exportSymbol("shaka.text.Mp4TtmlParser",shaka.text.Mp4TtmlParser);goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"parseMedia",shaka.text.Mp4TtmlParser.prototype.parseMedia);
goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"setSequenceMode",shaka.text.Mp4TtmlParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.Mp4TtmlParser.prototype,"parseInit",shaka.text.Mp4TtmlParser.prototype.parseInit);shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp"',function(){return new shaka.text.Mp4TtmlParser});shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml"',function(){return new shaka.text.Mp4TtmlParser});
shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.ttml.im1t"',function(){return new shaka.text.Mp4TtmlParser});shaka.text.TextEngine.registerParser('application/mp4; codecs="stpp.TTML.im1t"',function(){return new shaka.text.Mp4TtmlParser});shaka.text.VttTextParser=function(){this.sequenceMode_=!1};shaka.text.VttTextParser.prototype.parseInit=function(a){goog.asserts.assert(!1,"VTT does not have init segments")};shaka.text.VttTextParser.prototype.setSequenceMode=function(a){this.sequenceMode_=a};
shaka.text.VttTextParser.prototype.parseMedia=function(a,b){var c=shaka.text.VttTextParser;a=shaka.util.StringUtils.fromUTF8(a);a=a.replace(/\r\n|\r(?=[^\n]|$)/gm,"\n");a=a.split(/\n{2,}/m);if(!/^WEBVTT($|[ \t\n])/m.test(a[0]))throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_HEADER);var d=b.vttOffset;if(a[0].includes("X-TIMESTAMP-MAP")&&this.sequenceMode_){var e=a[0].match(/LOCAL:((?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{3}))/m),
f=a[0].match(/MPEGTS:(\d+)/m);if(e&&f){d=new shaka.util.TextParser(e[1]);d=shaka.text.VttTextParser.parseTime_(d);if(null==d)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_HEADER);f=Number(f[1]);e=shaka.text.VttTextParser.MPEG_TIMESCALE_;for(var g=shaka.text.VttTextParser.TS_ROLLOVER_/e,h=b.segmentStart-b.periodStart;h>=g;)h-=g,f+=shaka.text.VttTextParser.TS_ROLLOVER_;d=b.periodStart+f/e-d}}b=[];f=$jscomp.makeIterator(a[0].split("\n"));
for(e=f.next();!e.done;e=f.next())e=e.value,/^Region:/.test(e)&&(e=c.parseRegion_(e),b.push(e));f=new Map;c.addDefaultTextColor_(f);e=[];a=$jscomp.makeIterator(a.slice(1));for(g=a.next();!g.done;g=a.next())g=g.value.split("\n"),c.parseStyle_(g,f),(g=c.parseCue_(g,d,b,f))&&e.push(g);return e};
shaka.text.VttTextParser.addDefaultTextColor_=function(a){for(var b=$jscomp.makeIterator(Object.entries(shaka.text.Cue.defaultTextColor)),c=b.next();!c.done;c=b.next()){var d=$jscomp.makeIterator(c.value);c=d.next().value;d=d.next().value;var e=new shaka.text.Cue(0,0,"");e.color=d;a.set("."+c,e)}b=$jscomp.makeIterator(Object.entries(shaka.text.Cue.defaultTextBackgroundColor));for(c=b.next();!c.done;c=b.next())d=$jscomp.makeIterator(c.value),c=d.next().value,d=d.next().value,e=new shaka.text.Cue(0,
0,""),e.backgroundColor=d,a.set("."+c,e)};shaka.text.VttTextParser.parseRegion_=function(a){var b=shaka.text.VttTextParser;a=new shaka.util.TextParser(a);var c=new shaka.text.CueRegion;a.readWord();a.skipWhitespace();for(var d=a.readWord();d;)b.parseRegionSetting_(c,d)||shaka.log.warning("VTT parser encountered an invalid VTTRegion setting: ",d," The setting will be ignored."),a.skipWhitespace(),d=a.readWord();return c};
shaka.text.VttTextParser.parseStyle_=function(a,b){if((1!=a.length||a[0])&&!/^NOTE($|[ \t])/.test(a[0])&&"STYLE"==a[0]){for(var c=[],d=-1,e=1;e<a.length;e++)a[e].includes("::cue")&&(c.push([]),d=c.length-1),-1!=d&&(c[d].push(a[e]),a[e].includes("}")&&(d=-1));a=$jscomp.makeIterator(c);for(c=a.next();!c.done;c=a.next()){e=c.value;c="global";(d=e[0].match(/\((.*)\)/))&&(c=d.pop());d=e.slice(1,-1);e[0].includes("}")&&(e=/\{(.*?)\}/.exec(e[0]))&&(d=e[1].split(";"));(e=b.get(c))||(e=new shaka.text.Cue(0,
0,""));for(var f=!1,g=0;g<d.length;g++){var h=/^\s*([^:]+):\s*(.*)/.exec(d[g]);if(h){var k=h[1].trim(),l=h[2].trim().replace(";","");switch(k){case "background-color":case "background":f=!0;e.backgroundColor=l;break;case "color":f=!0;e.color=l;break;case "font-family":f=!0;e.fontFamily=l;break;case "font-size":f=!0;e.fontSize=l;break;case "font-weight":if(700<=parseInt(l,10)||"bold"==l)f=!0,e.fontWeight=shaka.text.Cue.fontWeight.BOLD;break;case "font-style":switch(l){case "normal":f=!0;e.fontStyle=
shaka.text.Cue.fontStyle.NORMAL;break;case "italic":f=!0;e.fontStyle=shaka.text.Cue.fontStyle.ITALIC;break;case "oblique":f=!0,e.fontStyle=shaka.text.Cue.fontStyle.OBLIQUE}break;case "opacity":f=!0;e.opacity=parseFloat(l);break;case "text-shadow":f=!0;e.textShadow=l;break;case "white-space":f=!0;e.wrapLine="noWrap"!=l;break;default:shaka.log.warning("VTT parser encountered an unsupported style: ",h)}}}f&&b.set(c,e)}}};
shaka.text.VttTextParser.parseCue_=function(a,b,c,d){var e=shaka.text.VttTextParser;if(1==a.length&&!a[0]||/^NOTE($|[ \t])/.test(a[0])||"STYLE"==a[0]||"REGION"==a[0])return null;var f=null;a[0].includes("--\x3e")||(f=a[0],a.splice(0,1));var g=new shaka.util.TextParser(a[0]),h=e.parseTime_(g),k=g.readRegex(/[ \t]+--\x3e[ \t]+/g),l=e.parseTime_(g);if(null==h||null==k||null==l)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_TEXT_CUE,
"Could not parse cue time range in WebVTT");h+=b;l+=b;b=a.slice(1).join("\n").trim();d.has("global")?(a=d.get("global").clone(),a.startTime=h,a.endTime=l,a.payload=""):a=new shaka.text.Cue(h,l,"");e.parseCueStyles(b,a,d);g.skipWhitespace();for(d=g.readWord();d;)e.parseCueSetting(a,d,c)||shaka.log.warning("VTT parser encountered an invalid VTT setting: ",d," The setting will be ignored."),g.skipWhitespace(),d=g.readWord();null!=f&&(a.id=f);return a};
shaka.text.VttTextParser.parseCueStyles=function(a,b,c){var d=shaka.text.VttTextParser;0===c.size&&d.addDefaultTextColor_(c);a=d.replaceColorPayload_(a);a=d.replaceKaraokeStylePayload_(a);a=d.replaceVoiceStylePayload_(a);var e=shaka.util.XmlUtils.parseXmlString("<span>"+a+"</span>","span");if(e){var f=[];e=e.childNodes;if(1==e.length){var g=e[0];if(g.nodeType==Node.TEXT_NODE||g.nodeType==Node.CDATA_SECTION_NODE){b.payload=d.htmlUnescape_(a);return}}a=$jscomp.makeIterator(e);for(e=a.next();!e.done;e=
a.next())d.generateCueFromElement_(e.value,b,f,c);b.nestedCues=f}else shaka.log.warning("The cue's markup could not be parsed: ",a),b.payload=d.htmlUnescape_(a)};
shaka.text.VttTextParser.replaceVoiceStylePayload_=function(a){for(var b=[],c=-1,d="",e=!1,f=0;f<a.length;f++)if("/"===a[f]){var g=a.indexOf(">",f);if(-1===g)return a;if((g=a.substring(f+1,g))&&"v"==g){e=!0;var h=null;b.length&&(h=b[b.length-1]);if(h){if(h===g)d+="/"+g+">";else{if(!h.startsWith("v")){d+=a[f];continue}d+="/"+h+">"}f+=g.length+1}else d+=a[f]}else d+=a[f]}else"<"===a[f]?(c=f+1,"v"!=a[c]&&(c=-1)):">"===a[f]&&0<c&&(b.push(a.substr(c,f-c)),c=-1),d+=a[f];a=$jscomp.makeIterator(b);for(b=
a.next();!b.done;b=a.next())b=b.value,c=b.replace(" ",".voice-"),d=d.replace("<"+b+">","<"+c+">"),d=d.replace("</"+b+">","</"+c+">"),e||(d+="</"+c+">");return d};
shaka.text.VttTextParser.replaceKaraokeStylePayload_=function(a){for(var b=[],c=-1,d=0;d<a.length;d++)"<"===a[d]?c=d+1:">"===a[d]&&0<c&&(c=a.substr(c,d-c),c.match(shaka.text.VttTextParser.timeFormat_)&&b.push(c),c=-1);b=$jscomp.makeIterator(b);for(d=b.next();!d.done;d=b.next())d=d.value,a=a.replace("<"+d+">",'<div time="'+d+'">'),a+="</div>";return a};
shaka.text.VttTextParser.replaceColorPayload_=function(a){for(var b=[],c=-1,d="",e=0;e<a.length;e++)if("/"===a[e]&&0<e&&"<"===a[e-1]){var f=a.indexOf(">",e);if(f<=e)return a;if((f=a.substring(e+1,f))&&"c"===f){var g=b.pop();g?g===f?(d+="/"+f+">",e+=f.length+1):g.startsWith("c.")?(e+=f.length+1,d+="/"+g+">"):d+=a[e]:d+=a[e]}else d+=a[e]}else"<"===a[e]?(c=e+1,"c"!=a[c]&&(c=-1)):">"===a[e]&&0<c&&(b.push(a.substr(c,e-c)),c=-1),d+=a[e];return d};
shaka.text.VttTextParser.getOrDefault_=function(a,b){return a&&0<a.length?a:b};shaka.text.VttTextParser.mergeStyle_=function(a,b){if(b){var c=shaka.text.VttTextParser;a.backgroundColor=c.getOrDefault_(b.backgroundColor,a.backgroundColor);a.color=c.getOrDefault_(b.color,a.color);a.fontFamily=c.getOrDefault_(b.fontFamily,a.fontFamily);a.fontSize=c.getOrDefault_(b.fontSize,a.fontSize);a.fontWeight=b.fontWeight;a.fontStyle=b.fontStyle;a.opacity=b.opacity;a.wrapLine=b.wrapLine}};
shaka.text.VttTextParser.generateCueFromElement_=function(a,b,c,d){var e=shaka.text.VttTextParser,f=b.clone();if(a.nodeType===Node.ELEMENT_NODE&&a.nodeName){var g=shaka.text.Cue.fontWeight.BOLD,h=shaka.text.Cue.fontStyle.ITALIC,k=shaka.text.Cue.textDecoration.UNDERLINE,l=a.nodeName.split(/(?=[ .])+/g);l=$jscomp.makeIterator(l);for(var m=l.next();!m.done;m=l.next()){var n=m=m.value;if(n.startsWith(".voice-")){var p=n.split("-").pop();n='v[voice="'+p+'"]';d.has(n)||(n="v[voice="+p+"]")}d.has(n)&&e.mergeStyle_(f,
d.get(n));switch(m){case "br":m=b.clone();m.lineBreak=!0;c.push(m);break;case "b":f.fontWeight=g;break;case "i":f.fontStyle=h;break;case "u":f.textDecoration.push(k);break;case "div":if(m=a.getAttribute("time"))if(m=new shaka.util.TextParser(m),m=shaka.text.VttTextParser.parseTime_(m))f.startTime=m}}}if(shaka.util.XmlUtils.isText(a))for(d=a.textContent.split("\n"),a=!0,d=$jscomp.makeIterator(d),g=d.next();!g.done;g=d.next())g=g.value,a||(a=b.clone(),a.lineBreak=!0,c.push(a)),0<g.length&&(a=f.clone(),
a.payload=e.htmlUnescape_(g),c.push(a)),a=!1;else for(b=$jscomp.makeIterator(a.childNodes),a=b.next();!a.done;a=b.next())e.generateCueFromElement_(a.value,f,c,d)};
shaka.text.VttTextParser.parseCueSetting=function(a,b,c){var d=shaka.text.VttTextParser,e;if(e=/^align:(start|middle|center|end|left|right)$/.exec(b))d.setTextAlign_(a,e[1]);else if(e=/^vertical:(lr|rl)$/.exec(b))d.setVerticalWritingMode_(a,e[1]);else if(e=/^size:([\d.]+)%$/.exec(b))a.size=Number(e[1]);else if(e=/^position:([\d.]+)%(?:,(line-left|line-right|center|start|end))?$/.exec(b))a.position=Number(e[1]),e[2]&&d.setPositionAlign_(a,e[2]);else if(e=/^region:(.*)$/.exec(b)){if(b=d.getRegionById_(c,
e[1]))a.region=b}else return d.parsedLineValueAndInterpretation_(a,b);return!0};shaka.text.VttTextParser.getRegionById_=function(a,b){a=a.filter(function(c){return c.id==b});if(!a.length)return shaka.log.warning("VTT parser could not find a region with id: ",b," The region will be ignored."),null;goog.asserts.assert(1==a.length,"VTTRegion ids should be unique!");return a[0]};
shaka.text.VttTextParser.parseRegionSetting_=function(a,b){var c;if(c=/^id=(.*)$/.exec(b))a.id=c[1];else if(c=/^width=(\d{1,2}|100)%$/.exec(b))a.width=Number(c[1]);else if(c=/^lines=(\d+)$/.exec(b))a.height=Number(c[1]),a.heightUnits=shaka.text.CueRegion.units.LINES;else if(c=/^regionanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/.exec(b))a.regionAnchorX=Number(c[1]),a.regionAnchorY=Number(c[2]);else if(c=/^viewportanchor=(\d{1,2}|100)%,(\d{1,2}|100)%$/.exec(b))a.viewportAnchorX=Number(c[1]),a.viewportAnchorY=
Number(c[2]);else if(/^scroll=up$/.exec(b))a.scroll=shaka.text.CueRegion.scrollMode.UP;else return!1;return!0};shaka.text.VttTextParser.setTextAlign_=function(a,b){var c=shaka.text.Cue;"middle"==b?a.textAlign=c.textAlign.CENTER:(goog.asserts.assert(b.toUpperCase()in c.textAlign,b.toUpperCase()+" Should be in Cue.textAlign values!"),a.textAlign=c.textAlign[b.toUpperCase()])};
shaka.text.VttTextParser.setPositionAlign_=function(a,b){var c=shaka.text.Cue;a.positionAlign="line-left"==b||"start"==b?c.positionAlign.LEFT:"line-right"==b||"end"==b?c.positionAlign.RIGHT:c.positionAlign.CENTER};shaka.text.VttTextParser.setVerticalWritingMode_=function(a,b){var c=shaka.text.Cue;a.writingMode="lr"==b?c.writingMode.VERTICAL_LEFT_TO_RIGHT:c.writingMode.VERTICAL_RIGHT_TO_LEFT};
shaka.text.VttTextParser.parsedLineValueAndInterpretation_=function(a,b){var c=shaka.text.Cue,d;if(d=/^line:([\d.]+)%(?:,(start|end|center))?$/.exec(b))a.lineInterpretation=c.lineInterpretation.PERCENTAGE,a.line=Number(d[1]),d[2]&&(goog.asserts.assert(d[2].toUpperCase()in c.lineAlign,d[2].toUpperCase()+" Should be in Cue.lineAlign values!"),a.lineAlign=c.lineAlign[d[2].toUpperCase()]);else if(d=/^line:(-?\d+)(?:,(start|end|center))?$/.exec(b))a.lineInterpretation=c.lineInterpretation.LINE_NUMBER,
a.line=Number(d[1]),d[2]&&(goog.asserts.assert(d[2].toUpperCase()in c.lineAlign,d[2].toUpperCase()+" Should be in Cue.lineAlign values!"),a.lineAlign=c.lineAlign[d[2].toUpperCase()]);else return!1;return!0};shaka.text.VttTextParser.parseTime_=function(a){a=a.readRegex(shaka.text.VttTextParser.timeFormat_);if(null==a)return null;var b=Number(a[2]),c=Number(a[3]);return 59<b||59<c?null:Number(a[4])/1E3+c+60*b+3600*(Number(a[1])||0)};
shaka.text.VttTextParser.htmlUnescape_=function(a){var b={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&nbsp;":"\u00a0","&lrm;":"\u200e","&rlm;":"\u200f"},c=/&(?:amp|lt|gt|quot|#(0+)?39|nbsp|lrm|rlm);/g,d=RegExp(c.source);return a&&d.test(a)?a.replace(c,function(e){return b[e]||"'"}):a||""};goog.exportSymbol("shaka.text.VttTextParser",shaka.text.VttTextParser);goog.exportProperty(shaka.text.VttTextParser.prototype,"parseMedia",shaka.text.VttTextParser.prototype.parseMedia);
goog.exportProperty(shaka.text.VttTextParser.prototype,"setSequenceMode",shaka.text.VttTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.VttTextParser.prototype,"parseInit",shaka.text.VttTextParser.prototype.parseInit);shaka.text.VttTextParser.MPEG_TIMESCALE_=9E4;shaka.text.VttTextParser.TS_ROLLOVER_=8589934592;shaka.text.VttTextParser.timeFormat_=/(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{2,3})/g;shaka.text.TextEngine.registerParser("text/vtt",function(){return new shaka.text.VttTextParser});
shaka.text.TextEngine.registerParser('text/vtt; codecs="vtt"',function(){return new shaka.text.VttTextParser});shaka.text.TextEngine.registerParser('text/vtt; codecs="wvtt"',function(){return new shaka.text.VttTextParser});shaka.text.Mp4VttParser=function(){this.timescale_=null};
shaka.text.Mp4VttParser.prototype.parseInit=function(a){var b=this,c=shaka.util.Mp4Parser,d=!1;(new c).box("moov",c.children).box("trak",c.children).box("mdia",c.children).fullBox("mdhd",function(e){goog.asserts.assert(0==e.version||1==e.version,"MDHD version can only be 0 or 1");e=shaka.util.Mp4BoxParsers.parseMDHD(e.reader,e.version);b.timescale_=e.timescale}).box("minf",c.children).box("stbl",c.children).fullBox("stsd",c.sampleDescription).box("wvtt",function(e){d=!0}).parse(a);if(!this.timescale_)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);if(!d)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);};shaka.text.Mp4VttParser.prototype.setSequenceMode=function(a){};
shaka.text.Mp4VttParser.prototype.parseMedia=function(a,b){if(!this.timescale_)throw shaka.log.error("No init segment for MP4+VTT!"),new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);var c=shaka.util.Mp4Parser,d=0,e=[],f,g=[],h=!1,k=!1,l=!1,m=null;(new c).box("moof",c.children).box("traf",c.children).fullBox("tfdt",function(t){h=!0;goog.asserts.assert(0==t.version||1==t.version,"TFDT version can only be 0 or 1");d=shaka.util.Mp4BoxParsers.parseTFDT(t.reader,
t.version).baseMediaDecodeTime}).fullBox("tfhd",function(t){goog.asserts.assert(null!=t.flags,"A TFHD box should have a valid flags value");m=shaka.util.Mp4BoxParsers.parseTFHD(t.reader,t.flags).defaultSampleDuration}).fullBox("trun",function(t){k=!0;goog.asserts.assert(null!=t.version,"A TRUN box should have a valid version value");goog.asserts.assert(null!=t.flags,"A TRUN box should have a valid flags value");e=shaka.util.Mp4BoxParsers.parseTRUN(t.reader,t.version,t.flags).sampleData}).box("mdat",
c.allData(function(t){goog.asserts.assert(!l,"VTT cues in mp4 with multiple MDAT are not currently supported");l=!0;f=t})).parse(a,!1);if(!l&&!h&&!k)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,shaka.util.Error.Code.INVALID_MP4_VTT);a=d;c=new shaka.util.DataViewReader(f,shaka.util.DataViewReader.Endianness.BIG_ENDIAN);for(var n=$jscomp.makeIterator(e),p=n.next();!p.done;p=n.next()){p=p.value;var q=p.sampleDuration||m,r=p.sampleCompositionTimeOffset?
d+p.sampleCompositionTimeOffset:a;a=r+(q||0);var w=0;do{var u=c.readUint32();w+=u;var v=c.readUint32();v=shaka.util.Mp4Parser.typeToString(v);var x=null;"vttc"==v?8<u&&(x=c.readBytes(u-8)):("vtte"!=v&&shaka.log.error("Unknown box "+v+"! Skipping!"),c.skip(u-8));q?x&&(goog.asserts.assert(null!=this.timescale_,"Timescale should not be null!"),u=shaka.text.Mp4VttParser.parseVTTC_(x,b.periodStart+r/this.timescale_,b.periodStart+a/this.timescale_),g.push(u)):shaka.log.error("WVTT sample duration unknown, and no default found!");
goog.asserts.assert(!p.sampleSize||w<=p.sampleSize,"The samples do not fit evenly into the sample sizes given in the TRUN box!")}while(p.sampleSize&&w<p.sampleSize)}goog.asserts.assert(!c.hasMoreData(),"MDAT which contain VTT cues and non-VTT data are not currently supported!");return g.filter(shaka.util.Functional.isNotNull)};
shaka.text.Mp4VttParser.parseVTTC_=function(a,b,c){var d,e,f;(new shaka.util.Mp4Parser).box("payl",shaka.util.Mp4Parser.allData(function(g){d=shaka.util.StringUtils.fromUTF8(g)})).box("iden",shaka.util.Mp4Parser.allData(function(g){e=shaka.util.StringUtils.fromUTF8(g)})).box("sttg",shaka.util.Mp4Parser.allData(function(g){f=shaka.util.StringUtils.fromUTF8(g)})).parse(a);return d?shaka.text.Mp4VttParser.assembleCue_(d,e,f,b,c):null};
shaka.text.Mp4VttParser.assembleCue_=function(a,b,c,d,e){d=new shaka.text.Cue(d,e,"");e=new Map;shaka.text.VttTextParser.parseCueStyles(a,d,e);b&&(d.id=b);if(c)for(a=new shaka.util.TextParser(c),b=a.readWord();b;)shaka.text.VttTextParser.parseCueSetting(d,b,[])||shaka.log.warning("VTT parser encountered an invalid VTT setting: ",b," The setting will be ignored."),a.skipWhitespace(),b=a.readWord();return d};goog.exportSymbol("shaka.text.Mp4VttParser",shaka.text.Mp4VttParser);
goog.exportProperty(shaka.text.Mp4VttParser.prototype,"parseMedia",shaka.text.Mp4VttParser.prototype.parseMedia);goog.exportProperty(shaka.text.Mp4VttParser.prototype,"setSequenceMode",shaka.text.Mp4VttParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.Mp4VttParser.prototype,"parseInit",shaka.text.Mp4VttParser.prototype.parseInit);shaka.text.TextEngine.registerParser('application/mp4; codecs="wvtt"',function(){return new shaka.text.Mp4VttParser});shaka.text.SbvTextParser=function(){};shaka.text.SbvTextParser.prototype.parseInit=function(a){goog.asserts.assert(!1,"SubViewer does not have init segments")};shaka.text.SbvTextParser.prototype.setSequenceMode=function(a){};
shaka.text.SbvTextParser.prototype.parseMedia=function(a,b){b=shaka.text.SbvTextParser;var c=shaka.util.StringUtils.fromUTF8(a).replace(/\r+/g,"");c=c.trim();a=[];if(""==c)return a;c=c.split("\n\n");c=$jscomp.makeIterator(c);for(var d=c.next();!d.done;d=c.next()){var e=d.value.split("\n"),f=new shaka.util.TextParser(e[0]);d=b.parseTime_(f);var g=f.readRegex(/,/g);f=b.parseTime_(f);if(null==d||null==g||null==f)throw new shaka.util.Error(shaka.util.Error.Severity.CRITICAL,shaka.util.Error.Category.TEXT,
shaka.util.Error.Code.INVALID_TEXT_CUE,"Could not parse cue time range in SubViewer");e=e.slice(1).join("\n").trim();d=new shaka.text.Cue(d,f,e);a.push(d)}return a};shaka.text.SbvTextParser.parseTime_=function(a){a=a.readRegex(/(?:(\d{1,}):)?(\d{2}):(\d{2})\.(\d{2,3})/g);if(null==a)return null;var b=Number(a[2]),c=Number(a[3]);return 59<b||59<c?null:Number(a[4])/1E3+c+60*b+3600*(Number(a[1])||0)};goog.exportSymbol("shaka.text.SbvTextParser",shaka.text.SbvTextParser);
goog.exportProperty(shaka.text.SbvTextParser.prototype,"parseMedia",shaka.text.SbvTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.SbvTextParser.prototype,"setSequenceMode",shaka.text.SbvTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.SbvTextParser.prototype,"parseInit",shaka.text.SbvTextParser.prototype.parseInit);shaka.text.TextEngine.registerParser("text/x-subviewer",function(){return new shaka.text.SbvTextParser});shaka.text.SrtTextParser=function(){this.parser_=new shaka.text.VttTextParser};shaka.text.SrtTextParser.prototype.parseInit=function(a){goog.asserts.assert(!1,"SRT does not have init segments")};shaka.text.SrtTextParser.prototype.setSequenceMode=function(a){};shaka.text.SrtTextParser.prototype.parseMedia=function(a,b){var c=shaka.text.SrtTextParser,d=shaka.util.BufferUtils,e=shaka.util.StringUtils;a=e.fromUTF8(a);c=c.srt2webvtt(a);d=d.toUint8(e.toUTF8(c));return this.parser_.parseMedia(d,b)};
shaka.text.SrtTextParser.srt2webvtt=function(a){var b=shaka.text.SrtTextParser,c="WEBVTT\n\n";if(""==a)return c;a=a.replace(/\r+/g,"");a=a.trim();a=a.split("\n\n");a=$jscomp.makeIterator(a);for(var d=a.next();!d.done;d=a.next())c+=b.convertSrtCue_(d.value);return c};shaka.text.SrtTextParser.convertSrtCue_=function(a){a=a.split(/\n/);a[0].match(/\d+/)&&a.shift();a[0]=a[0].replace(/,/g,".");return a.join("\n")+"\n\n"};goog.exportSymbol("shaka.text.SrtTextParser",shaka.text.SrtTextParser);
goog.exportProperty(shaka.text.SrtTextParser,"srt2webvtt",shaka.text.SrtTextParser.srt2webvtt);goog.exportProperty(shaka.text.SrtTextParser.prototype,"parseMedia",shaka.text.SrtTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.SrtTextParser.prototype,"setSequenceMode",shaka.text.SrtTextParser.prototype.setSequenceMode);goog.exportProperty(shaka.text.SrtTextParser.prototype,"parseInit",shaka.text.SrtTextParser.prototype.parseInit);shaka.text.TextEngine.registerParser("text/srt",function(){return new shaka.text.SrtTextParser});shaka.text.SsaTextParser=function(){};shaka.text.SsaTextParser.prototype.parseInit=function(a){goog.asserts.assert(!1,"SSA does not have init segments")};shaka.text.SsaTextParser.prototype.setSequenceMode=function(a){};
shaka.text.SsaTextParser.prototype.parseMedia=function(a,b){b=shaka.text.SsaTextParser;var c="",d="";a=shaka.util.StringUtils.fromUTF8(a).split(/\r?\n\s*\r?\n/);a=$jscomp.makeIterator(a);for(var e=a.next();!e.done;e=a.next()){e=e.value;var f=b.ssaContent_.exec(e);if(f){var g=f[1];f=f[2];if("V4 Styles"==g||"V4+ Styles"==g){c=f;continue}if("Events"==g){d=f;continue}}shaka.log.warning("SsaTextParser parser encountered an unknown part.",e)}a=[];e=null;c=c.split(/\r?\n/);c=$jscomp.makeIterator(c);for(f=
c.next();!f.done;f=c.next())if(g=f.value,!/^\s*;/.test(g)&&(f=b.lineParts_.exec(g)))if(g=f[1].trim(),f=f[2].trim(),"Format"==g)e=f.split(b.valuesFormat_);else if("Style"==g){g=f.split(b.valuesFormat_);f={};for(var h=0;h<e.length&&h<g.length;h++)f[e[h]]=g[h];a.push(f)}e=[];c=null;g=d.split(/\r?\n/);d={};g=$jscomp.makeIterator(g);for(f=g.next();!f.done;d={$jscomp$loop$prop$styleName$692:d.$jscomp$loop$prop$styleName$692},f=g.next())if(f=f.value,!/^\s*;/.test(f)&&(h=b.lineParts_.exec(f)))if(f=h[1].trim(),
h=h[2].trim(),"Format"==f)c=h.split(b.valuesFormat_);else if("Dialogue"==f){h=h.split(b.valuesFormat_);f={};for(var k=0;k<c.length&&k<h.length;k++)f[c[k]]=h[k];k=b.parseTime_(f.Start);var l=b.parseTime_(f.End);h=h.slice(c.length-1).join(",").replace(/\\N/g,"\n").replace(/\{[^}]+\}/g,"");h=new shaka.text.Cue(k,l,h);d.$jscomp$loop$prop$styleName$692=f.Style;(f=a.find(function(m){return function(n){return n.Name==m.$jscomp$loop$prop$styleName$692}}(d)))&&b.addStyle_(h,f);e.push(h)}return e};
shaka.text.SsaTextParser.addStyle_=function(a,b){var c=shaka.text.Cue,d=shaka.text.SsaTextParser,e=b.Fontname;e&&(a.fontFamily=e);if(e=b.Fontsize)a.fontSize=e+"px";if(e=b.PrimaryColour)if(e=d.parseSsaColor_(e))a.color=e;if(e=b.BackColour)if(d=d.parseSsaColor_(e))a.backgroundColor=d;b.Bold&&(a.fontWeight=c.fontWeight.BOLD);b.Italic&&(a.fontStyle=c.fontStyle.ITALIC);b.Underline&&a.textDecoration.push(c.textDecoration.UNDERLINE);if(d=b.Spacing)a.letterSpacing=d+"px";if(d=b.Alignment)switch(parseInt(d,
10)){case 1:a.displayAlign=c.displayAlign.AFTER;a.textAlign=c.textAlign.START;break;case 2:a.displayAlign=c.displayAlign.AFTER;a.textAlign=c.textAlign.CENTER;break;case 3:a.displayAlign=c.displayAlign.AFTER;a.textAlign=c.textAlign.END;break;case 5:a.displayAlign=c.displayAlign.BEFORE;a.textAlign=c.textAlign.START;break;case 6:a.displayAlign=c.displayAlign.BEFORE;a.textAlign=c.textAlign.CENTER;break;case 7:a.displayAlign=c.displayAlign.BEFORE;a.textAlign=c.textAlign.END;break;case 9:a.displayAlign=
c.displayAlign.CENTER;a.textAlign=c.textAlign.START;break;case 10:a.displayAlign=c.displayAlign.CENTER;a.textAlign=c.textAlign.CENTER;break;case 11:a.displayAlign=c.displayAlign.CENTER,a.textAlign=c.textAlign.END}if(b=b.AlphaLevel)a.opacity=parseFloat(b)};shaka.text.SsaTextParser.parseSsaColor_=function(a){a=parseInt(a.replace("&H",""),16);return 0<=a?"rgba("+(a&255)+","+(a>>8&255)+","+(a>>16&255)+","+(a>>24&255^255)/255+")":null};
shaka.text.SsaTextParser.parseTime_=function(a){var b=shaka.text.SsaTextParser.timeFormat_.exec(a);a=b[1]?parseInt(b[1].replace(":",""),10):0;var c=parseInt(b[2],10);b=parseFloat(b[3]);return 3600*a+60*c+b};goog.exportSymbol("shaka.text.SsaTextParser",shaka.text.SsaTextParser);goog.exportProperty(shaka.text.SsaTextParser.prototype,"parseMedia",shaka.text.SsaTextParser.prototype.parseMedia);goog.exportProperty(shaka.text.SsaTextParser.prototype,"setSequenceMode",shaka.text.SsaTextParser.prototype.setSequenceMode);
goog.exportProperty(shaka.text.SsaTextParser.prototype,"parseInit",shaka.text.SsaTextParser.prototype.parseInit);shaka.text.SsaTextParser.ssaContent_=/^\s*\[([^\]]+)\]\r?\n([\s\S]*)/;shaka.text.SsaTextParser.lineParts_=/^\s*([^:]+):\s*(.*)/;shaka.text.SsaTextParser.valuesFormat_=/\s*,\s*/;shaka.text.SsaTextParser.timeFormat_=/^(\d+:)?(\d{1,2}):(\d{1,2}(?:[.]\d{1,3})?)?$/;shaka.text.TextEngine.registerParser("text/x-ssa",function(){return new shaka.text.SsaTextParser});/*
 @license
 EME Encryption Scheme Polyfill
 Copyright 2019 Google LLC
 SPDX-License-Identifier: Apache-2.0
*/
var EmeEncryptionSchemePolyfill=function(){};
EmeEncryptionSchemePolyfill.install=function(){EmeEncryptionSchemePolyfill.originalRMKSA_?console.debug("EmeEncryptionSchemePolyfill: Already installed."):navigator.requestMediaKeySystemAccess&&MediaKeySystemAccess.prototype.getConfiguration?(EmeEncryptionSchemePolyfill.originalRMKSA_=navigator.requestMediaKeySystemAccess,console.debug("EmeEncryptionSchemePolyfill: Waiting to detect encryptionScheme support."),navigator.requestMediaKeySystemAccess=EmeEncryptionSchemePolyfill.probeRMKSA_):console.debug("EmeEncryptionSchemePolyfill: EME not found")};
EmeEncryptionSchemePolyfill.probeRMKSA_=function(a,b){var c=this,d;return $jscomp.asyncExecutePromiseGeneratorProgram(function(e){if(1==e.nextAddress)return console.assert(c==navigator,'bad "this" for requestMediaKeySystemAccess'),e.yield(EmeEncryptionSchemePolyfill.originalRMKSA_.call(c,a,b),2);d=e.yieldResult;if(hasEncryptionScheme(d))return console.debug("EmeEncryptionSchemePolyfill: Native encryptionScheme support found."),navigator.requestMediaKeySystemAccess=EmeEncryptionSchemePolyfill.originalRMKSA_,
e.return(d);console.debug("EmeEncryptionSchemePolyfill: No native encryptionScheme support found. Patching encryptionScheme support.");navigator.requestMediaKeySystemAccess=EmeEncryptionSchemePolyfill.polyfillRMKSA_;return e.return(EmeEncryptionSchemePolyfill.polyfillRMKSA_.call(c,a,b))})};
EmeEncryptionSchemePolyfill.polyfillRMKSA_=function(a,b){var c=this,d,e,f,g,h,k,l,m,n,p;return $jscomp.asyncExecutePromiseGeneratorProgram(function(q){if(1==q.nextAddress){console.assert(c==navigator,'bad "this" for requestMediaKeySystemAccess');d=guessSupportedScheme(a);e=[];f=$jscomp.makeIterator(b);for(g=f.next();!g.done;g=f.next())h=g.value,k=EmeEncryptionSchemePolyfill.filterCapabilities_(h.videoCapabilities,d),l=EmeEncryptionSchemePolyfill.filterCapabilities_(h.audioCapabilities,d),h.videoCapabilities&&
h.videoCapabilities.length&&!k.length||h.audioCapabilities&&h.audioCapabilities.length&&!l.length||(m=Object.assign({},h),m.videoCapabilities=k,m.audioCapabilities=l,e.push(m));if(!e.length)throw n=Error("Unsupported keySystem or supportedConfigurations."),n.name="NotSupportedError",n.code=DOMException.NOT_SUPPORTED_ERR,n;return q.yield(EmeEncryptionSchemePolyfill.originalRMKSA_.call(c,a,e),2)}p=q.yieldResult;return q.return(new EmeEncryptionSchemePolyfillMediaKeySystemAccess(p,d))})};
EmeEncryptionSchemePolyfill.filterCapabilities_=function(a,b){return a?a.filter(function(c){return!c.encryptionScheme||c.encryptionScheme==b}):a};goog.exportSymbol("EmeEncryptionSchemePolyfill",EmeEncryptionSchemePolyfill);goog.exportProperty(EmeEncryptionSchemePolyfill,"install",EmeEncryptionSchemePolyfill.install);var McEncryptionSchemePolyfill=function(){};
McEncryptionSchemePolyfill.install=function(){McEncryptionSchemePolyfill.originalDecodingInfo_?console.debug("McEncryptionSchemePolyfill: Already installed."):navigator.mediaCapabilities?(McEncryptionSchemePolyfill.originalDecodingInfo_=navigator.mediaCapabilities.decodingInfo,console.debug("McEncryptionSchemePolyfill: Waiting to detect encryptionScheme support."),navigator.mediaCapabilities.decodingInfo=McEncryptionSchemePolyfill.probeDecodingInfo_):console.debug("McEncryptionSchemePolyfill: MediaCapabilities not found")};
McEncryptionSchemePolyfill.probeDecodingInfo_=function(a){var b=this,c,d,e;return $jscomp.asyncExecutePromiseGeneratorProgram(function(f){switch(f.nextAddress){case 1:return console.assert(b==navigator.mediaCapabilities,'bad "this" for decodingInfo'),f.yield(McEncryptionSchemePolyfill.originalDecodingInfo_.call(b,a),2);case 2:c=f.yieldResult;if(!a.keySystemConfiguration)return f.return(c);if((d=c.keySystemAccess)&&hasEncryptionScheme(d))return console.debug("McEncryptionSchemePolyfill: Native encryptionScheme support found."),
navigator.mediaCapabilities.decodingInfo=McEncryptionSchemePolyfill.originalDecodingInfo_,f.return(c);console.debug("McEncryptionSchemePolyfill: No native encryptionScheme support found. Patching encryptionScheme support.");navigator.mediaCapabilities.decodingInfo=McEncryptionSchemePolyfill.polyfillDecodingInfo_;if(d){f.jumpTo(3);break}e=c;return f.yield(McEncryptionSchemePolyfill.getMediaKeySystemAccess_(a),4);case 4:return e.keySystemAccess=f.yieldResult,f.return(c);case 3:return f.return(McEncryptionSchemePolyfill.polyfillDecodingInfo_.call(b,
a))}})};
McEncryptionSchemePolyfill.polyfillDecodingInfo_=function(a){var b=this,c,d,e,f,g,h,k,l;return $jscomp.asyncExecutePromiseGeneratorProgram(function(m){switch(m.nextAddress){case 1:return console.assert(b==navigator.mediaCapabilities,'bad "this" for decodingInfo'),c=null,a.keySystemConfiguration&&(d=a.keySystemConfiguration,e=d.keySystem,f=d.audio&&d.audio.encryptionScheme,g=d.video&&d.video.encryptionScheme,c=guessSupportedScheme(e),h={powerEfficient:!1,smooth:!1,supported:!1,keySystemAccess:null,configuration:a},
f&&f!=c||g&&g!=c)?m.return(h):m.yield(McEncryptionSchemePolyfill.originalDecodingInfo_.call(b,a),2);case 2:k=m.yieldResult;if(k.keySystemAccess){k.keySystemAccess=new EmeEncryptionSchemePolyfillMediaKeySystemAccess(k.keySystemAccess,c);m.jumpTo(3);break}if(!a.keySystemConfiguration){m.jumpTo(3);break}l=k;return m.yield(McEncryptionSchemePolyfill.getMediaKeySystemAccess_(a),5);case 5:l.keySystemAccess=m.yieldResult;case 3:return m.return(k)}})};
McEncryptionSchemePolyfill.getMediaKeySystemAccess_=function(a){var b,c;return $jscomp.asyncExecutePromiseGeneratorProgram(function(d){if(1==d.nextAddress)return b=McEncryptionSchemePolyfill.convertToMediaKeySystemConfig_(a),d.yield(navigator.requestMediaKeySystemAccess(a.keySystemConfiguration.keySystem,[b]),2);c=d.yieldResult;return d.return(c)})};
McEncryptionSchemePolyfill.convertToMediaKeySystemConfig_=function(a){var b=a.keySystemConfiguration,c=[],d=[];b.audio&&c.push({robustness:b.audio.robustness||"",contentType:a.audio.contentType});b.video&&d.push({robustness:b.video.robustness||"",contentType:a.video.contentType});a={initDataTypes:b.initDataType?[b.initDataType]:[],distinctiveIdentifier:b.distinctiveIdentifier,persistentState:b.persistentState,sessionTypes:b.sessionTypes};c.length&&(a.audioCapabilities=c);d.length&&(a.videoCapabilities=
d);return a};goog.exportSymbol("McEncryptionSchemePolyfill",McEncryptionSchemePolyfill);goog.exportProperty(McEncryptionSchemePolyfill,"install",McEncryptionSchemePolyfill.install);var EmeEncryptionSchemePolyfillMediaKeySystemAccess=function(a,b){this.mksa_=a;this.scheme_=b;this.keySystem=a.keySystem};
EmeEncryptionSchemePolyfillMediaKeySystemAccess.prototype.getConfiguration=function(){var a=this.mksa_.getConfiguration();if(a.videoCapabilities)for(var b=$jscomp.makeIterator(a.videoCapabilities),c=b.next();!c.done;c=b.next())c.value.encryptionScheme=this.scheme_;if(a.audioCapabilities)for(b=$jscomp.makeIterator(a.audioCapabilities),c=b.next();!c.done;c=b.next())c.value.encryptionScheme=this.scheme_;return a};EmeEncryptionSchemePolyfillMediaKeySystemAccess.prototype.createMediaKeys=function(){return this.mksa_.createMediaKeys()};
function guessSupportedScheme(a){if(a.startsWith("com.widevine")||a.startsWith("com.microsoft")||a.startsWith("com.chromecast")||a.startsWith("com.adobe")||a.startsWith("org.w3"))return"cenc";if(a.startsWith("com.apple"))return"cbcs-1-9";console.warn("EmeEncryptionSchemePolyfill: Unknown key system:",a,"Please contribute!");return null}
function hasEncryptionScheme(a){a=a.getConfiguration();var b=a.audioCapabilities&&a.audioCapabilities[0];return(a=a.videoCapabilities&&a.videoCapabilities[0]||b)&&void 0!==a.encryptionScheme?!0:!1}var EncryptionSchemePolyfills=function(){};EncryptionSchemePolyfills.install=function(){EmeEncryptionSchemePolyfill.install();McEncryptionSchemePolyfill.install()};goog.exportSymbol("EncryptionSchemePolyfills",EncryptionSchemePolyfills);goog.exportProperty(EncryptionSchemePolyfills,"install",EncryptionSchemePolyfills.install);
(function(){"undefined"!==typeof module&&module.exports&&(module.exports=EncryptionSchemePolyfills)})();}).call(exportTo,innerGlobal,innerGlobal,undefined);if(typeof exports!="undefined")for(var k in exportTo.shaka)exports[k]=exportTo.shaka[k];else if(typeof define=="function"&&define.amd)define(function(){return exportTo.shaka});else _fakeGlobal.shaka=exportTo.shaka})();

var lib_export = exportTo.shaka;
if (typeof module !== 'undefined')
	module.exports = lib_export;
