2013 Google I/O의 WebRTC 소개 영상을 바탕으로 간단하게 정리한 글입니다.
1. WebRTC란?
WebRTC는 "Web Real-Time Communication"의 줄임말이다.
적은 비용으로, 고품질의 비디오와 오디오, 그리고 데이터를 통신하기 위한 기술이다.
WebRTC는 개방형 웹 표준으로 구현되며, 실시간 오디오, 비디오, 그리고 데이터 전송 기능을 구현한 웹 애플리케이션을 쉽게 구현할 수 있도록 모든 주요 브라우저에서 일반 JavaScript API를 제공한다. 이 API는 'to be open source, free, standardized, built into web browsers, and more efficient that existing technologies' 라는 원칙을 가지고 간다.
필요조건
WebRTC를 구현하기 위해서는 3가지 필요조건이 충족되어야 한다:
1) Acquiring audio and video: 비디오와 오디오에 대한 접근 (마이크와 카메라 등의 입력장치에 대한 접근)
2) Communicating audio and video (sending in real-time): 오디오와 비디오의 실시간 통신
3) Communicating arbitrary data: 임의의 데이터 (그 외의 데이터: 파일 등) 통신
API
이를 구현하기 위해 3가지 주요 JavaScript API를 제공하며, 다음과 같다:
1) MediaStream (aka getUserMedia
)

입력장치를 통해 들어온 비디오 혹은 오디오 스트림을 가리킨다.
- Represents a stream of audio and/or video
- Can contain multiple 'tracks'
- Obtain a MediaStream withnavigator.getUserMedia()
navigator.getUserMedia(constraints, successCallback, errorCallback)
// 예시코드 var constraints = {video: true}; function successCallback(stream) { // video.src 설정 var video = document.querySelector("video"); video.src = window.URL.createObjectURL(stream); } function errorCallback(error) { console.log("navigator.getUserMedia error: ", error); } navigator.getUserMedia(constraints, successCallback, errorCallback);
getUserMedia()
를 사용하면 사용자가 기기의 접근 허용 여부를 설정할 수 있도록 브라우저에 뜬다.- constraints: controls the contents of the MediaStream. Media type, resolution, frame rate.
이렇게 받은 미디어를 다른 기기들에 전송하기 위해서는 상대의 브라우저와 연결이 되어 있어야 한다. 이는 RTCPeerConnection을 통해 이루어진다.
2) RTCPeerConnection

