feat(desktop): 海康 NVR/摄像机预览、录像回放下载与内置 HCNetSDK

This commit is contained in:
liufumingren 2026-10-19 22:04:16 +08:00
parent cb511f33ae
commit cb504608a1
48 changed files with 4363 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@ -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;
/// <summary>
/// 用 ffmpeg 把设备**主码流**转成 MJPEG(浏览器内嵌用)。
///
/// 为什么需要它:主码流是 2560×1440,PlayM4 的 <c>PlayM4_GetJPEG</c> 对这种大帧直接返回 0,
/// 设备抓帧(<c>NET_DVR_CaptureJPEGPicture_NEW</c>)又只有约 5fps。ffmpeg 在 C 里解码 + 缩放 + 编码,
/// 实测主码流(1440p → 1280 宽)可以跑到 ~22fps、约 80KB/帧。
///
/// ffmpeg 定位顺序:
/// 1. 环境变量 <c>YUNCANG_FFMPEG</c>(指向 ffmpeg.exe)
/// 2. 程序目录下 <c>native\ffmpeg\ffmpeg.exe</c>
/// 3. 系统 PATH 里的 <c>ffmpeg.exe</c>
///
/// 同一个 RTSP 地址 + 参数只起**一个** ffmpeg 进程(引用计数),多个页面看同一路不会重复转码。
/// </summary>
public sealed class HikFfmpegService : IDisposable
{
/// <summary>帧队列上限(超出丢最旧的,防止客户端慢把内存吃满)</summary>
private const int MaxQueuedFrames = 8;
/// <summary>单个 JPEG 帧上限(防止一直等不到 EOI 把缓冲区撑爆)</summary>
private const int MaxFrameBytes = 8 * 1024 * 1024;
private readonly ConcurrentDictionary<int, FfmpegStream> _streams = new();
private readonly Dictionary<string, int> _byKey = new(StringComparer.OrdinalIgnoreCase);
private readonly object _gate = new();
private int _nextHandle;
private bool _disposed;
/// <summary>ffmpeg.exe 路径(找不到为 null)</summary>
public string? FfmpegPath { get; } = ResolveFfmpeg();
public bool IsAvailable => !string.IsNullOrEmpty(FfmpegPath);
public int Count => _streams.Count;
/// <summary>ffmpeg 定位</summary>
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;
}
/// <summary>
/// 启动(或复用)一路主码流转码
/// </summary>
/// <param name="streamId">RTSP 码流号:主码流 = 通道序号*100+1,子码流 = *100+2</param>
/// <param name="width">输出宽度(高度按比例),1280 是画质/带宽的平衡点</param>
/// <param name="fps">输出帧率上限(0 = 跟源)</param>
/// <param name="quality">MJPEG 质量 q:v(2 最好 ~ 31 最差;6 约等于高质量)</param>
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);
}
/// <summary>
/// 按**完整 RTSP 地址**打开一路(回放预览用:地址里带 starttime/endtime)
///
/// <paramref name="keyPrefix"/> 是复用键前缀,**不能含密码**(地址里有账号密码)。
/// </summary>
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;
}
}
/// <summary>
/// 取**比 afterVersion 更新**的帧(没有就等到超时)
///
/// 只保留「最新一帧」而不是帧队列:多个页面/多个会话共用同一路 ffmpeg 时,
/// 各自用自己的版本号取帧,互不抢帧,也不会互相拖慢。
/// </summary>
public bool TryGetLatest(int handle, long afterVersion, int timeoutMs, out byte[] frame, out long version)
{
frame = Array.Empty<byte>();
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<byte>(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
{
// 进程被杀 / 管道断开,属于正常结束
}
}
/// <summary>从缓冲区里切出完整 JPEG 帧</summary>
private static void ExtractFrames(FfmpegStream stream, List<byte> 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<byte> 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();
}
/// <summary>一路 ffmpeg 转码</summary>
private sealed class FfmpegStream
{
private readonly object _sync = new();
private byte[] _latest = Array.Empty<byte>();
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; }
/// <summary>新帧覆盖(背压:只留最新的,慢客户端不会把内存吃掉)</summary>
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<byte>();
return false;
}
}
public void Terminate()
{
try
{
if (Process is { HasExited: false })
{
Process.Kill(true);
}
}
catch
{
// 忽略
}
try { Process?.Dispose(); } catch { /* 忽略 */ }
}
}
}

View File

@ -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;
/// <summary>
/// 满帧率预览窗口(PlayM4 直接把解码画面画到窗口,**不经过 JPEG 编码**)。
///
/// 为什么需要它:浏览器里内嵌的画面必须逐帧转 JPEG(<c>PlayM4_GetJPEG</c>),
/// 实测 1080p 一帧编码约 140ms → 上限只有 **约 7fps**。要 25fps 就只能让解码器
/// 直接画到一个原生窗口上(带宽也低:只传 H.264/H.265 码流,不是 JPEG 序列)。
///
/// 窗口由本机软件(WPF 主线程)创建;网页点「原生窗口」→ 通过本机 HTTP 服务请求打开,
/// 关掉窗口时自动释放码流(不需要网页再通知)。
/// </summary>
public sealed class HikNativePreviewService : IDisposable
{
private readonly HikStreamService _stream;
private readonly ConcurrentDictionary<string, NativePreview> _windows = new(StringComparer.OrdinalIgnoreCase);
private bool _disposed;
public HikNativePreviewService(HikStreamService stream)
{
_stream = stream;
}
public int Count => _windows.Count;
/// <summary>
/// 打开一个满帧率预览窗口(必须在 UI 线程创建 WinForms 窗口)
/// </summary>
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));
}
/// <summary>按 id 关窗口(网页关闭时调)</summary>
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();
}
}
/// <summary>一个原生预览窗口</summary>
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;
/// <summary>关窗口(UI 线程)</summary>
public void Close()
{
try
{
var form = Form;
if (form is null) return;
if (form.InvokeRequired) form.BeginInvoke(form.Close);
else form.Close();
}
catch
{
// 已经关掉了
}
}
}

