From 5bfa069b7a18117d837c61f56d990496571ccb05 Mon Sep 17 00:00:00 2001 From: wenxin <1731551615@qq.com> Date: Tue, 17 Dec 2024 20:07:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8E=BB=E9=99=A4ws=E5=BF=83=E8=B7=B3=E6=9C=BA?= =?UTF-8?q?=E5=88=B6=EF=BC=8C=E6=94=B9=E4=B8=BAhttp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/config.py | 6 ++++-- app/main.py | 7 +++---- app/routes/stream.py | 29 +++++++++++++++++------------ app/routes/websocket.py | 17 ----------------- app/services/ffmpeg_service.py | 9 ++++++--- app/services/stream_manager.py | 6 +++++- linxyun/sso/middleware/security.py | 2 ++ linxyun/utils/result.py | 2 +- requirements.txt | Bin 582 -> 786 bytes 9 files changed, 38 insertions(+), 40 deletions(-) delete mode 100644 app/routes/websocket.py diff --git a/app/config.py b/app/config.py index 4861d0b..ee232a5 100644 --- a/app/config.py +++ b/app/config.py @@ -2,6 +2,8 @@ ffmpeg_path = r"D:\software\ffmpeg\ffmpeg-4.4.1\bin\ffmpeg.exe" cleanup_interval = 60 # 定时清理间隔时间(秒) expired_timeout = 60 * 1000 * 6 # 流空闲超时时间(毫秒) -rtmp_url = "rtmp://127.0.0.1/live" -flv_url = "http://127.0.0.1:8080/live" +srs_host = "127.0.0.1" +rtmp_url = f"rtmp://{srs_host}/live" +flv_url = f"http://{srs_host}:8080/live" +rtc_url = f"http://{srs_host}:1985/rtc/v1/whep/?app=live&stream=" md5_salt = "linxyun2024" \ No newline at end of file diff --git a/app/main.py b/app/main.py index aa57b52..1cf8c93 100644 --- a/app/main.py +++ b/app/main.py @@ -1,5 +1,5 @@ from app.middleware.cors import add_cors_middleware -from app.routes import websocket, stream +from app.routes import stream from app.tasks.cleanup_task import cleanup_streams from fastapi import FastAPI from contextlib import asynccontextmanager @@ -16,7 +16,7 @@ async def lifespan(app: FastAPI): # 创建 config config = Config( - entCode="57", + entCode="56", project="smartroadlamp", role={ "1101": ["/**"], @@ -34,9 +34,8 @@ app = FastAPI(lifespan=lifespan) # 添加跨域中间件 add_cors_middleware(app) # 添加鉴权中间件 -linxyun.add_security_middleware(app) +# linxyun.add_security_middleware(app) -app.include_router(websocket.router) app.include_router(stream.router) diff --git a/app/routes/stream.py b/app/routes/stream.py index 63e4479..be50315 100644 --- a/app/routes/stream.py +++ b/app/routes/stream.py @@ -1,17 +1,22 @@ from fastapi import APIRouter -from app.services.stream_manager import stop_stream -from app.services.ffmpeg_service import stream_rtsp_to_flv -from linxyun.utils.result import Result +from app.services.stream_manager import reset_stream_time +from app.services.ffmpeg_service import stream_rtsp_to_url +from linxyun.utils.result import Result, SysCodes router = APIRouter() @router.get("/get_stream") -async def get_stream(camera_id: str): - flv_url = await stream_rtsp_to_flv(camera_id) - if flv_url is None: - return Result.error("0001", "Stream not started") - return Result.ok(flv_url) +async def get_stream(camera_id: str, type: str="flv"): + url = await stream_rtsp_to_url(camera_id, type) + if url is None: + return Result.error(SysCodes.OPERATE_FAIL) + return Result.ok(url) + +@router.get("/looking/{camera_id}") +async def looking(camera_id: str): + status = reset_stream_time(camera_id) + if status is True: + return Result.ok() + else: + return Result.error(SysCodes.OPERATE_FAIL) + -@router.get("/stop_stream") -def stop(id: str): - stop_stream(id) - return {"message": "Stream stopped"} diff --git a/app/routes/websocket.py b/app/routes/websocket.py deleted file mode 100644 index 6b230c9..0000000 --- a/app/routes/websocket.py +++ /dev/null @@ -1,17 +0,0 @@ -# app/routes/websocket.py -from fastapi import APIRouter, WebSocket, WebSocketDisconnect -from app.services.stream_manager import reset_stream_time - -router = APIRouter() - -@router.websocket("/ws") -async def websocket_endpoint(websocket: WebSocket): - await websocket.accept() - try: - while True: - json_msg = await websocket.receive_json() - if json_msg: - reset_stream_time(json_msg.get("looking")) - await websocket.send_text("ok") - except WebSocketDisconnect: - print("WebSocket disconnected") diff --git a/app/services/ffmpeg_service.py b/app/services/ffmpeg_service.py index 7535242..b09981b 100644 --- a/app/services/ffmpeg_service.py +++ b/app/services/ffmpeg_service.py @@ -1,12 +1,11 @@ import asyncio import time -from app.config import ffmpeg_path, rtmp_url, flv_url +from app.config import ffmpeg_path, rtmp_url, flv_url, rtc_url from app.services.stream_manager import stream_manager from app.utils.logger import get_logger from app.utils.md5 import generate_md5 import subprocess -from urllib.parse import urljoin logger = get_logger(__name__) test_url = "rtsp://admin:jitu0818@192.168.4.102:554/Streaming/Channels/101" @@ -56,7 +55,7 @@ async def start_stream(stream_id: str, output_url: str): return process -async def stream_rtsp_to_flv(stream_id: str): +async def stream_rtsp_to_url(stream_id: str, type: str="flv"): md5_route = generate_md5(stream_id) output_url = f"{rtmp_url}/{md5_route}" # 如果流已经在运行,检查进程是否仍在运行 @@ -65,11 +64,15 @@ async def stream_rtsp_to_flv(stream_id: str): process = stream_manager[stream_id]["process"] if process.poll() is None: logger.info(f"Stream {stream_id} is still running.") + if type == "rtc": + return f"{rtc_url}{md5_route}.flv" return f"{flv_url}/{md5_route}.flv" # 如果流未在运行,启动新流 logger.info(f"Stream {stream_id} is not running. Starting new stream.") process = await start_stream(stream_id, output_url) if process.poll() is None: logger.info(f"Stream {stream_id} started successfully.") + if type == "rtc": + return f"{rtc_url}{md5_route}.flv" return f"{flv_url}/{md5_route}.flv" return None diff --git a/app/services/stream_manager.py b/app/services/stream_manager.py index bf595b7..86c8088 100644 --- a/app/services/stream_manager.py +++ b/app/services/stream_manager.py @@ -4,11 +4,13 @@ stream_manager = {} logger = get_logger(__name__) -def reset_stream_time(stream_id: str): +def reset_stream_time(stream_id: str) -> bool: if stream_id in stream_manager: new_time = int(time.time() * 1000) logger.info(f"Stream {stream_id} reset time to {new_time}") stream_manager[stream_id]["create_time"] = new_time + return True + return False def stop_stream(stream_id: str): if stream_id in stream_manager: @@ -18,3 +20,5 @@ def stop_stream(stream_id: str): logger.info(f"Stream {stream_id} stopped.") del stream_manager[stream_id] + + diff --git a/linxyun/sso/middleware/security.py b/linxyun/sso/middleware/security.py index 011e10f..198ac6e 100644 --- a/linxyun/sso/middleware/security.py +++ b/linxyun/sso/middleware/security.py @@ -25,6 +25,8 @@ class SecurityMiddleware(BaseHTTPMiddleware): # 获取请求路径 path = request.url.path method = request.method + if method == "OPTIONS": + return await call_next(request) logger.info(f"鉴权拦截: {method} {path}") # 获取请求头 Token token = request.headers.get("token") diff --git a/linxyun/utils/result.py b/linxyun/utils/result.py index e93af86..0d72101 100644 --- a/linxyun/utils/result.py +++ b/linxyun/utils/result.py @@ -71,7 +71,7 @@ class Result: @staticmethod - def ok(data): + def ok(data=None): return Result("0000", "操作成功", data, True) @staticmethod diff --git a/requirements.txt b/requirements.txt index 256b1262903bbb938ac7c6c9fea421576449b6ab..0d4ea79e69843d65c13fe9dba52d0bd995662ddf 100644 GIT binary patch delta 190 zcmX@cGKpCPNw!+XA5xg8>kmFz7K@0I@NU$IHOQkj#+5kO)*+%#aFH zt;>+dkPqbL0>yHG`l^7UMPS{=Ks_cCT}#DN87deGfKo+3oX3#PkOHKW8A>J>G73-J wwL-oKsH2df6i5~W%`1l546@G%Wb5Qu#-)-)K(j%nCjmtvF4Kd`{$}(B0M_9p!TOy*-+F!>yl3jkh52vh(7