본문 바로가기

Etc/RTSP

RTSP 웹 스트리밍 개발 - 1 -

1. VMS(Video Management System)으로 부터 CCTV들의 RTSP를 받아 웹 브라우저에서 출력해야하는 임무를 받게 되었다.(왜 협력해주는 vms에서 rtsp만 지원해주는지는 몰?루)

 

2. 여러 시도와 폭풍 구글링 끝에 웹브라우저에서는 RTSP URL을 직접적으로 출력할 수 없음을 알게됨...(참고 :  https://dvnest.com/user_20210809/)

 

3. 구글링 해보니 그래도 여러가지 방법이 있었음. (ffmpeg... websocket... webrtc... 등등)

 

4. 하지만 본인은 한낱 1년도 안된 신입에 c++과 unity(c#) 개발자인데.. 온통 자료들이 javascript 와 golang임.... 뭔가 매우 귀차는 일을 맡게된것 같음...

 

5. 그래도 일단 샘플코드들이 있으니 시도는 해봄..

 

6. 가장먼저 시작한 샘플은 ffmpegnode-rtsp-stream을 이용하여 샘플을 테스트 해봄.(참고: http://www.b1ix.net/419)


(npm은 기본적으로 설치 되어 있다고 가정함...설치 안되있으면 여기참고...)

 

먼저 ffmpeg 라는 인코딩, 디코딩 프로젝트를 설치 해야함.(다운로드 링크: https://www.gyan.dev/ffmpeg/builds/)

 

다운로드 링크에서 그냥 최신 release-full버전 받은후 압축해제를 한뒤에, (다운로드 경로)/ffmpeg/bin/ 를 시스템 변수 PATH목록에 추가시켜준다.

 

다음으로 cmd 창에서 프로젝트를 만들 경로로 들어간뒤 아래의 명령어를 차례로 실행한다.

 

$ mkdir rtsp_test
$ cd rtsp_test
$ npm install node-rtsp-stream
$ npm install ws

 

다음으로 index.html과 index.js를 생성한뒤 각각 아래의 코드를 입력해준다.

 

index.js

Stream = require('node-rtsp-stream')
stream = new Stream({
	name: 'name',
	streamUrl: 'rtsp://{아이디}:{비밀번호}@{rtps url}',
	wsPort: 9999,
	ffmpegOptions: { // options ffmpeg flags
		'-stats': '', // an option with no neccessary value uses a blank string
		'-r': 30 // options with required values specify the value after the key
	}
})

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jsmpeg/0.1/jsmpg.js"></script>
</head>
<body>

<canvas></canvas>

<script>
var client = new WebSocket('ws://localhost:9999');
var canvas = document.querySelector('canvas');
var player = new jsmpeg(client, {
	canvas: canvas
});
</script>
</body>
</html>

 

그리고 rtsp_test\node_modules\node-rtsp-stream\mpeg1muxer.js에서 옵션을 아래와 같이 수정해준다.

this.spawnOptions = [
    // "-i",
    // this.url,
    // '-f',
    // 'mpegts',
    // '-codec:v',
    // 'mpeg1video',
    // // additional ffmpeg options go here
    // ...this.additionalFlags,
    // '-'
    
    "-rtsp_transport", "tcp", "-i",
    this.url,
    '-f',
    'mpeg1video',
    //additional ffmpeg options go here
    ...this.additionalFlags,
    '-'
]

 

마지막으로 다시 cmd창에서 node를 실행해주면 스트리밍이 시작된다.

 

$ node index.js

 

스트리밍이 시작되면, index.html에서 영상이 재생되는것을 확인할 수 있다.

 

테스트용 rtsp링크는 공공데이터 포털에서 충청남도 천안시_교통정보 CCTV를 사용해봤다.(본인은 천안사람 아님...)

https://www.data.go.kr/data/15063717/fileData.do

 

충청남도 천안시_교통정보 CCTV_20220922

충청남도 천안시 관내 교통정보cctv에 대한 데이터입니다. 천안시 관내 교통정보cctv(CCTV관리번호, 경도, 위도, 설치위치명 등)의 항목들을 제공합니다.

www.data.go.kr

실행화면

 

성공이다!

 

하지만 임무를 완수 하려면 아직 멀었다....ㅠㅠ


다음에는 고정으로 rtsp url을 할당해주는 부분을 동적으로 할당해주도록 바꿔봐야 겠다.