All files / dash.js/src/dash WebmSegmentBaseLoader.js

39.83% Statements 49/123
31.03% Branches 18/58
70% Functions 14/20
39.83% Lines 49/123

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                    46x                         46x                                                                                                                                   49x                 48x 1x   47x 47x 47x 47x 47x 47x                                                                                                                                                                                                         1x 1x 1x                                                                                                                                                                   1x 1x 1x 1x 1x                     1x   1x   1x     1x     1x       1x           1x         1x 1x 1x 1x 1x 1x                           1x         1x   1x 1x 1x               1x             1x                     2x 2x 2x       5x 5x 5x       46x               46x   46x     1x    
import EBMLParser from '../streaming/utils/EBMLParser.js';
import Constants from '../streaming/constants/Constants.js';
import FactoryMaker from '../core/FactoryMaker.js';
import FragmentRequest from '../streaming/vo/FragmentRequest.js';
import URLLoader from '../streaming/net/URLLoader.js';
import DashJSError from '../streaming/vo/DashJSError.js';
import FullSegment from '../dash/vo/FullSegment.js';
 
function WebmSegmentBaseLoader() {
 
    const context = this.context;
 
    let instance,
        logger,
        WebM,
        errHandler,
        dashMetrics,
        mediaPlayerModel,
        urlLoader,
        errors,
        baseURLController;
 
    function setup() {
        WebM = {
            EBML: {
                tag: 0x1A45DFA3,
                required: true
            },
            Segment: {
                tag: 0x18538067,
                required: true,
                SeekHead: {
                    tag: 0x114D9B74,
                    required: true
                },
                Info: {
                    tag: 0x1549A966,
                    required: true,
                    TimecodeScale: {
                        tag: 0x2AD7B1,
                        required: true,
                        parse: 'getMatroskaUint'
                    },
                    Duration: {
                        tag: 0x4489,
                        required: true,
                        parse: 'getMatroskaFloat'
                    }
                },
                Tracks: {
                    tag: 0x1654AE6B,
                    required: true
                },
                Cues: {
                    tag: 0x1C53BB6B,
                    required: true,
                    CuePoint: {
                        tag: 0xBB,
                        required: true,
                        CueTime: {
                            tag: 0xB3,
                            required: true,
                            parse: 'getMatroskaUint'
                        },
                        CueTrackPositions: {
                            tag: 0xB7,
                            required: true,
                            CueTrack: {
                                tag: 0xF7,
                                required: true,
                                parse: 'getMatroskaUint'
                            },
                            CueClusterPosition: {
                                tag: 0xF1,
                                required: true,
                                parse: 'getMatroskaUint'
                            }
                        }
                    }
                }
            },
            Void: {
                tag: 0xEC,
                required: true
            }
        };
    }
 
    function initialize() {
        urlLoader = URLLoader(context).create({
            errHandler: errHandler,
            dashMetrics: dashMetrics,
            mediaPlayerModel: mediaPlayerModel,
            errors: errors
        });
    }
 
    function setConfig(config) {
        if (!config.baseURLController || !config.dashMetrics || !config.mediaPlayerModel || !config.errHandler) {
            throw new Error(Constants.MISSING_CONFIG_ERROR);
        }
        baseURLController = config.baseURLController;
        dashMetrics = config.dashMetrics;
        mediaPlayerModel = config.mediaPlayerModel;
        errHandler = config.errHandler;
        errors = config.errors;
        logger = config.debug.getLogger(instance);
    }
 
    function parseCues(ab) {
        let cues = [];
        let ebmlParser = EBMLParser(context).create({
            data: ab
        });
        let cue,
            cueTrack;
 
        ebmlParser.consumeTagAndSize(WebM.Segment.Cues);
 
        while (ebmlParser.moreData() &&
        ebmlParser.consumeTagAndSize(WebM.Segment.Cues.CuePoint, true)) {
            cue = {};
 
            cue.CueTime = ebmlParser.parseTag(WebM.Segment.Cues.CuePoint.CueTime);
 
            cue.CueTracks = [];
            while (ebmlParser.moreData() &&
            ebmlParser.consumeTag(WebM.Segment.Cues.CuePoint.CueTrackPositions, true)) {
                const cueTrackPositionSize = ebmlParser.getMatroskaCodedNum();
                const startPos = ebmlParser.getPos();
                cueTrack = {};
 
                cueTrack.Track = ebmlParser.parseTag(WebM.Segment.Cues.CuePoint.CueTrackPositions.CueTrack);
                if (cueTrack.Track === 0) {
                    throw new Error('Cue track cannot be 0');
                }
 
                cueTrack.ClusterPosition =
                    ebmlParser.parseTag(WebM.Segment.Cues.CuePoint.CueTrackPositions.CueClusterPosition);
 
                cue.CueTracks.push(cueTrack);
 
                // we're not interested any other elements - skip remaining bytes
                ebmlParser.setPos(startPos + cueTrackPositionSize);
            }
 
            if (cue.CueTracks.length === 0) {
                throw new Error('Mandatory cuetrack not found');
            }
            cues.push(cue);
        }
 
        if (cues.length === 0) {
            throw new Error('mandatory cuepoint not found');
        }
        return cues;
    }
 
    function parseSegments(data, segmentStart, segmentEnd, segmentDuration) {
        let duration,
            parsed,
            segments,
            segment,
            i,
            len,
            start,
            end;
 
        parsed = parseCues(data);
        segments = [];
 
        // we are assuming one cue track per cue point
        // both duration and media range require the i + 1 segment
        // the final segment has to use global segment parameters
        for (i = 0, len = parsed.length; i < len; i += 1) {
            segment = new FullSegment();
            duration = 0;
 
            if (i < parsed.length - 1) {
                duration = parsed[i + 1].CueTime - parsed[i].CueTime;
            } else {
                duration = segmentDuration - parsed[i].CueTime;
            }
 
            // note that we don't explicitly set segment.media as this will be
            // computed when all BaseURLs are resolved later
            segment.duration = duration;
            segment.startTime = parsed[i].CueTime;
            segment.timescale = 1000; // hardcoded for ms
            start = parsed[i].CueTracks[0].ClusterPosition + segmentStart;
 
            if (i < parsed.length - 1) {
                end = parsed[i + 1].CueTracks[0].ClusterPosition + segmentStart - 1;
            } else {
                end = segmentEnd - 1;
            }
 
            segment.mediaRange = start + '-' + end;
            segments.push(segment);
        }
 
        logger.debug('Parsed cues: ' + segments.length + ' cues.');
 
        return segments;
    }
 
    function parseEbmlHeader(data, media, theRange, callback) {
        if (!data || data.byteLength === 0) {
            callback(null);
            return;
        }
        let ebmlParser = EBMLParser(context).create({
            data: data
        });
        let duration,
            segments,
            segmentEnd,
            segmentStart;
        let parts = theRange ? theRange.split('-') : null;
        let request = null;
        let info = {
            url: media,
            range: {
                start: parts ? parseFloat(parts[0]) : null,
                end: parts ? parseFloat(parts[1]) : null
            },
            request: request
        };
 
        logger.debug('Parse EBML header: ' + info.url);
 
        // skip over the header itself
        ebmlParser.skipOverElement(WebM.EBML);
        ebmlParser.consumeTag(WebM.Segment);
 
        // segments start here
        segmentEnd = ebmlParser.getMatroskaCodedNum();
        segmentEnd += ebmlParser.getPos();
        segmentStart = ebmlParser.getPos();
 
        // skip over any top level elements to get to the segment info
        while (ebmlParser.moreData() &&
        !ebmlParser.consumeTagAndSize(WebM.Segment.Info, true)) {
            if (!(ebmlParser.skipOverElement(WebM.Segment.SeekHead, true) ||
                ebmlParser.skipOverElement(WebM.Segment.Tracks, true) ||
                ebmlParser.skipOverElement(WebM.Segment.Cues, true) ||
                ebmlParser.skipOverElement(WebM.Void, true))) {
                throw new Error('no valid top level element found');
            }
        }
 
        // we only need one thing in segment info, duration
        while (duration === undefined) {
            let infoTag = ebmlParser.getMatroskaCodedNum(true);
            let infoElementSize = ebmlParser.getMatroskaCodedNum();
 
            switch (infoTag) {
                case WebM.Segment.Info.Duration.tag:
                    duration = ebmlParser[WebM.Segment.Info.Duration.parse](infoElementSize);
                    break;
                default:
                    ebmlParser.setPos(ebmlParser.getPos() + infoElementSize);
                    break;
            }
        }
 
        // once we have what we need from segment info, we jump right to the
        // cues
 
        request = _getFragmentRequest(info);
 
        const onload = function (response) {
            segments = parseSegments(response, segmentStart, segmentEnd, duration);
            callback(segments);
        };
 
        const onloadend = function () {
            logger.error('Download Error: Cues ' + info.url);
            callback(null);
        };
 
        urlLoader.load({
            request: request,
            success: onload,
            error: onloadend
        });
 
        logger.debug('Perform cues load: ' + info.url + ' bytes=' + info.range.start + '-' + info.range.end);
    }
 
    function loadInitialization(representation, mediaType) {
        return new Promise((resolve) => {
            let request = null;
            let baseUrl = representation ? baseURLController.resolve(representation.path) : null;
            let initRange = representation ? representation.range.split('-') : null;
            let info = {
                range: {
                    start: initRange ? parseFloat(initRange[0]) : null,
                    end: initRange ? parseFloat(initRange[1]) : null
                },
                request: request,
                url: baseUrl ? baseUrl.url : undefined,
                init: true,
                mediaType: mediaType
            };
 
            logger.info('Start loading initialization.');
 
            request = _getFragmentRequest(info);
 
            const onload = function () {
                // note that we don't explicitly set rep.initialization as this
                // will be computed when all BaseURLs are resolved later
                resolve(representation);
            };
 
            const onloadend = function () {
                resolve(representation);
            };
 
            urlLoader.load({
                request: request,
                success: onload,
                error: onloadend
            });
 
            logger.debug('Perform init load: ' + info.url);
        });
    }
 
    function loadSegments(representation, mediaType, theRange) {
        return new Promise((resolve) => {
            let request = null;
            let baseUrl = representation ? baseURLController.resolve(representation.path) : null;
            let media = baseUrl ? baseUrl.url : undefined;
            let bytesToLoad = 8192;
            let info = {
                bytesLoaded: 0,
                bytesToLoad: bytesToLoad,
                range: {
                    start: 0,
                    end: bytesToLoad
                },
                request: request,
                url: media,
                init: false,
                mediaType: mediaType,
                representation
            };
 
            request = _getFragmentRequest(info);
 
            // first load the header, but preserve the manifest range so we can
            // load the cues after parsing the header
            // NOTE: we expect segment info to appear in the first 8192 bytes
            logger.debug('Parsing ebml header');
 
            const onload = function (response) {
                parseEbmlHeader(response, media, theRange, function (segments) {
                    resolve({
                        segments: segments,
                        representation: representation,
                        error: segments ? undefined : new DashJSError(errors.SEGMENT_BASE_LOADER_ERROR_CODE, errors.SEGMENT_BASE_LOADER_ERROR_MESSAGE)
                    });
                });
            };
 
            const onloadend = function () {
                resolve({
                    representation: representation,
                    error: new DashJSError(errors.SEGMENT_BASE_LOADER_ERROR_CODE, errors.SEGMENT_BASE_LOADER_ERROR_MESSAGE)
                });
            };
 
            urlLoader.load({
                request: request,
                success: onload,
                error: onloadend
            });
        });
 
    }
 
 
    function _getFragmentRequest(info) {
        const request = new FragmentRequest();
        request.setInfo(info);
        return request;
    }
 
    function reset() {
        if (urlLoader) {
            urlLoader.abort();
            urlLoader = null;
        }
    }
 
    instance = {
        setConfig,
        initialize,
        loadInitialization,
        loadSegments,
        reset
    };
 
    setup();
 
    return instance;
}
 
WebmSegmentBaseLoader.__dashjs_factory_name = 'WebmSegmentBaseLoader';
export default FactoryMaker.getSingletonFactory(WebmSegmentBaseLoader);