All files / dash.js/src/streaming/controllers AbrController.js

61.51% Statements 243/395
50.16% Branches 152/303
65.27% Functions 47/72
61.67% Lines 243/394

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                                                                                          1x 1x       3x 3x 3x                                                 3x 3x             38x 38x 38x           38x   38x 38x 38x 38x                   38x   38x 38x   38x   38x 38x   38x 38x     38x 38x 38x                                                   41x 41x 41x   41x 38x     41x 38x     41x 41x 41x 41x 41x         38x   38x 38x 38x 38x   38x 38x         38x       38x 38x   38x 38x   38x 38x   38x 38x   38x 38x   38x 38x   38x 38x   38x 38x   38x 38x   38x 38x   38x 38x         12x   12x 1x       11x 12x   11x 1x       10x 21x     10x 1x     9x 9x                                           27x     27x   27x       27x 27x 1x     26x 26x 26x   26x 26x       26x     26x     26x 68x             26x 68x   68x 68x     26x       26x 26x   26x 26x       26x     26x                                       27x 27x 27x 27x   27x                         27x 27x 68x 68x 68x 68x   68x 9x     59x     27x 24x     3x                         27x 27x 26x     1x   1x 3x     1x 1x                             27x   27x 27x                                                             26x 1x   25x     26x       26x 26x 68x 26x   68x     26x       1x 1x     1x         25x     41x 38x 1x   37x           3x 1x 2x 2x             25x         26x 68x               26x                                                                                                                                                                                                                                                               2x 1x     1x 1x       1x 1x 1x   1x 1x                                                                                                                       16x 5x       11x 2x     9x       9x 3x         6x       6x 6x     6x 1x     5x   5x 5x                                                           7x 2x     5x 5x   5x 4x     1x       3x 3x 3x 3x   3x 2x 2x     1x       2x 2x 2x 2x             1x 1x 1x 1x 1x     1x       1x 1x 1x 1x   1x       1x   1x 1x 1x             3x                   1x                               4x 4x       4x 4x 4x 4x   4x 4x                       4x 4x       4x 4x 4x                     38x                                                                                               1x 1x                                                         3x                                             3x   3x     1x 1x 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 ABRRulesCollection from '../rules/abr/ABRRulesCollection.js';
import Constants from '../constants/Constants.js';
import MetricsConstants from '../constants/MetricsConstants.js';
import FragmentModel from '../models/FragmentModel.js';
import EventBus from '../../core/EventBus.js';
import Events from '../../core/events/Events.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import RulesContext from '../rules/RulesContext.js';
import SwitchRequest from '../rules/SwitchRequest.js';
import SwitchRequestHistory from '../rules/SwitchRequestHistory.js';
import DroppedFramesHistory from '../rules/DroppedFramesHistory.js';
import Debug from '../../core/Debug.js';
import MediaPlayerEvents from '../MediaPlayerEvents.js';
 
const DEFAULT_VIDEO_BITRATE = 1000;
const DEFAULT_BITRATE = 100;
 
