All files media_manager.js

58.65% Statements 339/578
55.42% Branches 194/350
60.9% Functions 67/110
58.43% Lines 336/575

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        1x                               110x         110x           110x           110x         110x           110x                     110x         110x           110x           110x         110x 9x           110x               110x           110x 249x 249x         110x 101x       110x 101x           110x         110x         110x         110x           110x             110x         110x         110x         110x               110x             110x           110x         110x         110x         110x           110x           110x         110x         110x           110x         110x     110x     110x 110x   110x   110x                 110x             21x 21x   20x   1x     1x 1x 1x                             21x           21x         21x                 23x 23x 23x 23x 23x 161x 92x 92x 69x   92x 23x       23x     23x                             23x                     23x                                                                                                                                                                                               22x   3x       19x 19x 18x 18x       19x       19x 18x 18x     18x           18x         18x                   18x                         18x 18x     18x   17x   17x 17x       1x   1x 1x                                     1x                       43x   2x   2x 2x   2x 2x           41x   41x   1x     41x           41x     41x   1x         41x         41x 4x   41x                                                 1x               1x 1x 1x     1x     1x                         23x 23x 21x     23x           23x 2x 2x     2x   2x       21x 21x     21x   21x                               21x   21x 21x 19x 19x     21x 18x                                                                                         110x 110x                   2x 2x 1x   1x                     23x 23x 4x   23x 23x 23x 23x                   1x 1x 1x                   2x 2x   1x 1x 1x                                   1x 1x           5x 1x 1x     5x 1x 1x     5x                                                                                                                                   18x   18x     18x             18x 18x 18x 18x               18x 18x   18x 18x                   18x   18x     18x 18x     18x     18x           18x                       1x   1x 1x 1x       1x                   1x   1x 1x 1x       1x               20x   20x   19x 19x   3x 3x 3x   1x     1x       20x 4x     20x           20x 18x     18x       20x 1x                 20x       20x   20x   4x   4x   4x 4x 4x   16x     16x     20x 3x     20x 1x 1x                                                                                                           5x         5x 4x                             1x   1x 1x 1x 7x     1x                     1x 1x                 42x 1x 1x         3x     1x             1x 1x 1x                       1x   1x   1x 1x                                                                                             20x 20x                 20x 20x 20x                           20x 20x                 20x 20x 20x                   8x     8x     8x 8x         8x 8x             4x         4x     4x 4x     4x 4x     4x 4x     4x     4x 4x           22x 2x 2x 2x     22x 2x 2x                     6x 1x 1x     5x   5x     1x     1x   1x 1x       4x 4x 4x             21x 3x 3x           21x 3x 3x                 2x 1x 1x     1x   1x     1x       1x             1x   1x     1x   1x 1x                   1x 1x 1x                         20x   20x   1x   1x 1x       19x 19x                                                                                                                                                           4x 4x 4x 4x           4x         5x 2x 2x                                                                                                                                  
import {SoundMeter} from "./soundmeter.js"
import "./external/loglevel.min.js";
import {isAndroid} from "./utility.js";
 
const Logger = window.log;
/**
 * Media management class is responsible to manage audio and video
 * sources and tracks management for the local stream.
 * Also audio and video properties (like bitrate) are managed by this class .
 */
export class MediaManager {
    /**
     *
     * @param {object} initialValues
     */
    constructor(initialValues) {
        /**
         * the maximum bandwith value that browser can send a stream
         * keep in mind that browser may send video less than this value
         */
        this.bandwidth = 1200; //kbps
 
        /**
         * This flags enables/disables debug logging
         */
        this.debug = false;
 
        /**
         * The cam_location below is effective when camera and screen is send at the same time.
         * possible values are top and bottom. It's on right all the time
         */
        this.camera_location = "top"
 
        /**
         * The cam_margin below is effective when camera and screen is send at the same time.
         * This is the margin value in px from the edges
         */
        this.camera_margin = 15;
 
        /**
         * this camera_percent is how large the camera view appear on the screen. It's %15 by default.
         */
        this.camera_percent = 15;
 
        /**
         * initial media constraints provided by the user
	 * @type {MediaStreamConstraints}
         */
        this.mediaConstraints = {
	    /** @type {MediaTrackConstraints} */
            video: true,
	    /** @type {MediaTrackConstraints} */
            audio: true
        };
        ;
 
        /**
         * this is the callback function to get video/audio sender from WebRTCAdaptor
         */
        this.getSender = initialValues.getSender;
 
        /**
         * This is the Stream Id for the publisher.
         */
        this.publishStreamId = null;
 
        /**
         * this is the object of the local stream to publish
         * it is initiated in initLocalStream method
         */
        this.localStream = null;
 
        /**
         * publish mode is determined by the user and set by @mediaConstraints.video
         * It may be camera, screen, screen+camera
         */
        this.publishMode = "camera"; //screen, screen+camera
 
        /**
         * Default callback. It's overriden below if it exists
         */
        this.callback = (info, obj) => {
            Logger.debug("Callback info: " + info + " object: " + typeof obj !== undefined ? JSON.stringify(obj) : "");
		};
 
		/**
		 * Default callback error implementation. It's overriden below if it exists
		 */
		this.callbackError = (err) => {
            Logger.error(err)
		}
 
 
		/**
         * volume-meter-process.js file to find directly. You can locate the file to your assets
		 */
		this.volumeMeterUrl = 'volume-meter-processor.js';
 
        /**
         * The values of the above fields are provided as user parameters by the constructor.
         * TODO: Also some other hidden parameters may be passed here
         */
        for (var key in initialValues.userParameters) {
            Eif (initialValues.userParameters.hasOwnProperty(key)) {
                this[key] = initialValues.userParameters[key];
            }
        }
 
        //set the callback if it's defined
        if (initialValues.callback) {
			this.callback = initialValues.callback;
		}
 
        //set the callbackError if it's defined
		if (initialValues.callbackError) {
			this.callbackError = initialValues.callbackError;
		}
 
        /**
         * current volume value which is set by the user
         */
        this.currentVolume = null;
 
        /**
         * Keeps the audio track to be closed in case of audio track change
         */
        this.previousAudioTrack = null;
 
        /**
		 * silent audio track for switching between dummy track to real tracks on the fly
		 */
		this.silentAudioTrack = null;
 
        /**
         * The screen video track in screen+camera mode
         */
        this.desktopStream = null;
 
 
        /**
         * The camera (overlay) video track in screen+camera mode
         */
        this.smallVideoTrack = null;
		
		
		/**
		 * The screen share audio track in screen+camera mode or screen share mode when
		 * there browser tab is shared with audio
		 */
		this.screenShareAudioTrack = null;
 
        /**
		 * black video track for switching between dummy video track to real tracks on the fly
		 */
		this.blackVideoTrack = null;
 
        /**
         * Audio context to use for meter, mix, gain
         */
        this.audioContext = new AudioContext();
 
        /**
		 * osciallator to generate silent audio
		 */
        this.oscillator = null;
 
        /**
         * the main audio in single audio case
         * the primary audio in mixed audio case
         *
         * its volume can be controled
         */
        this.primaryAudioTrackGainNode = null;
 
        /**
         * the secondary audio in mixed audio case
         *
         * its volume can be controled
         */
        this.secondaryAudioTrackGainNode = null;
 
 
        /**
         * this is the sound meter object for the local stream
         */
        this.localStreamSoundMeter = null;
 
        /**
         * this is the level callback for sound meter object
         */
        this.levelCallback = null;
 
        /**
         * Timer to create black frame to publish when video is muted
         */
        this.blackFrameTimer = null;
 
        /**
         * Timer to draw camera and desktop to canvas
         */
        this.desktopCameraCanvasDrawerTimer = null;
 
        /**
         * For audio check when the user is muted itself.
         * Check enableAudioLevelWhenMuted
         */
        this.mutedAudioStream = null;
 
        /**
         * This flag is the status of audio stream
         * Checking when the audio stream is updated
         */
        this.isMuted = false;
 
        /**
         * meter refresh period for "are you talking?" check
         */
        this.meterRefresh = null;
 
        /**
         * For keeping track of whether user turned off the camera
         */
        this.cameraEnabled = true;
 
 
        /**
         * Replacement stream for video track when the camera is turn off
		 */
        this.replacementStream = null;
 
        /**
         * html video element that presents local stream
         */
        this.localVideo = this.localVideoElement || document.getElementById(this.localVideoId);
 
        //A dummy stream created to replace the tracks when camera is turned off.
        this.dummyCanvas = document.createElement("canvas");
 
        // It should be compatible with previous version
        if (this.mediaConstraints) {
            Iif (this.mediaConstraints.video == "camera") {
                this.publishMode = "camera";
            } else Iif (this.mediaConstraints.video == "screen") {
                this.publishMode = "screen";
            } else Iif (this.mediaConstraints.video == "screen+camera") {
                this.publishMode = "screen+camera";
            }
        } else E{
            //just define default values
            this.mediaConstraints = {video: true, audio: true};
        }
 
        //Check browser support for screen share function
        this.checkBrowserScreenShareSupported();
    }
 
