Free Motion Capture for Everyone πβ¨
TypeScript
fix the media capture / CvCamManager issue i created
Endurance Idehen3608343621e1
diff --git a/freemocap-ui/package.json b/freemocap-ui/package.jsonindex e99b375b..2a5f05fa 100644--- a/freemocap-ui/package.json+++ b/freemocap-ui/package.json@@ -43,7 +43,7 @@"@types/react-router-dom": "^5.1.6"},"scripts": {- "start": "react-scripts start",+ "start": "REACT_APP_DISABLE_LIVE_RELOAD=true react-scripts start","start:https": "HTTPS=true SSL_CRT_FILE=./localhost.pem SSL_KEY_FILE=./localhost-key.pem react-scripts start","certs": "./scripts/cert.sh","build": "react-scripts build",diff --git a/freemocap-ui/src/hooks/use-frame-capture.tsx b/freemocap-ui/src/hooks/use-frame-capture.tsxnew file mode 100644index 00000000..e3f8701f--- /dev/null+++ b/freemocap-ui/src/hooks/use-frame-capture.tsx@@ -0,0 +1,24 @@+import {useEffect, useState} from "react";+import {CaptureType, FrameCapture, OnMessageHandler} from "../services/frame-capture";++export const useFrameCapture = (webcam_id: string, captureType: CaptureType, onMessage?: OnMessageHandler): [FrameCapture, string] => {+ const [frameCapture,] = useState(() => new FrameCapture(webcam_id, captureType));+ const [data, setDataUrl] = useState<string>("");+ useEffect(() => {+ frameCapture.start_frame_capture(async (ev: MessageEvent<Blob>, data_url: string) => {+ setDataUrl(data_url);+ if (onMessage) {+ await onMessage(ev, data_url);+ }+ });+ return () => {+ frameCapture.cleanup()+ }+ }, [webcam_id]);++ window.onbeforeunload = () => {+ frameCapture.cleanup()+ }++ return [frameCapture, data];+}\ No newline at end of filediff --git a/freemocap-ui/src/services/frame-capture.tsx b/freemocap-ui/src/services/frame-capture.tsxindex 320c2c96..175b0f4f 100644--- a/freemocap-ui/src/services/frame-capture.tsx+++ b/freemocap-ui/src/services/frame-capture.tsx@@ -1,6 +1,4 @@-import {useEffect, useState} from "react";--type OnMessageHandler = (ev: MessageEvent<Blob>, data_url: string) => Promise<void>;+export type OnMessageHandler = (ev: MessageEvent<Blob>, data_url: string) => Promise<void>;export enum CaptureType {BoardDetection = "board_detection", SkeletonDetection = "skeleton_detection",@@ -42,24 +40,3 @@ export class FrameCapture {}}-export const useFrameCapture = (webcam_id: string, captureType: CaptureType, onMessage?: OnMessageHandler): [FrameCapture, string] => {- const [frameCapture,] = useState(() => new FrameCapture(webcam_id, captureType));- const [data, setDataUrl] = useState<string>("");- useEffect(() => {- frameCapture.start_frame_capture(async (ev: MessageEvent<Blob>, data_url: string) => {- setDataUrl(data_url);- if (onMessage) {- await onMessage(ev, data_url);- }- });- return () => {- frameCapture.cleanup()- }- }, [webcam_id]);-- window.onbeforeunload = () => {- frameCapture.cleanup()- }-- return [frameCapture, data];-}\ No newline at end of filediff --git a/freemocap-ui/src/views/BoardDetection.tsx b/freemocap-ui/src/views/BoardDetection.tsxindex 0b7a9cd7..92d0c625 100644--- a/freemocap-ui/src/views/BoardDetection.tsx+++ b/freemocap-ui/src/views/BoardDetection.tsx@@ -1,12 +1,14 @@import React from "react";import {Box} from "@mui/material";-import {CaptureType, useFrameCapture} from "../services/frame-capture";+import {CaptureType} from "../services/frame-capture";+import {useFrameCapture} from "../hooks/use-frame-capture";export const BoardDetection = () => {const [frameCapture, data] = useFrameCapture("0", CaptureType.BoardDetection);if (!data) {return null;}+return (<Box>{!frameCapture.isConnectionClosed && <img src={frameCapture.current_data_url} alt={"video capture"}/>}diff --git a/freemocap-ui/src/views/SkeletonDetection.tsx b/freemocap-ui/src/views/SkeletonDetection.tsxindex 390781a0..d4d33891 100644--- a/freemocap-ui/src/views/SkeletonDetection.tsx+++ b/freemocap-ui/src/views/SkeletonDetection.tsx@@ -1,6 +1,7 @@import React from "react";import {Box} from "@mui/material";-import {CaptureType, useFrameCapture} from "../services/frame-capture";+import {CaptureType} from "../services/frame-capture";+import {useFrameCapture} from "../hooks/use-frame-capture";export const SkeletonDetection = () => {const [frameCapture, data] = useFrameCapture("0", CaptureType.SkeletonDetection);diff --git a/src/api/routes/camera/cam_data_ws.py b/src/api/routes/camera/cam_data_ws.pyindex 6e00d0f2..9b5f0d00 100644--- a/src/api/routes/camera/cam_data_ws.py+++ b/src/api/routes/camera/cam_data_ws.py@@ -6,6 +6,7 @@ from fastapi import APIRouter, WebSocketfrom src.api.services.board_detect_service import BoardDetectServicefrom src.api.services.mediapipe_detect_service import MediapipeSkeletonDetectionService+from src.cameras.cam_factory import CVCameraManagerlogger = logging.getLogger(__name__)@@ -38,7 +39,9 @@ async def board_detection_as_ws(web_socket: WebSocket, webcam_id: str):@cam_ws_router.websocket("/ws/skeleton_detection/{webcam_id}")-async def skeleton_detection_as_ws(web_socket: WebSocket, webcam_id: str):+async def skeleton_detection_as_ws(+ web_socket: WebSocket, webcam_id: str, model_complexity: int+):await web_socket.accept()async def websocket_send(input_image):@@ -48,7 +51,7 @@ async def skeleton_detection_as_ws(web_socket: WebSocket, webcam_id: str):try:await MediapipeSkeletonDetectionService().run_as_loop(- webcam_id=webcam_id, cb=websocket_send+ webcam_id=webcam_id, cb=websocket_send, model_complexity=model_complexity)except:logger.error("Websocket ended")@@ -57,9 +60,9 @@ async def skeleton_detection_as_ws(web_socket: WebSocket, webcam_id: str):@cam_ws_router.get("/begin_mediapipe_skeleton_detection")-async def begin_mediapipe_skeleton_detection(model_complexity=2):+async def begin_mediapipe_skeleton_detection(model_complexity: int):"""model_complexity can be 1 (faster, less accurate) or 2 (slower, more accurate)"""- service = MediapipeSkeletonDetectionService(model_complexity)- await service.run()+ service = MediapipeSkeletonDetectionService(CVCameraManager())+ service.run(model_complexity)diff --git a/src/api/services/mediapipe_detect_service.py b/src/api/services/mediapipe_detect_service.pyindex 697211a7..ff4d47da 100644--- a/src/api/services/mediapipe_detect_service.py+++ b/src/api/services/mediapipe_detect_service.py@@ -1,14 +1,19 @@+from src.cameras.cam_factory import CVCameraManagerfrom src.core_processor.mediapipe_skeleton_detection.mediapipe_skeleton_detection import (MediapipeSkeletonDetection,)class MediapipeSkeletonDetectionService:- def __init__(self, model_complexity: int = 1):- self._model_complexity = model_complexity+ def __init__(self, cam_manager: CVCameraManager):+ self._cam_manager = cam_manager- async def run(self):- await MediapipeSkeletonDetection().process()+ def run(self, model_complexity: int):+ MediapipeSkeletonDetection(self._cam_manager).process(+ model_complexity=model_complexity+ )- async def run_as_loop(self, webcam_id, cb):- await MediapipeSkeletonDetection().process_as_frame_loop(webcam_id, cb)+ async def run_as_loop(self, webcam_id, cb, model_complexity: int):+ await MediapipeSkeletonDetection(self._cam_manager).process_as_frame_loop(+ webcam_id, model_complexity=model_complexity, cb=cb+ )diff --git a/src/cameras/cam_factory.py b/src/cameras/cam_factory.pyindex 2c35a9ec..498a9aec 100644--- a/src/cameras/cam_factory.py+++ b/src/cameras/cam_factory.py@@ -20,6 +20,7 @@ class CVCameraManager:logger.info("Creating cams.")# we create the _cv_cams once, and reuse it for the lifetime of the session_cv_cams = self._create_opencv_cams()+ self._cv_cams = _cv_camselse:logger.info("Reusing already created resources cam resources.")self._cv_cams = _cv_cams@@ -42,7 +43,6 @@ class CVCameraManager:# TODO: OBS Studio issue causes us to ignore a specific camera ID for Jon's computer.if int(webcam.webcam_id) < 3:cv_cams.append(OpenCVCamera(config=single_config))-return cv_cams@contextmanager@@ -53,10 +53,10 @@ class CVCameraManager:"""if webcam_id:self.start_frame_capture_on_cam_id(webcam_id)+ yield self.cv_cam_by_id(webcam_id)else:self.start_frame_capture_all_cams()-- yield self.cv_cam_by_id(webcam_id)+ yield self._cv_camslogger.debug("Cleaning up capture session")self.stop_frame_capture_all_cams()diff --git a/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py b/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.pyindex f77a817f..b8d654b7 100644--- a/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py+++ b/src/core_processor/mediapipe_skeleton_detection/mediapipe_skeleton_detection.py@@ -1,4 +1,3 @@-import asyncioimport loggingimport traceback@@ -16,13 +15,15 @@ logger = logging.getLogger(__name__)class MediapipeSkeletonDetection:- async def process_as_frame_loop(self, webcam_id, cb):- cam_manager: CVCameraManager = CVCameraManager()- with cam_manager.start_capture_session(webcam_id=webcam_id) as cv_cam:+ def __init__(self, cam_manager: CVCameraManager):+ self._cam_manager = cam_manager++ async def process_as_frame_loop(self, webcam_id, cb, model_complexity: int = 1):+ with self._cam_manager.start_capture_session(webcam_id=webcam_id) as cv_cam:with mp_holistic.Holistic(min_detection_confidence=0.5,min_tracking_confidence=0.5,- model_complexity=0,+ model_complexity=model_complexity,) as holistic:try:while True:@@ -34,15 +35,12 @@ class MediapipeSkeletonDetection:traceback.print_exc()raise e- async def process(self):- cam_manager: CVCameraManager = CVCameraManager()- cv_cams = cam_manager.cv_cams-- with cam_manager.start_capture_session():+ def process(self, model_complexity: int = 1):+ with self._cam_manager.start_capture_session() as cv_cams:with mp_holistic.Holistic(min_detection_confidence=0.5,min_tracking_confidence=0.5,- model_complexity=0,+ model_complexity=model_complexity,) as holistic:try:while True:@@ -106,4 +104,4 @@ class MediapipeSkeletonDetection:if __name__ == "__main__":- asyncio.run(MediapipeSkeletonDetection().process())+ MediapipeSkeletonDetection(CVCameraManager()).process()