File size: 1,738 Bytes
2f3bab9
 
64a031b
 
2f3bab9
64a031b
 
2f3bab9
64a031b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3bab9
64a031b
1be9c7c
 
64a031b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3bab9
64a031b
47d4d30
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
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const webrtc = require('wrtc');

// Instead of one global stream, keep one per room
const roomStreams = {};  // { [roomId]: MediaStream }

app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Consumer endpoint: front-end must POST { sdp, roomId }
app.post("/consumer", async ({ body }, res) => {
  const { sdp, roomId } = body;
  const stream = roomStreams[roomId];
  if (!stream) {
    return res.status(404).json({ error: "No broadcast for room " + roomId });
  }

  const peer = new webrtc.RTCPeerConnection({
    iceServers: [{ urls: "stun:stun.stunprotocol.org" }]
  });

  // add the broadcaster’s tracks for this room
  stream.getTracks().forEach(track => peer.addTrack(track, stream));

  await peer.setRemoteDescription(new webrtc.RTCSessionDescription(sdp));
  const answer = await peer.createAnswer();
  await peer.setLocalDescription(answer);

  res.json({ sdp: peer.localDescription });
});

// Broadcast endpoint: front-end must POST { sdp, roomId }
app.post("/broadcast", async ({ body }, res) => {
  const { sdp, roomId } = body;
  const peer = new webrtc.RTCPeerConnection({
    iceServers: [{ urls: "stun:stun.stunprotocol.org" }]
  });

  peer.ontrack = ({ streams }) => {
    // store the incoming stream under its roomId
    roomStreams[roomId] = streams[0];
  };

  await peer.setRemoteDescription(new webrtc.RTCSessionDescription(sdp));
  const answer = await peer.createAnswer();
  await peer.setLocalDescription(answer);

  res.json({ sdp: peer.localDescription });
});

app.listen(7860, () => console.log('SFU server running on port 5000'));