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

54.92% Statements 385/701
39.28% Branches 176/448
44.44% Functions 52/117
54.4% Lines 377/693

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 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772                                                                                                      1x 1x       1x 1x                         1x 1x 1x 1x   1x       41x   40x 40x 40x   40x 40x               40x   40x 40x     40x   40x   40x     40x   40x   40x 40x     40x 40x         40x       40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x     40x 40x     40x 40x 40x 40x 40x 40x   40x       23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x   23x 23x     23x 23x 23x 23x 23x 23x   23x       68x 4x         2x 1x                   3x 1x 1x                 2x 1x 1x               17x                               17x 17x   17x 1x     16x                   16x 1x     16x 16x 16x 16x 16x     16x   15x 15x 15x             15x   15x             1x 1x 1x                   16x       16x 15x                                             15x 15x 15x   1x                   15x     15x     15x 15x           15x 15x       15x 15x 15x       15x 9x 9x       15x   15x 15x     15x 15x                                                 15x     15x         15x 15x 15x   15x   15x 15x                     15x 15x       15x 15x         15x 15x 15x 15x   15x                 15x 15x   15x     15x     15x 15x                                                                                                         15x 15x 15x 15x     15x 15x 15x                                                                                 15x   15x 15x                                                                                                                                                                                                                                                                                                                                                                               16x       16x   16x 15x 15x   15x 15x       1x             15x 15x 15x 15x 15x 15x 15x   15x 15x                                                                                                                                                                                                                                                                                       15x         15x 15x 15x                                               15x 15x                         23x 15x 15x                       1x 1x 1x 1x   1x                                       1x               39x                                                                                                                                                                                                                                                                       15x 15x 9x   6x     15x           9x 9x   9x   9x 9x   9x                 9x 9x 5x   5x       9x 9x     9x         6x 6x 6x     6x                 6x 6x 3x   3x       6x                   15x 15x 2x   13x 13x 13x   13x                                                     13x 13x 13x 13x                 1x         1x 1x 1x     1x   1x           1x                       9x 9x     9x       9x                                             2x 1x       1x 1x     1x   1x   1x 1x             1x 1x 1x     1x 1x                 1x               1x                       23x   23x     23x                                                                                                                                                                     6x           6x   1x 1x   1x 1x   1x 1x 1x   1x 1x   1x 1x   1x 1x       6x         6x   6x       6x       6x 6x 6x   6x 6x                                     16x                       18x 1x 1x     17x                   43x       43x     43x 25x   43x 41x   43x 40x   43x     43x     43x 40x   43x 40x   43x 40x   43x 40x   43x 40x   43x 40x   43x 40x   43x     43x 15x   43x 25x   43x 25x   43x     43x     43x 40x   43x 40x   43x 15x   43x     43x 2x                       24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x               24x   23x   23x   23x 15x 15x     23x   23x 23x 23x 23x 23x 23x 23x 23x   23x 15x 15x   23x 23x 23x 23x 23x         23x 23x 23x                             2x 1x         19x     1x                                                 1x   1x     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 Stream from '../Stream.js';
import ManifestUpdater from '../ManifestUpdater.js';
import EventBus from '../../core/EventBus.js';
import Events from '../../core/events/Events.js';
import FactoryMaker from '../../core/FactoryMaker.js';
import {PlayList, PlayListTrace} from '../vo/metrics/PlayList.js';
import Debug from '../../core/Debug.js';
import InitCache from '../utils/InitCache.js';
import MediaPlayerEvents from '../MediaPlayerEvents.js';
import TimeSyncController from './TimeSyncController.js';
import MediaSourceController from './MediaSourceController.js';
import DashJSError from '../vo/DashJSError.js';
import Errors from '../../core/errors/Errors.js';
import EventController from './EventController.js';
import ConformanceViolationConstants from '../constants/ConformanceViolationConstants.js';
import ExtUrlQueryInfoController from './ExtUrlQueryInfoController.js';
import ProtectionEvents from '../protection/ProtectionEvents.js';
import ProtectionErrors from '../protection/errors/ProtectionErrors.js';
 
const PLAYBACK_ENDED_TIMER_INTERVAL = 200;
const DVR_WAITING_OFFSET = 2;
 