View File

@ -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;
/// <summary>一次「这个时段到底有没有录像」的探测结果</summary>
/// <param name="HasRecord">拉到数据 = 有录像</param>
/// <param name="Frames">RTSP 模式下解出的帧数(SDK 模式为 -1)</param>
/// <param name="LogicalChannel">换算出来的 ISAPI/RTSP 1 起通道序号(排查用)</param>
/// <param name="Error">失败原因(无录像 / 端口不通 / 密码错)</param>
/// <param name="Source">实际走通的通道:SDK(8000)/ RTSP(554)</param>
public sealed record PlaybackCheck(bool HasRecord, int Frames, int LogicalChannel, string? Error, string Source = "");
/// <summary>下载一路回放的进度</summary>
/// <param name="Percent">0~1(拿不到总时长时为 null,界面显示为不确定进度)</param>
/// <param name="Message">当前状态文案</param>
public sealed record PlaybackProgress(double? Percent, string Message);
/// <summary>
/// 海康 **按时间回放**:校验有没有录像 / 拉流预览 / 下载成 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 而不是空流 —— 两个信号都能用来判「有/无回放」。
/// </summary>
public sealed class HikPlaybackService : IDisposable
{
/// <summary>Hikvision RTSP 默认端口(设备侧可改,用环境变量覆盖)</summary>
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);
/// <summary>RTSP socket 读超时(微秒)。回放拉完设备不再推流,靠它让 ffmpeg 收尾退出</summary>
private const string SocketTimeoutUs = "5000000";
private readonly HikDeviceService _device;
/// <summary>
/// 「这台设备的 8000 下载能不能用」缓存(key = host|port|channel)
///
/// 实测:有些固件 <c>NET_DVR_GetFileByTime*</c> 直接不工作(返回句柄但 0 字节),
/// 每路都去试一遍要多等好几秒 → 试过一次就记住,下次直接走 RTSP。
/// </summary>
private readonly ConcurrentDictionary<string, bool> _sdkPlayback = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 「录像机时间 - 本机时间」偏差缓存(key = host|port|user)
///
/// 扫码时间是**本机时钟**打的,回放是按**录像机本地时间**定位的;两边不一致时
/// (现场实测本机慢了 9 秒),短回放窗口会把面单直接截掉。
/// 以录像机时钟为基准做平移,缓存 10 分钟(读不到设备时间时 1 分钟内不重试)。
/// </summary>
private readonly ConcurrentDictionary<string, (TimeSpan Offset, long At, long Ttl)> _clockOffsets =
new(StringComparer.OrdinalIgnoreCase);
private const long ClockOffsetTtlMs = 10 * 60 * 1000;
private const long ClockOffsetFailTtlMs = 60 * 1000;
public HikPlaybackService(HikDeviceService device)
{
_device = device;
}
/// <summary>ffmpeg 是否可用(没有就既不能校验也不能下载)</summary>
public bool Available => HikFfmpegService.ResolveFfmpeg() is not null;
// ==================== 通道号换算 ====================
/// <summary>
/// 海康通道号 → ISAPI/RTSP 的 1 起序号
///
/// 换算依赖设备的「首个数字通道号」(本项目是 33):
/// <c>logical = channel - startDigital + 1</c>。SDK 不可用时按 33 兜底。
/// </summary>
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;
}
/// <summary>
/// 生成回放 RTSP 地址
///
/// ⚠️ **时间语义实测结论(重要)**:海康 RTSP 的 <c>starttime</c> 按**设备本地时间**解析,
/// 结尾那个 <c>Z</c> 只是格式后缀、**不代表 UTC**。
/// 实测同一时间点:
/// - 传 <c>20261018T131550Z</c>(UTC 写法)→ 画面 OSD 是 **13:15:49**(2号工作台,无任务)
/// - 传 <c>20261018T211550Z</c>(本地写法)→ 画面 OSD 是 **21:15:49**(1号工作台,波次B…)
/// 也就是按 UTC 传会整整差一个时区(本机 +08:00 差 8 小时)。
///
/// 默认按本地时间拼;万一遇到严格按 UTC 解析的固件,用环境变量 <c>YUNCANG_RTSP_TIME=utc</c> 切回去。
/// </summary>
/// <param name="streamType">0 主码流 / 1 子码流(回放路径里是 01 / 02)</param>
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);
}
/// <summary>
/// 录像机时钟与本机时钟的偏差(设备 - 本机,秒)。
///
/// 扫码时间来自本机时钟,回放定位用设备时间 → 两者必须在同一条时间轴上。
/// 读不到设备时间 / 设备不支持该命令时返回零(保持原有行为)。
/// </summary>
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;
}
}
/// <summary>生成回放 RTSP 地址(自动把本机时间平移成录像机时间)</summary>
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);
}
// ==================== ① 校验有没有录像 ====================
/// <summary>
/// 探测该时段有没有录像
///
/// **先走 8000(SDK 下载 2 秒到临时文件,看有没有数据)**,不行再走 RTSP 拉 2 秒看帧。
/// 设备不会主动告诉你空段,只能真拉一次。
/// </summary>
public async Task<PlaybackCheck> 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 ====================
/// <summary>
/// 下载一路回放到文件
///
/// 实测出来的两个坑(本项目 NVR):
/// 1. **回放流不会按 endtime 自己断**:ffmpeg 拉完数据还挂在 RTSP 读上,进程不退出 →
/// 必须加 <c>-timeout</c>(socket I/O 超时)オ能让它正常收尾;
/// 2. **不能直接写 mp4**:流没正常结束就不会写 moov atom,文件无法播放(moov atom not found)。
/// 所以先写 <c>mpegts</c>(流式容器,中途中断也能播),完成后本地转封装成 mp4。
///
/// 回放速度实测约 0.5x~3x(跟码流大小有关),所以**必须显示进度、必须能取消**。
/// </summary>
/// <returns>落地文件路径(mp4;转封装失败时是 .ts)</returns>
public async Task<string> DownloadAsync(string host, int port, string userName, string password,
int channel, DateTimeOffset start, DateTimeOffset end, string outputPath,
IProgress<PlaybackProgress>? 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;
}
// ==================== ③ 按工作台布局合并成一个视频 ====================
/// <summary>
/// 把多路下载好的片段**按工作台画布布局合并成一个视频**
///
/// 做法:先铺一张黑画布(`color` 虚拟输入),每路 `scale` 到它在快照里的尺寸,
/// 再用 `overlay=x:y` 摆到对应位置 —— 与工作台页面上的画面摆放一致。
///
/// ⚠️ 踩过的坑:**不要**把每路先 <c>pad</c> 成整张画布再叠加 ——
/// 补边是黑底,叠上去会把下面那路的画面整块盖住(表现是「合成完只剩一个小窗,其余全黑」)。
///
/// 为什么要重新编码:多路叠加没法 `-c:v copy`(要重画每个像素),所以这一步比下载慢,
/// 用 <c>veryfast</c> + <c>crf 23</c> 折中。
/// </summary>
/// <param name="segments">各路下载好的文件(顺序与 <paramref name="streams"/> 一一对应)</param>
/// <returns>合并后文件路径</returns>
public async Task<string> ComposeAsync(IReadOnlyList<string> segments, IReadOnlyList<PackStream> streams,
string outputPath, IProgress<PlaybackProgress>? 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<string>();
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<string>
{
"-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;
}
// ==================== 内部 ====================
/// <summary>把设备原始录像(PS)转封装成 mp4;失败返回 false</summary>
private async Task<bool> 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
{
// 临时文件删不掉不影响业务
}
}
/// <summary>
/// 跑一次 ffmpeg:stderr 逐行回调(进度/错误都在 stderr)
/// </summary>
private async Task<int> RunAsync(string ffmpeg, string[] args, Action<string>? 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
{
// 进程已经退了
}
}
/// <summary>解析 `<c>-progress</c>` 的 `out_time_us=`,算百分比</summary>
private static void ReportProgress(IProgress<PlaybackProgress>? 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}"));
}
}
/// <summary>把 ffmpeg 的输出压成一句能看懂的错因</summary>
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()
{
// 后台任务由调用方各自取消;这里没有需要释放的资源
}
}