    /**
     * Called by the WebRTCAdaptor at the start if it isn't play mode
     */
    initLocalStream() {
        this.checkWebRTCPermissions();
        if (typeof this.mediaConstraints.video != "undefined" && this.mediaConstraints.video != false)
        {
            return this.openStream(this.mediaConstraints);
        }
        else if (typeof this.mediaConstraints.audio != "undefined" && this.mediaConstraints.audio != false)
        {
            // get only audio
            let media_audio_constraint = {audio: this.mediaConstraints.audio};
            return this.navigatorUserMedia(media_audio_constraint, stream => {
                return this.gotStream(stream);
            }, true)
        } else E{
            //neither video nor audio is requested
            //just return null stream
            Logger.debug("no media requested, just return an empty stream");
            return Promise.resolve(null);
        }
 
    }
 
    /*
    * Called to checks if Websocket and media usage are allowed
    */
    checkWebRTCPermissions() {
        Iif (!("WebSocket" in window)) {
            Logger.debug("WebSocket not supported.");
            this.callbackError("WebSocketNotSupported");
            return;
        }
 
        Iif (typeof navigator.mediaDevices == "undefined") {
            Logger.debug("Cannot open camera and mic because of unsecure context. Please Install SSL(https)");
            this.callbackError("UnsecureContext");
            return;
        }
        Iif (typeof navigator.mediaDevices == "undefined" || navigator.mediaDevices == undefined || navigator.mediaDevices == null) {
            this.callbackError("getUserMediaIsNotAllowed");
        }
    }
 
    /*
     * Called to get the available video and audio devices on the system
     */
    getDevices() {
        return navigator.mediaDevices.enumerateDevices().then(devices => {
            let deviceArray = new Array();
            let checkAudio = false
            let checkVideo = false
            devices.forEach(device => {
                if (device.kind == "audioinput" || device.kind == "videoinput") {
                    deviceArray.push(device);
                    if (device.kind == "audioinput") {
                        checkAudio = true;
                    }
                    if (device.kind == "videoinput") {
                        checkVideo = true;
                    }
                }
            });
            this.callback("available_devices", deviceArray);
 
            //TODO: is the following part necessary. why?
            Iif (checkAudio == false && this.localStream == null) {
                Logger.debug("Audio input not found")
                Logger.debug("Retrying to get user media without audio")
                if (this.inputDeviceNotFoundLimit < 2) {
                    if (checkVideo != false) {
                        this.openStream({video: true, audio: false})
                        this.inputDeviceNotFoundLimit++;
                    } else {
                        Logger.debug("Video input not found")
                        alert("There is no video or audio input")
                    }
                } else {
                    alert("No input device found, publish is not possible");
                }
            }
            return deviceArray;
        }).catch(err => {
            Logger.error("Cannot get devices -> error name: " + err.name + ": " + err.message);
            throw err;
        });
    }
 
    /*
     * Called to add a device change listener
     */
    trackDeviceChange() {
        navigator.mediaDevices.ondevicechange = () => {
            this.getDevices();
        }
    }
 
    /**
     * This function create a canvas which combines screen video and camera video as an overlay
     *
     * @param {*} stream : screen share stream
     * @param {*} streamId
     * @param {*} onEndedCallback : callback when called on screen share stop
     */
    setDesktopwithCameraSource(stream, streamId, onEndedCallback) {
        this.desktopStream = stream;
        return this.navigatorUserMedia({video: this.mediaConstraints.video, audio: false}, cameraStream => {
            this.smallVideoTrack = cameraStream.getVideoTracks()[0];
 
            //create a canvas element
            var canvas = document.createElement("canvas");
            var canvasContext = canvas.getContext("2d");
 
            //create video element for screen
            //var screenVideo = document.getElementById('sourceVideo');
            var screenVideo = document.createElement('video');
 
            screenVideo.srcObject = stream;
            screenVideo.play();
            //create video element for camera
            var cameraVideo = document.createElement('video');
 
            cameraVideo.srcObject = cameraStream;
            cameraVideo.play();
            var canvasStream = canvas.captureStream(15);
 
            if (onEndedCallback != null) {
                stream.getVideoTracks()[0].onended = function (event) {
                    onEndedCallback(event);
                }
            }
            var promise;
            if (this.localStream == null) {
                promise = this.gotStream(canvasStream);
            } else {
                promise = this.updateVideoTrack(canvasStream, streamId, onended, null);
            }
 
            promise.then(() => {
 
                //update the canvas
                this.desktopCameraCanvasDrawerTimer = setInterval(() => {
                    //draw screen to canvas
                    canvas.width = screenVideo.videoWidth;
                    canvas.height = screenVideo.videoHeight;
                    canvasContext.drawImage(screenVideo, 0, 0, canvas.width, canvas.height);
 
					if(this.cameraEnabled) {
	                    var cameraWidth = screenVideo.videoWidth * (this.camera_percent / 100);
	                    var cameraHeight = (cameraVideo.videoHeight / cameraVideo.videoWidth) * cameraWidth
	
	                    var positionX = (canvas.width - cameraWidth) - this.camera_margin;
	                    var positionY;
	
	                    if (this.camera_location == "top") {
	                        positionY = this.camera_margin;
	                    } else { //if not top, make it bottom
	                        //draw camera on right bottom corner
	                        positionY = (canvas.height - cameraHeight) - this.camera_margin;
	                    }
	                    canvasContext.drawImage(cameraVideo, positionX, positionY, cameraWidth, cameraHeight);
					}
                }, 66);
            });
        }, true)
    }
	
