Files

226 lines
8.4 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Diagnostics;
using System.Text;
using FpCollect.Agent.Sdk;
namespace FpCollect.Agent.Capture;
/// <summary>
/// S680E 采集服务 —— 移植自原版 HaveFingersForm.S680Run + ThreadLoopRcv:
/// 后台线程循环 BeginCapture → GetFPRawData → EndCapture,
/// 滚动模式下用 MOSAIC 库做拼接(IsFinger/Start/DoMosaic/Stop),
/// 每帧渲染 640×640 灰度位图,以 JPEG 推流(事件)、PNG 快照。
/// </summary>
public sealed class CaptureService : IDisposable
{
public const int Width = 640; // 证据:缓冲 409600 = 640*640*1
public const int Height = 640;
private readonly string _dllDir;
private Gals? _gals;
private Gamc? _amc;
private Thread? _loop;
private volatile bool _running;
public volatile bool RollMode; // 原版 chbRollMode
public bool IsRunning => _running;
public string? DeviceInfo { get; private set; }
public string? LastError { get; private set; }
/// <summary>JPEG 帧事件(推流用)。</summary>
public event Action<byte[]>? OnFrame;
/// <summary>每帧遥测事件(手指检测/图像质量/指纹质量/FPS,对应原版 lbhint+DisplayLable 的现代化)。</summary>
public event Action<Telemetry>? OnTelemetry;
public sealed record Telemetry(int FingerPresent, int ImageQuality, int FingerQuality, double Fps, bool RollMode);
private long _frameCount;
private long _fpsWindowStart;
private double _fps;
private DateTime _lastFrameAt = DateTime.MinValue;
private readonly object _snapLock = new();
private byte[]? _lastPng;
public CaptureService(string dllDir) { _dllDir = dllDir; }
/// <summary>启动采集。返回空串表示成功,否则为错误描述。</summary>
public string Start()
{
if (_running) return "已在采集中"; // 单飞行:避免双循环+二次拆除
Stop();
// 厂商 demo(FpTest.exe)均在 SDK 目录内运行:DLL 可能依赖 CWD 下的配置/辅助文件
var prevDir = Environment.CurrentDirectory;
try { Environment.CurrentDirectory = _dllDir; } catch { }
var gals = new Gals(_dllDir);
var amc = new Gamc(_dllDir);
if (!gals.DllOk) { var e = gals.LastError; gals.Dispose(); amc.Dispose(); return e; }
if (!amc.DllOk) { var e = amc.LastError; gals.Dispose(); amc.Dispose(); return e; }
int rc = gals.LS_Init?.Invoke() ?? -1;
if (rc != Gals.LS_ERROR_SUCCESS)
{
var info = new sbyte[256];
gals.LS_GetErrorInfo?.Invoke(rc, info);
var msg = $"LIVESCAN_Init 失败 rc={rc}:{ToString(info)}(采集仪未连接?)";
gals.Dispose(); amc.Dispose();
try { Environment.CurrentDirectory = prevDir; } catch { }
return msg;
}
// 原版 btnstart_Click:LS_GetProductInfo → "机器序号"+Serial
var prod = new Fp_Product_Info
{
ProductName = new byte[32],
Serial = new byte[32],
Version = new byte[16]
};
if (gals.LS_GetProductInfo?.Invoke(0, ref prod) == Gals.LS_ERROR_SUCCESS)
DeviceInfo = "机器序号" + Encoding.Default.GetString(prod.Serial).TrimEnd('\0');
amc.MC_Init?.Invoke();
_gals = gals; _amc = amc;
_running = true;
_loop = new Thread(Loop) { IsBackground = true, Name = "capture-loop" };
_loop.Start();
try { Environment.CurrentDirectory = prevDir; } catch { }
return "";
}
public void Stop()
{
_running = false;
var t = _loop;
if (t is not null)
{
// GetFPRawData 每帧阻塞 ~1.5s:必须等线程真正退出后再释放原生资源,
// 否则 FreeLibrary 会让正在执行的代码踩空(0xC0000005)。
if (!t.Join(8000))
{
LastError = "采集线程未在 8 秒内退出,已跳过资源释放以避免崩溃(可重试停止)";
return; // 宁可暂留句柄,不可崩进程
}
}
_loop = null;
try { _gals?.LS_Close?.Invoke(); } catch { }
_gals?.Dispose(); _amc?.Dispose();
_gals = null; _amc = null;
}
/// <summary>取最近一帧 PNG(原版"采集下一张"取 fingertmpb 的对应物)。</summary>
public byte[]? Snapshot()
{
lock (_snapLock) return _lastPng is null ? null : (byte[])_lastPng.Clone();
}
/// <summary>富设备状态(对应原版"机器数/序列号/版本"状态栏)。</summary>
public object GetInfo()
{
string? version = null;
var channels = -1;
var g = _gals;
if (g is not null)
{
try
{
var b = new sbyte[64];
if (g.LS_Get_Version?.Invoke(b) == 1) version = ToString(b);
}
catch { }
try { channels = g.LS_GetChannelCount?.Invoke() ?? -1; } catch { }
}
var lastFrameMs = _lastFrameAt == DateTime.MinValue ? -1
: (long)(DateTime.UtcNow - _lastFrameAt).TotalMilliseconds;
return new
{
running = _running,
state = !_running ? "idle" : RollMode ? "roll-capturing" : "capturing",
device = DeviceInfo,
sdkDir = _dllDir,
version,
channels,
fps = Math.Round(_fps, 1),
rollMode = RollMode,
lastFrameMs,
error = LastError
};
}
// ── 原版 ThreadLoopRcv 的移植(滚动分支条件按分支拓扑做了等价重排) ──
private void Loop()
{
var gals = _gals!;
var amc = _amc!;
var buf = new byte[Width * Height]; // 每帧原始灰度
var mosaic = new byte[Width * Height]; // 拼接缓冲(原版初始化为 255)
Array.Fill(mosaic, (byte)255);
bool mosaicActive = false;
var throttle = Stopwatch.StartNew();
while (_running)
{
gals.LS_BeginCapture?.Invoke(0);
int rc = gals.LS_GetFPRawData?.Invoke(0, buf) ?? -1;
gals.LS_EndCapture?.Invoke(0);
if (rc != Gals.LS_ERROR_SUCCESS) continue;
byte[] display;
if (RollMode)
{
if (!mosaicActive && (amc.MC_IsFinger?.Invoke(mosaic, Width, Height) ?? 0) > 0)
{
amc.MC_Start?.Invoke(mosaic, Width, Height);
mosaicActive = true;
}
int q = amc.MC_DoMosaic?.Invoke(mosaic, Width, Height) ?? -1;
if (q <= 0)
{
amc.MC_Stop?.Invoke();
mosaicActive = false;
}
display = mosaic;
}
else
{
display = buf;
}
if (throttle.ElapsedMilliseconds < 80) continue; // ~12fps 推流节流
throttle.Restart();
try
{
// 每帧质量遥测(MOSAIC:IsFinger/ImageQuality/FingerQuality)
int fp = -1, iq = -1, fq = -1;
try { fp = amc.MC_IsFinger?.Invoke(display, Width, Height) ?? -1; } catch { }
try { iq = amc.MC_ImageQuality?.Invoke(display, Width, Height) ?? -1; } catch { }
try { fq = amc.MC_FingerQuality?.Invoke(display, Width, Height) ?? -1; } catch { }
_frameCount++;
var now = Environment.TickCount64;
if (_fpsWindowStart == 0) _fpsWindowStart = now;
var window = now - _fpsWindowStart;
if (window >= 2000) { _fps = _frameCount * 1000.0 / window; _frameCount = 0; _fpsWindowStart = now; }
_lastFrameAt = DateTime.UtcNow;
using var bmp = GrayBitmap.ToGrayBitmap(display, Width, Height);
lock (_snapLock) _lastPng = GrayBitmap.ToPng(bmp);
OnFrame?.Invoke(GrayBitmap.ToJpeg(bmp));
OnTelemetry?.Invoke(new Telemetry(fp, iq, fq, Math.Round(_fps, 1), RollMode));
}
catch (Exception ex) { LastError = ex.Message; }
}
amc.MC_Stop?.Invoke();
amc.MC_Close?.Invoke();
}
private static string ToString(sbyte[] buf)
{
var bytes = buf.Select(b => (byte)b).TakeWhile(b => b != 0).ToArray();
return Encoding.Default.GetString(bytes);
}
public void Dispose() => Stop();
}