"""Stub file for streaming_gateway.camera_streamer directory."""
from typing import Any, Dict, List, Optional, Set, Tuple, Union

from __future__ import annotations
from abc import ABC, abstractmethod
from async_camera_worker import run_async_worker
from async_ffmpeg_worker import run_ffmpeg_worker
from camera_streamer import CameraStreamer
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import datetime, timezone
from device_detection import PlatformDetector
from device_detection import PlatformDetector, PlatformType
from device_detection import PlatformInfo, PlatformType
from encoder_manager import EncoderManager
from encoding_pool_manager import EncodingPoolManager
from enum import Enum
from ffmpeg_camera_streamer import FFmpegPipeline
from ffmpeg_config import FFmpegConfig, is_ffmpeg_available
from ffmpeg_config import FFmpegConfig, is_ffmpeg_available, detect_hwaccel
from frame_processor import FrameProcessor
from gi.repository import Gst
from gi.repository import Gst, GLib, GstRtp
from gi.repository import Gst, GstApp, GLib
from gstreamer_camera_streamer import GStreamerConfig
from gstreamer_subprocess_demuxer import GStreamerSubprocessDemuxer
from gstreamer_worker import run_gstreamer_worker, is_gstreamer_available
from matrice_common.optimize import FrameOptimizer
from matrice_common.stream import MatriceStream, StreamType
from matrice_common.stream.cuda_shm_ring_buffer import CudaIpcRingBuffer, GlobalFrameCounter
from matrice_common.stream.cuda_shm_ring_buffer import GlobalFrameCounter
from matrice_common.stream.gpu_camera_map import GpuCameraMap
from matrice_common.stream.matrice_stream import MatriceStream, StreamType
from matrice_common.stream.shm_ring_buffer import ShmRingBuffer
from matrice_common.stream.shm_ring_buffer import bgr_to_nv12
from matrice_common.video import H265StreamEncoder, H265FrameEncoder
from message_builder import StreamMessageBuilder
from nvdec import nvdec_pool_process, StreamConfig, DemuxerType, CUPY_AVAILABLE, PYNVCODEC_AVAILABLE, RING_BUFFER_AVAILABLE
from pathlib import Path
from platform_pipelines import PipelineFactory
from platform_pipelines import PipelineFactory, CpuOnlyPipelineBuilder
from retry_manager import RetryManager
from stream_statistics import StreamStatistics
from streaming_gateway_utils import StreamingGatewayUtil
from urllib.parse import urlparse, urlunparse
from video_capture_manager import VideoCaptureManager
import PyNvVideoCodec as nvc
import argparse
import asyncio
import atexit
import base64
import cupy as cp
import cv2
import gi
import glob
import hashlib
import json
import logging
import multiprocessing
import multiprocessing as mp
import numpy as _np
import numpy as np
import os
import platform
import psutil
import queue as thread_queue
import re
import requests
import signal
import site
import struct
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import uuid
import xxhash

# Constants
GST_AVAILABLE: bool = ...  # From gstreamer_camera_streamer
RTP_CLOCK_RATE: int = ...  # From gstreamer_rtp_demuxer
logger: Any = ...  # From gstreamer_rtp_demuxer
logger: Any = ...  # From gstreamer_subprocess_demuxer
GST_AVAILABLE: bool = ...  # From gstreamer_worker
GPU_CAMERA_MAP_AVAILABLE: bool = ...  # From nvdec
GSTREAMER_DEMUXER_AVAILABLE: bool = ...  # From nvdec
GstRTPDemuxer: None = ...  # From nvdec
NV12_HEIGHT: Any = ...  # From nvdec
TARGET_HEIGHT: int = ...  # From nvdec
TARGET_WIDTH: int = ...  # From nvdec
logger: Any = ...  # From nvdec
logger: Any = ...  # From nvdec_worker_manager
USE_SHM: Any = ...  # From worker_manager

# Functions
# From async_camera_worker
def pin_to_cores(worker_id: int, total_workers: int) -> Optional[List[int]]: ...
    """
    Pin worker process to specific CPU cores for cache locality.
    
        This optimization from cv2_bench.py improves throughput by 15-20%
        by reducing CPU cache misses when processing frames.
    
        Args:
            worker_id: Worker identifier (0-indexed)
            total_workers: Total number of worker processes
    
        Returns:
            List of CPU core indices this worker is pinned to, or None if pinning failed
    """

# From async_camera_worker
def run_async_worker(worker_id: int, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], stop_event: Any, health_queue: Any, command_queue: Optional[Any] = None, response_queue: Optional[Any] = None, use_shm: bool = True, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', drop_stale_frames: bool = False, use_simple_read: bool = True, pin_cpu_affinity: bool = False, total_workers: int = 1, buffer_size: int = 1, frame_optimizer_enabled: bool = False) -> Any: ...
    """
    Entry point for async worker process.
    
        This function is called by multiprocessing.Process to start a worker.
    
        Args:
            worker_id: Worker identifier
            camera_configs: List of camera configurations
            stream_config: Streaming configuration
            stop_event: Shutdown event
            health_queue: Health reporting queue
            command_queue: Queue for receiving dynamic camera commands
            response_queue: Queue for sending command responses
            use_shm: Enable SHM mode (raw frames in shared memory)
            shm_slot_count: Number of frame slots per camera ring buffer
            shm_frame_format: Frame format for SHM storage
            drop_stale_frames: Use grab()/grab()/retrieve() pattern for latest frame
            use_simple_read: Use cap.read() directly instead of grab/retrieve pattern
            pin_cpu_affinity: Pin worker process to specific CPU cores
            total_workers: Total number of workers for CPU affinity calculation
            buffer_size: VideoCapture buffer size (1 = minimal latency)
            frame_optimizer_enabled: Enable frame similarity detection (skip similar frames)
    """

# From async_ffmpeg_worker
def pin_to_cores(worker_id: int, total_workers: int) -> Optional[List[int]]: ...
    """
    Pin worker process to specific CPU cores for cache locality.
    
        Args:
            worker_id: Worker identifier (0-indexed)
            total_workers: Total number of worker processes
    
        Returns:
            List of CPU core indices this worker is pinned to, or None if pinning failed
    """

# From async_ffmpeg_worker
def run_ffmpeg_worker(worker_id: int, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], stop_event: Any, health_queue: Any, command_queue: Optional[Any] = None, response_queue: Optional[Any] = None, ffmpeg_config_dict: Optional[Dict[str, Any]] = None, use_shm: bool = False, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', pin_cpu_affinity: bool = True, total_workers: int = 1, frame_optimizer_enabled: bool = False, frame_optimizer_config: Optional[Dict[str, Any]] = None) -> Any: ...
    """
    Entry point for FFmpeg worker process.
    
        Args:
            worker_id: Worker identifier
            camera_configs: List of camera configurations
            stream_config: Streaming configuration
            stop_event: Shutdown event
            health_queue: Health reporting queue
            command_queue: Queue for receiving dynamic camera commands
            response_queue: Queue for sending command responses
            ffmpeg_config_dict: FFmpeg configuration as dict
            use_shm: Enable SHM mode
            shm_slot_count: Number of frame slots per camera ring buffer
            shm_frame_format: Frame format for SHM storage
            pin_cpu_affinity: Pin worker to specific CPU cores
            total_workers: Total number of workers
            frame_optimizer_enabled: Enable frame optimizer
            frame_optimizer_config: Frame optimizer configuration dict
    """

# From device_detection
def get_platform_info(force_redetect: bool = False) -> Any: ...
    """
    Convenience function to get platform information.
    
        Args:
            force_redetect: Force re-detection even if cached
    
        Returns:
            PlatformInfo with detected capabilities
    """

# From ffmpeg_config
def detect_hwaccel() -> str: ...
    """
    Detect available hardware acceleration.
    
        Returns:
            Best available hwaccel option: cuda, vaapi, videotoolbox, or none
    """

# From ffmpeg_config
def get_ffmpeg_version() -> Optional[str]: ...
    """
    Get FFmpeg version string.
    
        Returns:
            Version string or None if FFmpeg is not available
    """

# From ffmpeg_config
def is_ffmpeg_available() -> bool: ...
    """
    Check if FFmpeg is available on the system.
    
        Returns:
            True if FFmpeg is available, False otherwise
    """

# From gstreamer_camera_streamer
def is_gstreamer_available() -> bool: ...
    """
    Check if GStreamer is available on the system.
    """

# From gstreamer_worker
def is_gstreamer_available() -> bool: ...
    """
    Check if GStreamer is available.
    """

# From gstreamer_worker
def run_gstreamer_worker(worker_id: int, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], stop_event: Any, health_queue: Any, command_queue: Optional[Any] = None, response_queue: Optional[Any] = None, gstreamer_encoder: str = 'auto', gstreamer_codec: str = 'h264', gstreamer_preset: str = 'low-latency', gpu_id: int = 0, platform: str = 'auto', use_hardware_decode: bool = True, use_hardware_jpeg: bool = True, jetson_use_nvmm: bool = True, frame_optimizer_mode: str = 'hash-only', fallback_on_error: bool = True, verbose_pipeline_logging: bool = False) -> Any: ...
    """
    Entry point for GStreamer worker process.
    
        Args:
            worker_id: Worker identifier
            camera_configs: Camera configurations
            stream_config: Streaming configuration
            stop_event: Shutdown event
            health_queue: Health reporting queue
            command_queue: Command queue
            response_queue: Response queue
            gstreamer_encoder: Encoder type
            gstreamer_codec: Codec
            gstreamer_preset: NVENC preset
            gpu_id: GPU device ID
            platform: Platform override
            use_hardware_decode: Enable hardware decode
            use_hardware_jpeg: Enable hardware JPEG
            jetson_use_nvmm: Use NVMM on Jetson
            frame_optimizer_mode: Frame optimization mode
            fallback_on_error: Fallback to CPU on errors
            verbose_pipeline_logging: Verbose logging
    """

# From nvdec
def get_video_downloader() -> Any: ...
    """
    Get or create the global VideoDownloader instance.
    """

# From nvdec
def main() -> Any: ...

# From nvdec
def nv12_resize(y_plane: Any, uv_plane: Any, y_stride: int, uv_stride: int, src_h: int, src_w: int, dst_h: int = 640, dst_w: int = 640) -> Any: ...
    """
    Resize NV12 without color conversion.
    
        Output: concatenated Y (H*W) + UV ((H/2)*W) as single buffer.
        Total size: H*W + (H/2)*W = H*W*1.5 bytes (50% of RGB).
    """

