본문 바로가기
프로그래밍/WebRTC

[WebRTC] Real time communication with WebRTC 1

by YuminK 2022. 6. 5.

https://codelabs.developers.google.com/codelabs/webrtc-web

 

1. 소개

WebRTC는 실시간 소통을 위한 오픈 소스 프로젝트로 Web과 Native App에서 사용할 수 있습니다. 

WebRTC는 다양한 JavaScript API를 가지고 있습니다. 

  • getUserMedia(): capture audio and video. // 오디오와 비디오를 캡처합니다.
  • MediaRecorder: record audio and video. // 오디오와 비디오를 기록합니다.
  • RTCPeerConnection: stream audio and video between users. // 유저간 오디오와 비디오를 전송합니다. 
  • RTCDataChannel: stream data between users. // 유저간 데이터를 전송합니다. 

WebRTC는 파이어폭스, 오페라, 데스크톱 크롬, 네이티브 앱에서 사용할 수 있습니다.

 

Signaling이란?

WebRTC는  브라우저간 데이터 스트리밍을 위해 RTCPeerConection을 사용합니다. 이를 위해 Signaling이라는 과정이 필요합니다. Signaling methods와 protocols은 WebRTC에 의해 구체화된 것이 아닙니다. 예제에서는 Socket.io를 사용할 것이며 다양한 대안이 존재합니다.  many alternatives.

 

STUN과 TURN이란?

WebRTC는 peer to peer로 동작하도록 설계되어, 직접적인 경로로 연결할 수 있습니다. 다만, WebRTC는 실제 네트워크 대처하기 위해 설계되어 있습니다.  클라이언트 어플리케이션은 NAT gateways 와 firewalls를 순회하며 peer to peer 네트워크는 직접 연결이 실패할 경우를 대비한 기능이 필요합니다. 이로 인해 WebRTC API에서는 STUN서버를 사용하여 컴퓨터의 IP주소를 얻습니다. TURN 서버는 peer to peer 통신이 실패할 경우에 릴레이 서버로서 사용합니다.  (WebRTC in the real world explains in more detail.)

https://codesk.tistory.com/32

 

WebRTC에서 암호화는 필수사항이며 Javascript API는 안전한 HTTPS나 localhost에서만 사용할 수 있습니다. 시그널링의 경우에는 WebRTC기준에 의해 정의된 것이 아니며 개발자에게 달려 있습니다. 

 

2. 미리보기

WebRTC를 통해 비디오를 얻고 스냅샷을 찍기 위한 앱을 만들어보십시오. 코어 WebRTC API와 Node.js 서버를 사용하여 메시지를 설정하는 방법을 배우게 됩니다. 

  • Get video from your webcam // 웹캠에서 비디오 얻기
  • Stream video with RTCPeerConnection // RTCPeerConnection을 통한 비디오 스트림  
  • Stream data with RTCDataChannel // RTCDataChannel을 통한 데이터 스트림
  • Set up a signaling service to exchange messages // 메시지 교환을 위한 시그널링 설정
  • Combine peer connection and signaling // peer 연결과 시그널링 조합하기
  • Take a photo and share it via a data channel // 사진찍고 데이터 채널을 이용하여 공유하기

필요한 것

  • Chrome 47 or above
  • Web Server for Chrome, or use your own web server of choice.
  • The sample code
  • A text editor
  • Basic knowledge of HTML, CSS and JavaScript

3. 샘플 코드

git clone https://github.com/googlecodelabs/webrtc-web

https://github.com/googlecodelabs/webrtc-web/archive/master.zip

 

clone을 하거나 zip파일로 받으세요. work폴더에 있는 것만 작업을 할 것입니다. 

Step - nn 형태로 있는 것들은 완성된 파일입니다. 

Install and verify web server

While you're free to use your own web server, this codelab is designed to work well with the Chrome Web Server. If you don't have that app installed yet, you can install it from the Chrome Web Store.

Install Web Server for Chrome

After installing the Web Server for Chrome app, click on the Chrome Apps shortcut from the bookmarks bar, a New Tab page, or from the App Launcher:

Click on the Web Server icon:

Next, you'll see this dialog, which allows you to configure your local web server:

Click the CHOOSE FOLDER button, and select the work folder you just created. This will enable you to view your work in progress in Chrome via the URL highlighted in the Web Server dialog in the Web Server URL(s) section.

Under Options, check the box next to Automatically show index.html as shown below:

Then stop and restart the server by sliding the toggle labeled Web Server: STARTED to the left and then back to the right.

Now visit your work site in your web browser by clicking on the highlighted Web Server URL. You should see a page that looks like this, which corresponds to work/index.html:

4. 웹캠에서 비디오 스트림하기

In this step you'll find out how to:

  • Get a video stream from your webcam. // 웹캠에서 비디오 스트림 얻기 
  • Manipulate stream playback. // 스트림 playback 조작하기
  • Use CSS and SVG to manipulate video. // 비디오 조작을 위한 CSS와 SVG 

A complete version of this step is in the step-01 folder.

 

getUserMedia()를 call하면, 브라우저는 유저에게 카메라 권한을 요청합니다. 성공하면, MediaStream이 반환되고 미디어 엘리먼트에 의해 사용될 수 있습니다. 

navigator.mediaDevices.getUserMedia(mediaStreamConstraints)
  .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);
}
function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
}

 

constraints 인자는 어떤 미디어를 얻고자 하는지 정할 수 있습니다. video only, 기본적으로 음성은 false입니다. 

const mediaStreamConstraints = {
  video: true,
};

 

constraints에 해상도 같은 추가적인 요소를 넣을 수 있습니다. 

const hdConstraints = {
  video: {
    width: {
      min: 1280
    },
    height: {
      min: 720
    }
  }
}


만약, getUserMedia()가 성공적이라면 웹캠의 비디오 스트림은 비디오 엘리먼트의 소스로서 설정됩니다.

function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
}

 

  • What does localStream.getVideoTracks() return?

  • Try calling localStream.getVideoTracks()[0].stop().

readyState 값이 달라져 있다.

 

  • Look at the constraints object: what happens when you change it to {audio: true, video: true}?

오디오 하울링 현상

 

  • What size is the video element? How can you get the video's natural size from JavaScript, as opposed to display size? Use the Chrome Dev Tools to check.
    320 * 240
  • Try adding CSS filters to the video element. For example:
video {
  filter: blur(4px) invert(1) opacity(0.5);
}
  • Try adding SVG filters. For example:
video {
   filter: hue-rotate(180deg) saturate(200%);
 }

아바타 ㅋㅋ

 

Best practice

  • Make sure your video element doesn't overflow its container. We've added width and max-width to set a preferred size and a maximum size for the video. The browser will calculate the height automatically:
video {
  max-width: 100%;
  width: 320px;
}

댓글