View File

@ -0,0 +1,299 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace YuncangTrace.LocalService.Services.Hik;
/// <summary>
/// 预览会话管理。
///
/// 为什么要有「会话」这层:
/// - 浏览器要把实时画面显示出来,必须有一个能持续拉的地址;而密码**不能**出现在 URL 里
/// (会被历史记录、日志、代理记下来)。所以先 <c>POST /api/hik/preview</c> 换一个
/// <c>sid</c>,之后 <c>&lt;img src="/api/hik/preview/mjpeg?sid=...&gt;</c> 只带 sid;
/// - 会话里存着设备凭据与通道号,抓帧时直接复用 <see cref="HikDeviceService"/> 的连接池,
/// 不会每次请求都重新登录设备;
/// - 30 分钟没人刷新自动失效(滑动过期),进程内内存存储,不落盘。
///
/// 抓帧用 HCNetSDK 的 <c>NET_DVR_CaptureJPEGPicture_NEW</c>(8000 端口私有协议):
/// 不需要解码器、不需要转码,拿到的 JPEG 浏览器直接能显示。
/// </summary>
public sealed class HikPreviewService : IDisposable
{
/// <summary>会话空闲多久失效(浏览器一直开着流会不断续期)</summary>
private static readonly TimeSpan SessionTtl = TimeSpan.FromMinutes(30);
/// <summary>同时保留的会话上限(防止页面异常反复建会话把内存吃满)</summary>
private const int MaxSessions = 32;
private readonly HikDeviceService _device;
private readonly HikStreamService _stream;
private readonly HikFfmpegService _ffmpeg;
private readonly ConcurrentDictionary<string, HikPreviewSession> _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));
}
/// <summary>
/// 建预览会话(会登录一次设备验证账号密码,并从登录信息里读「首个数字通道号」)
/// </summary>
/// <param name="mode">
/// ffmpeg = ffmpeg 转码(主码流可用,缩到 width 宽);
/// stream = SDK 取流 + PlayM4 解码转 JPEG(适合子码流);
/// capture = 设备抓帧(约 5fps)。
/// </param>
/// <param name="streamType">0-主码流,1-子码流</param>
/// <param name="logicalChannel">ISAPI/RTSP 的 1 起通道序号;不传则按设备起始数字通道推算</param>
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;
}
/// <summary>按 sid 取会话(滑动续期);不存在/已过期返回 null</summary>
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;
}
/// <summary>抓一帧(阻塞调用,HTTP 层放线程池里跑)</summary>
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<byte>();
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);
}
/// <summary>解码画面的分辨率(拿不到返回 0x0)</summary>
public (int Width, int Height) SizeOf(HikPreviewSession session)
=> session.StreamHandle >= 0 ? _stream.GetSize(session.StreamHandle) : (0, 0);
/// <summary>当前打开的实时流数(排障用)</summary>
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 统一释放
}
}
/// <summary>一路预览</summary>
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;
/// <summary>海康通道号(数字通道从 33 起)</summary>
public int Channel { get; init; }
/// <summary>ISAPI/RTSP 用的 1 起通道序号</summary>
public int LogicalChannel { get; init; }
/// <summary>0-主码流(默认),1-子码流</summary>
public int StreamType { get; init; } = 0;
/// <summary>预览模式:stream=码流本地解码(25fps);capture=设备抓帧(约 5fps)</summary>
public string Mode { get; internal set; } = "capture";
/// <summary>降级时的提示</summary>
public string? Warning { get; internal set; }
/// <summary>实时流句柄(-1 = 未走码流;句柄 0 是合法的第一路)</summary>
public int StreamHandle { get; internal set; } = -1;
/// <summary>ffmpeg 转码句柄(-1 = 未用 ffmpeg)</summary>
public int FfmpegHandle { get; internal set; } = -1;
/// <summary>该会话已经取到的 ffmpeg 帧版本(避免两个页面抢同一帧)</summary>
public long FfmpegVersion { get; internal set; }
/// <summary>是否已经成功出过解码帧(用于首帧兑底判断)</summary>
public bool HadFrame { get; internal set; }
/// <summary>抓帧帧率(1~25)</summary>
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;
/// <summary>RTSP 码流 id:主码流 = 通道号 * 100 + 1(通道 1 → 101)</summary>
public string StreamId => $"{LogicalChannel}01";
/// <summary>标准 RTSP 地址(给 VLC 等外部播放器;浏览器用 MJPEG 那个)</summary>
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);
}
}

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
namespace YuncangTrace.LocalService.Services.Hik;
/// <summary>
/// 云台(PTZ)命令码表 —— 与 HCNetSDK.h 保持一致。
///
/// 注意:
/// - 方向/变倍/聚焦/光圈都是**连续动作**:先 <c>stop=0</c> 开始,再 <c>stop=1</c> 停止;
/// - 预置点走另一套接口(<c>NET_DVR_PTZPreset_Other</c>);
/// - <c>PAN_AUTO</c>(自动扫描)也是连续动作,需要停止才会结束。
/// </summary>
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;
/// <summary>前端用的名字 → 命令码</summary>
internal static readonly Dictionary<string, uint> 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,
};
/// <summary>预置点动作 → 命令码</summary>
internal static readonly Dictionary<string, uint> PresetActions = new(StringComparer.OrdinalIgnoreCase)
{
[ "set" ] = PresetSet,
[ "goto" ] = PresetGoto,
[ "clear" ] = PresetClear,
};
}

