All files / dash.js/src/streaming/models MediaPlayerModel.js

88.09% Statements 74/84
79.74% Branches 63/79
82.35% Functions 14/17
88.09% Lines 74/84

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                                                                    1x 1x 1x 1x 1x 1x 1x 1x 1x                                 113x 113x     113x       28x 28x   28x 28x                     8x 1x   7x 2x     2x   5x 2x     2x   3x                   8x 1x   7x 2x     2x   5x 2x     2x   3x               3x 1x     2x 2x 1x     1x                 9x   9x 5x           4x 4x 3x 3x           1x                                               155x 155x 155x 48x     107x 107x 6x     101x                     2x   2x       2x               3x 3x   3x               3x                 6x   6x                 6x   6x               3x 1x     2x                   113x                               113x   113x     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 Debug from '../../core/Debug.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import Settings from '../../core/Settings.js';
 
const CATCHUP_PLAYBACK_RATE_MAX_LIMIT = 1;
const CATCHUP_PLAYBACK_RATE_MIN_LIMIT = -0.5;
const DEFAULT_CATCHUP_MAX_DRIFT = 12;
const DEFAULT_CATCHUP_PLAYBACK_RATE_MAX = 0.5;
const DEFAULT_CATCHUP_PLAYBACK_RATE_MIN = -0.5;
const DEFAULT_MIN_BUFFER_TIME = 12;
const DEFAULT_MIN_BUFFER_TIME_FAST_SWITCH = 20;
const LOW_LATENCY_MULTIPLY_FACTOR = 5;
const LOW_LATENCY_REDUCTION_FACTOR = 10;
 
 
/**
 * We use this model as a wrapper/proxy between Settings.js and classes that are using parameters from Settings.js.
 * In some cases we require additional logic to be applied and the settings might need to be adjusted before being used.
 * @class
 * @ignore
 * @constructor
 */
