media-groups.js 29.1 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 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
import videojs from 'video.js';
import PlaylistLoader from './playlist-loader';
import DashPlaylistLoader from './dash-playlist-loader';
import noop from './util/noop';
import {isAudioOnly, playlistMatch} from './playlist.js';
import logger from './util/logger';

/**
 * Convert the properties of an HLS track into an audioTrackKind.
 *
 * @private
 */
const audioTrackKind_ = (properties) => {
  let kind = properties.default ? 'main' : 'alternative';

  if (properties.characteristics &&
      properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
    kind = 'main-desc';
  }

  return kind;
};

/**
 * Pause provided segment loader and playlist loader if active
 *
 * @param {SegmentLoader} segmentLoader
 *        SegmentLoader to pause
 * @param {Object} mediaType
 *        Active media type
 * @function stopLoaders
 */
export const stopLoaders = (segmentLoader, mediaType) => {
  segmentLoader.abort();
  segmentLoader.pause();

  if (mediaType && mediaType.activePlaylistLoader) {
    mediaType.activePlaylistLoader.pause();
    mediaType.activePlaylistLoader = null;
  }
};

/**
 * Start loading provided segment loader and playlist loader
 *
 * @param {PlaylistLoader} playlistLoader
 *        PlaylistLoader to start loading
 * @param {Object} mediaType
 *        Active media type
 * @function startLoaders
 */
export const startLoaders = (playlistLoader, mediaType) => {
  // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  // playlist loader
  mediaType.activePlaylistLoader = playlistLoader;
  playlistLoader.load();
};

/**
 * Returns a function to be called when the media group changes. It performs a
 * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
 * change of group is merely a rendition switch of the same content at another encoding,
 * rather than a change of content, such as switching audio from English to Spanish.
 *
 * @param {string} type
 *        MediaGroup type
 * @param {Object} settings
 *        Object containing required information for media groups
 * @return {Function}
 *         Handler for a non-destructive resync of SegmentLoader when the active media
 *         group changes.
 * @function onGroupChanged
 */
export const onGroupChanged = (type, settings) => () => {
  const {
    segmentLoaders: {
      [type]: segmentLoader,
      main: mainSegmentLoader
    },
    mediaTypes: { [type]: mediaType }
  } = settings;
  const activeTrack = mediaType.activeTrack();
  const activeGroup = mediaType.getActiveGroup();
  const previousActiveLoader = mediaType.activePlaylistLoader;
  const lastGroup = mediaType.lastGroup_;

  // the group did not change do nothing
  if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
    return;
  }

  mediaType.lastGroup_ = activeGroup;
  mediaType.lastTrack_ = activeTrack;

  stopLoaders(segmentLoader, mediaType);

  if (!activeGroup || activeGroup.isMasterPlaylist) {
    // there is no group active or active group is a main playlist and won't change
    return;
  }

  if (!activeGroup.playlistLoader) {
    if (previousActiveLoader) {
      // The previous group had a playlist loader but the new active group does not
      // this means we are switching from demuxed to muxed audio. In this case we want to
      // do a destructive reset of the main segment loader and not restart the audio
      // loaders.
      mainSegmentLoader.resetEverything();
    }
    return;
  }

  // Non-destructive resync
  segmentLoader.resyncLoader();

  startLoaders(activeGroup.playlistLoader, mediaType);
};

export const onGroupChanging = (type, settings) => () => {
  const {
    segmentLoaders: {
      [type]: segmentLoader
    },
    mediaTypes: { [type]: mediaType }
  } = settings;

  mediaType.lastGroup_ = null;

  segmentLoader.abort();
  segmentLoader.pause();
};

/**
 * Returns a function to be called when the media track changes. It performs a
 * destructive reset of the SegmentLoader to ensure we start loading as close to
 * currentTime as possible.
 *
 * @param {string} type
 *        MediaGroup type
 * @param {Object} settings
 *        Object containing required information for media groups
 * @return {Function}
 *         Handler for a destructive reset of SegmentLoader when the active media
 *         track changes.
 * @function onTrackChanged
 */
