"""Auto-generated stub for module: nvdec."""
from typing import Any, Dict, List, Optional, Tuple

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from gstreamer_subprocess_demuxer import GStreamerSubprocessDemuxer
from gstreamer_subprocess_demuxer import GStreamerSubprocessDemuxer
from matrice_common.stream.cuda_shm_ring_buffer import CudaIpcRingBuffer, GlobalFrameCounter
from matrice_common.stream.gpu_camera_map import GpuCameraMap
from pathlib import Path
from urllib.parse import urlparse, urlunparse
import PyNvVideoCodec as nvc
import argparse
import cupy as cp
import hashlib
import logging
import multiprocessing as mp
import numpy as _np
import numpy as np
import os
import queue as thread_queue
import requests
import tempfile
import threading
import time
import traceback
import uuid

# Constants
GPU_CAMERA_MAP_AVAILABLE: bool
GSTREAMER_DEMUXER_AVAILABLE: bool
GstRTPDemuxer: None
NV12_HEIGHT: Any
TARGET_HEIGHT: int
TARGET_WIDTH: int
logger: Any

# Functions
def get_video_downloader() -> Any: ...
    """
    Get or create the global VideoDownloader instance.
    """
def main() -> Any: ...
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).
    """
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")
    """
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)
    """
def setup_logging(quiet: bool = True) -> Any: ...
    """
    Configure logging level based on quiet mode.
    """
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).
    """

# Classes
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
class GatewayConfig:
    """
    Configuration for the streaming gateway.
    """

    pass
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.
        """

class StreamConfig:
    """
    Configuration for a single video stream.
    """

    pass
class StreamState:
    """
    Track state for each logical stream in NVDEC pool.
    """

    pass
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.
        """

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
        """