function MediaPlayerModel() {
 
    let instance,
        logger,
        playbackController,
        serviceDescriptionController;
 
    const context = this.context;
    const settings = Settings(context).getInstance();
 
    function setup() {
        logger = Debug(context).getInstance().getLogger(instance);
    }
 
    function setConfig(config) {
        if (config.playbackController) {
            playbackController = config.playbackController;
        }
        if (config.serviceDescriptionController) {
            serviceDescriptionController = config.serviceDescriptionController;
        }
    }
 
    /**
     * Checks the supplied min playback rate is a valid vlaue and within supported limits
     * @param {number} rate - Supplied min playback rate
     * @param {boolean} log - wether to shown warning or not
     * @returns {number} corrected min playback rate
     */
    function _checkMinPlaybackRate(rate, log) {
        if (isNaN(rate)) {
            return 0;
        }
        if (rate > 0) {
            Iif (log) {
                logger.warn(`Supplied minimum playback rate is a positive value when it should be negative or 0. The supplied rate will not be applied and set to 0: 100% playback speed.`)
            }
            return 0;
        }
        if (rate < CATCHUP_PLAYBACK_RATE_MIN_LIMIT) {
            Iif (log) {
                logger.warn(`Supplied minimum playback rate is out of range and will be limited to ${CATCHUP_PLAYBACK_RATE_MIN_LIMIT}: ${CATCHUP_PLAYBACK_RATE_MIN_LIMIT * 100}% playback speed.`);
            }
            return CATCHUP_PLAYBACK_RATE_MIN_LIMIT;
        }
        return rate;
    };
 
    /**
     * Checks the supplied max playback rate is a valid vlaue and within supported limits
     * @param {number} rate - Supplied max playback rate
     * @param {boolean} log - wether to shown warning or not
     * @returns {number} corrected max playback rate
     */
    function _checkMaxPlaybackRate(rate, log) {
        if (isNaN(rate)) {
            return 0;
        }
        if (rate < 0) {
            Iif (log) {
                logger.warn(`Supplied maximum playback rate is a negative value when it should be negative or 0. The supplied rate will not be applied and set to 0: 100% playback speed.`)
            }
            return 0;
        }
        if (rate > CATCHUP_PLAYBACK_RATE_MAX_LIMIT) {
            Iif (log) {
                logger.warn(`Supplied maximum playback rate is out of range and will be limited to ${CATCHUP_PLAYBACK_RATE_MAX_LIMIT}: ${(1 + CATCHUP_PLAYBACK_RATE_MAX_LIMIT) * 100}% playback speed.`);
            }
            return CATCHUP_PLAYBACK_RATE_MAX_LIMIT;
        }
        return rate;
    };
 
    /**
     * Returns the maximum drift allowed before applying a seek back to the live edge when the catchup mode is enabled
     * @return {number}
     */
    function getCatchupMaxDrift() {
        if (!isNaN(settings.get().streaming.liveCatchup.maxDrift) && settings.get().streaming.liveCatchup.maxDrift >= 0) {
            return settings.get().streaming.liveCatchup.maxDrift;
        }
 
        const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();
        if (serviceDescriptionSettings && serviceDescriptionSettings.liveCatchup && !isNaN(serviceDescriptionSettings.liveCatchup.maxDrift) && serviceDescriptionSettings.liveCatchup.maxDrift >= 0) {
            return serviceDescriptionSettings.liveCatchup.maxDrift;
        }
 
        return DEFAULT_CATCHUP_MAX_DRIFT;
    }
 
    /**
     * Returns the minimum and maximum playback rates to be used when applying the catchup mechanism
     * If only one of the min/max values has been set then the other will default to 0 (no playback rate change).
     * @return {number}
     */
    function getCatchupPlaybackRates(log) {
        const settingsPlaybackRate = settings.get().streaming.liveCatchup.playbackRate;
 
        if (!isNaN(settingsPlaybackRate.min) || !isNaN(settingsPlaybackRate.max)) {
            return {
                min: _checkMinPlaybackRate(settingsPlaybackRate.min, log),
                max: _checkMaxPlaybackRate(settingsPlaybackRate.max, log),
            }
        }
 
        const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();
        if (serviceDescriptionSettings && serviceDescriptionSettings.liveCatchup && (!isNaN(serviceDescriptionSettings.liveCatchup.playbackRate.min) || !isNaN(serviceDescriptionSettings.liveCatchup.playbackRate.max))) {
            const sdPlaybackRate = serviceDescriptionSettings.liveCatchup.playbackRate;
            return {
                min: _checkMinPlaybackRate(sdPlaybackRate.min, log),
                max: _checkMaxPlaybackRate(sdPlaybackRate.max, log),
            }
        }
 
        return {
            min: DEFAULT_CATCHUP_PLAYBACK_RATE_MIN,
            max: DEFAULT_CATCHUP_PLAYBACK_RATE_MAX
        }
    }
 
    /**
     * Returns whether the catchup mode is activated via the settings or internally in the PlaybackController
     * @return {boolean}
     */
    function getCatchupModeEnabled() {
        if (settings.get().streaming.liveCatchup.enabled !== null) {
            return settings.get().streaming.liveCatchup.enabled;
        }
 
        return playbackController.getInitialCatchupModeActivated();
    }
 
    /**
     * Returns the min,max or initial bitrate for a specific media type.
     * @param {string} field
     * @param {string} mediaType
     */
    function getAbrBitrateParameter(field, mediaType) {
        try {
            const setting = settings.get().streaming.abr[field][mediaType];
            if (!isNaN(setting) && setting !== -1) {
                return setting;
            }
 
            const serviceDescriptionSettings = serviceDescriptionController.getServiceDescriptionSettings();
            if (serviceDescriptionSettings && serviceDescriptionSettings[field] && !isNaN(serviceDescriptionSettings[field][mediaType])) {
                return serviceDescriptionSettings[field][mediaType];
            }
 
            return -1;
        } catch (e) {
            return -1;
        }
    }
 
    /**
     * Returns the initial buffer level taking the stable buffer time into account
     * @return {number}
     */
    function getInitialBufferLevel() {
        const initialBufferLevel = settings.get().streaming.buffer.initialBufferLevel;
 
        Iif (isNaN(initialBufferLevel) || initialBufferLevel < 0) {
            return 0;
        }
 
        return Math.min(getBufferTimeDefault(), initialBufferLevel);
    }
 
    /**
     * Returns the stable buffer time taking the live delay into account
     * @return {number}
     */
    function getBufferTimeDefault() {
        const bufferTimeDefault = getBufferTimeDefaultUnadjusted();
        const liveDelay = playbackController.getLiveDelay();
 
        return !isNaN(liveDelay) && liveDelay > 0 ? Math.min(bufferTimeDefault, liveDelay) : bufferTimeDefault;
    }
 
    /**
     * Returns the stable buffer
     * @return {number}
     */
    function getBufferTimeDefaultUnadjusted() {
        return settings.get().streaming.buffer.bufferTimeDefault > 0 ? settings.get().streaming.buffer.bufferTimeDefault : getFastSwitchEnabled() ? DEFAULT_MIN_BUFFER_TIME_FAST_SWITCH : DEFAULT_MIN_BUFFER_TIME;
    }
 
    /**
     * Returns the number of retry attempts for a specific media type
     * @param type
     * @return {number}
     */
    function getRetryAttemptsForType(type) {
        const lowLatencyMultiplyFactor = !isNaN(settings.get().streaming.retryAttempts.lowLatencyMultiplyFactor) ? settings.get().streaming.retryAttempts.lowLatencyMultiplyFactor : LOW_LATENCY_MULTIPLY_FACTOR;
 
        return playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.retryAttempts[type] * lowLatencyMultiplyFactor : settings.get().streaming.retryAttempts[type];
    }
 
    /**
     * Returns the retry interval for a specific media type
     * @param type
     * @return {number}
     */
    function getRetryIntervalsForType(type) {
        const lowLatencyReductionFactor = !isNaN(settings.get().streaming.retryIntervals.lowLatencyReductionFactor) ? settings.get().streaming.retryIntervals.lowLatencyReductionFactor : LOW_LATENCY_REDUCTION_FACTOR;
 
        return playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.retryIntervals[type] / lowLatencyReductionFactor : settings.get().streaming.retryIntervals[type];
    }
 
    /**
     * Returns whether the fast switch mode is defined in the settings options. If not we enable it by default but only for non low-latency playback.
     * @return {boolean}
     */
    function getFastSwitchEnabled() {
        if (settings.get().streaming.buffer.fastSwitchEnabled !== null) {
            return settings.get().streaming.buffer.fastSwitchEnabled;
        }
 
        return !playbackController.getLowLatencyModeEnabled();
    }
 
    function getScheduleTimeout() {
        return playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.scheduling.lowLatencyTimeout : settings.get().streaming.scheduling.defaultTimeout
    }
 
    function reset() {
    }
 
    instance = {
        getAbrBitrateParameter,
        getBufferTimeDefault,
        getBufferTimeDefaultUnadjusted,
        getCatchupMaxDrift,
        getCatchupModeEnabled,
        getCatchupPlaybackRates,
        getFastSwitchEnabled,
        getInitialBufferLevel,
        getRetryAttemptsForType,
        getRetryIntervalsForType,
        getScheduleTimeout,
        reset,
        setConfig,
    };
 
    setup();
 
    return instance;
}
 
MediaPlayerModel.__dashjs_factory_name = 'MediaPlayerModel';
export default FactoryMaker.getSingletonFactory(MediaPlayerModel);