All files / dash.js/src/streaming Stream.js

41.3% Statements 190/460
29.83% Branches 71/238
44% Functions 44/100
40.8% Lines 182/446

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157                                                                                                  1x         27x 27x 27x 27x   27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x                                                 27x 27x 27x 27x   27x   27x         27x                                       21x 21x 21x 21x             21x 21x 21x 21x             30x 30x 30x 30x             21x 21x 21x 21x 21x 21x               30x 30x 30x 30x 30x 30x                 189x                                                                                         1x   1x         1x 1x   1x                 1x 1x                                                 1x 1x   1x     1x 1x 1x   1x 1x     1x                                                                                                                   1x 1x   1x   1x   1x         1x 1x     1x       1x 2x   2x       2x 2x     2x         1x           1x 2x   1x       1x                                 1x         1x                                                             2x     2x             2x       2x         2x                                                                                                                                                                                                 57x 57x 57x           57x 57x   57x       57x 57x 57x 57x 57x 57x       1x       1x 1x 1x                   1x   1x           1x 1x 1x 1x   1x                   57x 57x 57x 57x 57x 57x         30x 27x 27x     30x 12x     30x 27x 27x     30x 27x     30x 12x     30x   30x   30x   30x         16x               57x       16x       19x       49x                       1x       1x                                                                                                                                                             4x 4x 4x                                                                                                                 2x 1x 1x                                                                                                                                                                                           16x         16x                 16x                     1x 1x   1x 1x     1x 1x                                             1x   1x     1x                         1x     1x               1x             1x   1x     1x                                                     59x       2x       15x                                                       15x     15x         27x                                                                       27x 27x     1x    
/**
 * The copyright in this software is being made available under the BSD License,
 * included below. This software may be subject to other third party and contributor
 * rights, including patent rights, and no such rights are granted under this license.
 *
 * Copyright (c) 2013, Dash Industry Forum.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *  * Redistributions of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation and/or
 *  other materials provided with the distribution.
 *  * Neither the name of Dash Industry Forum nor the names of its
 *  contributors may be used to endorse or promote products derived from this software
 *  without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
 *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */
