Convert Webcam into CCTV with PeerJS

Article


author small image Siva Kishore G
Posted : 01 Aug 2023
Modified : 01 Aug 2023
Expert Developers
WebCamera mounted on laptop

Introduction

PeerJS utilizes the WebRTC implementation within the browser, offering a comprehensive, customizable, and user-friendly API for establishing peer-to-peer connections. Armed only with an ID, a peer can effortlessly create a data or media stream connection to another remote peer.

Today, we will learn how to access the feed of a local webcamera remotely. This can lead to illegal activities, including hacking or any unauthorized access to someone's privacy, such as remotely accessing someone's webcam without their consent. So I strongly recommend caution.

What is Peer To Peer ?

A peer-to-peer (P2P) connection is a direct communication link established between two or more devices, such as computers or mobile devices, without the need for a central server. In a P2P network, each device connected to the network is considered a "peer," and these peers can communicate directly with one another. Unlike traditional client-server architectures, where a central server facilitates communication between clients (devices), P2P connections allow devices to interact with each other on an equal footing, sharing resources and information without the need for intermediaries.

P2P Connection

Key characteristics of peer-to-peer connections:

  • Decentralization: P2P networks do not rely on a central server to coordinate communication. Instead, each peer can directly communicate with other peers.
  • Direct Communication: Peers communicate directly with one another, which can lead to faster data transfer and reduced latency.
  • Resource Sharing: Peers in a P2P network can share various resources, such as files, processing power, or bandwidth.
  • Scalability: P2P networks can be highly scalable since the addition of new peers can enhance the overall network capacity and resilience.
  • Redundancy: The decentralized nature of P2P networks can provide some degree of redundancy, as there is no single point of failure.
  • Security Concerns: P2P connections may present certain security challenges, as direct communication between peers could potentially expose vulnerabilities or open channels for unauthorized access.

P2P connections have found various applications, including file sharing, content distribution, communication platforms, online gaming, and decentralized systems like blockchain networks. WebRTC (Web Real-Time Communication) is a technology that enables P2P connections directly within web browsers, allowing real-time audio, video, and data sharing between users without requiring the use of centralized servers.

Architecture

P2P is highly advantageous in this scenario since it eliminates the need for a large server to handle the stream feed distribution to users. Instead, the server serves as a token generator, which users will utilize to establish connections with their intended peers. The diagram below illustrates this process, where User 1 and User 2 exchange unique tokens, leading to a direct connection between their local routers. In this setup, the feed quality relies on each user's individual bandwidth capacity.

P2P Architecture

Requisites

  • Webcam.
  • Internet Connection.
  • Local Express NodeJS Server.
  • Remote Server.
  • Domain with SSL.
  • Knowledge in WebRTC / PeerJS Duh!

PeerJS in action

In this situation, we require a unidirectional camera feed from a local computer, accessible over the internet. To ensure security against unauthorized access, we implement a secret key, which is essentially the ID assigned to the peer connection for the sake of simplicity.

Current Architecture

Local Server

var express = require('express');
var app = express();
app.disable('x-powered-by');
var bodyParser = require('body-parser');
app.use(bodyParser.json({
  limit: "20mb"
}));
app.use(bodyParser.urlencoded({
  limit: "20mb",
  extended: true,
  parameterLimit: 50000
}));


var handlebars = require('express-handlebars').create({
  defaultLayout: 'main'
})

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.use('/static_files', express.static(__dirname + '/static_files'));


app.get('/', (req, res) => {
  res.render("home")
})


app.listen(8222);
console.log("Running on port 8222")
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<div class="container">
    <div class="my-5">
        <div class="text-center">
            <h1 class="h4">Video Feed</h1>
            <video id="videoContainer" autoplay>
                Use this if you want to show the video feed here also
            </video>
        </div>
    </div>
</div>
var peer = new Peer("STRONG_PASSWORD_TYPE_STRING");
peer.on('call', (call) => {
    if ('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices) {
        navigator.mediaDevices.getUserMedia({ video: true, audio : true }).then((stream) => {
            call.answer(stream); // Answer the call with an A/V stream.
        })
    }
})

Remote Server

var video = document.getElementById('videoContainer')
var peer = new Peer();
peer.on('error', (err) => {
    console.log("Some error", err)
})

peer.on('open', (ct) => {

    navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
        var call = peer.call('PASSWORD_TYPE_STRING_USED_PREVIOUSLY',stream, {
            'constraints': {
              'mandatory': {
                'OfferToReceiveAudio': true,
                'OfferToReceiveVideo': true
              },
              offerToReceiveAudio: 1,
              offerToReceiveVideo: 1,
            }
          });
        call.on('stream', function(remoteStream) {
            video.srcObject = remoteStream
        });
    })

})
<style>
    #videoContainer {
    max-width : 320px;
    width:100%;
    max-height: 480px;
    height:100%;
}
</style>
<div class="container">
    <div class="my-5">
        <div class="text-center">
            <h1 class="h4">Video Feed</h1>
            <video id="videoContainer" playsinline autoplay muted controls>
                
            </video>
        </div>
    </div>
</div>

<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>

Conclusion

If the domain lacks SSL, the video feed will not be visible. To enable the video, the video tag should be muted by default; otherwise, it won't function properly. When utilizing the video feed on a local computer, ensure it remains active for as long as needed. For enhanced security, contemplate deploying your own custom PeerJS server.



Post a comment

I promise, I keep it clean *

Comments

Alert SVG Cookie Consent

This website uses cookies and similar technologies, to enhance your browsing experience and provide personalized recommendations. By continuing to use our website, you agree to our Privacy policy.