View File

@ -0,0 +1,506 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace YuncangTrace.LocalService.Services.Hik;
/// <summary>
/// 海康「设备网络 SDK(HCNetSDK)」的 P/Invoke 声明与初始化。
///
/// 只覆盖本项目需要的最小集合:<c>NET_DVR_Login_V40</c>(走 8000 私有协议)、
/// <c>NET_DVR_GetDVRConfig</c>(读 IP 通道配置)、<c>NET_DVR_Logout</c>。
///
/// ⚠️ 关键约束(都踩过):
/// 1. **必须 x64**:desktop 本身是 x64 进程,SDK 只能用 Win64 包(32 位会加载失败);
/// 2. **必须 SetDllDirectory**:HCNetSDK.dll 依赖同目录的 HCCore.dll 与 <c>HCNetSDKCom\</c> 组件,
/// 不指定目录会 DLL 找不到 → <c>NET_DVR_Init</c> 直接失败;
/// 3. **结构体要按字节对齐**:<see cref="NET_DVR_USER_LOGIN_INFO"/> 的 <c>Marshal.SizeOf</c> 必须为 416,
/// 少一个填充字节密码就会读错位;
/// 4. **密码传明文**:MD5/RSA 是 SDK 与设备内部的挑战应答,应用层传明文(实测传 MD5 必然 err=1)。
/// </summary>
internal static class HikSdk
{
private const string Dll = "HCNetSDK.dll";
/// <summary>NET_DVR_GET_IPPARACFG_V40:读取 IP 接入配置(含 IP 通道列表)</summary>
internal const uint NET_DVR_GET_IPPARACFG_V40 = 1062;
/// <summary>NET_DVR_GET_TIMECFG:读取设备时间(输出 NET_DVR_TIME,24 字节)</summary>
internal const uint NET_DVR_GET_TIMECFG = 118;
/// <summary>NET_DVR_SET_TIMECFG:写入设备时间(输入 NET_DVR_TIME)</summary>
internal const uint NET_DVR_SET_TIMECFG = 119;
/// <summary>NET_DVR_GET_NTPCFG:读取 NTP 配置(输出 NET_DVR_NTPPARA,126 字节)</summary>
internal const uint NET_DVR_GET_NTPCFG = 224;
/// <summary>NET_DVR_SET_NTPCFG:写入 NTP 配置(输入 NET_DVR_NTPPARA)</summary>
internal const uint NET_DVR_SET_NTPCFG = 225;
/// <summary>NET_DVR_GET_DEVICECFG:读取设备参数(用于探活)</summary>
internal const uint NET_DVR_GET_DEVICECFG = 100;
/// <summary>
/// NET_DVR_JPEGPARA.wPicSize 常用值
///
/// <c>0xFF</c> = 用当前码流分辨率(部分老固件不支持,会回 err=17/23,调用方需降级重试)。
/// </summary>
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;
/// <summary>实际加载的 SDK 目录(排障用)</summary>
internal static string? SdkDirectory { get; private set; }
/// <summary>设备网络 SDK 的登录参数结构体(Win64 下 sizeof = 416)</summary>
[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);
/// <summary>写设备配置(如 <c>NET_DVR_SET_NTPCFG</c>);<paramref name="lpInBuffer"/> 指向命令对应的结构体</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_SetDVRConfig(
int lUserID,
uint dwCommand,
int lChannel,
IntPtr lpInBuffer,
uint dwInBufferSize);
/// <summary>
/// 从设备抓一帧 JPEG(走 8000 私有协议,**不需要** ISAPI/Web 端口)
///
/// 预览就是靠它按 fps 连续抓帧、再以 MJPEG 推给浏览器;不需要解码器,也不需要转码进程。
/// <c>lpJpegPara</c> 指向 <c>NET_DVR_JPEGPARA</c>(WORD wPicSize + WORD wPicQuality,4 字节)。
/// </summary>
[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);
/// <summary>
/// 实时预览信息(HCNetSDK.h 的 <c>NET_DVR_PREVIEWINFO</c>,x64 下 sizeof = 288)
///
/// 头文件**没有** <c>#pragma pack</c>,所以按自然对齐声明:<c>hPlayWnd</c> 前有 4 字节填充。
/// </summary>
[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;
}
/// <summary>实时流数据回调(dwDataType:1-系统头,2-流数据)</summary>
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);
/// <summary>
/// 云台连续动作(不依赖预览句柄,直接用登录的 UserID + 通道号)
///
/// <paramref name="dwStop"/>:0=开始,1=停止。云台必须“开始 + 停止”成对调用,否则会一直转。
/// </summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_PTZControlWithSpeed_Other(
int lUserID,
int lChannel,
uint dwPTZCommand,
uint dwStop,
uint dwSpeed);
/// <summary>预置点:设置 / 调用 / 删除(<c>dwPTZPresetCmd</c> 见 <see cref="HikPtz"/>)</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_PTZPreset_Other(
int lUserID,
int lChannel,
uint dwPTZPresetCmd,
uint dwPresetIndex);
// ==================== 按时间下载录像(走 8000 私有协议) ====================
/// <summary>HCNetSDK 的 <c>NET_DVR_TIME</c>(sizeof = 24)</summary>
[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;
}
/// <summary>
/// HCNetSDK 的 <c>NET_DVR_NTPPARA</c>(sizeof = 126)
///
/// <code>
/// BYTE sNTPServer[64]; // 域名/IP,ASCII
/// WORD wInterval; // 同步间隔(分钟)
/// BYTE byEnable; // 0-关闭 1-启用
/// BYTE byRes[59];
/// </code>
/// </summary>
[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;
}
/// <summary>
/// HCNetSDK 的 <c>NET_DVR_PLAYCOND</c>(sizeof = 356)
///
/// <code>
/// DWORD dwChannel; NET_DVR_TIME struStartTime; NET_DVR_TIME struStopTime;
/// BYTE byStreamType; BYTE byDownload; BYTE byOptimalStreamType; BYTE byRes2[301];
/// </code>
/// </summary>
[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;
}
/// <summary>
/// 按时间把录像**下载到文件**(8000 私有协议,不需要 554 / 不需要解码器)
///
/// 返回值是文件句柄(&gt;0 成功,-1 失败用 <see cref="NET_DVR_GetLastError"/> 查原因)。
/// 下载出来的是设备原始封装(PS),要 mp4 得再用 ffmpeg 转封装。
/// </summary>
[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);
/// <summary>下载进度(0~100,-1 表示失败)</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern int NET_DVR_GetDownloadPos(int lFileHandle);
/// <summary>停止下载并释放句柄</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_StopGetFile(int lFileHandle);
// ==================== 按时间**回放取流**(8000 私有协议,全速推送) ====================
/// <summary><c>NET_DVR_PlayBackControl</c> 控制码</summary>
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;
/// <summary>回放数据回调(<paramref name="dwDataType"/>:1 系统头,2 流数据)</summary>
internal delegate void PlayDataCallback(int lPlayHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize,
IntPtr pUser);
/// <summary>
/// 按时间打开回放(通道号用**海康通道号**,如 34)
///
/// ⚠️ 实测:这条接口是**全速推送**的,不按实时速率 —— 本项目设备 2 分钟主码流素材
/// 约 7 秒就推完(≈14 MB/s,17 倍速),所以下载录像不用再 `PlayFast`。
/// 相比之下 <c>NET_DVR_GetFileByTime*</c> 在这台固件上直接不工作(err 17 / 0 字节)。
/// </summary>
[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);
/// <summary>回放数据回调(<paramref name="hWnd"/> 传 0 时必须设,否则没有数据)</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_SetPlayDataCallBack(
int lPlayHandle,
PlayDataCallback? fPlayDataCallBack,
IntPtr pUser);
/// <summary>回放控制(开始 / 停止 / 暂停 / 快放…),<paramref name="dwControlCode"/> 见常量</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_PlayBackControl(
int lPlayHandle,
uint dwControlCode,
uint dwInValue,
IntPtr lpOutValue);
/// <summary>停止回放并释放句柄</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool NET_DVR_StopPlayBack(int lPlayHandle);
/// <summary>回放进度(0~100;-1 失败)。判「推完」用它,比数字节稳</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern int NET_DVR_GetPlayBackPos(int lPlayHandle);
/// <summary>初始化 SDK(幂等)。找不到 HCNetSDK.dll 时抛 <see cref="HikException"/></summary>
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}");
}
}
/// <summary>停用 SDK(进程退出时调用)</summary>
internal static void Shutdown()
{
lock (InitSync)
{
if (!_initialized) return;
try { NET_DVR_Cleanup(); } catch { /* 退出阶段忽略 */ }
_initialized = false;
}
}
/// <summary>登录设备,返回 UserID(&gt;=0);失败抛异常。调用方负责 FreeHGlobal(deviceInfo)</summary>
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;
}
/// <summary>常见错误码的中文描述(对照 HCNetSDK.h)</summary>
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})",
};
}
/// <summary>海康 SDK 调用异常(<see cref="ErrorCode"/> 为 NET_DVR_GetLastError 的原值)</summary>
public sealed class HikException : Exception
{
public HikException(uint errorCode, string message) : base(message)
{
ErrorCode = errorCode;
}
/// <summary>NET_DVR_GetLastError 返回码(非 SDK 错误时用 0xFFFFFFFF)</summary>
public uint ErrorCode { get; }
}

