273 lines
9.9 KiB
Python
273 lines
9.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""USB 摄像头枚举与过滤:只允许 USB 接入的摄像头工作。
|
||
|
||
现场为什么要卡死 USB
|
||
--------------------
|
||
Windows 里 DirectShow 的视频输入设备列表会混进「虚拟摄像头」:
|
||
手机投屏(一加 12 / DroidCam / iVCam)、OBS、ManyCam、IP 摄像头客户端等。
|
||
它们 OpenCV 照样能打开、看着像摄像头,但延迟大、画面可能是别的窗口内容、
|
||
随时掉线,一旦被选中参与抓拍,称重证据链就废了。现场只认插在 USB 上的
|
||
真实摄像头(UVC)。
|
||
|
||
判定双保险
|
||
----------
|
||
① PnP :WMI Win32_PnPEntity 里 InstanceId 以 ``USB\\`` 开头的 Camera/Image
|
||
设备 —— 这是「物理上确实挂在 USB 总线上」的硬证据。
|
||
② DShow:pygrabber 取到的名称列表,其顺序 **等于** OpenCV ``CAP_DSHOW``
|
||
的索引顺序(实测:['BisonCam,NB Pro', '一加 12 (Windows 虚拟摄像头)',
|
||
'4K AutoFocus Webcam'] 依次对应索引 0/1/2)。
|
||
|
||
只有 ① 中能找到同名设备、且不含虚拟摄像头关键词的,才算「USB 摄像头」。
|
||
两路信息都缺失时(WMI 不可用)退化为「排除虚拟摄像头关键词」的推测模式,
|
||
并在状态里明确标注,绝不假装已校验。
|
||
"""
|
||
import re
|
||
import time
|
||
import threading
|
||
|
||
VIRTUAL_KEYWORDS = (
|
||
'virtual', '虚拟',
|
||
'obs', 'manycam', 'xsplit', 'splitcam', 'vcam', 'epoccam',
|
||
'droidcam', 'ivcam', 'camo', 'snap camera', 'youcam', 'cyberlink',
|
||
'e2esoft', 'e2e soft', 'ip camera', 'rtsp', 'rtmp', 'ndi',
|
||
'screen capture', 'desktop capture', '抓屏', '录屏', '虚拟摄像头',
|
||
)
|
||
|
||
CACHE_TTL = 3.0
|
||
_LOCK = threading.Lock()
|
||
_CACHE = {'at': 0.0, 'pnp': None, 'pnp_err': None,
|
||
'names': None, 'names_err': None}
|
||
|
||
|
||
# ------------------------------------------------------------------ 工具
|
||
def _norm(s):
|
||
"""名称归一化:去空格/括号/连字符,小写,便于 PnP 名与 DShow 名对齐"""
|
||
s = (s or '').lower()
|
||
s = re.sub(r'[\s\(\)\[\]【】()\-_·,,.。/\\]+', '', s)
|
||
return s
|
||
|
||
|
||
def is_virtual_name(name):
|
||
low = (name or '').lower()
|
||
return any(k in low for k in VIRTUAL_KEYWORDS)
|
||
|
||
|
||
def _vid_pid(instance_id):
|
||
m = re.search(r'VID_([0-9A-Fa-f]{4})&PID_([0-9A-Fa-f]{4})', instance_id or '')
|
||
if not m:
|
||
return '', ''
|
||
return m.group(1).upper(), m.group(2).upper()
|
||
|
||
|
||
# ------------------------------------------------------------------ ① PnP
|
||
def pnp_cameras(force=False):
|
||
"""本机 Camera/Image 类 PnP 设备,带 usb 标记。
|
||
|
||
返回 (list, err)。list 元素:
|
||
{'name','instance_id','usb','vid','pid','status'}
|
||
"""
|
||
with _LOCK:
|
||
if (not force and _CACHE['pnp'] is not None
|
||
and time.monotonic() - _CACHE['at'] < CACHE_TTL):
|
||
return _CACHE['pnp'], _CACHE['pnp_err']
|
||
items, err = [], None
|
||
try:
|
||
import pythoncom
|
||
import win32com.client
|
||
pythoncom.CoInitialize()
|
||
try:
|
||
wmi = win32com.client.GetObject('winmgmts:')
|
||
q = ("SELECT Name, DeviceID, Status FROM Win32_PnPEntity "
|
||
"WHERE PNPClass='Camera' OR PNPClass='Image'")
|
||
for d in wmi.ExecQuery(q):
|
||
iid = (d.DeviceID or '')
|
||
vid, pid = _vid_pid(iid)
|
||
items.append({'name': d.Name or '',
|
||
'instance_id': iid,
|
||
'usb': iid.upper().startswith('USB\\'),
|
||
'vid': vid, 'pid': pid,
|
||
'status': d.Status or ''})
|
||
finally:
|
||
try:
|
||
pythoncom.CoUninitialize()
|
||
except Exception:
|
||
pass
|
||
except Exception as e: # noqa: BLE001 WMI 不可用不影响主流程
|
||
err = '%s: %s' % (type(e).__name__, e)
|
||
items = []
|
||
with _LOCK:
|
||
_CACHE['pnp'], _CACHE['pnp_err'] = items, err
|
||
_CACHE['at'] = time.monotonic()
|
||
return items, err
|
||
|
||
|
||
# ------------------------------------------------------------------ ② DShow
|
||
def dshow_names(force=False):
|
||
"""DirectShow 视频输入设备名列表(顺序 == OpenCV CAP_DSHOW 索引)。
|
||
|
||
返回 (names, err);names 为 None 表示取不到(缺 pygrabber / COM 异常)。
|
||
"""
|
||
with _LOCK:
|
||
if (not force and _CACHE['names'] is not None
|
||
and time.monotonic() - _CACHE['at'] < CACHE_TTL):
|
||
return _CACHE['names'], _CACHE['names_err']
|
||
names, err = None, None
|
||
try:
|
||
import comtypes
|
||
try:
|
||
comtypes.CoInitialize()
|
||
except Exception:
|
||
pass
|
||
from pygrabber.dshow_graph import FilterGraph
|
||
names = list(FilterGraph().get_input_devices() or [])
|
||
except Exception as e: # noqa: BLE001
|
||
names, err = None, '%s: %s' % (type(e).__name__, e)
|
||
with _LOCK:
|
||
if names is not None:
|
||
_CACHE['names'], _CACHE['names_err'] = names, None
|
||
_CACHE['at'] = time.monotonic()
|
||
return names, err
|
||
|
||
|
||
# ------------------------------------------------------------------ 汇总
|
||
def enumerate_cameras(force=False):
|
||
"""列出所有视频输入设备,并标注是否 USB。
|
||
|
||
返回 dict:
|
||
{'ok': bool, # 名称列表是否取到(取不到就无法按索引过滤)
|
||
'mode': 'usb' | 'guess' | 'unknown',
|
||
'devices': [{'index','name','is_usb','virtual','reason','vid','pid'}...],
|
||
'usb': [...], 'ignored': [...],
|
||
'note': str}
|
||
"""
|
||
names, nerr = dshow_names(force)
|
||
pnp, perr = pnp_cameras(force)
|
||
usb_pnp = [d for d in pnp if d['usb']]
|
||
by_norm = {}
|
||
for d in usb_pnp:
|
||
by_norm.setdefault(_norm(d['name']), d)
|
||
|
||
devices = []
|
||
if names is None:
|
||
mode, note = 'unknown', ('无法读取 DirectShow 设备名(%s),'
|
||
'已跳过 USB 校验' % (nerr or '未知原因'))
|
||
elif usb_pnp:
|
||
mode, note = 'usb', '已按 USB 总线校验(%d 台 USB 摄像头)' % len(usb_pnp)
|
||
elif perr:
|
||
mode, note = 'guess', ('设备管理器查询失败(%s),仅按名称排除虚拟摄像头'
|
||
% perr)
|
||
else:
|
||
mode, note = 'guess', '设备管理器未找到 USB 摄像头,仅按名称排除虚拟摄像头'
|
||
|
||
for idx, name in enumerate(names or []):
|
||
virtual = is_virtual_name(name)
|
||
hit = by_norm.get(_norm(name))
|
||
# 名称不完全一致时再做互相包含匹配(驱动常给名字加后缀)
|
||
if hit is None:
|
||
for k, d in by_norm.items():
|
||
if k and (_norm(name) in k or k in _norm(name)):
|
||
hit = d
|
||
break
|
||
if mode == 'usb':
|
||
is_usb = hit is not None and not virtual
|
||
if hit is None and virtual:
|
||
reason = '虚拟/投屏摄像头,非 USB 硬件'
|
||
elif hit is None:
|
||
reason = '不在 USB 总线上(内置/虚拟/网络摄像头)'
|
||
else:
|
||
reason = ''
|
||
elif mode == 'guess':
|
||
is_usb = not virtual
|
||
reason = '虚拟/投屏摄像头,非 USB 硬件' if virtual else ''
|
||
else:
|
||
is_usb, reason = True, '' # 信息全无时不拦,交给上层提示
|
||
devices.append({'index': idx, 'name': name, 'is_usb': is_usb,
|
||
'virtual': virtual, 'reason': reason,
|
||
'vid': (hit or {}).get('vid', ''),
|
||
'pid': (hit or {}).get('pid', '')})
|
||
|
||
usb = [d for d in devices if d['is_usb']]
|
||
ignored = [d for d in devices if not d['is_usb']]
|
||
return {'ok': names is not None, 'mode': mode, 'devices': devices,
|
||
'usb': usb, 'ignored': ignored, 'note': note,
|
||
'pnp_err': perr, 'names_err': nerr}
|
||
|
||
|
||
def usb_indices(force=False):
|
||
"""允许使用的索引(None 表示无法判断,调用方自行放行并提示)"""
|
||
info = enumerate_cameras(force)
|
||
if info['mode'] == 'unknown':
|
||
return None, info
|
||
return sorted(d['index'] for d in info['usb']), info
|
||
|
||
|
||
def is_usb_index(index, force=False):
|
||
"""单个索引是否 USB 摄像头:True / False / None(无法判断)"""
|
||
idxs, _ = usb_indices(force)
|
||
if idxs is None:
|
||
return None
|
||
return int(index) in idxs
|
||
|
||
|
||
def device_name(index):
|
||
"""索引 → 名称(拿不到返回空串)"""
|
||
names, _ = dshow_names()
|
||
try:
|
||
return (names or [])[int(index)]
|
||
except Exception:
|
||
return ''
|
||
|
||
|
||
INTEGRATED_KEYWORDS = ('integrated', '内置', 'nb pro', '笔记本', 'laptop',
|
||
'front camera', '前置', 'ir camera', 'windows hello')
|
||
|
||
|
||
def prefer_index(idxs):
|
||
"""多台 USB 摄像头时优先用哪台:排除像内置摄像头的,取索引最小的。
|
||
|
||
现场工位常是「笔记本自带 720P + 外接 2K USB」两台都算 USB,
|
||
默认挑外接那台(名字里带 Integrated/NB Pro/内置 的排后面),
|
||
操作员仍可在设置页按名字显式改。
|
||
"""
|
||
idxs = list(idxs or [])
|
||
if not idxs:
|
||
return None
|
||
if len(idxs) == 1:
|
||
return idxs[0]
|
||
ext = []
|
||
for i in idxs:
|
||
low = (device_name(i) or '').lower()
|
||
if any(k in low for k in INTEGRATED_KEYWORDS):
|
||
continue
|
||
ext.append(i)
|
||
return (ext or idxs)[0]
|
||
|
||
|
||
def resolve_name(name):
|
||
"""名称 → 当前索引(找不到返回 None)。
|
||
|
||
为什么要按名字找:DirectShow 索引会随设备插拔漂移(手机投屏一接上,
|
||
摄像头索引就整体后移)。记住名字比记住数字靠谱。
|
||
"""
|
||
if not name:
|
||
return None
|
||
names, _ = dshow_names()
|
||
names = names or []
|
||
target = _norm(name)
|
||
if not target:
|
||
return None
|
||
for i, n in enumerate(names):
|
||
if _norm(n) == target:
|
||
return i
|
||
for i, n in enumerate(names):
|
||
k = _norm(n)
|
||
if k and (target in k or k in target):
|
||
return i
|
||
return None
|
||
|
||
|
||
def clear_cache():
|
||
with _LOCK:
|
||
_CACHE.update({'at': 0.0, 'pnp': None, 'pnp_err': None,
|
||
'names': None, 'names_err': None})
|