How to have multiple websocket RTSP streams?

1.8k Views Asked by At

After spending some time reading various open-source projects on how to develop RTSP and WebSocket streams, I've almost built a simple project that allows me to display multiple streams on the page.

I have a working example of just one stream working with the code below. A single URL in an array is sent to the client via WebSocket and with JSMPeg, it displays it with some success.

However, I'm not sure how to build this where I have multiple sockets with an RTSP stream in each one and how to give each socket url it's own id. The idea is to encrypt the URL and when the client requests the list of streams, send back that as a socket id, and with JSMPeg, request that data.

Server:

class Stream extends EventEmitter {
  constructor() {
    super();
    this.urls = ["rtsp://someIPAddress:554/1"];
    this.urls.map((url) => {
      this.start(url);
    });
  }
  start(url) {
    this.startStream(url);
  }
  setOptions(url) {
    const options = {
      "-rtsp_transport": "tcp",
      "-i": url,
      "-f": "mpegts",
      "-codec:v": "mpeg1video",
      "-codec:a": "mp2",
      "-stats": "",
      "-b:v": "1500k",
      "-ar": "44100",
      "-r": 30,
    };
    let params = [];
    for (let key in options) {
      params.push(key);
      if (String(options[key]) !== "") {
        params.push(String(options[key]));
      }
    }
    params.push("-");
    return params;
  }
  startStream(url) {
    const wss = new WebSocket.Server({ port: 8080 });
    this.child = child_process.spawn("ffmpeg", this.setOptions(url));
    this.child.stdout.on("data", (data) => {
      wss.clients.forEach((client) => {
        client.send(data);
      });
      return this.emit("data", data);
    });
  }
}

const s = new Stream();
s.on("data", (data) => {
  console.log(data);
});

In the constructor, there's an array of URLs, while I only have one here, i'd like to add multiple. I create a websocket and send that back. What I'd like to do is encrypt that URL with Crypto.createHash('md5').update(url).digest('hex') to give it it's own ID and create a websocket based on that id, send the data to that websocket and send that with a list of other id's to the client.

client:

  <canvas id="video" style="width: 100%"></canvas>
  <script type="text/javascript">
    var player = new JSMpeg.Player("ws://localhost:8080", {
      loop: true,
      autoplay: true,
      canvas: document.getElementById("video"),
    });
  </script>

What I'd like to do here is request from /api/streams and get back an array of streams/socket id's and request them from the array.

But how do I open up multiple sockets with multiple URLs?

0

There are 0 best solutions below