View File

@ -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;
/// <summary>
/// 取实时码流 + 本地解码(25fps 的预览就是靠它)。
///
/// 链路:<c>NET_DVR_RealPlay_V40</c>(8000 私有协议,TCP)→ 回调收到 PS 流 →
/// <c>PlayM4_InputData</c> 解码 → <c>PlayM4_GetJPEG</c> 取当前帧交给浏览器。
///
/// 与「抓帧」模式的差别(实测):
/// - 抓帧:设备端编码 JPEG,**上限约 5fps**(1080p 每帧 ~190ms),只适合低频快照;
/// - 解码:一路码流持续解码,可稳稳跑到设备实际帧率(本项目 25fps),
/// 代价是本机多一个解码线程、设备多一路预览连接。
///
/// 子码流(<paramref name="streamType"/> = 1)默认,因为预览流畅度优先、带宽小;
/// 要看细节可以传 0 走主码流。
/// </summary>
public sealed class HikStreamService : IDisposable
{
/// <summary>PlayM4 缓冲区(2MB,够 1080p 一段 GOP)</summary>
private const uint BufferPoolSize = 2 * 1024 * 1024;
/// <summary>取帧用的 JPEG 缓冲区(4MB)</summary>
private const uint JpegBufferSize = 4 * 1024 * 1024;
private readonly HikDeviceService _device;
private readonly ConcurrentDictionary<int, StreamSession> _streams = new();
/// <summary>复用键(host:port|user|channel|streamType|模式)→ 句柄</summary>
private readonly Dictionary<string, int> _byKey = new(StringComparer.OrdinalIgnoreCase);
/// <summary>串行化 Open/Close,避免两个浏览器同时申请同一通道时各开一路</summary>
private readonly object _gate = new();
private bool _disposed;
public HikStreamService(HikDeviceService device)
{
_device = device;
}
/// <summary>当前打开的码流数(排障用)</summary>
public int Count => _streams.Count;
/// <summary>
/// 打开一路实时流,返回句柄(NET_DVR_RealPlay_V40 的返回值)
/// </summary>
/// <param name="streamType">0-主码流,1-子码流</param>
/// <param name="renderWnd">
/// 渲染窗口句柄:<c>IntPtr.Zero</c> = 只解码(配合 <see cref="GetJpeg"/> 推给浏览器);
/// 传窗口句柄 = 解码器直接画到窗口,**满帧率(设备 25fps)且不经过 JPEG 编码**。
/// </param>
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;
}
/// <summary>
/// 取当前帧 JPEG;尚无解码帧时返回空数组(调用方稍后重试即可)
/// </summary>
public byte[] GetJpeg(int handle, int timeoutMs = 800)
{
if (!_streams.TryGetValue(handle, out var session)) return Array.Empty<byte>();
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<byte>();
}
private static bool TryReadJpeg(StreamSession session, out byte[] frame)
{
frame = Array.Empty<byte>();
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);
}
}
/// <summary>解出来的画面尺寸(宽 x 高),拿不到返回 (0,0)</summary>
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);
}
/// <summary>关闭一路实时流(引用计数减到 0 才真的停)</summary>
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();
}
/// <summary>一路实时流的状态(回调线程与 HTTP 线程共用)</summary>
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; }
/// <summary>复用键(window 模式不参与复用,Key 为空)</summary>
public string Key { get; set; } = string.Empty;
/// <summary>有多少个预览会话在用它</summary>
public int RefCount { get; set; }
/// <summary>最近使用时间(配速/排障用)</summary>
public long LastUsedTicks { get; private set; } = Environment.TickCount64;
public void Touch() => LastUsedTicks = Environment.TickCount64;
/// <summary>渲染窗口(0 = 只解码不出图)</summary>
public IntPtr RenderWnd { get; set; }
public string? Name { get; set; }
/// <summary>回调委托(必须由本对象持有,避免被 GC 回收)</summary>
public HikSdk.RealDataCallback? Callback { get; set; }
/// <summary>SDK 网络线程回调:拿到 PS 流喂给 PlayM4</summary>
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<byte>();
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);
}
}
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Runtime.InteropServices;
namespace YuncangTrace.LocalService.Services.Hik;
/// <summary>
/// PlayCtrl(PlayM4)解码库的 P/Invoke。
///
/// 用它的理由:设备侧「抓 JPEG」只有约 5fps(<c>NET_DVR_CaptureJPEGPicture_NEW</c> 实测,
/// 是设备在编码 JPEG,很慢)。要 **25fps** 只能拿真正的码流:
/// <c>NET_DVR_RealPlay_V40</c> 收到 PS 流 → <c>PlayM4_InputData</c> 喂给解码器 →
/// <c>PlayM4_GetJPEG</c> 取当前解码帧(本地编码,快得多)。
///
/// DLL 与 HCNetSDK.dll 同目录(<c>native\HCNetSDK\PlayCtrl.dll</c>);
/// <see cref="HikSdk.EnsureInitialized"/> 里已经 <c>SetDllDirectory</c>,这里直接按名字加载即可。
/// </summary>
internal static class PlayM4
{
private const string Dll = "PlayCtrl.dll";
/// <summary>实时流(不追赶时间轴)</summary>
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);
/// <summary>开始播放;<paramref name="hWnd"/> 传 0 表示只解码不显示</summary>
[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);
/// <summary>取当前解码帧的 JPEG(本地编码,比设备端抓图快得多)</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool PlayM4_GetJPEG(int nPort, IntPtr pJpeg, uint nBufSize, out uint pJpegSize);
/// <summary>当前画面尺寸</summary>
[DllImport(Dll, CallingConvention = CallingConvention.StdCall)]
internal static extern bool PlayM4_GetPictureSize(int nPort, out int pWidth, out int pHeight);
}