function StreamController() {
 
    const context = this.context;
    const eventBus = EventBus(context).getInstance();
 
    let instance, logger, capabilities, capabilitiesFilter, manifestUpdater, manifestLoader, manifestModel, adapter,
        dashMetrics, mediaSourceController, timeSyncController, contentSteeringController, baseURLController,
        segmentBaseController, uriFragmentModel, abrController, throughputController, mediaController, eventController,
        initCache, errHandler, timelineConverter, streams, activeStream, protectionController, textController,
        protectionData, extUrlQueryInfoController,
        autoPlay, isStreamSwitchingInProgress, hasMediaError, hasInitialisationError, mediaSource, videoModel,
        playbackController, serviceDescriptionController, mediaPlayerModel, customParametersModel, isPaused,
        initialPlayback, initialSteeringRequest, playbackEndedTimerInterval, preloadingStreams, settings,
        firstLicenseIsFetched, waitForPlaybackStartTimeout, providedStartTime, errorInformation;
 
    function setup() {
        logger = Debug(context).getInstance().getLogger(instance);
        timeSyncController = TimeSyncController(context).getInstance();
        mediaSourceController = MediaSourceController(context).getInstance();
        initCache = InitCache(context).getInstance();
 
        resetInitialSettings();
    }
 
    function initialize(autoPl, protData) {
        _checkConfig();
 
        autoPlay = autoPl;
        protectionData = protData;
        timelineConverter.initialize();
 
        manifestUpdater = ManifestUpdater(context).create();
        manifestUpdater.setConfig({
            manifestModel,
            adapter,
            manifestLoader,
            errHandler,
            settings,
            contentSteeringController
        });
        manifestUpdater.initialize();
 
        eventController = EventController(context).getInstance();
        eventController.setConfig({
            manifestUpdater: manifestUpdater, playbackController: playbackController, settings
        });
        eventController.start();
 
        extUrlQueryInfoController = ExtUrlQueryInfoController(context).getInstance();
 
        timeSyncController.setConfig({
            dashMetrics, baseURLController, errHandler, settings
        });
        timeSyncController.initialize();
 
        mediaSourceController.setConfig({ settings });
 
        if (protectionController) {
            eventBus.trigger(Events.PROTECTION_CREATED, {
                controller: protectionController
            });
            protectionController.setMediaElement(videoModel.getElement());
            Iif (protectionData) {
                protectionController.setProtectionData(protectionData);
            }
        }
 
        registerEvents();
    }
 
    function registerEvents() {
        eventBus.on(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_ERROR, _onPlaybackError, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_PAUSED, _onPlaybackPaused, instance);
        eventBus.on(MediaPlayerEvents.PLAYBACK_ENDED, _onPlaybackEnded, instance);
        eventBus.on(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);
        eventBus.on(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, _onManifestValidityChanged, instance);
        eventBus.on(MediaPlayerEvents.BUFFER_LEVEL_UPDATED, _onBufferLevelUpdated, instance);
        eventBus.on(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED, _onQualityChanged, instance);
        eventBus.on(MediaPlayerEvents.CONTENT_STEERING_REQUEST_COMPLETED, _onSteeringManifestUpdated, instance);
 
 
        if (Events.KEY_SESSION_UPDATED) {
            eventBus.on(Events.KEY_SESSION_UPDATED, _onKeySessionUpdated, instance);
        }
 
        eventBus.on(Events.MANIFEST_UPDATED, _onManifestUpdated, instance);
        eventBus.on(Events.STREAM_BUFFERING_COMPLETED, _onStreamBufferingCompleted, instance);
        eventBus.on(Events.TIME_SYNCHRONIZATION_COMPLETED, _onTimeSyncCompleted, instance);
        eventBus.on(Events.CURRENT_TRACK_CHANGED, _onCurrentTrackChanged, instance);
        eventBus.on(Events.SETTING_UPDATED_LIVE_DELAY, _onLiveDelaySettingUpdated, instance);
        eventBus.on(Events.SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT, _onLiveDelaySettingUpdated, instance);
 
        eventBus.on(ProtectionEvents.INTERNAL_KEY_STATUSES_CHANGED, _onInternalKeyStatusesChanged, instance);
    }
 
    function unRegisterEvents() {
        eventBus.off(MediaPlayerEvents.PLAYBACK_TIME_UPDATED, _onPlaybackTimeUpdated, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_SEEKING, _onPlaybackSeeking, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_ERROR, _onPlaybackError, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_STARTED, _onPlaybackStarted, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_PAUSED, _onPlaybackPaused, instance);
        eventBus.off(MediaPlayerEvents.PLAYBACK_ENDED, _onPlaybackEnded, instance);
        eventBus.off(MediaPlayerEvents.METRIC_ADDED, _onMetricAdded, instance);
        eventBus.off(MediaPlayerEvents.MANIFEST_VALIDITY_CHANGED, _onManifestValidityChanged, instance);
        eventBus.off(MediaPlayerEvents.BUFFER_LEVEL_UPDATED, _onBufferLevelUpdated, instance);
        eventBus.off(MediaPlayerEvents.QUALITY_CHANGE_REQUESTED, _onQualityChanged, instance);
        eventBus.off(MediaPlayerEvents.CONTENT_STEERING_REQUEST_COMPLETED, _onSteeringManifestUpdated, instance);
 
        if (Events.KEY_SESSION_UPDATED) {
            eventBus.off(Events.KEY_SESSION_UPDATED, _onKeySessionUpdated, instance);
        }
 
        eventBus.off(Events.MANIFEST_UPDATED, _onManifestUpdated, instance);
        eventBus.off(Events.STREAM_BUFFERING_COMPLETED, _onStreamBufferingCompleted, instance);
        eventBus.off(Events.TIME_SYNCHRONIZATION_COMPLETED, _onTimeSyncCompleted, instance);
        eventBus.off(Events.CURRENT_TRACK_CHANGED, _onCurrentTrackChanged, instance);
        eventBus.off(Events.SETTING_UPDATED_LIVE_DELAY, _onLiveDelaySettingUpdated, instance);
        eventBus.off(Events.SETTING_UPDATED_LIVE_DELAY_FRAGMENT_COUNT, _onLiveDelaySettingUpdated, instance);
 
        eventBus.off(ProtectionEvents.INTERNAL_KEY_STATUSES_CHANGED, _onInternalKeyStatusesChanged, instance);
    }
 
    function _checkConfig() {
        if (!manifestLoader || !manifestLoader.hasOwnProperty('load') || !timelineConverter || !timelineConverter.hasOwnProperty('initialize') || !timelineConverter.hasOwnProperty('reset') || !timelineConverter.hasOwnProperty('getClientTimeOffset') || !manifestModel || !errHandler || !dashMetrics || !playbackController) {
            throw new Error(Constants.MISSING_CONFIG_ERROR);
        }
    }
 
    function _checkInitialize() {
        if (!manifestUpdater || !manifestUpdater.hasOwnProperty('setManifest')) {
            throw new Error('initialize function has to be called previously');
        }
    }
 
    /**
     * Start the streaming session by loading the target manifest
     * @param {string} url
     * @param {number} startTime
     */
    function load(url, startTime = NaN) {
        _checkConfig();
        providedStartTime = startTime;
        manifestLoader.load(url);
    }
 
    /**
     * Start the streaming session by using the provided manifest object
     * @param {object} manifest
     * @param {number} startTime
     */
    function loadWithManifest(manifest, startTime = NaN) {
        _checkInitialize();
        providedStartTime = startTime;
        manifestUpdater.setManifest(manifest);
    }
 
    /**
     * When the UTC snychronization is completed we can compose the streams
     * @private
     */
    function _onTimeSyncCompleted( /*e*/) {
        _composePeriods();
    }
 
    /**
     *
     * @private
     */
    function _onKeySessionUpdated() {
        firstLicenseIsFetched = true;
    }
 
    /**
     * Setup the stream objects after the stream start and each MPD reload. This function is called after the UTC sync has been done (TIME_SYNCHRONIZATION_COMPLETED)
     * @private
     */
    function _composePeriods() {
        try {
            const streamsInfo = adapter.getStreamsInfo();
 
            if (!activeStream && streamsInfo.length === 0) {
                throw new Error('There are no periods in the MPD');
            }
 
            Iif (activeStream && streamsInfo.length > 0) {
                dashMetrics.updateManifestUpdateInfo({
                    currentTime: playbackController.getTime(),
                    buffered: videoModel.getBufferRange(),
                    presentationStartTime: streamsInfo[0].start,
                    clientTimeOffset: timelineConverter.getClientTimeOffset()
                });
            }
 
            // Filter streams that are outdated and not included in the MPD anymore
            if (streams.length > 0) {
                _filterOutdatedStreams(streamsInfo);
            }
 
            const promises = [];
            for (let i = 0, ln = streamsInfo.length; i < ln; i++) {
                const streamInfo = streamsInfo[i];
                promises.push(_initializeOrUpdateStream(streamInfo));
                dashMetrics.addManifestUpdateStreamInfo(streamInfo);
            }
 
            Promise.all(promises)
                .then(() => {
                    return new Promise((resolve, reject) => {
                        if (!activeStream) {
                            _initializeForFirstStream(streamsInfo, resolve, reject);
                        } else E{
                            resolve();
                        }
                    });
                })
                .then(() => {
                    eventBus.trigger(Events.STREAMS_COMPOSED);
                    // Additional periods might have been added after an MPD update. Check again if we can start prebuffering.
                    _checkIfPrebufferingCanStart();
                })
                .catch((e) => {
                    throw e;
                })
 
        } catch (e) {
            errHandler.error(new DashJSError(Errors.MANIFEST_ERROR_ID_NOSTREAMS_CODE, e.message + ' nostreamscomposed', manifestModel.getValue()));
            hasInitialisationError = true;
            reset();
        }
    }
 
    /**
     * Called for each stream when composition is performed. Either a new instance of Stream is created or the existing one is updated.
     * @param {object} streamInfo
     * @private
     */
    function _initializeOrUpdateStream(streamInfo) {
        let stream = getStreamById(streamInfo.id);
 
        // If the Stream object does not exist we probably loaded the manifest the first time or it was
        // introduced in the updated manifest, so we need to create a new Stream and perform all the initialization operations
        if (!stream) {
            stream = Stream(context).create({
                manifestModel,
                mediaPlayerModel,
                dashMetrics,
                manifestUpdater,
                adapter,
                timelineConverter,
                capabilities,
                capabilitiesFilter,
                errHandler,
                baseURLController,
                segmentBaseController,
                textController,
                abrController,
                playbackController,
                throughputController,
                eventController,
                mediaController,
                protectionController,
                videoModel,
                streamInfo,
                settings
            });
            streams.push(stream);
            stream.initialize();
            return Promise.resolve();
        } else {
            return stream.updateData(streamInfo);
        }
    }
 
    /**
     * Initialize playback for the first period.
     * @param {array} streamsInfo
     * @private
     */
    function _initializeForFirstStream(streamsInfo, resolve, reject) {
        try {
 
            // Add the DVR window so we can calculate the right starting point
            addDVRMetric();
 
            // If the start is in the future we need to wait
            const dvrRange = dashMetrics.getCurrentDVRInfo().range;
            Iif (dvrRange.end < dvrRange.start) {
                _handleStartTimeInFuture(dvrRange, streamsInfo, resolve, reject);
                return;
            }
 
            // Calculate the producer reference time offsets if given
            if (settings.get().streaming.applyProducerReferenceTime) {
                serviceDescriptionController.calculateProducerReferenceTimeOffsets(streamsInfo);
            }
 
            // Apply Service description parameters.
            const manifestInfo = streamsInfo[0].manifestInfo;
            if (settings.get().streaming.applyServiceDescription) {
                serviceDescriptionController.applyServiceDescription(manifestInfo);
            }
 
            // Compute and set the live delay
            if (adapter.getIsDynamic()) {
                const fragmentDuration = _getFragmentDurationForLiveDelayCalculation(streamsInfo, manifestInfo);
                playbackController.computeAndSetLiveDelay(fragmentDuration, manifestInfo);
            }
 
            // Apply content steering
            _applyContentSteeringBeforeStart()
                .then(() => {
                    const manifest = manifestModel.getValue();
                    Iif (manifest) {
                        baseURLController.update(manifest)
                    }
                    _calculateStartTimeAndSwitchStream()
                    resolve();
                })
                .catch((e) => {
                    logger.error(e);
                    _calculateStartTimeAndSwitchStream();
                    resolve();
                })
        } catch (e) {
            reject(e);
        }
    }
 
    function _handleStartTimeInFuture(dvrRange, streamsInfo, resolve, reject) {
        if (waitForPlaybackStartTimeout) {
            clearTimeout(waitForPlaybackStartTimeout);
        }
        const waitingTime = Math.min((((dvrRange.end - dvrRange.start) * -1) + DVR_WAITING_OFFSET) * 1000, 2147483647);
        logger.debug(`Waiting for ${waitingTime} ms before playback can start`);
        eventBus.trigger(Events.AST_IN_FUTURE, { delay: waitingTime });
        waitForPlaybackStartTimeout = setTimeout(() => {
            _initializeForFirstStream(streamsInfo, resolve, reject);
        }, waitingTime);
    }
 
    function _applyContentSteeringBeforeStart() {
        Iif (settings.get().streaming.applyContentSteering && contentSteeringController.shouldQueryBeforeStart()) {
            return contentSteeringController.loadSteeringData();
        }
        return Promise.resolve();
    }
 
    function _calculateStartTimeAndSwitchStream() {
        // Figure out the correct start time and the correct start period
        const startTime = _getInitialStartTime();
        let streamForTime = getStreamForTime(startTime);
        const initialStream = streamForTime !== null ? streamForTime : streams[0];
 
        eventBus.trigger(Events.INITIAL_STREAM_SWITCH, { startTime });
 
        _switchStream(initialStream, null, startTime);
        _startPlaybackEndedTimerInterval();
    }
 
    /**
     * Switch from the current stream (period) to the next stream (period).
     * @param {object} targetStream
     * @param {object} previousStream
     * @param {number} seekTime
     * @private
     */
    function _switchStream(targetStream, previousStream, seekTime) {
        try {
            Iif (isStreamSwitchingInProgress || !targetStream || (previousStream === targetStream && targetStream.getIsActive())) {
                return;
            }
 
            isStreamSwitchingInProgress = true;
            eventBus.trigger(Events.PERIOD_SWITCH_STARTED, {
                fromStreamInfo: previousStream ? previousStream.getStreamInfo() : null,
                toStreamInfo: targetStream.getStreamInfo()
            });
 
            let keepBuffers = false;
            let representationsFromPreviousPeriod = [];
            let sourceBufferSinksFromPreviousPeriod = _getSourceBufferSinksFromPreviousPeriod(previousStream);
            activeStream = targetStream;
 
            Iif (previousStream) {
                keepBuffers = _canSourceBuffersBeKept(targetStream, previousStream);
                representationsFromPreviousPeriod = _getRepresentationsFromPreviousPeriod(previousStream);
                previousStream.deactivate(keepBuffers);
            }
 
            // Determine seek time when switching to new period
            // - seek at given seek time
            // - or seek at period start if upcoming period is not prebuffered
            seekTime = !isNaN(seekTime) ? seekTime : (!keepBuffers && previousStream ? targetStream.getStreamInfo().start : NaN);
            logger.info(`Switch to stream ${targetStream.getId()}. Seektime is ${seekTime}, current playback time is ${playbackController.getTime()}. Seamless period switch is set to ${keepBuffers}`);
 
            preloadingStreams = preloadingStreams.filter((s) => {
                return s.getId() !== activeStream.getId();
            });
            playbackController.initialize(getActiveStreamInfo(), !!previousStream);
 
            // If we have a video element we are not preloading into a virtual buffer
            if (videoModel.getElement()) {
                _openMediaSource({
                    seekTime,
                    keepBuffers,
                    sourceBufferSinksFromPreviousPeriod,
                    streamActivated: false,
                    representationsFromPreviousPeriod
                });
            } else E{
                _activateStream({ seekTime, keepBuffers, sourceBufferSinksFromPreviousPeriod });
            }
        } catch (e) {
            isStreamSwitchingInProgress = false;
        }
    }
 
    /**
     * Setup the Media Source. Open MSE and attach event listeners
     * @private
     * @param inputParameters
     */
    function _openMediaSource(inputParameters) {
        let sourceUrl;
 
        function _onMediaSourceOpen() {
            // Manage situations in which a call to reset happens while MediaSource is being opened
            if (!mediaSource || mediaSource.readyState !== 'open') {
                return;
            }
 
            logger.debug('MediaSource is open!');
            window.URL.revokeObjectURL(sourceUrl);
            mediaSource.removeEventListener('sourceopen', _onMediaSourceOpen);
            mediaSource.removeEventListener('webkitsourceopen', _onMediaSourceOpen);
 
            _setMediaDuration();
            const dvrInfo = dashMetrics.getCurrentDVRInfo();
            mediaSourceController.setSeekable(dvrInfo.range.start, dvrInfo.range.end);
            if (inputParameters.streamActivated) {
                if (!isNaN(inputParameters.seekTime)) {
                    playbackController.seek(inputParameters.seekTime, true, true);
                }
                // Set the media source for all StreamProcessors
                activeStream.setMediaSource(mediaSource)
                    .then(() => {
                        // Start text processing now that we have a video element
                        activeStream.initializeForTextWithMediaSource(mediaSource);
                    })
            } else {
                _activateStream(inputParameters);
            }
        }
 
        function _open() {
            mediaSource.addEventListener('sourceopen', _onMediaSourceOpen, false);
            mediaSource.addEventListener('webkitsourceopen', _onMediaSourceOpen, false);
            sourceUrl = mediaSourceController.attachMediaSource(videoModel);
            logger.debug('MediaSource attached to element.  Waiting on open...');
        }
 
        if (!mediaSource) {
            mediaSource = mediaSourceController.createMediaSource();
            _open();
        } else E{
            if (inputParameters.keepBuffers) {
                _activateStream(inputParameters);
            } else {
                mediaSourceController.detachMediaSource(videoModel);
                _open();
            }
        }
    }
 
    /**
     * Activates a new stream.
     * @param {number} seekTime
     * @param {boolean} keepBuffers
     */
    function _activateStream(inputParameters) {
        const representationsFromPreviousPeriod = inputParameters.representationsFromPreviousPeriod || [];
        activeStream.activate(mediaSource, inputParameters.sourceBufferSinksFromPreviousPeriod, representationsFromPreviousPeriod)
            .then(() => {
 
                // Set the initial time for this stream in the StreamProcessor
                if (!isNaN(inputParameters.seekTime)) {
                    eventBus.trigger(Events.SEEK_TARGET, { time: inputParameters.seekTime }, { streamId: activeStream.getId() });
                    playbackController.seek(inputParameters.seekTime, false, true);
                    activeStream.startScheduleControllers();
                }
 
                isStreamSwitchingInProgress = false;
                eventBus.trigger(Events.PERIOD_SWITCH_COMPLETED, { toStreamInfo: getActiveStreamInfo() });
            });
    }
 
    function _getRepresentationsFromPreviousPeriod(previousStream) {
        const previousStreamProcessors = previousStream ? previousStream.getStreamProcessors() : [];
        return previousStreamProcessors.map((streamProcessor) => {
            return streamProcessor.getRepresentation();
        })
    }
 
    function _getSourceBufferSinksFromPreviousPeriod(previousStream) {
        const sourceBufferSinkMap = new Map();
 
        if (!previousStream) {
            return sourceBufferSinkMap;
        }
 
        const previousStreamProcessors = previousStream ? previousStream.getStreamProcessors() : [];
 
        previousStreamProcessors.forEach((streamProcessor) => {
            const sourceBufferSink = streamProcessor.getBuffer();
            if (sourceBufferSink) {
                sourceBufferSinkMap.set(sourceBufferSink.getType(), sourceBufferSink);
            }
        })
 
        return sourceBufferSinkMap
    }
 
    /**
     * A playback seeking event was triggered. We need to disable the preloading streams and call the respective seeking handler.
     * We distinguish between inner period seeks and outer period seeks
     * @param {object} e
     * @private
     */
    function _onPlaybackSeeking(e) {
        const newTime = e.seekTime;
        const seekToStream = getStreamForTime(newTime);
 
        if (!seekToStream || seekToStream === activeStream) {
            _cancelPreloading();
            _handleInnerPeriodSeek(e);
        } else if (seekToStream && seekToStream !== activeStream) {
            _cancelPreloading(seekToStream);
            _handleOuterPeriodSeek(e, seekToStream);
        }
 
        _createPlaylistMetrics(PlayList.SEEK_START_REASON);
    }
 
    /**
     * Cancels the preloading of certain streams based on the position we are seeking to.
     * @param {object} seekToStream
     * @private
     */
    function _cancelPreloading(seekToStream = null) {
        // Inner period seek
        if (!seekToStream) {
            _deactivateAllPreloadingStreams();
        }
 
        // Outer period seek: Deactivate everything for now
        else {
            _deactivateAllPreloadingStreams();
        }
 
    }
 
    /**
     * Deactivates all preloading streams
     * @private
     */
    function _deactivateAllPreloadingStreams() {
        if (preloadingStreams && preloadingStreams.length > 0) {
            preloadingStreams.forEach((s) => {
                s.deactivate(true);
            });
            preloadingStreams = [];
        }
    }
 
    /**
     * Handle an inner period seek. Prepare all StreamProcessors for the seek.
     * @param {object} e
     * @private
     */
    function _handleInnerPeriodSeek(e) {
        const streamProcessors = activeStream.getStreamProcessors();
 
        streamProcessors.forEach((sp) => {
            return sp.prepareInnerPeriodPlaybackSeeking(e);
        });
 
        _flushPlaylistMetrics(PlayListTrace.USER_REQUEST_STOP_REASON);
    }
 
    /**
     * Handle an outer period seek. Dispatch the corresponding event to be handled in the BufferControllers and the ScheduleControllers
     * @param {object} e
     * @param {object} seekToStream
     * @private
     */
    function _handleOuterPeriodSeek(e, seekToStream) {
        // Stop segment requests
        const seekTime = e && !isNaN(e.seekTime) ? e.seekTime : NaN;
        const streamProcessors = activeStream.getStreamProcessors();
 
        const promises = streamProcessors.map((sp) => {
            // Cancel everything in case the active stream is still buffering
            return sp.prepareOuterPeriodPlaybackSeeking(e);
        });
 
        Promise.all(promises)
            .then(() => {
                _switchStream(seekToStream, activeStream, seekTime);
            })
            .catch((e) => {
                errHandler.error(e);
            });
    }
 
    /**
     * A track change occured. We deactivate the preloading streams
     * @param {object} e
     * @private
     */
    function _onCurrentTrackChanged(e) {
        // Track was changed in non-active stream. No need to do anything, this only happens when a stream starts preloading
        if (e.newMediaInfo.streamInfo.id !== activeStream.getId()) {
            return;
        }
 
        // If the track was changed in the active stream we need to stop preloading and remove the already prebuffered stuff. Since we do not support preloading specific handling of specific AdaptationSets yet.
        _deactivateAllPreloadingStreams();
 
        if (settings.get().streaming.buffer.resetSourceBuffersForTrackSwitch && e.oldMediaInfo && e.oldMediaInfo.codec !== e.newMediaInfo.codec) {
            const seekTime = playbackController.getTime();
            activeStream.deactivate(false);
            _openMediaSource({ seekTime, keepBuffers: false, streamActivated: false });
            return;
        }
 
        activeStream.prepareTrackChange(e);
    }
 
    /**
     * If the source buffer can be reused we can potentially start buffering the next period
     * @param {object} nextStream
     * @param {object} previousStream
     * @return {boolean}
     * @private
     */
    function _canSourceBuffersBeKept(nextStream, previousStream) {
        try {
            // Seamless period switch allowed only if:
            // - none of the periods uses contentProtection.
            // - AND changeType method is implemented
            return (settings.get().streaming.buffer.reuseExistingSourceBuffers
                && (capabilities.isProtectionCompatible(previousStream.getStreamInfo(), nextStream.getStreamInfo()) || firstLicenseIsFetched)
                && (capabilities.supportsChangeType() && settings.get().streaming.buffer.useChangeType));
        } catch (e) {
            return false;
        }
    }
 
    /**
     * Initiate the preloading of the next stream
     * @param {object} nextStream
     * @param {object} previousStream
     * @private
     */
    function _onStreamCanLoadNext(nextStream, previousStream = null) {
 
        if (!mediaSource || nextStream.getPreloaded()) {
            return;
        }
 
        let seamlessPeriodSwitch = _canSourceBuffersBeKept(nextStream, previousStream);
 
        if (!seamlessPeriodSwitch) {
            return;
        }
 
        const representationsFromPreviousPeriod = _getRepresentationsFromPreviousPeriod(previousStream);
        const previousSourceBufferSinks = _getSourceBufferSinksFromPreviousPeriod(previousStream);
        nextStream.startPreloading(mediaSource, previousSourceBufferSinks, representationsFromPreviousPeriod)
            .then(() => {
                preloadingStreams.push(nextStream);
            });
    }
 
    /**
     * Returns the corresponding stream object for a specific presentation time.
     * @param {number} time
     * @return {null|object}
     */
    function getStreamForTime(time) {
 
        Iif (isNaN(time)) {
            return null;
        }
 
        const ln = streams.length;
 
        for (let i = 0; i < ln; i++) {
            const stream = streams[i];
            const streamEnd = parseFloat((stream.getStartTime() + stream.getDuration()).toFixed(5));
 
            if (time < streamEnd) {
                return stream;
            }
        }
 
        return null;
    }
 
    /**
     * Add the DVR window to the metric list. We need the DVR window to restrict the seeking and calculate the right start time.
     */
    function addDVRMetric() {
        try {
            const isDynamic = adapter.getIsDynamic();
            const streamsInfo = adapter.getStreamsInfo();
            const manifestInfo = streamsInfo[0].manifestInfo;
            const time = playbackController.getTime();
            const range = timelineConverter.calcTimeShiftBufferWindow(streams, isDynamic);
            const activeStreamProcessors = getActiveStreamProcessors();
 
            if (typeof range.start === 'undefined' || typeof range.end === 'undefined') {
                return;
            }
 
            if (!activeStreamProcessors || activeStreamProcessors.length === 0) {
                dashMetrics.addDVRInfo(Constants.VIDEO, time, manifestInfo, range);
            } else {
                activeStreamProcessors.forEach((sp) => {
                    dashMetrics.addDVRInfo(sp.getType(), time, manifestInfo, range);
                });
            }
        } catch (e) {
        }
    }
 
    /**
     * The buffer level for a certain media type has been updated. If this is the initial playback and we want to autoplay the content we check if we can start playback now.
     * For livestreams we might have a drift of the target live delay compared to the current live delay because reaching the initial buffer level took time.
     * @param {object} e
     * @private
     */
    function _onBufferLevelUpdated(e) {
 
        // check if this is the initial playback and we reached the buffer target. If autoplay is true we start playback
        if (initialPlayback && autoPlay) {
            const initialBufferLevel = mediaPlayerModel.getInitialBufferLevel();
            const excludedStreamProcessors = [Constants.TEXT];
            if (isNaN(initialBufferLevel) || initialBufferLevel <= playbackController.getBufferLevel(excludedStreamProcessors) || (adapter.getIsDynamic() && initialBufferLevel > playbackController.getLiveDelay())) {
                initialPlayback = false;
                _createPlaylistMetrics(PlayList.INITIAL_PLAYOUT_START_REASON);
                playbackController.play();
            }
        }
 
        if (e && e.mediaType) {
            dashMetrics.addBufferLevel(e.mediaType, new Date(), e.bufferLevel * 1000);
        }
    }
 
    /**
     * When the quality is changed in the currently active stream we stop the prebuffering to avoid inconsistencies in the buffer settings like codec and append window
     * @param e
     * @private
     */
    function _onQualityChanged(e) {
        if (e.streamInfo.id === activeStream.getId()) {
            _deactivateAllPreloadingStreams();
        }
 
        const stream = getStreamById(e.streamInfo.id);
 
        stream.prepareQualityChange(e);
    }
 
    /**
     * A setting related to the live delay was updated. Check if one of the latency values changed. If so, recalculate the live delay.
     * @private
     */
    function _onLiveDelaySettingUpdated() {
        if (adapter.getIsDynamic() && playbackController.getOriginalLiveDelay() !== 0 && activeStream) {
            const streamsInfo = adapter.getStreamsInfo()
            if (streamsInfo.length > 0) {
                const manifestInfo = streamsInfo[0].manifestInfo;
                const fragmentDuration = _getFragmentDurationForLiveDelayCalculation(streamsInfo, manifestInfo);
 
                playbackController.computeAndSetLiveDelay(fragmentDuration, manifestInfo);
            }
        }
    }
 
    /**
     * When the playback time is updated we add the droppedFrames metric to the dash metric object
     * @private
     */
    function _onPlaybackTimeUpdated(/*e*/) {
        if (hasVideoTrack()) {
            const playbackQuality = videoModel.getPlaybackQuality();
            if (playbackQuality) {
                dashMetrics.addDroppedFrames(playbackQuality);
            }
        }
    }
 
    /**
     * Once playback starts add playlist metrics depending on whether this was the first playback or playback resumed after pause
     * @private
     */
    function _onPlaybackStarted( /*e*/) {
        logger.debug('[onPlaybackStarted]');
        if (!initialPlayback && isPaused) {
            _createPlaylistMetrics(PlayList.RESUME_FROM_PAUSE_START_REASON);
        }
        if (initialPlayback) {
            initialPlayback = false;
        }
        if (initialSteeringRequest) {
            initialSteeringRequest = false;
            // If this is the initial playback attempt and we have not yet triggered content steering now is the time
            if (settings.get().streaming.applyContentSteering && !contentSteeringController.shouldQueryBeforeStart()) {
                contentSteeringController.loadSteeringData();
            }
 
        }
        isPaused = false;
    }
 
    /**
     * Once playback is paused flush metrics
     * @param {object} e
     * @private
     */
    function _onPlaybackPaused(e) {
        logger.debug('[onPlaybackPaused]');
        if (!e.ended) {
            isPaused = true;
            _flushPlaylistMetrics(PlayListTrace.USER_REQUEST_STOP_REASON);
        }
    }
 
    /**
     * Callback once a stream/period is completely buffered. We can either signal the end of the stream or start prebuffering the next period.
     * @param {object} e
     * @private
     */
    function _onStreamBufferingCompleted(e) {
        logger.debug(`Stream with id ${e.streamInfo.id} finished buffering`);
        const isLast = e.streamInfo.isLast;
        if (mediaSource && isLast) {
            logger.info('[onStreamBufferingCompleted] calls signalEndOfStream of mediaSourceController.');
            mediaSourceController.signalEndOfStream(mediaSource);
        } else {
            _checkIfPrebufferingCanStart();
        }
    }
 
    /**
     * Check if we can start prebuffering the next period.
     * @private
     */
    function _checkIfPrebufferingCanStart() {
 
        Iif (!activeStream) {
            return;
        }
 
        // Check if we are finished buffering. In case this is the case the prebuffering will be triggered automatically
        if (!activeStream.getHasFinishedBuffering()) {
            activeStream.checkAndHandleCompletedBuffering();
            return;
        }
 
        // In case we have finished buffering already we can preload
        const upcomingStreams = _getNextStreams(activeStream);
        let i = 0;
 
        while (i < upcomingStreams.length) {
            const stream = upcomingStreams[i];
            const previousStream = i === 0 ? activeStream : upcomingStreams[i - 1];
 
            // If the preloading for the current stream is not scheduled, but its predecessor has finished buffering we can start prebuffering this stream
            if (!stream.getPreloaded() && previousStream.getHasFinishedBuffering()) {
                _onStreamCanLoadNext(stream, previousStream);
            }
            i += 1;
        }
    }
 
    /**
     * In some cases we need to fire the playback ended event manually
     * @private
     */
    function _startPlaybackEndedTimerInterval() {
        if (!playbackEndedTimerInterval) {
            playbackEndedTimerInterval = setInterval(function () {
                if (!isStreamSwitchingInProgress && playbackController.getTimeToStreamEnd() <= 0 && !playbackController.isSeeking()) {
                    eventBus.trigger(Events.PLAYBACK_ENDED, { 'isLast': getActiveStreamInfo().isLast });
                }
            }, PLAYBACK_ENDED_TIMER_INTERVAL);
        }
    }
 
    /**
     * Stop the check if the playback has ended
     * @private
     */
    function _stopPlaybackEndedTimerInterval() {
        if (playbackEndedTimerInterval) {
            clearInterval(playbackEndedTimerInterval);
            playbackEndedTimerInterval = null;
        }
    }
 
    /**
     * Returns a playhead time, in seconds, converted to be relative
     * to the start of an identified stream/period or null if no such stream
     * @param {number} time
     * @param {string} id
     * @returns {number|null}
     */
    function getTimeRelativeToStreamId(time, id) {
        let stream = null;
        let baseStart = 0;
        let streamStart = 0;
        let streamDur = null;
 
        for (let i = 0; i < streams.length; i++) {
            stream = streams[i];
            streamStart = stream.getStartTime();
            streamDur = stream.getDuration();
 
            // use start time, if not undefined or NaN or similar
            if (Number.isFinite(streamStart)) {
                baseStart = streamStart;
            }
 
            if (stream.getId() === id) {
                return time - baseStart;
            } else {
                // use duration if not undefined or NaN or similar
                if (Number.isFinite(streamDur)) {
                    baseStart += streamDur;
                }
            }
        }
 
        return null;
    }
 
    /**
     * Returns the streamProcessors of the active stream.
     * @return {array}
     */
    function getActiveStreamProcessors() {
        return activeStream ? activeStream.getStreamProcessors() : [];
    }
 
    /**
     * Once playback has ended we switch to the next stream
     * @param {object} e
     */
    function _onPlaybackEnded(e) {
        if (activeStream && !activeStream.getIsEndedEventSignaled()) {
            activeStream.setIsEndedEventSignaled(true);
            const nextStream = _getNextStream();
            if (nextStream) {
                logger.debug(`StreamController onEnded, found next stream with id ${nextStream.getStreamInfo().id}. Switching from ${activeStream.getStreamInfo().id} to ${nextStream.getStreamInfo().id}`);
                _switchStream(nextStream, activeStream, NaN);
            } else {
                logger.debug('StreamController no next stream found');
                activeStream.setIsEndedEventSignaled(false);
            }
            _flushPlaylistMetrics(nextStream ? PlayListTrace.END_OF_PERIOD_STOP_REASON : PlayListTrace.END_OF_CONTENT_STOP_REASON);
        }
        if (e && e.isLast) {
            _stopPlaybackEndedTimerInterval();
            contentSteeringController.stopSteeringRequestTimer();
        }
    }
 
    /**
     * Returns the next stream to be played relative to the stream provided. If no stream is provided we use the active stream.
     * In order to avoid rounding issues we should not use the duration of the periods. Instead find the stream with starttime closest to startTime of the previous stream.
     * @param {object} stream
     * @return {null|object}
     */
    function _getNextStream(stream = null) {
        const refStream = stream ? stream : activeStream ? activeStream : null;
 
        if (!refStream) {
            return null;
        }
 
        const refStreamInfo = refStream.getStreamInfo();
        const start = refStreamInfo.start;
        let i = 0;
        let targetIndex = -1;
        let lastDiff = NaN;
 
        while (i < streams.length) {
            const s = streams[i];
            const sInfo = s.getStreamInfo();
            const diff = sInfo.start - start;
 
            if (diff > 0 && (isNaN(lastDiff) || diff < lastDiff) && refStreamInfo.id !== sInfo.id) {
                lastDiff = diff;
                targetIndex = i;
            }
 
            i += 1;
        }
 
        if (targetIndex >= 0) {
            return streams[targetIndex];
        }
 
        return null;
    }
 
    /**
     * Returns all upcoming streams relative to the provided stream. If no stream is provided we use the active stream.
     * @param {object} stream
     * @return {array}
     */
    function _getNextStreams(stream = null) {
        try {
            const refStream = stream ? stream : activeStream ? activeStream : null;
 
            if (refStream) {
                const refStreamInfo = refStream.getStreamInfo();
 
                return streams.filter(function (stream) {
                    const sInfo = stream.getStreamInfo();
                    return sInfo.start > refStreamInfo.start && refStreamInfo.id !== sInfo.id;
                });
            }
        } catch (e) {
            return [];
        }
    }
 
    /**
     * Sets the duration attribute of the MediaSource using the MediaSourceController.
     * @param {number} duration
     * @private
     */
    function _setMediaDuration(duration) {
        const manifestDuration = duration ? duration : getActiveStreamInfo().manifestInfo.duration;
        mediaSourceController.setDuration(manifestDuration);
    }
 
    /**
     * Returns the active stream
     * @return {object}
     */
    function getActiveStream() {
        return activeStream;
    }
 
    /**
     * Initial playback indicates if we have called play() for the first time yet.
     * @return {*}
     */
    function getInitialPlayback() {
        return initialPlayback;
    }
 
    /**
     * Auto Play indicates if the stream starts automatically as soon as it is initialized.
     * @return {boolean}
     */
    function getAutoPlay() {
        return autoPlay;
    }
 
    /**
     * Called once the first stream has been initialized. We only use this function to seek to the right start time.
     * @return {number}
     * @private
     */
    function _getInitialStartTime() {
        // Seek new stream in priority order:
        // - at start time provided via the application
        // - at start time provided in URI parameters
        // - at stream/period start time (for static streams) or live start time (for dynamic streams)
        let startTime;
        const isDynamic = adapter.getIsDynamic();
        if (isDynamic) {
            startTime = _getInitialStartTimeForDynamicStream();
        } else {
            startTime = _getInitialStartTimeForStaticStream();
        }
 
        return startTime;
    }
 
    function _getInitialStartTimeForDynamicStream() {
        let startTime;
        // For dynamic stream, start by default at (live edge - live delay)
        const dvrInfo = dashMetrics.getCurrentDVRInfo();
        const liveEdge = dvrInfo && dvrInfo.range ? dvrInfo.range.end : 0;
        // we are already in the right start period. so time should not be smaller than period@start and should not be larger than period@end
        startTime = liveEdge - playbackController.getOriginalLiveDelay();
        // If start time in URI, take min value between live edge time and time from URI (capped by DVR window range)
        const dvrWindow = dvrInfo ? dvrInfo.range : null;
        if (dvrWindow) {
            // If start time was provided by the application as part of the call to initialize() or attachSource() use this value
            Iif (!isNaN(providedStartTime) || providedStartTime.toString().indexOf('posix:') !== -1) {
                logger.info(`Start time provided by the app: ${providedStartTime}`);
                const providedStartTimeAsPresentationTime = _getStartTimeFromProvidedData(true, providedStartTime)
                if (!isNaN(providedStartTimeAsPresentationTime)) {
                    // Do not move closer to the live edge as defined by live delay
                    startTime = Math.min(startTime, providedStartTimeAsPresentationTime);
                }
            } else {
                // #t shall be relative to period start
                const startTimeFromUri = _getStartTimeFromUriParameters(true);
                if (!isNaN(startTimeFromUri)) {
                    logger.info(`Start time from URI parameters: ${startTimeFromUri}`);
                    // Do not move closer to the live edge as defined by live delay
                    startTime = Math.min(startTime, startTimeFromUri);
                }
            }
            // If calcFromSegmentTimeline is enabled we saw problems caused by the MSE.seekableRange when starting at dvrWindow.start. Apply a small offset to avoid this problem.
            const offset = settings.get().streaming.timeShiftBuffer.calcFromSegmentTimeline ? 0.1 : 0;
            startTime = Math.max(startTime, dvrWindow.start + offset);
        }
 
        return startTime;
    }
 
    function _getInitialStartTimeForStaticStream() {
        // For static stream, start by default at period start
        const streams = getStreams();
        const streamInfo = streams[0].getStreamInfo();
        let startTime = streamInfo.start;
 
        // If start time was provided by the application as part of the call to initialize() or attachSource() use this value
        Iif (!isNaN(providedStartTime)) {
            logger.info(`Start time provided by the app: ${providedStartTime}`);
            const providedStartTimeAsPresentationTime = _getStartTimeFromProvidedData(false, providedStartTime)
            if (!isNaN(providedStartTimeAsPresentationTime)) {
                // Do not play earlier than the start of the first period
                startTime = Math.max(startTime, providedStartTimeAsPresentationTime);
            }
        } else {
            // If start time in URI, take max value between period start and time from URI (if in period range)
            const startTimeFromUri = _getStartTimeFromUriParameters(false);
            if (!isNaN(startTimeFromUri)) {
                logger.info(`Start time from URI parameters: ${startTimeFromUri}`);
                // Do not play earlier than the start of the first period
                startTime = Math.max(startTime, startTimeFromUri);
            }
        }
 
        return startTime;
    }
 
    /**
     * 23009-1 Annex C.4 defines MPD anchors to use URI fragment syntax to start a presentation at a given time and a given state
     * @param {boolean} isDynamic
     * @return {number}
     * @private
     */
    function _getStartTimeFromUriParameters(isDynamic) {
        const fragData = uriFragmentModel.getURIFragmentData();
        if (!fragData || !fragData.t) {
            return NaN;
        }
        const refStream = getStreams()[0];
        const referenceTime = refStream.getStreamInfo().start;
        fragData.t = fragData.t.split(',')[0];
 
        return _getStartTimeFromString(isDynamic, fragData.t, referenceTime);
    }
 
    /**
     * Calculate start time using the value that was provided via the application as part of attachSource() or initialize()
     * @param {boolean} isDynamic
     * @param {number | string} providedStartTime
     * @return {number}
     * @private
     */
    function _getStartTimeFromProvidedData(isDynamic, providedStartTime) {
        let referenceTime = 0;
 
        if (!isDynamic) {
            const refStream = getStreams()[0];
            referenceTime = refStream.getStreamInfo().start;
        }
 
        return _getStartTimeFromString(isDynamic, providedStartTime, referenceTime);
    }
 
 
    function _getStartTimeFromString(isDynamic, targetValue, referenceTime) {
        // Consider only start time of MediaRange
        // TODO: consider end time of MediaRange to stop playback at provided end time
        // "t=<time>" : time is relative to 1st period start
        // "t=posix:<time>" : time is absolute start time as number of seconds since 01-01-1970
        const period = adapter.getRegularPeriods()[0];
        const targetString = targetValue.toString();
        const posix = targetString.indexOf('posix:') !== -1 ? targetString.substring(6) === 'now' ? Date.now() / 1000 : parseFloat(targetString.substring(6)) : NaN;
        return (isDynamic && !isNaN(posix)) ? timelineConverter.calcPresentationTimeFromWallTime(new Date(posix * 1000), period) : parseFloat(targetString) + referenceTime;
    }
 
    /**
     * Streams that are no longer in the manifest can be filtered
     * @param {object} streamsInfo
     * @private
     */
    function _filterOutdatedStreams(streamsInfo) {
        Iif (streamsInfo.length === 0) {
            logger.warn(`No periods included in the current manifest. Skipping the filtering of outdated stream objects.`);
            return;
        }
 
        streams = streams.filter((stream) => {
            const isStillIncluded = streamsInfo.filter((sInfo) => {
                return sInfo.id === stream.getId();
            }).length > 0;
 
            const shouldKeepStream = isStillIncluded || stream.getId() === activeStream.getId();
 
            Iif (!shouldKeepStream) {
                logger.debug(`Removing stream ${stream.getId()}`);
                stream.reset(true);
                stream = null;
            }
 
            return shouldKeepStream;
        });
    }
 
    /**
     * In order to calculate the initial live delay we might required the duration of the segments.
     * @param {array} streamInfos
     * @param {object} manifestInfo
     * @return {number}
     * @private
     */
    function _getFragmentDurationForLiveDelayCalculation(streamInfos, manifestInfo) {
        try {
            let segmentDuration = NaN;
 
            //  We use the maxFragmentDuration attribute if present
            Iif (manifestInfo && !isNaN(manifestInfo.maxFragmentDuration) && isFinite(manifestInfo.maxFragmentDuration)) {
                return manifestInfo.maxFragmentDuration;
            }
 
            return isFinite(segmentDuration) ? segmentDuration : NaN;
        } catch (e) {
            return NaN;
        }
    }
 
    /**
     * Callback handler after the steering manifest was updated
     * @param {object} e
     * @private
     */
    function _onSteeringManifestUpdated() {
        const manifest = manifestModel.getValue();
        baseURLController.initialize(manifest);
    }
 
    /**
     * Callback handler after the manifest has been updated. Trigger an update in the adapter and filter unsupported stuff.
     * Finally, attempt UTC sync
     * @param {object} e
     * @private
     */
    function _onManifestUpdated(e) {
        if (!e.error) {
            logger.info('Manifest updated... updating data system wide.');
 
            //Since streams are not composed yet , need to manually look up useCalculatedLiveEdgeTime to detect if stream
            //is SegmentTimeline to avoid using time source
            const manifest = e.manifest;
            adapter.updatePeriods(manifest);
 
            // It is important to filter before initializing the baseUrlController. Otherwise we might end up with wrong references in case we remove AdaptationSets.
            capabilitiesFilter.filterUnsupportedFeatures(manifest)
                .then(() => {
                    baseURLController.initialize(manifest);
 
                    let manifestUTCTimingSources = adapter.getUTCTimingSources();
                    Iif (adapter.getIsDynamic() && (!manifestUTCTimingSources || manifestUTCTimingSources.length === 0)) {
                        eventBus.trigger(MediaPlayerEvents.CONFORMANCE_VIOLATION, {
                            level: ConformanceViolationConstants.LEVELS.WARNING,
                            event: ConformanceViolationConstants.EVENTS.NO_UTC_TIMING_ELEMENT
                        });
                    }
 
                    let allUTCTimingSources = (!adapter.getIsDynamic()) ? manifestUTCTimingSources : manifestUTCTimingSources.concat(customParametersModel.getUTCTimingSources());
                    timeSyncController.attemptSync(allUTCTimingSources, adapter.getIsDynamic());
                    extUrlQueryInfoController.createFinalQueryStrings(manifest);
                });
        } else {
            hasInitialisationError = true;
            reset();
        }
    }
 
    /**
     * Check if the stream has a video track
     * @return {boolean}
     */
    function hasVideoTrack() {
        return activeStream ? activeStream.getHasVideoTrack() : false;
    }
 
    /**
     * Check if the stream has an audio track
     * @return {boolean}
     */
    function hasAudioTrack() {
        return activeStream ? activeStream.getHasAudioTrack() : false;
    }
 
 
    function switchToVideoElement(seekTime) {
        if (activeStream) {
            playbackController.initialize(getActiveStreamInfo());
            _openMediaSource({ seekTime, keepBuffers: false, streamActivated: true });
        }
    }
 
    function _flushPlaylistMetrics(reason, time) {
        time = time || new Date();
 
        getActiveStreamProcessors().forEach(p => {
            p.finalisePlayList(time, reason);
        });
        dashMetrics.addPlayList();
    }
 
    function _createPlaylistMetrics(startReason) {
        dashMetrics.createPlaylistMetrics(playbackController.getTime() * 1000, startReason);
    }
 
    function _onInternalKeyStatusesChanged(e) {
        protectionController.updateKeyStatusesMap(e);
        _handleKeyStatuses();
    }
 
    function _handleKeyStatuses() {
        const streamProcessors = getActiveStreamProcessors();
        let hasUnusableKey = false;
 
        streamProcessors.forEach((streamProcessor) => {
            const currentMediaInfo = streamProcessor.getMediaInfo();
            const areKeyIdsUsable =
                currentMediaInfo ? capabilities.areKeyIdsUsable(currentMediaInfo) : true;
 
            if (!areKeyIdsUsable) {
                hasUnusableKey = true;
                _handleUnusableKeyId(streamProcessor)
            } else {
                const areKeyIdsExpired = currentMediaInfo ? capabilities.areKeyIdsExpired(currentMediaInfo) : false;
                if (areKeyIdsExpired) {
                    _handleExpiredKeyId(streamProcessor);
                }
            }
        })
        // we observed that playback still stalls if we replace the buffer when playhead is at 0. Do a minimal seek to avoid this
        if (hasUnusableKey) {
            _handleUnusableKeyStall();
        }
    }
 
    function _handleUnusableKeyStall() {
        if (playbackController.getTime() === 0) {
            eventBus.once(MediaPlayerEvents.FRAGMENT_LOADING_COMPLETED, () => {
                _triggerUnusableKeySeek();
            }, instance)
        } else {
            playbackController.isProgressing(500)
                .then((isProgressing) => {
                    if (!isProgressing) {
                        _triggerUnusableKeySeek();
                    }
                })
        }
    }
 
    function _triggerUnusableKeySeek() {
        const time = playbackController.getTime()
        playbackController.seek(time + 0.01, false, false);
    }
 
    function _handleUnusableKeyId(streamProcessor) {
        const possibleMediaInfos = streamProcessor.getAllMediaInfos();
        const supportedMediaInfos = possibleMediaInfos.filter((mediaInfo) => {
            return capabilities.areKeyIdsUsable(mediaInfo);
        })
 
        if (!supportedMediaInfos || supportedMediaInfos.length === 0) {
            const type = streamProcessor.getType();
            errHandler.error(new DashJSError(Errors.NO_SUPPORTED_KEY_IDS, `Type: ${type}: ${Errors.NO_SUPPORTED_KEY_IDS_MESSAGE}`));
            return
        }
 
        mediaController.setTrack(supportedMediaInfos[0], { replaceBuffer: true })
    }
 
    function _handleExpiredKeyId(streamProcessor) {
        const streamId = streamProcessor.getStreamId();
        const stream = getStreamById(streamId);
 
        if (stream) {
            stream.triggerProtectionError({ error: new DashJSError(ProtectionErrors.KEY_STATUS_CHANGED_EXPIRED_ERROR_CODE, ProtectionErrors.KEY_STATUS_CHANGED_EXPIRED_ERROR_MESSAGE) })
        }
 
    }
 
    function _onPlaybackError(e) {
        Iif (!e.error) {
            return;
        }
 
        let msg;
 
        switch (e.error.code) {
            case 1:
                msg = 'MEDIA_ERR_ABORTED';
                break;
            case 2:
                msg = 'MEDIA_ERR_NETWORK';
                break;
            case 3:
                msg = 'MEDIA_ERR_DECODE';
                errorInformation.counts.mediaErrorDecode += 1;
                break;
            case 4:
                msg = 'MEDIA_ERR_SRC_NOT_SUPPORTED';
                break;
            case 5:
                msg = 'MEDIA_ERR_ENCRYPTED';
                break;
            default:
                msg = 'UNKNOWN';
                break;
        }
 
 
        Iif (msg === 'MEDIA_ERR_DECODE' && settings.get().errors.recoverAttempts.mediaErrorDecode >= errorInformation.counts.mediaErrorDecode) {
            _handleMediaErrorDecode();
            return;
        }
 
        hasMediaError = true;
 
        Iif (e.error.message) {
            msg += ' (' + e.error.message + ')';
        }
 
        Iif (e.error.msExtendedCode) {
            msg += ' (0x' + (e.error.msExtendedCode >>> 0).toString(16).toUpperCase() + ')';
        }
 
        logger.fatal('Video Element Error: ' + msg);
        if (e.error) {
            logger.fatal(e.error);
        }
        errHandler.error(new DashJSError(e.error.code, msg));
        reset();
    }
 
    /**
     * Handles mediaError
     * @private
     */
    function _handleMediaErrorDecode() {
        logger.error('A MEDIA_ERR_DECODE occured: Resetting the MediaSource');
        const seekTime = playbackController.getTime();
        // Deactivate the current stream.
        activeStream.deactivate(false);
 
        // Reset MSE
        logger.info(`MediaSource has been resetted. Resuming playback from time ${seekTime}`);
        _openMediaSource({ seekTime, keepBuffers: false, streamActivated: false });
    }
 
    function getActiveStreamInfo() {
        return activeStream ? activeStream.getStreamInfo() : null;
    }
 
    function getIsStreamSwitchInProgress() {
        return isStreamSwitchingInProgress;
    }
 
    function getHasMediaOrInitialisationError() {
        return hasMediaError || hasInitialisationError;
    }
 
    function getStreamById(id) {
        for (let i = 0, ln = streams.length; i < ln; i++) {
            if (streams[i].getId() === id) {
                return streams[i];
            }
        }
        return null;
    }
 
    function _onManifestValidityChanged(e) {
        if (!isNaN(e.newDuration)) {
            _setMediaDuration(e.newDuration);
        }
    }
 
    function setConfig(config) {
        Iif (!config) {
            return;
        }
 
        Iif (config.capabilities) {
            capabilities = config.capabilities;
        }
        if (config.capabilitiesFilter) {
            capabilitiesFilter = config.capabilitiesFilter;
        }
        if (config.manifestLoader) {
            manifestLoader = config.manifestLoader;
        }
        if (config.manifestModel) {
            manifestModel = config.manifestModel;
        }
        Iif (config.mediaPlayerModel) {
            mediaPlayerModel = config.mediaPlayerModel;
        }
        Iif (config.customParametersModel) {
            customParametersModel = config.customParametersModel;
        }
        if (config.protectionController) {
            protectionController = config.protectionController;
        }
        if (config.adapter) {
            adapter = config.adapter;
        }
        if (config.dashMetrics) {
            dashMetrics = config.dashMetrics;
        }
        if (config.errHandler) {
            errHandler = config.errHandler;
        }
        if (config.timelineConverter) {
            timelineConverter = config.timelineConverter;
        }
        if (config.videoModel) {
            videoModel = config.videoModel;
        }
        if (config.playbackController) {
            playbackController = config.playbackController;
        }
        Iif (config.throughputController) {
            throughputController = config.throughputController;
        }
        if (config.serviceDescriptionController) {
            serviceDescriptionController = config.serviceDescriptionController;
        }
        if (config.contentSteeringController) {
            contentSteeringController = config.contentSteeringController;
        }
        if (config.textController) {
            textController = config.textController;
        }
        Iif (config.abrController) {
            abrController = config.abrController;
        }
        Iif (config.mediaController) {
            mediaController = config.mediaController;
        }
        if (config.settings) {
            settings = config.settings;
        }
        if (config.baseURLController) {
            baseURLController = config.baseURLController;
        }
        if (config.uriFragmentModel) {
            uriFragmentModel = config.uriFragmentModel;
        }
        Iif (config.segmentBaseController) {
            segmentBaseController = config.segmentBaseController;
        }
        if (config.manifestUpdater) {
            manifestUpdater = config.manifestUpdater;
        }
    }
 
    function setProtectionData(protData) {
        protectionData = protData;
        if (protectionController) {
            protectionController.setProtectionData(protectionData);
        }
    }
 
    function resetInitialSettings() {
        streams = [];
        providedStartTime = NaN;
        protectionController = null;
        isStreamSwitchingInProgress = false;
        activeStream = null;
        hasMediaError = false;
        hasInitialisationError = false;
        initialPlayback = true;
        initialSteeringRequest = true;
        isPaused = false;
        autoPlay = true;
        playbackEndedTimerInterval = null;
        firstLicenseIsFetched = false;
        preloadingStreams = [];
        waitForPlaybackStartTimeout = null;
        errorInformation = {
            counts: {
                mediaErrorDecode: 0
            }
        }
    }
 
    function reset() {
        _checkConfig();
 
        timeSyncController.reset();
 
        _flushPlaylistMetrics(hasMediaError || hasInitialisationError ? PlayListTrace.FAILURE_STOP_REASON : PlayListTrace.USER_REQUEST_STOP_REASON);
 
        for (let i = 0, ln = streams ? streams.length : 0; i < ln; i++) {
            const stream = streams[i];
            stream.reset(hasMediaError);
        }
 
        unRegisterEvents();
 
        baseURLController.reset();
        manifestUpdater.reset();
        eventController.reset();
        dashMetrics.clearAllCurrentMetrics();
        manifestModel.setValue(null);
        manifestLoader.reset();
        timelineConverter.reset();
        initCache.reset();
 
        if (mediaSource) {
            mediaSourceController.detachMediaSource(videoModel);
            mediaSource = null;
        }
        videoModel = null;
        if (protectionController) {
            protectionController = null;
            protectionData = null;
            Iif (manifestModel.getValue()) {
                eventBus.trigger(Events.PROTECTION_DESTROYED, { data: manifestModel.getValue().url });
            }
        }
 
        _stopPlaybackEndedTimerInterval();
        eventBus.trigger(Events.STREAM_TEARDOWN_COMPLETE);
        resetInitialSettings();
    }
 
    function _onMetricAdded(e) {
        if (e.metric === MetricsConstants.DVR_INFO) {
            //Match media type? How can DVR window be different for media types?
            //Should we normalize and union the two?
            const targetMediaType = hasAudioTrack() ? Constants.AUDIO : Constants.VIDEO;
            if (e.mediaType === targetMediaType) {
                mediaSourceController.setSeekable(e.value.range.start, e.value.range.end);
            }
        }
    }
 
    function refreshManifest() {
        if (!manifestUpdater.getIsUpdating()) {
            manifestUpdater.refreshManifest();
        }
    }
 
    function getStreams() {
        return streams;
    }
 
    instance = {
        addDVRMetric,
        getActiveStream,
        getActiveStreamInfo,
        getActiveStreamProcessors,
        getAutoPlay,
        getHasMediaOrInitialisationError,
        getInitialPlayback,
        getIsStreamSwitchInProgress,
        getStreamById,
        getStreamForTime,
        getStreams,
        getTimeRelativeToStreamId,
        hasAudioTrack,
        hasVideoTrack,
        initialize,
        load,
        loadWithManifest,
        refreshManifest,
        reset,
        setConfig,
        setProtectionData,
        switchToVideoElement,
    };
 
    setup();
 
    return instance;
}
 
StreamController.__dashjs_factory_name = 'StreamController';
export default FactoryMaker.getSingletonFactory(StreamController);