export const onTrackChanged = (type, settings) => () => {
  const {
    masterPlaylistLoader,
    segmentLoaders: {
      [type]: segmentLoader,
      main: mainSegmentLoader
    },
    mediaTypes: { [type]: mediaType }
  } = settings;
  const activeTrack = mediaType.activeTrack();
  const activeGroup = mediaType.getActiveGroup();
  const previousActiveLoader = mediaType.activePlaylistLoader;
  const lastTrack = mediaType.lastTrack_;

  // track did not change, do nothing
  if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
    return;
  }

  mediaType.lastGroup_ = activeGroup;
  mediaType.lastTrack_ = activeTrack;

  stopLoaders(segmentLoader, mediaType);

  if (!activeGroup) {
    // there is no group active so we do not want to restart loaders
    return;
  }

  if (activeGroup.isMasterPlaylist) {
    // track did not change, do nothing
    if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
      return;
    }

    const mpc = settings.vhs.masterPlaylistController_;
    const newPlaylist = mpc.selectPlaylist();

    // media will not change do nothing
    if (mpc.media() === newPlaylist) {
      return;
    }

    mediaType.logger_(`track change. Switching master audio from ${lastTrack.id} to ${activeTrack.id}`);
    masterPlaylistLoader.pause();
    mainSegmentLoader.resetEverything();
    mpc.fastQualityChange_(newPlaylist);

    return;
  }

  if (type === 'AUDIO') {
    if (!activeGroup.playlistLoader) {
      // when switching from demuxed audio/video to muxed audio/video (noted by no
      // playlist loader for the audio group), we want to do a destructive reset of the
      // main segment loader and not restart the audio loaders
      mainSegmentLoader.setAudio(true);
      // don't have to worry about disabling the audio of the audio segment loader since
      // it should be stopped
      mainSegmentLoader.resetEverything();
      return;
    }

    // although the segment loader is an audio segment loader, call the setAudio
    // function to ensure it is prepared to re-append the init segment (or handle other
    // config changes)
    segmentLoader.setAudio(true);
    mainSegmentLoader.setAudio(false);
  }

  if (previousActiveLoader === activeGroup.playlistLoader) {
    // Nothing has actually changed. This can happen because track change events can fire
    // multiple times for a "single" change. One for enabling the new active track, and
    // one for disabling the track that was active
    startLoaders(activeGroup.playlistLoader, mediaType);
    return;
  }

  if (segmentLoader.track) {
    // For WebVTT, set the new text track in the segmentloader
    segmentLoader.track(activeTrack);
  }

  // destructive reset
  segmentLoader.resetEverything();

  startLoaders(activeGroup.playlistLoader, mediaType);
};

export const onError = {
  /**
   * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
   * an error.
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Error handler. Logs warning (or error if the playlist is blacklisted) to
   *         console and switches back to default audio track.
   * @function onError.AUDIO
   */
  AUDIO: (type, settings) => () => {
    const {
      segmentLoaders: { [type]: segmentLoader},
      mediaTypes: { [type]: mediaType },
      blacklistCurrentPlaylist
    } = settings;

    stopLoaders(segmentLoader, mediaType);

    // switch back to default audio track
    const activeTrack = mediaType.activeTrack();
    const activeGroup = mediaType.activeGroup();
    const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
    const defaultTrack = mediaType.tracks[id];

    if (activeTrack === defaultTrack) {
      // Default track encountered an error. All we can do now is blacklist the current
      // rendition and hope another will switch audio groups
      blacklistCurrentPlaylist({
        message: 'Problem encountered loading the default audio track.'
      });
      return;
    }

    videojs.log.warn('Problem encountered loading the alternate audio track.' +
                       'Switching back to default.');

    for (const trackId in mediaType.tracks) {
      mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
    }

    mediaType.onTrackChanged();
  },
  /**
   * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
   * an error.
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Error handler. Logs warning to console and disables the active subtitle track
   * @function onError.SUBTITLES
   */
  SUBTITLES: (type, settings) => () => {
    const {
      segmentLoaders: { [type]: segmentLoader},
      mediaTypes: { [type]: mediaType }
    } = settings;

    videojs.log.warn('Problem encountered loading the subtitle track.' +
                     'Disabling subtitle track.');

    stopLoaders(segmentLoader, mediaType);

    const track = mediaType.activeTrack();

    if (track) {
      track.mode = 'disabled';
    }

    mediaType.onTrackChanged();
  }
};