View File

@ -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;
/// <summary>下载结果(HTTP 接口与桌面端共用)</summary>
/// <param name="Folder">最终存放目录(`{录像根}/yyyy/MM/dd`)</param>
/// <param name="Merged">合并后的成片路径(单路时就是那一路的路径)</param>
/// <param name="Segments">各路段文件(合并失败时才有多个,且都已搬到用户目录)</param>
/// <param name="Warnings">非致命问题(某路没下到等)</param>
public sealed record PlaybackDownloadResult(
string Folder,
string? Merged,
IReadOnlyList<string> Segments,
IReadOnlyList<string> Warnings);
/// <summary>
/// 「按运单下载录像」的完整流程(**与界面无关**,桌面端和网页查件都走它)
///
/// 1. `pack-query` 拿到回放计划(扫码当时的工作台快照);
/// 2. 逐路下载到 **临时目录**(并发 2 路,8000 全速拉流优先、失败回落 RTSP);
/// 3. 多路按工作台画布布局**自动合并**成一个视频;
/// 4. 成片放到 `{录像根}/年/月/日/`,删掉临时片段。
///
/// 关键点:**录像存储路径是每台机器自己的设置**,跟"是不是设备服务器"无关 ——
/// 任何装了本机软件的电脑,查件后都能下载到自己配的目录里。
/// </summary>
public sealed class PlaybackDownloadService
{
/// <summary>同时下载几路(给 NVR 回放连接留余量)</summary>
private const int MaxParallel = 2;
private readonly OrderQueryService _query;
private readonly HikPlaybackService _playback;
private readonly Func<ApiClient?> _api;
private readonly Func<int> _subjectId;
private readonly Func<string?> _token;
private readonly Func<string> _root;
public PlaybackDownloadService(
OrderQueryService query,
HikPlaybackService playback,
Func<ApiClient?> apiProvider,
Func<int> subjectIdProvider,
Func<string?> tokenProvider,
Func<string> videoRootProvider)
{
_query = query;
_playback = playback;
_api = apiProvider;
_subjectId = subjectIdProvider;
_token = tokenProvider;
_root = videoRootProvider;
}
/// <summary>
/// 按运单号下载这段时间的录像(多路自动合并)
/// </summary>
/// <exception cref="InvalidOperationException">查询失败 / 没有可下载的流(message 可直接给用户看)</exception>
public async Task<PlaybackDownloadResult> DownloadAsync(string code, IProgress<string>? 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<string>();
var saved = new string?[streams.Count];
var gate = new SemaphoreSlim(MaxParallel);
var credentials = new Dictionary<int, NvrCredential>();
var credentialGate = new SemaphoreSlim(1, 1);
try
{
var tasks = new List<Task>();
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<PlaybackProgress>(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<PlaybackProgress>(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<string>();
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<NvrCredential> CredentialAsync(int nvrId, Dictionary<int, NvrCredential> 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}");
}
}
}

View File

@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 录像存储目录
///
/// 约定:
/// - 默认根目录 <c>~/packVideo</c>(用户目录下,权限够、不会被清理工具删);
/// - 按 **扫码日期** 分目录:<c>{根}/2026/03/11/</c>,成片直接放在里面;
/// - 用户可以在「工具 → 设置录像存储路径」改根目录;切换时**把已有文件一起搬过去**。
/// </summary>
public static class VideoStorage
{
/// <summary>默认根目录:`%USERPROFILE%\packVideo`</summary>
public static string DefaultRoot { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "packVideo");
/// <summary>某个时间点对应的目录:`{根}/yyyy/MM/dd`</summary>
public static string FolderFor(string root, DateTime time)
=> Path.Combine(root, time.ToString("yyyy"), time.ToString("MM"), time.ToString("dd"));
/// <summary>
/// 把 <paramref name="from"/> 下的所有文件搬到 <paramref name="to"/>(保留相对目录结构)
///
/// 切换存储路径时用:只搬文件,搬完把**空的**旧目录删掉(旧目录里如果还有别的东西就留着,
/// 防止误删用户自己放进去的文件)。
/// </summary>
/// <returns>移动的文件数 / 出错信息(出错不抛,界面给提示)</returns>
public static (int Moved, string? Error) MoveAll(string from, string to, IProgress<string>? 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);
}
}
/// <summary>自底向上删空目录(不动有文件的目录)</summary>
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
{
// 删不掉跳过
}
}
}
}