	prepare
	
 
    /**
     * This function does these:
     *    1. Remove the audio track from the stream provided if it is camera. Other case
     *       is screen video + system audio track. In this case audio is kept in stream.
     *    2. Open audio track again if audio constaint isn't false
     *    3. Make audio track Gain Node to be able to volume adjustable
     *  4. If screen is shared and system audio is available then the system audio and
     *     opened audio track are mixed
     *
     * @param {*} mediaConstraints
     * @param {*} audioConstraint
     * @param {*} stream
     * @param {*} streamId
     */
    prepareStreamTracks(mediaConstraints, audioConstraint, stream, streamId) {
        //this trick, getting audio and video separately, make us add or remove tracks on the fly
		
		//if audio stream is silent, no need to change it
		if (mediaConstraints.audio == "dummy")
		{
			return this.gotStream(stream);
		}
 
		
        var audioTracks = stream.getAudioTracks()
        if (audioTracks.length > 0 && this.publishMode == "camera") {
            audioTracks[0].stop();
            stream.removeTrack(audioTracks[0]);
        }
 
		//stopScreenShareSystemAudioTrack if exists
		this.stopScreenShareSystemAudioTrack();
 
		
        //now get only audio to add this stream
        if (audioConstraint != "undefined" && audioConstraint != false) {
            var media_audio_constraint = {audio: audioConstraint};
            return this.navigatorUserMedia(media_audio_constraint).then((audioStream) => {
 
                //here audioStream has onr audio track only
                audioStream = this.setGainNodeStream(audioStream);
                // now audio stream has two audio strams.
                // 1. Gain Node : this will be added to local stream to publish
                // 2. Original audio track : keep its reference to stop later
 
                //add callback if desktop is sharing
                var onended = event => {
                    this.callback("screen_share_stopped");
                    this.setVideoCameraSource(streamId, mediaConstraints, null, true);
                }
 
                Iif (this.publishMode == "screen") {
                    return this.updateVideoTrack(stream, streamId, onended, true).then(() => {
                        if (audioTracks.length > 0) 
						{ //system audio share case, then mix it with device audio
							
							this.screenShareAudioTrack = audioTracks[0];
                            audioStream = this.mixAudioStreams(stream, audioStream);
                        }
                        return this.updateAudioTrack(audioStream, streamId, null);
                    });
                } else Iif (this.publishMode == "screen+camera") {
                    if (audioTracks.length > 0) 
					{ //system audio share case, then mix it with device audio
						
						this.screenShareAudioTrack = audioTracks[0];
                        audioStream = this.mixAudioStreams(stream, audioStream);
                    }
 
                    return this.updateAudioTrack(audioStream, streamId, null).then(() => {
                        return this.setDesktopwithCameraSource(stream, streamId, onended);
                    });
 
                } else {
                    Eif (audioConstraint != false && audioConstraint != undefined) {
                        stream.addTrack(audioStream.getAudioTracks()[0]);
                    }
					
                    if (stream.getVideoTracks().length > 0)
                    {
                        return this.updateVideoTrack(stream, streamId, null, null).then(() =>
                        {
                            return this.updateAudioTrack(stream, streamId, null).then(() => {
                                return this.gotStream(stream);
                            });
                        });
                    }
                    else if (stream.getAudioTracks().length > 0)
                    {
                        return this.updateAudioTrack(stream, streamId, null).then(() => {
                            return this.gotStream(stream);
                        });
                    }
                    else
                    E{
                        return this.gotStream(stream);
                    }
                }
            }).catch (error => {
	            if (error.name == "NotFoundError") {
	                this.getDevices()
	            }
                else {
	                this.callbackError(error.name, error.message);
	            }
	            //throw error for promise
                throw error;
            });
        } else {
            return this.gotStream(stream);
        }
    }
 
    /**
     * Called to get user media (camera and/or mic)
     *
     * @param {*} mediaConstraints : media constaint
     * @param {*} func : callback on success. The stream which is got, is passed as parameter to this function
     * @param {*} catch_error : error is checked if catch_error is true
     */
    navigatorUserMedia(mediaConstraints, func, catch_error) {
		if (mediaConstraints.video == "dummy" && mediaConstraints.audio == "dummy") {
			//if we will have black frame as video and silence as audio, lets add them and return. Can't get user media.
			var stream = new MediaStream();
	
			stream.addTrack(this.getSilentAudioTrack());
			stream.addTrack(this.getBlackVideoTrack());
	
			return new Promise((resolve, reject) => {
	        	resolve(stream);
	    	})
		}
		else
		{
			//We need to replace "dummy" with false before getting user media.
			var tempMediaConstraints = {video: mediaConstraints.video, audio: mediaConstraints.audio};
			
			if (mediaConstraints.audio == "dummy")
			{
				tempMediaConstraints.audio = false;
			}
	
			Iif (mediaConstraints.video == "dummy")
			{
				tempMediaConstraints.video = false;
			}
						
	
			return navigator.mediaDevices.getUserMedia(tempMediaConstraints).then((stream) => {
				//if silence is desired as audio, add it to stream. 
				//Stream shouldn't have audio because audio is set to false in tempMediaConstraints above.   
				if (mediaConstraints.audio == "dummy")
				{
					stream.addTrack(this.getSilentAudioTrack());
				}
	
				//if black frame is desired as video, add it to stream. 
				//Stream shouldn't have video because video is set to false in tempMediaConstraints above.   				
				Iif (mediaConstraints.video == "dummy")
				{
					stream.addTrack(this.getBlackVideoTrack());
				}
				
	            if (typeof func != "undefined" || func != null) {
	                func(stream);
	            }
	            return stream;
	        }).catch(error => {
	            if (catch_error == true) {
	                if (error.name == "NotFoundError") {
	                    this.getDevices()
	                } else {
	                    this.callbackError(error.name, error.message);
	                }
	            } else {
	                Logger.warn(error);
 
	            }
	            //throw error if there is a promise
	            throw error;
	        });
        }
    }
 