export const setupListeners = {
  /**
   * Setup event listeners for audio playlist loader
   *
   * @param {string} type
   *        MediaGroup type
   * @param {PlaylistLoader|null} playlistLoader
   *        PlaylistLoader to register listeners on
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function setupListeners.AUDIO
   */
  AUDIO: (type, playlistLoader, settings) => {
    if (!playlistLoader) {
      // no playlist loader means audio will be muxed with the video
      return;
    }

    const {
      tech,
      requestOptions,
      segmentLoaders: { [type]: segmentLoader }
    } = settings;

    playlistLoader.on('loadedmetadata', () => {
      const media = playlistLoader.media();

      segmentLoader.playlist(media, requestOptions);

      // if the video is already playing, or if this isn't a live video and preload
      // permits, start downloading segments
      if (!tech.paused() || (media.endList && tech.preload() !== 'none')) {
        segmentLoader.load();
      }
    });

    playlistLoader.on('loadedplaylist', () => {
      segmentLoader.playlist(playlistLoader.media(), requestOptions);

      // If the player isn't paused, ensure that the segment loader is running
      if (!tech.paused()) {
        segmentLoader.load();
      }
    });

    playlistLoader.on('error', onError[type](type, settings));
  },
  /**
   * Setup event listeners for subtitle playlist loader
   *
   * @param {string} type
   *        MediaGroup type
   * @param {PlaylistLoader|null} playlistLoader
   *        PlaylistLoader to register listeners on
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function setupListeners.SUBTITLES
   */
  SUBTITLES: (type, playlistLoader, settings) => {
    const {
      tech,
      requestOptions,
      segmentLoaders: { [type]: segmentLoader },
      mediaTypes: { [type]: mediaType }
    } = settings;

    playlistLoader.on('loadedmetadata', () => {
      const media = playlistLoader.media();

      segmentLoader.playlist(media, requestOptions);
      segmentLoader.track(mediaType.activeTrack());

      // if the video is already playing, or if this isn't a live video and preload
      // permits, start downloading segments
      if (!tech.paused() || (media.endList && tech.preload() !== 'none')) {
        segmentLoader.load();
      }
    });

    playlistLoader.on('loadedplaylist', () => {
      segmentLoader.playlist(playlistLoader.media(), requestOptions);

      // If the player isn't paused, ensure that the segment loader is running
      if (!tech.paused()) {
        segmentLoader.load();
      }
    });

    playlistLoader.on('error', onError[type](type, settings));
  }
};

