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

26.22% Statements 144/549
14.49% Branches 49/338
29.9% Functions 32/107
26.51% Lines 144/543

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 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343                                                                                      1x 1x 1x   1x       17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x                                                   17x 17x   17x               15x   15x 15x 15x   15x 15x 15x 15x 15x               120x               125x                                 16x 16x   16x                   16x                         15x 15x 1x 1x   14x 14x 14x   14x                                                               14x 14x         14x   14x     14x                   14x 14x   14x 14x     14x     14x                                       14x                                                                                                 2x 1x 1x   2x 2x                   2x   2x   1x       1x   1x   1x               2x                   5x     5x   5x           5x 5x                         5x                                   5x 5x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     4x     4x 4x 4x 4x 4x 4x       4x   4x 4x 15x 15x 15x 14x 14x   2x 2x 12x   1x 1x     1x 1x   1x             4x 3x             1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       16x 16x 15x 15x       1x   1x                                                                                       4x               1x                                                                                                                                                                           5x 5x       35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x   35x 14x 14x 14x 14x 14x   14x 14x               35x       18x 18x 18x   18x 18x 18x 18x 18x     18x     17x                                                                       17x 17x     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 MetricsConstants from '../constants/MetricsConstants.js';
import FragmentModel from '../models/FragmentModel.js';
import SourceBufferSink from '../SourceBufferSink.js';
import PreBufferSink from '../PreBufferSink.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 InitCache from '../utils/InitCache.js';
import {HTTPRequest} from '../vo/metrics/HTTPRequest.js';
import MediaPlayerEvents from '../../streaming/MediaPlayerEvents.js';
 
const BUFFER_END_THRESHOLD = 0.5;
const BUFFER_RANGE_CALCULATION_THRESHOLD = 0.01;
const QUOTA_EXCEEDED_ERROR_CODE = 22;
 
const BUFFER_CONTROLLER_TYPE = 'BufferController';
 