    /**
     * Called to get display media (screen share)
     * @param {*} streamId
     * @param {*} mediaConstraints : media constaint
     * @param {*} func : callback on success. The stream which is got, is passed as parameter to this function
     */
    navigatorDisplayMedia(streamId,mediaConstraints, func) {
        return navigator.mediaDevices.getDisplayMedia(mediaConstraints)
            .then((stream) => {
                if (typeof func != "undefined") {
                    func(stream);
                }
                return stream;
            })
            .catch(error => {
                Eif (error.name === "NotAllowedError") {
                    Logger.debug("Permission denied error");
                    this.callbackError("ScreenSharePermissionDenied");
 
                    // If error catched then redirect Default Stream Camera
                    Iif (this.localStream == null) {
                        this.openStream(this.mediaConstraints);
                    } else {
                        this.switchVideoCameraCapture(streamId);
                    }
                }
            });
    }
 
    /**
     * Called to get the media (User Media or Display Media)
     * @param {*} mediaConstraints, media constraints
     * @param {*} streamId, streamId to be used to replace track if there is an active peer connection
     */
    getMedia(mediaConstraints, streamId)
    {
        var audioConstraint = false;
        if (typeof mediaConstraints.audio != "undefined" && mediaConstraints.audio != false) {
            audioConstraint = mediaConstraints.audio;
        }
 
        Iif (this.desktopCameraCanvasDrawerTimer != null) {
            clearInterval(this.desktopCameraCanvasDrawerTimer);
            this.desktopCameraCanvasDrawerTimer = null;
        }
 
        // Check Media Constraint video value screen or screen + camera
        if (this.publishMode == "screen+camera" || this.publishMode == "screen") {
            return this.navigatorDisplayMedia(streamId,mediaConstraints).then(stream => {
                Iif (this.smallVideoTrack)
                    this.smallVideoTrack.stop();
 
				this.stopScreenShareSystemAudioTrack();
				
                return this.prepareStreamTracks(this.mediaConstraints, audioConstraint, stream, streamId);
            });
        }
        else {
            return this.navigatorUserMedia(mediaConstraints).then(stream => {
                Iif (this.smallVideoTrack)
                    this.smallVideoTrack.stop();
 
				this.stopScreenShareSystemAudioTrack();
				
                return this.prepareStreamTracks(this.mediaConstraints, audioConstraint, stream, streamId);
            }).catch(error => {
                if (error.name == "NotFoundError") {
                    this.getDevices()
                } else {
                    this.callbackError(error.name, error.message);
                }
            });
        }
    }
 
 
    /**
     * Open media stream, it may be screen, camera or audio
     */
    openStream(mediaConstraints, streamId) {
        this.mediaConstraints = mediaConstraints;
 
        return this.getMedia(mediaConstraints, streamId).then(() => {
			if (this.mediaConstraints.video != "dummy" && this.mediaConstraints.video != undefined) {
				this.stopBlackVideoTrack();
				this.clearBlackVideoTrackTimer();
			}
 
			if (this.mediaConstraints.audio != "dummy" && this.mediaConstraints.audio != undefined) {
				this.stopSilentAudioTrack();
			}
		});
    }
 
 
 
    /**
     * Closes stream, if you want to stop peer connection, call stop(streamId)
     */
    closeStream() {
        if (this.localStream) {
            this.localStream.getVideoTracks().forEach(function (track) {
                track.onended = null;
                track.stop();
            });
 
            this.localStream.getAudioTracks().forEach(function (track) {
                track.onended = null;
                track.stop();
            });
        }
 
        if (this.videoTrack) {
            this.videoTrack.stop();
        }
 
        if (this.audioTrack) {
            this.audioTrack.stop();
        }
 
        if (this.smallVideoTrack) {
            this.smallVideoTrack.stop();
        }
        if (this.previousAudioTrack) {
            this.previousAudioTrack.stop();
        }
    }
 
 
    /**
     * Checks browser supports screen share feature
     * if exist it calls callback with "browser_screen_share_supported"
     */
    checkBrowserScreenShareSupported() {
        Eif ((typeof navigator.mediaDevices != "undefined" && navigator.mediaDevices.getDisplayMedia) || navigator.getDisplayMedia) {
            this.callback("browser_screen_share_supported");
        }
    };
 
    /**
     * Changes the secondary stream gain in mixed audio mode
     *
     * @param {*} enable
     */
    enableSecondStreamInMixedAudio(enable) {
        Eif (this.secondaryAudioTrackGainNode != null) {
            if (enable) {
                this.secondaryAudioTrackGainNode.gain.value = 1;
            } else {
                this.secondaryAudioTrackGainNode.gain.value = 0;
            }
        }
    }
 
    /**
     * Changes local stream when new stream is prepared
     *
     * @param {*} stream
     */
    gotStream(stream) {
        this.localStream = stream;
        if (this.localVideo) {
            this.localVideo.srcObject = stream;
        }
        this.getDevices();
        this.trackDeviceChange();
        return new Promise((resolve, reject) => {
            resolve();
        })
    }
 
    /**
     * Changes local video and sets localStream as source
     *
     * @param {*} videoEl
     */
    changeLocalVideo(videoEl) {
        this.localVideo = videoEl
        Eif (this.localStream) {
            this.localVideo.srcObject = this.localStream
        }
    }
 
    /**
     * These methods are initialized when the user is muted himself in a publish scenario
     * It will keep track if the user is trying to speak without sending any data to server
     * Please don't forget to disable this function with disableAudioLevelWhenMuted if you use it.
     */
    enableAudioLevelWhenMuted() {
        return new Promise((resolve, reject) => {
            navigator.mediaDevices.getUserMedia({video: false, audio: true})
                .then((stream) => {
                    this.mutedAudioStream = stream;
                    this.mutedSoundMeter = new SoundMeter(this.audioContext, this.volumeMeterUrl);
                    this.mutedSoundMeter.connectToSource(this.mutedAudioStream, (value) => {
                        if (value > 0.1) {
                            this.callback("speaking_but_muted");
                        }
                    }, (e) => {
                        if (e) {
                            reject(e);
                        }
                        this.meterRefresh = setInterval(() => {
                            if (this.mutedSoundMeter .instant.toFixed(2) > 0.1) {
                                this.callback("speaking_but_muted");
                            }
                        }, 200);
                        resolve(null);
                    });
                })
 
            .catch(function (err) {
                Logger.debug("Can't get the soundlevel on mute")
                reject(err);
            });
        })
    }
 
