All files / dash.js/src/dash/controllers ServiceDescriptionController.js

90.98% Statements 111/122
79.76% Branches 67/84
88.88% Functions 24/27
90.83% Lines 109/120

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                                                                      1x 1x               50x                 50x 50x       46x       46x 46x         61x       111x                             111x             143x                 50x 16x     36x 36x 34x     34x 2x     32x 24x     32x 19x     32x       32x 20x     32x       32x                         24x 9x   15x     24x 1x         1x 1x   1x         23x 23x   23x                     15x 15x 15x   15x                           9x 9x 9x   9x                           19x 19x 19x 19x   19x 19x                                     20x       20x   20x 20x 20x   20x   20x 5x 15x 14x 14x     20x   33x 33x     33x 33x     33x 33x                         99x   99x                                                         2x                     18x 18x 18x 17x 17x   2x 2x   6x 6x     12x 12x 12x 12x 12x 12x 12x             12x   12x   12x     12x     2x     3x   15x 15x                     1x 1x 6x       1x         1x 1x     1x     50x                 50x   50x     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 FactoryMaker from '../../core/FactoryMaker.js';
import Debug from '../../core/Debug.js';
import Constants from '../../streaming/constants/Constants.js';
import DashConstants from '../constants/DashConstants.js';
 
const SUPPORTED_SCHEMES = [Constants.SERVICE_DESCRIPTION_DVB_LL_SCHEME];
const MEDIA_TYPES = {
    VIDEO: 'video',
    AUDIO: 'audio',
    ANY: 'any',
    ALL: 'all'
}
 