"Audio and video communication between peers"
peer 간의 스트리밍 데이터의 통신이 안정적이고 효율적으로 이루어지도록 해준다.
RTCPeerConnection이 하는 일:
- Signal processing (to remove noise from audio and video)
- Codec handling
- Peer-to-Peer communication (firewall, NAT, ...)
- Security (protect user data)
- Bandwidth management
...
// 예시코드 pc = new RTCPeerConnection(null); pc.onaddstream = gotRemoteStream; pc.addStream(localStream); pc.createOffer(gotOffer); // offer: info on media function gotOffer(desc) { pc.setLocalDescription(desc); sendOffer(desc); } function gotAnswer(desc) { pc.setRemoteDescription(desc); } function gotRemoteStream(e) { attachMediaStream(remoteVideo, e.stream); }
3) RTCDataChannel
"Bidirectional communication of arbitrary data between peers"
Peer 간 connection이 성립되었을 때 arbitrary data를 전송하는 방법을 제공한다. 실시간 채팅이나 파일 전송 등에 이용할 수 있다.
- Sampe API as WebSockets: 웹소켓처럼 작동한다.
- Ultra-low latency
- Unreliable or reliable: UDP vs TCP 느낌으로, 서비스의 목적에 따라 고를 수 있다.
- Secure: 암호화되어 전송
var pc = new webkitRTCPeerConnection(servers, {optional: [{RtpDataChannels: true}]}); pc.ondatachannel = function(event) { receiveChannel = event.channel; // datachannel 받으면 receiveChannel에 설정하고 receiveChannel.onmessage = function(event) { // 메시지를 받으면 (웹소켓처럼)~ document.querySelector("div#receive").innerHTML = event.data; }; }; sendChannel = pc.createDataChannel("sendDataChannel", {reliable: false}); document.querySelector("button#send").onClick = function () { var data = document.querySelector("textarea#send").value; sendChannel.send(data); };
2. STUN and TURN
"P2P in the age of firewalls and NATs"
*NAT: private IP address를 분배하는 역할을 한다.
Public address가 있어야 P2P 연결이 가능하기 때문에 NAT는 직통 커뮤니케이션을 가로막는 요소다.
NAT로 가로막힌 peer 간 통신을 위해 ICE (Interactive Connectivity Establishment) 프레임워크를 사용한다. ICE의 역할은 peer 를 서로 연결해줄 가장 좋은 path 를 찾는 것이다. ICE 프레임워크가 제공하는 'ICE candidates'는 public IP 주소, 포트 넘버, 그리고 연결에 관한 다른 정보를 포함하는 객체이다.
NAT이 있는 경우, ICE는 public 주소를 얻기 위해 STUN 서버와 TURN 서버를 이용한다.
Initially, ICE tries to connect peers directly with the lowest possible latency through UDP.
In this process, STUN servers have a single task: to enable a peer behind a NAT to find out its public address and port.
If UDP fails, ICE tries TCP. If direct connection fails—in particular because of enterprise NAT traversal and firewalls—ICE uses an intermediary (relay) TURN server.
STUN (Session Traversal Utilities for NAT)
Tell me what my public IP address is (WebRTC에게 public address를 알려줌)
각 peer가 스스로의 public address를 알도록 사용하는 것이 바로 STUN 서버다.
- Simple server, cheap to run: 비용은 상대적으로 저렴하지만, 100% 보장이 되지 않음
- Data flows peer-to-peer

86%의 확률로 STUN 만으로 통신이 가능하지만, 나머지 14% 정도는 NAT나 방화벽이 너무 복잡해서 뚫지 못하고 실패한다. 이 경우를 위해 대비하는 게 바로 TURN 서버다.
TURN (Traversal Using Relay NAT)
a protocol for relaying network traffic
- Provide a cloud fallback if peer-to-peer communication fails
- Data is sent through server, user server bandwidth
- Ensures the call works in almost all environments: 100% 보장은 되지만, 비싸다.
결과적으로 STUN을 먼저 시도해보고, 안 될 경우 TURN을 사용하여 ICE candidates를 얻는다.
또한, STUN 서버는 public IP 주소를 찾고 나면 더이상 연결에 관여하지 않지만, TURN 서버는 WebRTC 연결이 생성된 이후에도 쭉 있어야 한다.
3. Signaling

- a mechanism to coordinate communication and to send control messages
- exchanges connection signals (ICE candidates, Session description, etc.) between the two peers that intend to be connected.
다음과 같은 세 종류의 정보를 주고 받는다:
- Session control messages: to initialize or close communication and report errors.
- Network configuration: to the outside world, what's your computer's IP address and port?
- Media capabilities: what codecs and resolutions can be handled by your browser and the browser it wants to communicate with
Signaling에서 peer끼리 정보를 교환하기 위해 사용해야 하는 프로토콜은 없다. 개발자들이 필요와 목적에 따라 메시징 프로토콜을 선택할 수 있다.
Peer 끼리 네트워크 정보를 주고받아 connection을 만들고, Session Description Protocol(SDP)로 ICE candidates와 Session Description을 (같이 혹은 별도로) 담아 offer와 answer을 교환하여 media configuration 정보를 주고받는 단계가 이어진다.
즉, 'acquisition and exchange of network and media information' 이 이루어지는 단계이며, 이를 'signaling'이라 부른다.
서로서로가 Session Description을 받아 저장하면 브라우저에서 서로에게 미디어를 전송하기 위한 webRTC media link를 시작할 수 있다.
※ Session Description 에는 session information, time description, media description 등이 있다.
4. Security throughout WebRTC
- Mandatory encryption for media and data
- Secure UI, explicit opt-in: 사용자가 명시적으로 허용해야만 카메라/마이크에 접근 가능
- Sandboxed, no plugins: Chrome sandbox 안에서 동작한다.

5. Architectures
참여자의 수에 따른 구성 방법은 다음과 같다:
1) Mesh: small N-way call

모든 참여자가 다른 모든 참여자들과 연결된 형태.
서버 없이 단순하지만, CPU 와 bandwidth 비용이 든다.
전송하려는 media에 따라 이 구조는 굉장히 제한적이다.
2) Star: medium N-way call

"pick the most capable device to become the focus for the call"
focus는 data를 카피해서 모든 다른 endpoint들에 전송하는 역할을 함.
3) MCU: large N-way call
"most robust, recommended"

MCU(multi-point control unit)을 사용한다.
MCU란, 대량 오디오 혹은 비디오 데이터를 relay 하기 위해 만들어진 서버이다 (a server which is custom-made for relaying large amounts of audio and video).
하나의 endpoint에 문제 생겨도 전체 연결에는 영향이 미치지 않는 성격의 구조다.
참고
- [WebRTC] WebRTC란?
- Get Started with WebRTC
- [공식 홈페이지] WebRTC
- [공식 홈페이지] WebRTC 시작하기
- [Youtube] Real-time communication with WebRTC: Google I/O 2013 ⭐
- Understanding Web Real-Time Communication (WebRTC) ⭐
실습링크: https://codelabs.developers.google.com/codelabs/webrtc-web/#0
'웹 > Web' 카테고리의 다른 글
HTTPS와 SSL/TLS (0) | 2022.03.24 |
---|