# From nvdec
def nvdec_pool_process(process_id: int, camera_configs: List[StreamConfig], pool_size: int, duration_sec: float, result_queue: Any, stop_event: Any, burst_size: int = 4, num_slots: int = 32, target_fps: int = 0, shared_frame_count: Optional[mp.Value] = None, gpu_frame_counts: Optional[Dict[int, mp.Value]] = None, total_num_streams: int = 0, total_num_gpus: int = 1, demuxer_type: str = 'nvc') -> Any: ...
    """
    NVDEC process for one GPU.
    
        Creates NV12 ring buffers: (H*1.5, W) = 0.6 MB/frame.
    
        Args:
            gpu_frame_counts: Dict mapping gpu_id -> per-GPU frame counter (for per-GPU stats)
            shared_frame_count: Global frame counter (for overall stats)
            total_num_streams: Total streams across ALL GPUs (for global per-stream calc)
            total_num_gpus: Total number of GPUs (for context in logging)
            demuxer_type: Demuxer backend ("nvc" or "gstreamer")
    """

# From nvdec
def nvdec_pool_worker(worker_id: int, decoder_idx: int, pool: Any, ring_buffers: Dict[str, CudaIpcRingBuffer], frame_counter: Any, duration_sec: float, result_queue: Any, stop_event: Any, burst_size: int = 4, target_h: int = 640, target_w: int = 640, target_fps: int = 0, shared_frame_count: Optional[mp.Value] = None, gpu_frame_count: Optional[mp.Value] = None) -> Any: ...
    """
    NVDEC worker thread.
    
        Decodes frames and writes NV12 tensors to ring buffers.
        Uses dedicated CUDA stream per worker for kernel overlap.
        Supports FPS limiting when target_fps > 0.
    
        Args:
            shared_frame_count: Global counter (all GPUs)
            gpu_frame_count: Per-GPU counter (this GPU only)
    """

# From nvdec
def setup_logging(quiet: bool = True) -> Any: ...
    """
    Configure logging level based on quiet mode.
    """

# From nvdec
def surface_to_nv12(frame: Any, target_h: int = 640, target_w: int = 640) -> Optional[cp.ndarray]: ...
    """
    Convert NVDEC surface to resized NV12 (50% smaller than RGB).
    
        Output: (H + H/2, W) uint8 - concatenated Y + UV planes.
        Total size: H*W*1.5 bytes (vs H*W*3 for RGB).
    """

# From nvdec_worker_manager
def get_available_gpu_count() -> int: ...
    """
    Detect the number of available CUDA GPUs.
    
        Returns:
            Number of available GPUs, or 1 if detection fails.
    """

# From nvdec_worker_manager
def is_nvdec_available() -> bool: ...
    """
    Check if NVDEC backend is available.
    
        Requires:
            - CuPy with CUDA support
            - PyNvVideoCodec for NVDEC hardware decode
            - cuda_shm_ring_buffer module for CUDA IPC
    """

# Classes
# From async_camera_worker
class AsyncCameraWorker:
    """
    Async worker process that handles multiple cameras concurrently.
    
        This worker runs an async event loop to handle I/O-bound operations
        (video capture, Redis writes) for multiple cameras efficiently.
    """

    def __init__(self: Any, worker_id: int, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], stop_event: Any, health_queue: Any, command_queue: Optional[Any] = None, response_queue: Optional[Any] = None, frame_optimizer_enabled: bool = False, frame_optimizer_config: Optional[Dict[str, Any]] = None, use_shm: bool = True, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', drop_stale_frames: bool = False, use_simple_read: bool = True, pin_cpu_affinity: bool = False, total_workers: int = 1, buffer_size: int = 1) -> None: ...
        """
        Initialize async camera worker.
        
                Args:
                    worker_id: Unique identifier for this worker
                    camera_configs: List of camera configurations to handle
                    stream_config: Streaming configuration (Redis, Kafka, etc.)
                    stop_event: Event to signal worker shutdown
                    health_queue: Queue for reporting health status
                    command_queue: Queue for receiving dynamic camera commands (add/remove/update)
                    response_queue: Queue for sending command responses back to manager
                    frame_optimizer_enabled: Whether to enable frame optimization
                    frame_optimizer_config: Frame optimizer configuration
                    use_shm: Enable SHM mode (raw frames in shared memory, metadata in Redis)
                    shm_slot_count: Number of frame slots per camera ring buffer
                    shm_frame_format: Frame format for SHM storage ("BGR", "RGB", or "NV12")
                    drop_stale_frames: Use grab()/grab()/retrieve() pattern to get latest frame
                    use_simple_read: Use cap.read() directly instead of grab/retrieve pattern
                    pin_cpu_affinity: Pin worker process to specific CPU cores for cache locality
                    total_workers: Total number of workers (for CPU affinity calculation)
                    buffer_size: VideoCapture buffer size (1 = minimal latency)
        """

    async def initialize(self: Any) -> Any: ...
        """
        Initialize async resources (Redis client, etc.).
        """

    async def run(self: Any) -> Any: ...
        """
        Main worker loop - starts async tasks for all cameras and handles commands.
        """


# From async_ffmpeg_worker
class AsyncFFmpegWorker:
    """
    Async worker process that handles multiple cameras using FFmpeg pipelines.
    
        This worker runs an async event loop to handle I/O-bound operations
        for multiple cameras efficiently, using FFmpeg subprocesses for video
        decoding instead of OpenCV.
    """

    def __init__(self: Any, worker_id: int, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], stop_event: Any, health_queue: Any, command_queue: Optional[Any] = None, response_queue: Optional[Any] = None, ffmpeg_config: Optional[FFmpegConfig] = None, use_shm: bool = False, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', pin_cpu_affinity: bool = True, total_workers: int = 1, frame_optimizer_enabled: bool = False, frame_optimizer_config: Optional[Dict[str, Any]] = None) -> None: ...
        """
        Initialize async FFmpeg worker.
        
                Args:
                    worker_id: Unique identifier for this worker
                    camera_configs: List of camera configurations to handle
                    stream_config: Streaming configuration (Redis, Kafka, etc.)
                    stop_event: Event to signal worker shutdown
                    health_queue: Queue for reporting health status
                    command_queue: Queue for receiving dynamic camera commands
                    response_queue: Queue for sending command responses
                    ffmpeg_config: FFmpeg configuration options
                    use_shm: Enable SHM mode for raw frame sharing
                    shm_slot_count: Number of frame slots per camera ring buffer
                    shm_frame_format: Frame format for SHM storage
                    pin_cpu_affinity: Pin worker to specific CPU cores
                    total_workers: Total number of workers for CPU affinity calculation
                    frame_optimizer_enabled: Enable frame optimizer for skipping similar frames
                    frame_optimizer_config: Frame optimizer configuration dict
        """

    async def initialize(self: Any) -> Any: ...
        """
        Initialize async resources (Redis client, etc.).
        """

    async def run(self: Any) -> Any: ...
        """
        Main worker loop - starts async tasks for all cameras.
        """


# From camera_streamer
class CameraStreamer:
    """
    Simplified camera streamer using modular components.
    
        This class orchestrates video streaming with:
        - Robust retry logic (never gives up)
        - Multiple video codecs (H.264, H.265 frame/stream)
        - Automatic reconnection on failures
        - Statistics tracking
        - Support for cameras, video files, RTSP, HTTP streams
    """

    def __init__(self: Any, session: Any, service_id: str, server_type: str, strip_input_content: bool = False, video_codec: Optional[str] = None, h265_quality: int = 23, use_hardware: bool = False, h265_mode: str = 'frame', gateway_util: Optional[StreamingGatewayUtil] = None, connection_refresh_threshold: int = 10, connection_refresh_interval: float = 60.0, frame_optimizer_enabled: bool = False, frame_optimizer_config: Optional[Dict[str, Any]] = None) -> None: ...
        """
        Initialize CameraStreamer.
        
                Args:
                    session: Session object for making RPC calls
                    service_id: ID of the deployment
                    server_type: Type of server (kafka or redis)
                    strip_input_content: Strip content for out-of-band retrieval
                    video_codec: Video codec to use
                    h265_quality: H.265 quality (CRF value 0-51, lower=better)
                    use_hardware: Use hardware encoding if available
                    h265_mode: H.265 mode - "frame" or "stream"
                    gateway_util: StreamingGatewayUtil instance for fetching connection info
                    connection_refresh_threshold: Number of consecutive failures before refreshing connection
                    connection_refresh_interval: Minimum seconds between connection refresh attempts
                    frame_optimizer_enabled: Enable frame optimization to skip similar frames
                    frame_optimizer_config: Configuration for FrameOptimizer (scale, diff_threshold, etc.)
        """

    async def async_produce_request(self: Any, input_data: Any, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, metadata: Optional[Dict] = None, topic: Optional[str] = None, timeout: float = 60.0) -> bool: ...
        """
        Produce a stream request to MatriceStream (asynchronous).
        """

    def calculate_batch_parameters(num_cameras: int, fps: int = 10) -> Dict[str, Any]: ...
        """
        Calculate optimal batch parameters based on number of cameras.
        
                Uses conservative defaults for small camera counts to minimize latency,
                then scales up for better throughput with many cameras.
        
                Note: This should be called with per-worker camera count, not total
                cameras in deployment. WorkerManager calls this for each worker.
        
                Args:
                    num_cameras: Number of cameras being streamed (per worker)
                    fps: Target frames per second (default: 10)
        
                Returns:
                    Dictionary with 'batch_size' and 'batch_timeout' parameters
        
                Examples:
                    - 1-10 cameras: batch_size=10, timeout=10ms (low latency)
                    - 11-50 cameras: batch_size=50, timeout=20ms
                    - 51-200 cameras: batch_size=100, timeout=50ms
                    - 201-500 cameras: batch_size=100, timeout=20ms
                    - 500+ cameras: batch_size=50, timeout=10ms (per-worker optimized)
        """

    async def close(self: Any) -> Any: ...
        """
        Clean up resources.
        """

    def get_stream_timing_stats(self: Any, stream_key: Optional[str] = None) -> Dict[str, Any]: ...
        """
        Get timing statistics for a stream.
        """

    def get_topic_for_stream(self: Any, stream_key: str) -> Optional[str]: ...
        """
        Get the topic for a specific stream key.
        """

    def get_transmission_stats(self: Any) -> Dict[str, Any]: ...
        """
        Get transmission statistics.
        """

    def produce_request(self: Any, input_data: Any, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, metadata: Optional[Dict] = None, topic: Optional[str] = None, timeout: float = 60.0) -> bool: ...
        """
        Produce a stream request to MatriceStream (synchronous).
        """

    def refresh_connection_info(self: Any) -> bool: ...
        """
        Refresh connection info from API and reinitialize MatriceStream.
        
                This method checks the server connection info from the API and if it has changed,
                it reinitializes the MatriceStream with the new connection details.
        
                Returns:
                    bool: True if connection was refreshed successfully
        """

    def register_stream_topic(self: Any, stream_key: str, topic: str) -> Any: ...
        """
        Register a topic for a specific stream key.
        """

    def reset_transmission_stats(self: Any) -> Any: ...
        """
        Reset transmission statistics.
        """

    def setup_stream_for_topic(self: Any, topic: str) -> bool: ...
        """
        Setup MatriceStream for a topic.
        """

    def start_background_stream(self: Any, input: Union[str, int], fps: int = 10, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, quality: int = 95, width: Optional[int] = None, height: Optional[int] = None, simulate_video_file_stream: bool = False, is_video_chunk: bool = False, chunk_duration_seconds: Optional[float] = None, chunk_frames: Optional[int] = None, camera_location: Optional[str] = None) -> bool: ...
        """
        Start streaming in background thread (non-blocking).
        """

    def start_stream(self: Any, input: Union[str, int], fps: int = 10, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, quality: int = 95, width: Optional[int] = None, height: Optional[int] = None, simulate_video_file_stream: bool = False, is_video_chunk: bool = False, chunk_duration_seconds: Optional[float] = None, chunk_frames: Optional[int] = None, camera_location: Optional[str] = None) -> bool: ...
        """
        Start streaming in current thread (blocking).
        
                Args:
                    input: Video source (camera index, file path, or URL)
                    fps: Target frames per second
                    stream_key: Unique identifier for this stream
                    stream_group_key: Group identifier for related streams
                    quality: Video quality
                    width: Target width (None to keep original)
                    height: Target height (None to keep original)
                    simulate_video_file_stream: Loop video file continuously
                    is_video_chunk: Whether this is a chunked video stream
                    chunk_duration_seconds: Duration of each chunk
                    chunk_frames: Number of frames per chunk
                    camera_location: Physical location description
        
                Returns:
                    True if stream started successfully, False otherwise
        """

    def stop_streaming(self: Any) -> None: ...
        """
        Stop all streaming threads.
        """