export const initialize = {
  /**
   * Setup PlaylistLoaders and AudioTracks for the audio groups
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function initialize.AUDIO
   */
  'AUDIO': (type, settings) => {
    const {
      vhs,
      sourceType,
      segmentLoaders: { [type]: segmentLoader },
      requestOptions,
      master: {mediaGroups},
      mediaTypes: {
        [type]: {
          groups,
          tracks,
          logger_
        }
      },
      masterPlaylistLoader
    } = settings;

    const audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master);

    // force a default if we have none
    if (!mediaGroups[type] ||
        Object.keys(mediaGroups[type]).length === 0) {
      mediaGroups[type] = { main: { default: { default: true } } };
      if (audioOnlyMaster) {
        mediaGroups[type].main.default.playlists = masterPlaylistLoader.master.playlists;
      }
    }

    for (const groupId in mediaGroups[type]) {
      if (!groups[groupId]) {
        groups[groupId] = [];
      }
      for (const variantLabel in mediaGroups[type][groupId]) {
        let properties = mediaGroups[type][groupId][variantLabel];

        let playlistLoader;

        if (audioOnlyMaster) {
          logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a master playlist`);
          properties.isMasterPlaylist = true;
          playlistLoader = null;

          // if vhs-json was provided as the source, and the media playlist was resolved,
          // use the resolved media playlist object
        } else if (sourceType === 'vhs-json' && properties.playlists) {
          playlistLoader = new PlaylistLoader(
            properties.playlists[0],
            vhs,
            requestOptions
          );
        } else if (properties.resolvedUri) {
          playlistLoader = new PlaylistLoader(
            properties.resolvedUri,
            vhs,
            requestOptions
          );
        // TODO: dash isn't the only type with properties.playlists
        // should we even have properties.playlists in this check.
        } else if (properties.playlists && sourceType === 'dash') {
          playlistLoader = new DashPlaylistLoader(
            properties.playlists[0],
            vhs,
            requestOptions,
            masterPlaylistLoader
          );
        } else {
          // no resolvedUri means the audio is muxed with the video when using this
          // audio track
          playlistLoader = null;
        }

        properties = videojs.mergeOptions(
          { id: variantLabel, playlistLoader },
          properties
        );

        setupListeners[type](type, properties.playlistLoader, settings);

        groups[groupId].push(properties);

        if (typeof tracks[variantLabel] === 'undefined') {
          const track = new videojs.AudioTrack({
            id: variantLabel,
            kind: audioTrackKind_(properties),
            enabled: false,
            language: properties.language,
            default: properties.default,
            label: variantLabel
          });

          tracks[variantLabel] = track;
        }
      }
    }

    // setup single error event handler for the segment loader
    segmentLoader.on('error', onError[type](type, settings));
  },
  /**
   * Setup PlaylistLoaders and TextTracks for the subtitle groups
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function initialize.SUBTITLES
   */
  'SUBTITLES': (type, settings) => {
    const {
      tech,
      vhs,
      sourceType,
      segmentLoaders: { [type]: segmentLoader },
      requestOptions,
      master: { mediaGroups },
      mediaTypes: {
        [type]: {
          groups,
          tracks
        }
      },
      masterPlaylistLoader
    } = settings;

    for (const groupId in mediaGroups[type]) {
      if (!groups[groupId]) {
        groups[groupId] = [];
      }

      for (const variantLabel in mediaGroups[type][groupId]) {
        if (mediaGroups[type][groupId][variantLabel].forced) {
          // Subtitle playlists with the forced attribute are not selectable in Safari.
          // According to Apple's HLS Authoring Specification:
          //   If content has forced subtitles and regular subtitles in a given language,
          //   the regular subtitles track in that language MUST contain both the forced
          //   subtitles and the regular subtitles for that language.
          // Because of this requirement and that Safari does not add forced subtitles,
          // forced subtitles are skipped here to maintain consistent experience across
          // all platforms
          continue;
        }

        let properties = mediaGroups[type][groupId][variantLabel];

        let playlistLoader;

        if (sourceType === 'hls') {
          playlistLoader =
            new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
        } else if (sourceType === 'dash') {
          const playlists = properties.playlists.filter((p) => p.excludeUntil !== Infinity);

          if (!playlists.length) {
            return;
          }
          playlistLoader = new DashPlaylistLoader(
            properties.playlists[0],
            vhs,
            requestOptions,
            masterPlaylistLoader
          );
        } else if (sourceType === 'vhs-json') {
          playlistLoader = new PlaylistLoader(
            // if the vhs-json object included the media playlist, use the media playlist
            // as provided, otherwise use the resolved URI to load the playlist
            properties.playlists ? properties.playlists[0] : properties.resolvedUri,
            vhs,
            requestOptions
          );
        }

        properties = videojs.mergeOptions({
          id: variantLabel,
          playlistLoader
        }, properties);

        setupListeners[type](type, properties.playlistLoader, settings);

        groups[groupId].push(properties);

        if (typeof tracks[variantLabel] === 'undefined') {
          const track = tech.addRemoteTextTrack({
            id: variantLabel,
            kind: 'subtitles',
            default: properties.default && properties.autoselect,
            language: properties.language,
            label: variantLabel
          }, false).track;

          tracks[variantLabel] = track;
        }
      }
    }

    // setup single error event handler for the segment loader
    segmentLoader.on('error', onError[type](type, settings));
  },
  /**
   * Setup TextTracks for the closed-caption groups
   *
   * @param {String} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @function initialize['CLOSED-CAPTIONS']
   */
  'CLOSED-CAPTIONS': (type, settings) => {
    const {
      tech,
      master: { mediaGroups },
      mediaTypes: {
        [type]: {
          groups,
          tracks
        }
      }
    } = settings;

    for (const groupId in mediaGroups[type]) {
      if (!groups[groupId]) {
        groups[groupId] = [];
      }

      for (const variantLabel in mediaGroups[type][groupId]) {
        const properties = mediaGroups[type][groupId][variantLabel];

        // Look for either 608 (CCn) or 708 (SERVICEn) caption services
        if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
          continue;
        }

        const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};

        let newProps = {
          label: variantLabel,
          language: properties.language,
          instreamId: properties.instreamId,
          default: properties.default && properties.autoselect
        };

        if (captionServices[newProps.instreamId]) {
          newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
        }

        if (newProps.default === undefined) {
          delete newProps.default;
        }

        // No PlaylistLoader is required for Closed-Captions because the captions are
        // embedded within the video stream
        groups[groupId].push(videojs.mergeOptions({ id: variantLabel }, properties));

        if (typeof tracks[variantLabel] === 'undefined') {
          const track = tech.addRemoteTextTrack({
            id: newProps.instreamId,
            kind: 'captions',
            default: newProps.default,
            language: newProps.language,
            label: newProps.label
          }, false).track;

          tracks[variantLabel] = track;
        }
      }
    }
  }
};

const groupMatch = (list, media) => {
  for (let i = 0; i < list.length; i++) {
    if (playlistMatch(media, list[i])) {
      return true;
    }

    if (list[i].playlists && groupMatch(list[i].playlists, media)) {
      return true;
    }
  }

  return false;
};

/**
 * Returns a function used to get the active group of the provided type
 *
 * @param {string} type
 *        MediaGroup type
 * @param {Object} settings
 *        Object containing required information for media groups
 * @return {Function}
 *         Function that returns the active media group for the provided type. Takes an
 *         optional parameter {TextTrack} track. If no track is provided, a list of all
 *         variants in the group, otherwise the variant corresponding to the provided
 *         track is returned.
 * @function activeGroup
 */
export const activeGroup = (type, settings) => (track) => {
  const {
    masterPlaylistLoader,
    mediaTypes: { [type]: { groups } }
  } = settings;

  const media = masterPlaylistLoader.media();

  if (!media) {
    return null;
  }

  let variants = null;

  // set to variants to main media active group
  if (media.attributes[type]) {
    variants = groups[media.attributes[type]];
  }

  const groupKeys = Object.keys(groups);

  if (!variants) {
    // find the masterPlaylistLoader media
    // that is in a media group if we are dealing
    // with audio only
    if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
      for (let i = 0; i < groupKeys.length; i++) {
        const groupPropertyList = groups[groupKeys[i]];

        if (groupMatch(groupPropertyList, media)) {
          variants = groupPropertyList;
          break;
        }
      }
    // use the main group if it exists
    } else if (groups.main) {
      variants = groups.main;
    // only one group, use that one
    } else if (groupKeys.length === 1) {
      variants = groups[groupKeys[0]];
    }
  }

  if (typeof track === 'undefined') {
    return variants;
  }

  if (track === null || !variants) {
    // An active track was specified so a corresponding group is expected. track === null
    // means no track is currently active so there is no corresponding group
    return null;
  }

  return variants.filter((props) => props.id === track.id)[0] || null;
};

export const activeTrack = {
  /**
   * Returns a function used to get the active track of type provided
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Function that returns the active media track for the provided type. Returns
   *         null if no track is active
   * @function activeTrack.AUDIO
   */
  AUDIO: (type, settings) => () => {
    const { mediaTypes: { [type]: { tracks } } } = settings;

    for (const id in tracks) {
      if (tracks[id].enabled) {
        return tracks[id];
      }
    }

    return null;
  },
  /**
   * Returns a function used to get the active track of type provided
   *
   * @param {string} type
   *        MediaGroup type
   * @param {Object} settings
   *        Object containing required information for media groups
   * @return {Function}
   *         Function that returns the active media track for the provided type. Returns
   *         null if no track is active
   * @function activeTrack.SUBTITLES
   */
  SUBTITLES: (type, settings) => () => {
    const { mediaTypes: { [type]: { tracks } } } = settings;

    for (const id in tracks) {
      if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
        return tracks[id];
      }
    }

    return null;
  }
};

export const getActiveGroup = (type, {mediaTypes}) => () => {
  const activeTrack_ = mediaTypes[type].activeTrack();

  if (!activeTrack_) {
    return null;
  }

  return mediaTypes[type].activeGroup(activeTrack_);
};

/**
 * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
 * Closed-Captions) specified in the master manifest.
 *
 * @param {Object} settings
 *        Object containing required information for setting up the media groups
 * @param {Tech} settings.tech
 *        The tech of the player
 * @param {Object} settings.requestOptions
 *        XHR request options used by the segment loaders
 * @param {PlaylistLoader} settings.masterPlaylistLoader
 *        PlaylistLoader for the master source
 * @param {VhsHandler} settings.vhs
 *        VHS SourceHandler
 * @param {Object} settings.master
 *        The parsed master manifest
 * @param {Object} settings.mediaTypes
 *        Object to store the loaders, tracks, and utility methods for each media type
 * @param {Function} settings.blacklistCurrentPlaylist
 *        Blacklists the current rendition and forces a rendition switch.
 * @function setupMediaGroups
 */
export const setupMediaGroups = (settings) => {
  ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach((type) => {
    initialize[type](type, settings);
  });

  const {
    mediaTypes,
    masterPlaylistLoader,
    tech,
    vhs,
    segmentLoaders: {
      ['AUDIO']: audioSegmentLoader,
      main: mainSegmentLoader
    }
  } = settings;

  // setup active group and track getters and change event handlers
  ['AUDIO', 'SUBTITLES'].forEach((type) => {
    mediaTypes[type].activeGroup = activeGroup(type, settings);
    mediaTypes[type].activeTrack = activeTrack[type](type, settings);
    mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
    mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
    mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
    mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  });

  // DO NOT enable the default subtitle or caption track.
  // DO enable the default audio track
  const audioGroup = mediaTypes.AUDIO.activeGroup();

  if (audioGroup) {
    const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;

    mediaTypes.AUDIO.tracks[groupId].enabled = true;
    mediaTypes.AUDIO.onGroupChanged();
    mediaTypes.AUDIO.onTrackChanged();

    const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup();

    // a similar check for handling setAudio on each loader is run again each time the
    // track is changed, but needs to be handled here since the track may not be considered
    // changed on the first call to onTrackChanged
    if (!activeAudioGroup.playlistLoader) {
      // either audio is muxed with video or the stream is audio only
      mainSegmentLoader.setAudio(true);
    } else {
      // audio is demuxed
      mainSegmentLoader.setAudio(false);
      audioSegmentLoader.setAudio(true);
    }
  }

  masterPlaylistLoader.on('mediachange', () => {
    ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  });

  masterPlaylistLoader.on('mediachanging', () => {
    ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  });

  // custom audio track change event handler for usage event
  const onAudioTrackChanged = () => {
    mediaTypes.AUDIO.onTrackChanged();
    tech.trigger({ type: 'usage', name: 'vhs-audio-change' });
    tech.trigger({ type: 'usage', name: 'hls-audio-change' });
  };

  tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  tech.remoteTextTracks().addEventListener(
    'change',
    mediaTypes.SUBTITLES.onTrackChanged
  );

  vhs.on('dispose', () => {
    tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
    tech.remoteTextTracks().removeEventListener(
      'change',
      mediaTypes.SUBTITLES.onTrackChanged
    );
  });

  // clear existing audio tracks and add the ones we just created
  tech.clearTracks('audio');

  for (const id in mediaTypes.AUDIO.tracks) {
    tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  }
};

/**
 * Creates skeleton object used to store the loaders, tracks, and utility methods for each
 * media type
 *
 * @return {Object}
 *         Object to store the loaders, tracks, and utility methods for each media type
 * @function createMediaTypes
 */
export const createMediaTypes = () => {
  const mediaTypes = {};

  ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach((type) => {
    mediaTypes[type] = {
      groups: {},
      tracks: {},
      activePlaylistLoader: null,
      activeGroup: noop,
      activeTrack: noop,
      getActiveGroup: noop,
      onGroupChanged: noop,
      onTrackChanged: noop,
      lastTrack_: null,
      logger_: logger(`MediaGroups[${type}]`)
    };
  });

  return mediaTypes;
};