    disableAudioLevelWhenMuted() {
        if (this.meterRefresh != null) {
            clearInterval(this.meterRefresh);
            this.meterRefresh = null;
        }
 
        if (this.mutedSoundMeter != null) {
            this.mutedSoundMeter.stop();
            this.mutedSoundMeter = null;
        }
 
        Iif (this.mutedAudioStream != null) {
            this.mutedAudioStream.getTracks().forEach(function (track) {
                track.stop();
            });
        }
    }
 
 
    /**
	 * @Deprecated. It's not the job of SDK to make these things. It increases the complexity of the code.
     * We provide samples for having these function
     *
     * This method mixed the first stream audio to the second stream audio and
     * @param {*} stream  : Primary stream that contain video and audio (system audio)
     * @param {*} secondStream :stream has device audio
     * @returns mixed stream.
     */
    mixAudioStreams(stream, secondStream) {
        //Logger.debug("audio stream track count: " + audioStream.getAudioTracks().length);
        var composedStream = new MediaStream();
        //added the video stream from the screen
        stream.getVideoTracks().forEach(function (videoTrack) {
            composedStream.addTrack(videoTrack);
        });
 
        var audioDestionation = this.audioContext.createMediaStreamDestination();
 
        if (stream.getAudioTracks().length > 0) {
            this.primaryAudioTrackGainNode = this.audioContext.createGain();
 
            //Adjust the gain for screen sound
            this.primaryAudioTrackGainNode.gain.value = 1;
            var audioSource = this.audioContext.createMediaStreamSource(stream);
 
            audioSource.connect(this.primaryAudioTrackGainNode).connect(audioDestionation);
        } else {
            Logger.debug("Origin stream does not have audio track")
        }
 
        if (secondStream.getAudioTracks().length > 0) {
            this.secondaryAudioTrackGainNode = this.audioContext.createGain();
 
            //Adjust the gain for second sound
            this.secondaryAudioTrackGainNode.gain.value = 1;
 
            var audioSource2 = this.audioContext.createMediaStreamSource(secondStream);
            audioSource2.connect(this.secondaryAudioTrackGainNode).connect(audioDestionation);
        } else {
            Logger.debug("Second stream does not have audio track")
        }
 
        audioDestionation.stream.getAudioTracks().forEach(function (track) {
            composedStream.addTrack(track);
            Logger.debug("audio destination add track");
        });
 
        return composedStream;
    }
 
    /**
     * This method creates a Gain Node stream to make the audio track adjustable
     *
     * @param {*} stream
     * @returns
     */
    setGainNodeStream(stream) {
        Eif (this.mediaConstraints.audio != false && typeof this.mediaConstraints.audio != "undefined") {
            // Get the videoTracks from the stream.
            const videoTracks = stream.getVideoTracks();
 
            // Get the audioTracks from the stream.
            const audioTracks = stream.getAudioTracks();
 
            /**
             * Create a new audio context and build a stream source,
             * stream destination and a gain node. Pass the stream into
             * the mediaStreamSource so we can use it in the Web Audio API.
             */
            this.audioContext = new AudioContext();
            let mediaStreamSource = this.audioContext.createMediaStreamSource(stream);
            let mediaStreamDestination = this.audioContext.createMediaStreamDestination();
            this.primaryAudioTrackGainNode = this.audioContext.createGain();
 
            /**
             * Connect the stream to the gainNode so that all audio
             * passes through the gain and can be controlled by it.
             * Then pass the stream from the gain to the mediaStreamDestination
             * which can pass it back to the RTC client.
             */
            mediaStreamSource.connect(this.primaryAudioTrackGainNode);
            this.primaryAudioTrackGainNode.connect(mediaStreamDestination);
 
            if (this.currentVolume == null) {
                this.primaryAudioTrackGainNode.gain.value = 1;
            } else E{
                this.primaryAudioTrackGainNode.gain.value = this.currentVolume;
            }
 
            /**
             * The mediaStreamDestination.stream outputs a MediaStream object
             * containing a single AudioMediaStreamTrack. Add the video track
             * to the new stream to rejoin the video with the controlled audio.
             */
            const controlledStream = mediaStreamDestination.stream;
 
            for (const videoTrack of videoTracks) {
                controlledStream.addTrack(videoTrack);
            }
            for (const audioTrack of audioTracks) {
                controlledStream.addTrack(audioTrack);
            }
 
            Iif (this.previousAudioTrack !== null) {
                this.previousAudioTrack.stop();
            }
            this.previousAudioTrack = controlledStream.getAudioTracks()[1];
 
            /**
             * Use the stream that went through the gainNode. This
             * is the same stream but with altered input volume levels.
             */
            return controlledStream;
        }
        return stream;
    }
 
    /**
     * Called by User
     * to switch the Screen Share mode
     *
     * @param {*} streamId
     */
    switchDesktopCapture(streamId) {
        this.publishMode = "screen";
 
		let shareMediaConstraints = JSON.parse(JSON.stringify(this.mediaConstraints));
	    Eif (typeof this.mediaConstraints.video != "undefined" && this.mediaConstraints.video != false) {
	      shareMediaConstraints.video = true;
	    }
 
	    //TODO: I don't think we need to get audio again. We just need to switch the video stream
	    return this.getMedia(shareMediaConstraints, streamId);
    }
 
    /**
     * Called by User
     * to switch the Screen Share with Camera mode
     *
     * @param {*} streamId
     */
    switchDesktopCaptureWithCamera(streamId) {
        this.publishMode = "screen+camera";
 
		let shareMediaConstraints = JSON.parse(JSON.stringify(this.mediaConstraints));
	    Eif (typeof this.mediaConstraints.video != "undefined" && this.mediaConstraints.video != false) {
	      shareMediaConstraints.video = true;
	    }
 
	    //TODO: I don't think we need to get audio again. We just need to switch the video stream
	    return this.getMedia(shareMediaConstraints, streamId);
    }
 
