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
{
// 已经关掉了
}
}
}