# From device_detection
class PlatformDetector:
    """
    Singleton platform detector with caching.
    
        Detects hardware platform and GStreamer capabilities, caching results
        for efficient reuse across multiple pipeline instances.
    """

    def __init__(self: Any) -> None: ...
        """
        Private constructor - use get_instance() instead.
        """

    def clear_cache(self: Any) -> Any: ...
        """
        Clear cached platform detection results.
        """

    def detect(self: Any, force_redetect: bool = False) -> Any: ...
        """
        Detect platform and cache results.
        
                Args:
                    force_redetect: Force re-detection even if cached result exists
        
                Returns:
                    PlatformInfo with detected capabilities
        """

    def get_instance(cls: Any) -> Any: ...
        """
        Get singleton instance of PlatformDetector.
        """

    def override_platform(self: Any, platform_type: Any, model: str = 'Manual Override') -> Any: ...
        """
        Manually override platform detection (for testing).
        
                Args:
                    platform_type: Platform type to force
                    model: Optional model description
        """


# From device_detection
class PlatformInfo:
    """
    Detected platform information and capabilities.
    """

    pass

# From device_detection
class PlatformType(Enum):
    """
    Supported hardware platform types.
    """

    AMD_GPU: str
    CPU_ONLY: str
    DESKTOP_NVIDIA_GPU: str
    INTEL_GPU: str
    JETSON: str

    pass

# From encoder_manager
class EncoderConfig:
    """
    Configuration for encoding.
    """

    pass

# From encoder_manager
class EncoderManager:
    """
    Manages H.265 frame and stream encoders.
    """

    def __init__(self: Any, h265_mode: str = 'frame', quality: int = 23, use_hardware: bool = False) -> None: ...
        """
        Initialize encoder manager.
        
                Args:
                    h265_mode: Encoding mode - "frame" or "stream"
                    quality: H.265 quality (CRF value 0-51, lower=better)
                    use_hardware: Use hardware encoding if available
        """

    def cleanup(self: Any) -> None: ...
        """
        Clean up all encoders.
        """

    def encode_frame(self: Any, frame: Any, stream_key: str, fps: int, width: int, height: int, metadata: Dict[str, Any]) -> Tuple[bytes, Dict[str, Any], str]: ...
        """
        Encode frame using configured mode.
        
                Args:
                    frame: Frame to encode
                    stream_key: Stream identifier
                    fps: Frames per second
                    width: Frame width
                    height: Frame height
                    metadata: Metadata dictionary to update
        
                Returns:
                    Tuple of (encoded_data, updated_metadata, encoding_type)
        """


# From encoding_pool_manager
class EncodingPoolManager:
    """
    Manages a process pool for parallel frame encoding.
    
        The encoding pool handles CPU-bound operations in separate processes
        to bypass the GIL and achieve true parallel execution on multi-core systems.
    """

    def __init__(self: Any, num_workers: Optional[int] = None) -> None: ...
        """
        Initialize encoding pool manager.
        
                Args:
                    num_workers: Number of encoding workers (default: CPU_count - 2)
        """

    def get_pool(self: Any) -> Any: ...
        """
        Get the encoding process pool.
        
                Returns:
                    Process pool instance
        
                Raises:
                    RuntimeError: If pool is not started
        """

    def is_running(self: Any) -> bool: ...
        """
        Check if encoding pool is running.
        
                Returns:
                    True if pool is active
        """

    def start(self: Any) -> Any: ...
        """
        Start the encoding process pool.
        """

    def stop(self: Any, timeout: float = 10.0) -> Any: ...
        """
        Stop the encoding process pool gracefully.
        
                Args:
                    timeout: Maximum time to wait for workers to finish (seconds)
        """