function ServiceDescriptionController() {
    const context = this.context;
 
    let instance,
        serviceDescriptionSettings,
        prftOffsets,
        logger,
        adapter;
 
    function setup() {
        logger = Debug(context).getInstance().getLogger(instance);
        _resetInitialSettings();
    }
 
    function setConfig(config) {
        Iif (!config) {
            return;
        }
 
        if (config.adapter) {
            adapter = config.adapter;
        }
    }
 
    function reset() {
        _resetInitialSettings();
    }
 
    function _resetInitialSettings() {
        serviceDescriptionSettings = {
            liveDelay: NaN,
            liveCatchup: {
                maxDrift: NaN,
                playbackRate: {
                    min: NaN,
                    max: NaN
                },
            },
            minBitrate: {},
            maxBitrate: {},
            initialBitrate: {},
            contentSteering: null,
            clientDataReporting: null,
        };
        prftOffsets = [];
    }
 
    /**
     * Returns the service description settings for latency, catchup and bandwidth
     */
    function getServiceDescriptionSettings() {
        return serviceDescriptionSettings
    }
 
    /**
     * Check for potential ServiceDescriptor elements in the MPD and update the settings accordingly
     * @param {object} manifestInfo
     * @private
     */
    function applyServiceDescription(manifestInfo) {
        if (!manifestInfo || !manifestInfo.serviceDescriptions) {
            return;
        }
 
        const supportedServiceDescriptions = manifestInfo.serviceDescriptions.filter(sd => SUPPORTED_SCHEMES.includes(sd.schemeIdUri));
        const allClientsServiceDescriptions = manifestInfo.serviceDescriptions.filter(sd => sd.schemeIdUri == null);
        let sd = (supportedServiceDescriptions.length > 0)
            ? supportedServiceDescriptions[supportedServiceDescriptions.length - 1]
            : allClientsServiceDescriptions[allClientsServiceDescriptions.length - 1];
        if (!sd) {
            return;
        }
 
        if (sd.latency && sd.latency.target > 0) {
            _applyServiceDescriptionLatency(sd);
        }
 
        if (sd.playbackRate) {
            _applyServiceDescriptionPlaybackRate(sd);
        }
 
        Iif (sd.operatingQuality) {
            _applyServiceDescriptionOperatingQuality(sd);
        }
 
        if (sd.operatingBandwidth) {
            _applyServiceDescriptionOperatingBandwidth(sd);
        }
 
        Iif (sd.contentSteering) {
            _applyServiceDescriptionContentSteering(sd);
        }
 
        Iif (sd.clientDataReporting) {
            _applyServiceDescriptionClientDataReporting(sd);
        }
    }
 
    /**
     * Adjust the latency targets for the service.
     * @param {object} sd - service description element
     * @private
     */
    function _applyServiceDescriptionLatency(sd) {
        let params;
 
        if (sd.schemeIdUri === Constants.SERVICE_DESCRIPTION_DVB_LL_SCHEME) {
            params = _getDvbServiceDescriptionLatencyParameters(sd);
        } else {
            params = _getStandardServiceDescriptionLatencyParameters(sd);
        }
 
        if (prftOffsets.length > 0) {
            let { to, id } = _calculateTimeOffset(params);
 
            // TS 103 285 Clause 10.20.4. 3) Subtract calculated offset from Latency@target converted from milliseconds
            // liveLatency does not consider ST@availabilityTimeOffset so leave out that step
            // Since maxDrift is a difference rather than absolute it does not need offset applied
            serviceDescriptionSettings.liveDelay = params.liveDelay - to;
            serviceDescriptionSettings.liveCatchup.maxDrift = params.maxDrift;
 
            logger.debug(`
                Found latency properties coming from service description. Applied time offset of ${to} from ProducerReferenceTime element with id ${id}.
                Live Delay: ${params.liveDelay - to}, Live catchup max drift: ${params.maxDrift}
            `);
        } else {
            serviceDescriptionSettings.liveDelay = params.liveDelay;
            serviceDescriptionSettings.liveCatchup.maxDrift = params.maxDrift;
 
            logger.debug(`Found latency properties coming from service description: Live Delay: ${params.liveDelay}, Live catchup max drift: ${params.maxDrift}`);
        }
    }
 
    /**
     * Get default parameters for liveDelay,maxDrift
     * @param {object} sd
     * @return {{maxDrift: (number|undefined), liveDelay: number, referenceId: (number|undefined)}}
     * @private
     */
    function _getStandardServiceDescriptionLatencyParameters(sd) {
        const liveDelay = sd.latency.target / 1000;
        let maxDrift = !isNaN(sd.latency.max) && sd.latency.max > sd.latency.target ? (sd.latency.max - sd.latency.target + 500) / 1000 : NaN;
        const referenceId = sd.latency.referenceId || NaN;
 
        return {
            liveDelay,
            maxDrift,
            referenceId
        }
    }
 
    /**
     * Get DVB DASH parameters for liveDelay,maxDrift
     * @param sd
     * @return {{maxDrift: (number|undefined), liveDelay: number, referenceId: (number|undefined)}}
     * @private
     */
    function _getDvbServiceDescriptionLatencyParameters(sd) {
        const liveDelay = sd.latency.target / 1000;
        let maxDrift = !isNaN(sd.latency.max) && sd.latency.max > sd.latency.target ? (sd.latency.max - sd.latency.target + 500) / 1000 : NaN;
        const referenceId = sd.latency.referenceId || NaN;
 
        return {
            liveDelay,
            maxDrift,
            referenceId
        }
    }
 
    /**
     * Adjust the playback rate targets for the service
     * @param {object} sd
     * @private
     */
    function _applyServiceDescriptionPlaybackRate(sd) {
        // Convert each playback rate into a difference from 1. i.e 0.8 becomes -0.2.
        const min = sd.playbackRate.min ? (Math.round((sd.playbackRate.min - 1.0) * 1000) / 1000) : NaN;
        const max = sd.playbackRate.max ? (Math.round((sd.playbackRate.max - 1.0) * 1000) / 1000) : NaN;
        serviceDescriptionSettings.liveCatchup.playbackRate.min = min;
        serviceDescriptionSettings.liveCatchup.playbackRate.max = max;
 
        logger.debug(`Found latency properties coming from service description: Live catchup min playback rate: ${min}`);
        logger.debug(`Found latency properties coming from service description: Live catchup max playback rate: ${max}`);
    }
 
    /**
     * Used to specify a quality ranking. We do not support this yet.
     * @private
     */
    function _applyServiceDescriptionOperatingQuality() {
        return;
    }
 
    /**
     * Adjust the operating quality targets for the service
     * @param {object} sd
     * @private
     */
    function _applyServiceDescriptionOperatingBandwidth(sd) {
 
        // Aggregation of media types is not supported yet
        Iif (!sd || !sd.operatingBandwidth || !sd.operatingBandwidth.mediaType || sd.operatingBandwidth.mediaType === MEDIA_TYPES.ALL) {
            return;
        }
 
        const params = {};
 
        params.minBandwidth = sd.operatingBandwidth.min;
        params.maxBandwidth = sd.operatingBandwidth.max;
        params.targetBandwidth = sd.operatingBandwidth.target;
 
        const mediaTypesToApply = [];
 
        if (sd.operatingBandwidth.mediaType === MEDIA_TYPES.VIDEO || sd.operatingBandwidth.mediaType === MEDIA_TYPES.AUDIO) {
            mediaTypesToApply.push(sd.operatingBandwidth.mediaType);
        } else if (sd.operatingBandwidth.mediaType === MEDIA_TYPES.ANY) {
            mediaTypesToApply.push(MEDIA_TYPES.AUDIO);
            mediaTypesToApply.push(MEDIA_TYPES.VIDEO);
        }
 
        mediaTypesToApply.forEach((mediaType) => {
 
            if (!isNaN(params.minBandwidth)) {
                _updateBandwidthSetting('minBitrate', mediaType, params.minBandwidth);
            }
 
            if (!isNaN(params.maxBandwidth)) {
                _updateBandwidthSetting('maxBitrate', mediaType, params.maxBandwidth);
            }
 
            if (!isNaN(params.targetBandwidth)) {
                _updateBandwidthSetting('initialBitrate', mediaType, params.targetBandwidth);
            }
        })
    }
 
    /**
     * Update the bandwidth settings vor a specific field and media type
     * @param {string} field
     * @param {string} mediaType
     * @param {number} value
     * @private
     */
    function _updateBandwidthSetting(field, mediaType, value) {
        try {
            // Service description values are specified in bps. Settings expect the value in kbps
            serviceDescriptionSettings[field][mediaType] = value / 1000;
        } catch (e) {
            logger.error(e);
        }
    }
 
    /**
     * Add information about content steering element. Handling is up to the ContentSteeringController
     *  @param {object} sd
     *  @private
     */
    function _applyServiceDescriptionContentSteering(sd) {
        serviceDescriptionSettings.contentSteering = sd.contentSteering;
    }
 
    /**
     * Add information about client data reporting element. Handling is up to the CMCDModel
     *  @param {object} sd
     *  @private
     */
    function _applyServiceDescriptionClientDataReporting(sd) {
        serviceDescriptionSettings.clientDataReporting = sd.clientDataReporting;
    }
 
    /**
     * Returns the current calculated time offsets based on ProducerReferenceTime elements
     * @returns {array}
     */
    function getProducerReferenceTimeOffsets() {
        return prftOffsets;
    }
 
    /**
     * Calculates an array of time offsets each with matching ProducerReferenceTime id.
     * Call before applyServiceDescription if producer reference time elements should be considered.
     * @param {array} streamInfos
     * @returns {array}
     * @private
     */
    function calculateProducerReferenceTimeOffsets(streamInfos) {
        try {
            let timeOffsets = [];
            if (streamInfos && streamInfos.length > 0) {
                const mediaTypes = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT];
                const astInSeconds = adapter.getAvailabilityStartTime() / 1000;
 
                streamInfos.forEach((streamInfo) => {
                    const offsets = mediaTypes
                        .reduce((acc, mediaType) => {
                            acc = acc.concat(adapter.getAllMediaInfoForType(streamInfo, mediaType));
                            return acc;
                        }, [])
                        .reduce((acc, mediaInfo) => {
                            const prts = adapter.getProducerReferenceTimes(streamInfo, mediaInfo);
                            prts.forEach((prt) => {
                                const voRepresentations = adapter.getVoRepresentations(mediaInfo);
                                if (voRepresentations && voRepresentations.length > 0 && voRepresentations[0].adaptation && voRepresentations[0].segmentInfoType === DashConstants.SEGMENT_TEMPLATE) {
                                    const voRep = voRepresentations[0];
                                    const d = new Date(prt[DashConstants.WALL_CLOCK_TIME]);
                                    const wallClockTime = d.getTime() / 1000;
                                    // TS 103 285 Clause 10.20.4
                                    // 1) Calculate PRT0
                                    // i) take the PRT@presentationTime and subtract any ST@presentationTimeOffset
                                    // ii) convert this time to seconds by dividing by ST@timescale
                                    // iii) Add this to start time of period that contains PRT.
                                    // N.B presentationTimeOffset is already divided by timescale at this point
                                    const prt0 = wallClockTime - (((prt[DashConstants.PRESENTATION_TIME] / voRep[DashConstants.TIMESCALE]) - voRep[DashConstants.PRESENTATION_TIME_OFFSET]) + streamInfo.start);
                                    // 2) Calculate TO between PRT at the start of MPD timeline and the AST
                                    const to = astInSeconds - prt0;
                                    // 3) Not applicable as liveLatency does not consider ST@availabilityTimeOffset
                                    acc.push({ id: prt[DashConstants.ID], to });
                                }
                            });
                            return acc;
                        }, [])
 
                    timeOffsets = timeOffsets.concat(offsets);
                })
            }
            prftOffsets = timeOffsets;
        } catch (e) {
            logger.error(e);
            prftOffsets = [];
        }
    };
 
    /**
     * Calculates offset to apply to live delay as described in TS 103 285 Clause 10.20.4
     * @param {object} sdLatency - service description latency element
     * @returns {number}
     * @private
     */
    function _calculateTimeOffset(sdLatency) {
        let to = 0, id;
        let offset = prftOffsets.filter(prt => {
            return prt.id === sdLatency.referenceId;
        });
 
        // If only one ProducerReferenceTime to generate one TO, then use that regardless of matching ids
        Iif (offset.length === 0) {
            to = (prftOffsets.length > 0) ? prftOffsets[0].to : 0;
            id = prftOffsets[0].id || NaN;
        } else {
            // If multiple id matches, use the first but this should be invalid
            to = offset[0].to || 0;
            id = offset[0].id || NaN;
        }
 
        return { to, id }
    }
 
    instance = {
        getServiceDescriptionSettings,
        getProducerReferenceTimeOffsets,
        calculateProducerReferenceTimeOffsets,
        applyServiceDescription,
        reset,
        setConfig
    };
 
    setup();
 
    return instance;
}
 
ServiceDescriptionController.__dashjs_factory_name = 'ServiceDescriptionController';
export default FactoryMaker.getSingletonFactory(ServiceDescriptionController);