WebRTC video streaming is not in chrome
Published: 2023-05-03 13:31:03

why following code can not stream video on chrome                           

```
> // peer connection
> var pc = null;
> // data channel
> var dc = null, dcInterval = null;
> // Check if the preference is currently disabled
> // if (!navigator.userAgent.includes("Firefox/") || !Services.prefs.getBoolPref("media.devices.insecure.enabled")) {
> //     // If using Firefox or the preference is not enabled, set it to true
> //     Services.prefs.setBoolPref("media.devices.insecure.enabled", true);
> //   }
> // // Check if the preference is currently disabled
> // if (!navigator.userAgent.includes("Firefox/") || !Services.prefs.getBoolPref("media.getusermedia.insecure.enabled")) {
> //     // If using Firefox or the preference is not enabled, set it to true
> //     Services.prefs.setBoolPref("media.getusermedia.insecure.enabled", true);
> //   }
> function createPeerConnection() {
>     // var config = {
>     //     sdpSemantics: 'unified-plan'
>     // };
>     var config = {
>         iceServers: [
>           { urls: "stun:x.x.x.x:443" },
>           { 
>             urls: "turn:x.x.x.x:443",
>             username: "xx",
>             credential: "xx@xx#xx"
>           }
>         ]
>     };
>     pc = new RTCPeerConnection(config);
>     
>     // connect audio / video
>     pc.addEventListener('track', function(evt) {
>         if (evt.track.kind == 'video')
>             document.getElementById('video').srcObject = evt.streams[0];
>     });
>     return pc;
> }
> function negotiate() {
>     return pc.createOffer().then(function(offer) {
>         return pc.setLocalDescription(offer);
>     }).then(function() {
>         // wait for ICE gathering to complete
>         return new Promise(function(resolve) {
>             if (pc.iceGatheringState === 'complete') {
>                 resolve();
>             } else {
>                 function checkState() {
>                     if (pc.iceGatheringState === 'complete') {
>                         pc.removeEventListener('icegatheringstatechange', checkState);
>                         resolve();
>                     }
>                 }
>                 pc.addEventListener('icegatheringstatechange', checkState);
>             }
>         });
>     }).then(function() {
>         var offer = pc.localDescription;
>         var csrftoken = getCookie('csrftoken');
>         var codec;
>         codec = "default"; 
>         if (codec !== 'default') {
>             offer.sdp = sdpFilterCodec('video', codec, offer.sdp);
>         }
>         return fetch('http://127.0.0.1:8081/liveness_detect', {            
>             body: JSON.stringify({
>                 sdp: offer.sdp,
>                 type: offer.type,
>                 user_id: Math.random().toString(36).substring(2,7),
>                 video_transform:"liveness"
>             }),
>             headers: {
>                 'Content-Type': 'application/json',
>                 'X-CSRFToken':  csrftoken,
>                 "Access-Control-Allow-Origin": "http://127.0.0.1:8081",
>             },
>             method: 'POST',
>             mode: "cors"
>         });
>     }).then(function(response) {
>         return response.json();
>     }).then(function(answer) {
>         // return pc.setRemoteDescription(answer);
>         return pc.setRemoteDescription(new RTCSessionDescription(data));
>     }).catch(function(e) {
>         alert(e);
>     });
> }
> function start() {
>     document.getElementById('start').style.display = 'none';
>     pc = createPeerConnection();
>     var time_start = null;
>     function current_stamp() {
>         if (time_start === null) {
>             time_start = new Date().getTime();
>             return 0;
>         } else {
>             return new Date().getTime() - time_start;
>         }
>     }
>     if (true){
>         var parameters = JSON.parse('{"ordered": true}');
>         dc = pc.createDataChannel('chat', parameters);
>         dc.onclose = function() {
>             clearInterval(dcInterval);
>         };
>         dc.onopen = function() {
>             dcInterval = setInterval(function() {
>                 var message = 'ping ' + current_stamp();
>                 dc.send(message);
>             }, 1000);
>         };
>         dc.onmessage = function(evt) {
>             
>             if (evt.data.substring(0, 4) === 'pong') {
>                 var elapsed_ms = current_stamp() - parseInt(evt.data.substring(5), 10);
>                 document.getElementById('msg').textContent = evt.data.split('|')[1].trim();
>                 console.log("******************** datachannel_stop_199",evt.data.split('|')[1].trim())
>                 var is_stop = evt.data.split('|')[2].trim();
>                 if (is_stop == '1'){
>                     stop();
>                     console.log("******************** datachannel_stop",evt.data.split('|')[1].trim())
>                     document.getElementById('start').style.display = 'block';
>                 }
>             }
>         };
>     }
>     var constraints = {
>         audio: false,
>         video: false
>     };
>     if (true){
>         var resolution ="";
>         if (resolution) {
>             resolution = resolution.split('x');
>             constraints.video = {
>                 width: parseInt(resolution[0], 0),
>                 height: parseInt(resolution[1], 0)
>             };
>         } else {
>             // constraints.video = true;
>             constraints.video = {
>                 width: 320, // 23/04/2023 - gagani
>                 height: 240
>             };
>             
>         }
>     }
>     if (constraints.audio || constraints.video) {
>         if (constraints.video) {
>             document.getElementById('media').style.display = 'block';
>         }
>         navigator.mediaDevices.getUserMedia(constraints)
>         .then(function(stream) {
>             stream.getTracks().forEach(function(track) {
>                 pc.addTrack(track, stream);
>             });
>             return negotiate();
>         }, function(err) {
>             alert('Could not acquire media: ' + err);
>         });
>             
>     } else {
>         negotiate();
>     }
>     document.getElementById('stop').style.display = 'inline-block';
> }
> function stop() {
>     document.getElementById('stop').style.display = 'none';
>     console.log("-------------call stop function ----------------------")
>     // close data channel
> //     if (dc) {
> //         dc.close();
> //         dc = null; // 24/04/2023 - gagani
> //     }
> // // 24/04/2023 - gagani
> //     if (pc){
> //         pc.close();
> //         pc = null;
> //     }
>     // close transceivers
>     if (pc.getTransceivers) {
>         pc.getTransceivers().forEach(function(transceiver) {
>             if (transceiver.stop) {
>                 transceiver.stop();
>             }
>         });
>     }
>     // close local audio / video
>     pc.getSenders().forEach(function(sender) {
>         sender.track.stop();
>     });
>     // close peer connection
>     setTimeout(function() {
>         pc.close();
>     }, 500);
> }
> function sdpFilterCodec(kind, codec, realSdp) {
>     var allowed = []
>     var rtxRegex = new RegExp('a=fmtp:(\\d+) apt=(\\d+)\r$');
>     var codecRegex = new RegExp('a=rtpmap:([0-9]+) ' + escapeRegExp(codec))
>     var videoRegex = new RegExp('(m=' + kind + ' .*?)( ([0-9]+))*\\s*$')
>     
>     var lines = realSdp.split('\n');
>     var isKind = false;
>     for (var i = 0; i < lines.length; i++) {
>         if (lines[i].startsWith('m=' + kind + ' ')) {
>             isKind = true;
>         } else if (lines[i].startsWith('m=')) {
>             isKind = false;
>         }
>         if (isKind) {
>             var match = lines[i].match(codecRegex);
>             if (match) {
>                 allowed.push(parseInt(match[1]));
>             }
>             match = lines[i].match(rtxRegex);
>             if (match && allowed.includes(parseInt(match[2]))) {
>                 allowed.push(parseInt(match[1]));
>             }
>         }
>     }
>     var skipRegex = 'a=(fmtp|rtcp-fb|rtpmap):([0-9]+)';
>     var sdp = '';
>     isKind = false;
>     for (var i = 0; i < lines.length; i++) {
>         if (lines[i].startsWith('m=' + kind + ' ')) {
>             isKind = true;
>         } else if (lines[i].startsWith('m=')) {
>             isKind = false;
>         }
>         if (isKind) {
>             var skipMatch = lines[i].match(skipRegex);
>             if (skipMatch && !allowed.includes(parseInt(skipMatch[2]))) {
>                 continue;
>             } else if (lines[i].match(videoRegex)) {
>                 sdp += lines[i].replace(videoRegex, '$1 ' + allowed.join(' ')) + '\n';
>             } else {
>                 sdp += lines[i] + '\n';
>             }
>         } else {
>             sdp += lines[i] + '\n';
>         }
>     }
>     return sdp;
> }
> function escapeRegExp(string) {
>     return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
> }
> function getCookie(name) {
>     let cookieValue = null;
>     if (document.cookie && document.cookie !== '') {
>         const cookies = document.cookie.split(';');
>         for (let i = 0; i < cookies.length; i++) {
>             const cookie = cookies[i].trim();
>             // Does this cookie string begin with the name we want?
>             if (cookie.substring(0, name.length + 1) === (name + '=')) {
>                 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
>                 break;
>             }
>         }
>     }
>     return cookieValue;
> }
```