source-updater.js 25.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
/**
 * @file source-updater.js
 */
import videojs from 'video.js';
import logger from './util/logger';
import noop from './util/noop';
import { bufferIntersection } from './ranges.js';
import {getMimeForCodec} from '@videojs/vhs-utils/es/codecs.js';
import window from 'global/window';
import toTitleCase from './util/to-title-case.js';
import { QUOTA_EXCEEDED_ERR } from './error-codes';

const bufferTypes = [
  'video',
  'audio'
];

const updating = (type, sourceUpdater) => {
  const sourceBuffer = sourceUpdater[`${type}Buffer`];

  return (sourceBuffer && sourceBuffer.updating) || sourceUpdater.queuePending[type];
};

const nextQueueIndexOfType = (type, queue) => {
  for (let i = 0; i < queue.length; i++) {
    const queueEntry = queue[i];

    if (queueEntry.type === 'mediaSource') {
      // If the next entry is a media source entry (uses multiple source buffers), block
      // processing to allow it to go through first.
      return null;
    }

    if (queueEntry.type === type) {
      return i;
    }
  }

  return null;
};

const shiftQueue = (type, sourceUpdater) => {
  if (sourceUpdater.queue.length === 0) {
    return;
  }

  let queueIndex = 0;
  let queueEntry = sourceUpdater.queue[queueIndex];

  if (queueEntry.type === 'mediaSource') {
    if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
      sourceUpdater.queue.shift();
      queueEntry.action(sourceUpdater);

      if (queueEntry.doneFn) {
        queueEntry.doneFn();
      }

      // Only specific source buffer actions must wait for async updateend events. Media
      // Source actions process synchronously. Therefore, both audio and video source
      // buffers are now clear to process the next queue entries.
      shiftQueue('audio', sourceUpdater);
      shiftQueue('video', sourceUpdater);
    }

    // Media Source actions require both source buffers, so if the media source action
    // couldn't process yet (because one or both source buffers are busy), block other
    // queue actions until both are available and the media source action can process.
    return;
  }

  if (type === 'mediaSource') {
    // If the queue was shifted by a media source action (this happens when pushing a
    // media source action onto the queue), then it wasn't from an updateend event from an
    // audio or video source buffer, so there's no change from previous state, and no
    // processing should be done.
    return;
  }

  // Media source queue entries don't need to consider whether the source updater is
  // started (i.e., source buffers are created) as they don't need the source buffers, but
  // source buffer queue entries do.
  if (
    !sourceUpdater.ready() ||
    sourceUpdater.mediaSource.readyState === 'closed' ||
    updating(type, sourceUpdater)
  ) {
    return;
  }

  if (queueEntry.type !== type) {
    queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);

    if (queueIndex === null) {
      // Either there's no queue entry that uses this source buffer type in the queue, or
      // there's a media source queue entry before the next entry of this type, in which
      // case wait for that action to process first.
      return;
    }

    queueEntry = sourceUpdater.queue[queueIndex];
  }

  sourceUpdater.queue.splice(queueIndex, 1);
  // Keep a record that this source buffer type is in use.
  //
  // The queue pending operation must be set before the action is performed in the event
  // that the action results in a synchronous event that is acted upon. For instance, if
  // an exception is thrown that can be handled, it's possible that new actions will be
  // appended to an empty queue and immediately executed, but would not have the correct
  // pending information if this property was set after the action was performed.
  sourceUpdater.queuePending[type] = queueEntry;
  queueEntry.action(type, sourceUpdater);

  if (!queueEntry.doneFn) {
    // synchronous operation, process next entry
    sourceUpdater.queuePending[type] = null;
    shiftQueue(type, sourceUpdater);
    return;
  }
};

const cleanupBuffer = (type, sourceUpdater) => {
  const buffer = sourceUpdater[`${type}Buffer`];
  const titleType = toTitleCase(type);

  if (!buffer) {
    return;
  }

  buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);

  sourceUpdater.codecs[type] = null;
  sourceUpdater[`${type}Buffer`] = null;
};

const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer &&
  Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;

