1. 개요
RTSP(Real-Time Streaming Protocol)는 실시간 스트리밍 데이터의 제어를 위해 설계된 네트워크 프로토콜입니다. 주로 미디어 서버와 클라이언트 간의 통신에서 사용되며 IP 카메라, VOD(Video on Demand), 라이브 스트리밍에 사용된다.
RTSP(Real-Time Streaming Protocol)와 유사한 RTMP(Real-Time Messaging Protocol)도 또한 스트리밍 미디어를 전송하기 위한 프로토콜입니다. RTMP는 실시간 라이브 방송, Flash 미디어 서버 기반 스트리밍에 사용된다. RTMP는 표준이 아니며 Flash 기술의 쇠퇴로 사용 감소 중이다. 그런나 RTSP는 여전히 IP 카메라와 보안 시스템에서 중요한 프로토콜로 남아 있으며, 유연성과 낮은 지연 시간 덕분에 특정 산업에서 선호된다.
2. RTSP 스트림 보여주기
RTSP 서버를 통하여 보내오는 Live 스트림을 파이썬 코드에서 보여본다. 웹브라우저에서 직접 보여줄 수는 없다.
import cv2
import time
frame = None
video_capture= None
rtsp_url='rtsp://210.99.70.120:1935/live/cctv001.stream'
#rtsp_url='rtsp://127.0.0.1:8554/live'
def read_frame_with_timeout(video_capture, timeout=5):
start_time = time.time()
while True:
ret, frame = video_capture.read()
if ret:
return frame # 성공적으로 프레임을 읽음
# 현재 시간이 타임아웃 시간을 초과하면 에러 발생
if time.time() - start_time > timeout:
raise TimeoutError(f"Failed to read frame within {timeout} seconds.")
if __name__ == "__main__":
video_capture = cv2.VideoCapture(rtsp_url)
while True:
try:
frame = read_frame_with_timeout(video_capture, timeout=5)
cv2.imshow("Live Stream", frame)
except TimeoutError as e:
print(e)
video_capture.release()
video_capture = cv2.VideoCapture(rtsp_url)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
pass
3. RTSP 서버 실행하기
RTSP 서버 실행하기위하여 MediaMTX를 설치하고 실행한다. MediaMTX는 오픈 소스 미디어 서버로, RTSP, RTMP, HLS와 같은 다양한 스트리밍 프로토콜을 지원한다. 이전 이름은 RTSP Simple Server였으며, 최근에는 기능이 확장되면서 MediaMTX라는 이름으로 변경되었다. MediaMTX는 고성능, 다기능 미디어 스트리밍 서버로 설계되었으며, IP 카메라, DVR, 라이브 스트리밍, VOD(Video On Demand) 등 다양한 스트리밍 요구에 맞춰 사용할 수 있다. mediamtx는 다양한 프로토콜을 지원하는 오픈 소스 미디어 서버로, Windows용 64비트 버전 mediamtx_v1.10.0_windows_amd64.zip 파일을 아래에서 다운로드를 받고 실행할 수 있다.
다운로드 https://github.com/bluenviron/mediamtx/releases
D:\Program Files\RTSP_Server_mediamtx_v1.10.0_windows_amd64폴더에 설치 하였다면 Power Shell에서 다음과 같이 실행한다.
> cd "D:\Program Files\RTSP_Server_mediamtx_v1.10.0_windows_amd64"
> .\mediamtx.exe
위 미디어 서버는 RTSP는 8854,
RTMP는 1935,
HLS는 8888,
WebRTC는 8889,
SRT는 8890 포트를 사용한다.
4. 스트림 보내기
미디어 서버를 실행하고 다음 단계는 웹캠에서 스트림으로 미디어서버에 보낸다. 스트림을 보내기 위해서 ffmepeg 프로그램을 설치한다.
다음 명령어를 이용하여 PC에 부착된 웹캠이름을 알아낸다. ==> " Logi C270 HD WebCam"
> ffmpeg -list_devices true -f dshow -i dummy
웹캠을 사용하여 RTSP 스트림을 미디어 서버에 보낸다. RTSP는 8854 포트를 사용한다.
> ffmpeg -f dshow -i video="Logi C270 HD WebCam" -vcodec libx264 -rtsp_transport tcp -fflags nobuffer -tune zerolatency -f rtsp rtsp://localhost:8554/live
rtsp_url='rtsp://localhost:8554/live'