JSFiddle - React, Tailwind, and code Playground
HTML
<div id="no-support-banner" style="background-color: red">
<h1> Browser does not support insertable streams </h1>
</div>
Browser base64 Session Description<br />
<textarea id="localSessionDescription" readonly="true"></textarea> <br />
Golang base64 Session Description<br />
<textarea id="remoteSessionDescription"> </textarea> <br/>
<button onclick="window.startSession()"> Start Session </button> Decrypt Video <input type="checkbox" checked="checked" onclick="window.toggleDecryption()"/> <br />
<br />
Video<br />
<video id="remote-video" playsinline autoplay controls style="width: 640; height: 480"></video> <br />
Logs<br />
<div id="div"></div>
JavaScript
/* eslint-env browser */
// cipherKey that video is encrypted with
const cipherKey = 0xAA
let pc = new RTCPeerConnection({encodedInsertableStreams: true, forceEncodedVideoInsertableStreams: true})
let log = msg => {
document.getElementById('div').innerHTML += msg + '<br>'
}
// Offer to receive 1 video
let transceiver = pc.addTransceiver('video')
// The API has seen two iterations, support both
// In the future this will just be `createEncodedStreams`
let receiverStreams = getInsertableStream(transceiver)
// boolean controlled by checkbox to enable/disable encryption
let applyDecryption = true
window.toggleDecryption = () => {
applyDecryption = !applyDecryption
}
// Loop that is called for each video frame
const reader = receiverStreams.readable.getReader()
const writer = receiverStreams.writable.getWriter()
reader.read().then(function processVideo({ done, value }) {
let decrypted = new DataView(value.data)
if (applyDecryption) {
for (let i = 0; i < decrypted.buffer.byteLength; i++) {
decrypted.setInt8(i, decrypted.getInt8(i) ^ cipherKey)
}
}
value.data = decrypted.buffer
writer.write(value)
return reader.read().then(processVideo)
})
// Fire when remote video arrives
pc.ontrack = function (event) {
document.getElementById('remote-video').srcObject = event.streams[0]
document.getElementById('remote-video').style = ""
}
// Populate SDP field when finished gathering
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
pc.onicecandidate = event => {
if (event.candidate === null) {
document.getElementById('localSessionDescription').value = btoa(JSON.stringify(pc.localDescription))
}
}
pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log)
window.startSession = () => {
let sd = document.getElementById('remoteSessionDescription').value
if (sd === '') {
return alert('Session Description must not be empty')
}
try {
pc.setRemoteDescription(new...