Async WebRTC Demo
HTML
<script src="https://webrtchacks.github.io/adapter/adapter-latest.js"></script>
<video id="video1" width="160" height="120" autoplay muted></video>
<video id="video2" width="160" height="120" autoplay></video><br>
<video id="video3" width="160" height="120" autoplay></video><br>
<div id="div"></div>
JavaScript
const console = {
log: msg => div.innerHTML += msg + "<br>"
};
const pc1 = new RTCPeerConnection(),
pc2 = new RTCPeerConnection();
(async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {width: 1280, height: 720},
audio: false
});
for (const track of stream.getTracks()) {
pc1.addTrack(track, stream);
}
video1.srcObject = stream;
} catch (e) {
console.log(e);
}
})();
function transform(frame, controller) {
console.log(frame.timestamp/1000)
// Cropping from an existing video frame is supported by the API in Chrome 94+.
const newFrame = new VideoFrame(frame, {
visibleRect: {
x: 0,
width: 320,
y: 0,
height: 180,
}
});
controller.enqueue(newFrame);
frame.close();
}
pc2.ontrack = async (event) => {
const stream = event.streams[0]
video2.srcObject = stream;
const [track] = stream.getTracks();
const processor = new MediaStreamTrackProcessor({track});
const {readable} = processor;
const generator = new MediaStreamTrackGenerator({kind: 'video'});
const {writable} = generator;
video3.srcObject = new MediaStream([generator]);
readable
.pipeThrough(new TransformStream({transform}))
.pipeTo(writable);
}
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = () => console.log(pc1.iceConnectionState);
pc1.onnegotiationneeded = async () => {
await pc1.setLocalDescription();
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription();
await pc1.setRemoteDescription(pc2.localDescription);
}