All files / dash.js/src/streaming/rules/abr ABRRulesCollection.js

69.82% Statements 81/116
50% Branches 40/80
64.7% Functions 22/34
73.39% Lines 80/109

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                                                                                              49x 49x   49x 49x 49x 49x 49x               49x 49x 49x 49x   49x               201x 201x 1407x     201x 201x 201x       201x 201x                     201x 11x             11x                   1608x 1608x 270x       270x 1338x 924x     414x       270x   51x           51x       54x         54x   3x                     57x                   684x 1294x         924x 2117x                           4x 4x         4x       4x 4x 4x   4x 11x 11x   11x   10x         4x 4x     4x 2x     4x 2x     4x       1x 1x                                         1x 1x                           44x 88x 220x     44x 44x 44x 44x                       4x       3x       38x       38x       152x               49x                           49x     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 ThroughputRule from './ThroughputRule.js';
import InsufficientBufferRule from './InsufficientBufferRule.js';
import AbandonRequestsRule from './AbandonRequestsRule.js';
import DroppedFramesRule from './DroppedFramesRule.js';
import SwitchHistoryRule from './SwitchHistoryRule.js';
import BolaRule from './BolaRule.js';
import L2ARule from './L2ARule.js';
import LoLPRule from './lolp/LoLpRule.js';
import FactoryMaker from '../../../core/FactoryMaker.js';
import SwitchRequest from '../SwitchRequest.js';
import EventBus from '../../../core/EventBus.js';
import Events from '../../../core/events/Events.js';
import Constants from '../../constants/Constants.js';
 
 
function ABRRulesCollection(config) {
 
    config = config || {};
    const context = this.context;
 
    const mediaPlayerModel = config.mediaPlayerModel;
    const customParametersModel = config.customParametersModel;
    const dashMetrics = config.dashMetrics;
    const settings = config.settings;
    const eventBus = EventBus(context).getInstance();
 
    let instance,
        qualitySwitchRules,
        abandonFragmentRules,
        shouldUseBolaRuleByMediaType;
 
    function initialize() {
        qualitySwitchRules = [];
        abandonFragmentRules = [];
        shouldUseBolaRuleByMediaType = {};
        _updateRules();
 
        eventBus.on(Events.SETTING_UPDATED_ABR_ACTIVE_RULES, _onAbrSettingsActiveRulesUpdated, instance);
    }
 
    /**
     * Adds and removes rules to/from the respective rules arrays
     * @private
     */
    function _updateRules() {
        let qualitySwitchRulesList = Object.values(Constants.QUALITY_SWITCH_RULES)
        qualitySwitchRulesList.forEach((ruleName) => {
            qualitySwitchRules = _handleRuleUpdate(ruleName, qualitySwitchRules)
        })
 
        let abandonFragmentRulesList = Object.values(Constants.ABANDON_FRAGMENT_RULES)
        abandonFragmentRulesList.forEach((ruleName) => {
            abandonFragmentRules = _handleRuleUpdate(ruleName, abandonFragmentRules)
        })
 
        // add custom ABR rules if any
        const customRules = customParametersModel.getAbrCustomRules();
        customRules.forEach(function (rule) {
            if (rule.type === Constants.RULES_TYPES.QUALITY_SWITCH_RULES) {
                qualitySwitchRules.push(rule.rule(context).create());
            }
 
            if (rule.type === Constants.RULES_TYPES.ABANDON_FRAGMENT_RULES) {
                abandonFragmentRules.push(rule.rule(context).create());
            }
        });
 
        // If we still got no rule for quality switch use Throughput and Bola
        if (qualitySwitchRules.length === 0) {
            qualitySwitchRules.push(
                BolaRule(context).create({
                    dashMetrics: dashMetrics,
                    mediaPlayerModel: mediaPlayerModel,
                    settings: settings
                })
            );
            qualitySwitchRules.push(
                ThroughputRule(context).create({
                    dashMetrics: dashMetrics
                })
            );
        }
    }
 
    function _handleRuleUpdate(ruleName, rulesCollection) {
        // we use camel case in the settings while the rules start with a capital latter. Not ideal but convert between these formats
        const attribute = ruleName.charAt(0).toLowerCase() + ruleName.slice(1);
        if (settings.get().streaming.abr.rules[attribute].active && !_arrayContainsRule(rulesCollection, ruleName)) {
            rulesCollection.push(
                _createRuleInstance(ruleName)
            );
 
            return rulesCollection
        } else if (!settings.get().streaming.abr.rules[attribute].active) {
            return _removeRuleFromArray(rulesCollection, ruleName)
        }
 
        return rulesCollection
    }
 
    function _createRuleInstance(rule) {
        switch (rule) {
            case Constants.QUALITY_SWITCH_RULES.BOLA_RULE:
                return BolaRule(context).create({
                    dashMetrics: dashMetrics,
                    mediaPlayerModel: mediaPlayerModel,
                    settings: settings
                })
            case Constants.QUALITY_SWITCH_RULES.THROUGHPUT_RULE:
                return ThroughputRule(context).create({
                    dashMetrics: dashMetrics
                })
            case Constants.QUALITY_SWITCH_RULES.INSUFFICIENT_BUFFER_RULE:
                return InsufficientBufferRule(context).create({
                    dashMetrics: dashMetrics,
                    settings
                })
            case Constants.QUALITY_SWITCH_RULES.SWITCH_HISTORY_RULE:
                return SwitchHistoryRule(context).create()
            case Constants.QUALITY_SWITCH_RULES.DROPPED_FRAMES_RULE:
                return DroppedFramesRule(context).create()
            case Constants.QUALITY_SWITCH_RULES.LEARN_TO_ADAPT_RULE:
                return L2ARule(context).create({
                    dashMetrics: dashMetrics,
                    settings: settings
                })
            case Constants.QUALITY_SWITCH_RULES.LOL_PLUS_RULE:
                return LoLPRule(context).create({
                    dashMetrics: dashMetrics
                })
            case Constants.ABANDON_FRAGMENT_RULES.ABANDON_REQUEST_RULE:
                return AbandonRequestsRule(context).create({
                    dashMetrics: dashMetrics,
                    mediaPlayerModel: mediaPlayerModel,
                    settings: settings
                })
 
        }
    }
 
    function _arrayContainsRule(arr, ruleName) {
        return arr.filter((rule) => {
            return rule.getClassName() === ruleName
        }).length > 0
    }
 
    function _removeRuleFromArray(arr, ruleName) {
        return arr.filter((rule) => {
            return rule.getClassName() !== ruleName
        })
    }
 
    function _getRulesWithChange(srArray) {
        return srArray.filter(sr => sr.representation !== SwitchRequest.NO_CHANGE);
    }
 
    /**
     *
     * @param {array} srArray
     * @return {object} SwitchRequest
     */
    function getMinSwitchRequest(srArray) {
        const values = {};
        let newSwitchReq = null;
        let i,
            len,
            currentSwitchRequest;
 
        Iif (srArray.length === 0) {
            return;
        }
 
        values[SwitchRequest.PRIORITY.STRONG] = null;
        values[SwitchRequest.PRIORITY.WEAK] = null;
        values[SwitchRequest.PRIORITY.DEFAULT] = null;
 
        for (i = 0, len = srArray.length; i < len; i += 1) {
            currentSwitchRequest = srArray[i];
            if (currentSwitchRequest.representation !== SwitchRequest.NO_CHANGE) {
                // We only use the new quality in case the bitrate is lower than the already saved one or if no new quality has been selected for the respective priority
                if (values[currentSwitchRequest.priority] === null ||
                    (values[currentSwitchRequest.priority].representation !== SwitchRequest.NO_CHANGE && currentSwitchRequest.representation.bitrateInKbit < values[currentSwitchRequest.priority].representation.bitrateInKbit)) {
                    values[currentSwitchRequest.priority] = currentSwitchRequest;
                }
            }
        }
 
        if (values[SwitchRequest.PRIORITY.WEAK] && values[SwitchRequest.PRIORITY.WEAK].representation !== SwitchRequest.NO_CHANGE) {
            newSwitchReq = values[SwitchRequest.PRIORITY.WEAK];
        }
 
        if (values[SwitchRequest.PRIORITY.DEFAULT] && values[SwitchRequest.PRIORITY.DEFAULT].representation !== SwitchRequest.NO_CHANGE) {
            newSwitchReq = values[SwitchRequest.PRIORITY.DEFAULT];
        }
 
        if (values[SwitchRequest.PRIORITY.STRONG] && values[SwitchRequest.PRIORITY.STRONG].representation !== SwitchRequest.NO_CHANGE) {
            newSwitchReq = values[SwitchRequest.PRIORITY.STRONG];
        }
 
        return newSwitchReq
    }
 
    function getBestPossibleSwitchRequest(rulesContext) {
        if (!rulesContext) {
            return SwitchRequest(context).create()
        }
        // Only Throughput or Bola are active at the same time.
        const activeQualitySwitchRules = qualitySwitchRules.filter((rule) => {
            const ruleName = rule.getClassName();
 
            if (ruleName !== Constants.QUALITY_SWITCH_RULES.BOLA_RULE && ruleName !== Constants.QUALITY_SWITCH_RULES.THROUGHPUT_RULE) {
                return true
            }
            const mediaType = rulesContext.getMediaType();
 
            return (shouldUseBolaRuleByMediaType[mediaType] && ruleName === Constants.QUALITY_SWITCH_RULES.BOLA_RULE) || (!shouldUseBolaRuleByMediaType[mediaType] && ruleName === Constants.QUALITY_SWITCH_RULES.THROUGHPUT_RULE)
        })
        const switchRequestArray = activeQualitySwitchRules.map(rule => rule.getSwitchRequest(rulesContext));
        const activeRules = _getRulesWithChange(switchRequestArray);
        const maxQuality = getMinSwitchRequest(activeRules);
 
        return maxQuality || SwitchRequest(context).create();
    }
 
    function shouldAbandonFragment(rulesContext) {
        if (!rulesContext) {
            return SwitchRequest(context).create()
        }
        const abandonRequestArray = abandonFragmentRules.map(rule => rule.shouldAbandon(rulesContext));
        const activeRules = _getRulesWithChange(abandonRequestArray);
        const shouldAbandon = getMinSwitchRequest(activeRules);
 
        if (shouldAbandon && shouldAbandon.reason) {
            shouldAbandon.reason.forceAbandon = true
        }
 
        return shouldAbandon || SwitchRequest(context).create();
    }
 
    function reset() {
        [qualitySwitchRules, abandonFragmentRules].forEach(rules => {
            if (rules && rules.length) {
                rules.forEach(rule => rule.reset && rule.reset());
            }
        });
        qualitySwitchRules = [];
        abandonFragmentRules = [];
        shouldUseBolaRuleByMediaType = {}
        eventBus.off(Events.SETTING_UPDATED_ABR_ACTIVE_RULES, _onAbrSettingsActiveRulesUpdated, instance);
    }
 
    function clearDataForStream(streamId) {
        [qualitySwitchRules, abandonFragmentRules].forEach(rules => {
            if (rules && rules.length) {
                rules.forEach(rule => rule.clearDataForStream && typeof rule.clearDataForStream === 'function' && rule.clearDataForStream(streamId));
            }
        });
    }
 
    function getQualitySwitchRules() {
        return qualitySwitchRules;
    }
 
    function getAbandonFragmentRules() {
        return abandonFragmentRules
    }
 
    function setBolaState(mediaType, value) {
        shouldUseBolaRuleByMediaType[mediaType] = value
    }
 
    function getBolaState(mediaType) {
        return shouldUseBolaRuleByMediaType[mediaType]
    }
 
    function _onAbrSettingsActiveRulesUpdated() {
        _updateRules()
    }
 
    function handleNewMediaInfo(newMediaInfo) {
        qualitySwitchRules.forEach(rule => rule.handleNewMediaInfo && rule.handleNewMediaInfo(newMediaInfo));
        abandonFragmentRules.forEach(rule => rule.handleNewMediaInfo && rule.handleNewMediaInfo(newMediaInfo));
    }
 
    instance = {
        clearDataForStream,
        getAbandonFragmentRules,
        getBestPossibleSwitchRequest,
        getBolaState,
        getMinSwitchRequest,
        getQualitySwitchRules,
        handleNewMediaInfo,
        initialize,
        reset,
        setBolaState,
        shouldAbandonFragment,
    };
 
    return instance;
}
 
ABRRulesCollection.__dashjs_factory_name = 'ABRRulesCollection';
const factory = FactoryMaker.getClassFactory(ABRRulesCollection);
FactoryMaker.updateSingletonFactory(ABRRulesCollection.__dashjs_factory_name, factory);
 
export default factory;