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

89.97% Statements 305/339
81.77% Branches 184/225
94% Functions 47/50
89.88% Lines 302/336

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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770                                                                                              1x 1x 1x                                         49x 49x 49x 49x     49x 49x 49x       94x 94x 94x 94x 94x 94x       94x   94x       99x       99x 94x     99x 94x     99x 94x     99x 94x     99x 99x         99x               99x 99x 99x 99x 99x 99x 99x               4x 4x         4x       4x       99x 49x   50x 50x     50x     50x 50x     50x       39x 39x 38x 38x 38x   38x           38x           1x             74x 74x 74x   74x 571x   526x 526x     4x         37x 37x 36x 36x 36x 36x   36x           36x     1x             88x 88x       88x 8x       8x         88x 88x 88x       74x   74x 8x     74x 138x   74x         74x       74x       74x 74x 74x 74x 1274x   74x       74x 8x     74x       328x 328x 322x 322x         30x     328x       86x 86x   86x 8x     86x                 95x       86x 86x   86x   86x 80x 6x 74x 61x 61x 13x 9x 4x 3x 1x   1x 1x     6x               86x 62x 42x           1x   1x   1x                       6x   6x   6x       62x 62x 62x 62x 62x 62x 62x 62x 62x   62x     62x 47x   62x     62x     62x               62x 62x 56x   62x 10x     62x 47x 45x 2x 2x       62x 4x     62x 47x     62x 24x     62x 62x     62x 62x     62x 62x     62x 61x     62x 2x     62x 4x 4x     62x 37x 37x 37x     62x         123x 33x     123x 33x     123x 33x         9x   9x 9x   9x       3x   3x   3x         80x 80x   80x 80x   80x   80x 80x   80x   80x 4x     80x 2x     80x 2x     80x 2x     80x 4x 4x 4x   4x 4x 2x 2x           80x       36x 36x                 62x 62x             62x 62x 15x   57x   5x         62x 62x             62x 62x   5x         62x 62x 62x   57x 57x         5x         86x 86x   81x 81x         5x         2x 2x             2x 2x 2x 2x   2x 2x           2x 2x 2x   2x 2x   2x 2x                   2x 2x 2x       2x 2x 2x           62x 5x   57x 67x 47x           56x   56x 51x 51x   51x 51x   24x     24x 24x         24x 24x 24x 24x 24x       24x   32x         50x 50x 50x 50x 50x 50x   50x     49x                     49x   49x     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 EventBus from '../../core/EventBus.js';
import MediaPlayerEvents from '../MediaPlayerEvents.js';
import MetricsReportingEvents from '../metrics/MetricsReportingEvents.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import Settings from '../../core/Settings.js';
import Constants from '../../streaming/constants/Constants.js';
import {HTTPRequest} from '../vo/metrics/HTTPRequest.js';
import DashManifestModel from '../../dash/models/DashManifestModel.js';
import Debug from '../../core/Debug.js';
import Utils from '../../core/Utils.js';
import {CMCD_PARAM} from '@svta/common-media-library/cmcd/CMCD_PARAM';
import {CmcdObjectType} from '@svta/common-media-library/cmcd/CmcdObjectType';
import {CmcdStreamType} from '@svta/common-media-library/cmcd/CmcdStreamType';
import {CmcdStreamingFormat} from '@svta/common-media-library/cmcd/CmcdStreamingFormat';
import {encodeCmcd} from '@svta/common-media-library/cmcd/encodeCmcd';
import {toCmcdHeaders} from '@svta/common-media-library/cmcd/toCmcdHeaders';
import {CmcdHeaderField} from '@svta/common-media-library/cmcd/CmcdHeaderField';
const DEFAULT_CMCD_VERSION = 1;
const DEFAULT_INCLUDE_IN_REQUESTS = 'segment';
const RTP_SAFETY_FACTOR = 5;
 