import BlacklistController from './controllers/BlacklistController.js';
import BoxParser from './utils/BoxParser.js';
import Constants from './constants/Constants.js';
import DashConstants from '../dash/constants/DashConstants.js';
import DashJSError from './vo/DashJSError.js';
import Debug from '../core/Debug.js';
import Errors from '../core/errors/Errors.js';
import EventBus from '../core/EventBus.js';
import Events from '../core/events/Events.js';
import ExternalMediaSource from './ExternalMediaSource.js';
import FactoryMaker from '../core/FactoryMaker.js';
import FragmentController from './controllers/FragmentController.js';
import MediaInfoSelectionInput from './vo/MediaInfoSelectionInput.js';
import MediaPlayerEvents from './MediaPlayerEvents.js';
import StreamProcessor from './StreamProcessor.js';
import ThumbnailController from './thumbnail/ThumbnailController.js';
import URLUtils from './utils/URLUtils.js';
 
 
const MEDIA_TYPES = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT, Constants.MUXED, Constants.IMAGE];
 
 
function Stream(config) {
 
    config = config || {};
    const context = this.context;
    const eventBus = EventBus(context).getInstance();
    const urlUtils = URLUtils(context).getInstance();
 
    const manifestModel = config.manifestModel;
    const mediaPlayerModel = config.mediaPlayerModel;
    const dashMetrics = config.dashMetrics;
    const manifestUpdater = config.manifestUpdater;
    const adapter = config.adapter;
    const timelineConverter = config.timelineConverter;
    const capabilities = config.capabilities;
    const errHandler = config.errHandler;
    const abrController = config.abrController;
    const playbackController = config.playbackController;
    const throughputController = config.throughputController;
    const eventController = config.eventController;
    const mediaController = config.mediaController;
    const protectionController = config.protectionController;
    const textController = config.textController;
    const videoModel = config.videoModel;
    let streamInfo = config.streamInfo;
    const settings = config.settings;
 
 
    let boxParser,
        debug,
        fragmentController,
        hasAudioTrack,
        hasFinishedBuffering,
        hasVideoTrack,
        instance,
        isActive,
        isEndedEventSignaled,
        isInitialized,
        logger,
        preloaded,
        segmentBlacklistController,
        streamProcessors,
        thumbnailController,
        trackChangedEvents;
 
 
    /**
     * Setup the stream
     */
    function setup() {
        try {
            debug = Debug(context).getInstance();
            logger = debug.getLogger(instance);
            resetInitialSettings();
 
            boxParser = BoxParser(context).getInstance();
 
            segmentBlacklistController = BlacklistController(context).create({
                updateEventName: Events.SEGMENT_LOCATION_BLACKLIST_CHANGED,
                addBlacklistEventName: Events.SEGMENT_LOCATION_BLACKLIST_ADD
            });
 
            fragmentController = FragmentController(context).create({
                streamInfo: streamInfo,
                mediaPlayerModel: mediaPlayerModel,
                dashMetrics: dashMetrics,
                errHandler: errHandler,
                settings: settings,
                boxParser: boxParser,
                dashConstants: DashConstants,
                urlUtils: urlUtils
            });
 
        } catch (e) {
            throw e;
        }
    }
 
    /**
     * Initialize the events
     */
    function initialize() {
        registerEvents();
        registerProtectionEvents();
        textController.initializeForStream(streamInfo);
        eventBus.trigger(Events.STREAM_UPDATED, { streamInfo: streamInfo });
    }
 
    /**
     * Register the streaming events
     */
    function registerEvents() {
        eventBus.on(Events.BUFFERING_COMPLETED, _onBufferingCompleted, instance);
        eventBus.on(Events.INBAND_EVENTS, _onInbandEvents, instance);
        eventBus.on(Events.DATA_UPDATE_COMPLETED, _onDataUpdateCompleted, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKED, _onPlaybackSeeked, instance);
    }
 
    /**
     * Unregister the streaming events
     */
    function unRegisterEvents() {
        eventBus.off(Events.BUFFERING_COMPLETED, _onBufferingCompleted, instance);
        eventBus.off(Events.INBAND_EVENTS, _onInbandEvents, instance);
        eventBus.off(Events.DATA_UPDATE_COMPLETED, _onDataUpdateCompleted, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKED, _onPlaybackSeeked, instance);
    }
 
    /**
     * Register the protection events
     */
    function registerProtectionEvents() {
        if (protectionController) {
            eventBus.on(Events.KEY_ERROR, _onProtectionError, instance);
            eventBus.on(Events.SERVER_CERTIFICATE_UPDATED, _onProtectionError, instance);
            eventBus.on(Events.LICENSE_REQUEST_COMPLETE, _onProtectionError, instance);
            eventBus.on(Events.KEY_SYSTEM_SELECTED, _onProtectionError, instance);
            eventBus.on(Events.KEY_SESSION_CREATED, _onProtectionError, instance);
        }
    }
 
    /**
     * Unregister the protection events
     */
    function unRegisterProtectionEvents() {
        if (protectionController) {
            eventBus.off(Events.KEY_ERROR, _onProtectionError, instance);
            eventBus.off(Events.SERVER_CERTIFICATE_UPDATED, _onProtectionError, instance);
            eventBus.off(Events.LICENSE_REQUEST_COMPLETE, _onProtectionError, instance);
            eventBus.off(Events.KEY_SYSTEM_SELECTED, _onProtectionError, instance);
            eventBus.off(Events.KEY_SESSION_CREATED, _onProtectionError, instance);
        }
    }
 
    /**
     * Returns the stream id
     * @return {*|null}
     */
    function getStreamId() {
        return streamInfo ? streamInfo.id : null;
    }
 
    /**
     * Activates Stream by re-initializing some of its components
     * @param {MediaSource} mediaSource
     * @param {array} previousSourceBufferSinks
     * @param representationsFromPreviousPeriod
     * @memberof Stream#
     */
    function activate(mediaSource, previousSourceBufferSinks, representationsFromPreviousPeriod = []) {
        return new Promise((resolve, reject) => {
            if (isActive) {
                resolve();
                return;
            }
 
            if (getPreloaded()) {
                isActive = true;
                eventBus.trigger(Events.STREAM_ACTIVATED, {
                    streamInfo
                });
                resolve();
                return;
            }
 
 
            _initializeMedia(mediaSource, previousSourceBufferSinks, representationsFromPreviousPeriod)
                .then(() => {
                    isActive = true;
                    if (representationsFromPreviousPeriod && representationsFromPreviousPeriod.length > 0) {
                        startScheduleControllers();
                    }
                    eventBus.trigger(Events.STREAM_ACTIVATED, {
                        streamInfo
                    });
                    resolve();
                })
                .catch((e) => {
                    reject(e);
                });
        });
    }
 
    function startPreloading(mediaSource, previousBuffers, representationsFromPreviousPeriod = []) {
        return new Promise((resolve, reject) => {
 
            Iif (getPreloaded()) {
                reject();
                return;
            }
 
            logger.info(`[startPreloading] Preloading next stream with id ${getId()}`);
            _setPreloaded(true);
 
            _commonMediaInitialization(mediaSource, previousBuffers, representationsFromPreviousPeriod)
                .then(() => {
                    for (let i = 0; i < streamProcessors.length && streamProcessors[i]; i++) {
                        streamProcessors[i].setExplicitBufferingTime(getStartTime());
                        streamProcessors[i].getScheduleController().startScheduleTimer();
                    }
                    resolve();
                })
                .catch(() => {
                    _setPreloaded(false);
                    reject();
                });
        });
    }
 
    /**
     *
     * @param {object} mediaSource
     * @param {array} previousSourceBufferSinks
     * @param representationsFromPreviousPeriod
     * @return {Promise<Array>}
     * @private
     */
    function _initializeMedia(mediaSource, previousSourceBufferSinks, representationsFromPreviousPeriod = []) {
        return _commonMediaInitialization(mediaSource, previousSourceBufferSinks, representationsFromPreviousPeriod);
    }
 
    /**
     *
     * @param {object} mediaSource
     * @param {array} previousSourceBufferSinks
     * @return {Promise<array>}
     * @private
     */
    function _commonMediaInitialization(mediaSource, previousSourceBufferSinks, representationsFromPreviousPeriod) {
        return new Promise((resolve, reject) => {
            checkConfig();
 
            _addInlineEvents();
 
 
            let element = videoModel.getElement();
            const promises = [];
            MEDIA_TYPES.forEach((mediaType) => {
                // If we are preloading without a video element we can not start texttrack handling.
                if (!(mediaType === Constants.TEXT && !mediaSource) && (mediaType !== Constants.VIDEO || (!element || (element && (/^VIDEO$/i).test(element.nodeName))))) {
                    const representationFromPreviousPeriod = representationsFromPreviousPeriod.find((representation) => {
                        return representation.mediaInfo.type === mediaType
                    })
                    promises.push(_initializeMediaForType(mediaType, mediaSource, representationFromPreviousPeriod));
                }
            });
 
            Promise.all(promises)
                .then(() => {
                    return _createBufferSinks(previousSourceBufferSinks)
                })
                .then((bufferSinks) => {
                    if (streamProcessors.length === 0) {
                        const msg = 'No streams to play.';
                        errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_NOSTREAMS_CODE, msg, manifestModel.getValue()));
                        logger.fatal(msg);
                    } else {
                        _initializationCompleted();
                    }
 
                    if (mediaSource) {
                        // All mediaInfos for texttracks are added to the TextSourceBuffer by now. We can start creating the tracks
                        textController.createTracks(streamInfo);
                    }
 
                    resolve(bufferSinks);
                })
                .catch((e) => {
                    reject(e);
                });
        });
    }
 
    /**
     * We call this function if segments have been preloaded without a video element. Once the video element is attached MSE is available
     * @param mediaSource
     * @returns {Promise<unknown>}
     */
    function initializeForTextWithMediaSource(mediaSource) {
        return new Promise((resolve, reject) => {
            _initializeMediaForType(Constants.TEXT, mediaSource, null)
                .then(() => {
                    return createBufferSinkForText()
                })
                .then(() => {
                    textController.createTracks(streamInfo);
                    resolve()
                })
                .catch((e) => {
                    reject(e);
                })
        })
    }
 
    /**
     * Initialize for a given media type. Creates a corresponding StreamProcessor
     * @param {string} type
     * @param {object} mediaSource
     * @private
     */
    function _initializeMediaForType(type, mediaSource, representationFromPreviousPeriod) {
        let allMediaForType = adapter.getAllMediaInfoForType(streamInfo, type);
        let embeddedMediaInfos = [];
 
        let mediaInfo = null;
        let initialMediaInfo;
        let enhancementMediaInfoIndex = -1;
 
        Iif (!allMediaForType || allMediaForType.length === 0) {
            logger.info('No ' + type + ' data.');
            return Promise.resolve();
        }
 
        if (type === Constants.VIDEO) {
            hasVideoTrack = true;
        }
 
        Iif (type === Constants.AUDIO) {
            hasAudioTrack = true;
        }
 
        for (let i = 0, ln = allMediaForType.length; i < ln; i++) {
            mediaInfo = allMediaForType[i];
 
            Iif (type === Constants.TEXT && !!mediaInfo.isEmbedded) {
                textController.addEmbeddedTrack(streamInfo, mediaInfo);
                embeddedMediaInfos.push(mediaInfo);
            }
            if (_isMediaSupported(mediaInfo)) {
                mediaController.addTrack(mediaInfo);
            }
 
            Iif (mediaInfo.type === Constants.ENHANCEMENT) {
                enhancementMediaInfoIndex = i;
            }
        }
 
        Iif (embeddedMediaInfos.length > 0) {
            mediaController.setInitialMediaSettingsForType(type, streamInfo);
            textController.addMediaInfosToBuffer(streamInfo, type, embeddedMediaInfos);
        }
 
        // Filter out embedded text track before creating StreamProcessor
        allMediaForType = allMediaForType.filter(mediaInfo => {
            return !mediaInfo.isEmbedded;
        });
        Iif (allMediaForType.length === 0) {
            return Promise.resolve();
        }
 
        Iif (type === Constants.IMAGE) {
            thumbnailController = ThumbnailController(context).create({
                streamInfo: streamInfo,
                adapter: adapter,
                baseURLController: config.baseURLController,
                timelineConverter: config.timelineConverter,
                debug: debug,
                eventBus: eventBus,
                events: Events,
                dashConstants: DashConstants,
                dashMetrics: config.dashMetrics,
                segmentBaseController: config.segmentBaseController
            });
            thumbnailController.initialize();
            return Promise.resolve();
        }
 
        eventBus.trigger(Events.STREAM_INITIALIZING, {
            streamInfo: streamInfo,
            mediaInfo: mediaInfo
        });
 
        mediaController.setInitialMediaSettingsForType(type, streamInfo);
 
        let streamProcessor = _createStreamProcessor(allMediaForType, mediaSource, type);
 
        if (enhancementMediaInfoIndex >= 0) {
            // An adaptation set, mapped to mediaInfo, of enhancement type was found so a stream processor shall be created for it
            // the enhancement stream processor will work in parallel to the media stream processor it enhances
            let enhancementMediaSource = new ExternalMediaSource(eventBus);
            enhancementMediaSource.open();
            enhancementMediaSource.duration = streamInfo.manifestInfo.duration;
            let enhancementStreamProcessor = _createStreamProcessor(allMediaForType, enhancementMediaSource, Constants.ENHANCEMENT);
            enhancementStreamProcessor.selectMediaInfo(new MediaInfoSelectionInput({ newMediaInfo: allMediaForType[enhancementMediaInfoIndex] }));
            streamProcessor.setEnhancementStreamProcessor(enhancementStreamProcessor);
        }
 
        initialMediaInfo = mediaController.getCurrentTrackFor(type, streamInfo.id);
 
        if (initialMediaInfo) {
            // In case of mixed fragmented and embedded text tracks, check if initial selected text track is not an embedded track
            const newMediaInfo = type !== Constants.TEXT || !initialMediaInfo.isEmbedded ? initialMediaInfo : allMediaForType[0];
            const mediaInfoSelectionInput = new MediaInfoSelectionInput({
                newMediaInfo,
                previouslySelectedRepresentation: representationFromPreviousPeriod
            });
            return streamProcessor.selectMediaInfo(mediaInfoSelectionInput);
        }
 
        return Promise.resolve();
    }
 
    function _isMediaSupported(mediaInfo) {
        const type = mediaInfo ? mediaInfo.type : null;
        let msg;
 
        Iif (type === Constants.MUXED) {
            msg = 'Multiplexed representations are intentionally not supported, as they are not compliant with the DASH-AVC/264 guidelines';
            logger.fatal(msg);
            errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_MULTIPLEXED_CODE, msg, manifestModel.getValue()));
            return false;
        }
 
        Iif (type === Constants.TEXT || type === Constants.IMAGE) {
            return true;
        }
 
        Iif (!!mediaInfo.contentProtection && mediaInfo.contentProtection.length > 0 && !capabilities.supportsEncryptedMedia()) {
            errHandler.error(new DashJSError(Errors.CAPABILITY_MEDIAKEYS_ERROR_CODE, Errors.CAPABILITY_MEDIAKEYS_ERROR_MESSAGE));
            return false;
        }
 
        return true;
    }
 
    /**
     * Creates the StreamProcessor for a given media type.
     * @param {array} allMediaForType
     * @param {object} mediaSource
     * @param {object} streamProcessorMediaType
     * @private
     */
    function _createStreamProcessor(allMediaForType, mediaSource, streamProcessorMediaType) {
 
        const mediaInfo = (allMediaForType && allMediaForType.length > 0) ? allMediaForType.filter(m => (m.type === streamProcessorMediaType))[0] : null;
        let fragmentModel = fragmentController.getModel(mediaInfo ? mediaInfo.type : null);
        const type = mediaInfo ? mediaInfo.type : null;
        const mimeType = mediaInfo ? mediaInfo.mimeType : null;
        const isFragmented = mediaInfo ? mediaInfo.isFragmented : null;
 
        let streamProcessor = StreamProcessor(context).create({
            abrController,
            adapter,
            baseURLController: config.baseURLController,
            boxParser,
            capabilities,
            dashMetrics: config.dashMetrics,
            errHandler,
            fragmentModel,
            manifestModel,
            mediaController,
            mediaPlayerModel,
            mimeType,
            playbackController,
            segmentBaseController: config.segmentBaseController,
            segmentBlacklistController,
            settings,
            streamInfo,
            textController,
            throughputController,
            timelineConverter,
            type,
        });
 
        streamProcessor.initialize(mediaSource, hasVideoTrack, isFragmented);
        streamProcessors.push(streamProcessor);
        streamProcessor.setMediaInfoArray(allMediaForType);
 
        if (type === Constants.TEXT) {
            textController.addMediaInfosToBuffer(streamInfo, type, allMediaForType, fragmentModel);
        }
 
        return streamProcessor;
    }
 
    /**
     * Creates the SourceBufferSink objects for all StreamProcessors
     * @param {array} previousSourceBufferSinks
     * @return {Promise<object>}
     * @private
     */
    function _createBufferSinks(previousSourceBufferSinks) {
        return new Promise((resolve) => {
            const buffers = {};
            const promises = streamProcessors.map((sp) => {
                const oldRepresentation = sp.getRepresentation();
                return sp.createBufferSinks(previousSourceBufferSinks, oldRepresentation);
            });
 
            Promise.all(promises)
                .then((bufferSinks) => {
                    bufferSinks.forEach((sink) => {
                        if (sink) {
                            buffers[sink.getType()] = sink;
                        }
                    });
                    resolve(buffers);
                })
                .catch(() => {
                    resolve(buffers);
                });
        });
    }
 
    function createBufferSinkForText() {
        const sp = _getProcessorByType(Constants.TEXT);
        if (sp) {
            return sp.createBufferSinks()
        }
 
        return Promise.resolve();
    }
 
    /**
     * Partially resets some of the Stream elements. This function is called when preloading of streams is canceled or a stream switch occurs.
     * @memberof Stream#
     * @param {boolean} keepBuffers
     */
    function deactivate(keepBuffers) {
        let ln = streamProcessors ? streamProcessors.length : 0;
        const errored = false;
        for (let i = 0; i < ln; i++) {
            let fragmentModel = streamProcessors[i].getFragmentModel();
            fragmentModel.abortRequests();
            fragmentModel.resetInitialSettings();
            streamProcessors[i].reset(errored, keepBuffers);
        }
        if (textController) {
            textController.deactivateStream(streamInfo);
        }
        Iif (thumbnailController) {
            thumbnailController.reset();
            thumbnailController = null;
        }
        streamProcessors = [];
        isActive = false;
        hasFinishedBuffering = false;
        _setPreloaded(false);
        setIsEndedEventSignaled(false);
        eventBus.trigger(Events.STREAM_DEACTIVATED, { streamInfo });
    }
 
    function getIsActive() {
        return isActive;
    }
 
    function setMediaSource(mediaSource) {
        return new Promise((resolve, reject) => {
            const promises = [];
            for (let i = 0; i < streamProcessors.length;) {
                if (_isMediaSupported(streamProcessors[i].getMediaInfo())) {
                    promises.push(streamProcessors[i].setMediaSource(mediaSource));
                    i++;
                } else {
                    streamProcessors[i].reset();
                    streamProcessors.splice(i, 1);
                }
            }
 
            Promise.all(promises)
                .then(() => {
                    for (let i = 0; i < streamProcessors.length; i++) {
                        //Adding of new tracks to a stream processor isn't guaranteed by the spec after the METADATA_LOADED state
                        //so do this after the buffers are created above.
                        streamProcessors[i].dischargePreBuffer();
                    }
 
                    if (streamProcessors.length === 0) {
                        const msg = 'No streams to play.';
                        errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_NOSTREAMS_CODE, msg + 'nostreams', manifestModel.getValue()));
                        logger.fatal(msg);
                    }
                    resolve();
                })
                .catch((e) => {
                    logger.error(e);
                    reject(e);
                })
        })
    }
 
    function resetInitialSettings(keepBuffers) {
        deactivate(keepBuffers);
        isInitialized = false;
        hasVideoTrack = false;
        hasAudioTrack = false;
        isEndedEventSignaled = false;
        trackChangedEvents = [];
    }
 
    function reset(keepBuffers) {
 
        if (fragmentController) {
            fragmentController.reset();
            fragmentController = null;
        }
 
        if (abrController && streamInfo) {
            abrController.clearDataForStream(streamInfo.id);
        }
 
        if (segmentBlacklistController) {
            segmentBlacklistController.reset();
            segmentBlacklistController = null;
        }
 
        if (textController && streamInfo) {
            textController.clearDataForStream(streamInfo.id);
        }
 
        if (mediaController && streamInfo) {
            mediaController.clearDataForStream(streamInfo.id);
        }
 
        resetInitialSettings(keepBuffers);
 
        streamInfo = null;
 
        unRegisterEvents();
 
        unRegisterProtectionEvents();
 
    }
 
    function getDuration() {
        return streamInfo ? streamInfo.duration : NaN;
    }
 
    function getIsEndedEventSignaled() {
        return isEndedEventSignaled;
    }
 
    function setIsEndedEventSignaled(value) {
        isEndedEventSignaled = value;
    }
 
    function getStartTime() {
        return streamInfo ? streamInfo.start : NaN;
    }
 
    function getId() {
        return streamInfo ? streamInfo.id : null;
    }
 
    function getStreamInfo() {
        return streamInfo;
    }
 
    function getHasAudioTrack() {
        return hasAudioTrack;
    }
 
    function getHasVideoTrack() {
        return hasVideoTrack;
    }
 
    function getThumbnailController() {
        return thumbnailController;
    }
 
    function checkConfig() {
        Iif (!videoModel || !abrController) {
            throw new Error(Constants.MISSING_CONFIG_ERROR);
        }
    }
 
    /**
     * @param {string} type
     * @returns {Array}
     * @memberof Stream#
     */
    function getRepresentationsByType(type) {
        checkConfig();
        if (type === Constants.IMAGE) {
            if (!thumbnailController) {
                return [];
            }
            return thumbnailController.getPossibleVoRepresentations();
        }
        const mediaInfo = _getMediaInfo(type);
        return abrController.getPossibleVoRepresentationsFilteredBySettings(mediaInfo, true);
    }
 
    /**
     * @param {string} type
     * @param {string} id
     * @returns {Array}
     * @memberof Stream#
     */
    function getRepresentationForTypeById(type, id) {
        let possibleVoRepresentations;
 
        if (type === Constants.IMAGE) {
            if (!thumbnailController) {
                return null;
            }
            possibleVoRepresentations = thumbnailController.getPossibleVoRepresentations();
        } else {
            const mediaInfos = _getAllMediaInfos(type);
 
            possibleVoRepresentations = mediaInfos.flatMap((mediaInfo) => {
                return abrController.getPossibleVoRepresentationsFilteredBySettings(mediaInfo, true);
            })
        }
 
        if (!possibleVoRepresentations || possibleVoRepresentations.length === 0) {
            return null
        }
        const targetReps = possibleVoRepresentations.filter((rep) => {
            return rep.id === id
        })
 
        return targetReps && targetReps.length > 0 ? targetReps[0] : null;
    }
 
    /**
     * @param {string} type
     * @param {number} index
     * @returns {Array}
     * @memberof Stream#
     */
    function getRepresentationForTypeByIndex(type, index) {
        let possibleVoRepresentations;
 
        if (type === Constants.IMAGE) {
            if (!thumbnailController) {
                return null;
            }
            possibleVoRepresentations = thumbnailController.getPossibleVoRepresentations();
        } else {
            const mediaInfo = _getMediaInfo(type);
            possibleVoRepresentations = abrController.getPossibleVoRepresentationsFilteredBySettings(mediaInfo, true);
        }
 
        index = Math.max(Math.min(index, possibleVoRepresentations.length - 1), 0)
 
        return possibleVoRepresentations[index];
    }
 
    function _onProtectionError(event) {
        if (event.error) {
            errHandler.error(event.error);
            logger.fatal(event.error.message);
        }
    }
 
    function triggerProtectionError(event) {
        _onProtectionError(event);
    }
 
    function prepareTrackChange(e) {
        if (!isActive || !streamInfo) {
            return;
        }
 
        hasFinishedBuffering = false;
 
        let newMediaInfo = e.newMediaInfo;
        let manifest = manifestModel.getValue();
 
        let processor = getProcessorForMediaInfo(newMediaInfo);
        if (!processor) {
            return;
        }
 
        let currentTime = playbackController.getTime();
        logger.info('Stream -  Process track changed at current time ' + currentTime);
 
        // Applies only for MSS streams
        if (manifest.refreshManifestOnSwitchTrack) {
            trackChangedEvents.push(e);
            if (!manifestUpdater.getIsUpdating()) {
                logger.debug('Stream -  Refreshing manifest for switch track');
                manifestUpdater.refreshManifest();
            }
        } else {
            processor.clearScheduleTimer();
            processor.setTrackSwitchInProgress(true);
            const oldRepresentation = processor.getRepresentation();
            processor.selectMediaInfo(new MediaInfoSelectionInput({ newMediaInfo }))
                .then(() => {
                    const replaceBuffer = e && e.options && e.options.hasOwnProperty('replaceBuffer') ? e.options.replaceBuffer : false;
                    return processor.prepareTrackSwitch(oldRepresentation, replaceBuffer);
                })
                .then(() => {
                    processor.setTrackSwitchInProgress(false);
                })
        }
    }
 
    function prepareQualityChange(e) {
        const processor = _getProcessorByType(e.mediaType);
 
        if (processor) {
            processor.prepareQualityChange(e);
        }
    }
 
    function _addInlineEvents() {
        if (eventController) {
            const events = adapter.getEventsFor(streamInfo);
            Iif (events && events.length > 0) {
                eventController.addInlineEvents(events, streamInfo.id);
            }
        }
    }
 
    function _getMediaInfo(type) {
        let streamProcessor = _getStreamProcessorForType(type);
 
        if (streamProcessor) {
            return streamProcessor.getMediaInfo();
        }
 
        return null;
    }
 
    function _getAllMediaInfos(type) {
        let streamProcessor = _getStreamProcessorForType(type);
 
        if (streamProcessor) {
            return streamProcessor.getAllMediaInfos();
        }
 
        return [];
    }
 
    function _getStreamProcessorForType(type) {
        if (!type) {
            return null
        }
 
        return streamProcessors.find((streamProcessor) => {
            return streamProcessor.getType() === type;
        })
    }
 
    function _onBufferingCompleted() {
        let processors = getStreamProcessors();
        const ln = processors.length;
 
        if (ln === 0) {
            logger.warn('onBufferingCompleted - can\'t trigger STREAM_BUFFERING_COMPLETED because no streamProcessor is defined');
            return;
        }
 
        // if there is at least one buffer controller that has not completed buffering yet do nothing
        for (let i = 0; i < ln; i++) {
            //if audio or video buffer is not buffering completed state, do not send STREAM_BUFFERING_COMPLETED
            if (!processors[i].isBufferingCompleted() && (processors[i].getType() === Constants.AUDIO || processors[i].getType() === Constants.VIDEO)) {
                logger.debug('onBufferingCompleted - One streamProcessor has finished but', processors[i].getType(), 'one is not buffering completed');
                return;
            }
        }
 
        logger.debug('onBufferingCompleted - trigger STREAM_BUFFERING_COMPLETED');
        hasFinishedBuffering = true;
        eventBus.trigger(Events.STREAM_BUFFERING_COMPLETED, { streamInfo: streamInfo }, { streamInfo });
    }
 
    function _onInbandEvents(e) {
        if (eventController) {
            eventController.addInbandEvents(e.events, streamInfo.id);
        }
    }
 
    function _onDataUpdateCompleted() {
        _initializationCompleted();
    }
 
    function _onPlaybackSeeked() {
        _addInlineEvents();
    }
 
    function getProcessorForMediaInfo(mediaInfo) {
        if (!mediaInfo || !mediaInfo.type) {
            return null;
        }
 
        return _getProcessorByType(mediaInfo.type);
    }
 
    function _getProcessorByType(type) {
        if (!type) {
            return null;
        }
 
        let processors = getStreamProcessors();
 
        return processors.filter(function (processor) {
            return (processor.getType() === type);
        })[0];
    }
 
    function getStreamProcessors() {
        let arr = [];
 
        let type,
            streamProcessor;
 
        for (let i = 0; i < streamProcessors.length; i++) {
            streamProcessor = streamProcessors[i];
            type = streamProcessor.getType();
 
            if (type === Constants.AUDIO || type === Constants.VIDEO || type === Constants.TEXT || type === Constants.ENHANCEMENT) {
                arr.push(streamProcessor);
            }
        }
 
        return arr;
    }
 
    function startScheduleControllers() {
        const ln = streamProcessors.length;
        for (let i = 0; i < ln && streamProcessors[i]; i++) {
            streamProcessors[i].getScheduleController().startScheduleTimer();
        }
    }
 
    function updateData(updatedStreamInfo) {
        return new Promise((resolve) => {
            streamInfo = updatedStreamInfo;
 
            if (eventController) {
                _addInlineEvents();
            }
 
            let promises = [];
            for (let i = 0, ln = streamProcessors.length; i < ln; i++) {
                let streamProcessor = streamProcessors[i];
                const currentMediaInfo = streamProcessor.getMediaInfo();
                promises.push(streamProcessor.updateStreamInfo(streamInfo));
                let allMediaForType = adapter.getAllMediaInfoForType(streamInfo, streamProcessor.getType());
 
                // Filter out embedded text track before updating media info in  StreamProcessor
                allMediaForType = allMediaForType.filter(mediaInfo => {
                    return !mediaInfo.isEmbedded;
                });
 
                // Check if AdaptationSet has not been removed in MPD update
                streamProcessor.setMediaInfoArray(allMediaForType);
                if (allMediaForType) {
                    for (let j = 0; j < allMediaForType.length; j++) {
                        if (adapter.areMediaInfosEqual(currentMediaInfo, allMediaForType[j])) {
                            promises.push(streamProcessor.selectMediaInfo(new MediaInfoSelectionInput({ newMediaInfo: allMediaForType[j] })))
                        }
                    }
                }
            }
 
            let processor;
            Promise.all(promises)
                .then(() => {
                    let promises = [];
 
                    // Only relevant for MSS
                    while (trackChangedEvents.length > 0) {
                        let trackChangedEvent = trackChangedEvents.pop();
                        let newMediaInfo = trackChangedEvent.newMediaInfo;
                        processor = getProcessorForMediaInfo(trackChangedEvent.oldMediaInfo);
                        if (!processor) {
                            return;
                        }
                        const oldRepresentation = processor.getRepresentation();
                        processor.setTrackSwitchInProgress(true);
                        promises.push(processor.prepareTrackSwitch(oldRepresentation));
                        promises.push(processor.selectMediaInfo(new MediaInfoSelectionInput({ newMediaInfo })));
                    }
 
                    return Promise.all(promises)
                })
                .then(() => {
                    _initializationCompleted();
                    if (processor) {
                        processor.setTrackSwitchInProgress(false);
                    }
                    eventBus.trigger(Events.STREAM_UPDATED, { streamInfo: streamInfo });
                    resolve();
                })
                .catch((e) => {
                    errHandler.error(e);
                })
 
        })
    }
 
    function _initializationCompleted() {
        const ln = streamProcessors.length;
 
        if (protectionController) {
            // Need to check if streamProcessors exists because streamProcessors
            // could be cleared in case an error is detected while initializing DRM keysystem
            protectionController.clearMediaInfoArray();
            for (let i = 0; i < ln && streamProcessors[i]; i++) {
                const type = streamProcessors[i].getType();
                const mediaInfo = streamProcessors[i].getMediaInfo();
                if (type === Constants.AUDIO ||
                    type === Constants.VIDEO ||
                    (type === Constants.TEXT && mediaInfo && mediaInfo.isFragmented)) {
                    let mediaInfo = streamProcessors[i].getMediaInfo();
                    if (mediaInfo) {
                        protectionController.initializeForMedia(mediaInfo);
                    }
                }
            }
            protectionController.handleKeySystemFromManifest();
        }
 
        if (!isInitialized) {
            isInitialized = true;
            videoModel.waitForReadyState(Constants.VIDEO_ELEMENT_READY_STATES.HAVE_METADATA, () => {
                eventBus.trigger(Events.STREAM_INITIALIZED, {
                    streamInfo: streamInfo
                });
            })
        }
    }
 
    function _setPreloaded(value) {
        preloaded = value;
    }
 
    function getPreloaded() {
        return preloaded;
    }
 
    function getHasFinishedBuffering() {
        return hasFinishedBuffering;
    }
 
    function getAdapter() {
        return adapter;
    }
 
    function getCurrentRepresentationForType(type) {
        const sp = _getProcessorByType(type);
 
        if (!sp) {
            return null;
        }
 
        return sp.getRepresentation();
    }
 
    function getCurrentMediaInfoForType(type) {
        const sp = _getProcessorByType(type);
 
        if (!sp) {
            return null;
        }
 
        return sp.getMediaInfo();
    }
 
    function checkAndHandleCompletedBuffering() {
        Iif (hasFinishedBuffering) {
            return;
        }
        streamProcessors.forEach((streamProcessor) => {
            streamProcessor.checkAndHandleCompletedBuffering();
        })
    }
 
    instance = {
        activate,
        checkAndHandleCompletedBuffering,
        deactivate,
        getAdapter,
        getCurrentMediaInfoForType,
        getCurrentRepresentationForType,
        getDuration,
        getHasAudioTrack,
        getHasFinishedBuffering,
        getHasVideoTrack,
        getId,
        getIsActive,
        getIsEndedEventSignaled,
        getPreloaded,
        getRepresentationForTypeById,
        getRepresentationForTypeByIndex,
        getRepresentationsByType,
        getStartTime,
        getStreamId,
        getStreamInfo,
        getStreamProcessors,
        getThumbnailController,
        initialize,
        initializeForTextWithMediaSource,
        prepareQualityChange,
        prepareTrackChange,
        reset,
        setIsEndedEventSignaled,
        setMediaSource,
        startPreloading,
        startScheduleControllers,
        triggerProtectionError,
        updateData,
    };
 
    setup();
    return instance;
}
 
Stream.__dashjs_factory_name = 'Stream';
export default FactoryMaker.getClassFactory(Stream);