function BufferController(config) {
 
    config = config || {};
    const capabilities = config.capabilities;
    const context = this.context;
    const eventBus = EventBus(context).getInstance();
    const fragmentModel = config.fragmentModel;
    const playbackController = config.playbackController;
    const representationController = config.representationController;
    const settings = config.settings;
    const streamInfo = config.streamInfo;
    const textController = config.textController;
    const type = config.type;
 
    let instance,
        logger,
        isBufferingCompleted,
        bufferLevel,
        criticalBufferLevel,
        mediaSource,
        maxAppendedIndex,
        maximumIndex,
        sourceBufferSink,
        dischargeBuffer,
        isPrebuffering,
        dischargeFragments,
        bufferState,
        appendedBytesInfo,
        wallclockTicked,
        isPruningInProgress,
        isQuotaExceeded,
        initCache,
        pendingPruningRanges,
        replacingBuffer,
        seekTarget;
 
 
    function setup() {
        logger = Debug(context).getInstance().getLogger(instance);
        initCache = InitCache(context).getInstance();
 
        resetInitialSettings();
    }
 
    /**
     * Initialize the BufferController. Sets the media source and registers the event handlers.
     * @param {object} mediaSource
     */
    function initialize(mediaSource) {
        setMediaSource(mediaSource);
 
        eventBus.on(Events.INIT_FRAGMENT_LOADED, _onInitFragmentLoaded, instance);
        eventBus.on(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, instance);
        eventBus.on(Events.WALLCLOCK_TIME_UPDATED, _onWallclockTimeUpdated, instance);
 
        eventBus.on(MediaPlayerEvents.PLAYBACK_PLAYING, _onPlaybackPlaying, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_PROGRESS, _onPlaybackProgression, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackProgression, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_STALLED, _onPlaybackStalled, instance);
    }
 
    /**
     * Returns the stream id
     * @return {string}
     */
    function getStreamId() {
        return streamInfo.id;
    }
 
    /**
     * Returns the media type
     * @return {type}
     */
    function getType() {
        return type;
    }
 
    /**
     * Returns the type of the BufferController. We distinguish between standard buffer controllers and buffer controllers related to texttracks.
     * @return {string}
     */
    function getBufferControllerType() {
        return BUFFER_CONTROLLER_TYPE;
    }
 
    /**
     * Sets the mediasource.
     * @param {object} value
     * @param {object} mediaInfo
     */
    function setMediaSource(value, mediaInfo = null) {
        return new Promise((resolve, reject) => {
            mediaSource = value;
            // if we have a prebuffer, we should prepare to discharge it, and make a new sourceBuffer ready
            Iif (sourceBufferSink && mediaInfo && typeof sourceBufferSink.discharge === 'function') {
                dischargeBuffer = sourceBufferSink;
                createBufferSink(mediaInfo)
                    .then(() => {
                        resolve();
                    })
                    .catch((e) => {
                        reject(e);
                    })
            } else {
                resolve();
            }
        })
 
    }
 
    /**
     * Creates a SourceBufferSink object
     * @param {object} mediaInfo
     * @param {Map<any, any>} previousBufferSinks
     * @return {Promise<Object>} SourceBufferSink
     */
    function createBufferSink(mediaInfo, previousBufferSinks = new Map(), oldRepresentation) {
        return new Promise((resolve, reject) => {
            if (!initCache || !mediaInfo) {
                resolve(null);
                return;
            }
            if (mediaSource) {
                isPrebuffering = false;
                _initializeSinkForMseBuffering(mediaInfo, previousBufferSinks, oldRepresentation)
                    .then((sink) => {
                        resolve(sink);
                    })
                    .catch((e) => {
                        reject(e);
                    })
            } else E{
                isPrebuffering = true;
                _initializeSinkForPrebuffering()
                    .then((sink) => {
                        resolve(sink);
                    })
                    .catch((e) => {
                        reject(e);
                    })
            }
        });
    }
 
    function _initializeSinkForPrebuffering() {
        return new Promise((resolve, reject) => {
            sourceBufferSink = PreBufferSink(context).create(_onAppended.bind(this));
            updateBufferTimestampOffset(representationController.getCurrentRepresentation())
                .then(() => {
                    resolve(sourceBufferSink);
                })
                .catch(() => {
                    reject();
                })
        })
    }
 
    function _initializeSinkForMseBuffering(mediaInfo, previousBufferSinks, oldRepresentation) {
        return new Promise((resolve) => {
            sourceBufferSink = SourceBufferSink(context).create({
                mediaSource,
                textController,
                eventBus
            });
            _initializeSink(mediaInfo, previousBufferSinks, oldRepresentation)
                .then(() => {
                    return updateBufferTimestampOffset(representationController.getCurrentRepresentation());
                })
                .then(() => {
                    resolve(sourceBufferSink);
                })
                .catch((e) => {
                    logger.warn('Caught error on create SourceBuffer: ' + e);
                    resolve(sourceBufferSink);
                });
        })
    }
 
    function _initializeSink(mediaInfo, previousBufferSinks, oldRepresentation) {
        const newRepresentation = representationController.getCurrentRepresentation();
        let previousBufferSink = null;
 
        if (type === Constants.VIDEO || type === Constants.AUDIO) {
            previousBufferSink = previousBufferSinks.get(type);
        }
 
        Iif (previousBufferSink) {
            return _initializeSinkForBufferReuse(mediaInfo, newRepresentation, previousBufferSink, oldRepresentation)
        } else {
            return _initializeSinkForFirstUse(mediaInfo, newRepresentation);
        }
    }
 
    function _initializeSinkForBufferReuse(mediaInfo, newRepresentation, previousBufferSink, oldRepresentation) {
        sourceBufferSink.initializeForStreamSwitch(mediaInfo, newRepresentation, previousBufferSink);
 
        const promises = [];
        promises.push(sourceBufferSink.abortBeforeAppend());
        promises.push(updateAppendWindow());
        promises.push(_changeCodec(newRepresentation, oldRepresentation))
 
        if (newRepresentation && newRepresentation.mseTimeOffset !== undefined) {
            promises.push(updateBufferTimestampOffset(newRepresentation));
        }
 
        return Promise.allSettled(promises);
    }
 
    function _initializeSinkForFirstUse(mediaInfo, newRepresentation) {
        return sourceBufferSink.initializeForFirstUse(mediaInfo, newRepresentation);
    }
 
    function dischargePreBuffer() {
        if (sourceBufferSink && dischargeBuffer && typeof dischargeBuffer.discharge === 'function') {
            const ranges = dischargeBuffer.getAllBufferRanges();
 
            if (ranges.length > 0) {
                let rangeStr = 'Beginning ' + type + 'PreBuffer discharge, adding buffer for:';
                for (let i = 0; i < ranges.length; i++) {
                    rangeStr += ' start: ' + ranges.start(i) + ', end: ' + ranges.end(i) + ';';
                }
                logger.debug(rangeStr);
            } else {
                logger.debug('PreBuffer discharge requested, but there were no media segments in the PreBuffer.');
            }
 
            //A list of fragments to supress bytesAppended events for. This makes transferring from a prebuffer to a sourcebuffer silent.
            dischargeFragments = [];
            let chunks = dischargeBuffer.discharge();
            let lastInit = null;
            for (let j = 0; j < chunks.length; j++) {
                const chunk = chunks[j];
                if (chunk.segmentType !== HTTPRequest.INIT_SEGMENT_TYPE) {
                    const initChunk = initCache.extract(chunk.streamId, chunk.representation.id);
                    if (initChunk) {
                        if (lastInit !== initChunk) {
                            dischargeFragments.push(initChunk);
                            sourceBufferSink.append(initChunk);
                            lastInit = initChunk;
                        }
                    }
                }
                dischargeFragments.push(chunk);
                sourceBufferSink.append(chunk);
            }
 
            dischargeBuffer.reset();
            dischargeBuffer = null;
        }
    }
 
 
    /**
     * Callback handler when init segment has been loaded. Based on settings, the init segment is saved to the cache, and appended to the buffer.
     * @param {object} e
     * @private
     */
    function _onInitFragmentLoaded(e) {
        if (settings.get().streaming.cacheInitSegments) {
            logger.info('Init fragment finished loading saving to', type + '\'s init cache');
            initCache.save(e.chunk);
        }
        logger.debug(`Appending init fragment for type ${type}, representationId ${e.chunk.representation.id} and bandwidth ${e.chunk.representation.bandwidth}`);
        _appendToBuffer(e.chunk);
    }
 
    /**
     * Append the init segment for a certain representation to the buffer. If the init segment is cached we take the one from the cache. Otherwise the function returns false and the segment has to be requested again.
     * @param {string} representationId
     * @return {boolean}
     */
    function appendInitSegmentFromCache(representationId) {
        // Get init segment from cache
        const chunk = initCache.extract(streamInfo.id, representationId);
 
        if (!chunk) {
            // Init segment not in cache, shall be requested
            return false;
        }
 
        // Append init segment into buffer
        logger.debug(`Appending init fragment for type ${type}, representationId ${chunk.representation.id} and bandwidth ${chunk.representation.bandwidth}`);
 
        _appendToBuffer(chunk);
 
        return true;
    }
 
    /**
     * Calls the _appendToBuffer function to append the segment to the buffer. In case of a track switch the buffer might be cleared.
     * @param {object} e
     */
    function _onMediaFragmentLoaded(e) {
        _appendToBuffer(e.chunk, e.request);
    }
 
    /**
     * Append data to the MSE buffer using the SourceBufferSink
     * @param {object} chunk
     * @param {object} request
     * @private
     */
    function _appendToBuffer(chunk, request = null) {
        Iif (!sourceBufferSink) {
            return;
        }
        sourceBufferSink.append(chunk, request)
            .then((e) => {
                _onAppended(e);
            })
            .catch((e) => {
                _onAppended(e);
            });
 
        if (chunk.representation.mediaInfo.type === Constants.VIDEO) {
            _triggerEvent(Events.VIDEO_CHUNK_RECEIVED, { chunk: chunk });
        }
    }
 
    function _showBufferRanges(ranges) {
        if (ranges && ranges.length > 0) {
            for (let i = 0, len = ranges.length; i < len; i++) {
                logger.debug('Buffered range: ' + ranges.start(i) + ' - ' + ranges.end(i) + ', currentTime = ', playbackController.getTime());
            }
        }
    }
 
    function _onAppended(e) {
        Iif (e.error) {
            // If we receive a QUOTA_EXCEEDED_ERROR_CODE we should adjust the target buffer times to avoid this error in the future.
            if (e.error.code === QUOTA_EXCEEDED_ERROR_CODE) {
                _handleQuotaExceededError();
            }
            if (e.error.code === QUOTA_EXCEEDED_ERROR_CODE || !hasEnoughSpaceToAppend()) {
                logger.warn('Clearing playback buffer to overcome quota exceed situation');
                // Notify ScheduleController to stop scheduling until buffer has been pruned
                _triggerEvent(Events.QUOTA_EXCEEDED, {
                    criticalBufferLevel: criticalBufferLevel,
                    quotaExceededTime: e.chunk.start
                });
                clearBuffers(getClearRanges());
            }
            return;
        }
 
        // Check if session has not been stopped in the meantime (while last segment was being appended)
        if (!sourceBufferSink) {
            return;
        }
 
        _updateBufferLevel();
 
        isQuotaExceeded = false;
        appendedBytesInfo = e.chunk;
 
        if (!appendedBytesInfo || !appendedBytesInfo.endFragment) {
            return;
        }
 
        if (appendedBytesInfo && !isNaN(appendedBytesInfo.index)) {
            maxAppendedIndex = Math.max(appendedBytesInfo.index, maxAppendedIndex);
            _checkIfBufferingCompleted();
        }
 
        const ranges = sourceBufferSink.getAllBufferRanges();
        if (appendedBytesInfo.segmentType === HTTPRequest.MEDIA_SEGMENT_TYPE) {
            _showBufferRanges(ranges);
            _onPlaybackProgression();
            _adjustSeekTarget();
        }
 
        let suppressAppendedEvent = false;
        if (dischargeFragments) {
            if (dischargeFragments.indexOf(appendedBytesInfo) > 0) {
                suppressAppendedEvent = true;
            }
            dischargeFragments = null;
        }
 
        if (appendedBytesInfo && !suppressAppendedEvent) {
            _triggerEvent(Events.BYTES_APPENDED_END_FRAGMENT, {
                startTime: appendedBytesInfo.start,
                index: appendedBytesInfo.index,
                bufferedRanges: ranges,
                segmentType: appendedBytesInfo.segmentType,
                mediaType: type,
                representationId: appendedBytesInfo.representation.id
            });
        }
    }
 
    /**
     * In some cases the segment we requested might start at a different time than we initially aimed for. segments timeline/template tolerance.
     * We might need to do an internal seek if there is drift.
     * @private
     */
    function _adjustSeekTarget() {
        if (isNaN(seekTarget) || isPrebuffering) {
            return;
        }
        // Check buffered data only for audio and video
        if (type !== Constants.AUDIO && type !== Constants.VIDEO) {
            seekTarget = NaN;
            return;
        }
 
        // Check if current buffered range already contains seek target (and current video element time)
        const currentTime = playbackController.getTime();
        const rangeAtCurrenTime = getRangeAt(currentTime, 0);
        const rangeAtSeekTarget = getRangeAt(seekTarget, 0);
        if (rangeAtCurrenTime && rangeAtSeekTarget && rangeAtCurrenTime.start === rangeAtSeekTarget.start) {
            seekTarget = NaN;
            return;
        }
 
        // Get buffered range corresponding to the seek target
        const segmentDuration = representationController.getCurrentRepresentation().segmentDuration;
        const range = getRangeAt(seekTarget, segmentDuration);
        if (!range) {
            return;
        }
 
        if (settings.get().streaming.buffer.enableSeekDecorrelationFix && Math.abs(currentTime - seekTarget) > segmentDuration) {
            // If current video model time is decorrelated from seek target (and appended buffer) then seek video element
            // (in case of live streams on some browsers/devices for which we can't set video element time at unavalaible range)
 
            // Check if appended segment is not anterior from seek target (segments timeline/template tolerance)
            if (seekTarget <= range.end) {
                // Seek video element to seek target or range start if appended buffer starts after seek target (segments timeline/template tolerance)
                playbackController.seek(Math.max(seekTarget, range.start), false, true);
            }
        } else if (currentTime < range.start) {
            // If appended buffer starts after seek target (segments timeline/template tolerance) then seek to range start
            playbackController.seek(range.start, false, true);
        }
    }
 
    function _handleQuotaExceededError() {
        isQuotaExceeded = true;
        criticalBufferLevel = getTotalBufferedTime() * 0.8;
        logger.warn('Quota exceeded, Critical Buffer: ' + criticalBufferLevel);
 
        if (criticalBufferLevel > 0) {
            // recalculate buffer lengths according to criticalBufferLevel
            const bufferToKeep = Math.max(0.2 * criticalBufferLevel, 1);
            const bufferAhead = criticalBufferLevel - bufferToKeep;
            const bufferTimeAtTopQuality = Math.min(settings.get().streaming.buffer.bufferTimeAtTopQuality, bufferAhead * 0.9);
            const bufferTimeAtTopQualityLongForm = Math.min(settings.get().streaming.buffer.bufferTimeAtTopQualityLongForm, bufferAhead * 0.9);
            const s = {
                streaming: {
                    buffer: {
                        bufferToKeep: parseFloat(bufferToKeep.toFixed(5)),
                        bufferTimeAtTopQuality: parseFloat(bufferTimeAtTopQuality.toFixed(5)),
                        bufferTimeAtTopQualityLongForm: parseFloat(bufferTimeAtTopQualityLongForm.toFixed(5))
                    }
                }
            };
            settings.update(s);
        }
    }
 
    function prepareForPlaybackSeek() {
        if (isBufferingCompleted) {
            setIsBufferingCompleted(false);
        }
 
        // Abort the current request and empty all possible segments to be appended
        return sourceBufferSink.abort();
    }
 
    function prepareForForceReplacementQualitySwitch(newRepresentation, oldRepresentation) {
        return new Promise((resolve) => {
            const promises = [];
            promises.push(sourceBufferSink.abort())
            promises.push(updateAppendWindow())
            promises.push(pruneAllSafely())
            promises.push(updateBufferTimestampOffset(newRepresentation))
            promises.push(_changeCodec(newRepresentation, oldRepresentation))
 
            Promise.allSettled(promises)
                .then(() => {
                    setIsBufferingCompleted(false);
                    resolve();
                })
 
        });
    }
 
    function prepareForAbandonQualitySwitch(newRepresentation, oldRepresentation) {
        return _defaultQualitySwitchPreparation(newRepresentation, oldRepresentation);
    }
 
    function prepareForFastQualitySwitch(newRepresentation, oldRepresentation) {
        return _defaultQualitySwitchPreparation(newRepresentation, oldRepresentation);
    }
 
    function prepareForDefaultQualitySwitch(newRepresentation, oldRepresentation) {
        return _defaultQualitySwitchPreparation(newRepresentation, oldRepresentation);
    }
 
    function _defaultQualitySwitchPreparation(newRepresentation, oldRepresentation) {
        const promises = [];
        promises.push(updateBufferTimestampOffset(newRepresentation));
        promises.push(abort());
        promises.push(_changeCodec(newRepresentation, oldRepresentation));
 
        return Promise.allSettled(promises);
    }
 
    function prepareForReplacementTrackSwitch(newRepresentation, oldRepresentation) {
        return new Promise((resolve) => {
            const promises = [];
            promises.push(sourceBufferSink.abort());
            promises.push(updateAppendWindow());
            promises.push(_changeCodec(newRepresentation, oldRepresentation));
            promises.push(pruneAllSafely());
            promises.push(updateBufferTimestampOffset(newRepresentation));
 
            Promise.allSettled(promises)
                .then(() => {
                    setIsBufferingCompleted(false);
                    resolve();
                })
        })
    }
 
    function prepareForNonReplacementTrackSwitch(newRepresentation, oldRepresentation) {
        return new Promise((resolve) => {
            const promises = [];
 
            promises.push(updateAppendWindow());
            promises.push(_changeCodec(newRepresentation, oldRepresentation))
 
            Promise.allSettled(promises)
                .then(() => {
                    resolve();
                })
        });
    }
 
    function _changeCodec(newRepresentation, oldRepresentation) {
 
        if (!newRepresentation || !oldRepresentation) {
            logger.warn(`BufferController._changeCodec() is missing the information about the Representations. Doing nothing`);
            return Promise.resolve();
        }
 
        // we dont need change type for the codec change if we have the same mime type and codec family
        if (newRepresentation && oldRepresentation && newRepresentation.mimeType === oldRepresentation.mimeType && newRepresentation.codecFamily === oldRepresentation.codecFamily) {
            logger.debug(`Switching to new codec ${newRepresentation.codecs} without changeType as previous codec ${oldRepresentation.codecs} is compatible.`);
            return Promise.resolve();
        }
 
        // change type should not be used or is not supported
        if (!settings.get().streaming.buffer.useChangeType || !capabilities.supportsChangeType()) {
            logger.debug(`changeType() not available`);
            return Promise.resolve()
        }
 
        logger.debug(`Using changeType() to switch from codec ${oldRepresentation.codecs} to ${newRepresentation.codecs}`);
 
        // SourceBufferSink's changeType will be invoked with the AbrRepresentation, ie.
        // representation from the manifest. However, MSE SourceBuffer doesn't understand
        // enhancement codecs. In the case an enhancement representation is selected, resolve
        // the dependent (base) representation before passing the codecs to MSE's changeType
        const representation = newRepresentation.dependentRepresentation ?
            newRepresentation.dependentRepresentation : newRepresentation;
        return sourceBufferSink.changeType(representation);
    }
 
    function pruneAllSafely() {
        return new Promise((resolve, reject) => {
            let ranges = getAllRangesWithSafetyFactor();
 
            if (!ranges || ranges.length === 0) {
                _onPlaybackProgression();
                resolve();
                return;
            }
 
            clearBuffers(ranges)
                .then(() => {
                    resolve();
                })
                .catch((e) => {
                    reject(e);
                });
        });
    }
 
    function getAllRangesWithSafetyFactor(seekTime) {
        const clearRanges = [];
        const ranges = sourceBufferSink.getAllBufferRanges();
 
        // no valid ranges
        if (!ranges || ranges.length === 0) {
            return clearRanges;
        }
 
        // if no target time is provided we clear everything
        if ((!seekTime && seekTime !== 0) || isNaN(seekTime)) {
            clearRanges.push({
                start: ranges.start(0),
                end: ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD
            });
        }
 
        // otherwise we need to calculate the correct pruning range
        else {
            const behindPruningRange = _getRangeBehindForPruning(seekTime, ranges);
            const aheadPruningRange = _getRangeAheadForPruning(seekTime, ranges);
 
            if (behindPruningRange) {
                clearRanges.push(behindPruningRange);
            }
 
            if (aheadPruningRange) {
                clearRanges.push(aheadPruningRange);
            }
        }
 
        return clearRanges;
    }
 
    function _getRangeBehindForPruning(targetTime, ranges) {
        const bufferToKeepBehind = settings.get().streaming.buffer.bufferToKeep;
        const startOfBuffer = ranges.start(0);
 
        // if we do a seek ahead of the current play position we do need to prune behind the new play position
        const behindDiff = targetTime - startOfBuffer;
        if (behindDiff > bufferToKeepBehind) {
 
            let rangeEnd = Math.max(0, targetTime - bufferToKeepBehind);
            // Ensure we keep full range of current fragment
            const currentTimeRequest = fragmentModel.getRequests({
                state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
                time: targetTime,
                threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
            })[0];
 
            if (currentTimeRequest) {
                rangeEnd = Math.min(currentTimeRequest.startTime, rangeEnd);
            }
            if (rangeEnd > 0) {
                return {
                    start: startOfBuffer,
                    end: rangeEnd
                };
            }
        }
 
        return null;
    }
 
    function _getRangeAheadForPruning(targetTime, ranges) {
        // if we do a seek behind the current play position we do need to prune ahead of the new play position
        // we keep everything that is within bufferToKeepAhead but only if the buffer is continuous.
        // Otherwise we have gaps once the seek is done which might trigger an unintentional gap jump
        const endOfBuffer = ranges.end(ranges.length - 1) + BUFFER_END_THRESHOLD;
        const continuousBufferTime = getContinuousBufferTimeForTargetTime(targetTime);
 
        // This is the maximum range we keep ahead
        const isLongFormContent = streamInfo.manifestInfo.duration >= settings.get().streaming.buffer.longFormContentDurationThreshold;
        const bufferToKeepAhead = isLongFormContent ? settings.get().streaming.buffer.bufferTimeAtTopQualityLongForm : settings.get().streaming.buffer.bufferTimeAtTopQuality;
 
        // Define the start time from which we will prune. If there is no continuous range from the targettime we start immediately at the target time
        // Otherwise we set the start point to the end of the continuous range taking the maximum buffer to keep ahead into account
        let rangeStart = !isNaN(continuousBufferTime) ? Math.min(continuousBufferTime, targetTime + bufferToKeepAhead) : targetTime;
 
        // Check if we are done buffering, no need to prune then
        if (rangeStart >= ranges.end(ranges.length - 1)) {
            return null
        }
 
        // Ensure we keep full range of current fragment
        const currentTimeRequest = fragmentModel.getRequests({
            state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
            time: targetTime,
            threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
        })[0];
 
        if (currentTimeRequest) {
            rangeStart = Math.max(currentTimeRequest.startTime + currentTimeRequest.duration, rangeStart);
        }
 
        // Never remove the contiguous range of targetTime in order to avoid flushes & reenqueues when the user doesn't want it
        const avoidCurrentTimeRangePruning = settings.get().streaming.buffer.avoidCurrentTimeRangePruning;
        if (avoidCurrentTimeRangePruning) {
            for (let i = 0; i < ranges.length; i++) {
                if (ranges.start(i) <= targetTime && targetTime <= ranges.end(i)
                    && ranges.start(i) <= rangeStart && rangeStart <= ranges.end(i)) {
                    let oldRangeStart = rangeStart;
                    if (i + 1 < ranges.length) {
                        rangeStart = ranges.start(i + 1);
                    } else {
                        rangeStart = ranges.end(i) + 1;
                    }
                    logger.debug('Buffered range [' + ranges.start(i) + ', ' + ranges.end(i) + '] overlaps with targetTime ' + targetTime + ' and range to be pruned [' + oldRangeStart + ', ' + endOfBuffer + '], using [' + rangeStart + ', ' + endOfBuffer + '] instead' + ((rangeStart < endOfBuffer) ? '' : ' (no actual pruning)'));
                    break;
                }
            }
        }
 
        if (rangeStart < ranges.end(ranges.length - 1)) {
            return {
                start: rangeStart,
                end: endOfBuffer
            };
        }
        return null;
    }
 
 
    function _onPlaybackProgression() {
        if (!replacingBuffer || (type === Constants.TEXT && textController.isTextEnabled())) {
            _updateBufferLevel();
        }
    }
 
    function _onPlaybackStalled() {
        checkIfSufficientBuffer();
    }
 
    function _onPlaybackPlaying() {
        checkIfSufficientBuffer();
        seekTarget = NaN;
    }
 
    function hasBufferAtTime(time) {
        try {
            const ranges = sourceBufferSink.getAllBufferRanges();
 
            if (!ranges || ranges.length === 0) {
                return false;
            }
 
            let i = 0;
 
            while (i < ranges.length) {
                const start = ranges.start(i);
                const end = ranges.end(i);
 
                if (time >= start && time <= end) {
                    return true;
                }
 
                i += 1;
            }
 
            return false
 
        } catch (e) {
            logger.error(e);
            return false;
        }
    }
 
    function getRangeAt(time, tolerance) {
        Iif (!sourceBufferSink) {
            return null;
        }
        const ranges = sourceBufferSink.getAllBufferRanges();
        let start = 0;
        let end = 0;
        let firstStart = null;
        let lastEnd = null;
        let gap = 0;
        let len,
            i;
 
        const toler = !isNaN(tolerance) ? tolerance : 0.15;
 
        if (ranges !== null && ranges !== undefined) {
            for (i = 0, len = ranges.length; i < len; i++) {
                start = ranges.start(i);
                end = ranges.end(i);
                if (firstStart === null) {
                    gap = Math.abs(start - time);
                    if (time >= start && time < end) {
                        // start the range
                        firstStart = start;
                        lastEnd = end;
                    } else if (gap <= toler) {
                        // start the range even though the buffer does not contain time 0
                        firstStart = start;
                        lastEnd = end;
                    }
                } else {
                    gap = start - lastEnd;
                    if (gap <= toler) {
                        // the discontinuity is smaller than the tolerance, combine the ranges
                        lastEnd = end;
                    } else E{
                        break;
                    }
                }
            }
 
            if (firstStart !== null) {
                return {
                    start: firstStart,
                    end: lastEnd
                };
            }
        }
 
        return null;
    }
 
    function getBufferLength(time, tolerance) {
        let range,
            length;
 
        // Consider gap/discontinuity limit as tolerance
        if (settings.get().streaming.gaps.jumpGaps) {
            tolerance = settings.get().streaming.gaps.smallGapLimit;
        }
 
        range = getRangeAt(time, tolerance);
 
        if (range === null) {
            length = 0;
        } else {
            length = range.end - time;
        }
 
        return length;
    }
 
    function _updateBufferLevel() {
        if (playbackController) {
            let referenceTime = playbackController.getTime() || 0;
            // In case we are prebuffering we dont have a current time yet
            if (isPrebuffering) {
                referenceTime = !isNaN(seekTarget) ? seekTarget : 0;
            }
            const tolerance = settings.get().streaming.gaps.jumpGaps && !isNaN(settings.get().streaming.gaps.smallGapLimit) ? settings.get().streaming.gaps.smallGapLimit : NaN;
            bufferLevel = Math.max(getBufferLength(referenceTime, tolerance), 0);
            _triggerEvent(Events.BUFFER_LEVEL_UPDATED, { mediaType: type, bufferLevel: bufferLevel });
            checkIfSufficientBuffer();
        }
    }
 
    function _checkIfBufferingCompleted() {
        const isLastIdxAppended = maxAppendedIndex >= maximumIndex - 1; // Handles 0 and non 0 based request index
        // To avoid rounding error when comparing, the stream time and buffer level only must be within 5 decimal places
        const periodBuffered = playbackController.getTimeToStreamEnd(streamInfo) - bufferLevel < 0.00001;
        if ((isLastIdxAppended || periodBuffered) && !isBufferingCompleted) {
            setIsBufferingCompleted(true);
            logger.debug(`checkIfBufferingCompleted trigger BUFFERING_COMPLETED for stream id ${streamInfo.id} and type ${type}`);
        }
    }
 
    function checkIfSufficientBuffer() {
        // No need to check buffer if type is not audio or video (for example if several errors occur during text parsing, so that the buffer cannot be filled, no error must occur on video playback)
        if (type !== Constants.AUDIO && type !== Constants.VIDEO) {
            return;
        }
 
        //Set stall threshold based on player mode
        const stallThreshold = playbackController.getLowLatencyModeEnabled() ? settings.get().streaming.buffer.lowLatencyStallThreshold : settings.get().streaming.buffer.stallThreshold;
 
        if ((bufferLevel <= stallThreshold) && !isBufferingCompleted) {
            _notifyBufferStateChanged(MetricsConstants.BUFFER_EMPTY);
        } else if (isBufferingCompleted || bufferLevel > stallThreshold) {
            _notifyBufferStateChanged(MetricsConstants.BUFFER_LOADED);
        }
    }
 
    function _notifyBufferStateChanged(state) {
        if (bufferState === state ||
            (state === MetricsConstants.BUFFER_EMPTY && playbackController.getTime() === 0) || // Don't trigger BUFFER_EMPTY if it's initial loading
            (type === Constants.TEXT && !textController.isTextEnabled())) {
            return;
        }
 
        bufferState = state;
 
        _triggerEvent(Events.BUFFER_LEVEL_STATE_CHANGED, { state: state });
        _triggerEvent(state === MetricsConstants.BUFFER_LOADED ? Events.BUFFER_LOADED : Events.BUFFER_EMPTY);
        logger.debug(state === MetricsConstants.BUFFER_LOADED ? 'Got enough buffer to start' : 'Waiting for more buffer before starting playback');
    }
 
    /* prune buffer on our own in background to avoid browsers pruning buffer silently */
    function pruneBuffer() {
        if (!sourceBufferSink || type === Constants.TEXT) {
            return;
        }
 
        if (!isBufferingCompleted) {
            clearBuffers(getClearRanges());
        }
    }
 
    function getClearRanges() {
        const clearRanges = [];
        const ranges = sourceBufferSink.getAllBufferRanges();
        if (!ranges || ranges.length === 0) {
            return clearRanges;
        }
 
        const currentTime = playbackController.getTime();
        let startRangeToKeep = Math.max(0, currentTime - settings.get().streaming.buffer.bufferToKeep);
 
        const currentTimeRequest = fragmentModel.getRequests({
            state: FragmentModel.FRAGMENT_MODEL_EXECUTED,
            time: currentTime,
            threshold: BUFFER_RANGE_CALCULATION_THRESHOLD
        })[0];
 
        // Ensure we keep full range of current fragment
        if (currentTimeRequest) {
            startRangeToKeep = Math.min(currentTimeRequest.startTime, startRangeToKeep);
        } else if (currentTime === 0 && playbackController.getIsDynamic()) {
            // Don't prune before the live stream starts, it messes with low latency
            return [];
        }
 
        if (ranges.start(0) <= startRangeToKeep) {
            const behindRange = {
                start: 0,
                end: startRangeToKeep
            };
            for (let i = 0; i < ranges.length && ranges.end(i) <= startRangeToKeep; i++) {
                behindRange.end = ranges.end(i);
            }
            if (behindRange.start < behindRange.end) {
                clearRanges.push(behindRange);
            }
        }
 
        return clearRanges;
    }
 
    function clearBuffers(ranges) {
        return new Promise((resolve, reject) => {
            if (!ranges || !sourceBufferSink || ranges.length === 0) {
                _updateBufferLevel();
                resolve();
                return;
            }
 
            const promises = [];
            ranges.forEach((range) => {
                promises.push(_addClearRangeWithPromise(range));
            });
 
 
            if (!isPruningInProgress) {
                clearNextRange();
            }
 
            Promise.all(promises)
                .then(() => {
                    resolve();
                })
                .catch((e) => {
                    reject(e);
                });
        });
    }
 
    function _addClearRangeWithPromise(range) {
        return new Promise((resolve, reject) => {
            range.resolve = resolve;
            range.reject = reject;
            pendingPruningRanges.push(range);
        });
    }
 
    function clearNextRange() {
        try {
            // If there's nothing to prune reset state
            if (pendingPruningRanges.length === 0 || !sourceBufferSink) {
                logger.debug('Nothing to prune, halt pruning');
                pendingPruningRanges = [];
                isPruningInProgress = false;
                return;
            }
 
            const sourceBuffer = sourceBufferSink.getBuffer();
            // If there's nothing buffered any pruning is invalid, so reset our state
            if (!sourceBuffer || !sourceBuffer.buffered || sourceBuffer.buffered.length === 0) {
                logger.debug('SourceBuffer is empty (or does not exist), halt pruning');
                pendingPruningRanges = [];
                isPruningInProgress = false;
                return;
            }
 
            const range = pendingPruningRanges.shift();
            logger.debug(`${type}: Removing buffer from: ${range.start} to ${range.end}`);
            isPruningInProgress = true;
 
            // If removing buffer ahead current playback position, update maxAppendedIndex
            const currentTime = playbackController.getTime();
            if (currentTime < range.end) {
                setIsBufferingCompleted(false);
            }
 
            sourceBufferSink.remove(range)
                .then((e) => {
                    _onRemoved(e);
                })
                .catch((e) => {
                    _onRemoved(e);
                });
        } catch (e) {
            isPruningInProgress = false;
        }
    }
 
    function _onRemoved(e) {
        logger.debug('onRemoved buffer from:', e.from, 'to', e.to);
 
        if (!sourceBufferSink) {
            return;
        }
 
        const ranges = sourceBufferSink.getAllBufferRanges();
        _showBufferRanges(ranges);
 
        if (pendingPruningRanges.length === 0) {
            isPruningInProgress = false;
            _updateBufferLevel();
        }
 
        if (e.unintended) {
            logger.warn('Detected unintended removal from:', e.from, 'to', e.to, 'setting streamprocessor time to', e.from);
            _triggerEvent(Events.SEEK_TARGET, { time: e.from });
        }
 
        if (isPruningInProgress) {
            clearNextRange();
        } else {
            if (!replacingBuffer) {
                _updateBufferLevel();
            } else {
                replacingBuffer = false;
            }
            _triggerEvent(Events.BUFFER_CLEARED, {
                from: e.from,
                to: e.to,
                unintended: e.unintended,
                hasEnoughSpaceToAppend: hasEnoughSpaceToAppend(),
                quotaExceeded: isQuotaExceeded
            });
        }
    }
 
    function updateBufferTimestampOffset(voRepresentation) {
        return new Promise((resolve) => {
            if (!voRepresentation || voRepresentation.mseTimeOffset === undefined || !sourceBufferSink || !sourceBufferSink.updateTimestampOffset) {
                resolve();
                return;
            }
            // Each track can have its own @presentationTimeOffset, so we should set the offset
            // if it has changed after switching the quality or updating an MPD
            sourceBufferSink.updateTimestampOffset(voRepresentation.mseTimeOffset)
                .then(() => {
                    resolve();
                })
                .catch(() => {
                    resolve();
                });
        });
 
    }
 
    function abort() {
        if (sourceBufferSink) {
            return sourceBufferSink.abort();
        }
        return Promise.resolve();
    }
 
    function updateAppendWindow() {
        if (sourceBufferSink && !isBufferingCompleted) {
            return sourceBufferSink.updateAppendWindow(streamInfo);
        }
        return Promise.resolve();
    }
 
    function segmentRequestingCompleted(segmentIndex) {
        if (!isNaN(segmentIndex)) {
            maximumIndex = segmentIndex;
            _checkIfBufferingCompleted();
        }
    }
 
    function _onWallclockTimeUpdated() {
        wallclockTicked++;
        const secondsElapsed = (wallclockTicked * (settings.get().streaming.wallclockTimeUpdateInterval / 1000));
        if ((secondsElapsed >= settings.get().streaming.buffer.bufferPruningInterval)) {
            wallclockTicked = 0;
            pruneBuffer();
        }
    }
 
    function _onPlaybackRateChanged() {
        checkIfSufficientBuffer();
    }
 
    function getBuffer() {
        return sourceBufferSink;
    }
 
    function getBufferLevel() {
        return bufferLevel;
    }
 
    function getMediaSource() {
        return mediaSource;
    }
 
    function getIsBufferingCompleted() {
        return isBufferingCompleted;
    }
 
    function setIsBufferingCompleted(value) {
        isBufferingCompleted = value;
 
        if (isBufferingCompleted) {
            _triggerEvent(Events.BUFFERING_COMPLETED);
        } else {
            maximumIndex = Number.POSITIVE_INFINITY;
        }
    }
 
    function getIsPruningInProgress() {
        return isPruningInProgress;
    }
 
    function getTotalBufferedTime() {
        try {
            const ranges = sourceBufferSink.getAllBufferRanges();
            let totalBufferedTime = 0;
            let ln,
                i;
 
            if (!ranges) {
                return totalBufferedTime;
            }
 
            for (i = 0, ln = ranges.length; i < ln; i++) {
                totalBufferedTime += ranges.end(i) - ranges.start(i);
            }
 
            return totalBufferedTime;
        } catch (e) {
            return 0;
        }
    }
 
    /**
     * This function returns the maximum time for which the buffer is continuous starting from a target time.
     * As soon as there is a gap we return the time before the gap starts
     * @param {number} targetTime
     */
    function getContinuousBufferTimeForTargetTime(targetTime) {
        try {
            let adjustedTime = targetTime;
            const ranges = sourceBufferSink.getAllBufferRanges();
 
            if (!ranges || ranges.length === 0) {
                return NaN;
            }
 
            let i = 0;
 
            while (adjustedTime === targetTime && i < ranges.length) {
                const start = ranges.start(i);
                const end = ranges.end(i);
 
                if (adjustedTime >= start && adjustedTime <= end) {
                    adjustedTime = end;
                }
 
                i += 1;
            }
 
            return adjustedTime === targetTime ? NaN : adjustedTime;
 
        } catch (e) {
            return NaN
        }
    }
 
    function hasEnoughSpaceToAppend() {
        const totalBufferedTime = getTotalBufferedTime();
        return (isNaN(totalBufferedTime) || totalBufferedTime < criticalBufferLevel);
    }
 
    function setSeekTarget(value) {
        seekTarget = value;
    }
 
    function _triggerEvent(eventType, data) {
        let payload = data || {};
        eventBus.trigger(eventType, payload, { streamId: streamInfo.id, mediaType: type });
    }
 
    function resetInitialSettings(errored, keepBuffers) {
        criticalBufferLevel = Number.POSITIVE_INFINITY;
        bufferState = undefined;
        maximumIndex = Number.POSITIVE_INFINITY;
        maxAppendedIndex = 0;
        appendedBytesInfo = null;
        isBufferingCompleted = false;
        isPruningInProgress = false;
        isQuotaExceeded = false;
        bufferLevel = 0;
        wallclockTicked = 0;
        pendingPruningRanges = [];
        seekTarget = NaN;
        isPrebuffering = false;
 
        if (sourceBufferSink) {
            let tmpSourceBufferSinkToReset = sourceBufferSink;
            sourceBufferSink = null;
            if (!errored) {
                if (!keepBuffers) {
                    tmpSourceBufferSinkToReset.abort()
                        .then(() => {
                            tmpSourceBufferSinkToReset.reset(keepBuffers);
                            tmpSourceBufferSinkToReset = null;
                        });
                } else E{
                    tmpSourceBufferSinkToReset.removeEventListeners();
                }
            }
        }
 
        replacingBuffer = false;
    }
 
    function reset(errored, keepBuffers) {
        eventBus.off(Events.INIT_FRAGMENT_LOADED, _onInitFragmentLoaded, this);
        eventBus.off(Events.MEDIA_FRAGMENT_LOADED, _onMediaFragmentLoaded, this);
        eventBus.off(Events.WALLCLOCK_TIME_UPDATED, _onWallclockTimeUpdated, this);
 
        eventBus.off(MediaPlayerEvents.PLAYBACK_PLAYING, _onPlaybackPlaying, this);
        eventBus.off(MediaPlayerEvents.PLAYBACK_PROGRESS, _onPlaybackProgression, this);
        eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackProgression, this);
        eventBus.off(MediaPlayerEvents.PLAYBACK_RATE_CHANGED, _onPlaybackRateChanged, this);
        eventBus.off(MediaPlayerEvents.PLAYBACK_STALLED, _onPlaybackStalled, this);
 
 
        resetInitialSettings(errored, keepBuffers);
    }
 
    instance = {
        appendInitSegmentFromCache,
        clearBuffers,
        createBufferSink,
        dischargePreBuffer,
        getAllRangesWithSafetyFactor,
        getBuffer,
        getBufferControllerType,
        getBufferLevel,
        getContinuousBufferTimeForTargetTime,
        getIsBufferingCompleted,
        getIsPruningInProgress,
        getMediaSource,
        getRangeAt,
        getStreamId,
        getType,
        hasBufferAtTime,
        initialize,
        prepareForAbandonQualitySwitch,
        prepareForDefaultQualitySwitch,
        prepareForFastQualitySwitch,
        prepareForForceReplacementQualitySwitch,
        prepareForNonReplacementTrackSwitch,
        prepareForPlaybackSeek,
        prepareForReplacementTrackSwitch,
        pruneAllSafely,
        pruneBuffer,
        reset,
        segmentRequestingCompleted,
        setIsBufferingCompleted,
        setMediaSource,
        setSeekTarget,
        updateAppendWindow,
        updateBufferTimestampOffset,
    };
 
    setup();
    return instance;
}
 
BufferController.__dashjs_factory_name = BUFFER_CONTROLLER_TYPE;
export default FactoryMaker.getClassFactory(BufferController);