function CmcdModel() {
 
    let dashManifestModel,
        instance,
        logger,
        internalData,
        abrController,
        dashMetrics,
        playbackController,
        serviceDescriptionController,
        throughputController,
        streamProcessors,
        _lastMediaTypeRequest,
        _isStartup,
        _bufferLevelStarved,
        _initialMediaRequestsDone,
        _playbackStartedTime,
        _msdSent;
 
    let context = this.context;
    let eventBus = EventBus(context).getInstance();
    let settings = Settings(context).getInstance();
    let debug = Debug(context).getInstance();
 
    function setup() {
        dashManifestModel = DashManifestModel(context).getInstance();
        logger = debug.getLogger(instance);
        _resetInitialSettings();
    }
 
    function initialize(autoPlay) {
        eventBus.on(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);
        eventBus.on(MediaPlayerEvents.MANIFEST_LOADED, _onManifestLoaded, instance);
        eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKED, _onPlaybackSeeked, instance);
        eventBus.on(MediaPlayerEvents.PERIOD_SWITCH_COMPLETED, _onPeriodSwitchComplete, instance);
        Iif (autoPlay) {
            eventBus.on(MediaPlayerEvents.MANIFEST_LOADING_STARTED, _onPlaybackStarted, instance);
        }
        else {
            eventBus.on(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);
        }
        eventBus.on(MediaPlayerEvents.PLAYBACK_PLAYING, _onPlaybackPlaying, instance);
    }
 
    function setConfig(config) {
        Iif (!config) {
            return;
        }
 
        if (config.abrController) {
            abrController = config.abrController;
        }
 
        if (config.dashMetrics) {
            dashMetrics = config.dashMetrics;
        }
 
        if (config.throughputController) {
            throughputController = config.throughputController;
        }
 
        if (config.playbackController) {
            playbackController = config.playbackController;
        }
 
        if (config.serviceDescriptionController) {
            serviceDescriptionController = config.serviceDescriptionController;
        }
    }
 
    function _resetInitialSettings() {
        internalData = {
            pr: 1,
            nor: null,
            st: null,
            sf: null,
            sid: `${Utils.generateUuid()}`,
            cid: null
        };
        _bufferLevelStarved = {};
        _isStartup = {};
        _initialMediaRequestsDone = {};
        _lastMediaTypeRequest = undefined;
        _playbackStartedTime = undefined;
        _msdSent = false;
        _updateStreamProcessors();
    }
 
    function _onPeriodSwitchComplete() {
        _updateStreamProcessors();
    }
 
    function _onPlaybackStarted() {
        if (!_playbackStartedTime) {
            _playbackStartedTime = Date.now();
        }
    }
 
    function _onPlaybackPlaying() {
        Iif (!_playbackStartedTime || internalData.msd) {
            return;
        }
 
        internalData.msd = Date.now() - _playbackStartedTime;
    }
 
    function _updateStreamProcessors() {
        if (!playbackController) {
            return;
        }
        const streamController = playbackController.getStreamController();
        Iif (!streamController) {
            return;
        }
        Iif (typeof streamController.getActiveStream !== 'function') {
            return;
        }
        const activeStream = streamController.getActiveStream();
        Iif (!activeStream) {
            return;
        }
        streamProcessors = activeStream.getStreamProcessors();
    }
 
    function getQueryParameter(request) {
        try {
            if (isCmcdEnabled()) {
                const cmcdData = getCmcdData(request);
                const filteredCmcdData = _applyWhitelist(cmcdData);
                const finalPayloadString = encodeCmcd(filteredCmcdData);
 
                eventBus.trigger(MetricsReportingEvents.CMCD_DATA_GENERATED, {
                    url: request.url,
                    mediaType: request.mediaType,
                    cmcdData,
                    cmcdString: finalPayloadString
                });
                return {
                    key: CMCD_PARAM,
                    value: finalPayloadString
                };
            }
 
            return null;
        } catch (e) {
            return null;
        }
    }
 
    function _applyWhitelist(cmcdData) {
        try {
            const cmcdParametersFromManifest = getCmcdParametersFromManifest();
            const enabledCMCDKeys = cmcdParametersFromManifest.version ? cmcdParametersFromManifest.keys : settings.get().streaming.cmcd.enabledKeys;
 
            return Object.keys(cmcdData)
                .filter(key => enabledCMCDKeys.includes(key))
                .reduce((obj, key) => {
                    obj[key] = cmcdData[key];
                    return obj;
                }, {});
        } catch (e) {
            return cmcdData;
        }
    }
 
    function getHeaderParameters(request) {
        try {
            if (isCmcdEnabled()) {
                const cmcdData = getCmcdData(request);
                const filteredCmcdData = _applyWhitelist(cmcdData);
                const options = _createCmcdV2HeadersCustomMap();
                const headers = toCmcdHeaders(filteredCmcdData, options);
 
                eventBus.trigger(MetricsReportingEvents.CMCD_DATA_GENERATED, {
                    url: request.url,
                    mediaType: request.mediaType,
                    cmcdData,
                    headers
                });
                return headers;
            }
 
            return null;
        } catch (e) {
            return null;
        }
    }
 
    function isCmcdEnabled() {
        const cmcdParametersFromManifest = getCmcdParametersFromManifest();
        return _canBeEnabled(cmcdParametersFromManifest) && _checkIncludeInRequests(cmcdParametersFromManifest) && _checkAvailableKeys(cmcdParametersFromManifest);
    }
 
    function _canBeEnabled(cmcdParametersFromManifest) {
        if (Object.keys(cmcdParametersFromManifest).length) {
            Iif (parseInt(cmcdParametersFromManifest.version) !== 1) {
                logger.error(`version parameter must be defined in 1.`);
                return false;
            }
            Iif (!cmcdParametersFromManifest.keys) {
                logger.error(`keys parameter must be defined.`);
                return false;
            }
        }
        const isEnabledFromManifest = cmcdParametersFromManifest.version;
        const isEnabledFromSettings = settings.get().streaming.cmcd && settings.get().streaming.cmcd.enabled;
        return isEnabledFromManifest || isEnabledFromSettings;
    }
 
    function _checkIncludeInRequests(cmcdParametersFromManifest) {
        let enabledRequests = settings.get().streaming.cmcd.includeInRequests;
 
        if (cmcdParametersFromManifest.version) {
            enabledRequests = cmcdParametersFromManifest.includeInRequests ?? [DEFAULT_INCLUDE_IN_REQUESTS];
        }
 
        const defaultAvailableRequests = Constants.CMCD_AVAILABLE_REQUESTS;
        const invalidRequests = enabledRequests.filter(k => !defaultAvailableRequests.includes(k));
 
        Iif (invalidRequests.length === enabledRequests.length) {
            logger.error(`None of the request types are supported.`);
            return false;
        }
 
        invalidRequests.map((k) => {
            logger.warn(`request type ${k} is not supported.`);
        });
 
        return true;
    }
 
    function _checkAvailableKeys(cmcdParametersFromManifest) {
        const defaultAvailableKeys = Constants.CMCD_AVAILABLE_KEYS;
        const defaultV2AvailableKeys = Constants.CMCD_V2_AVAILABLE_KEYS;
        const enabledCMCDKeys = cmcdParametersFromManifest.version ? cmcdParametersFromManifest.keys : settings.get().streaming.cmcd.enabledKeys;
        const cmcdVersion = settings.get().streaming.cmcd.version;
        const invalidKeys = enabledCMCDKeys.filter(k => !defaultAvailableKeys.includes(k) && !(cmcdVersion === 2 && defaultV2AvailableKeys.includes(k)));
 
        Iif (invalidKeys.length === enabledCMCDKeys.length && enabledCMCDKeys.length > 0) {
            logger.error(`None of the keys are implemented for CMCD version ${cmcdVersion}.`);
            return false;
        }
        invalidKeys.map((k) => {
            logger.warn(`key parameter ${k} is not implemented for CMCD version ${cmcdVersion}.`);
        });
 
        return true;
    }
 
    function getCmcdParametersFromManifest() {
        let cmcdParametersFromManifest = {};
        if (serviceDescriptionController) {
            const serviceDescription = serviceDescriptionController.getServiceDescriptionSettings();
            if (
                settings.get().streaming.cmcd.applyParametersFromMpd &&
                serviceDescription.clientDataReporting &&
                serviceDescription.clientDataReporting.cmcdParameters
            ) {
                cmcdParametersFromManifest = serviceDescription.clientDataReporting.cmcdParameters;
            }
        }
        return cmcdParametersFromManifest;
    }
 
    function _isIncludedInRequestFilter(type) {
        const cmcdParametersFromManifest = getCmcdParametersFromManifest();
        let includeInRequestsArray = settings.get().streaming.cmcd.includeInRequests;
 
        if (cmcdParametersFromManifest.version) {
            includeInRequestsArray = cmcdParametersFromManifest.includeInRequests ? cmcdParametersFromManifest.includeInRequests : [DEFAULT_INCLUDE_IN_REQUESTS];
        }
 
        const filtersTypes = {
            [HTTPRequest.INIT_SEGMENT_TYPE]: 'segment',
            [HTTPRequest.MEDIA_SEGMENT_TYPE]: 'segment',
            [HTTPRequest.XLINK_EXPANSION_TYPE]: 'xlink',
            [HTTPRequest.MPD_TYPE]: 'mpd',
            [HTTPRequest.CONTENT_STEERING_TYPE]: 'steering',
            [HTTPRequest.OTHER_TYPE]: 'other',
        };
 
        return includeInRequestsArray.some(t => filtersTypes[type] === t);
    }
 
    function getCmcdData(request) {
        try {
            let cmcdData = null;
 
            _updateLastMediaTypeRequest(request.type, request.mediaType);
 
            if (_isIncludedInRequestFilter(request.type)) {
                if (request.type === HTTPRequest.MPD_TYPE) {
                    return _getCmcdDataForMpd(request);
                } else if (request.type === HTTPRequest.MEDIA_SEGMENT_TYPE) {
                    _initForMediaType(request.mediaType);
                    return _getCmcdDataForMediaSegment(request, request.mediaType);
                } else if (request.type === HTTPRequest.INIT_SEGMENT_TYPE) {
                    return _getCmcdDataForInitSegment(request);
                } else if (request.type === HTTPRequest.OTHER_TYPE || request.type === HTTPRequest.XLINK_EXPANSION_TYPE) {
                    return _getCmcdDataForOther(request);
                } else Iif (request.type === HTTPRequest.LICENSE) {
                    return _getCmcdDataForLicense(request);
                } else if (request.type === HTTPRequest.CONTENT_STEERING_TYPE) {
                    return _getCmcdDataForSteering(request);
                }
            }
            return cmcdData;
        } catch (e) {
            return null;
        }
    }
 
    function _updateLastMediaTypeRequest(type, mediatype) {
        // Video > Audio > None
        if (mediatype === Constants.VIDEO || mediatype === Constants.AUDIO) {
            if (!_lastMediaTypeRequest || _lastMediaTypeRequest == Constants.AUDIO) {
                _lastMediaTypeRequest = mediatype;
            }
        }
    }
 
    function _getCmcdDataForSteering(request) {
        const data = !_lastMediaTypeRequest ? _getGenericCmcdData(request) : _getCmcdDataForMediaSegment(request, _lastMediaTypeRequest);
 
        data.ot = CmcdObjectType.OTHER;
 
        return data;
    }
 
    function _getCmcdDataForLicense(request) {
        const data = _getGenericCmcdData(request);
 
        data.ot = CmcdObjectType.KEY;
 
        return data;
    }
 
    function _getCmcdDataForMpd() {
        const data = _getGenericCmcdData();
 
        data.ot = CmcdObjectType.MANIFEST;
 
        return data;
    }
 
    function _getCmcdDataForMediaSegment(request, mediaType) {
        _initForMediaType(mediaType);
        const data = _getGenericCmcdData();
        const encodedBitrate = _getBitrateByRequest(request);
        const d = _getObjectDurationByRequest(request);
        const mtp = _getMeasuredThroughputByType(mediaType);
        const dl = _getDeadlineByType(mediaType);
        const bl = _getBufferLevelByType(mediaType);
        const tb = _getTopBitrateByType(request.representation?.mediaInfo);
        const pr = internalData.pr;
 
        const nextRequest = _probeNextRequest(mediaType);
 
        let ot;
        if (mediaType === Constants.VIDEO) {
            ot = CmcdObjectType.VIDEO;
        }
        Iif (mediaType === Constants.AUDIO) {
            ot = CmcdObjectType.AUDIO;
        }
        Iif (request.mediaType === Constants.ENHANCEMENT) {
            ot = CmcdObjectType.OTHER;
        }
        Iif (mediaType === Constants.TEXT) {
            if (request.representation.mediaInfo.mimeType === 'application/mp4') {
                ot = CmcdObjectType.TIMED_TEXT;
            } else {
                ot = CmcdObjectType.CAPTION;
            }
        }
 
        let rtp = settings.get().streaming.cmcd.rtp;
        if (!rtp) {
            rtp = _calculateRtp(request);
        }
        if (!isNaN(rtp)) {
            data.rtp = rtp;
        }
 
        if (nextRequest) {
            if (request.url !== nextRequest.url) {
                data.nor = encodeURIComponent(Utils.getRelativeUrl(request.url, nextRequest.url));
            } else if (nextRequest.range) {
                data.nrr = nextRequest.range;
            }
        }
 
        if (encodedBitrate) {
            data.br = encodedBitrate;
        }
 
        if (ot) {
            data.ot = ot;
        }
 
        if (!isNaN(d)) {
            data.d = d;
        }
 
        if (!isNaN(mtp)) {
            data.mtp = mtp;
        }
 
        if (!isNaN(dl)) {
            data.dl = dl;
        }
 
        if (!isNaN(bl)) {
            data.bl = bl;
        }
 
        if (!isNaN(tb)) {
            data.tb = tb;
        }
 
        if (!isNaN(pr) && pr !== 1) {
            data.pr = pr;
        }
 
        if (_bufferLevelStarved[mediaType]) {
            data.bs = true;
            _bufferLevelStarved[mediaType] = false;
        }
 
        if (_isStartup[mediaType] || !_initialMediaRequestsDone[mediaType]) {
            data.su = true;
            _isStartup[mediaType] = false;
            _initialMediaRequestsDone[mediaType] = true;
        }
 
        return data;
    }
 
    function _initForMediaType(mediaType) {
 
        if (!_initialMediaRequestsDone.hasOwnProperty(mediaType)) {
            _initialMediaRequestsDone[mediaType] = false;
        }
 
        if (!_isStartup.hasOwnProperty(mediaType)) {
            _isStartup[mediaType] = false;
        }
 
        if (!_bufferLevelStarved.hasOwnProperty(mediaType)) {
            _bufferLevelStarved[mediaType] = false;
        }
    }
 
    function _getCmcdDataForInitSegment() {
        const data = _getGenericCmcdData();
 
        data.ot = CmcdObjectType.INIT;
        data.su = true;
 
        return data;
    }
 
    function _getCmcdDataForOther() {
        const data = _getGenericCmcdData();
 
        data.ot = CmcdObjectType.OTHER;
 
        return data;
    }
 
 
    function _getGenericCmcdData() {
        const cmcdParametersFromManifest = getCmcdParametersFromManifest();
        const data = {};
 
        let cid = settings.get().streaming.cmcd.cid ? settings.get().streaming.cmcd.cid : internalData.cid;
        cid = cmcdParametersFromManifest.contentID ? cmcdParametersFromManifest.contentID : cid;
 
        data.v = settings.get().streaming.cmcd.version ?? DEFAULT_CMCD_VERSION;
 
        data.sid = settings.get().streaming.cmcd.sid ? settings.get().streaming.cmcd.sid : internalData.sid;
        data.sid = cmcdParametersFromManifest.sessionID ? cmcdParametersFromManifest.sessionID : data.sid;
 
        data.sid = `${data.sid}`;
 
        if (cid) {
            data.cid = `${cid}`;
        }
 
        if (!isNaN(internalData.pr) && internalData.pr !== 1 && internalData.pr !== null) {
            data.pr = internalData.pr;
        }
 
        if (internalData.st) {
            data.st = internalData.st;
        }
 
        if (internalData.sf) {
            data.sf = internalData.sf;
        }
 
        if (data.v === 2) {
            let ltc = playbackController.getCurrentLiveLatency() * 1000;
            if (!isNaN(ltc)) {
                data.ltc = ltc;
            }
            const msd = internalData.msd;
            if (!_msdSent && !isNaN(msd)) {
                data.msd = msd;
                _msdSent = true;
            }
        }
 
        
 
        return data;
    }
 
    function _createCmcdV2HeadersCustomMap() {
        const cmcdVersion = settings.get().streaming.cmcd.version;
        return cmcdVersion === 1 ? {} : { 
            customHeaderMap: { 
                [CmcdHeaderField.REQUEST]: ['ltc'],
                [CmcdHeaderField.SESSION]: ['msd']
            }
        };
    }
 
    function _getBitrateByRequest(request) {
        try {
            return parseInt(request.bandwidth / 1000);
        } catch (e) {
            return null;
        }
    }
 
    function _getTopBitrateByType(mediaInfo) {
        try {
            const bitrates = abrController.getPossibleVoRepresentationsFilteredBySettings(mediaInfo).map((rep) => {
                return rep.bitrateInKbit
            });
            return Math.max(...bitrates)
        } catch (e) {
            return null;
        }
    }
 
    function _getObjectDurationByRequest(request) {
        try {
            return !isNaN(request.duration) ? Math.round(request.duration * 1000) : NaN;
        } catch (e) {
            return null;
        }
    }
 
    function _getMeasuredThroughputByType(mediaType) {
        try {
            return parseInt(throughputController.getSafeAverageThroughput(mediaType) / 100) * 100;
        } catch (e) {
            return null;
        }
    }
 
    function _getDeadlineByType(mediaType) {
        try {
            const playbackRate = internalData.pr;
            const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);
 
            if (!isNaN(playbackRate) && !isNaN(bufferLevel)) {
                return parseInt((bufferLevel / playbackRate) * 10) * 100;
            }
 
            return null;
        } catch (e) {
            return null;
        }
    }
 
    function _getBufferLevelByType(mediaType) {
        try {
            const bufferLevel = dashMetrics.getCurrentBufferLevel(mediaType);
 
            if (!isNaN(bufferLevel)) {
                return parseInt(bufferLevel * 10) * 100;
            }
 
            return null;
        } catch (e) {
            return null;
        }
    }
 
    function _onPlaybackRateChanged(data) {
        try {
            internalData.pr = data.playbackRate;
        } catch (e) {
 
        }
    }
 
    function _onManifestLoaded(data) {
        try {
            const isDynamic = dashManifestModel.getIsDynamic(data.data);
            const st = isDynamic ? CmcdStreamType.LIVE : CmcdStreamType.VOD;
            const sf = data.protocol && data.protocol === 'MSS' ? CmcdStreamingFormat.SMOOTH : CmcdStreamingFormat.DASH;
 
            internalData.st = `${st}`;
            internalData.sf = `${sf}`;
        } catch (e) {
        }
    }
 
    function _onBufferLevelStateChanged(data) {
        try {
            if (data.state && data.mediaType) {
                if (data.state === MediaPlayerEvents.BUFFER_EMPTY) {
 
                    if (!_bufferLevelStarved[data.mediaType]) {
                        _bufferLevelStarved[data.mediaType] = true;
                    }
                    if (!_isStartup[data.mediaType]) {
                        _isStartup[data.mediaType] = true;
                    }
                }
            }
        } catch (e) {
 
        }
    }
 
    function _onPlaybackSeeked() {
        for (let key in _bufferLevelStarved) {
            if (_bufferLevelStarved.hasOwnProperty(key)) {
                _bufferLevelStarved[key] = true;
            }
        }
 
        for (let key in _isStartup) {
            if (_isStartup.hasOwnProperty(key)) {
                _isStartup[key] = true;
            }
        }
    }
 
    function _probeNextRequest(mediaType) {
        if (!streamProcessors || streamProcessors.length === 0) {
            return;
        }
        for (let streamProcessor of streamProcessors) {
            if (streamProcessor.getType() === mediaType) {
                return streamProcessor.probeNextRequest();
            }
        }
    }
 
    function _calculateRtp(request) {
        try {
            // Get the values we need
            let playbackRate = playbackController.getPlaybackRate();
            if (!playbackRate) {
                playbackRate = 1;
            }
            let { bandwidth, mediaType, representation, duration } = request;
            const mediaInfo = representation.mediaInfo;
 
            Iif (!mediaInfo) {
                return NaN;
            }
            let currentBufferLevel = _getBufferLevelByType(mediaType);
            Iif (currentBufferLevel === 0) {
                currentBufferLevel = 500;
            }
 
            // Calculate RTP
            let segmentSize = (bandwidth * duration) / 1000; // Calculate file size in kilobits
            let timeToLoad = (currentBufferLevel / playbackRate) / 1000; // Calculate time available to load file in seconds
            let minBandwidth = segmentSize / timeToLoad; // Calculate the exact bandwidth required
            let rtpSafetyFactor = settings.get().streaming.cmcd.rtpSafetyFactor && !isNaN(settings.get().streaming.cmcd.rtpSafetyFactor) ? settings.get().streaming.cmcd.rtpSafetyFactor : RTP_SAFETY_FACTOR;
            let maxBandwidth = minBandwidth * rtpSafetyFactor; // Include a safety buffer
 
 
            // Round to the next multiple of 100
            return (parseInt(maxBandwidth / 100) + 1) * 100;
        } catch (e) {
            return NaN;
        }
    }
 
    function reset() {
        eventBus.off(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, this);
        eventBus.off(MediaPlayerEvents.MANIFEST_LOADED, _onManifestLoaded, this);
        eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_STATE_CHANGED, _onBufferLevelStateChanged, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKED, _onPlaybackSeeked, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_PLAYING, _onPlaybackPlaying, instance);
 
        _resetInitialSettings();
    }
 
    instance = {
        getCmcdData,
        getQueryParameter,
        getHeaderParameters,
        getCmcdParametersFromManifest,
        setConfig,
        reset,
        initialize,
        isCmcdEnabled,
    };
 
    setup();
 
    return instance;
}
 
CmcdModel.__dashjs_factory_name = 'CmcdModel';
export default FactoryMaker.getSingletonFactory(CmcdModel);