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

46.06% Statements 76/165
21.56% Branches 22/102
34.21% Functions 13/38
46.06% Lines 76/165

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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485                                                                                  11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x                               11x 11x 11x       7x   7x 7x 7x 7x 7x 7x                       42x       42x                             11x                                                                                                                                                                                                                                                                                           11x 11x   11x 2x     9x 2x 7x 1x   6x     9x                 2x 2x 1x 1x           1x     1x                         1x 1x 1x         1x 1x                             6x 6x 6x 6x 4x 4x   2x                                       11x                                                                                                                                                     22x 22x 22x 22x     22x 22x 22x       11x 11x 11x 11x 11x 11x   11x 11x 11x 11x             11x                                     11x   11x     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 Constants from '../constants/Constants.js';
import FragmentModel from '../models/FragmentModel.js';
import EventBus from '../../core/EventBus.js';
import Events from '../../core/events/Events.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import Debug from '../../core/Debug.js';
import MetricsConstants from '../constants/MetricsConstants.js';
import MediaPlayerEvents from '../MediaPlayerEvents.js';
 
function ScheduleController(config) {
 
    config = config || {};
    const context = this.context;
    const eventBus = EventBus(context).getInstance();
    const dashMetrics = config.dashMetrics;
    const mediaPlayerModel = config.mediaPlayerModel;
    const fragmentModel = config.fragmentModel;
    const abrController = config.abrController;
    const playbackController = config.playbackController;
    const textController = config.textController;
    const type = config.type;
    const bufferController = config.bufferController;
    const representationController = config.representationController
    const settings = config.settings;
 
    let shouldCheckPlaybackQuality,
        hasVideoTrack,
        initSegmentRequired,
        instance,
        lastFragmentRequest,
        lastInitializedRepresentationId,
        logger,
        managedMediaSourceAllowsRequest,
        scheduleTimeout,
        streamInfo,
        switchTrack,
        timeToLoadDelay;
 
    function setup() {
        logger = Debug(context).getInstance().getLogger(instance);
        resetInitialSettings();
        streamInfo = config.streamInfo;
    }
 
    function initialize(_hasVideoTrack) {
        hasVideoTrack = _hasVideoTrack;
 
        eventBus.on(Events.URL_RESOLUTION_FAILED, _onURLResolutionFailed, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);
        eventBus.on(MediaPlayerEvents.MANAGED_MEDIA_SOURCE_START_STREAMING, _onManagedMediaSourceStartStreaming, instance);
        eventBus.on(MediaPlayerEvents.MANAGED_MEDIA_SOURCE_END_STREAMING, _onManagedMediaSourceEndStreaming, instance);
    }
 
    function _onManagedMediaSourceStartStreaming() {
        managedMediaSourceAllowsRequest = true;
    }
 
    function _onManagedMediaSourceEndStreaming() {
        managedMediaSourceAllowsRequest = false;
    }
 
    function getType() {
        return type;
    }
 
    function getStreamId() {
        return streamInfo.id;
    }
 
    function startScheduleTimer(value) {
        //return if both buffering and playback have ended
        if (bufferController.getIsBufferingCompleted()) {
            return;
        }
 
        clearScheduleTimer();
        const timeoutValue = !isNaN(value) ? value : 0;
        scheduleTimeout = setTimeout(_schedule, timeoutValue);
    }
 
    function clearScheduleTimer() {
        Iif (scheduleTimeout) {
            clearTimeout(scheduleTimeout);
            scheduleTimeout = null;
        }
    }
 
    /**
     * Schedule the request for an init or a media segment
     */
    function _schedule() {
        const scheduleTimeout = mediaPlayerModel.getScheduleTimeout();
        try {
            if (_shouldClearScheduleTimer()) {
                clearScheduleTimer();
                return;
            }
 
            if (_shouldScheduleNextRequest()) {
                _scheduleNextRequest()
            } else {
                startScheduleTimer(scheduleTimeout);
            }
        } catch (e) {
            startScheduleTimer(scheduleTimeout);
        }
    }
 
    function _scheduleNextRequest() {
        const hasTriggeredManualQualitySwitch = abrController.handlePendingManualQualitySwitch(streamInfo.id, type);
 
        if (hasTriggeredManualQualitySwitch) {
            return
        }
 
        let qualityChange = false;
        if (shouldCheckPlaybackQuality) {
            // in case the playback quality is supposed to be changed, the corresponding StreamProcessor will update the currentRepresentation.
            // The StreamProcessor will also start the schedule timer again once the quality switch has been prepared. Consequently, we only call _getNextFragment if the quality is not changed.
            qualityChange = abrController.checkPlaybackQuality(type, streamInfo.id);
        }
        if (!qualityChange) {
            _getNextFragment();
        }
    }
 
    /**
     * Triggers the events to start requesting an init or a media segment. This will be picked up by the corresponding StreamProcessor.
     * @private
     */
    function _getNextFragment() {
        const currentRepresentation = representationController.getCurrentRepresentation();
 
        // A quality changed occured or we are switching the AdaptationSet. In that case we need to load a new init segment
        if (initSegmentRequired || currentRepresentation.id !== lastInitializedRepresentationId || switchTrack) {
            _initFragmentNeeded(currentRepresentation)
        } else {
            _mediaFragmentNeeded()
        }
    }
 
    function _initFragmentNeeded(currentRepresentation) {
        if (switchTrack) {
            logger.debug('Switch track for ' + type + ', representation id = ' + currentRepresentation.id);
            switchTrack = false;
        } else {
            logger.debug('Quality has changed, get init request for representationid = ' + currentRepresentation.id);
        }
        eventBus.trigger(Events.INIT_FRAGMENT_NEEDED,
            { representationId: currentRepresentation.id, sender: instance },
            { streamId: streamInfo.id, mediaType: type }
        );
        shouldCheckPlaybackQuality = false;
        initSegmentRequired = false;
    }
 
    function _mediaFragmentNeeded() {
        logger.debug(`Media segment needed for ${type} and stream id ${streamInfo.id}`);
        eventBus.trigger(Events.MEDIA_FRAGMENT_NEEDED,
            {},
            { streamId: streamInfo.id, mediaType: type }
        );
        shouldCheckPlaybackQuality = true;
    }
 
    /**
     * Check if we need to stop scheduling for now.
     * @return {boolean}
     * @private
     */
    function _shouldClearScheduleTimer() {
        try {
            return (((type === Constants.TEXT) && !textController.isTextEnabled()) ||
                (playbackController.isPaused() && (!playbackController.getStreamController().getInitialPlayback() || !playbackController.getStreamController().getAutoPlay()) && !settings.get().streaming.scheduling.scheduleWhilePaused));
        } catch (e) {
            return false;
        }
    }
 
    /**
     * Check if we can start scheduling the next request
     * @return {boolean}
     * @private
     */
    function _shouldScheduleNextRequest() {
        try {
            if (!managedMediaSourceAllowsRequest) {
                return false;
            }
            const currentRepresentation = representationController.getCurrentRepresentation();
            return currentRepresentation && (lastInitializedRepresentationId == null || switchTrack || _shouldBuffer());
        } catch (e) {
            return false;
        }
    }
 
    /**
     * Check if the current buffer level is below our buffer target.
     * @return {boolean}
     * @private
     */
    function _shouldBuffer() {
        const currentRepresentation = representationController.getCurrentRepresentation();
        if (!type || !currentRepresentation) {
            return true;
        }
        let segmentDurationToAddToBufferLevel = currentRepresentation && currentRepresentation.segmentDuration && !isNaN(currentRepresentation.segmentDuration) ? currentRepresentation.segmentDuration : 0;
        const bufferLevel = dashMetrics.getCurrentBufferLevel(type);
        const bufferTarget = getBufferTarget();
 
        // If the buffer target is smaller than the segment duration we do not take it into account. For low latency playback do not delay the buffering.
        if (bufferTarget <= segmentDurationToAddToBufferLevel || playbackController.getLowLatencyModeEnabled() || (type === Constants.AUDIO && hasVideoTrack)) {
            segmentDurationToAddToBufferLevel = 0;
        }
 
        return bufferLevel + segmentDurationToAddToBufferLevel < bufferTarget;
    }
 
    /**
     * Determine the buffer target depending on the type and whether we have audio and video AdaptationSets available
     * @return {number}
     */
    function getBufferTarget() {
        let bufferTarget = NaN;
        const currentRepresentation = representationController.getCurrentRepresentation();
 
        if (!type || !currentRepresentation) {
            return bufferTarget;
        }
 
        if (type === Constants.TEXT) {
            bufferTarget = _getBufferTargetForFragmentedText();
        } else if (type === Constants.AUDIO && hasVideoTrack) {
            bufferTarget = _getBufferTargetForAudio();
        } else {
            bufferTarget = _getGenericBufferTarget();
        }
 
        return bufferTarget;
    }
 
    /**
     * Returns the buffer target for fragmented text tracks
     * @return {number}
     * @private
     */
    function _getBufferTargetForFragmentedText() {
        try {
            if (textController.isTextEnabled()) {
                const currentRepresentation = representationController.getCurrentRepresentation();
                Iif (isNaN(currentRepresentation.fragmentDuration)) {
                    // call metrics function to have data in the latest scheduling info...
                    // if no metric, returns 0. In this case, rule will return false.
                    const schedulingInfo = dashMetrics.getCurrentSchedulingInfo(MetricsConstants.SCHEDULING_INFO);
                    return schedulingInfo ? schedulingInfo.duration : 0;
                } else {
                    return currentRepresentation.fragmentDuration;
                }
            } else { // text is disabled, rule will return false
                return 0;
            }
        } catch (e) {
            return 0;
        }
    }
 
    /**
     * Returns the buffer target for audio tracks in case we have a video track available as well
     * @return {number}
     * @private
     */
    function _getBufferTargetForAudio() {
        try {
            const videoBufferLevel = dashMetrics.getCurrentBufferLevel(Constants.VIDEO);
            const currentRepresentation = representationController.getCurrentRepresentation();
            // For multiperiod we need to consider that audio and video segments might have different durations.
            // This can lead to scenarios in which we completely buffered the video segments and the video buffer level for the current period is not changing anymore. However we might still need a small audio segment to finish buffering audio as well.
            // If we set the buffer time of audio equal to the video buffer time scheduling for the remaining audio segment will only be triggered when audio fragmentDuration > videoBufferLevel. That will delay preloading of the upcoming period.
            // Should find a better solution than just adding 1
            if (isNaN(currentRepresentation.fragmentDuration)) {
                return videoBufferLevel + 1;
            } else E{
                return Math.max(videoBufferLevel + 1, currentRepresentation.fragmentDuration);
            }
        } catch (e) {
            return 0;
        }
    }
 
    /**
     * Determines the generic buffer target, for instance for video tracks or when we got an audio only stream
     * @return {number}
     * @private
     */
    function _getGenericBufferTarget() {
        try {
            const currentRepresentation = representationController.getCurrentRepresentation();
            const streamInfo = currentRepresentation.mediaInfo.streamInfo;
            if (abrController.isPlayingAtTopQuality(currentRepresentation)) {
                const isLongFormContent = streamInfo.manifestInfo.duration >= settings.get().streaming.buffer.longFormContentDurationThreshold;
                return isLongFormContent ? settings.get().streaming.buffer.bufferTimeAtTopQualityLongForm : settings.get().streaming.buffer.bufferTimeAtTopQuality;
            } else {
                return mediaPlayerModel.getBufferTimeDefaultUnadjusted();
            }
        } catch (e) {
            return mediaPlayerModel.getBufferTimeDefaultUnadjusted();
        }
    }
 
    function setSwitchTrack(value) {
        switchTrack = value;
    }
 
    function getSwitchTrack() {
        return switchTrack;
    }
 
    function _onPlaybackTimeUpdated() {
        _completeQualityChange(true);
    }
 
    function _completeQualityChange(triggerQualityChangeRenderedEvent) {
        Iif (playbackController && fragmentModel) {
            const item = fragmentModel.getRequests({
                state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
                time: playbackController.getTime(),
                threshold: 0
            })[0];
 
            if (item && playbackController.getTime() >= item.startTime) {
                if ((!lastFragmentRequest.representation || (item.representation.mediaInfo.type === lastFragmentRequest.representation.mediaInfo.type && item.representation.mediaInfo.index !== lastFragmentRequest.representation.mediaInfo.index)) && triggerQualityChangeRenderedEvent) {
                    _triggerTrackChangeRendered(item);
                }
                if ((!lastFragmentRequest.representation || (item.representation.id !== lastFragmentRequest.representation.id)) && triggerQualityChangeRenderedEvent) {
                    _triggerQualityChangeRendered(item);
                }
                lastFragmentRequest.representation = item.representation
            }
        }
    }
 
    function _triggerTrackChangeRendered(item) {
        logger.debug(`Track change rendered for streamId ${streamInfo.id} and type ${type}`);
        eventBus.trigger(Events.TRACK_CHANGE_RENDERED, {
            mediaType: type,
            oldMediaInfo: lastFragmentRequest && lastFragmentRequest.representation && lastFragmentRequest.representation.mediaInfo ? lastFragmentRequest.representation.mediaInfo : null,
            newMediaInfo: item.representation.mediaInfo,
            streamId: streamInfo.id
        });
    }
 
    function _triggerQualityChangeRendered(item) {
        logger.debug(`Quality change rendered for streamId ${streamInfo.id} and type ${type}`);
        eventBus.trigger(Events.QUALITY_CHANGE_RENDERED, {
            mediaType: type,
            oldRepresentation: lastFragmentRequest.representation ? lastFragmentRequest.representation : null,
            newRepresentation: item.representation,
            streamId: streamInfo.id
        });
    }
 
    function _onURLResolutionFailed() {
        fragmentModel.abortRequests();
        clearScheduleTimer();
    }
 
    function _onPlaybackStarted() {
        if (!settings.get().streaming.scheduling.scheduleWhilePaused) {
            startScheduleTimer();
        }
    }
 
    function _onPlaybackRateChanged(e) {
        dashMetrics.updatePlayListTraceMetrics({ playbackspeed: e.playbackRate.toString() });
    }
 
    function setTimeToLoadDelay(value) {
        timeToLoadDelay = value;
    }
 
    function getTimeToLoadDelay() {
        return timeToLoadDelay;
    }
 
    function setShouldCheckPlaybackQuality(value) {
        shouldCheckPlaybackQuality = value;
    }
 
    function setInitSegmentRequired(value) {
        initSegmentRequired = value;
    }
 
    function setLastInitializedRepresentationId(value) {
        lastInitializedRepresentationId = value;
    }
 
    function resetInitialSettings() {
        shouldCheckPlaybackQuality = true;
        timeToLoadDelay = 0;
        lastInitializedRepresentationId = null;
        lastFragmentRequest = {
            representation: null,
        };
        switchTrack = false;
        initSegmentRequired = false;
        managedMediaSourceAllowsRequest = true;
    }
 
    function reset() {
        eventBus.off(Events.URL_RESOLUTION_FAILED, _onURLResolutionFailed, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);
        eventBus.off(MediaPlayerEvents.MANAGED_MEDIA_SOURCE_START_STREAMING, _onManagedMediaSourceStartStreaming, instance);
        eventBus.off(MediaPlayerEvents.MANAGED_MEDIA_SOURCE_END_STREAMING, _onManagedMediaSourceEndStreaming, instance);
 
        clearScheduleTimer();
        _completeQualityChange(false);
        resetInitialSettings();
        streamInfo = null;
    }
 
    function getPlaybackController() {
        return playbackController;
    }
 
    instance = {
        clearScheduleTimer,
        getBufferTarget,
        getPlaybackController,
        getStreamId,
        getSwitchTrack,
        getTimeToLoadDelay,
        getType,
        initialize,
        reset,
        setShouldCheckPlaybackQuality,
        setInitSegmentRequired,
        setLastInitializedRepresentationId,
        setup,
        setSwitchTrack,
        setTimeToLoadDelay,
        startScheduleTimer,
    };
 
    setup();
 
    return instance;
}
 
ScheduleController.__dashjs_factory_name = 'ScheduleController';
export default FactoryMaker.getClassFactory(ScheduleController);