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

52.94% Statements 54/102
31.91% Branches 15/47
61.53% Functions 8/13
52.47% Lines 53/101

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                                                                          1x 1x 1x       47x 47x 47x 47x               47x   47x                                         1x   1x 1x 1x             1x   1x 1x 1x         2x       2x 2x 2x   2x 2x   2x                                                                           2x       2x 2x     2x 2x     1x 1x 1x 1x   1x       1x 1x     1x 1x             2x         2x 3x 3x         2x 3x 3x         2x       2x               2x                                                 2x                                                                       47x           47x 47x     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 XlinkLoader from '../XlinkLoader.js';
import EventBus from '../../core/EventBus.js';
import Events from '../../core/events/Events.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import URLUtils from '../utils/URLUtils.js';
import DashConstants from '../../dash/constants/DashConstants.js';
 
const RESOLVE_TYPE_ONLOAD = 'onLoad';
const RESOLVE_TYPE_ONACTUATE = 'onActuate';
const RESOLVE_TO_ZERO = 'urn:mpeg:dash:resolve-to-zero:2013';
 
function XlinkController(config) {
 
    config = config || {};
    let context = this.context;
    let eventBus = EventBus(context).getInstance();
    const urlUtils = URLUtils(context).getInstance();
 
    let instance,
        parser,
        manifest,
        xlinkLoader;
 
    function setup() {
        eventBus.on(Events.XLINK_ELEMENT_LOADED, onXlinkElementLoaded, instance);
 
        xlinkLoader = XlinkLoader(context).create({
            errHandler: config.errHandler,
            dashMetrics: config.dashMetrics,
            mediaPlayerModel: config.mediaPlayerModel,
            settings: config.settings
        });
    }
 
    function setParser(value) {
        if (value) {
            parser = value;
        }
    }
 
    /**
     * <p>Triggers the resolution of the xlink.onLoad attributes in the manifest file </p>
     * @param {Object} mpd - the manifest
     */
    function resolveManifestOnLoad(mpd) {
        let elements;
        // First resolve all periods, so unnecessary requests inside onLoad Periods with Default content are avoided
        manifest = mpd;
 
        if (manifest.Period) {
            elements = getElementsToResolve(manifest.Period, manifest, DashConstants.PERIOD, RESOLVE_TYPE_ONLOAD);
            resolve(elements, DashConstants.PERIOD, RESOLVE_TYPE_ONLOAD);
        } else E{
            eventBus.trigger(Events.XLINK_READY, {manifest: manifest});
        }
    }
 
    function reset() {
        eventBus.off(Events.XLINK_ELEMENT_LOADED, onXlinkElementLoaded, instance);
 
        if (xlinkLoader) {
            xlinkLoader.reset();
            xlinkLoader = null;
        }
    }
 
    function resolve(elements, type, resolveType) {
        let resolveObject = {};
        let element,
            url;
 
        resolveObject.elements = elements;
        resolveObject.type = type;
        resolveObject.resolveType = resolveType;
        // If nothing to resolve, directly call allElementsLoaded
        if (resolveObject.elements.length === 0) {
            onXlinkAllElementsLoaded(resolveObject);
        }
        for (let i = 0; i < resolveObject.elements.length; i++) {
            element = resolveObject.elements[i];
            if (urlUtils.isHTTPURL(element.url)) {
                url = element.url;
            } else {
                url = element.originalContent.BaseURL + element.url;
            }
            xlinkLoader.load(url, element, resolveObject);
        }
    }
 
    function onXlinkElementLoaded(event) {
        let element,
            resolveObject;
 
        const openingTag = '<response>';
        const closingTag = '</response>';
        let mergedContent = '';
 
        element = event.element;
        resolveObject = event.resolveObject;
        // if the element resolved into content parse the content
        if (element.resolvedContent) {
            let index = 0;
            // we add a parent elements so the converter is able to parse multiple elements of the same type which are not wrapped inside a container
            if (element.resolvedContent.indexOf('<?xml') === 0) {
                index = element.resolvedContent.indexOf('?>') + 2; //find the closing position of the xml declaration, if it exists.
            }
            mergedContent = element.resolvedContent.substr(0,index) + openingTag + element.resolvedContent.substr(index) + closingTag;
            element.resolvedContent = parser.parseXml(mergedContent).response;
        }
        if (isResolvingFinished(resolveObject)) {
            onXlinkAllElementsLoaded(resolveObject);
        }
    }
 
    // We got to wait till all elements of the current queue are resolved before merging back
    function onXlinkAllElementsLoaded (resolveObject) {
        let elements = [];
        let i,
            obj;
 
        mergeElementsBack(resolveObject);
        Iif (resolveObject.resolveType === RESOLVE_TYPE_ONACTUATE) {
            eventBus.trigger(Events.XLINK_READY, { manifest: manifest });
        }
        if (resolveObject.resolveType === RESOLVE_TYPE_ONLOAD) {
            switch (resolveObject.type) {
                // Start resolving the other elements. We can do Adaptation Set and EventStream in parallel
                case DashConstants.PERIOD:
                    for (i = 0; i < manifest[DashConstants.PERIOD].length; i++) {
                        obj = manifest[DashConstants.PERIOD][i];
                        if (obj.hasOwnProperty(DashConstants.ADAPTATION_SET)) {
                            elements = elements.concat(getElementsToResolve(obj[DashConstants.ADAPTATION_SET], obj, DashConstants.ADAPTATION_SET, RESOLVE_TYPE_ONLOAD));
                        }
                        Iif (obj.hasOwnProperty(DashConstants.EVENT_STREAM)) {
                            elements = elements.concat(getElementsToResolve(obj[DashConstants.EVENT_STREAM], obj, DashConstants.EVENT_STREAM, RESOLVE_TYPE_ONLOAD));
                        }
                    }
                    resolve(elements, DashConstants.ADAPTATION_SET, RESOLVE_TYPE_ONLOAD);
                    break;
                case DashConstants.ADAPTATION_SET:
                    // TODO: Resolve SegmentList here
                    eventBus.trigger(Events.XLINK_READY, { manifest: manifest });
                    break;
            }
        }
    }
 
    // Returns the elements with the specific resolve Type
    function getElementsToResolve(elements, parentElement, type, resolveType) {
        let toResolve = [];
        let element,
            i,
            xlinkObject;
        // first remove all the resolve-to-zero elements
        for (i = elements.length - 1; i >= 0; i--) {
            element = elements[i];
            Iif (element.hasOwnProperty('xlink:href') && element['xlink:href'] === RESOLVE_TO_ZERO) {
                elements.splice(i, 1);
            }
        }
        // now get the elements with the right resolve type
        for (i = 0; i < elements.length; i++) {
            element = elements[i];
            Iif (element.hasOwnProperty('xlink:href') && element.hasOwnProperty('xlink:actuate') && element['xlink:actuate'] === resolveType) {
                xlinkObject = createXlinkObject(element['xlink:href'], parentElement, type, i, resolveType, element);
                toResolve.push(xlinkObject);
            }
        }
        return toResolve;
    }
 
    function mergeElementsBack(resolveObject) {
        let resolvedElements = [];
        let element,
            type,
            obj,
            i,
            j,
            k;
        // Start merging back from the end because of index shifting. Note that the elements with the same parent have to be ordered by index ascending
        for (i = resolveObject.elements.length - 1; i >= 0; i --) {
            element = resolveObject.elements[i];
            type = element.type;
 
            // Element couldn't be resolved or is TODO Inappropriate target: Remove all Xlink attributes
            if (!element.resolvedContent || isInappropriateTarget()) {
                delete element.originalContent['xlink:actuate'];
                delete element.originalContent['xlink:href'];
                resolvedElements.push(element.originalContent);
            }
            // Element was successfully resolved
            else if (element.resolvedContent) {
                for (j = 0; j < element.resolvedContent[type].length; j++) {
                    //TODO Contains another Xlink attribute with xlink:actuate set to onload. Remove all xLink attributes
                    obj = element.resolvedContent[type][j];
                    resolvedElements.push(obj);
                }
            }
            // Replace the old elements in the parent with the resolved ones
            element.parentElement[type].splice(element.index, 1);
            for (k = 0; k < resolvedElements.length; k++) {
                element.parentElement[type].splice(element.index + k, 0, resolvedElements[k]);
            }
            resolvedElements = [];
        }
        Iif (resolveObject.elements.length > 0) {
            parser.getIron().run(manifest);
        }
    }
 
    function createXlinkObject(url, parentElement, type, index, resolveType, originalContent) {
        return {
            url: url,
            parentElement: parentElement,
            type: type,
            index: index,
            resolveType: resolveType,
            originalContent: originalContent,
            resolvedContent: null,
            resolved: false
        };
    }
 
    // Check if all pending requests are finished
    function isResolvingFinished(elementsToResolve) {
        let i,
            obj;
        for (i = 0; i < elementsToResolve.elements.length; i++) {
            obj = elementsToResolve.elements[i];
            if (obj.resolved === false) {
                return false;
            }
        }
        return true;
    }
 
    // TODO : Do some syntax check here if the target is valid or not
    function isInappropriateTarget() {
        return false;
    }
 
    instance = {
        resolveManifestOnLoad: resolveManifestOnLoad,
        setParser: setParser,
        reset: reset
    };
 
    setup();
    return instance;
}
 
XlinkController.__dashjs_factory_name = 'XlinkController';
export default FactoryMaker.getClassFactory(XlinkController);