Skip to content

Commit

Permalink
Make server.js delete old peer connections on the same IP (#118)
Browse files Browse the repository at this point in the history
* Make server.js delete old peer connections on the same IP

* fixes from testing on lovelace

* Include the IP in the request

* Add note about one publisher or subscriber at a time
  • Loading branch information
amalnanavati authored Jan 16, 2024
1 parent be2d0ea commit 961bce4
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 12 deletions.
38 changes: 31 additions & 7 deletions feedingwebapp/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,43 @@ const bodyParser = require('body-parser')
var cors = require('cors')
const webrtc = require('wrtc')

let senderStream = {}
let senderStream = {} // key: topic, value: MediaStream
// NOTE: There is something wrong with the IPs being passed in being
// all or mostly the same. As a result, in essense this only allows
// one publisher or subscriber at a time.
let publishPeers = {} // key: IP4:topic, value: RTCPeerConnection
let subscribePeers = {} // key: IP4:topic, value: RTCPeerConnection

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors())

app.post('/subscribe', async ({ body }, res) => {
console.log('got subscriber on topic: ' + body.topic)
console.log('got subscriber on IP', body.ip, 'for topic', body.topic)

// Configure the peer connection
const peer = new webrtc.RTCPeerConnection({
iceServers: [
{
urls: 'stun:stun.stunprotocol.org'
urls: 'stun:stun1.l.google.com:19302'
}
]
})

// Close any old peers on the same IP address
const topic = body.topic
const key = body.ip + ':' + topic
if (key in subscribePeers) {
const senders = subscribePeers[key].getSenders()
senders.forEach((sender) => subscribePeers[key].removeTrack(sender))
subscribePeers[key].close()
}
subscribePeers[key] = peer

const desc = new webrtc.RTCSessionDescription(body.sdp)
await peer.setRemoteDescription(desc)

// Add the publisher's video stream to the subscriber's peer connection
const topic = body.topic
if (topic in senderStream) {
senderStream[topic].getTracks().forEach((track) => peer.addTrack(track, senderStream[topic]))
}
Expand All @@ -50,19 +65,28 @@ app.post('/subscribe', async ({ body }, res) => {
})

app.post('/publish', async ({ body }, res) => {
console.log('got publisher on topic: ' + body.topic)
console.log('got publisher on IP', body.ip, 'for topic', body.topic)

// Configure the peer connection
const peer = new webrtc.RTCPeerConnection({
iceServers: [
{
urls: 'stun:stun.stunprotocol.org'
urls: 'stun:stun1.l.google.com:19302'
}
]
})

// Send the publisher's video stream to all subscribers on that topic
// Close any old peers on the same IP address
const topic = body.topic
const key = body.ip + ':' + topic
if (key in publishPeers) {
const senders = publishPeers[key].getSenders()
senders.forEach((sender) => publishPeers[key].removeTrack(sender))
publishPeers[key].close()
}
publishPeers[key] = peer

// Send the publisher's video stream to all subscribers on that topic
peer.ontrack = (e) => handleTrackEvent(e, topic)

// Create an answer to the publisher's offer
Expand Down
4 changes: 2 additions & 2 deletions feedingwebapp/src/Pages/Home/VideoFeed.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import PropTypes from 'prop-types'
// Local Imports
import { CAMERA_FEED_TOPIC, REALSENSE_WIDTH, REALSENSE_HEIGHT } from '../Constants'
import { useWindowSize } from '../../helpers'
import { createPeerConnection } from '../../webrtc/webrtc_helpers'
import { createPeerConnection, closePeerConnection } from '../../webrtc/webrtc_helpers'

/**
* Takes in an imageWidth and imageHeight, and returns a width and height that
Expand Down Expand Up @@ -100,7 +100,7 @@ const VideoFeed = (props) => {
peer.addTransceiver('video', { direction: 'recvonly' })

return () => {
peer.close()
closePeerConnection(peer)
}
}, [props.topic, props.webrtcURL, videoRef])

Expand Down
29 changes: 26 additions & 3 deletions feedingwebapp/src/webrtc/webrtc_helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function createPeerConnection(url, topic, onTrackAdded, onConnectionEnd)
const peerConnection = new RTCPeerConnection({
iceServers: [
{
urls: 'stun:stun.stunprotocol.org'
urls: 'stun:stun1.l.google.com:19302'
}
]
})
Expand All @@ -28,9 +28,11 @@ export function createPeerConnection(url, topic, onTrackAdded, onConnectionEnd)
try {
const offer = await peerConnection.createOffer()
await peerConnection.setLocalDescription(offer)
const ip = await getIPAddress()
const payload = {
sdp: peerConnection.localDescription,
topic: topic
topic: topic,
ip: ip
}
console.log('sending payload', payload)
const { data } = await axios.post(url, payload)
Expand All @@ -53,7 +55,7 @@ export function createPeerConnection(url, topic, onTrackAdded, onConnectionEnd)
if (peerConnection.connectionState === 'failed' || peerConnection.connectionState === 'disconnected') {
console.error(peerConnection.connectionState, 'Resetting the PeerConnection')
if (onConnectionEnd) onConnectionEnd()
createPeerConnection()
// peerConnection = createPeerConnection(url, topic, onTrackAdded, onConnectionEnd)
}
console.log('peerConnection.onconnectionstatechange', peerConnection.connectionState)
}
Expand All @@ -69,3 +71,24 @@ export function createPeerConnection(url, topic, onTrackAdded, onConnectionEnd)
return
}
}

/**
* Closes the given peer connection.
* @param {object} peerConnection The RTCPeerConnection to close.
*/
export function closePeerConnection(peerConnection) {
if (!peerConnection) return
console.log('Closing RTCPeerConnection', peerConnection)
if (peerConnection.connectionState !== 'closed') {
const senders = peerConnection.getSenders()
senders.forEach((sender) => peerConnection.removeTrack(sender))
peerConnection.close()
console.log('Closed RTCPeerConnection')
}
}

export async function getIPAddress() {
const res = await axios.get('https://api.ipify.org/?format=json')
console.log(res.data)
return res.data.ip
}

0 comments on commit 961bce4

Please sign in to comment.