    /**
     * This method updates the local stream. It removes existant audio track from the local stream
     * and add the audio track in `stream` parameter to the local stream
     */
    updateLocalAudioStream(stream, onEndedCallback) {
        var newAudioTrack = stream.getAudioTracks()[0];
 
        if (this.localStream != null && this.localStream.getAudioTracks()[0] != null)
        {
            var audioTrack = this.localStream.getAudioTracks()[0];
            if (audioTrack != newAudioTrack)
            {
	            this.localStream.removeTrack(audioTrack);
	            audioTrack.stop();
	            this.localStream.addTrack(newAudioTrack);
            }
        } else Iif (this.localStream != null) {
            this.localStream.addTrack(newAudioTrack);
        } else {
            this.localStream = stream;
        }
 
 
        if (this.localVideo != null) {   //it can be null
            this.localVideo.srcObject = this.localStream;
        }
 
        Iif (onEndedCallback != null) {
            stream.getAudioTracks()[0].onended = function (event) {
                onEndedCallback(event);
            }
        }
 
		if (this.mediaConstraints.audio != "dummy") {
			Iif (this.isMuted) {
	            this.muteLocalMic();
	        } else {
	            this.unmuteLocalMic();
	        }
		}
 
        if (this.localStreamSoundMeter != null) {
            this.enableAudioLevelForLocalStream(this.levelCallback)
        }
    }
 
    /**
     * This method updates the local stream. It removes existant video track from the local stream
     * and add the video track in `stream` parameter to the local stream
     */
    updateLocalVideoStream(stream, onEndedCallback, stopDesktop) {
        Iif (stopDesktop && this.desktopStream != null) {
            this.desktopStream.getVideoTracks()[0].stop();
        }
 
        var newVideoTrack = stream.getVideoTracks()[0];
 
        if (this.localStream != null && this.localStream.getVideoTracks()[0] != null )
        {
            var videoTrack = this.localStream.getVideoTracks()[0];
 
            Eif (videoTrack != newVideoTrack)
            {
	            this.localStream.removeTrack(videoTrack);
	            videoTrack.stop();
	            this.localStream.addTrack(newVideoTrack);
            }
        } else Iif (this.localStream != null) {
            this.localStream.addTrack(newVideoTrack);
        } else {
            this.localStream = stream;
        }
 
        if (this.localVideo) {
            this.localVideo.srcObject = this.localStream;
        }
 
        if (onEndedCallback != null) {
            stream.getVideoTracks()[0].onended = function (event) {
                onEndedCallback(event);
            }
        }
    }
 
    /**
     * Called by User
     * to change video source
     *
     * @param {*} streamId
     * @param {*} deviceId
     */
    switchAudioInputSource(streamId, deviceId) {
        //stop the track because in some android devices need to close the current camera stream
        var audioTrack = this.localStream.getAudioTracks()[0];
        if (audioTrack && isAndroid()) {
            audioTrack.stop();
        }
 
        if(typeof audioTrack == "undefined") {
            Logger.warn("There is no audio track in local stream");
        }
 
        if (typeof deviceId != "undefined") {
            //Update the media constraints
            if (this.mediaConstraints.audio !== true)
                this.mediaConstraints.audio.deviceId = deviceId;
            else
                this.mediaConstraints.audio = {"deviceId": deviceId};
 
            //to change only audio track set video false otherwise issue #3826 occurs on Android
            let tempMediaConstraints = {"video": false, "audio": {"deviceId": deviceId}};
            return this.setAudioInputSource(streamId, tempMediaConstraints, null, deviceId);
        } else {
            return new Promise((resolve, reject) => {
                reject("There is no device id for audio input source");
            });
        }
    }
 
 
    /**
     * This method sets Audio Input Source and called when you change audio device
     * It calls updateAudioTrack function to update local audio stream.
     */
    setAudioInputSource(streamId, mediaConstraints, onEndedCallback) {
        return this.navigatorUserMedia(mediaConstraints, stream => {
            stream = this.setGainNodeStream(stream);
            return this.updateAudioTrack(stream, streamId, mediaConstraints, onEndedCallback);
        }, true);
    }
 
    checkAndStopLocalVideoTrackOnAndroid() {
        //stop the track because in some android devices need to close the current camera stream
        Iif (this.localStream && this.localStream.getVideoTracks().length > 0 && isAndroid()) {
            let videoTrack = this.localStream.getVideoTracks()[0];
            videoTrack.stop();
        }
 
        if(this.localStream === null || this.localStream.getVideoTracks().length === 0) {
            Logger.warn("There is no video track in local stream");
        }
    }
 
    /**
     * Called by User
     * to change video camera capture
     *
     * @param {*} streamId Id of the stream to be changed.
     * @param {*} deviceId Id of the device which will use as a media device
     * @param {*} onEndedCallback callback for when the switching video state is completed, can be used to understand if it is loading or not
     *
     * This method is used to switch to video capture.
     */
    switchVideoCameraCapture(streamId, deviceId, onEndedCallback) {
        this.checkAndStopLocalVideoTrackOnAndroid();
 
        this.publishMode = "camera";
        return navigator.mediaDevices.enumerateDevices().then(devices => {
            for (let i = 0; i < devices.length; i++) {
                if (devices[i].kind == "videoinput") {
                    //Adjust video source only if there is a matching device id with the given one.
                    //It creates problems if we don't check that since video can be just true to select default cam and it is like that in many cases.
                    Iif (devices[i].deviceId == deviceId) {
                        if (this.mediaConstraints.video !== true)
                            this.mediaConstraints.video.deviceId = {exact: deviceId};
                        else
                            this.mediaConstraints.video = {deviceId: {exact: deviceId}};
                        break;
                    }
                }
            }
            ;
            //If no matching device found don't adjust the media constraints let it be true instead of a device ID
            Logger.debug("Given deviceId = " + deviceId + " - Media constraints video property = " + this.mediaConstraints.video);
            return this.setVideoCameraSource(streamId, this.mediaConstraints, onEndedCallback, true, deviceId);
        })
 
    }
	
	
	stopScreenShareSystemAudioTrack() 
	{
		//stopping the audoTrack resolves the screen sharing banner issue https://github.com/ant-media/Ant-Media-Server/issues/7335
		if (this.screenShareAudioTrack) {
			this.screenShareAudioTrack.stop();
            this.screenShareAudioTrack = null;
		}
	}
	
	setGainNodeandUpdateAudioTrack(streamId, stream, mediaConstraints, stopDesktop, onEndedCallback){
		if (stopDesktop && this.secondaryAudioTrackGainNode && stream.getAudioTracks().length > 0) {
 
			//if there is a screen share audio track from browser tab, stop it 
			this.stopScreenShareSystemAudioTrack();
 
			//This audio track update is necessary for such a case:
			//If you enable screen share with browser audio and then
			//return back to the camera, the audio should be only from mic.
			//If, we don't update audio with the following lines,
			//the mixed (mic+browser) audio would be streamed in the camera mode.
			this.secondaryAudioTrackGainNode = null;
			stream = this.setGainNodeStream(stream);
			this.updateAudioTrack(stream, streamId, mediaConstraints, onEndedCallback)
 
		}
	}
	
 
    /**
     * This method sets Video Input Source and called when you change video device
     * It calls updateVideoTrack function to update local video stream.
     */
    setVideoCameraSource(streamId, mediaConstraints, onEndedCallback, stopDesktop) {
		
        return this.navigatorUserMedia(mediaConstraints, stream => {
			
			this.setGainNodeandUpdateAudioTrack(streamId, stream, mediaConstraints, stopDesktop, onEndedCallback);
           
            if (this.cameraEnabled) {
                return this.updateVideoTrack(stream, streamId, onEndedCallback, stopDesktop);
            } else E{
                return this.turnOffLocalCamera();
            }
        }, true);
    }
 
