deepch / RTSPtoWeb

RTSP Stream to WebBrowser
MIT License
1.17k stars 284 forks source link

Webrtc connection close with toggle button #404

Open gtirth opened 7 months ago

gtirth commented 7 months ago

Issue: I am trying to create my own html page to display the webrtc video. It is working well but the only problem that i have is it is always on. I would like to add a toggle button to start the webrtc connection and close it to save the bandwidth. I was able to add a toggle button to have it paused at the loading of the page and start with the toggle button but when i try to close it does not close the video. i can still see the video even after closing the data channel

Code:

var video_toggle = document.getElementById("video_toggle");

video_toggle.addEventListener("change", function () {
  function startPlay (videoEl, url) {
    const webrtc = new RTCPeerConnection({
      iceServers: [{
        urls: ['stun:stun.l.google.com:19302']
      }],
      sdpSemantics: 'unified-plan'
    })
    webrtc.ontrack = function (event) {
      console.log(event.streams.length + ' track is delivered')
      videoEl.srcObject = event.streams[0]
      videoEl.play()
    }
    webrtc.addTransceiver('video', { direction: 'sendrecv' })
    webrtc.onnegotiationneeded = async function handleNegotiationNeeded () {
      const offer = await webrtc.createOffer()

      await webrtc.setLocalDescription(offer)

      fetch(url, {
        method: 'POST',
        body: new URLSearchParams({ data: btoa(webrtc.localDescription.sdp) })
      })
        .then(response => response.text())
        .then(data => {
          try {
            webrtc.setRemoteDescription(
              new RTCSessionDescription({ type: 'answer', sdp: atob(data) })
            )
          } catch (e) {
            console.warn(e)
          }
        })
    }

    const webrtcSendChannel = webrtc.createDataChannel('rtsptowebSendChannel')
    webrtcSendChannel.onopen = (event) => {
      console.log(`${webrtcSendChannel.label} has opened`)
      webrtcSendChannel.send('ping')
    }
    webrtcSendChannel.onclose = (_event) => {
      console.log(`${webrtcSendChannel.label} has closed`)
      // startPlay(videoEl, url)
    }
    webrtcSendChannel.onmessage = event => console.log(event.data)

  }

  const videoEl = document.querySelector('#webrtc-video')
  const webrtcUrl = document.querySelector('#webrtc-url').value

  if (video_toggle.checked){
  startPlay(videoEl, webrtcUrl)
  }

 else {
    const webrtc = new RTCPeerConnection({
    iceServers: [{
      urls: ['stun:stun.l.google.com:19302']
    }],
    sdpSemantics: 'unified-plan'
  })

  let webrtcSendChannel = webrtc.createDataChannel('rtsptowebSendChannel')
  webrtcSendChannel.close();
  webrtcSendChannel.onclose = (_event) => {
    console.log(`${webrtcSendChannel.label} has closed`)
  }
webrtc.close()
}

})

Expected Behaviour: to be able to stop bandwidth consumption on the server side with the toggle off