# From ffmpeg_camera_streamer
class FFmpegCameraStreamer:
    """
    FFmpeg-based camera streamer with same API as CameraStreamer.
    
        This class provides a drop-in replacement for CameraStreamer using
        FFmpeg subprocess pipelines for video ingestion. It supports:
        - Background streaming to Redis/Kafka
        - Dynamic camera add/remove/update
        - Frame optimization (similarity detection)
        - SHM mode for raw frame sharing
    """

    def __init__(self: Any, session: Any, service_id: str, server_type: str = 'redis', video_codec: Optional[str] = None, gateway_util: Any = None, ffmpeg_config: Optional[FFmpegConfig] = None, use_shm: bool = False, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', frame_optimizer_enabled: bool = False, frame_optimizer_config: Optional[Dict[str, Any]] = None, pin_cpu_affinity: bool = False, cpu_affinity_core: Optional[int] = None) -> None: ...
        """
        Initialize FFmpeg camera streamer.
        
                Args:
                    session: Session object for authentication
                    service_id: Service identifier
                    server_type: Backend type (redis or kafka)
                    video_codec: Video codec (h264 or h265)
                    gateway_util: Gateway utility for API interactions
                    ffmpeg_config: FFmpeg configuration
                    use_shm: Enable SHM mode for raw frame sharing
                    shm_slot_count: Number of frame slots per camera ring buffer
                    shm_frame_format: Frame format for SHM storage ("BGR", "RGB", or "NV12")
                    frame_optimizer_enabled: Enable frame optimizer for skipping similar frames
                    frame_optimizer_config: Frame optimizer configuration dict
                    pin_cpu_affinity: Pin process to specific CPU core
                    cpu_affinity_core: CPU core to pin to (None = auto-assign)
        """

    def get_transmission_stats(self: Any) -> Dict[str, Any]: ...
        """
        Get transmission statistics.
        
                Returns:
                    Dictionary of statistics
        """

    def register_stream_topic(self: Any, stream_key: str, topic: str) -> Any: ...
        """
        Register a topic for a stream.
        
                Args:
                    stream_key: Stream identifier
                    topic: Topic name for this stream
        """

    def reset_transmission_stats(self: Any) -> Any: ...
        """
        Reset transmission statistics.
        """

    def setup_stream_for_topic(self: Any, topic: str) -> Any: ...
        """
        Setup stream for a topic (create topic if needed).
        
                Args:
                    topic: Topic name to setup
        """

    def start_background_stream(self: Any, input: Union[str, int], fps: int = 30, stream_key: str = 'default', stream_group_key: str = 'default', quality: int = 90, width: Optional[int] = None, height: Optional[int] = None, simulate_video_file_stream: bool = False, camera_location: str = 'Unknown') -> bool: ...
        """
        Start background streaming for a camera.
        
                Args:
                    input: Video source (file path, URL, or device ID)
                    fps: Target FPS
                    stream_key: Unique stream identifier
                    stream_group_key: Stream group identifier
                    quality: JPEG quality (1-100)
                    width: Target width (None = use source)
                    height: Target height (None = use source)
                    simulate_video_file_stream: Loop video files
                    camera_location: Camera location description
        
                Returns:
                    True if stream started successfully
        """

    def stop_streaming(self: Any, stream_key: Optional[str] = None) -> None: ...
        """
        Stop streaming for one or all cameras.
        
                Args:
                    stream_key: Stream to stop (None = stop all)
        """


# From ffmpeg_camera_streamer
class FFmpegPipeline:
    """
    FFmpeg subprocess-based frame capture pipeline.
    
        This class manages an FFmpeg subprocess that decodes video and outputs
        raw frames via stdout pipe. It provides both sync and async interfaces.
    """

    def __init__(self: Any, source: str, width: int, height: int, config: Optional[FFmpegConfig] = None, stream_key: str = 'default') -> None: ...
        """
        Initialize FFmpeg pipeline.
        
                Args:
                    source: Video source (file path, RTSP URL, HTTP URL, device)
                    width: Frame width (0 = auto-detect from source)
                    height: Frame height (0 = auto-detect from source)
                    config: FFmpeg configuration options
                    stream_key: Stream identifier for logging
        """

    def close(self: Any) -> Any: ...
        """
        Close the pipeline and release resources.
        """

    def get_metrics(self: Any) -> Dict[str, Any]: ...
        """
        Get pipeline metrics.
        
                Returns:
                    Dictionary of metrics
        """

    def read_frame(self: Any) -> Optional[np.ndarray]: ...
        """
        Read one raw frame from FFmpeg pipe (blocking).
        
                Returns:
                    numpy array of shape (height, width, 3) or None if failed
        """

    async def read_frame_async(self: Any, executor: Optional[ThreadPoolExecutor] = None) -> Optional[np.ndarray]: ...
        """
        Read frame asynchronously using executor.
        
                Args:
                    executor: Thread pool executor (uses default if None)
        
                Returns:
                    numpy array or None if failed
        """

    def restart(self: Any) -> bool: ...
        """
        Restart the FFmpeg pipeline.
        
                Returns:
                    True if restart succeeded
        """


# From ffmpeg_config
class FFmpegConfig:
    """
    Configuration for FFmpeg-based streaming.
    
        This configuration controls how FFmpeg subprocesses are spawned
        for video ingestion, with options for hardware acceleration,
        low-latency settings, and output format control.
    """

    def to_ffmpeg_args(self: Any, source: str, width: int = 0, height: int = 0) -> List[str]: ...
        """
        Build FFmpeg command line arguments.
        
                Args:
                    source: Input source (file path, RTSP URL, etc.)
                    width: Frame width (0 = auto-detect)
                    height: Frame height (0 = auto-detect)
        
                Returns:
                    List of command line arguments for FFmpeg
        """


# From ffmpeg_worker_manager
class FFmpegWorkerManager:
    """
    Manages multiple FFmpeg async camera worker processes.
    
        This manager coordinates worker processes, distributing cameras
        across them for optimal throughput using FFmpeg subprocesses
        for video ingestion.
    """

    def __init__(self: Any, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], num_workers: Optional[int] = None, cpu_percentage: float = 0.9, max_cameras_per_worker: int = 100, ffmpeg_config: Optional[FFmpegConfig] = None, use_shm: bool = False, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', pin_cpu_affinity: bool = True) -> None: ...
        """
        Initialize FFmpeg worker manager.
        
                Args:
                    camera_configs: List of all camera configurations
                    stream_config: Streaming configuration (Redis, Kafka, etc.)
                    num_workers: Number of worker processes (default: auto-calculated)
                    cpu_percentage: Percentage of CPU cores to use (default: 0.9)
                    max_cameras_per_worker: Maximum cameras per worker (default: 100)
                    ffmpeg_config: FFmpeg configuration options
                    use_shm: Enable SHM mode for raw frame sharing
                    shm_slot_count: Number of frame slots per camera ring buffer
                    shm_frame_format: Frame format for SHM storage
                    pin_cpu_affinity: Pin workers to specific CPU cores
        """

    def add_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Add a camera to the least-loaded worker at runtime.
        
                Args:
                    camera_config: Camera configuration dictionary
        
                Returns:
                    bool: True if camera was added successfully
        """

    def get_camera_assignments(self: Any) -> Dict[str, int]: ...
        """
        Get current camera-to-worker assignments.
        """

    def get_worker_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get detailed statistics about workers and cameras.
        """

    def monitor(self: Any, duration: Optional[float] = None) -> Any: ...
        """
        Monitor workers and collect health reports.
        
                Args:
                    duration: How long to monitor (None = indefinite)
        """

    def remove_camera(self: Any, stream_key: str) -> bool: ...
        """
        Remove a camera from its assigned worker.
        
                Args:
                    stream_key: Unique identifier for the camera stream
        
                Returns:
                    bool: True if camera removal was initiated
        """

    def run(self: Any, duration: Optional[float] = None) -> Any: ...
        """
        Start workers and monitor until stopped.
        
                Args:
                    duration: How long to run (None = until interrupted)
        """

    def start(self: Any) -> Any: ...
        """
        Start all workers and begin streaming.
        """

    def stop(self: Any, timeout: float = 15.0) -> Any: ...
        """
        Stop all workers gracefully.
        
                Args:
                    timeout: Maximum time to wait per worker (seconds)
        """


# From frame_processor
class FrameProcessor:
    """
    Handles frame processing operations like resizing.
    """

    def calculate_actual_dimensions(video_width: int, video_height: int, target_width: Optional[int], target_height: Optional[int]) -> Tuple[int, int]: ...
        """
        Calculate actual output dimensions.
        
                Args:
                    video_width: Original video width
                    video_height: Original video height
                    target_width: Target width (None for original)
                    target_height: Target height (None for original)
        
                Returns:
                    Tuple of (actual_width, actual_height)
        """

    def resize_frame(frame: Any, target_width: Optional[int], target_height: Optional[int]) -> Any: ...
        """
        Resize frame if needed.
        
                Args:
                    frame: Input frame
                    target_width: Target width (None to keep current)
                    target_height: Target height (None to keep current)
        
                Returns:
                    Resized frame or original if no resize needed
        """

    def should_skip_frame(frame_counter: int, frame_skip: int) -> bool: ...
        """
        Check if frame should be skipped based on skip rate.
        
                Args:
                    frame_counter: Current frame count
                    frame_skip: Frame skip rate
        
                Returns:
                    True if frame should be skipped
        """


# From gstreamer_camera_streamer
class GStreamerCameraStreamer:
    """
    GStreamer-based camera streamer with the same API as CameraStreamer.
    
        This class provides:
        - Same public API as CameraStreamer for drop-in replacement
        - GStreamer-based video capture and encoding
        - Support for hardware encoding (NVENC) when available
        - Multiple codec support (H.264, H.265, JPEG)
        - Robust retry logic and statistics tracking
    """

    def __init__(self: Any, session: Any, service_id: str, server_type: str, strip_input_content: bool = False, video_codec: Optional[str] = None, gateway_util: Optional[StreamingGatewayUtil] = None, gstreamer_config: Optional[GStreamerConfig] = None, frame_optimizer_enabled: bool = False, frame_optimizer_config: Optional[Dict[str, Any]] = None) -> None: ...
        """
        Initialize GStreamerCameraStreamer.
        
                Args:
                    session: Session object for authentication
                    service_id: Deployment/gateway ID
                    server_type: 'kafka' or 'redis'
                    strip_input_content: Strip content for out-of-band retrieval
                    video_codec: Video codec override
                    gateway_util: Utility for API interactions
                    gstreamer_config: GStreamer-specific configuration
                    frame_optimizer_enabled: Enable frame optimization to skip similar frames
                    frame_optimizer_config: Configuration for FrameOptimizer (scale, diff_threshold, etc.)
        """

    async def async_produce_request(self: Any, input_data: Any, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, metadata: Optional[Dict] = None, topic: Optional[str] = None, timeout: float = 60.0) -> bool: ...
        """
        Produce a stream request to MatriceStream (asynchronous).
        
                Args:
                    input_data: Frame data bytes
                    stream_key: Stream identifier
                    stream_group_key: Stream group identifier
                    metadata: Optional metadata dictionary
                    topic: Optional topic override
                    timeout: Timeout in seconds
        
                Returns:
                    bool: True if successful, False otherwise
        """

    async def close(self: Any) -> Any: ...
        """
        Clean up resources.
        """

    def get_topic_for_stream(self: Any, stream_key: str) -> Optional[str]: ...
        """
        Get the topic for a specific stream key.
        """

    def get_transmission_stats(self: Any) -> Dict[str, Any]: ...
        """
        Get transmission statistics.
        """

    def produce_request(self: Any, input_data: Any, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, metadata: Optional[Dict] = None, topic: Optional[str] = None, timeout: float = 60.0) -> bool: ...
        """
        Produce a stream request to MatriceStream (synchronous).
        
                Args:
                    input_data: Frame data bytes
                    stream_key: Stream identifier
                    stream_group_key: Stream group identifier
                    metadata: Optional metadata dictionary
                    topic: Optional topic override
                    timeout: Timeout in seconds
        
                Returns:
                    bool: True if successful, False otherwise
        """

    def refresh_connection_info(self: Any) -> bool: ...
        """
        Refresh connection info from API and reinitialize MatriceStream.
        
                This method checks the server connection info from the API and if it has changed,
                it reinitializes the MatriceStream with the new connection details.
        
                Returns:
                    bool: True if connection was refreshed successfully
        """

    def register_stream_topic(self: Any, stream_key: str, topic: str) -> Any: ...
        """
        Register a topic for a specific stream key.
        """

    def reset_transmission_stats(self: Any) -> Any: ...
        """
        Reset transmission statistics.
        """

    def setup_stream_for_topic(self: Any, topic: str) -> bool: ...
        """
        Setup MatriceStream for a topic.
        """

    def start_background_stream(self: Any, input: Union[str, int], fps: int = 10, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, quality: int = 95, width: Optional[int] = None, height: Optional[int] = None, simulate_video_file_stream: bool = False, is_video_chunk: bool = False, chunk_duration_seconds: Optional[float] = None, chunk_frames: Optional[int] = None, camera_location: Optional[str] = None) -> bool: ...
        """
        Start streaming in background thread (non-blocking).
        """

    def start_stream(self: Any, input: Union[str, int], fps: int = 10, stream_key: Optional[str] = None, stream_group_key: Optional[str] = None, quality: int = 95, width: Optional[int] = None, height: Optional[int] = None, simulate_video_file_stream: bool = False, is_video_chunk: bool = False, chunk_duration_seconds: Optional[float] = None, chunk_frames: Optional[int] = None, camera_location: Optional[str] = None) -> bool: ...
        """
        Start streaming in current thread (blocking).
        """

    def stop_streaming(self: Any) -> None: ...
        """
        Stop all streaming threads and pipelines.
        """


# From gstreamer_camera_streamer
class GStreamerConfig:
    """
    Configuration for GStreamer encoding.
    
        Default: JPEG for frame-by-frame streaming with maximum performance.
        JPEG provides:
        - No inter-frame dependencies (true frame-by-frame)
        - Consistent per-frame latency
        - Simple frame caching (hash-based works perfectly)
        - Maximum throughput for static scenes
    """

    pass

# From gstreamer_camera_streamer
class GStreamerMetrics:
    """
    Metrics for a GStreamer stream.
    """

    pass

# From gstreamer_camera_streamer
class GStreamerPipeline:
    """
    Manages a single GStreamer pipeline for video capture and encoding.
    
        This class handles:
        - Pipeline construction with automatic encoder detection
        - Video source handling (cameras, files, RTSP, HTTP)
        - Frame pulling from appsink
        - PTS-based latency measurement
    """

    def __init__(self: Any, stream_key: str, source: Union[str, int], width: int, height: int, fps: int, config: Any) -> None: ...
        """
        Initialize GStreamer pipeline.
        
                Args:
                    stream_key: Unique identifier for this stream
                    source: Video source (camera index, file path, RTSP URL, etc.)
                    width: Target output width
                    height: Target output height
                    fps: Target frames per second
                    config: GStreamer configuration
        """

    def get_metrics(self: Any) -> Any: ...
        """
        Get pipeline metrics.
        """

    def pull_frame(self: Any, timeout_ns: Optional[int] = None) -> Optional[tuple]: ...
        """
        Pull an encoded frame from the pipeline.
        
                Args:
                    timeout_ns: Timeout in nanoseconds (default: 100ms)
        
                Returns:
                    Tuple of (frame_data, latency_ms, size) or None if no frame
        """

    def start(self: Any) -> bool: ...
        """
        Start the GStreamer pipeline.
        
                Returns:
                    bool: True if started successfully
        """

    def stop(self: Any) -> Any: ...
        """
        Stop the GStreamer pipeline.
        """


# From gstreamer_rtp_demuxer
class DemuxerType(Enum):
    """
    Demuxer backend selection.
    """

    GSTREAMER: str
    NVC: str

    pass

# From gstreamer_rtp_demuxer
class GstRTPDemuxer:
    """
    GStreamer H264 demuxer with ABSOLUTE RTP timestamp capture.
    
        For RTSP streams:
        - Captures RAW 32-bit RTP timestamps via pad probe BEFORE depayloading
        - These are the ACTUAL timestamps from the RTP packet header
        - NOT normalized like PyAV (which starts near 0 each session)
        - Timestamps persist across reconnections (monotonically increasing from source)
        - Automatically converts localhost to 127.0.0.1 to avoid IPv6 issues
        - Uses TCP by default to avoid UDP IPv6 socket issues
    
        For files:
        - Uses container PTS (presentation timestamp)
        - No RTP timestamps available
    
        Outputs H264 NAL units for external decoder (e.g., PyNvVideoCodec).
    
        Args:
            source: RTSP URL or file path
            use_tcp: Use TCP for RTSP transport (default: True, more reliable)
            loop: Loop file playback (default: False)
    """

    def __init__(self: Any, source: str, use_tcp: bool = True, loop: bool = False) -> None: ...

    MAX_RETRIES: int
    RETRY_DELAY: float

    def close(self: Any) -> Any: ...
        """
        Close demuxer and release resources.
        """

    def demux(self: Any) -> Any: ...
        """
        Demux H264 NAL units with timestamps.
        
                Yields:
                    (h264_bytes, timestamp, timestamp_ns, absolute_time_ns)
        
                    For RTSP:
                    - h264_bytes: H264 NAL unit as bytes
                    - timestamp: RAW 32-bit RTP timestamp (ABSOLUTE, NOT normalized)
                    - timestamp_ns: RTP timestamp converted to nanoseconds (at 90kHz)
                    - absolute_time_ns: Unix time if RTCP SR available, None otherwise
        
                    For files:
                    - h264_bytes: H264 NAL unit as bytes
                    - timestamp: Container PTS
                    - timestamp_ns: PTS in nanoseconds
                    - absolute_time_ns: None
        """

    def first_rtp_timestamp(self: Any) -> Optional[int]: ...
        """
        First ABSOLUTE RTP timestamp captured (RTSP only).
        """

    def fps(self: Any) -> float: ...
        """
        Video frame rate.
        """

    def frames_demuxed(self: Any) -> int: ...
        """
        Number of frames demuxed in this session.
        """

    def has_rtcp_sr(self: Any) -> bool: ...
        """
        Whether RTCP Sender Report is available for absolute time mapping.
        """

    def height(self: Any) -> int: ...
        """
        Video frame height.
        """

    def is_eof(self: Any) -> bool: ...
        """
        Whether end-of-stream has been reached.
        """

    def is_rtsp(self: Any) -> bool: ...
        """
        Whether source is RTSP stream.
        """

    def latest_rtcp_sr(self: Any) -> Optional[RTCPSenderReport]: ...
        """
        Most recent RTCP Sender Report.
        """

    def open(self: Any, quiet: bool = False) -> Any: ...
        """
        Open source and initialize demuxer pipeline with retry logic.
        
                For RTSP streams, automatically retries with TCP if UDP fails,
                and converts localhost to 127.0.0.1 to avoid IPv6 issues.
        
                Args:
                    quiet: Suppress info logging
        
                Returns:
                    self (for chaining)
        
                Raises:
                    RuntimeError: If pipeline creation fails after all retries
        """

    def session_id(self: Any) -> str: ...
        """
        Unique session identifier.
        """

    def session_start_ns(self: Any) -> int: ...
        """
        Session start time in nanoseconds.
        """

    def width(self: Any) -> int: ...
        """
        Video frame width.
        """


# From gstreamer_rtp_demuxer
class RTCPSenderReport:
    """
    Parsed RTCP Sender Report for RTP-to-NTP time mapping.
    
        Attributes:
            ssrc: Synchronization source identifier
            ntp_timestamp: 64-bit NTP timestamp from RTCP SR
            rtp_timestamp: 32-bit RTP timestamp at SR time
            unix_time: NTP timestamp converted to Unix time
            received_at_ns: Local time when SR was received (nanoseconds)
    """

    pass

# From gstreamer_rtp_demuxer
class RTCPTracker:
    """
    Tracks RTCP Sender Reports for RTP-to-absolute-time mapping.
    
        RTCP Sender Reports provide the mapping between RTP timestamps (at 90kHz)
        and absolute wall-clock time (NTP). This allows converting any RTP timestamp
        to Unix time for cross-camera synchronization.
    """

    def __init__(self: Any, clock_rate: int = RTP_CLOCK_RATE) -> None: ...

    NTP_UNIX_EPOCH_DIFF: int

    def has_sender_report(self: Any) -> bool: ...
        """
        Check if at least one RTCP Sender Report has been received.
        """

    def latest_sr(self: Any) -> Optional[RTCPSenderReport]: ...
        """
        Get the most recent RTCP Sender Report.
        """

    def rtp_to_unix_ns(self: Any, rtp_timestamp: int) -> Optional[int]: ...
        """
        Convert RTP timestamp to absolute Unix time in nanoseconds.
        
                Uses the most recent RTCP Sender Report to map RTP timestamps to
                absolute wall-clock time. Handles 32-bit RTP timestamp rollover.
        
                Args:
                    rtp_timestamp: 32-bit RTP timestamp to convert
        
                Returns:
                    Unix time in nanoseconds, or None if no SR available
        """

    def update_from_session_stats(self: Any, stats_str: str, ssrc: int) -> Optional[RTCPSenderReport]: ...
        """
        Parse RTCP SR from GStreamer session stats.
        
                Args:
                    stats_str: GStreamer stats structure as string
                    ssrc: Source SSRC identifier
        
                Returns:
                    RTCPSenderReport if valid SR found, None otherwise
        """


# From gstreamer_subprocess_demuxer
class GStreamerSubprocessDemuxer:
    """
    GStreamer demuxer that runs in a subprocess to avoid FFmpeg conflicts.
    
        Drop-in replacement for GstRTPDemuxer with the same interface:
        - open() / close()
        - demux() generator yielding (h264_bytes, rtp_ts, rtp_ts_ns, absolute_ns)
        - Properties: width, height, fps, session_id, first_rtp_timestamp
    """

    def __init__(self: Any, video_path: str, use_tcp: bool = True) -> None: ...

    def close(self: Any) -> None: ...
        """
        Stop the subprocess.
        """

    def demux(self: Any) -> Any: ...
        """
        Yield (h264_bytes, rtp_ts, rtp_ts_ns, absolute_ns) from subprocess.
        """

    def open(self: Any, quiet: bool = True) -> None: ...
        """
        Start the GStreamer subprocess and wait for metadata.
        """

    def restart(self: Any) -> None: ...
        """
        Restart the demuxer (reconnect to RTSP).
        """


# From gstreamer_worker
class GStreamerAsyncWorker:
    """
    Async worker process that handles multiple cameras using GStreamer.
    
        This worker runs an async event loop to manage GStreamer pipelines
        for multiple cameras with efficient encoding (NVENC/x264/JPEG).
    """

    def __init__(self: Any, worker_id: int, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], stop_event: Any, health_queue: Any, command_queue: Optional[Any] = None, response_queue: Optional[Any] = None, gstreamer_encoder: str = 'auto', gstreamer_codec: str = 'h264', gstreamer_preset: str = 'low-latency', gpu_id: int = 0, platform: str = 'auto', use_hardware_decode: bool = True, use_hardware_jpeg: bool = True, jetson_use_nvmm: bool = True, frame_optimizer_mode: str = 'hash-only', fallback_on_error: bool = True, verbose_pipeline_logging: bool = False) -> None: ...
        """
        Initialize GStreamer async worker.
        
                Args:
                    worker_id: Unique identifier for this worker
                    camera_configs: List of camera configurations
                    stream_config: Streaming configuration (Redis, Kafka, etc.)
                    stop_event: Event to signal worker shutdown
                    health_queue: Queue for reporting health status
                    command_queue: Queue for receiving dynamic commands
                    response_queue: Queue for sending responses
                    gstreamer_encoder: Encoder type (auto, nvenc, x264, openh264, jpeg)
                    gstreamer_codec: Codec (h264, h265)
                    gstreamer_preset: NVENC preset
                    gpu_id: GPU device ID for NVENC
                    platform: Platform override (auto, jetson, desktop-gpu, intel, amd, cpu)
                    use_hardware_decode: Enable hardware decode
                    use_hardware_jpeg: Enable hardware JPEG encoding
                    jetson_use_nvmm: Use NVMM zero-copy on Jetson
                    frame_optimizer_mode: Frame optimization mode
                    fallback_on_error: Fallback to CPU on errors
                    verbose_pipeline_logging: Enable verbose logging
        """

    async def initialize(self: Any) -> Any: ...
        """
        Initialize async resources.
        """

    async def run(self: Any) -> Any: ...
        """
        Main worker loop.
        """