    /**
     * Called by User
     * to switch between front and back camera on mobile devices
     *
     * @param {*} streamId Id of the stream to be changed.
     * @param {*} facingMode it can be "user" or "environment"
     *
     * This method is used to switch front and back camera.
     */
    switchVideoCameraFacingMode(streamId, facingMode) {
        this.checkAndStopLocalVideoTrackOnAndroid();
 
        // When device id set, facing mode is not working
        // so, remove device id
        if (this.mediaConstraints.video !== undefined && this.mediaConstraints.video.deviceId !== undefined) {
            delete this.mediaConstraints.video.deviceId;
        }
 
        var videoConstraint = {
            'facingMode': facingMode
        };
 
        this.mediaConstraints.video = Object.assign({},
            this.mediaConstraints.video,
            videoConstraint);
 
        this.publishMode = "camera";
        Logger.debug("Media constraints video property = " + this.mediaConstraints.video);
        return this.setVideoCameraSource(streamId, {video: this.mediaConstraints.video}, null, true);
    }
 
    /**
     * Updates the audio track in the audio sender
     * getSender method is set on MediaManagercreation by WebRTCAdaptor
     *
     * @param {*} stream
     * @param {*} streamId
     * @param {*} onEndedCallback
     */
    updateAudioTrack(stream, streamId, onEndedCallback) {
        var audioTrackSender = this.getSender(streamId, "audio");
        Iif (audioTrackSender) {
            return audioTrackSender.replaceTrack(stream.getAudioTracks()[0]).then(result => {
                this.updateLocalAudioStream(stream, onEndedCallback);
 
            }).catch(function (error) {
                Logger.debug(error.name);
                throw error;
            });
        } else {
            this.updateLocalAudioStream(stream, onEndedCallback);
            return new Promise((resolve, reject) => {
                resolve();
            });
        }
    }
 
    /**
     * Updates the video track in the video sender
     * getSender method is set on MediaManagercreation by WebRTCAdaptor
     *
     * @param {*} stream
     * @param {*} streamId
     * @param {*} onEndedCallback
     */
    updateVideoTrack(stream, streamId, onEndedCallback, stopDesktop) {
        var videoTrackSender = this.getSender(streamId, "video");
        Iif (videoTrackSender)
        {
            return videoTrackSender.replaceTrack(stream.getVideoTracks()[0]).then(result => {
                this.updateLocalVideoStream(stream, onEndedCallback, stopDesktop);
 
            }).catch(error => {
                Logger.debug(error.name);
            });
        } else {
            this.updateLocalVideoStream(stream, onEndedCallback, stopDesktop);
            return new Promise((resolve, reject) => {
                resolve();
            });
        }
    }
 
    /**
     * If you mute turn off the camera still some data should be sent
     * Tihs method create a black frame to reduce data transfer
     */
    getBlackVideoTrack() {
		this.dummyCanvas.getContext('2d').fillRect(0, 0, 320, 240);
 
		//REFACTOR: it's not good to set to a replacement stream
		this.replacementStream = this.dummyCanvas.captureStream();
		 //We need to send black frames within a time interval, because when the user turn off the camera,
        //player can't connect to the sender since there is no data flowing. Sending a black frame in each 3 seconds resolves it.
        Eif (this.blackFrameTimer == null) {
            this.blackFrameTimer = setInterval(() => {
                this.getBlackVideoTrack();
            }, 3000);
        }
 
        this.blackVideoTrack = this.replacementStream.getVideoTracks()[0];
        return this.blackVideoTrack;
	}
 
    /**
     * Silent audio track
	 */	
	getSilentAudioTrack() {
		Iif (!this.audioContext) {
			this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
		}
 
		// Stop previous track if exists
		this.stopSilentAudioTrack();
 
		// Create oscillator
		this.oscillator = this.audioContext.createOscillator();
		this.oscillator.frequency.value = 0; // technically optional
 
		// Create gain node to mute
		this.gainNode = this.audioContext.createGain();
		this.gainNode.gain.value = 0;
 
		// Connect oscillator -> gain -> destination
		this.oscillator.connect(this.gainNode);
		let dst = this.gainNode.connect(this.audioContext.createMediaStreamDestination());
 
		// Start oscillator
		this.oscillator.start();
 
		// Return silent audio track
		this.silentAudioTrack = dst.stream.getAudioTracks()[0];
		return this.silentAudioTrack;
	}
 
 
 
	stopSilentAudioTrack() {
		if (this.oscillator != null) {
			this.oscillator.stop();
			this.oscillator.disconnect();
			this.oscillator = null;
		}
 
		if (this.silentAudioTrack != null) {
			this.silentAudioTrack.stop();
			this.silentAudioTrack = null;
		}
 
 
	}
 
    /**
     * Called by User
     * turns of the camera stream and starts streaming black dummy frame
     */
    turnOffLocalCamera(streamId) {
		if(this.publishMode == "screen+camera") {
			this.cameraEnabled = false;
			return;
		}
        //Initialize the first dummy frame for switching.
        this.getBlackVideoTrack();
 
        if (this.localStream != null)
        {
            let choosenId;
            Iif (streamId != null || typeof streamId != "undefined") {
                choosenId = streamId;
            } else {
                choosenId = this.publishStreamId;
            }
            this.cameraEnabled = false;
            return this.updateVideoTrack(this.replacementStream, choosenId, null, true);
        }
        else {
 
            return new Promise((resolve, reject) => {
                this.callbackError("NoActiveConnection");
                reject("NoActiveStream");
            });
        }
    }
 
    clearBlackVideoTrackTimer()
    {
		if (this.blackFrameTimer != null) {
            clearInterval(this.blackFrameTimer);
            this.blackFrameTimer = null;
        }
	}
 
	stopBlackVideoTrack()
	{
		 if (this.blackVideoTrack != null) {
			this.blackVideoTrack.stop();
			this.blackVideoTrack = null;
		}
	}
 