const actions = {
  appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
    const sourceBuffer = sourceUpdater[`${type}Buffer`];

    // can't do anything if the media source / source buffer is null
    // or the media source does not contain this source buffer.
    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
      return;
    }

    sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);

    try {
      sourceBuffer.appendBuffer(bytes);
    } catch (e) {
      sourceUpdater.logger_(`Error with code ${e.code} ` +
        (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') +
        `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
      sourceUpdater.queuePending[type] = null;
      onError(e);
    }
  },
  remove: (start, end) => (type, sourceUpdater) => {
    const sourceBuffer = sourceUpdater[`${type}Buffer`];

    // can't do anything if the media source / source buffer is null
    // or the media source does not contain this source buffer.
    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
      return;
    }

    sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
    try {
      sourceBuffer.remove(start, end);
    } catch (e) {
      sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
    }
  },
  timestampOffset: (offset) => (type, sourceUpdater) => {
    const sourceBuffer = sourceUpdater[`${type}Buffer`];

    // can't do anything if the media source / source buffer is null
    // or the media source does not contain this source buffer.
    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
      return;
    }

    sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);

    sourceBuffer.timestampOffset = offset;
  },
  callback: (callback) => (type, sourceUpdater) => {
    callback();
  },
  endOfStream: (error) => (sourceUpdater) => {
    if (sourceUpdater.mediaSource.readyState !== 'open') {
      return;
    }
    sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);

    try {
      sourceUpdater.mediaSource.endOfStream(error);
    } catch (e) {
      videojs.log.warn('Failed to call media source endOfStream', e);
    }
  },
  duration: (duration) => (sourceUpdater) => {
    sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
    try {
      sourceUpdater.mediaSource.duration = duration;
    } catch (e) {
      videojs.log.warn('Failed to set media source duration', e);
    }
  },
  abort: () => (type, sourceUpdater) => {
    if (sourceUpdater.mediaSource.readyState !== 'open') {
      return;
    }
    const sourceBuffer = sourceUpdater[`${type}Buffer`];

    // can't do anything if the media source / source buffer is null
    // or the media source does not contain this source buffer.
    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
      return;
    }

    sourceUpdater.logger_(`calling abort on ${type}Buffer`);
    try {
      sourceBuffer.abort();
    } catch (e) {
      videojs.log.warn(`Failed to abort on ${type}Buffer`, e);
    }
  },
  addSourceBuffer: (type, codec) => (sourceUpdater) => {
    const titleType = toTitleCase(type);
    const mime = getMimeForCodec(codec);

    sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);

    const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);

    sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
    sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
    sourceUpdater.codecs[type] = codec;
    sourceUpdater[`${type}Buffer`] = sourceBuffer;
  },
  removeSourceBuffer: (type) => (sourceUpdater) => {
    const sourceBuffer = sourceUpdater[`${type}Buffer`];

    cleanupBuffer(type, sourceUpdater);

    // can't do anything if the media source / source buffer is null
    // or the media source does not contain this source buffer.
    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
      return;
    }

    sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);

    try {
      sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
    } catch (e) {
      videojs.log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
    }
  },
  changeType: (codec) => (type, sourceUpdater) => {
    const sourceBuffer = sourceUpdater[`${type}Buffer`];
    const mime = getMimeForCodec(codec);

    // can't do anything if the media source / source buffer is null
    // or the media source does not contain this source buffer.
    if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
      return;
    }

    // do not update codec if we don't need to.
    if (sourceUpdater.codecs[type] === codec) {
      return;
    }

    sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);

    sourceBuffer.changeType(mime);
    sourceUpdater.codecs[type] = codec;
  }
};

const pushQueue = ({type, sourceUpdater, action, doneFn, name}) => {
  sourceUpdater.queue.push({
    type,
    action,
    doneFn,
    name
  });
  shiftQueue(type, sourceUpdater);
};

const onUpdateend = (type, sourceUpdater) => (e) => {
  // Although there should, in theory, be a pending action for any updateend receieved,
  // there are some actions that may trigger updateend events without set definitions in
  // the w3c spec. For instance, setting the duration on the media source may trigger
  // updateend events on source buffers. This does not appear to be in the spec. As such,
  // if we encounter an updateend without a corresponding pending action from our queue
  // for that source buffer type, process the next action.
  if (sourceUpdater.queuePending[type]) {
    const doneFn = sourceUpdater.queuePending[type].doneFn;

    sourceUpdater.queuePending[type] = null;

    if (doneFn) {
      // if there's an error, report it
      doneFn(sourceUpdater[`${type}Error_`]);
    }
  }

  shiftQueue(type, sourceUpdater);
};

/**
 * A queue of callbacks to be serialized and applied when a
 * MediaSource and its associated SourceBuffers are not in the
 * updating state. It is used by the segment loader to update the
 * underlying SourceBuffers when new data is loaded, for instance.
 *
 * @class SourceUpdater
 * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
 * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
 */
export default class SourceUpdater extends videojs.EventTarget {
  constructor(mediaSource) {
    super();
    this.mediaSource = mediaSource;
    this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
    this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
    this.logger_ = logger('SourceUpdater');
    // initial timestamp offset is 0
    this.audioTimestampOffset_ = 0;
    this.videoTimestampOffset_ = 0;
    this.queue = [];
    this.queuePending = {
      audio: null,
      video: null
    };
    this.delayedAudioAppendQueue_ = [];
    this.videoAppendQueued_ = false;
    this.codecs = {};
    this.onVideoUpdateEnd_ = onUpdateend('video', this);
    this.onAudioUpdateEnd_ = onUpdateend('audio', this);
    this.onVideoError_ = (e) => {
      // used for debugging
      this.videoError_ = e;
    };
    this.onAudioError_ = (e) => {
      // used for debugging
      this.audioError_ = e;
    };
    this.createdSourceBuffers_ = false;
    this.initializedEme_ = false;
    this.triggeredReady_ = false;
  }

  initializedEme() {
    this.initializedEme_ = true;
    this.triggerReady();
  }

  hasCreatedSourceBuffers() {
    // if false, likely waiting on one of the segment loaders to get enough data to create
    // source buffers
    return this.createdSourceBuffers_;
  }

  hasInitializedAnyEme() {
    return this.initializedEme_;
  }

  ready() {
    return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  }

  createSourceBuffers(codecs) {
    if (this.hasCreatedSourceBuffers()) {
      // already created them before
      return;
    }

    // the intial addOrChangeSourceBuffers will always be
    // two add buffers.
    this.addOrChangeSourceBuffers(codecs);
    this.createdSourceBuffers_ = true;
    this.trigger('createdsourcebuffers');
    this.triggerReady();
  }

  triggerReady() {
    // only allow ready to be triggered once, this prevents the case
    // where:
    // 1. we trigger createdsourcebuffers
    // 2. ie 11 synchronously initializates eme
    // 3. the synchronous initialization causes us to trigger ready
    // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
    if (this.ready() && !this.triggeredReady_) {
      this.triggeredReady_ = true;
      this.trigger('ready');
    }
  }

  /**
   * Add a type of source buffer to the media source.
   *
   * @param {string} type
   *        The type of source buffer to add.
   *
   * @param {string} codec
   *        The codec to add the source buffer with.
   */
  addSourceBuffer(type, codec) {
    pushQueue({
      type: 'mediaSource',
      sourceUpdater: this,
      action: actions.addSourceBuffer(type, codec),
      name: 'addSourceBuffer'
    });
  }

  /**
   * call abort on a source buffer.
   *
   * @param {string} type
   *        The type of source buffer to call abort on.
   */
  abort(type) {
    pushQueue({
      type,
      sourceUpdater: this,
      action: actions.abort(type),
      name: 'abort'
    });
  }

  /**
   * Call removeSourceBuffer and remove a specific type
   * of source buffer on the mediaSource.
   *
   * @param {string} type
   *        The type of source buffer to remove.
   */
  removeSourceBuffer(type) {
    if (!this.canRemoveSourceBuffer()) {
      videojs.log.error('removeSourceBuffer is not supported!');
      return;
    }

    pushQueue({
      type: 'mediaSource',
      sourceUpdater: this,
      action: actions.removeSourceBuffer(type),
      name: 'removeSourceBuffer'
    });
  }

  /**
   * Whether or not the removeSourceBuffer function is supported
   * on the mediaSource.
   *
   * @return {boolean}
   *          if removeSourceBuffer can be called.
   */
  canRemoveSourceBuffer() {
    // IE reports that it supports removeSourceBuffer, but often throws
    // errors when attempting to use the function. So we report that it
    // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
    // throws errors, so we report that it does not support this as well.
    return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource &&
      window.MediaSource.prototype &&
      typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  }

  /**
   * Whether or not the changeType function is supported
   * on our SourceBuffers.
   *
   * @return {boolean}
   *         if changeType can be called.
   */
  static canChangeType() {
    return window.SourceBuffer &&
        window.SourceBuffer.prototype &&
        typeof window.SourceBuffer.prototype.changeType === 'function';
  }

  /**
   * Whether or not the changeType function is supported
   * on our SourceBuffers.
   *
   * @return {boolean}
   *         if changeType can be called.
   */
  canChangeType() {
    return this.constructor.canChangeType();
  }

  /**
   * Call the changeType function on a source buffer, given the code and type.
   *
   * @param {string} type
   *        The type of source buffer to call changeType on.
   *
   * @param {string} codec
   *        The codec string to change type with on the source buffer.
   */
  changeType(type, codec) {
    if (!this.canChangeType()) {
      videojs.log.error('changeType is not supported!');
      return;
    }

    pushQueue({
      type,
      sourceUpdater: this,
      action: actions.changeType(codec),
      name: 'changeType'
    });
  }

  /**
   * Add source buffers with a codec or, if they are already created,
   * call changeType on source buffers using changeType.
   *
   * @param {Object} codecs
   *        Codecs to switch to
   */
  addOrChangeSourceBuffers(codecs) {
    if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
      throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
    }

    Object.keys(codecs).forEach((type) => {
      const codec = codecs[type];

      if (!this.hasCreatedSourceBuffers()) {
        return this.addSourceBuffer(type, codec);
      }

      if (this.canChangeType()) {
        this.changeType(type, codec);
      }
    });
  }

  /**
   * Queue an update to append an ArrayBuffer.
   *
   * @param {MediaObject} object containing audioBytes and/or videoBytes
   * @param {Function} done the function to call when done
   * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
   */
  appendBuffer(options, doneFn) {
    const {segmentInfo, type, bytes} = options;

    this.processedAppend_ = true;
    if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
      this.delayedAudioAppendQueue_.push([options, doneFn]);
      this.logger_(`delayed audio append of ${bytes.length} until video append`);
      return;
    }

    // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
    // not be fired. This means that the queue will be blocked until the next action
    // taken by the segment-loader. Provide a mechanism for segment-loader to handle
    // these errors by calling the doneFn with the specific error.
    const onError = doneFn;

    pushQueue({
      type,
      sourceUpdater: this,
      action: actions.appendBuffer(bytes, segmentInfo || {mediaIndex: -1}, onError),
      doneFn,
      name: 'appendBuffer'
    });

    if (type === 'video') {
      this.videoAppendQueued_ = true;
      if (!this.delayedAudioAppendQueue_.length) {
        return;
      }
      const queue = this.delayedAudioAppendQueue_.slice();

      this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);

      this.delayedAudioAppendQueue_.length = 0;
      queue.forEach((que) => {
        this.appendBuffer.apply(this, que);
      });
    }
  }

  /**
   * Get the audio buffer's buffered timerange.
   *
   * @return {TimeRange}
   *         The audio buffer's buffered time range
   */
  audioBuffered() {
    // no media source/source buffer or it isn't in the media sources
    // source buffer list
    if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
      return videojs.createTimeRange();
    }

    return this.audioBuffer.buffered ? this.audioBuffer.buffered :
      videojs.createTimeRange();
  }

  /**
   * Get the video buffer's buffered timerange.
   *
   * @return {TimeRange}
   *         The video buffer's buffered time range
   */
  videoBuffered() {
    // no media source/source buffer or it isn't in the media sources
    // source buffer list
    if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
      return videojs.createTimeRange();
    }
    return this.videoBuffer.buffered ? this.videoBuffer.buffered :
      videojs.createTimeRange();
  }

  /**
   * Get a combined video/audio buffer's buffered timerange.
   *
   * @return {TimeRange}
   *         the combined time range
   */
  buffered() {
    const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
    const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;

    if (audio && !video) {
      return this.audioBuffered();
    }

    if (video && !audio) {
      return this.videoBuffered();
    }

    return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  }

  /**
   * Add a callback to the queue that will set duration on the mediaSource.
   *
   * @param {number} duration
   *        The duration to set
   *
   * @param {Function} [doneFn]
   *        function to run after duration has been set.
   */
  setDuration(duration, doneFn = noop) {
    // In order to set the duration on the media source, it's necessary to wait for all
    // source buffers to no longer be updating. "If the updating attribute equals true on
    // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
    // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
    pushQueue({
      type: 'mediaSource',
      sourceUpdater: this,
      action: actions.duration(duration),
      name: 'duration',
      doneFn
    });
  }

  /**
   * Add a mediaSource endOfStream call to the queue
   *
   * @param {Error} [error]
   *        Call endOfStream with an error
   *
   * @param {Function} [doneFn]
   *        A function that should be called when the
   *        endOfStream call has finished.
   */
  endOfStream(error = null, doneFn = noop) {
    if (typeof error !== 'string') {
      error = undefined;
    }
    // In order to set the duration on the media source, it's necessary to wait for all
    // source buffers to no longer be updating. "If the updating attribute equals true on
    // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
    // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
    pushQueue({
      type: 'mediaSource',
      sourceUpdater: this,
      action: actions.endOfStream(error),
      name: 'endOfStream',
      doneFn
    });
  }

  /**
   * Queue an update to remove a time range from the buffer.
   *
   * @param {number} start where to start the removal
   * @param {number} end where to end the removal
   * @param {Function} [done=noop] optional callback to be executed when the remove
   * operation is complete
   * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
   */
  removeAudio(start, end, done = noop) {
    if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
      done();
      return;
    }

    pushQueue({
      type: 'audio',
      sourceUpdater: this,
      action: actions.remove(start, end),
      doneFn: done,
      name: 'remove'
    });
  }

  /**
   * Queue an update to remove a time range from the buffer.
   *
   * @param {number} start where to start the removal
   * @param {number} end where to end the removal
   * @param {Function} [done=noop] optional callback to be executed when the remove
   * operation is complete
   * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
   */
  removeVideo(start, end, done = noop) {
    if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
      done();
      return;
    }

    pushQueue({
      type: 'video',
      sourceUpdater: this,
      action: actions.remove(start, end),
      doneFn: done,
      name: 'remove'
    });
  }

  /**
   * Whether the underlying sourceBuffer is updating or not
   *
   * @return {boolean} the updating status of the SourceBuffer
   */
  updating() {
    // the audio/video source buffer is updating
    if (updating('audio', this) || updating('video', this)) {
      return true;
    }

    return false;
  }

  /**
   * Set/get the timestampoffset on the audio SourceBuffer
   *
   * @return {number} the timestamp offset
   */
  audioTimestampOffset(offset) {
    if (typeof offset !== 'undefined' &&
        this.audioBuffer &&
        // no point in updating if it's the same
        this.audioTimestampOffset_ !== offset) {
      pushQueue({
        type: 'audio',
        sourceUpdater: this,
        action: actions.timestampOffset(offset),
        name: 'timestampOffset'
      });
      this.audioTimestampOffset_ = offset;
    }
    return this.audioTimestampOffset_;
  }

  /**
   * Set/get the timestampoffset on the video SourceBuffer
   *
   * @return {number} the timestamp offset
   */
  videoTimestampOffset(offset) {
    if (typeof offset !== 'undefined' &&
        this.videoBuffer &&
        // no point in updating if it's the same
        this.videoTimestampOffset !== offset) {
      pushQueue({
        type: 'video',
        sourceUpdater: this,
        action: actions.timestampOffset(offset),
        name: 'timestampOffset'
      });
      this.videoTimestampOffset_ = offset;
    }
    return this.videoTimestampOffset_;
  }

  /**
   * Add a function to the queue that will be called
   * when it is its turn to run in the audio queue.
   *
   * @param {Function} callback
   *        The callback to queue.
   */
  audioQueueCallback(callback) {
    if (!this.audioBuffer) {
      return;
    }
    pushQueue({
      type: 'audio',
      sourceUpdater: this,
      action: actions.callback(callback),
      name: 'callback'
    });
  }

  /**
   * Add a function to the queue that will be called
   * when it is its turn to run in the video queue.
   *
   * @param {Function} callback
   *        The callback to queue.
   */
  videoQueueCallback(callback) {
    if (!this.videoBuffer) {
      return;
    }
    pushQueue({
      type: 'video',
      sourceUpdater: this,
      action: actions.callback(callback),
      name: 'callback'
    });
  }

  /**
   * dispose of the source updater and the underlying sourceBuffer
   */
  dispose() {
    this.trigger('dispose');
    bufferTypes.forEach((type) => {
      this.abort(type);
      if (this.canRemoveSourceBuffer()) {
        this.removeSourceBuffer(type);
      } else {
        this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
      }
    });

    this.videoAppendQueued_ = false;
    this.delayedAudioAppendQueue_.length = 0;

    if (this.sourceopenListener_) {
      this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
    }

    this.off();
  }
}