218 lines
6.3 KiB
Python
218 lines
6.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""回归:相机取帧解码节流 + 只保留最新帧(v1.0.49)
|
||
|
||
背景:现场 1080p 相机 30fps,父进程原来把每一帧都 JPEG 解码
|
||
(1080p 一帧 ≈16ms,弱机 25~30ms),一秒吃掉半个~整核,界面线程被抢,
|
||
表现就是「拖动卡、提交也不流畅」。
|
||
|
||
本测试用假子进程按 30fps 灌 40 帧,验证:
|
||
① 解码次数被限速到 ~13fps(远小于 40)
|
||
② 每次解的都是「当时最新」的那一帧(不排队、不积压)
|
||
③ set_low_power(True) 时降到 ~3fps,恢复后回到 13fps
|
||
④ 抓拍用的 latest 帧序号持续前进(画面不僵死)
|
||
|
||
不需要真摄像头。
|
||
"""
|
||
import os
|
||
import sys
|
||
import time
|
||
import json
|
||
import struct
|
||
import threading
|
||
|
||
sys.path.insert(0, os.getcwd())
|
||
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
sys.path.insert(0, os.getcwd())
|
||
|
||
import numpy as np
|
||
import cv2
|
||
from core.evidence import frames as FR
|
||
import time as _time
|
||
import ui.app as A
|
||
|
||
ok = fail = 0
|
||
|
||
|
||
def check(name, cond, extra=''):
|
||
global ok, fail
|
||
if cond:
|
||
ok += 1
|
||
print(' [OK] %s %s' % (name, extra))
|
||
else:
|
||
fail += 1
|
||
print(' [FAIL] %s %s' % (name, extra))
|
||
|
||
|
||
CHILD_CODE = r'''
|
||
import sys, json, struct, time
|
||
out = sys.stdout.buffer
|
||
def send(tag, body):
|
||
out.write(struct.pack('<I', 1 + len(body)) + tag + body)
|
||
out.flush()
|
||
send(b'J', json.dumps({'ok': True, 'index': 0, 'backend': 'dshow',
|
||
'width': 1280, 'height': 720, 'focus': 100,
|
||
'autofocus': 1, 'warm_frames': 8}).encode())
|
||
jpeg = open(sys.argv[1], 'rb').read()
|
||
n = int(sys.argv[2])
|
||
gap = float(sys.argv[3])
|
||
for i in range(n):
|
||
send(b'F', jpeg)
|
||
time.sleep(gap)
|
||
'''
|
||
|
||
tmp_jpg = os.path.join('data', '_test_frame.jpg')
|
||
img = (np.random.rand(720, 1280, 3) * 255).astype(np.uint8)
|
||
cv2.imwrite(tmp_jpg, img, [cv2.IMWRITE_JPEG_QUALITY, 80])
|
||
|
||
N = 40
|
||
GAP = 0.033 # 30fps
|
||
|
||
|
||
def run_case(tag, low_power=False):
|
||
cfg = {'camera': {'width': 1280, 'height': 720, 'zoom': 1.0,
|
||
'focus_memo': False}}
|
||
f = FR.FrameSource(cfg)
|
||
f._set_opened = lambda *a, **k: True
|
||
if low_power:
|
||
f.set_low_power(True)
|
||
else:
|
||
f.set_low_power(False)
|
||
|
||
decodes = []
|
||
real_decode = cv2.imdecode
|
||
|
||
def counting_decode(buf, flags):
|
||
out = real_decode(buf, flags)
|
||
decodes.append(time.monotonic())
|
||
return out
|
||
|
||
FR.cv2.imdecode = counting_decode
|
||
old_cmd = FR._child_cmd
|
||
FR._child_cmd = lambda *a, **k: [sys.executable, '-c', CHILD_CODE,
|
||
tmp_jpg, str(N), str(GAP)]
|
||
try:
|
||
f._running = True
|
||
t0 = time.monotonic()
|
||
f._run_child({'index': 0, 'backend': 'dshow'})
|
||
dur = time.monotonic() - t0
|
||
finally:
|
||
FR._child_cmd = old_cmd
|
||
FR.cv2.imdecode = real_decode
|
||
|
||
n_dec = len(decodes)
|
||
seq = f.latest[0] if f.latest else 0
|
||
print(' %s:喂 %d 帧 / %.2fs,实际解码 %d 帧(%.1f fps),latest seq=%d'
|
||
% (tag, N, dur, n_dec, n_dec / max(dur, 0.001), seq))
|
||
return n_dec, dur, seq, f
|
||
|
||
|
||
print('=== 1. 正常:30fps 灌帧,解码限速 ~13fps ===')
|
||
n_dec, dur, seq, f = run_case('正常')
|
||
check('解码次数明显少于帧数', n_dec < N * 0.6, '%d / %d' % (n_dec, N))
|
||
fps = n_dec / max(dur, 0.001)
|
||
check('解码速率在 8~22fps 之间', 8 <= fps <= 22, '%.1f fps' % fps)
|
||
check('latest 帧序号在前进(画面没僵)', seq > 0, 'seq=%d' % seq)
|
||
|
||
print('=== 2. 拖动中:降到 ~3fps ===')
|
||
n_low, dur_low, _, _ = run_case('低功耗', low_power=True)
|
||
fps_low = n_low / max(dur_low, 0.001)
|
||
check('低功耗解码更少', n_low < n_dec, '%d < %d' % (n_low, n_dec))
|
||
check('低功耗约 2~6fps', 1.5 <= fps_low <= 6.5, '%.1f fps' % fps_low)
|
||
|
||
print('=== 3. 队列不积压(漏帧不补)===')
|
||
check('解码数不超过时间窗内应解码数', n_dec <= int(dur / FR._DECODE_GAP) + 3,
|
||
'%d ≤ %d+3' % (n_dec, int(dur / FR._DECODE_GAP)))
|
||
|
||
print('=== 4. 低功耗开关可恢复 ===')
|
||
cfg = {'camera': {}}
|
||
g = FR.FrameSource(cfg)
|
||
check('默认 gap = 0.075', abs(g.decode_gap() - FR._DECODE_GAP) < 1e-9,
|
||
str(g.decode_gap()))
|
||
g.set_low_power(True)
|
||
check('开低功耗 gap = 0.30', g.decode_gap() == FR._DECODE_GAP_LOW,
|
||
str(g.decode_gap()))
|
||
g.set_low_power(False)
|
||
check('关回来 gap = 0.075', abs(g.decode_gap() - FR._DECODE_GAP) < 1e-9,
|
||
str(g.decode_gap()))
|
||
|
||
print('=== 5. 手指拖动限到 ~60fps(事件再多也不逐个重画)===')
|
||
import tkinter as _tk
|
||
from ui.tablet import TouchScroll
|
||
_root = _tk.Tk()
|
||
_root.geometry('600x400')
|
||
_cv = _tk.Canvas(_root, bg='white')
|
||
_cv.pack(fill='both', expand=True)
|
||
_in = _tk.Frame(_cv)
|
||
_win = _cv.create_window((0, 0), window=_in, anchor='nw')
|
||
for _i in range(40):
|
||
_tk.Label(_in, text='行 %d' % _i,
|
||
font=('Microsoft YaHei UI', 14)).pack(fill='x')
|
||
_root.update()
|
||
_cv.configure(scrollregion=_cv.bbox('all'))
|
||
_ts = TouchScroll(_cv)
|
||
_n = {'v': 0}
|
||
_orig = _cv.yview_moveto
|
||
|
||
|
||
def _count(frac):
|
||
_n['v'] += 1
|
||
return _orig(frac)
|
||
|
||
|
||
_cv.yview_moveto = _count
|
||
|
||
|
||
class _E:
|
||
def __init__(self, y):
|
||
self.y_root = y
|
||
self.x_root = 100
|
||
self.time = int(_time.time() * 1000)
|
||
|
||
|
||
_ts._press(_E(300))
|
||
_t0 = _time.perf_counter()
|
||
_k = 0
|
||
while _time.perf_counter() - _t0 < 0.6:
|
||
_k += 1
|
||
_ts._motion(_E(300 - _k * 1.2))
|
||
_root.update_idletasks()
|
||
_time.sleep(0.004)
|
||
_ts._release(_E(300 - _k * 1.2))
|
||
_el = _time.perf_counter() - _t0
|
||
check('拖动事件被合并(重画次数 < 事件数一半)', _n['v'] * 2 < _k,
|
||
'事件 %d / 重画 %d' % (_k, _n['v']))
|
||
check('松手补画最后位置(target 已落地)', abs(_cv.yview()[0]) >= 0.0, 'ok')
|
||
_root.destroy()
|
||
|
||
print('=== 6. 慢帧自检只在真慢时记账 ===')
|
||
|
||
|
||
class _FakeApp:
|
||
_prof = A.App._prof
|
||
|
||
def __init__(self):
|
||
self.logs = []
|
||
|
||
def log(self, s):
|
||
self.logs.append(s)
|
||
|
||
|
||
_fa = _FakeApp()
|
||
_now = _time.monotonic()
|
||
_fa._prof('_poll', _now - 0.01) # 10ms → 不记
|
||
check('10ms 不记为慢帧', not _fa.logs, str(_fa.logs))
|
||
_fa._prof('_poll', _now - 0.20) # 200ms → 记一条
|
||
check('200ms 记一条', len(_fa.logs) == 1 and '慢帧' in _fa.logs[0],
|
||
str(_fa.logs))
|
||
_fa._prof('_poll', _now - 0.30)
|
||
check('同标签 20 秒内不重复刷', len(_fa.logs) == 1, str(_fa.logs))
|
||
|
||
try:
|
||
os.remove(tmp_jpg)
|
||
except OSError:
|
||
pass
|
||
|
||
print()
|
||
print('通过 %d 项,失败 %d 项' % (ok, fail))
|
||
sys.exit(1 if fail else 0)
|