Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

alter `create` abstraction strat

jonmatthis65692e05f5ab
diff --git a/freemocap/freemocap_app/freemocap_app_state.py b/freemocap/freemocap_app/freemocap_app_state.py
index c6a66208..c5d584f1 100644
--- a/freemocap/freemocap_app/freemocap_app_state.py
+++ b/freemocap/freemocap_app/freemocap_app_state.py
@@ -11,7 +11,7 @@ from skellycam.core.camera_group.shmorchestrator.shared_memory.ring_buffer_camer
from skellycam.skellycam_app.skellycam_app_controller.skellycam_app_controller import create_skellycam_app_controller
from skellycam.skellycam_app.skellycam_app_state import SkellycamAppState, get_skellycam_app_state
-from freemocap.pipelines.dummy_pipeline import DummyProcessingServer, DummyPipelineConfig
+from freemocap.pipelines.dummy_pipeline import DummyProcessingServer, DummyPipelineConfig, DummyProcessingPipeline
from freemocap.pipelines.pipeline_abcs import ReadTypes
logger = logging.getLogger(__name__)
@@ -53,8 +53,8 @@ class FreemocapAppState:
if self.skellycam_app_state.camera_group is None:
raise ValueError("Cannot get RingBufferCameraSharedMemory without CameraGroup!")
self.camera_ring_buffer_shms = {camera_id: RingBufferCameraSharedMemory.create(camera_config=config,
- memory_allocation=1_000_000_000,
- # TODO - 1GB per camera to test, need shrink this later
+ memory_allocation=100_000_000,
+ # 100 MB
read_only=False)
for camera_id, config in
self.skellycam_app_state.camera_group.camera_configs.items()}
@@ -62,14 +62,15 @@ class FreemocapAppState:
def create_processing_server(self) -> DummyProcessingServer:
if not self.frame_escape_shm:
raise ValueError("Cannot create image processing server without frame escape shared memory!")
+
self.pipeline_shutdown_event.clear()
- return DummyProcessingServer.create(camera_shm_dtos=self.get_camera_ring_buffer_shm_dtos(),
- pipeline_config=DummyPipelineConfig.create(
- camera_ids=self.skellycam_app_state.camera_group.camera_ids),
- read_type=ReadTypes.LATEST,
- shutdown_event=self.pipeline_shutdown_event,
- )
+ return DummyProcessingServer.create(
+ config =DummyPipelineConfig.create(camera_ids=self.skellycam_app_state.camera_group.camera_ids),
+ camera_shm_dtos=self.get_camera_ring_buffer_shm_dtos(),
+ read_type=ReadTypes.LATEST_AND_INCREMENT,
+ shutdown_event=self.pipeline_shutdown_event,
+ )
def close(self):
self.pipeline_shutdown_event.set()
diff --git a/freemocap/pipelines/dummy_pipeline.py b/freemocap/pipelines/dummy_pipeline.py
index 1525fd14..15454936 100644
--- a/freemocap/pipelines/dummy_pipeline.py
+++ b/freemocap/pipelines/dummy_pipeline.py
@@ -1,12 +1,12 @@
import multiprocessing
import time
from enum import Enum
-from multiprocessing import Queue
+from multiprocessing import Queue, Process
from typing import Dict
from skellycam import CameraId
from skellycam.core.camera_group.shmorchestrator.shared_memory.ring_buffer_camera_shared_memory import \
- RingBufferCameraSharedMemory
+ RingBufferCameraSharedMemory, RingBufferCameraSharedMemoryDTO
from freemocap.pipelines.pipeline_abcs import CameraProcessingNode, PipelineStageConfig, logger, PipelineData, \
AggregationProcessNode, PipelineConfig, CameraGroupProcessingPipeline, CameraGroupProcessingServer, ReadTypes
@@ -34,22 +34,49 @@ class DummyPipelineConfig(PipelineConfig):
class DummyCameraProcessingNode(CameraProcessingNode):
+ @classmethod
+ def create(cls,
+ config: DummyCameraPipelineConfig,
+ camera_id: CameraId,
+ camera_ring_shm_dto: RingBufferCameraSharedMemoryDTO,
+ output_queue: Queue,
+ shutdown_event: multiprocessing.Event,
+ read_type: ReadTypes = ReadTypes.LATEST_AND_INCREMENT
+ ):
+ return cls(config=config,
+ camera_id=camera_id,
+ camera_ring_shm=RingBufferCameraSharedMemory.recreate(dto=camera_ring_shm_dto,
+ read_only=False),
+ process=Process(target=cls._run,
+ kwargs=dict(config=config,
+ camera_ring_shm_dto=camera_ring_shm_dto,
+ output_queue=output_queue,
+ read_type=read_type,
+ shutdown_event=shutdown_event
+ )
+ ),
+ read_type=read_type,
+ shutdown_event=shutdown_event
+ )
@staticmethod
def _run(config: DummyPipelineConfig,
camera_ring_shm_dto: RingBufferCameraSharedMemory,
output_queue: Queue,
shutdown_event: multiprocessing.Event,
- read_type: ReadTypes = ReadTypes.LATEST,
+ read_type: ReadTypes = ReadTypes.LATEST_AND_INCREMENT
):
+ logger.trace(f"Starting camera processing node for camera {camera_ring_shm_dto.camera_id}")
camera_ring_shm = RingBufferCameraSharedMemory.recreate(dto=camera_ring_shm_dto,
- read_only=True)
+ read_only=False)
while not shutdown_event.is_set():
time.sleep(0.001)
if camera_ring_shm.ready_to_read:
- if read_type == ReadTypes.LATEST:
+ if read_type == ReadTypes.LATEST_AND_INCREMENT:
image = camera_ring_shm.retrieve_latest_frame(increment=True)
+ elif read_type == ReadTypes.LATEST_READ_ONLY:
+ image = camera_ring_shm.retrieve_latest_frame(increment=False)
elif read_type == ReadTypes.NEXT:
image = camera_ring_shm.retrieve_next_frame()
else:
@@ -61,6 +88,22 @@ class DummyCameraProcessingNode(CameraProcessingNode):
class DummyAggregationProcessNode(AggregationProcessNode):
+ @classmethod
+ def create(cls,
+ config: PipelineConfig,
+ input_queues: dict[CameraId, Queue],
+ output_queue: Queue,
+ shutdown_event: multiprocessing.Event):
+ return cls(config=config,
+ process=Process(target=cls._run,
+ kwargs=dict(config=config,
+ input_queues=input_queues,
+ output_queue=output_queue,
+ shutdown_event=shutdown_event)
+ ),
+ input_queues=input_queues,
+ output_queue=output_queue,
+ shutdown_event=shutdown_event)
@staticmethod
def _run(config: PipelineConfig, input_queues: Dict[CameraId, Queue], output_queue: Queue,
@@ -81,10 +124,53 @@ class DummyAggregationProcessNode(AggregationProcessNode):
class DummyProcessingPipeline(CameraGroupProcessingPipeline):
config: DummyPipelineConfig
- camera_node: Dict[CameraId, DummyCameraProcessingNode]
+ camera_nodes: Dict[CameraId, DummyCameraProcessingNode]
aggregation_node: DummyAggregationProcessNode
+ @classmethod
+ def create(cls,
+ config: PipelineConfig,
+ camera_shm_dtos: dict[CameraId, RingBufferCameraSharedMemoryDTO],
+ read_type: ReadTypes,
+ shutdown_event: multiprocessing.Event):
+ if not all(camera_id in camera_shm_dtos.keys() for camera_id in config.camera_node_configs.keys()):
+ raise ValueError("Camera IDs provided in config not in camera shared memory DTOS!")
+ camera_output_queues = {camera_id: Queue() for camera_id in camera_shm_dtos.keys()}
+ aggregation_output_queue = Queue()
+ camera_nodes = {camera_id: DummyCameraProcessingNode.create(config=config,
+ camera_id=CameraId(camera_id),
+ camera_ring_shm_dto=camera_shm_dtos[camera_id],
+ output_queue=camera_output_queues[camera_id],
+ read_type=read_type,
+ shutdown_event=shutdown_event)
+ for camera_id, config in config.camera_node_configs.items()}
+ aggregation_process = DummyAggregationProcessNode.create(config=config.aggregation_node_config,
+ input_queues=camera_output_queues,
+ output_queue=aggregation_output_queue,
+ shutdown_event=shutdown_event)
+
+ return cls(config=config,
+ camera_nodes=camera_nodes,
+ aggregation_node=aggregation_process,
+ shutdown_event=shutdown_event,
+ )
class DummyProcessingServer(CameraGroupProcessingServer):
processing_pipeline: DummyProcessingPipeline
pipeline_config: DummyPipelineConfig
+
+ @classmethod
+ def create(cls,
+ config:DummyPipelineConfig,
+ camera_shm_dtos: dict[CameraId, RingBufferCameraSharedMemoryDTO],
+ read_type: ReadTypes,
+ shutdown_event: multiprocessing.Event):
+ processing_pipeline = DummyProcessingPipeline.create(
+ camera_shm_dtos=camera_shm_dtos,
+ read_type=read_type,
+ shutdown_event=shutdown_event,
+
+ )
+
+ return cls(processing_pipeline=processing_pipeline,
+ shutdown_event=shutdown_event)
diff --git a/freemocap/pipelines/pipeline_abcs.py b/freemocap/pipelines/pipeline_abcs.py
index 13d3314e..c24947d8 100644
--- a/freemocap/pipelines/pipeline_abcs.py
+++ b/freemocap/pipelines/pipeline_abcs.py
@@ -15,13 +15,9 @@ from skellycam.core.frames.payloads.multi_frame_payload import MultiFramePayload
logger = logging.getLogger(__name__)
-class StageConfigKeys(str, Enum):
- CAMERA_PROCESSES = "camera_processes"
- AGGREGATION_PROCESS = "aggregation_process"
-
-
class ReadTypes(str, Enum):
- LATEST = "latest"
+ LATEST_READ_ONLY = "latest_read_only"
+ LATEST_AND_INCREMENT = "latest_and_increment"
NEXT = "next"
@@ -41,9 +37,8 @@ class PipelineConfig(BaseModel, ABC):
class CameraGroupPipelineConfig(PipelineConfig):
- stage_configs: dict[str, PipelineStageConfig] = {
- StageConfigKeys.CAMERA_PROCESSES.value: dict[CameraId, PipelineStageConfig],
- StageConfigKeys.AGGREGATION_PROCESS.value: PipelineStageConfig}
+ camera_node_configs: dict[CameraId, PipelineStageConfig]
+ aggregation_node_configs: PipelineStageConfig
class PipelineData(BaseModel, ABC):
@@ -69,32 +64,55 @@ class CameraProcessingNode(ABC):
output_queue: Queue,
read_type: ReadTypes,
shutdown_event: multiprocessing.Event):
- return cls(config=config,
- camera_id=camera_id,
- camera_ring_shm=RingBufferCameraSharedMemory.recreate(dto=camera_ring_shm_dto,
- read_only=False),
- process=Process(target=cls._run,
- kwargs=dict(config=config,
- camera_ring_shm_dto=camera_ring_shm_dto,
- output_queue=output_queue,
- read_type=read_type,
- shutdown_event=shutdown_event
- )
- ),
- read_type=read_type,
- shutdown_event=shutdown_event
- )
+ raise NotImplementedError("You need to re-implement this method with your pipeline's version of the CameraProcessingNode "
+ "abstract base class! See example in the `freemocap/.../dummy_pipeline.py` file.")
+ # return cls(config=config,
+ # camera_id=camera_id,
+ # camera_ring_shm=RingBufferCameraSharedMemory.recreate(dto=camera_ring_shm_dto,
+ # read_only=False),
+ # process=Process(target=cls._run,
+ # kwargs=dict(config=config,
+ # camera_ring_shm_dto=camera_ring_shm_dto,
+ # output_queue=output_queue,
+ # read_type=read_type,
+ # shutdown_event=shutdown_event
+ # )
+ # ),
+ # read_type=read_type,
+ # shutdown_event=shutdown_event
+ # )
def intake_data(self, frame_payload: FramePayload):
self.camera_ring_shm.put_frame(frame_payload.image, frame_payload.metadata)
+
+
@staticmethod
def _run(config: PipelineStageConfig,
camera_ring_shm_dto: RingBufferCameraSharedMemoryDTO,
output_queue: Queue,
read_type: ReadTypes,
shutdown_event: multiprocessing.Event):
- pass
+ raise NotImplementedError("Add your camera process logic here! See example in the `freemocap/.../dummy_pipeline.py` file.")
+ # logger.trace(f"Starting camera processing node for camera {camera_ring_shm_dto.camera_id}")
+ # camera_ring_shm = RingBufferCameraSharedMemory.recreate(dto=camera_ring_shm_dto,
+ # read_only=False)
+ # while not shutdown_event.is_set():
+ # time.sleep(0.001)
+ # if camera_ring_shm.ready_to_read:
+ #
+ # if read_type == ReadTypes.LATEST_AND_INCREMENT:
+ # image = camera_ring_shm.retrieve_latest_frame(increment=True)
+ # elif read_type == ReadTypes.LATEST_READ_ONLY:
+ # image = camera_ring_shm.retrieve_latest_frame(increment=False)
+ # elif read_type == ReadTypes.NEXT:
+ # image = camera_ring_shm.retrieve_next_frame()
+ # else:
+ # raise ValueError(f"Invalid read_type: {read_type}")
+ #
+ # logger.trace(f"Processing image from camera {camera_ring_shm.camera_id}")
+ # # TODO - process image
+ # output_queue.put(PipelineData(data=image))
def start(self):
logger.debug(f"Starting {self.__class__.__name__} for camera {self.camera_id}")
@@ -105,8 +123,6 @@ class CameraProcessingNode(ABC):
self.shutdown_event.set()
self.process.join()
- def join(self):
- self.process.join()
@dataclass
@@ -123,23 +139,37 @@ class AggregationProcessNode(ABC):
input_queues: dict[CameraId, Queue],
output_queue: Queue,
shutdown_event: multiprocessing.Event):
- return cls(config=config,
- process=Process(target=cls._run,
- kwargs=dict(config=config,
- input_queues=input_queues,
- output_queue=output_queue,
- shutdown_event=shutdown_event)
- ),
- input_queues=input_queues,
- output_queue=output_queue,
- shutdown_event=shutdown_event)
+ raise NotImplementedError("You need to re-implement this method with your pipeline's version of the AggregationProcessNode "
+ "abstract base class! See example in the `freemocap/.../dummy_pipeline.py` file.")
+ # return cls(config=config,
+ # process=Process(target=cls._run,
+ # kwargs=dict(config=config,
+ # input_queues=input_queues,
+ # output_queue=output_queue,
+ # shutdown_event=shutdown_event)
+ # ),
+ # input_queues=input_queues,
+ # output_queue=output_queue,
+ # shutdown_event=shutdown_event)
@staticmethod
def _run(config: PipelineConfig,
input_queues: dict[CameraId, Queue],
output_queue: Queue,
shutdown_event: multiprocessing.Event):
- pass
+ raise NotImplementedError("Add your aggregation process logic here! See example in the `freemocap/.../dummy_pipeline.py` file.")
+ # while not shutdown_event.is_set():
+ # data_by_camera_id = {camera_id: None for camera_id in input_queues.keys()}
+ # while any([input_queues[camera_id].empty() for camera_id in input_queues.keys()]):
+ # time.sleep(0.001)
+ # for camera_id in input_queues.keys():
+ # if not input_queues[camera_id] is None:
+ # if not input_queues[camera_id].empty():
+ # data_by_camera_id[camera_id] = input_queues[camera_id].get()
+ # if len(data_by_camera_id) == len(input_queues):
+ # logger.trace(f"Processing aggregated data from cameras {data_by_camera_id.keys()}")
+ # # TODO - process aggregated data
+ # output_queue.put(PipelineData(data=data_by_camera_id))
def start(self):
logger.debug(f"Starting {self.__class__.__name__}")
@@ -150,15 +180,13 @@ class AggregationProcessNode(ABC):
self.shutdown_event.set()
self.process.join()
- def join(self):
- self.process.join()
@dataclass
class CameraGroupProcessingPipeline(ABC):
model_config = ConfigDict(arbitrary_types_allowed=True)
config: PipelineConfig
- camera_node: dict[CameraId, CameraProcessingNode]
+ camera_nodes: dict[CameraId, CameraProcessingNode]
aggregation_node: AggregationProcessNode
shutdown_event: multiprocessing.Event
@@ -168,54 +196,54 @@ class CameraGroupProcessingPipeline(ABC):
camera_shm_dtos: dict[CameraId, RingBufferCameraSharedMemoryDTO],
read_type: ReadTypes,
shutdown_event: multiprocessing.Event):
- if not all(camera_id in camera_shm_dtos.keys() for camera_id in config.camera_node_configs.keys()):
- raise ValueError("Camera IDs provided in config not in camera shared memory DTOS!")
- camera_output_queues = {camera_id: Queue() for camera_id in camera_shm_dtos.keys()}
- aggregation_output_queue = Queue()
- camera_processes = {camera_id: CameraProcessingNode.create(config=config,
- camera_id=CameraId(camera_id),
- camera_ring_shm_dto=camera_shm_dtos[camera_id],
- output_queue=camera_output_queues[camera_id],
- read_type=read_type,
- shutdown_event=shutdown_event)
- for camera_id, config in config.camera_node_configs.items()}
- aggregation_process = AggregationProcessNode.create(config=config.aggregation_node_config,
- input_queues=camera_output_queues,
- output_queue=aggregation_output_queue,
- shutdown_event=shutdown_event)
-
- return cls(config=config,
- camera_node=camera_processes,
- aggregation_node=aggregation_process,
- shutdown_event=shutdown_event,
- )
+ raise NotImplementedError("You need to re-implement this method with your pipeline's version of the CameraGroupProcessingPipeline "
+ "and CameraProcessingNode abstract base classes! See example in the `freemocap/.../dummy_pipeline.py` file.")
+ # if not all(camera_id in camera_shm_dtos.keys() for camera_id in config.camera_node_configs.keys()):
+ # raise ValueError("Camera IDs provided in config not in camera shared memory DTOS!")
+ # camera_output_queues = {camera_id: Queue() for camera_id in camera_shm_dtos.keys()}
+ # aggregation_output_queue = Queue()
+ # camera_nodes = {camera_id: CameraProcessingNode.create(config=config,
+ # camera_id=CameraId(camera_id),
+ # camera_ring_shm_dto=camera_shm_dtos[camera_id],
+ # output_queue=camera_output_queues[camera_id],
+ # read_type=read_type,
+ # shutdown_event=shutdown_event)
+ # for camera_id, config in config.camera_node_configs.items()}
+ # aggregation_process = AggregationProcessNode.create(config=config.aggregation_node_config,
+ # input_queues=camera_output_queues,
+ # output_queue=aggregation_output_queue,
+ # shutdown_event=shutdown_event)
+ #
+ # return cls(config=config,
+ # camera_nodes=camera_nodes,
+ # aggregation_node=aggregation_process,
+ # shutdown_event=shutdown_event,
+ # )
def intake_data(self, multiframe_payload: MultiFramePayload):
- if not all(camera_id in self.camera_node.keys() for camera_id in multiframe_payload.camera_ids):
+ if not all(camera_id in self.camera_nodes.keys() for camera_id in multiframe_payload.camera_ids):
raise ValueError("Data provided for camera IDs not in camera processes!")
for camera_id, frame_payload in multiframe_payload.frames.items():
- self.camera_node[camera_id].intake_data(frame_payload)
+ self.camera_nodes[camera_id].intake_data(frame_payload)
def start(self):
- logger.debug(f"Starting {self.__class__.__name__} with camera processes {self.camera_node.keys()}...")
+ logger.debug(f"Starting {self.__class__.__name__} with camera processes {self.camera_nodes.keys()}...")
self.aggregation_node.start()
- for camera_id, camera_node in self.camera_node.items():
+ for camera_id, camera_node in self.camera_nodes.items():
camera_node.start()
def shutdown(self):
logger.debug(f"Shutting down {self.__class__.__name__}...")
self.shutdown_event.set()
- self.aggregation_node.join()
- for camera_id, camera_process in self.camera_node.items():
- camera_process.join()
+ self.aggregation_node.stop()
+ for camera_id, camera_process in self.camera_nodes.items():
+ camera_process.stop()
@dataclass
class CameraGroupProcessingServer(ABC):
model_config = ConfigDict(arbitrary_types_allowed=True)
- pipeline_config: PipelineConfig
processing_pipeline: CameraGroupProcessingPipeline
- read_type: ReadTypes
shutdown_event: multiprocessing.Event
def intake_data(self, multiframe_payload: MultiFramePayload):
@@ -223,23 +251,26 @@ class CameraGroupProcessingServer(ABC):
@classmethod
def create(cls,
- pipeline_config: PipelineConfig,
+ processing_pipeline: CameraGroupProcessingPipeline,
camera_shm_dtos: dict[CameraId, RingBufferCameraSharedMemoryDTO],
- read_type: ReadTypes,
+ read_type: ReadTypes,
shutdown_event: multiprocessing.Event):
- return cls(processing_pipeline=CameraGroupProcessingPipeline.create(config=pipeline_config,
- camera_shm_dtos=camera_shm_dtos,
- read_type=read_type,
- shutdown_event=shutdown_event),
- pipeline_config=pipeline_config,
- read_type=read_type,
- shutdown_event=shutdown_event)
+ raise NotImplementedError("You need to re-implement this method with your pipeline's version of the CameraGroupProcessingServer "
+ "and CameraGroupProcessingPipeline abstract base classes! See example in the `freemocap/.../dummy_pipeline.py` file.")
+ # processing_pipeline = CameraGroupProcessingPipeline.create(
+ # camera_shm_dtos=camera_shm_dtos,
+ # read_type=read_type,
+ # shutdown_event=shutdown_event,
+ # )
+ # return cls(processing_pipeline=processing_pipeline,
+ # shutdown_event=shutdown_event)
+
def start(self):
logger.debug(f"Starting {self.__class__.__name__}...")
self.processing_pipeline.start()
- def shutdown(self):
+ def shutdown_pipeline(self):
logger.debug(f"Shutting down {self.__class__.__name__}...")
self.shutdown_event.set()
self.processing_pipeline.shutdown()