Files
windows-fenjian/core/evidence/_probe_child.py
T

129 lines
4.1 KiB
Python

# -*- coding: utf-8 -*-
"""摄像头探测子进程(被 frames.discover_devices 调用)。
单独成进程的原因:cv2.VideoCapture 在部分 Windows 驱动上会无限期阻塞
(DSHOW 打不开时能卡满 40 秒),主进程无法中断,只能用子进程 + 硬超时兜住。
子进程每探测到一台可用设备就打一行 JSON(flush),父进程超时杀进程后仍能
拿到已探到的结果。
参数:
argv[1] 要探测的索引,逗号分隔("0,2");缺省 0
argv[2] 期望宽(默认 1280;0 或负数表示自动选档)
argv[3] 期望高
分辨率同样按档位回退(8MP 模组不认 2560×1440 这种档位)。
输出(每台一条 JSON):
成功 {"index":0,"backend":"dshow","width":1280,"height":720}
失败 {"index":0,"fail":"open"|"noframe"} ← 父进程据此区分病因
open = VideoCapture 打不开(被占用 / 驱动异常 / 索引不存在)
noframe = 能打开但一帧都读不出(模组挂死 / 档位全不支持)
"""
import sys
import json
import time
import cv2
BACKENDS = (('dshow', cv2.CAP_DSHOW), ('msmf', cv2.CAP_MSMF))
SIZE_CHAIN = ((3264, 2448), (2592, 1944), (2560, 1440),
(1920, 1080), (1280, 720))
def _parse_indices(s):
out = []
for part in str(s or '').replace(' ', '').split(','):
if not part:
continue
try:
out.append(int(part))
except ValueError:
pass
return out or [0]
def _sizes(want_w, want_h):
out = []
if want_w > 0 and want_h > 0:
out.append((want_w, want_h))
for s in SIZE_CHAIN:
if s not in out:
out.append(s)
return out
def _probe(idx, sizes, bname, be):
"""返回 (失败原因, 命中结果);成功时原因为 None
区分 open / noframe 是为了给现场不同的处置建议:
打不开多半是别的程序占着,能打开没画面基本是模组或驱动卡住。
"""
cap = None
try:
cap = cv2.VideoCapture(idx, be)
if not cap.isOpened():
return 'open', None
try:
cap.set(cv2.CAP_PROP_OPEN_TIMEOUT_MSEC, 4000)
cap.set(cv2.CAP_PROP_READ_TIMEOUT_MSEC, 2000)
except Exception:
pass
for w, h in sizes:
try:
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
cap.set(cv2.CAP_PROP_FRAME_WIDTH, int(w))
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, int(h))
except Exception:
pass
for _ in range(5):
try:
ok, f = cap.read()
except Exception:
ok, f = False, None
if ok and f is not None and getattr(f, 'size', 0):
hh, ww = f.shape[:2]
return None, {'index': idx, 'backend': bname,
'width': int(ww), 'height': int(hh)}
time.sleep(0.05)
return 'noframe', None
except Exception:
return 'open', None
finally:
if cap is not None:
try:
cap.release()
except Exception:
pass
def main():
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
pass
idxs = _parse_indices(sys.argv[1] if len(sys.argv) > 1 else '0')
want_w = int(sys.argv[2]) if len(sys.argv) > 2 else 1280
want_h = int(sys.argv[3]) if len(sys.argv) > 3 else 720
sizes = _sizes(want_w, want_h)
for idx in idxs:
hit = None
fail = []
for bname, be in BACKENDS:
why, got = _probe(idx, sizes, bname, be)
if got:
hit = got
break
if why:
fail.append(why)
if hit:
print(json.dumps(hit), flush=True)
else:
# 任一个后端「能打开没画面」比「打不开」更具体,优先报它
reason = 'noframe' if 'noframe' in fail else 'open'
print(json.dumps({'index': idx, 'fail': reason}), flush=True)
print('END', flush=True)
if __name__ == '__main__':
main()