diff --git a/desktop/Services/Hik/HikDeviceService.cs b/desktop/Services/Hik/HikDeviceService.cs new file mode 100644 index 0000000..6be8156 --- /dev/null +++ b/desktop/Services/Hik/HikDeviceService.cs @@ -0,0 +1,1247 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Xml.Linq; +using System.Collections.Concurrent; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 海康设备连接池 + 通道读取。 +/// +/// 连接模型(实测结论,见 README/提交说明): +/// - NET_DVR_Login_V40 得到的是一个**逻辑会话(UserID)**,SDK 内部维持心跳并在断链后自动重连 +/// (NET_DVR_SetReconnect),所以**不要每次请求都登录**; +/// - 同一设备可同时存在多个 UserID(实测 0/1/2 三路并发),设备侧上限为 128 个注册用户; +/// - 会话空闲 10 分钟自动登出,避免长期占用设备名额; +/// - 同一会话的调用用 串行化,避免并发读写同一 UserID。 +/// +public sealed class HikDeviceService : IDisposable +{ + /// 会话空闲多久后自动登出 + private static readonly TimeSpan IdleTimeout = TimeSpan.FromMinutes(10); + + /// IP 通道配置缓冲区(实测设备返回 50792 字节,留余量) + private const int IpParaBufferSize = 60000; + + private readonly ConcurrentDictionary _sessions = new(StringComparer.OrdinalIgnoreCase); + private readonly Timer _sweeper; + private bool _disposed; + + public HikDeviceService() + { + _sweeper = new Timer(_ => SweepIdleSessions(), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); + } + + /// 读取设备通道列表(登录 → 读 IP 接入配置 → 补通道名 → 返回)。阻塞调用,调用方放在线程池里跑 + /// 设备 Web/ISAPI 端口(用于取真实通道名,默认 80;取不到就留空,不影响主流程) + public HikChannelsResult GetChannels(string host, int port, string userName, string password, int webPort = 80) + { + Validate(host, port, userName, password); + + var stopwatch = Stopwatch.StartNew(); + var key = MakeKey(host, port, userName, password); + var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); + + session.Gate.Wait(); + try + { + var reused = session.UserId >= 0; + + for (var attempt = 1; ; attempt++) + { + if (session.UserId < 0) + { + Login(session, password); + reused = false; + } + + try + { + var result = ReadChannels(session, password, webPort); + result.userId = session.UserId; + result.sessionReused = reused; + result.elapsedMs = stopwatch.ElapsedMilliseconds; + session.Touch(); + return result; + } + catch (HikException ex) when (attempt == 1 && IsLinkError(ex.ErrorCode)) + { + // 会话可能已经掉了:登出并重登一次 + AppLog.Write($"海康会话失效({ex.Message}),尝试重新登录 {session.Host}:{session.Port}"); + CloseSession(session); + reused = false; + } + } + } + catch + { + // 登录/取通道彻底失败:把会话从池里摘掉,下次重新来过 + if (session.UserId < 0) + { + _sessions.TryRemove(key, out _); + } + throw; + } + finally + { + session.Gate.Release(); + } + } + + /// 当前池中的会话数(排障用) + public int SessionCount => _sessions.Values.Count(s => s.UserId >= 0); + + /// + /// 确保已登录并返回 UserID(给实时取流等需要自己发命令的地方用) + /// + public int EnsureUser(string host, int port, string userName, string password) + { + Validate(host, port, userName, password); + + var key = MakeKey(host, port, userName, password); + var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); + + session.Gate.Wait(); + try + { + if (session.UserId < 0) Login(session, password); + session.Touch(); + return session.UserId; + } + catch + { + if (session.UserId < 0) _sessions.TryRemove(key, out _); + throw; + } + finally + { + session.Gate.Release(); + } + } + + /// + /// 取设备的「首个数字通道号」(登录时读到的 byStartDChan) + /// + /// 预览要把它换算成 ISAPI/RTSP 用的 1 起序号:logical = channel - startDigital + 1 + /// (本项目设备 32 路模拟 + 32 路数字,数字通道从 33 起 → 通道 33 对应 101 码流)。 + /// 会话是池化的,重复调用只会读内存。 + /// + public int GetStartDigitalChannel(string host, int port, string userName, string password) + { + Validate(host, port, userName, password); + + var key = MakeKey(host, port, userName, password); + var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); + + session.Gate.Wait(); + try + { + if (session.UserId < 0) Login(session, password); + session.Touch(); + + var start = session.Device?.StartDigitalChannel ?? 0; + return start > 0 ? start : 33; + } + catch + { + if (session.UserId < 0) _sessions.TryRemove(key, out _); + throw; + } + finally + { + session.Gate.Release(); + } + } + + /// NET_DVR_GET_TIMECFG 的输出缓冲(NET_DVR_TIME = 24 字节) + private const int TimeCfgBufferSize = 24; + + /// + /// 读设备当前时间(8000 私有协议 NET_DVR_GET_TIMECFG,不需要 Web/ISAPI 端口) + /// + /// 用途:回放是按**设备本地时间**定位的,而扫码时间是**本机时钟**打的。 + /// 两边不一致时(现场实测本机慢了 9 秒),录像会整体错位,短回放窗口会直接看不到面单。 + /// + public DateTime GetDeviceTime(string host, int port, string userName, string password) + { + Validate(host, port, userName, password); + + var time = DateTime.MinValue; + + ExecuteWithSession(host, port, userName, password, userId => + { + var buffer = Marshal.AllocHGlobal(TimeCfgBufferSize); + try + { + Marshal.Copy(new byte[TimeCfgBufferSize], 0, buffer, TimeCfgBufferSize); + + if (!HikSdk.NET_DVR_GetDVRConfig(userId, HikSdk.NET_DVR_GET_TIMECFG, 0, + buffer, TimeCfgBufferSize, out _)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"读取设备时间失败:{HikSdk.DescribeError(err)}"); + } + + var year = Marshal.ReadInt32(buffer, 0); + var month = Marshal.ReadInt32(buffer, 4); + var day = Marshal.ReadInt32(buffer, 8); + var hour = Marshal.ReadInt32(buffer, 12); + var minute = Marshal.ReadInt32(buffer, 16); + var second = Marshal.ReadInt32(buffer, 20); + + time = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified); + } + finally + { + Marshal.FreeHGlobal(buffer); + } + }); + + return time; + } + + /// + /// 写设备时间(NET_DVR_SET_TIMECFG)。 + /// 用于「设置 NVR 的 NTP 后立即生效」:先把 NTP 配置写进去,再直接把设备时间校准到 NTP 时间。 + /// + public void SetDeviceTime(string host, int port, string userName, string password, DateTime time) + { + Validate(host, port, userName, password); + + ExecuteWithSession(host, port, userName, password, userId => + { + var sdkTime = ToSdkTime(time); + var size = Marshal.SizeOf(sdkTime); + var buffer = Marshal.AllocHGlobal(size); + try + { + Marshal.StructureToPtr(sdkTime, buffer, false); + + if (!HikSdk.NET_DVR_SetDVRConfig(userId, HikSdk.NET_DVR_SET_TIMECFG, 0, buffer, (uint)size)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"设置设备时间失败:{HikSdk.DescribeError(err)}"); + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + }); + + AppLog.Write($"[hik] 设备时间已写入 {host}:{port}:{time:yyyy-MM-dd HH:mm:ss}"); + } + + /// + /// 写设备时间并**等待设备真正生效**。 + /// + /// 实测两个坑: + /// 1. SET_TIMECFG 返回成功后立刻 GET 可能还是旧值(设备异步应用); + /// 2. **写调用本身要 3~4 秒**,而写入的值是调用前就该有的时间 → + /// 设备应用时已经「过时」了,原来直接回读永远是 -3~-4 秒。 + /// + /// 做法:先看当前时间是否已经够准;不准就写一次、量出这次调用的耗时, + /// 下一次写入时把这段耗时补偿进去(迭代最多 4 次,直到与目标时间相差 ≤2 秒)。 + /// + /// 期望的设备时间(绝对时间,调用时刻的值) + /// 回读到的设备时间(超时仍未对上就是最后一次读到的值) + public DateTime SetDeviceTimeAndConfirm(string host, int port, string userName, string password, + DateTime target, int timeoutMs = 20000) + { + var callStarted = DateTime.Now; + var last = target; + var lead = TimeSpan.Zero; + var deadline = Environment.TickCount64 + Math.Max(timeoutMs, 8000); + + // 已经够准就不写(避免每次都动设备时钟) + try + { + last = GetDeviceTime(host, port, userName, password); + var earlyDiff = (last - target).TotalSeconds; + AppLog.Write($"[hik] 校时前检查:设备 {last:HH:mm:ss.fff},目标 {target:HH:mm:ss.fff},差 {earlyDiff:+0.0;-0.0}s"); + if (Math.Abs(earlyDiff) <= 1.5) return last; + } + catch (Exception ex) + { + AppLog.Write($"[hik] 读取设备时间失败(继续尝试写入):{ex.Message}"); + } + + // 写一次 → 等设备应用完再回读(连续快速写会被设备忽略)→ 差得多就补偿「设备应用延迟」再写一次 + for (var attempt = 0; attempt < 3 && Environment.TickCount64 < deadline; attempt++) + { + var writeValue = target.Add(DateTime.Now - callStarted).Add(lead); + + SetDeviceTime(host, port, userName, password, writeValue); + + // 设备应用时间有延迟(实测量约 2.5 秒),等它稳定下来再回读;同时避免连续写入被忽略 + Thread.Sleep(2500); + + try + { + last = GetDeviceTime(host, port, userName, password); + } + catch (Exception ex) + { + AppLog.Write($"[hik] 回读设备时间失败(继续重试):{ex.Message}"); + continue; + } + + var expected = target.Add(DateTime.Now - callStarted); + var diff = (last - expected).TotalSeconds; + + AppLog.Write($"[hik] 校时尝试 {attempt + 1}:写入 {writeValue:HH:mm:ss.fff}," + + $"回读 {last:HH:mm:ss.fff},期望 {expected:HH:mm:ss.fff},差 {diff:+0.0;-0.0}s,补偿 {lead.TotalSeconds:0.0}s"); + + if (Math.Abs(diff) <= 1.5) return last; + + // 设备比期望慢多少,下次写入就把这段延迟补回去(不能用 SDK 调用耗时:它只有几毫秒) + lead = lead.Add(TimeSpan.FromSeconds(-diff)); + } + + AppLog.Write($"[hik] 设备时间校准后仍差 {(last - target.Add(DateTime.Now - callStarted)).TotalSeconds:+0.0;-0.0} 秒({host}:{port})"); + return last; + } + + /// + /// 读录像机的 NTP 配置(走 **8000 私有协议**:NET_DVR_GET_NTPCFG,不需要 Web/ISAPI 端口)。 + /// + public HikNtpConfig GetNtpConfig(string host, int port, string userName, string password) + { + Validate(host, port, userName, password); + + HikNtpConfig? config = null; + + ExecuteWithSession(host, port, userName, password, userId => + { + var size = Marshal.SizeOf(); + var buffer = Marshal.AllocHGlobal(size); + try + { + Marshal.Copy(new byte[size], 0, buffer, size); + + if (!HikSdk.NET_DVR_GetDVRConfig(userId, HikSdk.NET_DVR_GET_NTPCFG, 0, + buffer, (uint)size, out _)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"读取 NTP 配置失败:{HikSdk.DescribeError(err)}"); + } + + var raw = new byte[size]; + Marshal.Copy(buffer, raw, 0, size); + + var end = Array.IndexOf(raw, (byte)0, 0, 64); + if (end < 0) end = 64; + var server = Encoding.ASCII.GetString(raw, 0, end).Trim(); + var interval = BitConverter.ToUInt16(raw, 64); + var enabled = raw[66] != 0; + + config = new HikNtpConfig(server, interval, enabled); + } + finally + { + Marshal.FreeHGlobal(buffer); + } + }); + + return config!; + } + + /// + /// 写录像机的 NTP 配置(NET_DVR_SET_NTPCFG)。 + /// + /// NTP 服务器(域名或 IP,最多 63 字节 ASCII) + /// 同步间隔(分钟,1~1440;设备常见默认 60) + public void SetNtpConfig(string host, int port, string userName, string password, + string server, int intervalMinutes, bool enabled) + { + Validate(host, port, userName, password); + + var text = (server ?? string.Empty).Trim(); + if (text.Length == 0) throw new ArgumentException("NTP 服务器不能为空"); + if (Encoding.ASCII.GetByteCount(text) > 63) throw new ArgumentException("NTP 服务器地址过长(最多 63 字节)"); + + var interval = (ushort)Math.Clamp(intervalMinutes, 1, 1440); + + ExecuteWithSession(host, port, userName, password, userId => + { + var size = Marshal.SizeOf(); + var buffer = Marshal.AllocHGlobal(size); + try + { + // ⚠️ 必须「先读后改再写」: + // 本机实测把整个 NET_DVR_NTPPARA 清零后重填(只填 server/interval/enable)会报 err=11, + // 因为固件在保留字段里还放了 NTP 端口(读取值里 offset 70 = 0x007B = 123)等数据。 + // 原样保留其它字节、只改 sNTPServer / wInterval / byEnable,写入才会成功。 + Marshal.Copy(new byte[size], 0, buffer, size); + if (!HikSdk.NET_DVR_GetDVRConfig(userId, HikSdk.NET_DVR_GET_NTPCFG, 0, + buffer, (uint)size, out _)) + { + var readError = HikSdk.NET_DVR_GetLastError(); + throw new HikException(readError, $"读取当前 NTP 配置失败:{HikSdk.DescribeError(readError)}"); + } + + var raw = new byte[size]; + Marshal.Copy(buffer, raw, 0, size); + + // sNTPServer[64]:整段清空后写 ASCII(域名的剩余字节保持 0) + Array.Clear(raw, 0, 64); + Encoding.ASCII.GetBytes(text, 0, text.Length, raw, 0); + + // WORD wInterval(offset 64)+ BYTE byEnable(offset 66) + raw[64] = (byte)(interval & 0xFF); + raw[65] = (byte)(interval >> 8); + raw[66] = (byte)(enabled ? 1 : 0); + + Marshal.Copy(raw, 0, buffer, size); + + if (!HikSdk.NET_DVR_SetDVRConfig(userId, HikSdk.NET_DVR_SET_NTPCFG, 0, buffer, (uint)size)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"设置 NTP 配置失败:{HikSdk.DescribeError(err)}"); + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + }); + + AppLog.Write($"[hik] NTP 配置已写入 {host}:{port}:{text},间隔 {interval} 分钟,{(enabled ? "启用" : "关闭")}"); + } + + /// + /// 抓一帧 JPEG(预览用) + /// + /// 走 8000 私有协议的 NET_DVR_CaptureJPEGPicture_NEW: + /// - 不需要 ISAPI/Web 端口,也不需要解码器(PlayM4),拿到就是可直接给浏览器的 JPEG; + /// - 是**海康通道号**(数字通道从 33 起),不是 ISAPI 的 1 起序号; + /// - 同一 UserID 的抓帧被 串行化,多路预览也不会撞车(只是帧率分摊)。 + /// + public byte[] CaptureJpeg(string host, int port, string userName, string password, int channel) + { + Validate(host, port, userName, password); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + + var key = MakeKey(host, port, userName, password); + var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); + + session.Gate.Wait(); + try + { + for (var attempt = 1; ; attempt++) + { + if (session.UserId < 0) Login(session, password); + + try + { + var frame = CaptureOnce(session.UserId, channel); + session.Touch(); + return frame; + } + catch (HikException ex) when (attempt == 1 && IsLinkError(ex.ErrorCode)) + { + AppLog.Write($"海康抓帧会话失效({ex.Message}),尝试重新登录 {session.Host}:{session.Port}"); + CloseSession(session); + } + } + } + catch + { + if (session.UserId < 0) _sessions.TryRemove(key, out _); + throw; + } + finally + { + session.Gate.Release(); + } + } + + /// 抓帧缓冲区(4MB 足够 1080p JPEG) + private const int JpegBufferSize = 4 * 1024 * 1024; + + /// + /// 云台连续动作(方向 / 变倍 / 聚焦 / 光圈 / 自动扫描) + /// + /// 走 NET_DVR_PTZControlWithSpeed_Other:只需登录的 UserID + 通道号, + /// **不依赖预览句柄**,所以没开预览也能控。 + /// + /// up / down / left / right / up-left / ... / zoom-in / auto ... + /// true = 停止(必须与开始成对调用,否则云台会一直转) + /// 1~7(默认 4),部分设备只支持 1~7 + public void PtzControl(string host, int port, string userName, string password, int channel, string command, bool stop, int speed = 4) + { + Validate(host, port, userName, password); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + if (!HikPtz.Commands.TryGetValue(command ?? string.Empty, out var code)) + { + throw new ArgumentException($"不支持的云台命令:{command}"); + } + + var finalSpeed = (uint)Math.Clamp(speed <= 0 ? 4 : speed, 1, 7); + + ExecuteWithSession(host, port, userName, password, userId => + { + if (!HikSdk.NET_DVR_PTZControlWithSpeed_Other(userId, channel, code, stop ? 1u : 0u, finalSpeed)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"云台控制失败:{HikSdk.DescribeError(err)}"); + } + }); + } + + /// 预置点:set / goto / clear( 1~256) + public void PtzPreset(string host, int port, string userName, string password, int channel, string action, int preset) + { + Validate(host, port, userName, password); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + if (!HikPtz.PresetActions.TryGetValue(action ?? string.Empty, out var code)) + { + throw new ArgumentException($"不支持的预置点操作:{action}"); + } + if (preset is < 1 or > 256) throw new ArgumentException("预置点编号必须在 1~256 之间"); + + ExecuteWithSession(host, port, userName, password, userId => + { + if (!HikSdk.NET_DVR_PTZPreset_Other(userId, channel, code, (uint)preset)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"预置点操作失败:{HikSdk.DescribeError(err)}"); + } + }); + } + + /// 取登录 UserID 执行一段 SDK 调用(串行化 + 链路错误重登一次) + private void ExecuteWithSession(string host, int port, string userName, string password, Action action) + { + var key = MakeKey(host, port, userName, password); + var session = _sessions.GetOrAdd(key, _ => new Session(host, port, userName)); + + session.Gate.Wait(); + try + { + for (var attempt = 1; ; attempt++) + { + if (session.UserId < 0) Login(session, password); + + try + { + action(session.UserId); + session.Touch(); + return; + } + catch (HikException ex) when (attempt == 1 && IsLinkError(ex.ErrorCode)) + { + AppLog.Write($"海康调用会话失效({ex.Message}),尝试重新登录 {session.Host}:{session.Port}"); + CloseSession(session); + } + } + } + catch + { + if (session.UserId < 0) _sessions.TryRemove(key, out _); + throw; + } + finally + { + session.Gate.Release(); + } + } + + /// + /// 按时间**下载录像到文件**(走 8000 私有协议:NET_DVR_GetFileByTime_V40) + /// + /// 与 RTSP 回放的差别: + /// - 不需要 554 端口、不需要解码器,设备自己按时间段把录像推下来(比 RTSP 稳,现场防火墙常只开 8000); + /// - 落地是设备原始封装(PS),要 mp4 还得用 ffmpeg 转封装; + /// - 文件名走 ANSI(SDK 是 char*)→ 这里的 必须是 ASCII 路径, + /// 调用方下载完再搬到用户选的中文目录。 + /// + /// 下载进度 0~100(SDK 的 NET_DVR_GetDownloadPos) + public void DownloadByTime(string host, int port, string userName, string password, + int channel, DateTime start, DateTime end, string outputPath, int streamType = 0, + Action? onProgress = null, CancellationToken ct = default) + { + Validate(host, port, userName, password); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + if (end <= start) throw new ArgumentException("结束时间必须晚于开始时间"); + + HikSdk.EnsureInitialized(); + + ExecuteWithSession(host, port, userName, password, userId => + { + var condition = new HikSdk.NET_DVR_PLAYCOND + { + dwChannel = (uint)channel, + struStartTime = ToSdkTime(start), + struStopTime = ToSdkTime(end), + byStreamType = (byte)streamType, + byDownload = 0, + byOptimalStreamType = 0, + byRes2 = new byte[301], + }; + + var handle = HikSdk.NET_DVR_GetFileByTime_V40(userId, outputPath, ref condition); + if (handle < 0) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"按时间下载录像失败:{HikSdk.DescribeError(err)}"); + } + + try + { + // 录像下载一般 2~5x 实时;留足余量,超时按失败处理(别把界面卡死) + var deadline = DateTime.UtcNow.AddSeconds((end - start).TotalSeconds * 2 + 120); + var lastPos = -1; + var lastSize = 0L; + var lastGrowth = DateTime.UtcNow; + + while (true) + { + ct.ThrowIfCancellationRequested(); + + var pos = HikSdk.NET_DVR_GetDownloadPos(handle); + if (pos < 0) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"下载中断:{HikSdk.DescribeError(err)}"); + } + + if (pos != lastPos) + { + onProgress?.Invoke(Math.Min(pos, 100)); + lastPos = pos; + } + + // 有些固件(实测本项目这台 NVR)调 GetFileByTime 会「成功返回句柄但一个字节都不推」, + // 所以用**文件是否在长**判断真实进度;长时间不增长就快速失败,别让上层干等。 + var size = File.Exists(outputPath) ? new FileInfo(outputPath).Length : 0; + if (size > lastSize) + { + lastSize = size; + lastGrowth = DateTime.UtcNow; + } + else if ((DateTime.UtcNow - lastGrowth).TotalSeconds > 5) + { + if (size == 0) + { + throw new HikException(uint.MaxValue, + "设备没有推送录像数据(该固件可能不支持按时间下载)"); + } + return; // 有数据且已停止增长 = 拉完了 + } + + if (pos >= 100 && size > 0) return; + + if (DateTime.UtcNow > deadline) + { + throw new HikException(uint.MaxValue, "下载超时(设备没有继续推录像)"); + } + + // 短睡,避免把设备问烦;取消时立刻退出 + ct.WaitHandle.WaitOne(300); + } + } + finally + { + HikSdk.NET_DVR_StopGetFile(handle); + } + }); + } + + /// + /// 按时间**拉回放流写文件**(8000 私有协议:NET_DVR_PlayBackByTime + 数据回调) + /// + /// 这是实测**唯一可用且最快**的回放下载方式: + /// - 设备**全速推送**(本项目 2560×1440 主码流约 14 MB/s ≈ 17 倍速), + /// 2 分钟素材 7 秒拉完;RTSP 回放是 ~0.7 倍速(30 秒要 40 秒); + /// - 落地是原始 PS 流,要 mp4 再用 ffmpeg 转封装( 里做); + /// - ⚠️ NET_DVR_GetFileByTime*(直接存文件)在这台固件上不工作,不要用。 + /// + /// 已接收字节数(总大小未知,界面按 MB 显示) + /// 实际写入字节数 + public long PullPlaybackToFile(string host, int port, string userName, string password, + int channel, DateTime start, DateTime end, string outputPath, + Action? onProgress = null, CancellationToken ct = default) + { + Validate(host, port, userName, password); + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + if (end <= start) throw new ArgumentException("结束时间必须晚于开始时间"); + + HikSdk.EnsureInitialized(); + + FileStream? stream = null; + var sync = new object(); + var written = 0L; + + // 回调在 SDK 网络线程:只做「拷贝 + 写盘」,不碰 UI + HikSdk.PlayDataCallback callback = (_, _, buffer, size, _) => + { + if (size == 0) return; + + var chunk = new byte[size]; + Marshal.Copy(buffer, chunk, 0, (int)size); + + lock (sync) + { + stream?.Write(chunk, 0, (int)size); + written += size; + } + }; + + try + { + stream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read, + 1 << 20, FileOptions.SequentialScan); + + ExecuteWithSession(host, port, userName, password, userId => + { + var sdkStart = ToSdkTime(start); + var sdkStop = ToSdkTime(end); + + var handle = HikSdk.NET_DVR_PlayBackByTime(userId, channel, ref sdkStart, ref sdkStop, IntPtr.Zero); + if (handle < 0) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"打开回放失败:{HikSdk.DescribeError(err)}"); + } + + try + { + if (!HikSdk.NET_DVR_SetPlayDataCallBack(handle, callback, IntPtr.Zero)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"设置回放回调失败:{HikSdk.DescribeError(err)}"); + } + + if (!HikSdk.NET_DVR_PlayBackControl(handle, HikSdk.PlayStart, 0, IntPtr.Zero)) + { + var err = HikSdk.NET_DVR_GetLastError(); + throw new HikException(err, $"启动回放失败:{HikSdk.DescribeError(err)}"); + } + + // 全速推送:优先看设备给的回放进度(录像中间有断档时,数字节会误判「推完了」) + var deadline = DateTime.UtcNow.AddSeconds((end - start).TotalSeconds + 120); + var lastSize = 0L; + var lastGrowth = DateTime.UtcNow; + + while (true) + { + ct.ThrowIfCancellationRequested(); + + var pos = HikSdk.NET_DVR_GetPlayBackPos(handle); + + long current; + lock (sync) current = written; + + if (current > lastSize) + { + lastSize = current; + lastGrowth = DateTime.UtcNow; + onProgress?.Invoke(current); + } + + if (pos >= 100) break; + + if (current > 0 && (DateTime.UtcNow - lastGrowth).TotalSeconds > 5) break; + + if (current == 0 && (DateTime.UtcNow - lastGrowth).TotalSeconds > 8) + { + throw new HikException(uint.MaxValue, "设备没有推送回放数据(该时段可能没有录像)"); + } + + if (DateTime.UtcNow > deadline) + { + throw new HikException(uint.MaxValue, "回放拉流超时"); + } + + ct.WaitHandle.WaitOne(200); + } + + HikSdk.NET_DVR_PlayBackControl(handle, HikSdk.PlayStop, 0, IntPtr.Zero); + } + finally + { + HikSdk.NET_DVR_StopPlayBack(handle); + } + }); + } + finally + { + lock (sync) + { + stream?.Flush(); + stream?.Dispose(); + stream = null; + } + } + + return written; + } + + private static HikSdk.NET_DVR_TIME ToSdkTime(DateTime time) => new() + { + dwYear = (uint)time.Year, + dwMonth = (uint)time.Month, + dwDay = (uint)time.Day, + dwHour = (uint)time.Hour, + dwMinute = (uint)time.Minute, + dwSecond = (uint)time.Second, + }; + + /// 抓一帧;分辨率参数按「当前码流 → 720p → D1」降级重试 + private static byte[] CaptureOnce(int userId, int channel) + { + var para = Marshal.AllocHGlobal(4); + var buffer = Marshal.AllocHGlobal(JpegBufferSize); + try + { + Marshal.WriteInt16(para, 0, HikSdk.JpegSizeCurrent); + Marshal.WriteInt16(para, 2, 2); // 质量:最好 → 较好(枚举:0最好 1较好 2一般 3较差 4差) + + if (HikSdk.NET_DVR_CaptureJPEGPicture_NEW(userId, channel, para, buffer, JpegBufferSize, out var size) && size > 0) + { + return CopyFrame(buffer, size); + } + + var firstError = HikSdk.NET_DVR_GetLastError(); + + // 「用当前分辨率」不被支持时退到固定尺寸(实测部分固件回 17/23) + foreach (var sizeHint in new[] { HikSdk.JpegSize720P, HikSdk.JpegSizeD1 }) + { + Marshal.WriteInt16(para, 0, sizeHint); + if (HikSdk.NET_DVR_CaptureJPEGPicture_NEW(userId, channel, para, buffer, JpegBufferSize, out size) && size > 0) + { + return CopyFrame(buffer, size); + } + } + + throw new HikException(firstError, $"抓取画面失败:{HikSdk.DescribeError(firstError)}"); + } + finally + { + Marshal.FreeHGlobal(para); + Marshal.FreeHGlobal(buffer); + } + } + + private static byte[] CopyFrame(IntPtr buffer, uint size) + { + var bytes = new byte[(int)size]; + Marshal.Copy(buffer, bytes, 0, bytes.Length); + return bytes; + } + + /// 登出所有会话 + public void CloseAll() + { + foreach (var key in _sessions.Keys.ToList()) + { + if (!_sessions.TryRemove(key, out var session)) continue; + session.Gate.Wait(); + try { CloseSession(session); } + finally { session.Gate.Release(); session.Gate.Dispose(); } + } + } + + private static void Login(Session session, string password) + { + var userId = HikSdk.Login(session.Host, (ushort)session.Port, session.User, password, out var info); + try + { + session.Device = ParseDeviceInfo(info); + } + finally + { + Marshal.FreeHGlobal(info); + } + + session.UserId = userId; + session.Touch(); + AppLog.Write($"海康登录成功:{session.Host}:{session.Port} 用户={session.User} UserID={userId} 序列号={session.Device?.SerialNumber}"); + } + + private static void CloseSession(Session session) + { + if (session.UserId >= 0) + { + try { HikSdk.NET_DVR_Logout(session.UserId); } catch { /* 忽略 */ } + AppLog.Write($"海康已登出:{session.Host}:{session.Port} UserID={session.UserId}"); + } + + session.UserId = -1; + session.Device = null; + } + + private static void Validate(string host, int port, string userName, string password) + { + if (string.IsNullOrWhiteSpace(host)) throw new ArgumentException("host 不能为空"); + if (host.Length > 128) throw new ArgumentException("host 过长"); + if (port is <= 0 or > 65535) throw new ArgumentException("port 必须在 1~65535 之间"); + if (string.IsNullOrEmpty(userName)) throw new ArgumentException("user 不能为空"); + if (string.IsNullOrEmpty(password)) throw new ArgumentException("password 不能为空"); + if (userName.Length > 63) throw new ArgumentException("user 过长(最多 63 字节)"); + if (password.Length > 63) throw new ArgumentException("password 过长(最多 63 字节)"); + + // HCNetSDK 的字段是 char[](ANSI),非 ASCII 会按码页转换,跨机器容易错位 —— 直接拦住 + foreach (var ch in host + userName + password) + { + if (ch < 0x20 || ch > 0x7E) throw new ArgumentException("host/user/password 仅支持 ASCII 可见字符"); + } + } + + /// + /// 会话键:设备 + 用户 + **密码指纹**。 + /// 必须带密码指纹 —— 否则「改密码 / 用错密码」会命中已有会话,把错误密码也放过去(实测踩过)。 + /// + private static string MakeKey(string host, int port, string userName, string password) + { + var fingerprint = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(password)))[..16]; + return $"{host.Trim().ToLowerInvariant()}:{port}|{userName}|{fingerprint}"; + } + + private static bool IsLinkError(uint code) => code is 7 or 8 or 9 or 10 or 11 or 5 or 27; + + /// 登录返回体(NET_DVR_DEVICEINFO_V40 的前 80 字节为 V30 部分) + private static DeviceSnapshot ParseDeviceInfo(IntPtr buffer) + { + var serialBytes = new byte[48]; + Marshal.Copy(buffer, serialBytes, 0, 48); + var serial = Encoding.ASCII.GetString(serialBytes).TrimEnd('\0').Trim(); + + return new DeviceSnapshot + { + SerialNumber = serial, + DiskCount = Marshal.ReadByte(buffer, 50), + AnalogChannelCount = Marshal.ReadByte(buffer, 52), + StartChannel = Marshal.ReadByte(buffer, 53), + DigitalChannelCount = Marshal.ReadByte(buffer, 55) + (Marshal.ReadByte(buffer, 68) << 8), + StartDigitalChannel = Marshal.ReadByte(buffer, 66), + }; + } + + private static HikChannelsResult ReadChannels(Session session, string password, int webPort) + { + var device = session.Device ?? throw new HikException(3, "设备信息缺失(会话状态异常)"); + + var channels = new List(); + string? warning = null; + + var buffer = Marshal.AllocHGlobal(IpParaBufferSize); + try + { + Marshal.Copy(new byte[IpParaBufferSize], 0, buffer, IpParaBufferSize); + Marshal.WriteInt32(buffer, 0, IpParaBufferSize); // dwSize 必须预先填好 + + var ok = HikSdk.NET_DVR_GetDVRConfig( + session.UserId, + HikSdk.NET_DVR_GET_IPPARACFG_V40, + 0, // ⚠️ 必须传 0,传 -1 会 err=11 + buffer, + IpParaBufferSize, + out var returned); + + if (!ok || returned < 100) + { + var err = HikSdk.NET_DVR_GetLastError(); + if (IsLinkError(err)) throw new HikException(err, $"读取通道配置失败:{HikSdk.DescribeError(err)}"); + + warning = $"读取 IP 接入配置失败({HikSdk.DescribeError(err)}),仅返回登录时的通道统计"; + } + else + { + var analogCount = Marshal.ReadInt32(buffer, 8); + var digitalCount = Marshal.ReadInt32(buffer, 12); + var startDigital = Marshal.ReadInt32(buffer, 16); + + if (analogCount > 0) + { + for (var i = 0; i < analogCount; i++) + { + channels.Add(new HikChannelInfo + { + channel = device.StartChannel + i, + type = "analog", + enabled = true, + }); + } + } + + for (var i = 0; i < digitalCount; i++) + { + var item = ReadIpDevice(buffer, i); + channels.Add(new HikChannelInfo + { + channel = startDigital + i, + type = "digital", + enabled = item.Enabled, + ip = item.Enabled ? item.Ip : null, + port = item.Enabled ? item.Port : null, + user = item.Enabled ? item.UserName : null, + }); + } + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + + // 拿不到配置时用登录信息兜底 + if (channels.Count == 0) + { + for (var i = 0; i < device.AnalogChannelCount; i++) + { + channels.Add(new HikChannelInfo { channel = device.StartChannel + i, type = "analog", enabled = true }); + } + + for (var i = 0; i < device.DigitalChannelCount; i++) + { + channels.Add(new HikChannelInfo { channel = device.StartDigitalChannel + i, type = "digital", enabled = false }); + } + } + + // 通道名:SDK 那段配置里没有名字,走设备 Web/ISAPI 再取一次(取不到不影响其他字段) + TryFillChannelNames(session.Host, webPort, session.User, password, device.StartDigitalChannel, channels); + + return new HikChannelsResult + { + endpoint = $"{session.Host}:{session.Port}", + serialNumber = device.SerialNumber, + diskCount = device.DiskCount, + analogChannelCount = device.AnalogChannelCount, + digitalChannelCount = device.DigitalChannelCount, + startChannel = device.StartChannel, + startDigitalChannel = device.StartDigitalChannel, + channels = channels, + warning = warning, + }; + } + + /// + /// 用 ISAPI 补全通道名(数字通道) + /// + /// ISAPI ContentMgmt/InputProxy/channels 返回的 id 是从 1 开始的 IP 通道序号, + /// 对应海康通道号 startDigitalChannel + (id - 1)。优先按 IP 匹配(最稳),取不到再按 id 匹配。 + /// Web 端口优先用传入的(默认 80),再试 8443(自签证书)。任何失败都静默,不拖慢主流程。 + /// + private static void TryFillChannelNames(string host, int webPort, string userName, string password, int startDigitalChannel, List channels) + { + if (channels.Count == 0) return; + + var urls = new List(); + if (webPort > 0) urls.Add($"http://{host}:{webPort}/ISAPI/ContentMgmt/InputProxy/channels"); + urls.Add($"https://{host}:8443/ISAPI/ContentMgmt/InputProxy/channels"); + + foreach (var url in urls) + { + try + { + using var handler = new HttpClientHandler + { + Credentials = new System.Net.NetworkCredential(userName, password), + PreAuthenticate = false, + // 设备都是自签证书,这里只用于内网取名字,不值得为它做校验 + ServerCertificateCustomValidationCallback = (_, _, _, _) => true, + }; + using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(3) }; + var xml = client.GetStringAsync(url).GetAwaiter().GetResult(); + if (string.IsNullOrWhiteSpace(xml)) continue; + + var document = XDocument.Parse(xml); + var byIp = new Dictionary(StringComparer.OrdinalIgnoreCase); + var byId = new Dictionary(); + + foreach (var node in document.Descendants().Where(e => e.Name.LocalName == "InputProxyChannel")) + { + var name = node.Elements().FirstOrDefault(e => e.Name.LocalName == "name")?.Value?.Trim() ?? string.Empty; + var idText = node.Elements().FirstOrDefault(e => e.Name.LocalName == "id")?.Value; + var ipText = node.Descendants().FirstOrDefault(e => e.Name.LocalName == "ipAddress")?.Value?.Trim(); + + if (int.TryParse(idText, out var id)) byId[id] = name; + if (!string.IsNullOrWhiteSpace(ipText)) byIp[ipText] = name; + } + + if (byIp.Count == 0 && byId.Count == 0) continue; + + foreach (var item in channels) + { + if (item.type != "digital") continue; + + if (!string.IsNullOrWhiteSpace(item.ip) && byIp.TryGetValue(item.ip!, out var nameByIp)) + { + item.name = nameByIp; + continue; + } + + // IP 对不上就按 id 推:isapi id = 1 对应第一个数字通道 + var idGuess = item.channel - startDigitalChannel + 1; + if (idGuess > 0 && byId.TryGetValue(idGuess, out var nameById)) item.name = nameById; + } + + return; // 拿到一次就够 + } + catch + { + // 换下一个地址/协议再试 + } + } + } + + /// NET_DVR_IPPARACFG_V40.struIPDevInfo[i](每项 296 字节,起点偏移 84) + private static IpDeviceEntry ReadIpDevice(IntPtr buffer, int index) + { + const int ipDeviceStart = 84; + const int ipDeviceSize = 296; + + var baseOffset = ipDeviceStart + index * ipDeviceSize; + var enabled = Marshal.ReadByte(buffer, baseOffset); + + // 越界保护:设备返回的缓冲区可能比 64 项小 + var ip = ReadAscii(buffer, baseOffset + 116, 16); + var port = Marshal.ReadInt16(buffer, baseOffset + 260); + var user = ReadAscii(buffer, baseOffset + 4, 32); + + return new IpDeviceEntry + { + Enabled = enabled == 1, + Ip = ip, + Port = port, + UserName = user, + }; + } + + private static string ReadAscii(IntPtr buffer, int offset, int length) + { + var bytes = new byte[length]; + Marshal.Copy(IntPtr.Add(buffer, offset), bytes, 0, length); + var text = Encoding.ASCII.GetString(bytes); + var end = text.IndexOf('\0'); + return (end >= 0 ? text[..end] : text).Trim(); + } + + private void SweepIdleSessions() + { + if (_disposed) return; + + var now = Environment.TickCount64; + foreach (var pair in _sessions) + { + var session = pair.Value; + if (now - session.LastUsedTicks < (long)IdleTimeout.TotalMilliseconds) continue; + if (!session.Gate.Wait(0)) continue; // 正在被使用,下轮再说 + + try + { + if (now - session.LastUsedTicks < (long)IdleTimeout.TotalMilliseconds) continue; + CloseSession(session); + _sessions.TryRemove(pair.Key, out _); + } + finally + { + session.Gate.Release(); + } + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + + _sweeper.Dispose(); + try { CloseAll(); } catch { /* 退出阶段忽略 */ } + HikSdk.Shutdown(); + } + + private sealed class Session + { + public Session(string host, int port, string user) + { + Host = host.Trim(); + Port = port; + User = user; + LastUsedTicks = Environment.TickCount64; + } + + public string Host { get; } + public int Port { get; } + public string User { get; } + + public int UserId { get; set; } = -1; + public DeviceSnapshot? Device { get; set; } + public long LastUsedTicks { get; private set; } + + /// 同一 UserID 的调用串行化 + public SemaphoreSlim Gate { get; } = new(1, 1); + + public void Touch() => LastUsedTicks = Environment.TickCount64; + } + + private sealed class DeviceSnapshot + { + public string SerialNumber { get; init; } = string.Empty; + public int DiskCount { get; init; } + public int AnalogChannelCount { get; init; } + public int StartChannel { get; init; } + public int DigitalChannelCount { get; init; } + public int StartDigitalChannel { get; init; } + } + + private readonly record struct IpDeviceEntry(bool Enabled, string Ip, int Port, string UserName); +} + +/// 一个通道 +public sealed class HikChannelInfo +{ + /// 通道号(海康通道号,1 起;数字通道通常从 33 起) + public int channel { get; init; } + + /// analog / digital + public string type { get; init; } = string.Empty; + + public bool enabled { get; init; } + + /// 设备上的通道名(来自 ISAPI,可能为空) + public string? name { get; set; } + + /// 数字通道对应的前端 IP(未配置时为 null) + public string? ip { get; init; } + + public int? port { get; init; } + + public string? user { get; init; } +} + +/// 录像机的 NTP 配置(8000 私有协议读写) +/// NTP 服务器(域名或 IP) +/// 同步间隔(分钟) +/// 是否启用 NTP 校时 +public sealed record HikNtpConfig(string Server, int IntervalMinutes, bool Enabled); + +/// 通道接口返回体 +public sealed class HikChannelsResult +{ public string endpoint { get; init; } = string.Empty; + public string serialNumber { get; init; } = string.Empty; + public int diskCount { get; init; } + public int analogChannelCount { get; init; } + public int digitalChannelCount { get; init; } + public int startChannel { get; init; } + public int startDigitalChannel { get; init; } + public List channels { get; init; } = new(); + + /// 部分数据读取失败时的提示(不影响已返回的通道) + public string? warning { get; init; } + + // 以下由服务层填充 + public int userId { get; set; } + public bool sessionReused { get; set; } + public long elapsedMs { get; set; } +} diff --git a/desktop/Services/Hik/HikFfmpegService.cs b/desktop/Services/Hik/HikFfmpegService.cs new file mode 100644 index 0000000..3611dce --- /dev/null +++ b/desktop/Services/Hik/HikFfmpegService.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 用 ffmpeg 把设备**主码流**转成 MJPEG(浏览器内嵌用)。 +/// +/// 为什么需要它:主码流是 2560×1440,PlayM4 的 PlayM4_GetJPEG 对这种大帧直接返回 0, +/// 设备抓帧(NET_DVR_CaptureJPEGPicture_NEW)又只有约 5fps。ffmpeg 在 C 里解码 + 缩放 + 编码, +/// 实测主码流(1440p → 1280 宽)可以跑到 ~22fps、约 80KB/帧。 +/// +/// ffmpeg 定位顺序: +/// 1. 环境变量 YUNCANG_FFMPEG(指向 ffmpeg.exe) +/// 2. 程序目录下 native\ffmpeg\ffmpeg.exe +/// 3. 系统 PATH 里的 ffmpeg.exe +/// +/// 同一个 RTSP 地址 + 参数只起**一个** ffmpeg 进程(引用计数),多个页面看同一路不会重复转码。 +/// +public sealed class HikFfmpegService : IDisposable +{ + /// 帧队列上限(超出丢最旧的,防止客户端慢把内存吃满) + private const int MaxQueuedFrames = 8; + + /// 单个 JPEG 帧上限(防止一直等不到 EOI 把缓冲区撑爆) + private const int MaxFrameBytes = 8 * 1024 * 1024; + + private readonly ConcurrentDictionary _streams = new(); + private readonly Dictionary _byKey = new(StringComparer.OrdinalIgnoreCase); + private readonly object _gate = new(); + private int _nextHandle; + private bool _disposed; + + /// ffmpeg.exe 路径(找不到为 null) + public string? FfmpegPath { get; } = ResolveFfmpeg(); + + public bool IsAvailable => !string.IsNullOrEmpty(FfmpegPath); + + public int Count => _streams.Count; + + /// ffmpeg 定位 + public static string? ResolveFfmpeg() + { + // ① 环境变量 + var fromEnv = Environment.GetEnvironmentVariable("YUNCANG_FFMPEG"); + if (!string.IsNullOrWhiteSpace(fromEnv) && File.Exists(fromEnv)) return fromEnv; + + // ② 程序目录 native\ffmpeg\ffmpeg.exe + var local = Path.Combine(AppContext.BaseDirectory, "native", "ffmpeg", "ffmpeg.exe"); + if (File.Exists(local)) return local; + + // ③ PATH + var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; + foreach (var dir in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + try + { + var candidate = Path.Combine(dir.Trim(), "ffmpeg.exe"); + if (File.Exists(candidate)) return candidate; + } + catch + { + // 路径非法跳过 + } + } + + return null; + } + + /// + /// 启动(或复用)一路主码流转码 + /// + /// RTSP 码流号:主码流 = 通道序号*100+1,子码流 = *100+2 + /// 输出宽度(高度按比例),1280 是画质/带宽的平衡点 + /// 输出帧率上限(0 = 跟源) + /// MJPEG 质量 q:v(2 最好 ~ 31 最差;6 约等于高质量) + public int Open(string host, int rtspPort, string userName, string password, string streamId, int width = 1280, int fps = 25, int quality = 6) + { + var url = BuildRtspUrl(host, rtspPort, userName, password, streamId); + return OpenUrl(url, $"{host}:{rtspPort}|{streamId}", width, fps, quality); + } + + /// + /// 按**完整 RTSP 地址**打开一路(回放预览用:地址里带 starttime/endtime) + /// + /// 是复用键前缀,**不能含密码**(地址里有账号密码)。 + /// + public int OpenUrl(string url, string keyPrefix, int width = 1280, int fps = 25, int quality = 6) + { + if (!IsAvailable) + { + throw new HikException(uint.MaxValue, + "未找到 ffmpeg:安装目录下 native\\ffmpeg\\ffmpeg.exe 缺失(安装包可能不完整,建议重新安装本软件);" + + "也可以设置环境变量 YUNCANG_FFMPEG 指定 ffmpeg.exe,或改用「满帧率窗口」看主码流。"); + } + + var key = $"{keyPrefix}|{width}|{fps}|{quality}"; + + lock (_gate) + { + if (_byKey.TryGetValue(key, out var existing) && _streams.TryGetValue(existing, out var alive)) + { + alive.RefCount++; + AppLog.Write($"ffmpeg 复用:{key} 引用数={alive.RefCount}"); + return existing; + } + + var handle = ++_nextHandle; + var stream = new FfmpegStream + { + Handle = handle, + Key = key, + Description = key, + RefCount = 1, + }; + + StartProcess(stream, url, width, fps, quality); + + _streams[handle] = stream; + _byKey[key] = handle; + AppLog.Write($"ffmpeg 已启动:{key}({width} 宽,{fps}fps,q={quality})handle={handle}"); + return handle; + } + } + + /// + /// 取**比 afterVersion 更新**的帧(没有就等到超时) + /// + /// 只保留「最新一帧」而不是帧队列:多个页面/多个会话共用同一路 ffmpeg 时, + /// 各自用自己的版本号取帧,互不抢帧,也不会互相拖慢。 + /// + public bool TryGetLatest(int handle, long afterVersion, int timeoutMs, out byte[] frame, out long version) + { + frame = Array.Empty(); + version = afterVersion; + + if (!_streams.TryGetValue(handle, out var stream)) return false; + + var deadline = Environment.TickCount64 + Math.Max(timeoutMs, 0); + while (true) + { + if (stream.TryGetLatest(afterVersion, out frame, out version)) return true; + if (Environment.TickCount64 > deadline) return false; + Thread.Sleep(10); + } + } + + public bool Close(int handle) + { + lock (_gate) + { + if (!_streams.TryGetValue(handle, out var stream)) return false; + + stream.RefCount--; + if (stream.RefCount > 0) + { + AppLog.Write($"ffmpeg 释放引用:handle={handle} 剩余={stream.RefCount}"); + return true; + } + + _streams.TryRemove(handle, out _); + if (_byKey.TryGetValue(stream.Key, out var mapped) && mapped == handle) _byKey.Remove(stream.Key); + + stream.Terminate(); + AppLog.Write($"ffmpeg 已停止:{stream.Description} handle={handle}"); + return true; + } + } + + private static string BuildRtspUrl(string host, int rtspPort, string userName, string password, string streamId) + { + // 海康 RTSP:/Streaming/Channels/{通道序号}{码流号},如 101=第1通道主码流、102=子码流 + return $"rtsp://{Uri.EscapeDataString(userName)}:{Uri.EscapeDataString(password)}@{host}:{rtspPort}/Streaming/Channels/{streamId}"; + } + + private void StartProcess(FfmpegStream stream, string url, int width, int fps, int quality) + { + var scale = fps is > 0 and < 25 + ? $"scale={width}:-2,fps={fps}" + : $"scale={width}:-2"; + + var args = string.Join(' ', + "-nostdin", + "-loglevel", "error", + "-rtsp_transport", "tcp", + "-fflags", "nobuffer", + "-flags", "low_delay", + "-i", Quote(url), + "-vf", Quote(scale), + "-f", "mjpeg", + "-q:v", quality.ToString(), + "-an", + "-flush_packets", "1", + "pipe:1"); + + var psi = new ProcessStartInfo + { + FileName = FfmpegPath!, + Arguments = args, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = false, + }; + + var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; + stream.Process = process; + + if (!process.Start()) + { + throw new HikException(uint.MaxValue, "ffmpeg 启动失败"); + } + + // stderr 只留最后一段用于报错 + Task.Run(() => + { + try + { + string? line; + while ((line = process.StandardError.ReadLine()) != null) + { + stream.LastError = line; + } + } + catch + { + // 进程退出 + } + }); + + // stdout:按 JPEG 的 FFD8…FFD9 切帧 + Task.Run(() => PumpFrames(stream)); + } + + private static void PumpFrames(FfmpegStream stream) + { + var process = stream.Process!; + var buffer = new List(256 * 1024); + var chunk = new byte[64 * 1024]; + + try + { + var stdout = process.StandardOutput.BaseStream; + int read; + while ((read = stdout.Read(chunk, 0, chunk.Length)) > 0) + { + buffer.AddRange(chunk.AsSpan(0, read).ToArray()); + ExtractFrames(stream, buffer); + } + } + catch + { + // 进程被杀 / 管道断开,属于正常结束 + } + } + + /// 从缓冲区里切出完整 JPEG 帧 + private static void ExtractFrames(FfmpegStream stream, List buffer) + { + while (true) + { + var start = IndexOf(buffer, 0xFF, 0xD8, 0); + if (start < 0) + { + buffer.Clear(); + return; + } + + if (start > 0) buffer.RemoveRange(0, start); + + var end = IndexOf(buffer, 0xFF, 0xD9, 2); + if (end < 0) + { + if (buffer.Count > MaxFrameBytes) buffer.Clear(); + return; + } + + var frame = new byte[end + 2]; + buffer.CopyTo(0, frame, 0, frame.Length); + buffer.RemoveRange(0, frame.Length); + + if (frame.Length > 1000) stream.Enqueue(frame); + } + } + + private static int IndexOf(List buffer, byte first, byte second, int from) + { + for (var i = from; i < buffer.Count - 1; i++) + { + if (buffer[i] == first && buffer[i + 1] == second) return i; + } + return -1; + } + + private static string Quote(string value) => $"\"{value.Replace("\"", "\\\"")}\""; + + public void CloseAll() + { + foreach (var handle in _streams.Keys.ToList()) + { + Close(handle); + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + CloseAll(); + } + + /// 一路 ffmpeg 转码 + private sealed class FfmpegStream + { + private readonly object _sync = new(); + private byte[] _latest = Array.Empty(); + private long _version; + + public int Handle { get; init; } + public string Key { get; init; } = string.Empty; + public string Description { get; init; } = string.Empty; + public int RefCount { get; set; } + public Process? Process { get; set; } + public string? LastError { get; set; } + + /// 新帧覆盖(背压:只留最新的,慢客户端不会把内存吃掉) + public void Enqueue(byte[] frame) + { + lock (_sync) + { + _latest = frame; + _version++; + } + } + + public bool TryGetLatest(long afterVersion, out byte[] frame, out long version) + { + lock (_sync) + { + version = _version; + if (_version > afterVersion && _latest.Length > 0) + { + frame = _latest; + return true; + } + + frame = Array.Empty(); + return false; + } + } + + public void Terminate() + { + try + { + if (Process is { HasExited: false }) + { + Process.Kill(true); + } + } + catch + { + // 忽略 + } + + try { Process?.Dispose(); } catch { /* 忽略 */ } + } + } +} diff --git a/desktop/Services/Hik/HikNativePreviewService.cs b/desktop/Services/Hik/HikNativePreviewService.cs new file mode 100644 index 0000000..6b02554 --- /dev/null +++ b/desktop/Services/Hik/HikNativePreviewService.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Concurrent; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 满帧率预览窗口(PlayM4 直接把解码画面画到窗口,**不经过 JPEG 编码**)。 +/// +/// 为什么需要它:浏览器里内嵌的画面必须逐帧转 JPEG(PlayM4_GetJPEG), +/// 实测 1080p 一帧编码约 140ms → 上限只有 **约 7fps**。要 25fps 就只能让解码器 +/// 直接画到一个原生窗口上(带宽也低:只传 H.264/H.265 码流,不是 JPEG 序列)。 +/// +/// 窗口由本机软件(WPF 主线程)创建;网页点「原生窗口」→ 通过本机 HTTP 服务请求打开, +/// 关掉窗口时自动释放码流(不需要网页再通知)。 +/// +public sealed class HikNativePreviewService : IDisposable +{ + private readonly HikStreamService _stream; + private readonly ConcurrentDictionary _windows = new(StringComparer.OrdinalIgnoreCase); + private bool _disposed; + + public HikNativePreviewService(HikStreamService stream) + { + _stream = stream; + } + + public int Count => _windows.Count; + + /// + /// 打开一个满帧率预览窗口(必须在 UI 线程创建 WinForms 窗口) + /// + public NativePreview Open(string host, int port, string userName, string password, int channel, int streamType = 0, string? name = null) + { + // ⚠️ 这里是 WPF 的 Application(本文件已 using WinForms,`Application` 会被解析成 WinForms 的) + var dispatcher = System.Windows.Application.Current?.Dispatcher + ?? throw new InvalidOperationException("本机软件界面未就绪,无法打开预览窗口"); + + return dispatcher.Invoke(() => OpenOnUiThread(host, port, userName, password, channel, streamType, name)); + } + + /// 按 id 关窗口(网页关闭时调) + public bool Close(string? id) + { + if (string.IsNullOrWhiteSpace(id) || !_windows.TryGetValue(id, out var preview)) return false; + preview.Close(); + return true; + } + + public void CloseAll() + { + foreach (var id in _windows.Keys.ToList()) Close(id); + } + + private NativePreview OpenOnUiThread(string host, int port, string userName, string password, int channel, int streamType, string? name) + { + var wid = Guid.NewGuid().ToString("N")[..8]; + var title = string.IsNullOrWhiteSpace(name) ? $"通道 {channel}" : name!; + + var form = new Form + { + Text = $"实时预览 - {title}({host} 通道 {channel})", + StartPosition = FormStartPosition.CenterScreen, + ClientSize = new Size(1024, 600), + BackColor = Color.Black, + Icon = null, + MinimizeBox = true, + ShowIcon = false, + }; + + var panel = new Panel { Dock = DockStyle.Fill, BackColor = Color.Black }; + + // 底部状态条:告诉用户这是满帧率模式,以及码流类型 + var status = new Label + { + Dock = DockStyle.Bottom, + Height = 26, + TextAlign = ContentAlignment.MiddleLeft, + Padding = new Padding(10, 0, 0, 0), + ForeColor = Color.Gainsboro, + BackColor = Color.FromArgb(24, 24, 24), + Text = $"{host} · 通道 {channel} · {(streamType == 0 ? "主码流" : "子码流")} · 满帧率(约 25fps)", + }; + + form.Controls.Add(panel); + form.Controls.Add(status); + + var preview = new NativePreview { Id = wid, Form = form, Channel = channel, Host = host, StreamType = streamType }; + + // 窗口句柄要等窗口创建后才有效 → 在 Shown 里开流 + form.Shown += (_, _) => + { + try + { + var handle = _stream.Open(host, port, userName, password, channel, streamType, name, panel.Handle); + preview.StreamHandle = handle; + } catch (Exception ex) + { + AppLog.Write($"满帧率预览打开失败(通道 {channel}):{ex.Message}"); + MessageBox.Show(form, ex.Message, "预览失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + form.Close(); + } + }; + + // 双击全屏/还原 + panel.DoubleClick += (_, _) => + { + form.FormBorderStyle = form.FormBorderStyle == FormBorderStyle.None + ? FormBorderStyle.Sizable + : FormBorderStyle.None; + form.WindowState = form.WindowState == FormWindowState.Maximized + ? FormWindowState.Normal + : FormWindowState.Maximized; + }; + + form.FormClosed += (_, _) => + { + if (preview.StreamHandle >= 0) _stream.Close(preview.StreamHandle); + _windows.TryRemove(wid, out _); + }; + + _windows[wid] = preview; + form.Show(); + form.Activate(); + + AppLog.Write($"满帧率预览窗口已打开:{host} 通道 {channel}(wid={wid})"); + return preview; + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + CloseAll(); + } +} + +/// 一个原生预览窗口 +public sealed class NativePreview +{ + public string Id { get; init; } = string.Empty; + public string Host { get; init; } = string.Empty; + public int Channel { get; init; } + public int StreamType { get; init; } + + internal Form? Form { get; init; } + internal int StreamHandle { get; set; } = -1; + + /// 关窗口(UI 线程) + public void Close() + { + try + { + var form = Form; + if (form is null) return; + + if (form.InvokeRequired) form.BeginInvoke(form.Close); + else form.Close(); + } + catch + { + // 已经关掉了 + } + } +} diff --git a/desktop/Services/Hik/HikPlaybackService.cs b/desktop/Services/Hik/HikPlaybackService.cs new file mode 100644 index 0000000..e1bf683 --- /dev/null +++ b/desktop/Services/Hik/HikPlaybackService.cs @@ -0,0 +1,686 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// 一次「这个时段到底有没有录像」的探测结果 +/// 拉到数据 = 有录像 +/// RTSP 模式下解出的帧数(SDK 模式为 -1) +/// 换算出来的 ISAPI/RTSP 1 起通道序号(排查用) +/// 失败原因(无录像 / 端口不通 / 密码错) +/// 实际走通的通道:SDK(8000)/ RTSP(554) +public sealed record PlaybackCheck(bool HasRecord, int Frames, int LogicalChannel, string? Error, string Source = ""); + +/// 下载一路回放的进度 +/// 0~1(拿不到总时长时为 null,界面显示为不确定进度) +/// 当前状态文案 +public sealed record PlaybackProgress(double? Percent, string Message); + +/// +/// 海康 **按时间回放**:校验有没有录像 / 拉流预览 / 下载成 mp4 +/// +/// 两条通道,**优先 8000(SDK 私有协议),不行再走 554(RTSP)**: +/// +/// | | SDK(`NET_DVR_GetFileByTime_V40`) | RTSP(`Streaming/tracks/...`) | +/// | --- | --- | --- | +/// | 端口 | 8000(现场基本都开) | 554(可能关/改端口) | +/// | 通道号 | **海康通道号**(34) | **ISAPI 序号**(2) | +/// | 落地 | 设备原始封装 PS,需 ffmpeg 转封装 | 直接交给 ffmpeg | +/// | 速度 | 2~5x 实时,带百分比进度 | 约 0.5~3x,靠 ffmpeg 进度 | +/// +/// 实测(本项目 NVR):RTSP 的 `tracks/201`(=通道34)能拉到回放, +/// `tracks/3401` 直接 400;空时段会返回 400 而不是空流 —— 两个信号都能用来判「有/无回放」。 +/// +public sealed class HikPlaybackService : IDisposable +{ + /// Hikvision RTSP 默认端口(设备侧可改,用环境变量覆盖) + private static readonly int RtspPort = ResolveRtspPort(); + + private static readonly Regex FrameRegex = new(@"frame=\s*(\d+)", RegexOptions.Compiled); + private static readonly Regex OutTimeRegex = new(@"out_time_us=(\d+)", RegexOptions.Compiled); + private static readonly Regex SpeedRegex = new(@"speed=\s*([\d.]+)x", RegexOptions.Compiled); + + /// RTSP socket 读超时(微秒)。回放拉完设备不再推流,靠它让 ffmpeg 收尾退出 + private const string SocketTimeoutUs = "5000000"; + + private readonly HikDeviceService _device; + + /// + /// 「这台设备的 8000 下载能不能用」缓存(key = host|port|channel) + /// + /// 实测:有些固件 NET_DVR_GetFileByTime* 直接不工作(返回句柄但 0 字节), + /// 每路都去试一遍要多等好几秒 → 试过一次就记住,下次直接走 RTSP。 + /// + private readonly ConcurrentDictionary _sdkPlayback = new(StringComparer.OrdinalIgnoreCase); + + /// + /// 「录像机时间 - 本机时间」偏差缓存(key = host|port|user) + /// + /// 扫码时间是**本机时钟**打的,回放是按**录像机本地时间**定位的;两边不一致时 + /// (现场实测本机慢了 9 秒),短回放窗口会把面单直接截掉。 + /// 以录像机时钟为基准做平移,缓存 10 分钟(读不到设备时间时 1 分钟内不重试)。 + /// + private readonly ConcurrentDictionary _clockOffsets = + new(StringComparer.OrdinalIgnoreCase); + + private const long ClockOffsetTtlMs = 10 * 60 * 1000; + private const long ClockOffsetFailTtlMs = 60 * 1000; + + public HikPlaybackService(HikDeviceService device) + { + _device = device; + } + + /// ffmpeg 是否可用(没有就既不能校验也不能下载) + public bool Available => HikFfmpegService.ResolveFfmpeg() is not null; + + // ==================== 通道号换算 ==================== + + /// + /// 海康通道号 → ISAPI/RTSP 的 1 起序号 + /// + /// 换算依赖设备的「首个数字通道号」(本项目是 33): + /// logical = channel - startDigital + 1。SDK 不可用时按 33 兜底。 + /// + public int LogicalChannel(string host, int port, string userName, string password, int channel) + { + var startDigital = 33; + try + { + var start = _device.GetStartDigitalChannel(host, port, userName, password); + if (start > 0) startDigital = start; + } + catch (Exception ex) + { + AppLog.Write($"[playback] 取起始数字通道号失败,按 {startDigital} 兜底:{ex.Message}"); + } + + var logical = channel - startDigital + 1; + return logical > 0 ? logical : channel; + } + + /// + /// 生成回放 RTSP 地址 + /// + /// ⚠️ **时间语义实测结论(重要)**:海康 RTSP 的 starttime 按**设备本地时间**解析, + /// 结尾那个 Z 只是格式后缀、**不代表 UTC**。 + /// 实测同一时间点: + /// - 传 20261018T131550Z(UTC 写法)→ 画面 OSD 是 **13:15:49**(2号工作台,无任务) + /// - 传 20261018T211550Z(本地写法)→ 画面 OSD 是 **21:15:49**(1号工作台,波次B…) + /// 也就是按 UTC 传会整整差一个时区(本机 +08:00 差 8 小时)。 + /// + /// 默认按本地时间拼;万一遇到严格按 UTC 解析的固件,用环境变量 YUNCANG_RTSP_TIME=utc 切回去。 + /// + /// 0 主码流 / 1 子码流(回放路径里是 01 / 02) + public static string BuildRtspUrl(string host, string userName, string password, int logicalChannel, + DateTimeOffset start, DateTimeOffset end, int streamType = 0, int rtspPort = 0) + { + var port = rtspPort > 0 ? rtspPort : RtspPort; + var startText = FormatTime(start); + var endText = FormatTime(end); + var streamNo = streamType == 1 ? "02" : "01"; + + return $"rtsp://{Uri.EscapeDataString(userName)}:{Uri.EscapeDataString(password)}@{host}:{port}" + + $"/Streaming/tracks/{logicalChannel}{streamNo}?starttime={startText}&endtime={endText}"; + } + + private static string FormatTime(DateTimeOffset value) + { + var useUtc = string.Equals(Environment.GetEnvironmentVariable("YUNCANG_RTSP_TIME"), "utc", + StringComparison.OrdinalIgnoreCase); + + var time = useUtc ? value.UtcDateTime : value.ToLocalTime().DateTime; + return time.ToString("yyyyMMdd'T'HHmmss'Z'", CultureInfo.InvariantCulture); + } + + /// + /// 录像机时钟与本机时钟的偏差(设备 - 本机,秒)。 + /// + /// 扫码时间来自本机时钟,回放定位用设备时间 → 两者必须在同一条时间轴上。 + /// 读不到设备时间 / 设备不支持该命令时返回零(保持原有行为)。 + /// + public TimeSpan ClockOffset(string host, int port, string userName, string password) + { + var key = $"{host}|{port}|{userName}"; + if (_clockOffsets.TryGetValue(key, out var hit) && Environment.TickCount64 - hit.At < hit.Ttl) + { + return hit.Offset; + } + + try + { + var before = DateTime.Now; + var device = _device.GetDeviceTime(host, port, userName, password); + var after = DateTime.Now; + + // 取请求中点做本机时间,抵消一次往返的一半延迟 + var local = before.AddTicks((after - before).Ticks / 2); + var offset = device - local; + + _clockOffsets[key] = (offset, Environment.TickCount64, ClockOffsetTtlMs); + AppLog.Write($"[playback] 录像机 {host}:{port} 与本机时钟相差 {offset.TotalSeconds:+0.0;-0.0} 秒,回放时间已按录像机时钟对齐"); + return offset; + } + catch (Exception ex) + { + _clockOffsets[key] = (TimeSpan.Zero, Environment.TickCount64, ClockOffsetFailTtlMs); + AppLog.Write($"[playback] 读不到录像机时间(按本机时钟处理):{ex.Message}"); + return TimeSpan.Zero; + } + } + + /// 生成回放 RTSP 地址(自动把本机时间平移成录像机时间) + public string BuildRtspUrlFor(string host, int port, string userName, string password, + int logicalChannel, DateTimeOffset start, DateTimeOffset end, int streamType = 0) + { + var offset = ClockOffset(host, port, userName, password); + return BuildRtspUrl(host, userName, password, logicalChannel, + start.Add(offset), end.Add(offset), streamType); + } + + // ==================== ① 校验有没有录像 ==================== + + /// + /// 探测该时段有没有录像 + /// + /// **先走 8000(SDK 下载 2 秒到临时文件,看有没有数据)**,不行再走 RTSP 拉 2 秒看帧。 + /// 设备不会主动告诉你空段,只能真拉一次。 + /// + public async Task CheckAsync(string host, int port, string userName, string password, + int channel, DateTimeOffset start, DateTimeOffset end, CancellationToken ct = default) + { + if (end <= start) return new PlaybackCheck(false, 0, 0, "回放区间为空"); + + // 扫码时间是本机时钟 → 平移成录像机时间,否则时钟偏差会把面单挤出回放窗口 + var clock = ClockOffset(host, port, userName, password); + start = start.Add(clock); + end = end.Add(clock); + + var sdkKey = $"{host}|{port}|{channel}|pb"; + var trySdk = !_sdkPlayback.TryGetValue(sdkKey, out var capable) || capable; + + // ① SDK(8000 私有协议):**全速推送**,实测 14 MB/s(≈17 倍速) + var probeEnd = start.AddSeconds(Math.Min(2, Math.Max((end - start).TotalSeconds, 1))); + var probeFile = Path.Combine(Path.GetTempPath(), $"yc_probe_{Guid.NewGuid():N}.ps"); + + if (trySdk) + { + try + { + var bytes = await Task.Run(() => _device.PullPlaybackToFile(host, port, userName, password, + channel, start.LocalDateTime, probeEnd.LocalDateTime, probeFile, null, ct), ct) + .ConfigureAwait(false); + + AppLog.Write($"[playback] SDK 探测 {host} 通道{channel}:{bytes} 字节"); + + if (bytes > 16 * 1024) + { + _sdkPlayback[sdkKey] = true; + return new PlaybackCheck(true, -1, LogicalChannel(host, port, userName, password, channel), + null, "SDK"); + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + _sdkPlayback[sdkKey] = false; + AppLog.Write($"[playback] SDK 探测失败({ex.Message}),本设备后续直接走 RTSP"); + } + finally + { + TryDelete(probeFile); + } + } + + // ② RTSP 回落 + var ffmpeg = HikFfmpegService.ResolveFfmpeg() + ?? throw new HikException(uint.MaxValue, "未找到 ffmpeg,无法校验回放(安装目录 native\\ffmpeg\\ffmpeg.exe 缺失,建议重新安装本软件)"); + + var logical = LogicalChannel(host, port, userName, password, channel); + var url = BuildRtspUrl(host, userName, password, logical, start, end); + var seconds = Math.Clamp((end - start).TotalSeconds, 0.5, 2.0); + + var args = new[] + { + "-hide_banner", "-nostdin", "-loglevel", "error", + "-rtsp_transport", "tcp", "-timeout", SocketTimeoutUs, + "-i", url, + "-t", seconds.ToString("0.#", CultureInfo.InvariantCulture), + "-an", "-f", "null", + // ⚠️ 靠 -progress 才能拿到 frame=:ffmpeg 的统计行是 info 级别, + // 用 -loglevel error 时根本不会打印(曾经因此把所有时段误判成「无录像」) + "-progress", "pipe:2", "-nostats", + "-", + }; + + var output = new StringBuilder(); + var exit = await RunAsync(ffmpeg, args, line => { lock (output) output.AppendLine(line); }, ct) + .ConfigureAwait(false); + + string text; + lock (output) text = output.ToString(); + + var match = FrameRegex.Match(text); + var frames = match.Success && int.TryParse(match.Groups[1].Value, out var count) ? count : 0; + + if (frames > 0) return new PlaybackCheck(true, frames, logical, null, "RTSP"); + + var error = Summarize(text) ?? (exit == 0 ? "该时段没有录像" : $"ffmpeg 退出码 {exit}"); + return new PlaybackCheck(false, 0, logical, error, "RTSP"); + } + + // ==================== ② 下载成 mp4 ==================== + + /// + /// 下载一路回放到文件 + /// + /// 实测出来的两个坑(本项目 NVR): + /// 1. **回放流不会按 endtime 自己断**:ffmpeg 拉完数据还挂在 RTSP 读上,进程不退出 → + /// 必须加 -timeout(socket I/O 超时)オ能让它正常收尾; + /// 2. **不能直接写 mp4**:流没正常结束就不会写 moov atom,文件无法播放(moov atom not found)。 + /// 所以先写 mpegts(流式容器,中途中断也能播),完成后本地转封装成 mp4。 + /// + /// 回放速度实测约 0.5x~3x(跟码流大小有关),所以**必须显示进度、必须能取消**。 + /// + /// 落地文件路径(mp4;转封装失败时是 .ts) + public async Task DownloadAsync(string host, int port, string userName, string password, + int channel, DateTimeOffset start, DateTimeOffset end, string outputPath, + IProgress? progress = null, CancellationToken ct = default) + { + var ffmpeg = HikFfmpegService.ResolveFfmpeg() + ?? throw new HikException(uint.MaxValue, "未找到 ffmpeg,无法下载录像(安装目录 native\\ffmpeg\\ffmpeg.exe 缺失,建议重新安装本软件)"); + + if (end <= start) throw new HikException(uint.MaxValue, "回放区间为空"); + + // 扫码时间是本机时钟 → 平移成录像机时间(见 CheckAsync 的说明) + var clock = ClockOffset(host, port, userName, password); + start = start.Add(clock); + end = end.Add(clock); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? AppContext.BaseDirectory); + + // ① 优先 SDK(8000 私有协议),但**只在它被证明可用时**; + // 实测部分固件(本项目这台 NVR)GetFileByTime 返回句柄却不推数据 → 试一次就永久回落 RTSP。 + var sdkKey = $"{host}|{port}|{channel}|pb"; + if (!_sdkPlayback.TryGetValue(sdkKey, out var sdkCapable) || sdkCapable) + { + var tempPs = Path.Combine(Path.GetTempPath(), $"yc_pb_{Guid.NewGuid():N}.ps"); + try + { + progress?.Report(new PlaybackProgress(0, "下载中(8000 全速)…")); + + var bytes = await Task.Run(() => _device.PullPlaybackToFile(host, port, userName, password, channel, + start.LocalDateTime, end.LocalDateTime, tempPs, + received => progress?.Report(new PlaybackProgress(null, + $"下载中(8000 全速){received / 1024.0 / 1024.0:0.0} MB")), ct), ct) + .ConfigureAwait(false); + + AppLog.Write($"[playback] SDK 拉流完成:{bytes} 字节"); + + if (bytes > 16 * 1024) + { + _sdkPlayback[sdkKey] = true; + progress?.Report(new PlaybackProgress(0.99, "正在封装成 mp4…")); + if (await RepackAsync(ffmpeg, tempPs, outputPath, ct).ConfigureAwait(false)) + { + var okSize = new FileInfo(outputPath).Length; + progress?.Report(new PlaybackProgress(1, $"下载完成({Math.Round(okSize / 1024.0 / 1024.0, 1)} MB)")); + AppLog.Write($"[playback] 回放已下载:{outputPath}({okSize} 字节)"); + return outputPath; + } + + // mp4 封装不了 → 把设备原始 PS 留下(PotPlayer/VLC 能直接播) + var psPath = outputPath + ".ps"; + if (File.Exists(psPath)) File.Delete(psPath); + File.Move(tempPs, psPath); + progress?.Report(new PlaybackProgress(1, "下载完成(原始封装 .ps)")); + AppLog.Write($"[playback] 封装失败,保留原始录像:{psPath}"); + return psPath; + } + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + _sdkPlayback[sdkKey] = false; + AppLog.Write($"[playback] SDK 下载失败({ex.Message}),本设备后续直接走 RTSP 554"); + } + finally + { + TryDelete(tempPs); + } + } + + var logical = LogicalChannel(host, port, userName, password, channel); + var url = BuildRtspUrl(host, userName, password, logical, start, end); + var totalMs = Math.Max((end - start).TotalMilliseconds, 1); + var totalSec = Math.Max((end - start).TotalSeconds, 1); + + Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? AppContext.BaseDirectory); + + var tsPath = Path.ChangeExtension(outputPath, ".ts"); + if (File.Exists(tsPath)) File.Delete(tsPath); + + progress?.Report(new PlaybackProgress(0, "开始下载…")); + + // ① 拉流存 ts(流式容器,中途取消也能播) + var pullArgs = new[] + { + "-hide_banner", "-nostdin", "-loglevel", "error", + "-rtsp_transport", "tcp", "-timeout", SocketTimeoutUs, + "-i", url, + "-t", (totalSec + 1).ToString("0", CultureInfo.InvariantCulture), + "-c:v", "copy", "-an", "-f", "mpegts", + "-progress", "pipe:2", "-nostats", + "-y", tsPath, + }; + + var exit = await RunAsync(ffmpeg, pullArgs, + line => ReportProgress(progress, line, totalMs, "下载中"), ct).ConfigureAwait(false); + + var size = File.Exists(tsPath) ? new FileInfo(tsPath).Length : 0; + if (!File.Exists(tsPath) || size < 16 * 1024) + { + throw new HikException(uint.MaxValue, + exit == 0 ? "该时段没有拉到录像数据" : $"下载失败(ffmpeg 退出码 {exit})"); + } + + // ② 转封装成 mp4(本地操作,很快;失败就保留 ts) + progress?.Report(new PlaybackProgress(0.99, "正在封装成 mp4…")); + if (File.Exists(outputPath)) File.Delete(outputPath); + + var convertArgs = new[] + { + "-hide_banner", "-nostdin", "-loglevel", "error", + "-i", tsPath, + "-c:v", "copy", "-an", "-movflags", "+faststart", + "-y", outputPath, + }; + + var convertExit = await RunAsync(ffmpeg, convertArgs, null, ct).ConfigureAwait(false); + + var result = outputPath; + if (convertExit != 0 || !File.Exists(outputPath) || new FileInfo(outputPath).Length < 16 * 1024) + { + // mp4 封装不了(极少见)→ 保留 ts,也能直接播 + AppLog.Write($"[playback] mp4 封装失败(exit={convertExit}),保留 ts:{tsPath}"); + result = tsPath; + } + else + { + File.Delete(tsPath); + } + + var finalSize = new FileInfo(result).Length; + progress?.Report(new PlaybackProgress(1, $"下载完成({Math.Round(finalSize / 1024.0 / 1024.0, 1)} MB)")); + AppLog.Write($"[playback] 回放已下载:{result}({finalSize} 字节)"); + return result; + } + + // ==================== ③ 按工作台布局合并成一个视频 ==================== + + /// + /// 把多路下载好的片段**按工作台画布布局合并成一个视频** + /// + /// 做法:先铺一张黑画布(`color` 虚拟输入),每路 `scale` 到它在快照里的尺寸, + /// 再用 `overlay=x:y` 摆到对应位置 —— 与工作台页面上的画面摆放一致。 + /// + /// ⚠️ 踩过的坑:**不要**把每路先 pad 成整张画布再叠加 —— + /// 补边是黑底,叠上去会把下面那路的画面整块盖住(表现是「合成完只剩一个小窗,其余全黑」)。 + /// + /// 为什么要重新编码:多路叠加没法 `-c:v copy`(要重画每个像素),所以这一步比下载慢, + /// 用 veryfast + crf 23 折中。 + /// + /// 各路下载好的文件(顺序与 一一对应) + /// 合并后文件路径 + public async Task ComposeAsync(IReadOnlyList segments, IReadOnlyList streams, + string outputPath, IProgress? progress = null, CancellationToken ct = default) + { + if (segments.Count == 0) throw new HikException(uint.MaxValue, "没有可合并的片段"); + if (segments.Count != streams.Count) throw new HikException(uint.MaxValue, "片段数与流数量不一致"); + + var ffmpeg = HikFfmpegService.ResolveFfmpeg() + ?? throw new HikException(uint.MaxValue, "未找到 ffmpeg,无法合并视频(安装目录 native\\ffmpeg\\ffmpeg.exe 缺失,建议重新安装本软件)"); + + if (segments.Count == 1) + { + if (!string.Equals(segments[0], outputPath, StringComparison.OrdinalIgnoreCase)) + { + if (File.Exists(outputPath)) File.Delete(outputPath); + File.Copy(segments[0], outputPath); + } + return outputPath; + } + + var canvasWidth = streams.Max(item => item.CanvasWidth) > 0 + ? streams.Max(item => item.CanvasWidth) + : 1920; + var canvasHeight = streams.Max(item => item.CanvasHeight) > 0 + ? streams.Max(item => item.CanvasHeight) + : 1080; + + var totalSec = Math.Max((streams[0].EndTime - streams[0].StartTime).TotalSeconds, 1); + + var filters = new List(); + for (var i = 0; i < streams.Count; i++) + { + var stream = streams[i]; + var width = stream.Layout.Width > 0 ? stream.Layout.Width : canvasWidth; + var height = stream.Layout.Height > 0 ? stream.Layout.Height : canvasHeight; + + // 帧率统一到 25(各路帧率不一样,overlay 会互相等待并对不齐) + filters.Add($"[{i + 1}:v]scale={width}:{height}:force_original_aspect_ratio=decrease," + + $"fps=25,format=yuv420p,setsar=1[v{i}]"); + } + + var current = "[0:v]"; + for (var i = 0; i < streams.Count; i++) + { + var label = i == streams.Count - 1 ? "[out]" : $"[c{i}]"; + filters.Add($"{current}[v{i}]overlay={streams[i].Layout.X}:{streams[i].Layout.Y}{label}"); + current = label; + } + + var args = new List + { + "-hide_banner", "-nostdin", "-loglevel", "error", + // 黑画布当底板(d 与录像时长一致);索引 0,各路视频从 1 开始 + "-f", "lavfi", "-i", + $"color=c=black:s={canvasWidth}x{canvasHeight}:r=25:d={totalSec.ToString("0", CultureInfo.InvariantCulture)}", + }; + foreach (var segment in segments) + { + args.Add("-i"); + args.Add(segment); + } + + args.AddRange(new[] + { + "-filter_complex", string.Join(';', filters), + "-map", current, + "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", + "-an", "-movflags", "+faststart", + "-t", totalSec.ToString("0", CultureInfo.InvariantCulture), + "-progress", "pipe:2", "-nostats", + "-y", outputPath, + }); + + progress?.Report(new PlaybackProgress(0, "正在合并(按工作台布局)…")); + + var totalMs = totalSec * 1000; + var exit = await RunAsync(ffmpeg, args.ToArray(), + line => ReportProgress(progress, line, totalMs, "合并中"), ct).ConfigureAwait(false); + + if (exit != 0 || !File.Exists(outputPath) || new FileInfo(outputPath).Length < 16 * 1024) + { + throw new HikException(uint.MaxValue, $"合并失败(ffmpeg 退出码 {exit})"); + } + + var size = new FileInfo(outputPath).Length; + progress?.Report(new PlaybackProgress(1, $"合并完成({Math.Round(size / 1024.0 / 1024.0, 1)} MB)")); + AppLog.Write($"[playback] 已合并 {segments.Count} 路 → {outputPath}({size} 字节)"); + return outputPath; + } + + // ==================== 内部 ==================== + + /// 把设备原始录像(PS)转封装成 mp4;失败返回 false + private async Task RepackAsync(string ffmpeg, string input, string outputPath, CancellationToken ct) + { + if (File.Exists(outputPath)) File.Delete(outputPath); + + var args = new[] + { + "-hide_banner", "-nostdin", "-loglevel", "error", + "-i", input, + "-c:v", "copy", "-an", "-movflags", "+faststart", + "-y", outputPath, + }; + + var exit = await RunAsync(ffmpeg, args, null, ct).ConfigureAwait(false); + if (exit == 0 && File.Exists(outputPath) && new FileInfo(outputPath).Length > 16 * 1024) return true; + + // 复制失败(PS 里码流不规范)→ 转码兜底 + AppLog.Write($"[playback] 转封装失败(exit={exit}),改用转码"); + if (File.Exists(outputPath)) File.Delete(outputPath); + + var transcode = new[] + { + "-hide_banner", "-nostdin", "-loglevel", "error", + "-i", input, + "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", + "-an", "-movflags", "+faststart", + "-y", outputPath, + }; + + exit = await RunAsync(ffmpeg, transcode, null, ct).ConfigureAwait(false); + return exit == 0 && File.Exists(outputPath) && new FileInfo(outputPath).Length > 16 * 1024; + } + + private static void TryDelete(string path) + { + try + { + if (File.Exists(path)) File.Delete(path); + } + catch + { + // 临时文件删不掉不影响业务 + } + } + + /// + /// 跑一次 ffmpeg:stderr 逐行回调(进度/错误都在 stderr) + /// + private async Task RunAsync(string ffmpeg, string[] args, Action? onLine, CancellationToken ct) + { + var psi = new ProcessStartInfo + { + FileName = ffmpeg, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = false, + }; + foreach (var arg in args) psi.ArgumentList.Add(arg); + + using var process = new Process { StartInfo = psi, EnableRaisingEvents = true }; + process.ErrorDataReceived += (_, e) => { if (e.Data is not null) onLine?.Invoke(e.Data); }; + process.OutputDataReceived += (_, e) => { if (e.Data is not null) onLine?.Invoke(e.Data); }; + + process.Start(); + process.BeginErrorReadLine(); + process.BeginOutputReadLine(); + + try + { + await process.WaitForExitAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + TryKill(process); + throw; + } + + return process.ExitCode; + } + + private static void TryKill(Process process) + { + try + { + if (!process.HasExited) process.Kill(entireProcessTree: true); + } + catch + { + // 进程已经退了 + } + } + + /// 解析 `-progress` 的 `out_time_us=`,算百分比 + private static void ReportProgress(IProgress? progress, string line, double totalMs, string label) + { + if (progress is null) return; + + var time = OutTimeRegex.Match(line); + if (time.Success && long.TryParse(time.Groups[1].Value, out var micro)) + { + var doneMs = micro / 1000.0; + var percent = Math.Clamp(doneMs / totalMs, 0, 0.999); + var speed = SpeedRegex.Match(line); + var suffix = speed.Success ? $" · {speed.Groups[1].Value}x" : string.Empty; + progress.Report(new PlaybackProgress(percent, $"{label} {percent:P0}{suffix}")); + } + } + + /// 把 ffmpeg 的输出压成一句能看懂的错因 + private static string? Summarize(string output) + { + foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries)) + { + var text = line.Trim(); + if (text.Length == 0) continue; + + if (text.Contains("401", StringComparison.Ordinal) || text.Contains("Unauthorized", StringComparison.OrdinalIgnoreCase)) + return "录像机拒绝访问(账号/密码错)"; + if (text.Contains("400 Bad Request", StringComparison.OrdinalIgnoreCase)) + return "该时段没有录像(RTSP 返回 400)"; + if (text.Contains("404", StringComparison.Ordinal) || text.Contains("Not Found", StringComparison.OrdinalIgnoreCase)) + return "该通道/时段没有录像(RTSP 404)"; + if (text.Contains("Connection refused", StringComparison.OrdinalIgnoreCase)) + return "连不上录像机的 RTSP 端口(554)"; + if (text.Contains("timed out", StringComparison.OrdinalIgnoreCase)) + return "连接录像机超时"; + if (line.StartsWith("Error", StringComparison.OrdinalIgnoreCase) || text.StartsWith("rtsp:", StringComparison.OrdinalIgnoreCase)) + return text.Length > 160 ? text[..160] : text; + } + return null; + } + + private static int ResolveRtspPort() + { + return int.TryParse(Environment.GetEnvironmentVariable("YUNCANG_RTSP_PORT"), out var port) && port > 0 + ? port + : 554; + } + + public void Dispose() + { + // 后台任务由调用方各自取消;这里没有需要释放的资源 + } +} diff --git a/desktop/Services/Hik/HikPreviewService.cs b/desktop/Services/Hik/HikPreviewService.cs new file mode 100644 index 0000000..bf71f76 --- /dev/null +++ b/desktop/Services/Hik/HikPreviewService.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 预览会话管理。 +/// +/// 为什么要有「会话」这层: +/// - 浏览器要把实时画面显示出来,必须有一个能持续拉的地址;而密码**不能**出现在 URL 里 +/// (会被历史记录、日志、代理记下来)。所以先 POST /api/hik/preview 换一个 +/// sid,之后 <img src="/api/hik/preview/mjpeg?sid=...> 只带 sid; +/// - 会话里存着设备凭据与通道号,抓帧时直接复用 的连接池, +/// 不会每次请求都重新登录设备; +/// - 30 分钟没人刷新自动失效(滑动过期),进程内内存存储,不落盘。 +/// +/// 抓帧用 HCNetSDK 的 NET_DVR_CaptureJPEGPicture_NEW(8000 端口私有协议): +/// 不需要解码器、不需要转码,拿到的 JPEG 浏览器直接能显示。 +/// +public sealed class HikPreviewService : IDisposable +{ + /// 会话空闲多久失效(浏览器一直开着流会不断续期) + private static readonly TimeSpan SessionTtl = TimeSpan.FromMinutes(30); + + /// 同时保留的会话上限(防止页面异常反复建会话把内存吃满) + private const int MaxSessions = 32; + + private readonly HikDeviceService _device; + private readonly HikStreamService _stream; + private readonly HikFfmpegService _ffmpeg; + private readonly ConcurrentDictionary _sessions = new(StringComparer.OrdinalIgnoreCase); + private readonly Timer _sweeper; + private bool _disposed; + + public HikPreviewService(HikDeviceService device, HikStreamService stream, HikFfmpegService ffmpeg) + { + _device = device; + _stream = stream; + _ffmpeg = ffmpeg; + _sweeper = new Timer(_ => Sweep(), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); + } + + /// + /// 建预览会话(会登录一次设备验证账号密码,并从登录信息里读「首个数字通道号」) + /// + /// + /// ffmpeg = ffmpeg 转码(主码流可用,缩到 width 宽); + /// stream = SDK 取流 + PlayM4 解码转 JPEG(适合子码流); + /// capture = 设备抓帧(约 5fps)。 + /// + /// 0-主码流,1-子码流 + /// ISAPI/RTSP 的 1 起通道序号;不传则按设备起始数字通道推算 + public HikPreviewSession Create( + string host, + int port, + string userName, + string password, + int channel, + int fps = 25, + int? logicalChannel = null, + string? name = null, + string mode = "stream", + int streamType = 0) + { + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + + // 顺带验证账号密码:密码错在这里就抛,不会等到浏览器拉流时才失败 + var startDigital = _device.GetStartDigitalChannel(host, port, userName, password); + + var logical = logicalChannel is > 0 + ? logicalChannel.Value + : (channel >= startDigital ? channel - startDigital + 1 : channel); + + Trim(); + + var session = new HikPreviewSession + { + Id = Guid.NewGuid().ToString("N")[..16], + Host = host.Trim(), + Port = port, + User = userName, + Password = password, + Channel = channel, + LogicalChannel = logical, + StreamType = streamType == 1 ? 1 : 0, + Fps = Math.Clamp(fps <= 0 ? 25 : fps, 1, 25), + Name = name, + CreatedAt = DateTime.Now, + ExpiresAt = DateTime.Now + SessionTtl, + }; + + // 三种取帧方式(ffmpeg 转码 / SDK 取流解码 / 设备抓帧) + var normalizedMode = (mode ?? string.Empty).Trim().ToLowerInvariant(); + + if (normalizedMode == "ffmpeg") + { + try + { + // RTSP 码流号:通道序号*100 + 码流号(通道 1 主码流 = 101,子码流 = 102) + var streamId = (session.LogicalChannel * 100 + (session.StreamType == 0 ? 1 : 2)).ToString(); + session.FfmpegHandle = _ffmpeg.Open(host, 554, userName, password, streamId, 1280, session.Fps, 6); + session.Mode = "ffmpeg"; + } + catch (HikException ex) + { + AppLog.Write($"ffmpeg 预览失败(通道 {channel}):{ex.Message},降级为设备抓帧"); + session.Mode = "capture"; + session.Warning = $"{ex.Message}已降级为设备抓帧(约 5fps)"; + session.Fps = Math.Min(session.Fps, 5); + } + } + else if (normalizedMode == "capture") + { + session.Mode = "capture"; + session.Fps = Math.Min(session.Fps, 5); + } + else + { + // 默认:SDK 取流 + PlayM4 解码(子码流能稳定 25fps) + try + { + session.StreamHandle = _stream.Open(host, port, userName, password, channel, session.StreamType, name); + session.Mode = "stream"; + } + catch (HikException ex) + { + AppLog.Write($"取流预览失败(通道 {channel}):{ex.Message},降级为抓帧"); + session.Mode = "capture"; + session.Warning = $"取流失败({ex.Message}),已降级为抓帧模式(约 5fps)"; + session.Fps = Math.Min(session.Fps, 5); + } + } + + _sessions[session.Id] = session; + return session; + } + + /// 按 sid 取会话(滑动续期);不存在/已过期返回 null + public HikPreviewSession? Get(string? id) + { + if (string.IsNullOrWhiteSpace(id)) return null; + if (!_sessions.TryGetValue(id, out var session)) return null; + + if (DateTime.Now > session.ExpiresAt) + { + _sessions.TryRemove(id, out _); + return null; + } + + session.Touch(); + return session; + } + + public bool Remove(string? id) + { + if (string.IsNullOrWhiteSpace(id) || !_sessions.TryRemove(id, out var session)) return false; + + if (session.StreamHandle >= 0) _stream.Close(session.StreamHandle); + if (session.FfmpegHandle >= 0) _ffmpeg.Close(session.FfmpegHandle); + return true; + } + + /// 抓一帧(阻塞调用,HTTP 层放线程池里跑) + public byte[] CaptureFrame(HikPreviewSession session) + { + // ffmpeg 转码:取比上次更新的一帧(多个会话共用同一路转码也不会互抢) + if (session.FfmpegHandle >= 0) + { + if (!_ffmpeg.TryGetLatest(session.FfmpegHandle, session.FfmpegVersion, 600, out var frame, out var version)) return Array.Empty(); + session.FfmpegVersion = version; + session.HadFrame = true; + return frame; + } + + // ⚠️ 句柄 0 是**合法**的(NET_DVR_RealPlay_V40 第一路就返回 0),所以用 -1 当“没流” + if (session.StreamHandle >= 0) + { + // 取流模式**不能**再退回去用设备抓图: + // 设备抓图(1080p 约 190ms)会占住 SDK 的网络线程,PlayM4 随即拿不到新帧, + // 于是每帧都退化成抓图、永久卡在 ~7fps(实测踩过)。 + // 拿不到帧就返回空,由 HTTP 层跳过这一轮,等下一帧即可。 + var frame = _stream.GetJpeg(session.StreamHandle, session.HadFrame ? 250 : 2000); + if (frame.Length > 0) session.HadFrame = true; + return frame; + } + + return _device.CaptureJpeg(session.Host, session.Port, session.User, session.Password, session.Channel); + } + + /// 解码画面的分辨率(拿不到返回 0x0) + public (int Width, int Height) SizeOf(HikPreviewSession session) + => session.StreamHandle >= 0 ? _stream.GetSize(session.StreamHandle) : (0, 0); + + /// 当前打开的实时流数(排障用) + public int StreamCount => _stream.Count; + + public int Count => _sessions.Count; + + private void Trim() + { + if (_sessions.Count < MaxSessions) return; + + // 满了就把最久没用的踢掉 + foreach (var stale in _sessions.Values.OrderBy(s => s.LastUsedTicks).Take(_sessions.Count - MaxSessions + 1).ToList()) + { + Remove(stale.Id); + } + } + + private void Sweep() + { + if (_disposed) return; + + var now = DateTime.Now; + foreach (var pair in _sessions) + { + if (now <= pair.Value.ExpiresAt) continue; + + _sessions.TryRemove(pair.Key, out var expired); + if (expired is null) continue; + + if (expired.StreamHandle >= 0) _stream.Close(expired.StreamHandle); + if (expired.FfmpegHandle >= 0) _ffmpeg.Close(expired.FfmpegHandle); + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _sweeper.Dispose(); + _sessions.Clear(); + // 注意:_stream 是共用的(满帧率窗口也在用),由 LocalHttpServer 统一释放 + } +} + +/// 一路预览 +public sealed class HikPreviewSession +{ + public string Id { get; init; } = string.Empty; + public string Host { get; init; } = string.Empty; + public int Port { get; init; } + + // 设备凭据只存在内存里,不外泄到 URL + public string User { get; init; } = string.Empty; + public string Password { get; init; } = string.Empty; + + /// 海康通道号(数字通道从 33 起) + public int Channel { get; init; } + + /// ISAPI/RTSP 用的 1 起通道序号 + public int LogicalChannel { get; init; } + + /// 0-主码流(默认),1-子码流 + public int StreamType { get; init; } = 0; + + /// 预览模式:stream=码流本地解码(25fps);capture=设备抓帧(约 5fps) + public string Mode { get; internal set; } = "capture"; + + /// 降级时的提示 + public string? Warning { get; internal set; } + + /// 实时流句柄(-1 = 未走码流;句柄 0 是合法的第一路) + public int StreamHandle { get; internal set; } = -1; + + /// ffmpeg 转码句柄(-1 = 未用 ffmpeg) + public int FfmpegHandle { get; internal set; } = -1; + + /// 该会话已经取到的 ffmpeg 帧版本(避免两个页面抢同一帧) + public long FfmpegVersion { get; internal set; } + + /// 是否已经成功出过解码帧(用于首帧兑底判断) + public bool HadFrame { get; internal set; } + + /// 抓帧帧率(1~25) + public int Fps { get; internal set; } + + public string? Name { get; init; } + + public DateTime CreatedAt { get; init; } + public DateTime ExpiresAt { get; internal set; } + + public long LastUsedTicks { get; private set; } = Environment.TickCount64; + + /// RTSP 码流 id:主码流 = 通道号 * 100 + 1(通道 1 → 101) + public string StreamId => $"{LogicalChannel}01"; + + /// 标准 RTSP 地址(给 VLC 等外部播放器;浏览器用 MJPEG 那个) + public string RtspUrl => + $"rtsp://{Uri.EscapeDataString(User)}:{Uri.EscapeDataString(Password)}@{Host}:554/Streaming/Channels/{StreamId}"; + + public void Touch() + { + LastUsedTicks = Environment.TickCount64; + ExpiresAt = DateTime.Now + TimeSpan.FromMinutes(30); + } +} diff --git a/desktop/Services/Hik/HikPtz.cs b/desktop/Services/Hik/HikPtz.cs new file mode 100644 index 0000000..548db96 --- /dev/null +++ b/desktop/Services/Hik/HikPtz.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 云台(PTZ)命令码表 —— 与 HCNetSDK.h 保持一致。 +/// +/// 注意: +/// - 方向/变倍/聚焦/光圈都是**连续动作**:先 stop=0 开始,再 stop=1 停止; +/// - 预置点走另一套接口(NET_DVR_PTZPreset_Other); +/// - PAN_AUTO(自动扫描)也是连续动作,需要停止才会结束。 +/// +internal static class HikPtz +{ + // 连续动作 + internal const uint ZoomIn = 11; + internal const uint ZoomOut = 12; + internal const uint FocusNear = 13; + internal const uint FocusFar = 14; + internal const uint IrisOpen = 15; + internal const uint IrisClose = 16; + + internal const uint TiltUp = 21; + internal const uint TiltDown = 22; + internal const uint PanLeft = 23; + internal const uint PanRight = 24; + internal const uint UpLeft = 25; + internal const uint UpRight = 26; + internal const uint DownLeft = 27; + internal const uint DownRight = 28; + internal const uint PanAuto = 29; + + // 灯光 / 雨刷 / 风扇 / 加热 + internal const uint LightPowerOn = 2; + internal const uint WiperPowerOn = 3; + internal const uint FanPowerOn = 4; + internal const uint HeaterPowerOn = 5; + + // 预置点 + internal const uint PresetSet = 8; + internal const uint PresetClear = 9; + internal const uint PresetGoto = 39; + + /// 前端用的名字 → 命令码 + internal static readonly Dictionary Commands = new(StringComparer.OrdinalIgnoreCase) + { + [ "up" ] = TiltUp, + [ "down" ] = TiltDown, + [ "left" ] = PanLeft, + [ "right" ] = PanRight, + [ "up-left" ] = UpLeft, + [ "up-right" ] = UpRight, + [ "down-left" ] = DownLeft, + [ "down-right" ] = DownRight, + [ "auto" ] = PanAuto, + [ "zoom-in" ] = ZoomIn, + [ "zoom-out" ] = ZoomOut, + [ "focus-near" ] = FocusNear, + [ "focus-far" ] = FocusFar, + [ "iris-open" ] = IrisOpen, + [ "iris-close" ] = IrisClose, + [ "light-on" ] = LightPowerOn, + [ "wiper-on" ] = WiperPowerOn, + [ "fan-on" ] = FanPowerOn, + [ "heater-on" ] = HeaterPowerOn, + }; + + /// 预置点动作 → 命令码 + internal static readonly Dictionary PresetActions = new(StringComparer.OrdinalIgnoreCase) + { + [ "set" ] = PresetSet, + [ "goto" ] = PresetGoto, + [ "clear" ] = PresetClear, + }; +} diff --git a/desktop/Services/Hik/HikSdk.cs b/desktop/Services/Hik/HikSdk.cs new file mode 100644 index 0000000..fe2a5ed --- /dev/null +++ b/desktop/Services/Hik/HikSdk.cs @@ -0,0 +1,506 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 海康「设备网络 SDK(HCNetSDK)」的 P/Invoke 声明与初始化。 +/// +/// 只覆盖本项目需要的最小集合:NET_DVR_Login_V40(走 8000 私有协议)、 +/// NET_DVR_GetDVRConfig(读 IP 通道配置)、NET_DVR_Logout。 +/// +/// ⚠️ 关键约束(都踩过): +/// 1. **必须 x64**:desktop 本身是 x64 进程,SDK 只能用 Win64 包(32 位会加载失败); +/// 2. **必须 SetDllDirectory**:HCNetSDK.dll 依赖同目录的 HCCore.dll 与 HCNetSDKCom\ 组件, +/// 不指定目录会 DLL 找不到 → NET_DVR_Init 直接失败; +/// 3. **结构体要按字节对齐**: 的 Marshal.SizeOf 必须为 416, +/// 少一个填充字节密码就会读错位; +/// 4. **密码传明文**:MD5/RSA 是 SDK 与设备内部的挑战应答,应用层传明文(实测传 MD5 必然 err=1)。 +/// +internal static class HikSdk +{ + private const string Dll = "HCNetSDK.dll"; + + /// NET_DVR_GET_IPPARACFG_V40:读取 IP 接入配置(含 IP 通道列表) + internal const uint NET_DVR_GET_IPPARACFG_V40 = 1062; + + /// NET_DVR_GET_TIMECFG:读取设备时间(输出 NET_DVR_TIME,24 字节) + internal const uint NET_DVR_GET_TIMECFG = 118; + + /// NET_DVR_SET_TIMECFG:写入设备时间(输入 NET_DVR_TIME) + internal const uint NET_DVR_SET_TIMECFG = 119; + + /// NET_DVR_GET_NTPCFG:读取 NTP 配置(输出 NET_DVR_NTPPARA,126 字节) + internal const uint NET_DVR_GET_NTPCFG = 224; + + /// NET_DVR_SET_NTPCFG:写入 NTP 配置(输入 NET_DVR_NTPPARA) + internal const uint NET_DVR_SET_NTPCFG = 225; + + /// NET_DVR_GET_DEVICECFG:读取设备参数(用于探活) + internal const uint NET_DVR_GET_DEVICECFG = 100; + + /// + /// NET_DVR_JPEGPARA.wPicSize 常用值 + /// + /// 0xFF = 用当前码流分辨率(部分老固件不支持,会回 err=17/23,调用方需降级重试)。 + /// + internal const byte JpegSizeCurrent = 0xFF; + + internal const byte JpegSize720P = 0x0B; + + internal const byte JpegSizeD1 = 0x02; + + private static readonly object InitSync = new(); + private static bool _initialized; + + /// 实际加载的 SDK 目录(排障用) + internal static string? SdkDirectory { get; private set; } + + /// 设备网络 SDK 的登录参数结构体(Win64 下 sizeof = 416) + [StructLayout(LayoutKind.Sequential)] + internal struct NET_DVR_USER_LOGIN_INFO + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 129)] public byte[] sDeviceAddress; + public byte byUseTransport; + public ushort wPort; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] sUserName; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] sPassword; + public IntPtr cbLoginResult; + public IntPtr pUser; + public int bUseAsynLogin; + public byte byProxyType; + public byte byUseUTCTime; + public byte byLoginMode; + public byte byHttps; + public int iProxyID; + public byte byVerifyMode; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 119)] public byte[] byRes3; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern bool SetDllDirectory(string lpPathName); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + private static extern bool NET_DVR_Init(); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + private static extern bool NET_DVR_Cleanup(); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern uint NET_DVR_GetLastError(); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + private static extern bool NET_DVR_SetConnectTime(uint dwWaitTime, uint dwTryTimes); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + private static extern bool NET_DVR_SetReconnect(uint dwInterval, int bEnableRecon); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + private static extern int NET_DVR_Login_V40(ref NET_DVR_USER_LOGIN_INFO pLoginInfo, IntPtr lpDeviceInfo); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_Logout(int lUserID); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_GetDVRConfig( + int lUserID, + uint dwCommand, + int lChannel, + IntPtr lpOutBuffer, + uint dwOutBufferSize, + out uint lpBytesReturned); + + /// 写设备配置(如 NET_DVR_SET_NTPCFG); 指向命令对应的结构体 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_SetDVRConfig( + int lUserID, + uint dwCommand, + int lChannel, + IntPtr lpInBuffer, + uint dwInBufferSize); + + /// + /// 从设备抓一帧 JPEG(走 8000 私有协议,**不需要** ISAPI/Web 端口) + /// + /// 预览就是靠它按 fps 连续抓帧、再以 MJPEG 推给浏览器;不需要解码器,也不需要转码进程。 + /// lpJpegPara 指向 NET_DVR_JPEGPARA(WORD wPicSize + WORD wPicQuality,4 字节)。 + /// + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_CaptureJPEGPicture_NEW( + int lUserID, + int lChannel, + IntPtr lpJpegPara, + IntPtr sJpegPicBuffer, + uint dwPicSize, + out uint lpSizeReturned); + + /// + /// 实时预览信息(HCNetSDK.h 的 NET_DVR_PREVIEWINFO,x64 下 sizeof = 288) + /// + /// 头文件**没有** #pragma pack,所以按自然对齐声明:hPlayWnd 前有 4 字节填充。 + /// + [StructLayout(LayoutKind.Sequential)] + internal struct NET_DVR_PREVIEWINFO + { + public int lChannel; + public uint dwStreamType; // 0-主码流 1-子码流 2-第三码流 + public uint dwLinkMode; // 0-TCP + public IntPtr hPlayWnd; // 0 = 只要数据、不显示 + public uint bBlocked; + public uint bPassbackRecord; + public byte byPreviewMode; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] byStreamID; + public byte byProtoType; + public byte byRes1; + public byte byVideoCodingType; + public uint dwDisplayBufNum; + public byte byNPQMode; + public byte byRecvMetaData; + public byte byDataType; + public byte byReconnect; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 212)] public byte[] byRes; + } + + /// 实时流数据回调(dwDataType:1-系统头,2-流数据) + internal delegate void RealDataCallback(int lRealHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, IntPtr pUser); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern int NET_DVR_RealPlay_V40( + int lUserID, + ref NET_DVR_PREVIEWINFO lpPreviewInfo, + RealDataCallback? fRealDataCallBack_V30, + IntPtr pUser); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_StopRealPlay(int lRealHandle); + + /// + /// 云台连续动作(不依赖预览句柄,直接用登录的 UserID + 通道号) + /// + /// :0=开始,1=停止。云台必须“开始 + 停止”成对调用,否则会一直转。 + /// + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_PTZControlWithSpeed_Other( + int lUserID, + int lChannel, + uint dwPTZCommand, + uint dwStop, + uint dwSpeed); + + /// 预置点:设置 / 调用 / 删除(dwPTZPresetCmd 见 ) + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_PTZPreset_Other( + int lUserID, + int lChannel, + uint dwPTZPresetCmd, + uint dwPresetIndex); + + // ==================== 按时间下载录像(走 8000 私有协议) ==================== + + /// HCNetSDK 的 NET_DVR_TIME(sizeof = 24) + [StructLayout(LayoutKind.Sequential)] + internal struct NET_DVR_TIME + { + public uint dwYear; + public uint dwMonth; + public uint dwDay; + public uint dwHour; + public uint dwMinute; + public uint dwSecond; + } + + /// + /// HCNetSDK 的 NET_DVR_NTPPARA(sizeof = 126) + /// + /// + /// BYTE sNTPServer[64]; // 域名/IP,ASCII + /// WORD wInterval; // 同步间隔(分钟) + /// BYTE byEnable; // 0-关闭 1-启用 + /// BYTE byRes[59]; + /// + /// + [StructLayout(LayoutKind.Sequential)] + internal struct NET_DVR_NTPPARA + { + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] sNTPServer; + public ushort wInterval; + public byte byEnable; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 59)] public byte[] byRes; + } + + /// + /// HCNetSDK 的 NET_DVR_PLAYCOND(sizeof = 356) + /// + /// + /// DWORD dwChannel; NET_DVR_TIME struStartTime; NET_DVR_TIME struStopTime; + /// BYTE byStreamType; BYTE byDownload; BYTE byOptimalStreamType; BYTE byRes2[301]; + /// + /// + [StructLayout(LayoutKind.Sequential)] + internal struct NET_DVR_PLAYCOND + { + public uint dwChannel; + public NET_DVR_TIME struStartTime; + public NET_DVR_TIME struStopTime; + public byte byStreamType; // 0-主码流 1-子码流 + public byte byDownload; // 0-下载(存文件)1-回放(需解码器) + public byte byOptimalStreamType; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 301)] public byte[] byRes2; + } + + /// + /// 按时间把录像**下载到文件**(8000 私有协议,不需要 554 / 不需要解码器) + /// + /// 返回值是文件句柄(>0 成功,-1 失败用 查原因)。 + /// 下载出来的是设备原始封装(PS),要 mp4 得再用 ffmpeg 转封装。 + /// + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern int NET_DVR_GetFileByTime_V40( + int lUserID, + [MarshalAs(UnmanagedType.LPStr)] string sSavedFileName, + ref NET_DVR_PLAYCOND pDownloadCond); + + /// 下载进度(0~100,-1 表示失败) + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern int NET_DVR_GetDownloadPos(int lFileHandle); + + /// 停止下载并释放句柄 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_StopGetFile(int lFileHandle); + + // ==================== 按时间**回放取流**(8000 私有协议,全速推送) ==================== + + /// NET_DVR_PlayBackControl 控制码 + internal const uint PlayStart = 1; + + internal const uint PlayStop = 2; + + internal const uint PlayPause = 3; + + internal const uint PlayFast = 5; + + internal const uint PlayNormal = 7; + + /// 回放数据回调(:1 系统头,2 流数据) + internal delegate void PlayDataCallback(int lPlayHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, + IntPtr pUser); + + /// + /// 按时间打开回放(通道号用**海康通道号**,如 34) + /// + /// ⚠️ 实测:这条接口是**全速推送**的,不按实时速率 —— 本项目设备 2 分钟主码流素材 + /// 约 7 秒就推完(≈14 MB/s,17 倍速),所以下载录像不用再 `PlayFast`。 + /// 相比之下 NET_DVR_GetFileByTime* 在这台固件上直接不工作(err 17 / 0 字节)。 + /// + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern int NET_DVR_PlayBackByTime( + int lUserID, + int lChannel, + ref NET_DVR_TIME lpStartTime, + ref NET_DVR_TIME lpStopTime, + IntPtr hWnd); + + /// 回放数据回调( 传 0 时必须设,否则没有数据) + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_SetPlayDataCallBack( + int lPlayHandle, + PlayDataCallback? fPlayDataCallBack, + IntPtr pUser); + + /// 回放控制(开始 / 停止 / 暂停 / 快放…), 见常量 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_PlayBackControl( + int lPlayHandle, + uint dwControlCode, + uint dwInValue, + IntPtr lpOutValue); + + /// 停止回放并释放句柄 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool NET_DVR_StopPlayBack(int lPlayHandle); + + /// 回放进度(0~100;-1 失败)。判「推完」用它,比数字节稳 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern int NET_DVR_GetPlayBackPos(int lPlayHandle); + + /// 初始化 SDK(幂等)。找不到 HCNetSDK.dll 时抛 + internal static void EnsureInitialized() + { + lock (InitSync) + { + if (_initialized) return; + + var dir = ResolveSdkDirectory() + ?? throw new HikException(uint.MaxValue, + "未找到 HCNetSDK.dll:请把海康 Win64 SDK 的「库文件」目录放到程序目录下的 native\\HCNetSDK\\," + + "或设置环境变量 YUNCANG_HIKSDK_DIR 指向该目录"); + + SetDllDirectory(dir); + + // 组件(HCNetSDKCom)里的 DLL 由 HCCore 自行 LoadLibrary,补齐 PATH 更稳 + var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; + if (path.IndexOf(dir, StringComparison.OrdinalIgnoreCase) < 0) + { + Environment.SetEnvironmentVariable("PATH", dir + Path.PathSeparator + path); + } + + if (!NET_DVR_Init()) + { + throw new HikException(NET_DVR_GetLastError(), "HCNetSDK 初始化失败(NET_DVR_Init)"); + } + + // 3 秒连接超时、2 次重试;断链后 5 秒重连(SDK 默认 30 秒,这里更快恢复) + NET_DVR_SetConnectTime(3000, 2); + NET_DVR_SetReconnect(5000, 1); + + SdkDirectory = dir; + _initialized = true; + AppLog.Write($"HCNetSDK 已初始化:{dir}"); + } + } + + /// 停用 SDK(进程退出时调用) + internal static void Shutdown() + { + lock (InitSync) + { + if (!_initialized) return; + try { NET_DVR_Cleanup(); } catch { /* 退出阶段忽略 */ } + _initialized = false; + } + } + + /// 登录设备,返回 UserID(>=0);失败抛异常。调用方负责 FreeHGlobal(deviceInfo) + internal static int Login(string host, ushort port, string userName, string password, out IntPtr deviceInfo) + { + EnsureInitialized(); + + var info = new NET_DVR_USER_LOGIN_INFO + { + sDeviceAddress = new byte[129], + sUserName = new byte[64], + sPassword = new byte[64], + byRes3 = new byte[119], + byUseTransport = 0, + wPort = port, + bUseAsynLogin = 0, + byProxyType = 0, + byUseUTCTime = 0, + byLoginMode = 0, // 0 = 私有协议(走 8000);1 = ISAPI + byHttps = 0, // 0 = 不套 TLS + iProxyID = -1, // 不使用代理时必须为 -1(填 0 新固件会报参数错误 17,实测) + byVerifyMode = 0, + }; + + // 用 Latin1 保证 1 字符 = 1 字节,不会像 UTF-8 那样把非 ASCII 撑成多字节错位 + WriteFixed(info.sDeviceAddress, host); + WriteFixed(info.sUserName, userName); + WriteFixed(info.sPassword, password); + + // 设备信息结构体(NET_DVR_DEVICEINFO_V40)比较大,给足空间;给小了会报参数错误 17 + const int infoSize = 4096; + deviceInfo = Marshal.AllocHGlobal(infoSize); + Marshal.Copy(new byte[infoSize], 0, deviceInfo, infoSize); + + var userId = NET_DVR_Login_V40(ref info, deviceInfo); + if (userId < 0) + { + var err = NET_DVR_GetLastError(); + Marshal.FreeHGlobal(deviceInfo); + deviceInfo = IntPtr.Zero; + throw new HikException(err, $"登录设备失败:{DescribeError(err)}"); + } + + return userId; + } + + private static void WriteFixed(byte[] buffer, string? value) + { + var bytes = Encoding.Latin1.GetBytes(value ?? string.Empty); + var count = Math.Min(bytes.Length, buffer.Length - 1); + Array.Copy(bytes, 0, buffer, 0, count); + } + + private static string? ResolveSdkDirectory() + { + var candidates = new[] + { + Environment.GetEnvironmentVariable("YUNCANG_HIKSDK_DIR"), + Path.Combine(AppContext.BaseDirectory, "native", "HCNetSDK"), + Path.Combine(AppContext.BaseDirectory, "native"), + // 兜底:有些部署(历史安装包)把运行库直接放在 exe 同级的 HCNetSDK 目录 + Path.Combine(AppContext.BaseDirectory, "HCNetSDK"), + AppContext.BaseDirectory, + }; + + foreach (var dir in candidates) + { + if (string.IsNullOrWhiteSpace(dir)) continue; + try + { + if (File.Exists(Path.Combine(dir, Dll))) return Path.GetFullPath(dir); + } + catch + { + // 路径非法就跳过 + } + } + + return null; + } + + /// 常见错误码的中文描述(对照 HCNetSDK.h) + internal static string DescribeError(uint code) => code switch + { + 0 => "成功", + 1 => "用户名或密码错误(密码必须传明文)", + 2 => "权限不足", + 3 => "SDK 未初始化", + 4 => "通道号错误", + 5 => "连接到设备的客户端个数超过最大", + 6 => "设备版本不匹配", + 7 => "连接设备失败(IP/端口不通或设备未开机)", + 8 => "网络发送失败", + 9 => "网络接收失败", + 10 => "网络接收超时", + 11 => "网络数据错误", + 12 => "调用次序错误", + 13 => "无此权限", + 14 => "命令执行超时", + 15 => "串口号错误", + 16 => "报警端口错误", + 17 => "参数错误(检查登录参数,如代理序号 / 结构体大小)", + 18 => "通道状态异常", + 19 => "没有硬盘", + 20 => "硬盘号错误", + 21 => "硬盘已满", + 22 => "硬盘出错", + 23 => "设备不支持", + 24 => "设备忙", + 25 => "设备修改不成功", + 26 => "密码格式不正确", + 27 => "硬盘正在格式化", + 47 => "用户不存在", + 72 => "账号被锁定", + 73 => "账号已过期", + 74 => "账号已禁用", + 76 => "该用户有权限的设备数量超过最大值", + 251 => "密码为风险密码(设备拒绝)", + 1231 => "初始密码未修改,功能受限", + _ => $"未知错误({code})", + }; +} + +/// 海康 SDK 调用异常( 为 NET_DVR_GetLastError 的原值) +public sealed class HikException : Exception +{ + public HikException(uint errorCode, string message) : base(message) + { + ErrorCode = errorCode; + } + + /// NET_DVR_GetLastError 返回码(非 SDK 错误时用 0xFFFFFFFF) + public uint ErrorCode { get; } +} diff --git a/desktop/Services/Hik/HikStreamService.cs b/desktop/Services/Hik/HikStreamService.cs new file mode 100644 index 0000000..18c7f8a --- /dev/null +++ b/desktop/Services/Hik/HikStreamService.cs @@ -0,0 +1,366 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Threading; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// 取实时码流 + 本地解码(25fps 的预览就是靠它)。 +/// +/// 链路:NET_DVR_RealPlay_V40(8000 私有协议,TCP)→ 回调收到 PS 流 → +/// PlayM4_InputData 解码 → PlayM4_GetJPEG 取当前帧交给浏览器。 +/// +/// 与「抓帧」模式的差别(实测): +/// - 抓帧:设备端编码 JPEG,**上限约 5fps**(1080p 每帧 ~190ms),只适合低频快照; +/// - 解码:一路码流持续解码,可稳稳跑到设备实际帧率(本项目 25fps), +/// 代价是本机多一个解码线程、设备多一路预览连接。 +/// +/// 子码流( = 1)默认,因为预览流畅度优先、带宽小; +/// 要看细节可以传 0 走主码流。 +/// +public sealed class HikStreamService : IDisposable +{ + /// PlayM4 缓冲区(2MB,够 1080p 一段 GOP) + private const uint BufferPoolSize = 2 * 1024 * 1024; + + /// 取帧用的 JPEG 缓冲区(4MB) + private const uint JpegBufferSize = 4 * 1024 * 1024; + + private readonly HikDeviceService _device; + private readonly ConcurrentDictionary _streams = new(); + /// 复用键(host:port|user|channel|streamType|模式)→ 句柄 + private readonly Dictionary _byKey = new(StringComparer.OrdinalIgnoreCase); + /// 串行化 Open/Close,避免两个浏览器同时申请同一通道时各开一路 + private readonly object _gate = new(); + private bool _disposed; + + public HikStreamService(HikDeviceService device) + { + _device = device; + } + + /// 当前打开的码流数(排障用) + public int Count => _streams.Count; + + /// + /// 打开一路实时流,返回句柄(NET_DVR_RealPlay_V40 的返回值) + /// + /// 0-主码流,1-子码流 + /// + /// 渲染窗口句柄:IntPtr.Zero = 只解码(配合 推给浏览器); + /// 传窗口句柄 = 解码器直接画到窗口,**满帧率(设备 25fps)且不经过 JPEG 编码**。 + /// + public int Open(string host, int port, string userName, string password, int channel, int streamType = 0, string? name = null, IntPtr renderWnd = default) + { + if (channel <= 0) throw new ArgumentException("channel 必须是正整数"); + + var finalStreamType = streamType == 1 ? 1 : 0; + var mode = renderWnd == IntPtr.Zero ? "decode" : "window"; + var key = $"{host.Trim().ToLowerInvariant()}:{port}|{userName}|{channel}|{finalStreamType}|{mode}"; + + lock (_gate) + { + // 同一通道 + 同一码流已经在拉:直接复用,RefCount+1。 + // 不这么做的话,每开一次预览就多一路 realplay,设备/摄像头很快到达并发上限, + // 新开的那一路拿到的是“没有数据的流”,页面就卡在“画面中断”(实测踩过)。 + if (renderWnd == IntPtr.Zero && _byKey.TryGetValue(key, out var existing) && _streams.TryGetValue(existing, out var alive)) + { + alive.RefCount++; + alive.Touch(); + AppLog.Write($"实时流复用:{host} 通道 {channel}({(finalStreamType == 0 ? "主码流" : "子码流")})handle={existing} 引用数={alive.RefCount}"); + return existing; + } + + var handle = CreateStream(host, port, userName, password, channel, finalStreamType, name, renderWnd, key); + return handle; + } + } + + private int CreateStream(string host, int port, string userName, string password, int channel, int finalStreamType, string? name, IntPtr renderWnd, string key) + { + // 复用登录会话(不重复登录设备),密码错在这里就会抛 + var userId = _device.EnsureUser(host, port, userName, password); + + var session = new StreamSession(); + if (!PlayM4.PlayM4_GetPort(out var playPort)) + { + throw new HikException(HikSdk.NET_DVR_GetLastError(), "PlayM4 取解码端口失败(PlayCtrl.dll 是否随 SDK 一起安装?)"); + } + + session.PlayPort = playPort; + session.Name = name; + session.RenderWnd = renderWnd; + session.Key = key; + PlayM4.PlayM4_SetStreamOpenMode(playPort, PlayM4.STREAME_REALTIME); + + var info = new HikSdk.NET_DVR_PREVIEWINFO + { + lChannel = channel, + dwStreamType = (uint)finalStreamType, + dwLinkMode = 0, // TCP + hPlayWnd = IntPtr.Zero, // 只要数据,不由 SDK 画 + bBlocked = 0, + bPassbackRecord = 0, + byPreviewMode = 0, + byStreamID = new byte[32], + byProtoType = 0, + byVideoCodingType = 0, + dwDisplayBufNum = 0, + byRes = new byte[212], + }; + + session.Callback = session.OnRealData; // 必须持有引用,否则被 GC 后回调崩 + var handle = HikSdk.NET_DVR_RealPlay_V40(userId, ref info, session.Callback, IntPtr.Zero); + if (handle < 0) + { + var err = HikSdk.NET_DVR_GetLastError(); + PlayM4.PlayM4_FreePort(playPort); + throw new HikException(err, $"打开实时流失败:{HikSdk.DescribeError(err)}"); + } + + session.Handle = handle; + session.Host = host; + session.Channel = channel; + session.StreamType = finalStreamType; + session.RefCount = 1; + + _streams[handle] = session; + if (renderWnd == IntPtr.Zero) _byKey[key] = handle; + + AppLog.Write($"实时流已打开:{host} 通道 {channel}({(finalStreamType == 0 ? "主码流" : "子码流")},{(renderWnd == IntPtr.Zero ? "仅解码" : "窗口渲染")})handle={handle} port={playPort}"); + return handle; + } + + /// + /// 取当前帧 JPEG;尚无解码帧时返回空数组(调用方稍后重试即可) + /// + public byte[] GetJpeg(int handle, int timeoutMs = 800) + { + if (!_streams.TryGetValue(handle, out var session)) return Array.Empty(); + + var deadline = Environment.TickCount64 + Math.Max(timeoutMs, 0); + while (Environment.TickCount64 <= deadline) + { + if (TryReadJpeg(session, out var frame) && frame.Length > 0) return frame; + + if (_disposed) break; + Thread.Sleep(15); + } + + return Array.Empty(); + } + + private static bool TryReadJpeg(StreamSession session, out byte[] frame) + { + frame = Array.Empty(); + + var buffer = Marshal.AllocHGlobal((int)JpegBufferSize); + try + { + if (!PlayM4.PlayM4_GetJPEG(session.PlayPort, buffer, JpegBufferSize, out var size) || size == 0) + { + return false; + } + + frame = new byte[size]; + Marshal.Copy(buffer, frame, 0, frame.Length); + return true; + } + catch + { + return false; + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + + /// 解出来的画面尺寸(宽 x 高),拿不到返回 (0,0) + public (int Width, int Height) GetSize(int handle) + { + if (!_streams.TryGetValue(handle, out var session)) return (0, 0); + return PlayM4.PlayM4_GetPictureSize(session.PlayPort, out var width, out var height) ? (width, height) : (0, 0); + } + + /// 关闭一路实时流(引用计数减到 0 才真的停) + public bool Close(int handle) + { + lock (_gate) + { + if (!_streams.TryGetValue(handle, out var session)) return false; + + session.RefCount--; + if (session.RefCount > 0) + { + AppLog.Write($"实时流释放引用:handle={handle} 剩余={session.RefCount}"); + return true; + } + + _streams.TryRemove(handle, out _); + if (!string.IsNullOrEmpty(session.Key) && _byKey.TryGetValue(session.Key, out var mapped) && mapped == handle) + { + _byKey.Remove(session.Key); + } + + try + { + HikSdk.NET_DVR_StopRealPlay(handle); + } + catch + { + // 退出阶段忽略 + } + + try + { + PlayM4.PlayM4_Stop(session.PlayPort); + PlayM4.PlayM4_CloseStream(session.PlayPort); + PlayM4.PlayM4_FreePort(session.PlayPort); + } + catch + { + // 忽略 + } + + AppLog.Write($"实时流已关闭:{session.Host} 通道 {session.Channel} handle={handle}"); + return true; + } + } + + public void CloseAll() + { + foreach (var handle in _streams.Keys.ToList()) + { + Close(handle); + } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + CloseAll(); + } + + /// 一路实时流的状态(回调线程与 HTTP 线程共用) + private sealed class StreamSession + { + private readonly object _sync = new(); + private byte[]? _systemHeader; + private bool _opened; + private bool _openFailed; + private bool _loggedFirstPacket; + + public int Handle { get; set; } + public int PlayPort { get; set; } + public string Host { get; set; } = string.Empty; + public int Channel { get; set; } + public int StreamType { get; set; } + + /// 复用键(window 模式不参与复用,Key 为空) + public string Key { get; set; } = string.Empty; + + /// 有多少个预览会话在用它 + public int RefCount { get; set; } + + /// 最近使用时间(配速/排障用) + public long LastUsedTicks { get; private set; } = Environment.TickCount64; + + public void Touch() => LastUsedTicks = Environment.TickCount64; + + /// 渲染窗口(0 = 只解码不出图) + public IntPtr RenderWnd { get; set; } + + public string? Name { get; set; } + + /// 回调委托(必须由本对象持有,避免被 GC 回收) + public HikSdk.RealDataCallback? Callback { get; set; } + + /// SDK 网络线程回调:拿到 PS 流喂给 PlayM4 + public void OnRealData(int lRealHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, IntPtr pUser) + { + try + { + // 首次回调记一笔(排障:主码流打不开时能看出是没数据还是没解码) + if (!_loggedFirstPacket) + { + _loggedFirstPacket = true; + AppLog.Write($"实时流首包:通道 {Channel}({(StreamType == 0 ? "主码流" : "子码流")})type={dwDataType} size={dwBufSize}"); + } + + switch (dwDataType) + { + case 1: // 系统头(PS 头),打开流时一起交给解码器 + lock (_sync) + { + _systemHeader = new byte[dwBufSize]; + Marshal.Copy(pBuffer, _systemHeader, 0, (int)dwBufSize); + } + return; + + case 2: // 流数据 + break; + + default: + return; + } + + if (!EnsureOpened()) return; + + // 直接指向 SDK 的缓冲区,解码器会拷走 + PlayM4.PlayM4_InputData(PlayPort, pBuffer, dwBufSize); + } + catch (Exception ex) + { + if (!_openFailed) + { + _openFailed = true; + AppLog.Write($"实时流解码失败(通道 {Channel}):{ex.Message}"); + } + } + } + + private bool EnsureOpened() + { + if (_opened) return true; + + lock (_sync) + { + if (_opened) return true; + + var header = _systemHeader ?? Array.Empty(); + var headerPtr = IntPtr.Zero; + + try + { + if (header.Length > 0) + { + headerPtr = Marshal.AllocHGlobal(header.Length); + Marshal.Copy(header, 0, headerPtr, header.Length); + } + + // 没拿到系统头也要开(PS 流的第一包自带头) + if (!PlayM4.PlayM4_OpenStream(PlayPort, headerPtr, (uint)header.Length, BufferPoolSize)) + { + _openFailed = true; + AppLog.Write($"PlayM4 打开流失败:通道 {Channel} port={PlayPort} 头长度={header.Length}"); + return false; + } + + PlayM4.PlayM4_Play(PlayPort, RenderWnd); // 0 = 只解码不显示;有句柄 = 直接画到窗口(满帧) + _opened = true; + AppLog.Write($"PlayM4 已开流:通道 {Channel} port={PlayPort} 头长度={header.Length} 模式={(RenderWnd == IntPtr.Zero ? "仅解码" : "窗口")}"); + return true; + } + finally + { + if (headerPtr != IntPtr.Zero) Marshal.FreeHGlobal(headerPtr); + } + } + } + } +} diff --git a/desktop/Services/Hik/PlayM4.cs b/desktop/Services/Hik/PlayM4.cs new file mode 100644 index 0000000..a8d6f3c --- /dev/null +++ b/desktop/Services/Hik/PlayM4.cs @@ -0,0 +1,56 @@ +using System; +using System.Runtime.InteropServices; + +namespace YuncangTrace.LocalService.Services.Hik; + +/// +/// PlayCtrl(PlayM4)解码库的 P/Invoke。 +/// +/// 用它的理由:设备侧「抓 JPEG」只有约 5fps(NET_DVR_CaptureJPEGPicture_NEW 实测, +/// 是设备在编码 JPEG,很慢)。要 **25fps** 只能拿真正的码流: +/// NET_DVR_RealPlay_V40 收到 PS 流 → PlayM4_InputData 喂给解码器 → +/// PlayM4_GetJPEG 取当前解码帧(本地编码,快得多)。 +/// +/// DLL 与 HCNetSDK.dll 同目录(native\HCNetSDK\PlayCtrl.dll); +/// 里已经 SetDllDirectory,这里直接按名字加载即可。 +/// +internal static class PlayM4 +{ + private const string Dll = "PlayCtrl.dll"; + + /// 实时流(不追赶时间轴) + internal const uint STREAME_REALTIME = 0; + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_GetPort(out int nPort); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_FreePort(int nPort); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_SetStreamOpenMode(int nPort, uint nMode); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_OpenStream(int nPort, IntPtr pFileHeadBuf, uint nSize, uint nBufPoolSize); + + /// 开始播放; 传 0 表示只解码不显示 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_Play(int nPort, IntPtr hWnd); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_Stop(int nPort); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_CloseStream(int nPort); + + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_InputData(int nPort, IntPtr pBuf, uint nSize); + + /// 取当前解码帧的 JPEG(本地编码,比设备端抓图快得多) + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_GetJPEG(int nPort, IntPtr pJpeg, uint nBufSize, out uint pJpegSize); + + /// 当前画面尺寸 + [DllImport(Dll, CallingConvention = CallingConvention.StdCall)] + internal static extern bool PlayM4_GetPictureSize(int nPort, out int pWidth, out int pHeight); +} diff --git a/desktop/Services/PlaybackDownloadService.cs b/desktop/Services/PlaybackDownloadService.cs new file mode 100644 index 0000000..c2fad03 --- /dev/null +++ b/desktop/Services/PlaybackDownloadService.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using YuncangTrace.LocalService.Services.Hik; + +namespace YuncangTrace.LocalService.Services; + +/// 下载结果(HTTP 接口与桌面端共用) +/// 最终存放目录(`{录像根}/yyyy/MM/dd`) +/// 合并后的成片路径(单路时就是那一路的路径) +/// 各路段文件(合并失败时才有多个,且都已搬到用户目录) +/// 非致命问题(某路没下到等) +public sealed record PlaybackDownloadResult( + string Folder, + string? Merged, + IReadOnlyList Segments, + IReadOnlyList Warnings); + +/// +/// 「按运单下载录像」的完整流程(**与界面无关**,桌面端和网页查件都走它) +/// +/// 1. `pack-query` 拿到回放计划(扫码当时的工作台快照); +/// 2. 逐路下载到 **临时目录**(并发 2 路,8000 全速拉流优先、失败回落 RTSP); +/// 3. 多路按工作台画布布局**自动合并**成一个视频; +/// 4. 成片放到 `{录像根}/年/月/日/`,删掉临时片段。 +/// +/// 关键点:**录像存储路径是每台机器自己的设置**,跟"是不是设备服务器"无关 —— +/// 任何装了本机软件的电脑,查件后都能下载到自己配的目录里。 +/// +public sealed class PlaybackDownloadService +{ + /// 同时下载几路(给 NVR 回放连接留余量) + private const int MaxParallel = 2; + + private readonly OrderQueryService _query; + private readonly HikPlaybackService _playback; + private readonly Func _api; + private readonly Func _subjectId; + private readonly Func _token; + private readonly Func _root; + + public PlaybackDownloadService( + OrderQueryService query, + HikPlaybackService playback, + Func apiProvider, + Func subjectIdProvider, + Func tokenProvider, + Func videoRootProvider) + { + _query = query; + _playback = playback; + _api = apiProvider; + _subjectId = subjectIdProvider; + _token = tokenProvider; + _root = videoRootProvider; + } + + /// + /// 按运单号下载这段时间的录像(多路自动合并) + /// + /// 查询失败 / 没有可下载的流(message 可直接给用户看) + public async Task DownloadAsync(string code, IProgress? progress = null, + CancellationToken ct = default) + { + var outcome = await _query.QueryAsync(code, ct).ConfigureAwait(false); + if (!outcome.Http.Ok || outcome.Query is null) + { + throw new InvalidOperationException(outcome.Http.Message); + } + + var query = outcome.Query; + if (!query.Playback || query.Records.Count == 0) + { + throw new InvalidOperationException("这个运单没有可下载的回放(扫码时该通道没绑定工作台)"); + } + + var streams = query.Records.SelectMany(item => item.Streams).ToList(); + if (streams.Count == 0) + { + throw new InvalidOperationException("工作台没有绑定摄像头,没有可下载的流"); + } + + var scanTime = query.Records[0].ScanTime.LocalDateTime; + var folder = VideoStorage.FolderFor(_root(), scanTime); + Directory.CreateDirectory(folder); + + var stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var workDir = Path.Combine(Path.GetTempPath(), "YuncangTrace", "playback", + $"{Sanitize(code)}_{stamp}"); + Directory.CreateDirectory(workDir); + + var warnings = new List(); + var saved = new string?[streams.Count]; + var gate = new SemaphoreSlim(MaxParallel); + var credentials = new Dictionary(); + var credentialGate = new SemaphoreSlim(1, 1); + + try + { + var tasks = new List(); + for (var i = 0; i < streams.Count; i++) + { + var slot = i; + var stream = streams[i]; + tasks.Add(Task.Run(async () => + { + await gate.WaitAsync(ct).ConfigureAwait(false); + try + { + progress?.Report($"[{slot + 1}/{streams.Count}] {stream.DisplayName} 连接中…"); + + var credential = await CredentialAsync(stream.NvrId, credentials, credentialGate, ct) + .ConfigureAwait(false); + + var name = $"{Sanitize(code)}_{stream.CameraId}_{stream.CameraName}" + + $"_{stream.StartTime.ToLocalTime():yyyyMMdd_HHmmss}.mp4"; + var path = Path.Combine(workDir, name); + + var file = await _playback.DownloadAsync(credential.Host, credential.Port, + credential.Username, credential.Password, stream.ChannelNo, + stream.StartTime, stream.EndTime, path, + new Progress(p => + progress?.Report($"[{slot + 1}/{streams.Count}] {stream.DisplayName} {p.Message}")), + ct).ConfigureAwait(false); + + saved[slot] = file; + progress?.Report($"[{slot + 1}/{streams.Count}] {stream.DisplayName} ✓ 完成"); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + warnings.Add($"{stream.DisplayName}:{ex.Message}"); + progress?.Report($"[{slot + 1}/{streams.Count}] {stream.DisplayName} ✗ {ex.Message}"); + } + finally + { + gate.Release(); + } + }, ct)); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); + + var parts = new List<(PackStream Stream, string Path)>(); + for (var i = 0; i < streams.Count; i++) + { + if (saved[i] is { } file) parts.Add((streams[i], file)); + } + + if (parts.Count == 0) + { + throw new InvalidOperationException( + "所有通道都没能下载成功:" + string.Join(";", warnings)); + } + + if (parts.Count == 1) + { + var target = Path.Combine(folder, Path.GetFileName(parts[0].Path)); + if (File.Exists(target)) File.Delete(target); + File.Move(parts[0].Path, target); + progress?.Report($"已保存:{target}"); + return new PlaybackDownloadResult(folder, target, new[] { target }, warnings); + } + + var merged = Path.Combine(folder, + $"{Sanitize(code)}_合并_{parts[0].Stream.StartTime.ToLocalTime():yyyyMMdd_HHmmss}.mp4"); + + progress?.Report("正在按工作台布局合并…"); + try + { + await _playback.ComposeAsync( + parts.Select(item => item.Path).ToList(), + parts.Select(item => item.Stream).ToList(), + merged, + new Progress(p => progress?.Report(p.Message)), + ct).ConfigureAwait(false); + + progress?.Report($"已合并:{merged}"); + return new PlaybackDownloadResult(folder, merged, new[] { merged }, warnings); + } + catch (Exception ex) + { + // 合并失败不丢数据:把各路段搬到用户目录 + warnings.Add($"合并失败:{ex.Message}"); + var moved = new List(); + foreach (var (_, path) in parts) + { + var target = Path.Combine(folder, Path.GetFileName(path)); + if (File.Exists(target)) File.Delete(target); + File.Move(path, target); + moved.Add(target); + } + return new PlaybackDownloadResult(folder, null, moved, warnings); + } + } + finally + { + TryDeleteDirectory(workDir); + } + } + + private async Task CredentialAsync(int nvrId, Dictionary cache, + SemaphoreSlim gate, CancellationToken ct) + { + await gate.WaitAsync(ct).ConfigureAwait(false); + try + { + if (cache.TryGetValue(nvrId, out var cached)) return cached; + + var api = _api() ?? throw new InvalidOperationException("本机软件未登录"); + var token = _token() ?? throw new InvalidOperationException("本机软件未登录"); + + var credential = await api.NvrCredentialAsync(token, _subjectId(), nvrId, ct).ConfigureAwait(false); + if (string.IsNullOrEmpty(credential.Password)) + { + throw new InvalidOperationException( + $"录像机「{credential.Name}」没有保存密码,请到网页端「录像机」页补填"); + } + + cache[nvrId] = credential; + return credential; + } + finally + { + gate.Release(); + } + } + + private static string Sanitize(string text) + { + var invalid = Path.GetInvalidFileNameChars(); + return new string(text.Select(ch => invalid.Contains(ch) ? '_' : ch).ToArray()); + } + + private static void TryDeleteDirectory(string dir) + { + try + { + if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); + } + catch (Exception ex) + { + AppLog.Write($"[playback] 清理临时目录失败({dir}):{ex.Message}"); + } + } +} diff --git a/desktop/Services/VideoStorage.cs b/desktop/Services/VideoStorage.cs new file mode 100644 index 0000000..ae52ee8 --- /dev/null +++ b/desktop/Services/VideoStorage.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 录像存储目录 +/// +/// 约定: +/// - 默认根目录 ~/packVideo(用户目录下,权限够、不会被清理工具删); +/// - 按 **扫码日期** 分目录:{根}/2026/03/11/,成片直接放在里面; +/// - 用户可以在「工具 → 设置录像存储路径」改根目录;切换时**把已有文件一起搬过去**。 +/// +public static class VideoStorage +{ + /// 默认根目录:`%USERPROFILE%\packVideo` + public static string DefaultRoot { get; } = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "packVideo"); + + /// 某个时间点对应的目录:`{根}/yyyy/MM/dd` + public static string FolderFor(string root, DateTime time) + => Path.Combine(root, time.ToString("yyyy"), time.ToString("MM"), time.ToString("dd")); + + /// + /// 把 下的所有文件搬到 (保留相对目录结构) + /// + /// 切换存储路径时用:只搬文件,搬完把**空的**旧目录删掉(旧目录里如果还有别的东西就留着, + /// 防止误删用户自己放进去的文件)。 + /// + /// 移动的文件数 / 出错信息(出错不抛,界面给提示) + public static (int Moved, string? Error) MoveAll(string from, string to, IProgress? progress = null) + { + try + { + if (!Directory.Exists(from)) return (0, null); + + var source = Path.GetFullPath(from).TrimEnd(Path.DirectorySeparatorChar); + var target = Path.GetFullPath(to).TrimEnd(Path.DirectorySeparatorChar); + if (string.Equals(source, target, StringComparison.OrdinalIgnoreCase)) return (0, null); + + Directory.CreateDirectory(target); + + var moved = 0; + foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(source, file); + var destination = Path.Combine(target, relative); + + var folder = Path.GetDirectoryName(destination); + if (!string.IsNullOrEmpty(folder)) Directory.CreateDirectory(folder); + + if (File.Exists(destination)) File.Delete(destination); + File.Move(file, destination); + + moved++; + if (moved % 20 == 0) progress?.Report($"已移动 {moved} 个文件…"); + } + + DeleteEmptyDirectories(source); + + // 旧根目录空了就删掉(还有东西就保留) + try + { + if (Directory.Exists(source) && !Directory.EnumerateFileSystemEntries(source).Any()) + { + Directory.Delete(source, recursive: false); + } + } + catch + { + // 删不掉也无所谓 + } + + return (moved, null); + } + catch (Exception ex) + { + return (0, ex.Message); + } + } + + /// 自底向上删空目录(不动有文件的目录) + private static void DeleteEmptyDirectories(string root) + { + var directories = Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories) + .OrderByDescending(item => item.Length) + .ToList(); + + foreach (var directory in directories) + { + try + { + if (!Directory.EnumerateFileSystemEntries(directory).Any()) + { + Directory.Delete(directory, recursive: false); + } + } + catch + { + // 删不掉跳过 + } + } + } +} diff --git a/desktop/Views/PlaybackPreviewWindow.xaml b/desktop/Views/PlaybackPreviewWindow.xaml new file mode 100644 index 0000000..0729152 --- /dev/null +++ b/desktop/Views/PlaybackPreviewWindow.xaml @@ -0,0 +1,18 @@ + + + +