function AbrController() {
 
    const context = this.context;
    const debug = Debug(context).getInstance();
    const eventBus = EventBus(context).getInstance();
 
    let abandonmentStateDict,
        abandonmentTimeout,
        abrRulesCollection,
        adapter,
        capabilities,
        cmsdModel,
        currentRepresentationId,
        customParametersModel,
        dashMetrics,
        domStorage,
        droppedFramesHistory,
        instance,
        logger,
        mediaPlayerModel,
        queuedManualQualitySwitches,
        settings,
        streamController,
        streamProcessorDict,
        switchRequestHistory,
        throughputController,
        videoModel
 
    function setup() {
        logger = debug.getLogger(instance);
        resetInitialSettings();
    }
 
    /**
     * Initialize everything that is not period specific. We only have one instance of the ABR Controller for all periods.
     */
    function initialize() {
        droppedFramesHistory = DroppedFramesHistory(context).create();
        switchRequestHistory = SwitchRequestHistory(context).create();
        abrRulesCollection = ABRRulesCollection(context).create({
            dashMetrics,
            customParametersModel,
            mediaPlayerModel,
            settings
        });
        abrRulesCollection.initialize();
 
        eventBus.on(MediaPlayerEvents.QUALITY_CHANGE_RENDERED, _onQualityChangeRendered, instance);
        eventBus.on(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);
        eventBus.on(Events.LOADING_PROGRESS, _onFragmentLoadProgress, instance);
        eventBus.on(Events.VIDEO_ELEMENT_RESIZED, _onVideoElementResized, instance);
    }
 
    /**
     * Whenever a StreamProcessor is created it is added to the list of streamProcessorDict
     * In addition, the corresponding objects for this object and its stream id are created
     * @param {object} type
     * @param {object} streamProcessor
     */
    function registerStreamType(type, streamProcessor) {
        const streamId = streamProcessor.getStreamInfo().id;
 
        if (!streamProcessorDict[streamId]) {
            streamProcessorDict[streamId] = {};
        }
        streamProcessorDict[streamId][type] = streamProcessor;
 
        if (!abandonmentStateDict[streamId]) {
            abandonmentStateDict[streamId] = {};
        }
        abandonmentStateDict[streamId][type] = {};
        abandonmentStateDict[streamId][type].state = MetricsConstants.ALLOW_LOAD;
 
        // Do not change current value if it has been set before
        const currentState = abrRulesCollection.getBolaState(type)
        if (currentState === undefined) {
            abrRulesCollection.setBolaState(type, settings.get().streaming.abr.rules.bolaRule.active && !_shouldApplyDynamicAbrStrategy());
        }
 
    }
 
    /**
     * Remove all parameters that belong to a specific period
     * @param {string} streamId
     * @param {string} type
     */
    function unRegisterStreamType(streamId, type) {
        try {
            if (streamProcessorDict[streamId] && streamProcessorDict[streamId][type]) {
                delete streamProcessorDict[streamId][type];
            }
 
            if (abandonmentStateDict[streamId] && abandonmentStateDict[streamId][type]) {
                delete abandonmentStateDict[streamId][type];
            }
 
        } catch (e) {
 
        }
    }
 
    function resetInitialSettings() {
        abandonmentStateDict = {};
        streamProcessorDict = {};
        queuedManualQualitySwitches = new Map();
 
        if (droppedFramesHistory) {
            droppedFramesHistory.reset();
        }
 
        if (switchRequestHistory) {
            switchRequestHistory.reset();
        }
 
        currentRepresentationId = undefined;
        droppedFramesHistory = undefined;
        switchRequestHistory = undefined;
        clearTimeout(abandonmentTimeout);
        abandonmentTimeout = null;
    }
 
    function reset() {
 
        resetInitialSettings();
 
        eventBus.off(MediaPlayerEvents.QUALITY_CHANGE_RENDERED, _onQualityChangeRendered, instance);
        eventBus.off(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);
        eventBus.off(Events.LOADING_PROGRESS, _onFragmentLoadProgress, instance);
        eventBus.off(Events.VIDEO_ELEMENT_RESIZED, _onVideoElementResized, instance);
 
        if (abrRulesCollection) {
            abrRulesCollection.reset();
        }
    }
 
    function setConfig(config) {
        Iif (!config) {
            return;
        }
 
        if (config.streamController) {
            streamController = config.streamController;
        }
        if (config.throughputController) {
            throughputController = config.throughputController;
        }
        if (config.domStorage) {
            domStorage = config.domStorage;
        }
        if (config.mediaPlayerModel) {
            mediaPlayerModel = config.mediaPlayerModel;
        }
        if (config.customParametersModel) {
            customParametersModel = config.customParametersModel;
        }
        if (config.cmsdModel) {
            cmsdModel = config.cmsdModel
        }
        if (config.dashMetrics) {
            dashMetrics = config.dashMetrics;
        }
        if (config.adapter) {
            adapter = config.adapter;
        }
        if (config.videoModel) {
            videoModel = config.videoModel;
        }
        if (config.settings) {
            settings = config.settings;
        }
        if (config.capabilities) {
            capabilities = config.capabilities;
        }
    }
 
    function getOptimalRepresentationForBitrate(mediaInfo, bitrateInKbit, includeCompatibleMediaInfos = true) {
        const possibleVoRepresentations = getPossibleVoRepresentationsFilteredBySettings(mediaInfo, includeCompatibleMediaInfos);
 
        if (!possibleVoRepresentations || possibleVoRepresentations.length === 0) {
            return null;
        }
 
        // If bitrate should be as small as possible return the Representation with the lowest bitrate
        const smallestRepresentation = possibleVoRepresentations.reduce((a, b) => {
            return a.bandwidth < b.bandwidth ? a : b;
        })
        if (bitrateInKbit <= 0) {
            return smallestRepresentation
        }
 
        // Get all Representations that have lower or equal bitrate than our target bitrate
        const targetRepresentations = possibleVoRepresentations.filter((rep) => {
            return rep.bitrateInKbit <= bitrateInKbit
        });
 
        if (!targetRepresentations || targetRepresentations.length === 0) {
            return smallestRepresentation
        }
 
        return targetRepresentations.reduce((max, curr) => {
            return (curr.absoluteIndex > max.absoluteIndex) ? curr : max;
        })
 
    }
 
    function getRepresentationByAbsoluteIndex(absoluteIndex, mediaInfo, includeCompatibleMediaInfos = true) {
        if (isNaN(absoluteIndex) || absoluteIndex < 0) {
            return null;
        }
 
        const possibleVoRepresentations = getPossibleVoRepresentationsFilteredBySettings(mediaInfo, includeCompatibleMediaInfos);
 
        return possibleVoRepresentations.find((rep) => {
            return rep.absoluteIndex === absoluteIndex
        })
    }
 
    function getPossibleVoRepresentations(mediaInfo, includeCompatibleMediaInfos = true) {
        return _getPossibleVoRepresentations(mediaInfo, includeCompatibleMediaInfos)
    }
 
    function getPossibleVoRepresentationsFilteredBySettings(mediaInfo, includeCompatibleMediaInfos = true) {
        let voRepresentations = _getPossibleVoRepresentations(mediaInfo, includeCompatibleMediaInfos);
 
        // Filter the list of options based on the provided settings
        voRepresentations = _filterByAllowedSettings(voRepresentations)
 
        return voRepresentations;
    }
 
    function _getPossibleVoRepresentations(mediaInfo, includeCompatibleMediaInfos) {
        let voRepresentations = [];
        if (!mediaInfo) {
            return voRepresentations;
        }
 
        const mediaInfos = _getPossibleMediaInfos(mediaInfo)
        mediaInfos.forEach((mediaInfo) => {
            let currentVoRepresentations = adapter.getVoRepresentations(mediaInfo);
 
            if (currentVoRepresentations && currentVoRepresentations.length > 0) {
                voRepresentations = voRepresentations.concat(currentVoRepresentations)
            }
        })
        // Resolve dependencies
        voRepresentations = _resolveDependencies(voRepresentations);
 
        // Now sort by quality (usually simply by bitrate)
        voRepresentations = _sortRepresentationsByQuality(voRepresentations);
 
        // Add an absolute index
        voRepresentations.forEach((rep, index) => {
            rep.absoluteIndex = index
        })
 
        // Filter the Representations in case we do not want to include compatible Media Infos
        // We can not apply the filter before otherwise the absolute index would be wrong
        // Also ignore Representations with a key ID that is not usable
 
        voRepresentations = voRepresentations.filter((representation) => {
            const isMediaInfoAllowed = includeCompatibleMediaInfos ? true : adapter.areMediaInfosEqual(representation.mediaInfo, mediaInfo);
            const areKeyIdsUsable =
                representation && representation.mediaInfo ? capabilities.areKeyIdsUsable(representation.mediaInfo) : true;
            return isMediaInfoAllowed && areKeyIdsUsable
        })
 
        return voRepresentations
    }
 
    function _getPossibleMediaInfos(mediaInfo) {
        try {
            const possibleMediaInfos = [];
 
            if (mediaInfo) {
                possibleMediaInfos.push(mediaInfo);
            }
 
            // If AS switching is disabled return only the current MediaInfo
            if (!settings.get().streaming.abr.enableSupplementalPropertyAdaptationSetSwitching
                || !mediaInfo.adaptationSetSwitchingCompatibleIds
                || mediaInfo.adaptationSetSwitchingCompatibleIds.length === 0) {
                return possibleMediaInfos
            }
 
            // Otherwise add everything that is compatible
            const mediaInfoArr = streamProcessorDict[mediaInfo.streamInfo.id][mediaInfo.type].getAllMediaInfos()
            const compatibleMediaInfos = mediaInfoArr.filter((entry) => {
                return mediaInfo.adaptationSetSwitchingCompatibleIds.includes(entry.id)
            })
 
            return possibleMediaInfos.concat(compatibleMediaInfos);
        } catch (e) {
            return [mediaInfo]
        }
    }
 
    /**
     * @param {Representation[]} voRepresentations
     * @return {Representation[]}
     */
    function _filterByAllowedSettings(voRepresentations) {
        try {
            voRepresentations = _filterByPossibleBitrate(voRepresentations);
            voRepresentations = _filterByPortalSize(voRepresentations);
            voRepresentations = _filterByCmsdMaxBitrate(voRepresentations);
 
            return voRepresentations;
        } catch (e) {
            logger.error(e);
            return voRepresentations
        }
    }
 
    /**
     * Returns all RepresentationInfo objects that have at least one bitrate that fulfills the constraint
     * @param {Representation[]} voRepresentations
     * @return {Representation[]}
     */
    function _filterByPossibleBitrate(voRepresentations) {
        try {
            const filteredArray = voRepresentations.filter((voRepresentation) => {
                const type = voRepresentation.mediaInfo.type;
                const representationBitrate = voRepresentation.bitrateInKbit;
                const maxBitrate = mediaPlayerModel.getAbrBitrateParameter('maxBitrate', type);
                const minBitrate = mediaPlayerModel.getAbrBitrateParameter('minBitrate', type);
 
                if (maxBitrate > -1 && representationBitrate > maxBitrate) {
                    return false;
                }
 
                return !(minBitrate > -1 && representationBitrate < minBitrate);
            })
 
            if (filteredArray.length > 0) {
                return filteredArray
            }
 
            return voRepresentations
        } catch (e) {
            logger.error(e);
            return voRepresentations
        }
    }
 
    /**
     * @param {Representation[]} voRepresentations
     * @return {Representation[]}
     * @private
     */
    function _filterByPortalSize(voRepresentations) {
        try {
            if (!settings.get().streaming.abr.limitBitrateByPortal) {
                return voRepresentations;
            }
 
            const { elementWidth } = videoModel.getVideoElementSize();
 
            const filteredArray = voRepresentations.filter((voRepresentation) => {
                return voRepresentation.mediaInfo.type !== Constants.VIDEO || voRepresentation.width <= elementWidth;
            })
 
            if (filteredArray.length > 0) {
                return filteredArray
            }
 
            return voRepresentations
        } catch (e) {
            logger.error(e);
            return voRepresentations
        }
    }
 
    /**
     * @param {Representation[]} voRepresentations
     * @return {Representation[]}
     */
    function _filterByCmsdMaxBitrate(voRepresentations) {
        try {
            // Check CMSD max suggested bitrate only for video segments
            if (!settings.get().streaming.cmsd.enabled || !settings.get().streaming.cmsd.abr.applyMb) {
                return voRepresentations
            }
 
            const filteredArray = voRepresentations.filter((voRepresentation) => {
                const type = voRepresentation.mediaInfo.type;
                let maxCmsdBitrate = cmsdModel.getMaxBitrate(type);
 
                if (type !== Constants.VIDEO || maxCmsdBitrate < 0) {
                    return true
                }
                // Subtract audio bitrate
                const streamId = voRepresentation.mediaInfo.streamInfo.id;
                const streamProcessor = streamProcessorDict[streamId][Constants.AUDIO];
                const representation = streamProcessor.getRepresentation();
                const audioBitrate = representation.bitrateInKbit;
                maxCmsdBitrate -= audioBitrate ? audioBitrate : 0;
                return voRepresentation.bitrateInKbit <= maxCmsdBitrate
            })
 
            if (filteredArray.length > 0) {
                return filteredArray
            }
 
            return voRepresentations
        } catch (e) {
            logger.error(e);
            return voRepresentations
        }
    }
 
    function _sortRepresentationsByQuality(voRepresentations) {
        if (_shouldSortByQualityRankingAttribute(voRepresentations)) {
            voRepresentations = _sortByQualityRankingAttribute(voRepresentations)
        } else {
            voRepresentations = _sortByDefaultParameters(voRepresentations)
        }
 
        return voRepresentations
    }
 
    function _shouldSortByQualityRankingAttribute(voRepresentations) {
        let firstMediaInfo = null;
        const filteredRepresentations = voRepresentations.filter((rep) => {
            if (!firstMediaInfo) {
                firstMediaInfo = rep.mediaInfo;
            }
            return !isNaN(rep.qualityRanking) && adapter.areMediaInfosEqual(firstMediaInfo, rep.mediaInfo);
        })
 
        return filteredRepresentations.length === voRepresentations.length
    }
 
    function _sortByQualityRankingAttribute(voRepresentations) {
        voRepresentations.sort((a, b) => {
            return b.qualityRanking - a.qualityRanking;
        })
 
        return voRepresentations
    }
 
 
    function _sortByDefaultParameters(voRepresentations) {
        voRepresentations.sort((a, b) => {
 
            // In case both Representations are coming from the same MediaInfo then choose the one with the highest resolution and highest bitrate
            if (adapter.areMediaInfosEqual(a.mediaInfo, b.mediaInfo)) {
                if (!isNaN(a.pixelsPerSecond) && !isNaN(b.pixelsPerSecond) && a.pixelsPerSecond !== b.pixelsPerSecond) {
                    return a.pixelsPerSecond - b.pixelsPerSecond
                } else {
                    return a.bandwidth - b.bandwidth
                }
            }
 
            // In case the Representations are coming from different MediaInfos they might have different codecs. The bandwidth is not a good indicator, use bits per pixel instead
            else {
                if (!isNaN(a.pixelsPerSecond) && !isNaN(b.pixelsPerSecond) && a.pixelsPerSecond !== b.pixelsPerSecond) {
                    return a.pixelsPerSecond - b.pixelsPerSecond
                } else if (!isNaN(a.bitsPerPixel) && !isNaN(b.bitsPerPixel)) {
                    return b.bitsPerPixel - a.bitsPerPixel
                } else E{
                    return a.bandwidth - b.bandwidth
                }
            }
        })
 
        return voRepresentations
    }
 
 
    function _resolveDependencies(voRepresentations) {
        voRepresentations.forEach(rep => {
            Iif (rep.dependentRepresentation && rep.dependentRepresentation.mediaInfo === null) {
                let dependentId = rep.dependentRepresentation.id;
                let dependentRep = voRepresentations.find((element) => element.id === dependentId);
                if (dependentRep) {
                    rep.dependentRepresentation = dependentRep;
                }
            }
        });
        return voRepresentations;
    }
 
    /**
     * While fragment loading is in progress we check if we might need to abort the request
     * @param {object} e
     * @private
     */
    function _onFragmentLoadProgress(e) {
        const type = e.request.mediaType;
        const streamId = e.streamId;
 
        if (!type || !streamId || !streamProcessorDict[streamId] || !settings.get().streaming.abr.autoSwitchBitrate[type]) {
            return;
        }
 
        const streamProcessor = streamProcessorDict[streamId][type];
        if (!streamProcessor) {
            return;
        }
 
        const lastSegment = streamProcessor.getLastSegment();
        const canAbandonRequest = _canAbandonRequest(lastSegment);
 
        if (!canAbandonRequest) {
            return;
        }
 
        const rulesContext = _createRulesContext(streamProcessor, e.request);
        const switchRequest = abrRulesCollection.shouldAbandonFragment(rulesContext);
 
        if (switchRequest && switchRequest.representation !== SwitchRequest.NO_CHANGE) {
            _onSegmentDownloadShouldBeAbandoned(e, streamId, type, streamProcessor, switchRequest);
        }
    }
 
    function _onVideoElementResized() {
        if (settings.get().streaming.abr.limitBitrateByPortal) {
            Object.keys(streamProcessorDict).forEach(streamId => {
                Object.keys(streamProcessorDict[streamId]).forEach(mediaType => {
                    checkPlaybackQuality(mediaType, streamId);
                });
            });
        }
    }
 
    function _createRulesContext(streamProcessor, currentRequest) {
        return RulesContext(context).create({
            abrController: instance,
            adapter,
            currentRequest,
            droppedFramesHistory,
            streamProcessor,
            switchRequestHistory,
            throughputController,
            videoModel
        });
    }
 
    function _canAbandonRequest(lastSegment) {
        // For now we only allow abandoning the first partial segment as we are sure there is an IDR at the beginning of the segment
        if (!lastSegment || !lastSegment.isPartialSegment || isNaN(lastSegment.totalNumberOfPartialSegments) || isNaN(lastSegment.replacementSubNumber)) {
            return true
        }
        return lastSegment.replacementSubNumber === 0;
    }
 
    function _onSegmentDownloadShouldBeAbandoned(e, streamId, type, streamProcessor, switchRequest) {
        const fragmentModel = streamProcessor.getFragmentModel();
        const request = fragmentModel.getRequests({
            state: FragmentModel.FRAGMENT_MODEL_LOADING,
            index: e.request.index
        })[0];
        if (request) {
            const targetAbandonmentStateDict = _getAbandonmentStateDictFor(streamId, type);
 
            if (targetAbandonmentStateDict) {
                targetAbandonmentStateDict.state = MetricsConstants.ABANDON_LOAD;
            }
            switchRequestHistory.reset();
            setPlaybackQuality(type, streamController.getActiveStreamInfo(), switchRequest.representation, switchRequest.reason);
 
            clearTimeout(abandonmentTimeout);
            abandonmentTimeout = setTimeout(
                () => {
                    if (targetAbandonmentStateDict) {
                        abandonmentStateDict[streamId][type].state = MetricsConstants.ALLOW_LOAD;
                    }
                    abandonmentTimeout = null;
                },
                settings.get().streaming.abandonLoadTimeout
            );
        }
    }
 
    /**
     * Update dropped frames history when the quality was changed
     * @param {object} e
     * @private
     */
    function _onQualityChangeRendered(e) {
        if (e.mediaType === Constants.VIDEO) {
            _addDroppedFramesHistoryEntry(e.streamId);
            currentRepresentationId = e.newRepresentation.id;
        }
    }
 
    /**
     * When the buffer level is updated we check if we need to change the ABR strategy
     * @param e
     * @private
     */
    function _onMetricAdded(e) {
        if (_shouldApplyDynamicAbrStrategy()
            && e.metric === MetricsConstants.BUFFER_LEVEL
            && (e.mediaType === Constants.AUDIO || e.mediaType === Constants.VIDEO)) {
            _updateDynamicAbrStrategy(e.mediaType, 0.001 * e.value.level);
        }
    }
 
    /**
     * Returns the initial bitrate for a specific media type
     * @param {string} type
     * @returns {number} A value of the initial bitrate, kbps
     * @memberof AbrController#
     */
    function getInitialBitrateFor(type) {
 
        if (type === Constants.TEXT) {
            return NaN;
        }
 
        let configBitrate = mediaPlayerModel.getAbrBitrateParameter('initialBitrate', type);
        Iif (configBitrate > 0) {
            return configBitrate;
        }
 
        let savedBitrate = NaN;
        if (domStorage && domStorage.hasOwnProperty('getSavedBitrateSettings')) {
            savedBitrate = domStorage.getSavedBitrateSettings(type);
        }
        if (!isNaN(savedBitrate)) {
            return savedBitrate
        }
 
        const averageThroughput = throughputController.getAverageThroughput(type);
        if (!isNaN(averageThroughput) && averageThroughput > 0) {
            return averageThroughput
        }
 
        return (type === Constants.VIDEO) ? DEFAULT_VIDEO_BITRATE : DEFAULT_BITRATE;
    }
 
    /**
     * This function is called by the scheduleControllers to check if the quality should be changed.
     * Consider this the main entry point for the ABR decision logic
     * @param {string} type
     * @param {string} streamId
     */
    function checkPlaybackQuality(type, streamId) {
        try {
            if (!type || !streamProcessorDict || !streamProcessorDict[streamId] || !streamProcessorDict[streamId][type]) {
                return false;
            }
 
            _addDroppedFramesHistoryEntry(streamId)
 
            const streamProcessor = streamProcessorDict[streamId][type];
            const lastSegment = streamProcessor.getLastSegment();
            const currentRepresentation = streamProcessor.getRepresentationController()?.getCurrentCompositeRepresentation();
            const canSwitchQuality = canPerformQualitySwitch(lastSegment, currentRepresentation);
 
            if (!settings.get().streaming.abr.autoSwitchBitrate[type] || !canSwitchQuality) {
                return false;
            }
 
            const rulesContext = _createRulesContext(streamProcessor);
            const switchRequest = abrRulesCollection.getBestPossibleSwitchRequest(rulesContext);
 
            if (!switchRequest || !switchRequest.representation) {
                return false;
            }
 
            let newRepresentation = switchRequest.representation;
            _addSwitchHistoryEntry(currentRepresentation, newRepresentation);
            if (newRepresentation.id !== currentRepresentation.id && (abandonmentStateDict[streamId][type].state === MetricsConstants.ALLOW_LOAD || newRepresentation.absoluteIndex < currentRepresentation.absoluteIndex)) {
                _changeQuality(type, currentRepresentation, newRepresentation, switchRequest.reason);
                return true;
            }
 
            return false;
        } catch (e) {
            logger.error(e);
            return false;
        }
    }
 
    /**
     * When playing Segment Sequence Representations we can not simply switch from one partial segment to another partial segment or another full segment.
     * @private
     */
    function canPerformQualitySwitch(lastSegment, currentRepresentation) {
        if (!lastSegment || !lastSegment.isPartialSegment || isNaN(lastSegment.totalNumberOfPartialSegments) || isNaN(lastSegment.replacementSubNumber)) {
            return true
        }
 
        // For partial segments we allow switching at the end of a segment sequence
        if (lastSegment.replacementSubNumber === (lastSegment.totalNumberOfPartialSegments - 1)) {
            return true;
        }
 
        return _segmentSequencePropertiesAllowsSwitching(lastSegment, currentRepresentation);
    }
 
    function _segmentSequencePropertiesAllowsSwitching(lastSegment, currentRepresentation) {
        if (!currentRepresentation || !currentRepresentation.segmentSequenceProperties || currentRepresentation.segmentSequenceProperties.length <= 0) {
            return false;
        }
 
        // We do not allow quality switches at non segment boundaries in case Adaptation Set Switching is available in the MPD.
        // This is because we can not control the switching process at this point, and the ABR rules might select a Representation that has a different SAPType + Cadence than the current Representation.
        Iif (currentRepresentation && currentRepresentation.mediaInfo && currentRepresentation.mediaInfo.adaptationSetSwitchingCompatibleIds && currentRepresentation.mediaInfo.adaptationSetSwitchingCompatibleIds.length > 0) {
            return false;
        }
 
        const segmentSequencePropertiesWithTargetSapType = currentRepresentation.segmentSequenceProperties.filter((ssp) => {
            return !isNaN(ssp.sapType) && ssp.sapType <= 1;
        })
 
        if (segmentSequencePropertiesWithTargetSapType.length === 0) {
            return false;
        }
 
        let nextPartialSubNumber = (lastSegment.replacementSubNumber + 1) % lastSegment.totalNumberOfPartialSegments;
 
        return segmentSequencePropertiesWithTargetSapType.some((ssp) => {
            return nextPartialSubNumber % ssp.cadence === 0
        })
    }
 
    function _addDroppedFramesHistoryEntry(streamId) {
        if (droppedFramesHistory) {
            const playbackQuality = videoModel.getPlaybackQuality();
            if (playbackQuality) {
                droppedFramesHistory.push(streamId, currentRepresentationId, playbackQuality);
            }
        }
    }
 
    function _addSwitchHistoryEntry(currentRepresentation, newRepresentation) {
        switchRequestHistory.push({
            currentRepresentation,
            newRepresentation
        })
    }
 
    /**
     * Sets the new playback quality. Starts from index 0.
     * If the index of the new quality is the same as the old one changeQuality will not be called.
     * @param {string} type
     * @param {object} streamInfo
     * @param {Representation} representation
     * @param {string} reason
     * @param {string} rule
     */
    function setPlaybackQuality(type, streamInfo, representation, reason = {}) {
        if (!streamInfo || !streamInfo.id || !type || !streamProcessorDict || !streamProcessorDict[streamInfo.id] || !streamProcessorDict[streamInfo.id][type] || !representation) {
            return false;
        }
 
        const streamProcessor = streamProcessorDict[streamInfo.id][type];
        const currentRepresentation = streamProcessor.getRepresentationController()?.getCurrentCompositeRepresentation();
 
        if (!currentRepresentation || representation.id !== currentRepresentation.id) {
            return _changeQuality(type, currentRepresentation, representation, reason);
        }
 
        return false;
    }
 
    function manuallySetPlaybackQuality(type, streamInfo, representation, reason = {}) {
        const streamProcessor = streamProcessorDict[streamInfo.id][type];
        const lastSegment = streamProcessor.getLastSegment();
        const currentRepresentation = streamProcessor.getRepresentation();
        const canSwitchQuality = canPerformQualitySwitch(lastSegment, currentRepresentation);
 
        if (!canSwitchQuality) {
            _queueManualQualitySwitch(type, streamInfo, representation, reason);
            return;
        }
 
        return setPlaybackQuality(type, streamInfo, representation, reason);
    }
 
    function _queueManualQualitySwitch(type, streamInfo, representation, reason) {
        try {
            logger.debug(`[AbrController] Queuing manual quality switch for stream ${streamInfo.id} and type ${type} to representation ${representation.id}`);
            const key = _getManualQualitySwitchKey(streamInfo.id, type);
            queuedManualQualitySwitches.set(key, { type, streamInfo, representation, reason });
        } catch (e) {
            logger.error(`Can not queue manual quality switch: ${e}`);
        }
    }
 
    function handlePendingManualQualitySwitch(streamId, mediaType) {
        try {
            const manualQualitySwitchKey = _getManualQualitySwitchKey(streamId, mediaType);
            let switchRequest = null;
            if (queuedManualQualitySwitches.has(manualQualitySwitchKey)) {
                switchRequest = queuedManualQualitySwitches.get(manualQualitySwitchKey);
            }
 
            Iif (!switchRequest) {
                return false
            }
 
            const streamProcessor = streamProcessorDict[streamId][mediaType];
            const lastSegment = streamProcessor.getLastSegment();
            const currentRepresentation = streamProcessor.getRepresentation();
            const canSwitchQuality = canPerformQualitySwitch(lastSegment, currentRepresentation);
 
            Iif (!canSwitchQuality) {
                return false
            }
 
            const { type, streamInfo, representation, reason } = switchRequest;
 
            queuedManualQualitySwitches.delete(manualQualitySwitchKey);
            setPlaybackQuality(type, streamInfo, representation, reason);
            return true;
        } catch (e) {
            logger.error(`Can not handle pending manual quality switch: ${e}`);
        }
    }
 
    function _getManualQualitySwitchKey(streamId, mediaType) {
        return `${streamId}-${mediaType}`
    }
 
    /**
     *
     * @param {string} streamId
     * @param {type} type
     * @return {*|null}
     */
    function getAbandonmentStateFor(streamId, type) {
        return abandonmentStateDict[streamId] && abandonmentStateDict[streamId][type] ? abandonmentStateDict[streamId][type].state : null;
    }
 
    function _getAbandonmentStateDictFor(streamId, type) {
        return abandonmentStateDict[streamId] && abandonmentStateDict[streamId][type] ? abandonmentStateDict[streamId][type] : null;
 
    }
 
    /**
     * Changes the internal qualityDict values according to the new quality
     * @param {Representation} oldRepresentation
     * @param {Representation} newRepresentation
     * @param {string} reason
     * @private
     */
    function _changeQuality(type, oldRepresentation, newRepresentation, reason) {
        const streamId = newRepresentation.mediaInfo.streamInfo.id;
        Iif (!type || !streamProcessorDict[streamId] || !streamProcessorDict[streamId][type]) {
            return false
        }
 
        const streamInfo = streamProcessorDict[streamId][type].getStreamInfo();
        const bufferLevel = dashMetrics.getCurrentBufferLevel(type);
        const isAdaptationSetSwitch = oldRepresentation !== null && !adapter.areMediaInfosEqual(oldRepresentation.mediaInfo, newRepresentation.mediaInfo);
        const oldBitrate = oldRepresentation ? oldRepresentation.bitrateInKbit : 0;
 
        logger.info(`[AbrController]: Switching quality in period ${streamId} for media type ${type}. Switch from bitrate ${oldBitrate} to bitrate ${newRepresentation.bitrateInKbit}. Current buffer level: ${bufferLevel}. Reason:` + (reason ? JSON.stringify(reason) : '/'));
        eventBus.trigger(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED,
            {
                isAdaptationSetSwitch,
                mediaType: type,
                newRepresentation: newRepresentation,
                oldRepresentation: oldRepresentation,
                reason,
                streamInfo,
            },
            { streamId: streamInfo.id, mediaType: type }
        );
 
        _saveBitrateSettings(type)
        return true
    }
 
    function _saveBitrateSettings(type) {
        const bitrate = throughputController.getAverageThroughput(type);
        if (!isNaN(bitrate)) {
            domStorage.setSavedBitrateSettings(type, bitrate);
        }
    }
 
 
    /**
     * If both BOLA and Throughput Rule are active we switch dynamically between both of them
     * @returns {boolean}
     * @private
     */
    function _shouldApplyDynamicAbrStrategy() {
        return settings.get().streaming.abr.rules.bolaRule.active && settings.get().streaming.abr.rules.throughputRule.active
    }
 
    /**
     * Switch between BOLA and ThroughputRule
     * @param mediaType
     * @param bufferLevel
     * @private
     */
    function _updateDynamicAbrStrategy(mediaType, bufferLevel) {
        try {
            const bufferTimeDefault = mediaPlayerModel.getBufferTimeDefault();
            const switchOnThreshold = bufferTimeDefault;
            const switchOffThreshold = 0.5 * bufferTimeDefault;
 
            const isUsingBolaRule = abrRulesCollection.getBolaState(mediaType)
            const shouldUseBolaRule = bufferLevel >= (isUsingBolaRule ? switchOffThreshold : switchOnThreshold); // use hysteresis to avoid oscillating rules
            abrRulesCollection.setBolaState(mediaType, shouldUseBolaRule);
 
            if (shouldUseBolaRule !== isUsingBolaRule) {
                if (shouldUseBolaRule) {
                    logger.info('[' + mediaType + '] switching from throughput to buffer occupancy ABR rule (buffer: ' + bufferLevel.toFixed(3) + ').');
                } else {
                    logger.info('[' + mediaType + '] switching from buffer occupancy to throughput ABR rule (buffer: ' + bufferLevel.toFixed(3) + ').');
                }
            }
        } catch (e) {
            logger.error(e);
        }
    }
 
    /**
     * Checks if the provided Representation has the lowest possible quality
     * @param representation
     * @returns {boolean}
     */
    function isPlayingAtLowestQuality(representation) {
        const voRepresentations = getPossibleVoRepresentationsFilteredBySettings(representation.mediaInfo, true);
 
        return voRepresentations[0].id === representation.id
    }
 
    /**
     * Checks if the provided Representation has the highest possible quality
     * @param representation
     * @returns {boolean}
     */
    function isPlayingAtTopQuality(representation) {
        if (!representation) {
            return true;
        }
        const voRepresentations = getPossibleVoRepresentationsFilteredBySettings(representation.mediaInfo, true);
 
        return voRepresentations[voRepresentations.length - 1].id === representation.id;
    }
 
    function clearDataForStream(streamId) {
        if (droppedFramesHistory) {
            droppedFramesHistory.clearForStream(streamId);
        }
        if (streamProcessorDict[streamId]) {
            delete streamProcessorDict[streamId];
        }
        if (switchRequestHistory) {
            switchRequestHistory.clearForStream(streamId);
        }
        if (abandonmentStateDict[streamId]) {
            delete abandonmentStateDict[streamId];
        }
 
        abrRulesCollection.clearDataForStream(streamId);
    }
 
    function handleNewMediaInfo(newMediaInfo) {
        abrRulesCollection.handleNewMediaInfo(newMediaInfo);
    }
 
 
    instance = {
        canPerformQualitySwitch,
        checkPlaybackQuality,
        clearDataForStream,
        getAbandonmentStateFor,
        getInitialBitrateFor,
        getOptimalRepresentationForBitrate,
        getPossibleVoRepresentations,
        getPossibleVoRepresentationsFilteredBySettings,
        getRepresentationByAbsoluteIndex,
        handleNewMediaInfo,
        handlePendingManualQualitySwitch,
        initialize,
        isPlayingAtLowestQuality,
        isPlayingAtTopQuality,
        manuallySetPlaybackQuality,
        registerStreamType,
        reset,
        setConfig,
        setPlaybackQuality,
        unRegisterStreamType,
    };
 
    setup();
 
    return instance;
}
 
AbrController.__dashjs_factory_name = 'AbrController';
const factory = FactoryMaker.getSingletonFactory(AbrController);
FactoryMaker.updateSingletonFactory(AbrController.__dashjs_factory_name, factory);
export default factory;