# From gstreamer_worker_manager
class GStreamerWorkerManager:
    """
    Manages multiple GStreamer async camera worker processes.
    
        This manager coordinates worker processes using GStreamer pipelines
        for efficient hardware/software video encoding. It follows the same
        API as WorkerManager for drop-in replacement.
    """

    def __init__(self: Any, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], num_workers: Optional[int] = None, cpu_percentage: float = 0.9, max_cameras_per_worker: int = 100, gstreamer_encoder: str = 'auto', gstreamer_codec: str = 'h264', gstreamer_preset: str = 'low-latency', gpu_id: int = 0, platform: str = 'auto', use_hardware_decode: bool = True, use_hardware_jpeg: bool = True, jetson_use_nvmm: bool = True, frame_optimizer_mode: str = 'hash-only', fallback_on_error: bool = True, verbose_pipeline_logging: bool = False) -> None: ...
        """
        Initialize GStreamer worker manager.
        
                Args:
                    camera_configs: List of all camera configurations
                    stream_config: Streaming configuration (Redis, Kafka, etc.)
                    num_workers: Number of worker processes (auto-calculated if None)
                    cpu_percentage: Percentage of CPU cores to use (default: 90%)
                    max_cameras_per_worker: Maximum cameras per worker
                    gstreamer_encoder: Encoder type (auto, nvenc, x264, openh264, jpeg)
                    gstreamer_codec: Codec (h264, h265)
                    gstreamer_preset: NVENC preset
                    gpu_id: GPU device ID for NVENC
                    platform: Platform override (auto, jetson, desktop-gpu, intel, amd, cpu)
                    use_hardware_decode: Enable hardware decode
                    use_hardware_jpeg: Enable hardware JPEG encoding
                    jetson_use_nvmm: Use NVMM zero-copy on Jetson
                    frame_optimizer_mode: Frame optimization mode (hash-only, dual-appsink, disabled)
                    fallback_on_error: Fallback to CPU pipeline on errors
                    verbose_pipeline_logging: Enable verbose pipeline logging
        """

    def add_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Add a camera to least-loaded worker.
        """

    def get_camera_assignments(self: Any) -> Dict[str, int]: ...
        """
        Get camera-to-worker assignments.
        """

    def get_worker_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get worker statistics.
        """

    def monitor(self: Any, duration: Optional[float] = None) -> Any: ...
        """
        Monitor workers and collect health reports.
        """

    def remove_camera(self: Any, stream_key: str) -> bool: ...
        """
        Remove a camera.
        """

    def run(self: Any, duration: Optional[float] = None) -> Any: ...
        """
        Start workers and monitor.
        """

    def start(self: Any) -> Any: ...
        """
        Start all workers.
        """

    def stop(self: Any, timeout: float = 15.0) -> Any: ...
        """
        Stop all workers.
        """

    def update_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Update a camera's configuration.
        """


# From message_builder
class StreamMessageBuilder:
    """
    Builds stream messages with proper structure and metadata.
    """

    def __init__(self: Any, service_id: str, strip_input_content: bool = False) -> None: ...
        """
        Initialize message builder.
        
                Args:
                    service_id: Service/deployment identifier
                    strip_input_content: Strip content for out-of-band retrieval
        """

    def build_frame_metadata(self: Any, input_source: Union[str, int], video_props: Dict[str, Any], fps: int, quality: int, actual_width: int, actual_height: int, stream_type: str, frame_counter: int, is_video_chunk: bool, chunk_duration_seconds: Optional[float], chunk_frames: Optional[int], camera_location: Optional[str]) -> Dict[str, Any]: ...
        """
        Build frame metadata dictionary.
        
                Args:
                    input_source: Input source identifier
                    video_props: Video properties dictionary
                    fps: Target FPS
                    quality: Quality setting
                    actual_width: Frame width
                    actual_height: Frame height
                    stream_type: Type of stream source
                    frame_counter: Current frame number
                    is_video_chunk: Whether this is a chunked stream
                    chunk_duration_seconds: Chunk duration
                    chunk_frames: Number of frames per chunk
                    camera_location: Camera location description
        
                Returns:
                    Metadata dictionary
        """

    def build_message(self: Any, frame_data: Any, stream_key: str, stream_group_key: str, codec: str, metadata: Dict[str, Any], topic: str, broker_config: str, input_order: int, last_read_time: float, last_write_time: float, last_process_time: float, cached_frame_id: Optional[str] = None) -> Dict[str, Any]: ...
        """
        Build complete stream message.
        
                Supports both normal frames (with content) and cached frames (empty content + cached_frame_id).
        
                Args:
                    frame_data: Encoded frame bytes (can be empty for cached frames)
                    stream_key: Stream identifier
                    stream_group_key: Stream group identifier
                    codec: Video codec (use "cached" for cached frames)
                    metadata: Frame metadata
                    topic: Topic name
                    broker_config: Broker configuration string
                    input_order: Input order number
                    last_read_time: Last read time
                    last_write_time: Last write time
                    last_process_time: Last process time
                    cached_frame_id: Frame ID to use cached results from (None for normal frames)
        
                Returns:
                    Complete message dictionary
        """


# From nvdec
class DemuxerType(Enum):
    """
    Demuxer backend selection.
    
        NVC: PyNvVideoCodec demuxer - fastest for local files
        GSTREAMER: GStreamer demuxer - provides ABSOLUTE RTP timestamps for RTSP
    """

    GSTREAMER: str
    NVC: str

    pass

# From nvdec
class GatewayConfig:
    """
    Configuration for the streaming gateway.
    """

    pass

# From nvdec
class NVDECDecoderPool:
    """
    Pool of NVDEC decoders that time-multiplex streams.
    
        Each decoder is exclusively owned by one worker thread.
        Outputs NV12: 1.5*H*W bytes (50% smaller than RGB).
    
        Supports two demuxer backends:
        - NVC (default): PyNvVideoCodec demuxer, fastest for local files
        - GStreamer: Provides ABSOLUTE RTP timestamps for RTSP streams
    """

    def __init__(self: Any, pool_size: int, gpu_id: int = 0, demuxer_type: str = 'nvc') -> None: ...

    def assign_stream(self: Any, stream_id: int, camera_id: str, video_path: str, width: int = 640, height: int = 640, stream_type: str = 'file', demuxer_type: str = None) -> bool: ...
        """
        Assign a stream to a decoder (round-robin).
        
                Supports two demuxer backends:
                - NVC: PyNvVideoCodec demuxer (fastest for files)
                - GStreamer: Provides ABSOLUTE RTP timestamps for RTSP
        
                Args:
                    stream_id: Stream identifier
                    camera_id: Camera identifier
                    video_path: Video file path or RTSP URL
                    width: Target width
                    height: Target height
                    stream_type: Source type ("file" or "rtsp")
                    demuxer_type: Override demuxer type ("nvc" or "gstreamer"), uses pool default if None
        """

    def close(self: Any) -> Any: ...
        """
        Close all decoders and demuxers.
        """

    def decode_round(self: Any, decoder_idx: int, frames_per_stream: int = 4, target_h: int = 640, target_w: int = 640) -> Tuple[int, List[Tuple[str, cp.ndarray, int, str, str, int, Optional[int]]]]: ...
        """
        Decode frames and convert to NV12.
        
                Supports two demuxer backends:
                - NVC: PyNvVideoCodec demuxer (fastest for local files)
                - GStreamer: Provides ABSOLUTE RTP timestamps for RTSP streams
        
                Returns:
                    (total_frames, [(camera_id, nv12_tensor, timestamp_ns, stream_type, session_id, session_start_ns, rtp_timestamp), ...])
                    where:
                    - timestamp_ns: For RTSP = T0 + PTS (absolute wall clock ns), for files = PTS (video-relative ns)
                    - stream_type: "rtsp" or "file"
                    - session_id: 8-char unique ID for RTSP (changes on reconnect), empty for files
                    - session_start_ns: T0 wall clock when RTSP connected (0 for files)
                    - rtp_timestamp: ABSOLUTE 32-bit RTP timestamp (GStreamer only, None for NVC)
        """

    def get_camera_ids_for_decoder(self: Any, decoder_idx: int) -> List[str]: ...
        """
        Get camera IDs for a decoder.
        """

    def get_source_fps_for_decoder(self: Any, decoder_idx: int) -> float: ...
        """
        Get average source FPS for streams assigned to a decoder.
        
                Used when target_fps=0 to cap output to source video rate.
        """


# From nvdec
class StreamConfig:
    """
    Configuration for a single video stream.
    """

    pass

# From nvdec
class StreamState:
    """
    Track state for each logical stream in NVDEC pool.
    """

    pass

# From nvdec
class StreamingGateway:
    """
    Multi-stream video producer outputting NV12 tensors (minimal IPC payload).
    """

    def __init__(self: Any, config: Any) -> None: ...

    def start(self: Any) -> Dict: ...
        """
        Start the gateway.
        """

    def stop(self: Any) -> Any: ...
        """
        Stop all workers.
        """


# From nvdec
class VideoDownloader:
    """
    Downloads and caches video files from HTTPS URLs.
    
        PyNvVideoCodec uses a bundled FFmpeg that doesn't have HTTPS support.
        This class downloads HTTPS videos to local files before passing them
        to the NVDEC demuxer.
    
        Features:
        - URL deduplication: same video URL (ignoring query params) is only downloaded once
        - Disk caching: reuses existing files across runs
        - Progress tracking for large files
        - Dynamic timeout based on file size
    """

    def __init__(self: Any) -> None: ...
        """
        Initialize the video downloader.
        """

    def cleanup(self: Any) -> None: ...
        """
        Clean up downloaded temporary files.
        """

    def prepare_source(self: Any, video_path: str, camera_id: str) -> str: ...
        """
        Prepare video source, downloading HTTPS URLs if needed.
        
                Args:
                    video_path: Video file path, RTSP URL, or HTTPS URL
                    camera_id: Camera identifier for logging
        
                Returns:
                    Local file path (downloaded if HTTPS) or original path
        """


# From nvdec_worker_manager
class NVDECWorkerManager:
    """
    Manager for NVDEC worker processes - fully dynamic camera configuration.
    
        This manager wraps the existing nvdec_pool_process function to integrate
        with StreamingGateway. Key features:
    
        - Fully dynamic camera configuration (add, remove, update at runtime)
        - Smart per-GPU restarts: only restarts workers for GPUs whose cameras changed
        - Debounced batching: rapid successive changes are batched into a single restart
        - Stable GPU assignment: cameras are assigned to GPUs via consistent hashing,
          so add/remove of one camera doesn't shuffle other cameras across GPUs
        - Outputs to CUDA IPC ring buffers (not Redis/Kafka)
        - NV12 format output (50% smaller than RGB)
        - One worker process per GPU
    """

    def __init__(self: Any, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], gpu_id: int = 0, num_gpus: int = 0, nvdec_pool_size: int = 8, nvdec_burst_size: int = 4, frame_width: int = 640, frame_height: int = 640, num_slots: int = 32, target_fps: int = 0, duration_sec: float = 0, demuxer_type: str = 'nvc', restart_delay: float = 1.0) -> None: ...
        """
        Initialize NVDEC Worker Manager.
        
                Args:
                    camera_configs: List of camera configuration dicts with keys:
                        - camera_id or stream_key: Unique identifier (used for ring buffer naming)
                        - source: Video file path or RTSP URL
                        - width: Optional frame width (default: frame_width)
                        - height: Optional frame height (default: frame_height)
                        - fps: FPS limit for this camera (used by default)
                    stream_config: Stream configuration (unused, for interface consistency)
                    gpu_id: Primary GPU device ID (starting GPU for round-robin assignment)
                    num_gpus: Number of GPUs to use (0 = auto-detect all available GPUs)
                    nvdec_pool_size: Number of NVDEC decoders per GPU
                    nvdec_burst_size: Frames per stream before rotating to next
                    frame_width: Default output frame width (used if camera config doesn't specify)
                    frame_height: Default output frame height (used if camera config doesn't specify)
                    num_slots: Ring buffer slots per camera
                    target_fps: Global FPS override (0 = use per-camera FPS from config)
                    duration_sec: Duration to run (0 = infinite until stop)
                    demuxer_type: Demuxer backend - "nvc" (PyNvVideoCodec, fastest for files) or
                                  "gstreamer" (provides ABSOLUTE RTP timestamps for RTSP streams)
                    restart_delay: Seconds to wait before restarting after a config change,
                                   allowing multiple rapid changes to be batched into one restart
        """

    def add_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Add a new camera at runtime.
        
                The config change is applied immediately. If the manager is running,
                a debounced per-GPU restart is scheduled so that rapid successive adds
                are batched into a single restart affecting only the relevant GPU(s).
        
                Args:
                    camera_config: Camera configuration dict
        
                Returns:
                    True if the camera was accepted (restart may be pending)
        """

    def get_camera_assignments(self: Any) -> Dict[str, int]: ...
        """
        Return mapping of camera_id to GPU ID.
        
                Returns:
                    Dict mapping camera_id -> gpu_id
        """

    def get_worker_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Return statistics from workers.
        
                Returns:
                    Dict with worker count, camera count, FPS metrics, per-GPU stats, etc.
        """

    def is_running(self: Any) -> bool: ...
        """
        Check if the manager is currently running.
        """

    def remove_camera(self: Any, stream_key: str) -> bool: ...
        """
        Remove a camera at runtime.
        
                Args:
                    stream_key: Camera ID / stream key to remove
        
                Returns:
                    True if the camera was found and removed (restart may be pending)
        """

    def restart_workers(self: Any) -> None: ...
        """
        Full restart of all workers (stops everything, then starts fresh).
        
                This is the heavy-weight approach. Prefer add_camera/remove_camera/update_camera
                which use smart per-GPU restarts with debouncing.
        """

    def start(self: Any) -> None: ...
        """
        Start NVDEC worker processes (one per GPU).
        
                Initializes shared multiprocessing primitives and starts a worker
                process for each GPU that has cameras assigned. If no cameras are
                configured, primitives are still created so that later add_camera
                calls can schedule per-GPU starts without a full restart.
        """

    def stop(self: Any, timeout: float = 15.0) -> None: ...
        """
        Stop all worker processes and cancel any pending restart.
        
                Args:
                    timeout: Maximum time to wait for each worker to stop gracefully
        """

    def update_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Update a camera's configuration at runtime.
        
                Args:
                    camera_config: Updated camera configuration dict
        
                Returns:
                    True if the camera was found and updated (restart may be pending)
        """


# From platform_pipelines
class AmdGpuPipelineBuilder(IntelGpuPipelineBuilder):
    """
    AMD GPU pipeline builder with VAAPI.
    
        Inherits from IntelGpuPipelineBuilder as AMD uses same VAAPI interface.
        Can be extended in future for AMD-specific optimizations.
    """

    pass

# From platform_pipelines
class CpuOnlyPipelineBuilder(PipelineBuilder):
    """
    CPU-only fallback pipeline builder.
    
        Uses software encoders/decoders:
        - jpegenc for JPEG
        - x264enc for H.264
        - avdec_h264 for decode
    """

    def build_convert_element(self: Any) -> str: ...

    def build_decode_element(self: Any, source_type: str, source: str) -> str: ...

    def build_encode_element(self: Any, encoder: str, quality: int, bitrate: int) -> Tuple[str, str]: ...

    def build_memory_element(self: Any, encoder: str) -> str: ...


# From platform_pipelines
class DesktopNvidiaGpuPipelineBuilder(PipelineBuilder):
    """
    Desktop NVIDIA GPU pipeline builder.
    
        Optimizations:
        - nvdec for hardware video decode
        - nvh264enc/nvh265enc for hardware video encode
        - CUDA memory for zero-copy (video codecs only)
    
        Limitations:
        - NO hardware JPEG encoding (GStreamer limitation on desktop GPUs)
        - Must use CPU jpegenc
    """

    def build_convert_element(self: Any) -> str: ...

    def build_decode_element(self: Any, source_type: str, source: str) -> str: ...

    def build_encode_element(self: Any, encoder: str, quality: int, bitrate: int) -> Tuple[str, str]: ...

    def build_memory_element(self: Any, encoder: str) -> str: ...


# From platform_pipelines
class IntelGpuPipelineBuilder(PipelineBuilder):
    """
    Intel GPU pipeline builder with VAAPI.
    
        Optimizations:
        - vaapijpegenc for hardware JPEG encoding
        - vaapih264enc/h265enc for hardware video encode
        - vaapih264dec for hardware video decode
    """

    def build_convert_element(self: Any) -> str: ...

    def build_decode_element(self: Any, source_type: str, source: str) -> str: ...

    def build_encode_element(self: Any, encoder: str, quality: int, bitrate: int) -> Tuple[str, str]: ...

    def build_memory_element(self: Any, encoder: str) -> str: ...


# From platform_pipelines
class JetsonPipelineBuilder(PipelineBuilder):
    """
    Jetson-optimized pipeline builder.
    
        Optimizations:
        - nvjpegenc for hardware JPEG encoding (10x faster than CPU)
        - nvvidconv for GPU-accelerated color conversion
        - NVMM zero-copy memory
        - nvv4l2decoder for hardware video decode
        - nvv4l2h264enc/h265enc for hardware video encode
    """

    def build_convert_element(self: Any) -> str: ...

    def build_decode_element(self: Any, source_type: str, source: str) -> str: ...

    def build_encode_element(self: Any, encoder: str, quality: int, bitrate: int) -> Tuple[str, str]: ...

    def build_memory_element(self: Any, encoder: str) -> str: ...


# From platform_pipelines
class PipelineBuilder(ABC):
    """
    Abstract base class for platform-specific pipeline builders.
    
        Implements Template Method pattern with platform-specific overrides.
    """

    def __init__(self: Any, config: Any, platform_info: Any) -> None: ...
        """
        Initialize pipeline builder.
        
                Args:
                    config: GStreamer configuration
                    platform_info: Detected platform information
        """

    def build_complete_pipeline(self: Any, builder_config: Dict) -> str: ...
        """
        Build complete GStreamer pipeline (Template Method).
        
                Args:
                    builder_config: Pipeline configuration dict with:
                        - source_type: str
                        - source: str
                        - width: int
                        - height: int
                        - fps: int
                        - encoder: str
                        - quality: int
                        - bitrate: int
        
                Returns:
                    Complete GStreamer pipeline string
        """

    def build_convert_element(self: Any) -> str: ...
        """
        Build color conversion element (CPU or GPU accelerated).
        
                Returns:
                    GStreamer converter element string
        """

    def build_decode_element(self: Any, source_type: str, source: str) -> str: ...
        """
        Build hardware-accelerated decode element for source.
        
                Args:
                    source_type: Type of source (rtsp, file, camera)
                    source: Source URI or path
        
                Returns:
                    GStreamer decode element string
        """

    def build_dual_appsink_pipeline(self: Any, builder_config: Dict) -> str: ...
        """
        Build pipeline with dual appsinks for FrameOptimizer.
        
                Args:
                    builder_config: Pipeline configuration dict
        
                Returns:
                    Pipeline string with similarity-sink and output-sink
        """

    def build_encode_element(self: Any, encoder: str, quality: int, bitrate: int) -> Tuple[str, str]: ...
        """
        Build encoder element and output caps.
        
                Args:
                    encoder: Encoder type (jpeg, h264, h265)
                    quality: Quality setting (JPEG quality or video quality hint)
                    bitrate: Bitrate for video encoders (bps)
        
                Returns:
                    Tuple of (encoder_string, output_caps)
        """

    def build_memory_element(self: Any, encoder: str) -> str: ...
        """
        Build memory transfer/format element (NVMM, CUDA, standard).
        
                Args:
                    encoder: Encoder type being used
        
                Returns:
                    GStreamer memory/format caps string
        """


# From platform_pipelines
class PipelineFactory:
    """
    Factory for selecting appropriate pipeline builder based on platform.
    """

    def get_builder(config: Any, platform_info: Any) -> Any: ...
        """
        Select and instantiate appropriate pipeline builder.
        
                Args:
                    config: GStreamer configuration
                    platform_info: Detected platform information
        
                Returns:
                    Platform-specific PipelineBuilder instance
        """


# From retry_manager
class RetryConfig:
    """
    Configuration for retry logic.
    """

    pass

# From retry_manager
class RetryManager:
    """
    Manages retry logic and connection state with infinite retries.
    """

    def __init__(self: Any, stream_key: str) -> None: ...
        """
        Initialize retry manager.
        
                Args:
                    stream_key: Stream identifier for logging
        """

    def get_stats(self: Any) -> dict: ...
        """
        Get retry statistics.
        
                Returns:
                    Dictionary with retry statistics
        """

    def handle_connection_failure(self: Any, error: Any) -> Any: ...
        """
        Handle connection failure and calculate backoff.
        
                Args:
                    error: The exception that occurred
        """

    def handle_successful_reconnect(self: Any) -> Any: ...
        """
        Handle successful reconnection.
        """

    def record_read_failure(self: Any) -> Any: ...
        """
        Record a frame read failure.
        """

    def record_success(self: Any) -> Any: ...
        """
        Record a successful operation (resets failure counter).
        """

    def should_reconnect(self: Any) -> bool: ...
        """
        Check if should reconnect due to consecutive failures.
        
                Returns:
                    True if should reconnect
        """

    def wait_after_read_failure(self: Any) -> Any: ...
        """
        Brief pause after read failure before retrying.
        """

    def wait_before_restart(self: Any) -> Any: ...
        """
        Brief pause before restarting video file.
        """

    def wait_before_retry(self: Any) -> Any: ...
        """
        Wait with exponential backoff before retry.
        
                This implements exponential backoff with a maximum cooldown.
                The system will NEVER give up - it retries forever.
        """


# From stream_statistics
class StreamStatistics:
    """
    Manages streaming statistics and timing data.
    """

    def __init__(self: Any) -> None: ...
        """
        Initialize statistics tracker.
        """

    MAX_HISTORY_SIZE: int
    STATS_LOG_INTERVAL: int

    def add_bytes_saved(self: Any, bytes_count: int) -> Any: ...
        """
        Add to bytes saved counter.
        """

    def clear_timing_history(self: Any, stream_key: Optional[str] = None) -> Any: ...
        """
        Clear accumulated timing history for a stream or all streams.
        
                This should be called after metrics have been reported to prevent
                unbounded memory growth.
        
                Args:
                    stream_key: Specific stream key to clear, or None to clear all streams
        """

    def get_next_input_order(self: Any, stream_key: str) -> int: ...
        """
        Get next input order number for a stream.
        
                Args:
                    stream_key: Stream identifier
        
                Returns:
                    Next input order number
        """

    def get_timing(self: Any, stream_key: str) -> Tuple[float, float, float]: ...
        """
        Get timing data for a stream.
        
                Args:
                    stream_key: Stream identifier
        
                Returns:
                    Tuple of (read_time, write_time, process_time)
        """

    def get_timing_statistics(self: Any, stream_key: str) -> Dict[str, Any]: ...
        """
        Calculate min/max/avg statistics from accumulated timing history.
        
                Args:
                    stream_key: Stream identifier
        
                Returns:
                    Dictionary with statistical metrics for read_time, write_time, process_time,
                    frame_size, and FPS calculations
        """

    def get_timing_stats(self: Any, stream_key: Optional[str] = None) -> Dict[str, Any]: ...
        """
        Get timing statistics for streams.
        
                Args:
                    stream_key: Specific stream key, or None for all streams
        
                Returns:
                    Dictionary with timing statistics
        """

    def get_transmission_stats(self: Any, video_codec: str, active_streams: int) -> Dict[str, Any]: ...
        """
        Get comprehensive transmission statistics.
        
                Args:
                    video_codec: Current video codec being used
                    active_streams: Number of active streams
        
                Returns:
                    Dictionary with all transmission statistics
        """

    def increment_frames_diff_sent(self: Any) -> Any: ...
        """
        Increment diff frames counter.
        """

    def increment_frames_sent(self: Any) -> Any: ...
        """
        Increment sent frames counter.
        """

    def increment_frames_skipped(self: Any) -> Any: ...
        """
        Increment skipped frames counter.
        """

    def log_aggregated_stats(self: Any) -> None: ...
        """
        Log aggregated metrics across all streams.
        """

    def log_detailed_stats(self: Any, stream_key: str) -> None: ...
        """
        Log comprehensive metrics for a stream.
        
                Args:
                    stream_key: Stream identifier
        """

    def log_periodic_stats(self: Any, stream_key: str, read_time: float, encoding_time: float, write_time: float) -> Any: ...
        """
        Log periodic statistics.
        
                Args:
                    stream_key: Stream identifier
                    read_time: Time spent reading frame
                    encoding_time: Time spent encoding frame
                    write_time: Time spent writing frame
        """

    def reset(self: Any) -> Any: ...
        """
        Reset all statistics.
        """

    def should_log_stats(self: Any) -> bool: ...
        """
        Check if it's time to log statistics.
        
                Returns:
                    True if should log stats based on interval
        """

    def update_timing(self: Any, stream_key: str, read_time: float, write_time: float, process_time: float, frame_size: Optional[int] = None, encoding_time: float = 0.0) -> Any: ...
        """
        Update timing statistics for a stream.
        
                Args:
                    stream_key: Stream identifier
                    read_time: Time spent reading frame
                    write_time: Time spent writing/sending frame
                    process_time: Total processing time
                    frame_size: Size of encoded frame in bytes (ACG frame size)
                    encoding_time: Time spent encoding frame (NEW)
        """


# From video_capture_manager
class VideoCaptureManager:
    """
    Manages video capture from various sources with retry logic and caching.
    
        Features URL deduplication: if multiple cameras use the same video URL
        (ignoring query parameters like AWS signed URL tokens), the video is only
        downloaded once and the local path is shared between cameras.
    """

    def __init__(self: Any) -> None: ...
        """
        Initialize video capture manager.
        """

    def calculate_frame_skip(self: Any, source_type: str, original_fps: float, target_fps: int) -> int: ...
        """
        Calculate frame skip rate for RTSP streams.
        
                Args:
                    source_type: Type of video source
                    original_fps: Original FPS from video
                    target_fps: Target FPS for streaming
        
                Returns:
                    Frame skip rate (1 means no skip)
        """

    def cleanup(self: Any) -> None: ...
        """
        Clean up downloaded temporary files.
        """

    def get_video_properties(self: Any, cap: Any) -> Dict[str, Any]: ...
        """
        Extract video properties from capture.
        
                Args:
                    cap: VideoCapture object
        
                Returns:
                    Dictionary with video properties
        """

    def open_capture(self: Any, source: Union[str, int], width: Optional[int] = None, height: Optional[int] = None) -> Tuple[cv2.VideoCapture, str]: ...
        """
        Open video capture with retry logic.
        
                Args:
                    source: Video source
                    width: Target width for camera
                    height: Target height for camera
        
                Returns:
                    Tuple of (VideoCapture object, source_type)
        
                Raises:
                    RuntimeError: If unable to open capture after retries
        """

    def prepare_source(self: Any, source: Union[str, int], stream_key: str) -> Union[str, int]: ...
        """
        Prepare video source, downloading if it's a URL.
        
                Args:
                    source: Video source (camera index, file path, or URL)
                    stream_key: Stream identifier for caching
        
                Returns:
                    Prepared source (downloaded file path or original source)
        """


# From video_capture_manager
class VideoSourceConfig:
    """
    Configuration for video source handling.
    """

    pass

# From worker_manager
class WorkerManager:
    """
    Manages multiple async camera worker processes with dynamic scaling.
    
        This manager coordinates worker processes based on available CPU cores,
        distributing cameras across them for optimal throughput. Each worker handles
        multiple cameras concurrently using async I/O.
    """

    def __init__(self: Any, camera_configs: List[Dict[str, Any]], stream_config: Dict[str, Any], num_workers: Optional[int] = None, cpu_percentage: float = 0.9, num_encoding_workers: Optional[int] = None, max_cameras_per_worker: int = 100, use_shm: bool = USE_SHM, shm_slot_count: int = 1000, shm_frame_format: str = 'BGR', drop_stale_frames: bool = False, use_simple_read: bool = True, pin_cpu_affinity: bool = False, buffer_size: int = 1, frame_optimizer_enabled: bool = False) -> None: ...
        """
        Initialize worker manager with dynamic CPU-based scaling.
        
                Args:
                    camera_configs: List of all camera configurations
                    stream_config: Streaming configuration (Redis, Kafka, etc.)
                    num_workers: Number of worker processes (default: auto-calculated from CPU cores)
                    cpu_percentage: Percentage of CPU cores to use (default: 0.9 = 90%)
                    num_encoding_workers: Number of encoding workers (default: CPU_count - 2)
                    max_cameras_per_worker: Maximum cameras per worker for load balancing (default: 100)
                    use_shm: Enable SHM mode (raw frames in shared memory, metadata in Redis)
                    shm_slot_count: Number of frame slots per camera ring buffer
                    shm_frame_format: Frame format for SHM storage
                    drop_stale_frames: Use grab()/grab()/retrieve() pattern for latest frame
                    use_simple_read: Use cap.read() directly instead of grab/retrieve pattern
                    pin_cpu_affinity: Pin worker processes to specific CPU cores for cache locality
                    buffer_size: VideoCapture buffer size (1 = minimal latency)
                    frame_optimizer_enabled: Enable frame similarity detection (skip similar frames for bandwidth saving)
        """

    def add_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Add a camera to the least-loaded worker at runtime.
        
                Args:
                    camera_config: Camera configuration dictionary with stream_key, source, etc.
        
                Returns:
                    bool: True if camera was added successfully
        """

    def get_camera_assignments(self: Any) -> Dict[str, int]: ...
        """
        Get current camera-to-worker assignments.
        
                Returns:
                    Dict mapping stream_key to worker_id
        """

    def get_worker_statistics(self: Any) -> Dict[str, Any]: ...
        """
        Get detailed statistics about workers and cameras.
        
                Returns:
                    Dict with worker statistics for metrics/monitoring
        """

    def monitor(self: Any, duration: Optional[float] = None) -> Any: ...
        """
        Monitor workers and collect health reports.
        
                Args:
                    duration: How long to monitor (None = indefinite)
        """

    def remove_camera(self: Any, stream_key: str) -> bool: ...
        """
        Remove a camera from its assigned worker.
        
                Args:
                    stream_key: Unique identifier for the camera stream
        
                Returns:
                    bool: True if camera removal was initiated
        """

    def run(self: Any, duration: Optional[float] = None) -> Any: ...
        """
        Start workers and monitor until stopped.
        
                This is the main entry point that combines start(), monitor(), and stop().
        
                Args:
                    duration: How long to run (None = until interrupted)
        """

    def start(self: Any) -> Any: ...
        """
        Start all workers and begin streaming.
        """

    def stop(self: Any, timeout: float = 15.0) -> Any: ...
        """
        Stop all workers gracefully.
        
                Args:
                    timeout: Maximum time to wait per worker (seconds)
        """

    def update_camera(self: Any, camera_config: Dict[str, Any]) -> bool: ...
        """
        Update a camera's configuration (removes and re-adds with new config).
        
                Args:
                    camera_config: Updated camera configuration
        
                Returns:
                    bool: True if update was initiated
        """


from . import async_camera_worker, async_ffmpeg_worker, camera_streamer, device_detection, encoder_manager, encoding_pool_manager, ffmpeg_camera_streamer, ffmpeg_config, ffmpeg_worker_manager, frame_processor, gstreamer_camera_streamer, gstreamer_rtp_demuxer, gstreamer_subprocess_demuxer, gstreamer_worker, gstreamer_worker_manager, message_builder, nvdec, nvdec_worker_manager, platform_pipelines, retry_manager, stream_statistics, video_capture_manager, worker_manager