{"record":{"id":"30a778d663ab64af","repo":"hacksider/Deep-Live-Cam","slug":"invalid-device-index-device-index-available-dev","errorCode":null,"errorMessage":"Invalid device index {device_index}. Available devices: {len(devices)}","messagePattern":"Invalid device index (.+?)\\. Available devices: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"modules/video_capture.py","lineNumber":32,"sourceCode":"    def __init__(self, device_index: int):\n        self.device_index = device_index\n        self.frame_callback = None\n        self._current_frame = None\n        self._frame_ready = threading.Event()\n        self.is_running = False\n        self.cap = None\n        # Actual values reported by the camera after configuration\n        self.actual_width: int = 0\n        self.actual_height: int = 0\n        self.actual_fps: float = 0.0\n\n        # Initialize Windows-specific components if on Windows\n        if platform.system() == \"Windows\":\n            self.graph = FilterGraph()\n            # Verify device exists\n            devices = self.graph.get_input_devices()\n            if self.device_index >= len(devices):\n                raise ValueError(\n                    f\"Invalid device index {device_index}. Available devices: {len(devices)}\"\n                )\n\n    def start(self, width: int = 960, height: int = 540, fps: int = 60) -> bool:\n        \"\"\"Initialize and start video capture\"\"\"\n        try:\n            if platform.system() == \"Windows\":\n                # device_index comes from pygrabber.FilterGraph (DirectShow\n                # enumeration), so open with DSHOW first to preserve mapping.\n                # MSMF and DirectShow enumerate cameras in different orders, so\n                # opening MSMF with a DSHOW index silently selects the wrong\n                # camera. MSMF/ANY remain as fallbacks for cameras DSHOW can't\n                # open.\n                #\n                # Pass codec + resolution + fps as construction params (OpenCV\n                # 4.6+). DSHOW locks the pixel format at open time and ignores\n                # later cap.set(CAP_PROP_FOURCC, ...) — without this, DSHOW\n                # falls back to uncompressed YUYV at 1080p, which is USB-","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/hacksider/Deep-Live-Cam/blob/987f6b392b1740623b3fa8a5cb46fdd0b7e185b9/modules/video_capture.py#L14-L50","documentation":"ValueError raised in the VideoCapture constructor (modules/video_capture.py, Windows-only path) when the requested device_index is >= the number of cameras returned by pygrabber FilterGraph.get_input_devices() (DirectShow enumeration). It is a fail-fast check at construction time so a bogus index doesn't reach OpenCV, where it would fail more obscurely. Note the message embeds len(devices) but the validation is done in __init__ before any capture starts.","triggerScenarios":"Constructing VideoCapture with an index >= camera count on Windows (e.g. index 1 with a single camera, index 0 with none); a camera being unplugged or disabled between enumeration in the UI and object construction; an index saved from a previous session when the machine had more cameras; virtual cameras not exposing a DirectShow filter so they aren't counted.","commonSituations":"Hardcoded camera index from a different machine; device disconnected/privacy-killed (Windows camera privacy toggle hides it from DirectShow); hot-plug races; the camera existing but its driver not registering a DirectShow capture filter (some modern drivers are MSMF-only), making the DSHOW device list shorter than expected.","solutions":["Enumerate devices with the same method and pick a valid index dynamically: from pygrabber.dshow_graph import FilterGraph; n = len(FilterGraph().get_input_devices()); use 0 <= index < n.","If the camera is genuinely present but not listed, enable it in Windows privacy settings (Settings > Privacy > Camera) and confirm its driver exposes a DirectShow filter; update or switch the driver if MSMF-only.","Persist device selection by name rather than index where possible, resolving the name to an index at startup, since enumeration order changes across reboots/hot-plugs.","If no camera is attached, connect one or point the app at a video file/stream instead."],"exampleFix":"# before\ncap = VideoCapture(device_index=1)  # single camera attached -> ValueError\n\n# after\nfrom pygrabber.dshow_graph import FilterGraph\nnames = FilterGraph().get_input_devices()\nif not names:\n    raise SystemExit(\"No DirectShow cameras found\")\ndevice_index = names.index(\"My Webcam\") if \"My Webcam\" in names else 0\ncap = VideoCapture(device_index=device_index)","handlingStrategy":"validation","validationCode":"from pygrabber.dshow_graph import FilterGraph  # Windows only\ndevices = FilterGraph().get_input_devices()\nif not devices:\n    raise SystemExit(\"No DirectShow cameras found\")\nif not (0 <= device_index < len(devices)):\n    device_index = 0  # or surface a device picker with `devices` names\ncap = VideoCapture(device_index=device_index)","typeGuard":"def is_valid_device_index(index: int) -> bool:\n    if index < 0:\n        return False\n    try:\n        from pygrabber.dshow_graph import FilterGraph\n        return index < len(FilterGraph().get_input_devices())\n    except Exception:\n        return False  # enumeration unavailable; let VideoCapture decide","tryCatchPattern":"try:\n    cap = VideoCapture(device_index=i)\nexcept ValueError as e:\n    if \"Invalid device index\" in str(e):\n        # re-enumerate and pick a live camera instead of a hardcoded index\n        i = 0\n        cap = VideoCapture(device_index=i)\n    else:\n        raise","preventionTips":["Enumerate devices at startup and let the user/config pick from names, not raw indices.","Re-validate the index immediately before constructing VideoCapture — hot-plug changes the count.","Check Windows camera privacy settings when a known camera vanishes from the list.","Remember this list is DirectShow-based; MSMF-only drivers won't appear in it."],"tags":["python","opencv","windows","directshow","camera","device-enumeration"],"backgroundTag":null,"analyzedSha":"987f6b392b1740623b3fa8a5cb46fdd0b7e185b9","analyzedAt":"2026-08-14T19:48:25.860Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}