    /**
     * Called by User
     * turns of the camera stream and starts streaming camera again instead of black dummy frame
     */
    turnOnLocalCamera(streamId) {
        if(this.publishMode == "screen+camera") {
			this.cameraEnabled = true;
			return;
		}
 
        this.clearBlackVideoTrackTimer();
 
        this.stopBlackVideoTrack();
		
		//make video true if it is "dummy"
		var tempMediaConstraints = {video: this.mediaConstraints.video == "dummy" ? true : this.mediaConstraints.video, 
			audio: this.mediaConstraints.audio};
 
 
        Iif (this.localStream == null) {
            return this.navigatorUserMedia(tempMediaConstraints, stream => {
                this.gotStream(stream);
            }, false);
        }
        //This method will get the camera track and replace it with dummy track
        else {
            return this.navigatorUserMedia(tempMediaConstraints, stream => {
                let choosenId;
                Iif (streamId != null || typeof streamId != "undefined") {
                    choosenId = streamId;
                } else {
                    choosenId = this.publishStreamId;
                }
                this.cameraEnabled = true;
                this.updateVideoTrack(stream, choosenId, null, true);
            }, false);
        }
    }
 
    /**
     * Called by User
     * to mute local audio streaming
     */
    muteLocalMic() {
        this.isMuted = true;
        if (this.localStream != null) {
            this.localStream.getAudioTracks().forEach(track => track.enabled = false);
        } else E{
            this.callbackError("NoActiveConnection");
        }
    }
 
    /**
     * Called by User
     * to unmute local audio streaming
     *
     * if there is audio it calls callbackError with "AudioAlreadyActive" parameter
     */
    unmuteLocalMic() {
		this.isMuted = false;
 
		if (this.mediaConstraints.audio == "dummy") {
			//make audio true if it is "dummy"
			var tempMediaConstraints = {video: this.mediaConstraints.video, 
					audio: this.mediaConstraints.audio == "dummy" ? true : this.mediaConstraints.audio};
            return this.navigatorUserMedia(tempMediaConstraints, stream => {
				this.updateAudioTrack(stream, this.publishStreamId, null);
            }, false);
        }
		
        if (this.localStream != null) {
            this.localStream.getAudioTracks().forEach(track => track.enabled = true);
        } else E{
            this.callbackError("NoActiveConnection");
        }
    }
 
    /**
     * If we have multiple video tracks in coming versions, this method may cause some issues
     */
    getVideoSender(streamId) {
        var videoSender = null;
        if (typeof adapter !== "undefined" && adapter !== null && ((adapter.browserDetails.browser === 'chrome' ||
                (adapter.browserDetails.browser === 'firefox' ||
                    adapter.browserDetails.browser === 'safari' &&
                    adapter.browserDetails.version >= 64)) &&
            'RTCRtpSender' in window &&
            'setParameters' in window.RTCRtpSender.prototype)) {
            videoSender = this.getSender(streamId, "video");
 
        }
        return videoSender;
    }
 
    /**
     * Called by User
     * to set maximum video bandwidth is in kbps
     */
    changeBandwidth(bandwidth, streamId) {
        var errorDefinition = "";
 
        var videoSender = this.getVideoSender(streamId);
 
        if (videoSender != null) {
            const parameters = videoSender.getParameters();
 
            if (!parameters.encodings) {
                parameters.encodings = [{}];
            }
 
            if (bandwidth === 'unlimited') {
                delete parameters.encodings[0].maxBitrate;
            } else {
                parameters.encodings[0].maxBitrate = bandwidth * 1000;
            }
 
            return videoSender.setParameters(parameters)
        } else {
            errorDefinition = "Video sender not found to change bandwidth. Streaming may not be active";
        }
 
        return Promise.reject(errorDefinition);
    };
 
    /**
     * Called by user
     * sets the volume level
     *
     * @param {*} volumeLevel : Any number between 0 and 1.
     */
    setVolumeLevel(volumeLevel) {
        this.currentVolume = volumeLevel;
        if (this.primaryAudioTrackGainNode != null) {
            this.primaryAudioTrackGainNode.gain.value = volumeLevel;
        }
 
        if (this.secondaryAudioTrackGainNode != null) {
            this.secondaryAudioTrackGainNode.gain.value = volumeLevel;
        }
    }
 
    /**
     * Called by user
     * To create a sound meter for the local stream
     *
     * @param {Function} levelCallback : callback to provide the audio level to user
     * @param {*} period : measurement period
     */
    enableAudioLevelForLocalStream(levelCallback) {
        this.levelCallback = levelCallback;
        this.disableAudioLevelForLocalStream();
        this.localStreamSoundMeter = new SoundMeter(this.audioContext, this.volumeMeterUrl);
        Iif (this.audioContext.state !== 'running') {
            return this.audioContext.resume().then(() => {
                return this.localStreamSoundMeter.connectToSource(this.localStream, levelCallback);
            })
        }
        else {
            return this.localStreamSoundMeter.connectToSource(this.localStream, levelCallback);
        }
    }
 
    disableAudioLevelForLocalStream() {
        if (this.localStreamSoundMeter != null) {
            this.localStreamSoundMeter.stop();
            this.localStreamSoundMeter = null;
        }
    }
 
    /**
     * Called by user
     * To change audio/video constraints on the fly
     *
     */
    applyConstraints(newConstraints) {
 
        var constraints = {};
        if (newConstraints.audio === undefined && newConstraints.video === undefined) {
            //if audio or video field is not defined, assume that it's a video constraint
            constraints.video = newConstraints;
            this.mediaConstraints.video = Object.assign({},
                this.mediaConstraints.video,
                constraints.video);
        } else if (newConstraints.video !== undefined) {
            constraints.video = newConstraints.video;
            this.mediaConstraints.video = Object.assign({},
                this.mediaConstraints.video,
                constraints.video);
        }
 
 
        if (newConstraints.audio !== undefined) {
 
            constraints.audio = newConstraints.audio;
 
            this.mediaConstraints.audio = Object.assign({},
                this.mediaConstraints.audio,
                constraints.audio);
        }
 
 
        var promise = null;
        if (constraints.video !== undefined)
        {
            if (this.localStream && this.localStream.getVideoTracks().length > 0) {
                var videoTrack = this.localStream.getVideoTracks()[0];
                promise = videoTrack.applyConstraints(this.mediaConstraints.video);
            } else {
                promise = new Promise((resolve, reject) => {
                    reject("There is no video track to apply constraints");
                });
            }
        }
 
        if (constraints.audio !== undefined) {
            //just give the audio constraints not to get video stream
            //we dont call applyContrains for audio because it does not work. I think this is due to gainStream things. This is why we call getUserMedia again
 
            //use the publishStreamId because we don't have streamId in the parameter anymore
            promise = this.setAudioInputSource(this.publishStreamId, {audio: this.mediaConstraints.audio}, null);
        }
 
        if (this.localStreamSoundMeter != null) {
            this.enableAudioLevelForLocalStream(this.levelCallback)
        }
        return promise;
    }
}