View File

@ -0,0 +1,18 @@
<Window x:Class="YuncangTrace.LocalService.Views.PlaybackPreviewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="回放预览" Height="760" Width="1180"
WindowStartupLocation="CenterOwner"
Background="#101216">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="12,10,12,6">
<Button DockPanel.Dock="Right" Content="关闭" Padding="14,4" Click="Close_Click" />
<TextBlock x:Name="TitleText" Foreground="#E5E7EB" FontSize="13"
VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
Text="回放预览" />
</DockPanel>
<Viewbox Stretch="Uniform" StretchDirection="Both" Margin="12" HorizontalAlignment="Center">
<Canvas x:Name="Canvas" Background="Black" Width="1920" Height="1080" />
</Viewbox>
</DockPanel>
</Window>

View File

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using YuncangTrace.LocalService.Services;
using YuncangTrace.LocalService.Services.Hik;
namespace YuncangTrace.LocalService.Views;
/// <summary>
/// 多路回放预览:**按扫码当时工作台的画布布局**把几路回放摆在一起播
///
/// 做法(和网页端预览一条路):
/// ffmpeg 按时间拉 RTSP 回放 → 转 MJPEG → 每帧取最新一张贴到 <see cref="Image"/>。
/// 不解码到窗口,所以可以同时播很多路;坏处是 CPU 比硬解高一点。
///
/// 布局直接从后端快照来(canvasWidth/Height + 每路的 x/y/width/height),
/// 用 <see cref="Viewbox"/> 等比缩放,窗口多大都不变形。
/// </summary>
public partial class PlaybackPreviewWindow : Window
{
/// <summary>取帧频率(ms):40ms ≈ 25fps,与设备帧率一致</summary>
private const int FrameIntervalMs = 40;
private readonly List<Session> _sessions = new();
private readonly DispatcherTimer? _timer;
private readonly HikFfmpegService? _ffmpeg;
private sealed class Session
{
public PackStream Stream { get; init; } = null!;
public Image Image { get; init; } = null!;
public TextBlock Status { get; init; } = null!;
public int Handle { get; set; }
public long FrameVersion { get; set; }
public DateTime StartedAt { get; } = DateTime.Now;
public bool Finished { get; set; }
}
/// <param name="streams">要播的回放流(同一工作台的一批)</param>
/// <param name="ffmpeg">MJPEG 管线</param>
/// <param name="playback">回放服务(生成 RTSP 地址)</param>
/// <param name="credentials">nvrId → 凭据</param>
public PlaybackPreviewWindow(IReadOnlyList<PackStream> streams,
HikFfmpegService ffmpeg, HikPlaybackService playback, IReadOnlyDictionary<int, NvrCredential> credentials)
{
InitializeComponent();
_ffmpeg = ffmpeg;
if (streams.Count == 0)
{
TitleText.Text = "没有可播放的回放流";
return;
}
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;
Canvas.Width = canvasWidth;
Canvas.Height = canvasHeight;
var first = streams[0];
TitleText.Text = $"{first.StartTime.ToLocalTime():yyyy-MM-dd HH:mm:ss} ~ "
+ $"{first.EndTime.ToLocalTime():HH:mm:ss} · {streams.Count} 路回放"
+ $"({canvasWidth}×{canvasHeight})";
foreach (var stream in streams.OrderBy(item => item.Layout.ZIndex).ThenBy(item => item.Layout.SortNo))
{
if (!credentials.TryGetValue(stream.NvrId, out var credential)) continue;
var logical = playback.LogicalChannel(credential.Host, credential.Port,
credential.Username, credential.Password, stream.ChannelNo);
// 自动把本机时间平移成录像机时间(时钟偏差会让回放错位)
var url = playback.BuildRtspUrlFor(credential.Host, credential.Port,
credential.Username, credential.Password, logical,
stream.StartTime, stream.EndTime, stream.StreamType);
// 布局:宽高为 0 表示占满整张画布
var width = stream.Layout.Width > 0 ? stream.Layout.Width : canvasWidth;
var height = stream.Layout.Height > 0 ? stream.Layout.Height : canvasHeight;
var image = new Image { Stretch = System.Windows.Media.Stretch.Uniform };
var status = new TextBlock
{
Text = $"{stream.DisplayName} 连接中…",
Foreground = System.Windows.Media.Brushes.White,
Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(140, 0, 0, 0)),
Padding = new Thickness(4, 1, 4, 1),
FontSize = 12,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
};
var host = new Grid();
host.Children.Add(image);
host.Children.Add(status);
var panel = new Border
{
Width = width,
Height = height,
Background = System.Windows.Media.Brushes.Black,
Child = host,
BorderBrush = System.Windows.Media.Brushes.Gray,
BorderThickness = new Thickness(1),
};
Canvas.SetLeft(panel, stream.Layout.X);
Canvas.SetTop(panel, stream.Layout.Y);
Panel.SetZIndex(panel, stream.Layout.ZIndex);
Canvas.Children.Add(panel);
var session = new Session { Stream = stream, Image = image, Status = status };
try
{
session.Handle = ffmpeg.OpenUrl(url,
$"{credential.Host}|{stream.ChannelNo}|{stream.StartTime.ToUnixTimeSeconds()}|{stream.EndTime.ToUnixTimeSeconds()}");
_sessions.Add(session);
}
catch (Exception ex)
{
status.Text = $"{stream.DisplayName} 打开失败:{ex.Message}";
}
}
_timer = new DispatcherTimer(DispatcherPriority.Render) { Interval = TimeSpan.FromMilliseconds(FrameIntervalMs) };
_timer.Tick += OnTick;
_timer.Start();
Closed += (_, _) => DisposeSessions();
}
private void OnTick(object? sender, EventArgs e)
{
foreach (var session in _sessions)
{
if (_ffmpeg is null || session.Finished || session.Handle <= 0) continue;
if (!_ffmpeg.TryGetLatest(session.Handle, session.FrameVersion, 1, out var frame, out var version))
{
// 超过 12 秒还没出帧:大概率这段时间没录像
if (session.Image.Source is null && (DateTime.Now - session.StartedAt).TotalSeconds > 12)
{
session.Status.Text = $"{session.Stream.DisplayName} 没有画面(该时段可能没有录像)";
session.Finished = true;
}
continue;
}
session.FrameVersion = version;
try
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = new System.IO.MemoryStream(frame);
bitmap.EndInit();
bitmap.Freeze();
session.Image.Source = bitmap;
if (session.Status.Text.EndsWith('…'))
{
var elapsed = (DateTime.Now - session.StartedAt).TotalSeconds;
session.Status.Text = $"{session.Stream.DisplayName} {elapsed:0}s";
}
else
{
var elapsed = (DateTime.Now - session.StartedAt).TotalSeconds;
session.Status.Text = $"{session.Stream.DisplayName} {elapsed:0}s";
}
}
catch
{
// 半帧/坏帧直接丢掉,下一帧再说
}
}
}
private void Close_Click(object sender, RoutedEventArgs e) => Close();
private void DisposeSessions()
{
_timer?.Stop();
foreach (var session in _sessions)
{
if (session.Handle <= 0 || _ffmpeg is null) continue;
try
{
_ffmpeg.Close(session.Handle);
}
catch
{
// 关窗时忽略
}
session.Handle = 0;
}
_sessions.Clear();
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.