2021-05-21
요즘 많이 쓰이는 CCTV는 보통 rtsp를 지원한다.
하지만 rtsp는 웹페이지에서 바로 재생이 안되기 때문에, 따로 서버에서 처리를 해주거나 해야 하는데, 그중에서 Node의 node-rtsp-stream모듈을 사용하는 방법을 알아 보겠다.

우선 FFMPEG를 다운 받아서 시스템 변수에 등록하자(FFMPEG가 설치 안되어 있으면, 에러가 뜬다)
다운로드링크: https://www.gyan.dev/ffmpeg/builds/
위 링크로 들어가서, release의 full 버전을 다운 받으면 된다.
release 다운로드링크: https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z
c:\ 에 압축을 해제한 뒤에, 시스템 변수의 path에 "C:\ffmpeg\bin"식으로 등록 하면 된다.

그러면 이제 본격적으로 시작해 보자.
일단 임의의 디렉토리를 만들고, 해당 디렉토리에 npm으로 node-rtsp-stream와 ws 모듈을 설치한다.
$ mkdir rtsp_test $ cd rtsp_test $ npm install node-rtsp-stream $ npm install ws

그후에 index.js와 test.html파일을 생성후 아래와 같이 소스를 작성한다.

index.js
Stream = require('node-rtsp-stream')
stream = new Stream({
	name: 'name',
	streamUrl: 'rtsp://{아이디}:{비밀번호}@b1ix.iptimecam.com:21176/stream_ch00_1',
	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
	}
})
test.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>

그리고 마지막으로, C:\rtsp_test\node_modules\node-rtsp-stream\mpeg1muxer.js 파일로 들어가서, 23번째줄 부분을 아래처럼 바꿔 준다.
  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',
    '-b:v', '1000k',
    '-maxrate', '1000k',
    '-bufsize', '1000k',
     '-an', '-r', '24',
    // additional ffmpeg options go here
    ...this.additionalFlags,
    '-'
  ]
위에 주석처리 되어 있는 부분이 원래 소스이고, 그 아래 있는 소스가 새롭게 바꿔준 부분이다.

이제 노드를 실행 시키고, test.html 파일을 열어보면 해당 스트리밍이 재생되고 있을 것이다.
$ node index.js