feat: add http vedio test
This commit is contained in:
parent
81f91b2b71
commit
4c14ada97b
|
@ -2,9 +2,11 @@ using System.Net;
|
|||
using System.Net.Sockets;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Newtonsoft.Json;
|
||||
using NLog;
|
||||
using NLog.Web;
|
||||
using server.src;
|
||||
|
||||
// Early init of NLog to allow startup and exception logging, before host is built
|
||||
var logger = NLog.LogManager.Setup()
|
||||
|
@ -36,9 +38,7 @@ try
|
|||
// Configure Newtonsoft.Json options here
|
||||
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
||||
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
|
||||
});
|
||||
|
||||
// Add CORS policy
|
||||
}); // Add CORS policy
|
||||
if (builder.Environment.IsDevelopment())
|
||||
{
|
||||
builder.Services.AddCors(options =>
|
||||
|
@ -56,10 +56,7 @@ try
|
|||
.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
);
|
||||
});
|
||||
|
||||
// Add Swagger
|
||||
builder.Services.AddControllers();
|
||||
}); // Add Swagger
|
||||
builder.Services.AddOpenApiDocument(options =>
|
||||
{
|
||||
options.PostProcess = document =>
|
||||
|
@ -81,8 +78,10 @@ try
|
|||
// Url = "https://example.com/license"
|
||||
// }
|
||||
};
|
||||
};
|
||||
});
|
||||
}; });
|
||||
// 添加 HTTP 视频流服务 - 使用简化的类型引用
|
||||
builder.Services.AddSingleton<HttpVideoStreamService>();
|
||||
builder.Services.AddHostedService(provider => provider.GetRequiredService<HttpVideoStreamService>());
|
||||
|
||||
// Application Settings
|
||||
var app = builder.Build();
|
||||
|
|
|
@ -22,9 +22,10 @@
|
|||
<PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.OpenApi" Version="1.6.23" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="NLog" Version="5.4.0" />
|
||||
<PackageReference Include="NLog" Version="5.4.0" />
|
||||
<PackageReference Include="NLog.Web.AspNetCore" Version="5.4.0" />
|
||||
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.10" />
|
||||
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.119" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
|
@ -0,0 +1,115 @@
|
|||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace server.src.Controllers; /// <summary>
|
||||
/// HTTP 视频流控制器
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class VideoStreamController : ControllerBase
|
||||
{ private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
private readonly server.src.HttpVideoStreamService _videoStreamService; /// <summary>
|
||||
/// 初始化HTTP视频流控制器
|
||||
/// </summary>
|
||||
/// <param name="videoStreamService">HTTP视频流服务</param>
|
||||
public VideoStreamController(server.src.HttpVideoStreamService videoStreamService)
|
||||
{
|
||||
logger.Info("创建VideoStreamController,命名空间:{Namespace}", this.GetType().Namespace);
|
||||
_videoStreamService = videoStreamService;
|
||||
} /// <summary>
|
||||
/// 获取 HTTP 视频流服务状态
|
||||
/// </summary>
|
||||
/// <returns>服务状态信息</returns>
|
||||
[HttpGet("Status")]
|
||||
[EnableCors("Users")]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)] public IResult GetStatus()
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.Info("GetStatus方法被调用,控制器:{Controller},路径:api/VideoStream/Status", this.GetType().Name);
|
||||
|
||||
// 使用HttpVideoStreamService提供的状态信息
|
||||
var status = _videoStreamService.GetServiceStatus();
|
||||
|
||||
// 转换为小写首字母的JSON属性(符合前端惯例)
|
||||
return TypedResults.Ok(new
|
||||
{
|
||||
isRunning = true, // HTTP视频流服务作为后台服务始终运行
|
||||
serverPort = _videoStreamService.ServerPort,
|
||||
streamUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-feed.html",
|
||||
mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream",
|
||||
snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot",
|
||||
connectedClients = _videoStreamService.ConnectedClientsCount,
|
||||
clientEndpoints = _videoStreamService.GetConnectedClientEndpoints()
|
||||
});
|
||||
} catch (Exception ex)
|
||||
{
|
||||
logger.Error(ex, "获取 HTTP 视频流服务状态失败"); return TypedResults.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 HTTP 视频流信息
|
||||
/// </summary>
|
||||
/// <returns>流信息</returns>
|
||||
[HttpGet("StreamInfo")]
|
||||
[EnableCors("Users")]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||
public IResult GetStreamInfo()
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.Info("获取 HTTP 视频流信息");
|
||||
return TypedResults.Ok(new
|
||||
{
|
||||
frameRate = _videoStreamService.FrameRate,
|
||||
frameWidth = _videoStreamService.FrameWidth,
|
||||
frameHeight = _videoStreamService.FrameHeight,
|
||||
format = "MJPEG",
|
||||
htmlUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-feed.html",
|
||||
mjpegUrl = $"http://localhost:{_videoStreamService.ServerPort}/video-stream",
|
||||
snapshotUrl = $"http://localhost:{_videoStreamService.ServerPort}/snapshot"
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.Error(ex, "获取 HTTP 视频流信息失败"); return TypedResults.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 测试 HTTP 视频流连接
|
||||
/// </summary>
|
||||
/// <returns>连接测试结果</returns>
|
||||
[HttpPost("TestConnection")]
|
||||
[EnableCors("Users")]
|
||||
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(Exception), StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IResult> TestConnection()
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.Info("测试 HTTP 视频流连接");
|
||||
|
||||
// 尝试通过HTTP请求检查视频流服务是否可访问
|
||||
using (var httpClient = new HttpClient())
|
||||
{
|
||||
httpClient.Timeout = TimeSpan.FromSeconds(2); // 设置较短的超时时间
|
||||
var response = await httpClient.GetAsync($"http://localhost:{_videoStreamService.ServerPort}/");
|
||||
|
||||
// 只要能连接上就认为成功,不管返回状态
|
||||
bool isConnected = response.IsSuccessStatusCode;
|
||||
|
||||
return TypedResults.Ok(isConnected);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.Error(ex, "HTTP 视频流连接测试失败");
|
||||
// 连接失败但不抛出异常,而是返回连接失败的结果
|
||||
return TypedResults.Ok(false);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,583 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using System.Text;
|
||||
|
||||
namespace server.src
|
||||
{
|
||||
/// <summary>
|
||||
/// HTTP 视频流服务,用于从 FPGA 获取图像数据并推送到前端网页
|
||||
/// 简化版本实现,先建立基础框架
|
||||
/// </summary>
|
||||
public class HttpVideoStreamService : BackgroundService
|
||||
{
|
||||
private readonly ILogger<HttpVideoStreamService> _logger;
|
||||
private HttpListener? _httpListener;
|
||||
private readonly int _serverPort = 8080;
|
||||
private readonly int _frameRate = 30; // 30 FPS
|
||||
private readonly int _frameWidth = 640;
|
||||
private readonly int _frameHeight = 480;
|
||||
|
||||
// 模拟 FPGA 图像数据
|
||||
private int _frameCounter = 0;
|
||||
private readonly List<HttpListenerResponse> _activeClients = new List<HttpListenerResponse>();
|
||||
private readonly object _clientsLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前连接的客户端数量
|
||||
/// </summary>
|
||||
public int ConnectedClientsCount
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_clientsLock)
|
||||
{
|
||||
return _activeClients.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取服务端口
|
||||
/// </summary>
|
||||
public int ServerPort => _serverPort;
|
||||
|
||||
/// <summary>
|
||||
/// 获取帧宽度
|
||||
/// </summary>
|
||||
public int FrameWidth => _frameWidth;
|
||||
|
||||
/// <summary>
|
||||
/// 获取帧高度
|
||||
/// </summary>
|
||||
public int FrameHeight => _frameHeight;
|
||||
|
||||
/// <summary>
|
||||
/// 获取帧率
|
||||
/// </summary>
|
||||
public int FrameRate => _frameRate;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化 HttpVideoStreamService
|
||||
/// </summary>
|
||||
/// <param name="logger">日志记录器</param>
|
||||
public HttpVideoStreamService(ILogger<HttpVideoStreamService> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行 HTTP 视频流服务
|
||||
/// </summary>
|
||||
/// <param name="stoppingToken">取消令牌</param>
|
||||
/// <returns>任务</returns>
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("启动 HTTP 视频流服务,端口: {Port}", _serverPort);
|
||||
// 创建 HTTP 监听器
|
||||
_httpListener = new HttpListener();
|
||||
_httpListener.Prefixes.Add($"http://localhost:{_serverPort}/");
|
||||
_httpListener.Start();
|
||||
|
||||
_logger.LogInformation("HTTP 视频流服务已启动,监听端口: {Port}", _serverPort);
|
||||
|
||||
// 开始接受客户端连接
|
||||
_ = Task.Run(() => AcceptClientsAsync(stoppingToken), stoppingToken);
|
||||
|
||||
// 开始生成视频帧
|
||||
await GenerateVideoFrames(stoppingToken);
|
||||
}
|
||||
catch (HttpListenerException ex)
|
||||
{
|
||||
_logger.LogError(ex, "HTTP 视频流服务启动失败,请确保您有管理员权限或使用netsh配置URL前缀权限");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "HTTP 视频流服务启动失败");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcceptClientsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested && _httpListener != null && _httpListener.IsListening)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 等待客户端连接
|
||||
var context = await _httpListener.GetContextAsync();
|
||||
var request = context.Request;
|
||||
var response = context.Response;
|
||||
|
||||
_logger.LogInformation("新HTTP客户端连接: {RemoteEndPoint}", request.RemoteEndPoint);
|
||||
// 处理不同的请求路径
|
||||
var requestPath = request.Url?.AbsolutePath ?? "/";
|
||||
|
||||
if (requestPath == "/video-stream")
|
||||
{
|
||||
// MJPEG 流请求
|
||||
_ = Task.Run(() => HandleMjpegStreamAsync(response, cancellationToken), cancellationToken);
|
||||
}
|
||||
else if (requestPath == "/snapshot")
|
||||
{
|
||||
// 单帧图像请求
|
||||
await HandleSnapshotRequestAsync(response, cancellationToken);
|
||||
}
|
||||
else if (requestPath == "/video-feed.html")
|
||||
{
|
||||
// HTML页面请求
|
||||
await SendVideoHtmlPageAsync(response);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 默认返回简单的HTML页面,提供链接到视频页面
|
||||
await SendIndexHtmlPageAsync(response);
|
||||
}
|
||||
}
|
||||
catch (HttpListenerException)
|
||||
{
|
||||
// HTTP监听器可能已停止
|
||||
break;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// 对象可能已被释放
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "接受HTTP客户端连接时发生错误");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleMjpegStreamAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 设置MJPEG流的响应头
|
||||
response.ContentType = "multipart/x-mixed-replace; boundary=--boundary";
|
||||
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
response.Headers.Add("Pragma", "no-cache");
|
||||
response.Headers.Add("Expires", "0");
|
||||
|
||||
// 跟踪活跃的客户端
|
||||
lock (_clientsLock)
|
||||
{
|
||||
_activeClients.Add(response);
|
||||
}
|
||||
|
||||
_logger.LogDebug("已启动MJPEG流,客户端: {RemoteEndPoint}", response.OutputStream?.GetHashCode() ?? 0);
|
||||
|
||||
// 保持连接直到取消或出错
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(100, cancellationToken); // 简单的保活循环
|
||||
}
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
// 预期的取消
|
||||
}
|
||||
|
||||
_logger.LogDebug("MJPEG流已结束,客户端: {ClientId}", response.OutputStream?.GetHashCode() ?? 0);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "处理MJPEG流时出错");
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_clientsLock)
|
||||
{
|
||||
_activeClients.Remove(response);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略关闭时的错误
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleSnapshotRequestAsync(HttpListenerResponse response, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 获取当前帧
|
||||
var imageData = await GetFPGAImageData();
|
||||
var jpegData = ConvertToJpeg(imageData);
|
||||
|
||||
// 设置响应头
|
||||
response.ContentType = "image/jpeg";
|
||||
response.ContentLength64 = jpegData.Length;
|
||||
response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
|
||||
// 发送JPEG数据
|
||||
await response.OutputStream.WriteAsync(jpegData, 0, jpegData.Length, cancellationToken);
|
||||
await response.OutputStream.FlushAsync(cancellationToken);
|
||||
|
||||
_logger.LogDebug("已发送快照图像,大小:{Size} 字节", jpegData.Length);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "处理快照请求时出错");
|
||||
}
|
||||
finally
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendVideoHtmlPageAsync(HttpListenerResponse response)
|
||||
{
|
||||
string html = $@"<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>FPGA 视频流</title>
|
||||
<meta charset=""utf-8"">
|
||||
<style>
|
||||
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
||||
h1 {{ color: #333; }}
|
||||
.video-container {{ margin: 20px auto; max-width: 800px; }}
|
||||
.controls {{ margin: 10px 0; }}
|
||||
img {{ max-width: 100%; border: 1px solid #ddd; }}
|
||||
button {{ padding: 8px 16px; margin: 0 5px; cursor: pointer; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>FPGA 实时视频流</h1>
|
||||
<div class=""video-container"">
|
||||
<img id=""videoStream"" src=""/video-stream"" alt=""FPGA视频流"" />
|
||||
</div>
|
||||
<div class=""controls"">
|
||||
<button onclick=""document.getElementById('videoStream').src='/snapshot?t=' + new Date().getTime()"">刷新快照</button>
|
||||
<button onclick=""document.getElementById('videoStream').src='/video-stream'"">开始流媒体</button>
|
||||
<span id=""status"">状态: 连接中...</span>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('videoStream').onload = function() {{
|
||||
document.getElementById('status').textContent = '状态: 已连接';
|
||||
}};
|
||||
document.getElementById('videoStream').onerror = function() {{
|
||||
document.getElementById('status').textContent = '状态: 连接错误';
|
||||
}};
|
||||
</script>
|
||||
</body>
|
||||
</html>";
|
||||
|
||||
response.ContentType = "text/html";
|
||||
response.ContentEncoding = Encoding.UTF8;
|
||||
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
||||
response.ContentLength64 = buffer.Length;
|
||||
|
||||
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
||||
response.Close();
|
||||
}
|
||||
|
||||
private async Task SendIndexHtmlPageAsync(HttpListenerResponse response)
|
||||
{
|
||||
string html = $@"<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>FPGA WebLab 视频服务</title>
|
||||
<meta charset=""utf-8"">
|
||||
<style>
|
||||
body {{ font-family: Arial, sans-serif; text-align: center; margin: 20px; }}
|
||||
h1 {{ color: #333; }}
|
||||
.links {{ margin: 20px; }}
|
||||
a {{ padding: 10px 15px; background-color: #4CAF50; color: white; text-decoration: none; border-radius: 4px; margin: 5px; display: inline-block; }}
|
||||
a:hover {{ background-color: #45a049; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>FPGA WebLab 视频服务</h1>
|
||||
<div class=""links"">
|
||||
<a href=""/video-feed.html"">观看实时视频</a>
|
||||
<a href=""/snapshot"" target=""_blank"">获取当前快照</a>
|
||||
</div>
|
||||
<p>HTTP流媒体服务端口: {_serverPort}</p>
|
||||
</body>
|
||||
</html>";
|
||||
|
||||
response.ContentType = "text/html";
|
||||
response.ContentEncoding = Encoding.UTF8;
|
||||
byte[] buffer = Encoding.UTF8.GetBytes(html);
|
||||
response.ContentLength64 = buffer.Length;
|
||||
|
||||
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
|
||||
response.Close();
|
||||
}
|
||||
|
||||
private async Task GenerateVideoFrames(CancellationToken cancellationToken)
|
||||
{
|
||||
var frameInterval = TimeSpan.FromMilliseconds(1000.0 / _frameRate);
|
||||
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 从 FPGA 获取图像数据(模拟)
|
||||
var imageData = await GetFPGAImageData();
|
||||
|
||||
// 将图像数据转换为 JPEG
|
||||
var jpegData = ConvertToJpeg(imageData);
|
||||
|
||||
// 向所有连接的客户端发送帧
|
||||
await BroadcastFrameAsync(jpegData, cancellationToken);
|
||||
|
||||
_frameCounter++;
|
||||
|
||||
// 等待下一帧
|
||||
await Task.Delay(frameInterval, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "生成视频帧时发生错误");
|
||||
await Task.Delay(1000, cancellationToken); // 错误恢复延迟
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模拟从 FPGA 获取图像数据的函数
|
||||
/// 实际实现时,这里应该通过 UDP 连接读取 FPGA 特定地址范围的数据
|
||||
/// </summary>
|
||||
private async Task<byte[]> GetFPGAImageData()
|
||||
{
|
||||
// 模拟异步 FPGA 数据读取
|
||||
await Task.Delay(1);
|
||||
|
||||
// 简化的模拟图像数据生成
|
||||
var random = new Random(_frameCounter);
|
||||
var imageData = new byte[_frameWidth * _frameHeight * 3]; // RGB24 格式
|
||||
|
||||
// 生成简单的彩色噪声图案
|
||||
for (int i = 0; i < imageData.Length; i += 3)
|
||||
{
|
||||
// 基于帧计数器和位置生成颜色
|
||||
var baseColor = (_frameCounter + i / 3) % 256;
|
||||
imageData[i] = (byte)((baseColor + random.Next(0, 50)) % 256); // R
|
||||
imageData[i + 1] = (byte)((baseColor * 2 + random.Next(0, 50)) % 256); // G
|
||||
imageData[i + 2] = (byte)((baseColor * 3 + random.Next(0, 50)) % 256); // B
|
||||
}
|
||||
|
||||
if (_frameCounter % 30 == 0) // 每秒更新一次日志
|
||||
{
|
||||
_logger.LogDebug("生成第 {FrameNumber} 帧", _frameCounter);
|
||||
}
|
||||
|
||||
return imageData;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 RGB 图像数据转换为 JPEG 格式
|
||||
/// </summary>
|
||||
private byte[] ConvertToJpeg(byte[] rgbData)
|
||||
{
|
||||
using var image = new Image<Rgb24>(_frameWidth, _frameHeight);
|
||||
|
||||
// 将 RGB 数据复制到 ImageSharp 图像
|
||||
for (int y = 0; y < _frameHeight; y++)
|
||||
{
|
||||
for (int x = 0; x < _frameWidth; x++)
|
||||
{
|
||||
int index = (y * _frameWidth + x) * 3;
|
||||
var pixel = new Rgb24(rgbData[index], rgbData[index + 1], rgbData[index + 2]);
|
||||
image[x, y] = pixel;
|
||||
}
|
||||
}
|
||||
|
||||
using var stream = new MemoryStream();
|
||||
image.SaveAsJpeg(stream, new JpegEncoder { Quality = 80 });
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 向所有连接的客户端广播帧数据
|
||||
/// </summary>
|
||||
private async Task BroadcastFrameAsync(byte[] frameData, CancellationToken cancellationToken)
|
||||
{
|
||||
if (frameData == null || frameData.Length == 0)
|
||||
{
|
||||
_logger.LogWarning("尝试广播空帧数据");
|
||||
return;
|
||||
}
|
||||
|
||||
// 准备MJPEG帧数据
|
||||
var mjpegFrameHeader = $"--boundary\r\nContent-Type: image/jpeg\r\nContent-Length: {frameData.Length}\r\n\r\n";
|
||||
var headerBytes = Encoding.ASCII.GetBytes(mjpegFrameHeader);
|
||||
|
||||
var clientsToRemove = new List<HttpListenerResponse>();
|
||||
var clientsToProcess = new List<HttpListenerResponse>();
|
||||
|
||||
// 获取当前连接的客户端列表
|
||||
lock (_clientsLock)
|
||||
{
|
||||
clientsToProcess.AddRange(_activeClients);
|
||||
}
|
||||
|
||||
if (clientsToProcess.Count == 0)
|
||||
{
|
||||
return; // 没有活跃客户端
|
||||
}
|
||||
|
||||
// 向每个活跃的客户端发送帧
|
||||
foreach (var client in clientsToProcess)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 发送帧头部
|
||||
await client.OutputStream.WriteAsync(headerBytes, 0, headerBytes.Length, cancellationToken);
|
||||
|
||||
// 发送JPEG数据
|
||||
await client.OutputStream.WriteAsync(frameData, 0, frameData.Length, cancellationToken);
|
||||
|
||||
// 发送结尾换行符
|
||||
await client.OutputStream.WriteAsync(Encoding.ASCII.GetBytes("\r\n"), 0, 2, cancellationToken);
|
||||
|
||||
// 确保数据立即发送
|
||||
await client.OutputStream.FlushAsync(cancellationToken);
|
||||
|
||||
if (_frameCounter % 30 == 0) // 每秒记录一次日志
|
||||
{
|
||||
_logger.LogDebug("已向客户端 {ClientId} 发送第 {FrameNumber} 帧,大小:{Size} 字节",
|
||||
client.OutputStream.GetHashCode(), _frameCounter, frameData.Length);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug("发送帧数据时出错: {Error}", ex.Message);
|
||||
clientsToRemove.Add(client);
|
||||
}
|
||||
}
|
||||
|
||||
// 移除断开连接的客户端
|
||||
if (clientsToRemove.Count > 0)
|
||||
{
|
||||
lock (_clientsLock)
|
||||
{
|
||||
foreach (var client in clientsToRemove)
|
||||
{
|
||||
_activeClients.Remove(client);
|
||||
try { client.Close(); }
|
||||
catch { /* 忽略关闭错误 */ }
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("已移除 {Count} 个断开连接的客户端,当前连接数: {ActiveCount}",
|
||||
clientsToRemove.Count, _activeClients.Count);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取连接的客户端端点列表
|
||||
/// </summary>
|
||||
public List<string> GetConnectedClientEndpoints()
|
||||
{
|
||||
List<string> endpoints = new List<string>();
|
||||
|
||||
lock (_clientsLock)
|
||||
{
|
||||
foreach (var client in _activeClients)
|
||||
{
|
||||
endpoints.Add($"Client-{client.OutputStream?.GetHashCode() ?? 0}");
|
||||
}
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取服务状态信息
|
||||
/// </summary>
|
||||
public object GetServiceStatus()
|
||||
{
|
||||
return new
|
||||
{
|
||||
IsRunning = _httpListener?.IsListening ?? false,
|
||||
ServerPort = _serverPort,
|
||||
FrameRate = _frameRate,
|
||||
Resolution = $"{_frameWidth}x{_frameHeight}",
|
||||
ConnectedClients = ConnectedClientsCount,
|
||||
ClientEndpoints = GetConnectedClientEndpoints()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止 HTTP 视频流服务
|
||||
/// </summary>
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("正在停止 HTTP 视频流服务...");
|
||||
|
||||
if (_httpListener != null && _httpListener.IsListening)
|
||||
{
|
||||
_httpListener.Stop();
|
||||
_httpListener.Close();
|
||||
}
|
||||
|
||||
// 关闭所有客户端连接
|
||||
lock (_clientsLock)
|
||||
{
|
||||
foreach (var client in _activeClients)
|
||||
{
|
||||
try { client.Close(); }
|
||||
catch { /* 忽略关闭错误 */ }
|
||||
}
|
||||
_activeClients.Clear();
|
||||
}
|
||||
|
||||
await base.StopAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("HTTP 视频流服务已停止");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放资源
|
||||
/// </summary>
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_httpListener != null)
|
||||
{
|
||||
if (_httpListener.IsListening)
|
||||
{
|
||||
_httpListener.Stop();
|
||||
}
|
||||
_httpListener.Close();
|
||||
}
|
||||
|
||||
lock (_clientsLock)
|
||||
{
|
||||
foreach (var client in _activeClients)
|
||||
{
|
||||
try { client.Close(); }
|
||||
catch { /* 忽略关闭错误 */ }
|
||||
}
|
||||
_activeClients.Clear();
|
||||
}
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
141
src/APIClient.ts
141
src/APIClient.ts
|
@ -2189,3 +2189,144 @@ function throwException(message: string, status: number, response: string, heade
|
|||
else
|
||||
throw new ApiException(message, status, response, headers, null);
|
||||
}
|
||||
|
||||
// VideoStreamClient - 手动添加,用于HTTP视频流控制
|
||||
export class VideoStreamClient {
|
||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||
private baseUrl: string;
|
||||
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
||||
|
||||
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
||||
this.http = http ? http : window as any;
|
||||
this.baseUrl = baseUrl ?? "http://localhost:5000";
|
||||
} /**
|
||||
* 获取HTTP视频流服务状态
|
||||
* @return HTTP视频流服务状态信息
|
||||
*/
|
||||
status(): Promise<any> {
|
||||
let url_ = this.baseUrl + "/api/VideoStream/Status";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processStatus(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processStatus(response: Response): Promise<any> {
|
||||
const status = response.status;
|
||||
let _headers: any = {};
|
||||
if (response.headers && response.headers.forEach) {
|
||||
response.headers.forEach((v: any, k: any) => _headers[k] = v);
|
||||
}
|
||||
|
||||
if (status === 200) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result200: any = null;
|
||||
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||
return result200;
|
||||
});
|
||||
} else if (status === 500) {
|
||||
return response.text().then((_responseText) => {
|
||||
throw new Error(_responseText);
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
throw new Error("未知的响应状态码: " + status + ", 响应文本: " + _responseText);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<any>(null as any);
|
||||
} /**
|
||||
* 获取HTTP视频流信息
|
||||
* @return HTTP视频流信息
|
||||
*/
|
||||
streamInfo(): Promise<any> {
|
||||
let url_ = this.baseUrl + "/api/VideoStream/StreamInfo";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processStreamInfo(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processStreamInfo(response: Response): Promise<any> {
|
||||
const status = response.status;
|
||||
let _headers: any = {};
|
||||
if (response.headers && response.headers.forEach) {
|
||||
response.headers.forEach((v: any, k: any) => _headers[k] = v);
|
||||
}
|
||||
|
||||
if (status === 200) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result200: any = null;
|
||||
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||
return result200;
|
||||
});
|
||||
} else if (status === 500) {
|
||||
return response.text().then((_responseText) => {
|
||||
throw new Error(_responseText);
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
throw new Error("未知的响应状态码: " + status + ", 响应文本: " + _responseText);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<any>(null as any);
|
||||
} /**
|
||||
* 测试HTTP视频流连接
|
||||
* @return 测试结果
|
||||
*/
|
||||
testConnection(): Promise<boolean> {
|
||||
let url_ = this.baseUrl + "/api/VideoStream/TestConnection";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processTestConnection(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processTestConnection(response: Response): Promise<boolean> {
|
||||
const status = response.status;
|
||||
let _headers: any = {};
|
||||
if (response.headers && response.headers.forEach) {
|
||||
response.headers.forEach((v: any, k: any) => _headers[k] = v);
|
||||
}
|
||||
|
||||
if (status === 200) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result200: any = null;
|
||||
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||
return result200;
|
||||
});
|
||||
} else if (status === 500) {
|
||||
return response.text().then((_responseText) => {
|
||||
throw new Error(_responseText);
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
throw new Error("未知的响应状态码: " + status + ", 响应文本: " + _responseText);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<boolean>(false);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -39,8 +39,7 @@
|
|||
</svg>
|
||||
工程界面
|
||||
</router-link>
|
||||
</li>
|
||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||
</li> <li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||
<router-link to="/test" class="text-base font-medium">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2">
|
||||
|
@ -49,6 +48,14 @@
|
|||
测试功能
|
||||
</router-link>
|
||||
</li>
|
||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||
<router-link to="/video-stream" class="text-base font-medium">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2">
|
||||
<path d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"></path>
|
||||
</svg>
|
||||
HTTP视频流 </router-link>
|
||||
</li>
|
||||
<li class="my-1 hover:translate-x-1 transition-all duration-300">
|
||||
<router-link to="/markdown-test" class="text-base font-medium">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 opacity-70" viewBox="0 0 24 24" fill="none"
|
||||
|
|
|
@ -6,6 +6,7 @@ import ProjectView from '../views/ProjectView.vue'
|
|||
import TestView from '../views/TestView.vue'
|
||||
import UserView from '../views/UserView.vue'
|
||||
import AdminView from '../views/AdminView.vue'
|
||||
import VideoStreamView from '../views/VideoStreamView.vue'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
|
@ -16,7 +17,7 @@ const router = createRouter({
|
|||
{path: '/project',name: 'project',component: ProjectView},
|
||||
{path: '/test', name: 'test', component: TestView},
|
||||
{path: '/user', name: 'user', component: UserView},
|
||||
{path: '/admin', name: 'admin', component: AdminView}]
|
||||
{path: '/admin', name: 'admin', component: AdminView}, {path: '/video-stream',name: 'video-stream',component: VideoStreamView}]
|
||||
})
|
||||
|
||||
export default router
|
||||
|
|
|
@ -0,0 +1,505 @@
|
|||
<template>
|
||||
<div class="min-h-screen bg-base-100">
|
||||
<!-- 标题栏 -->
|
||||
<div class="bg-base-200 p-4 border-b border-base-300">
|
||||
<h1 class="text-2xl font-bold text-base-content">HTTP 视频流</h1>
|
||||
<p class="text-base-content/70 mt-1">FPGA WebLab 视频流传输功能</p>
|
||||
</div>
|
||||
|
||||
<div class="container mx-auto p-6 space-y-6">
|
||||
<!-- 控制面板 -->
|
||||
<div class="card bg-base-200 shadow-xl">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-primary">
|
||||
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4"/>
|
||||
</svg>
|
||||
控制面板
|
||||
</h2>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<!-- 服务状态 -->
|
||||
<div class="stats shadow">
|
||||
<div class="stat">
|
||||
<div class="stat-figure text-primary">
|
||||
<div class="badge" :class="statusInfo.isRunning ? 'badge-success' : 'badge-error'">
|
||||
{{ statusInfo.isRunning ? '运行中' : '已停止' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-title">服务状态</div>
|
||||
<div class="stat-value text-primary">HTTP</div>
|
||||
<div class="stat-desc">端口: {{ statusInfo.serverPort }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 流信息 -->
|
||||
<div class="stats shadow">
|
||||
<div class="stat">
|
||||
<div class="stat-figure text-secondary">
|
||||
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-title">视频规格</div>
|
||||
<div class="stat-value text-secondary">{{ streamInfo.frameWidth }}×{{ streamInfo.frameHeight }}</div>
|
||||
<div class="stat-desc">{{ streamInfo.frameRate }} FPS</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 连接数 -->
|
||||
<div class="stats shadow">
|
||||
<div class="stat">
|
||||
<div class="stat-figure text-accent">
|
||||
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="stat-title">连接数</div>
|
||||
<div class="stat-value text-accent">{{ statusInfo.connectedClients }}</div>
|
||||
<div class="stat-desc">
|
||||
<div class="dropdown dropdown-hover">
|
||||
<div tabindex="0" role="button" class="text-xs underline cursor-help">查看客户端</div>
|
||||
<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52">
|
||||
<li v-for="(client, index) in statusInfo.clientEndpoints" :key="index" class="text-xs">
|
||||
<a>{{ client }}</a>
|
||||
</li>
|
||||
<li v-if="!statusInfo.clientEndpoints || statusInfo.clientEndpoints.length === 0">
|
||||
<a class="text-xs opacity-50">无活跃连接</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="card-actions justify-end mt-4">
|
||||
<button
|
||||
class="btn btn-outline btn-primary"
|
||||
@click="refreshStatus"
|
||||
:disabled="loading"
|
||||
>
|
||||
<svg v-if="loading" class="animate-spin h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
{{ loading ? '刷新中...' : '刷新状态' }}
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-primary"
|
||||
@click="testConnection"
|
||||
:disabled="testing"
|
||||
>
|
||||
<svg v-if="testing" class="animate-spin h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||
<path class="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
{{ testing ? '测试中...' : '测试连接' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 视频预览区域 -->
|
||||
<div class="card bg-base-200 shadow-xl">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-primary">
|
||||
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/>
|
||||
</svg>
|
||||
视频预览
|
||||
</h2>
|
||||
|
||||
<div class="relative bg-black rounded-lg overflow-hidden" style="aspect-ratio: 4/3;">
|
||||
<!-- 视频播放器 - 使用img标签直接显示MJPEG流 -->
|
||||
<div v-show="isPlaying" class="w-full h-full flex items-center justify-center">
|
||||
<img
|
||||
:src="currentVideoSource"
|
||||
alt="视频流"
|
||||
class="max-w-full max-h-full object-contain"
|
||||
@error="handleVideoError"
|
||||
@load="handleVideoLoad"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 错误信息显示 -->
|
||||
<div v-if="hasVideoError" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70">
|
||||
<div class="card bg-error text-white shadow-lg w-full max-w-lg">
|
||||
<div class="card-body">
|
||||
<h3 class="card-title flex items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||
</svg>
|
||||
视频流加载失败
|
||||
</h3>
|
||||
<p>无法连接到视频服务器,请检查以下内容:</p>
|
||||
<ul class="list-disc list-inside">
|
||||
<li>视频流服务是否已启动</li>
|
||||
<li>网络连接是否正常</li>
|
||||
<li>端口 {{ statusInfo.serverPort }} 是否可访问</li>
|
||||
</ul>
|
||||
<div class="card-actions justify-end mt-2">
|
||||
<button class="btn btn-sm btn-outline btn-primary" @click="tryReconnect">重试连接</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 占位符 -->
|
||||
<div
|
||||
v-show="!isPlaying && !hasVideoError"
|
||||
class="absolute inset-0 flex items-center justify-center text-white"
|
||||
>
|
||||
<div class="text-center">
|
||||
<svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/>
|
||||
</svg>
|
||||
<p class="text-lg opacity-75">{{ videoStatus }}</p>
|
||||
<p class="text-sm opacity-60 mt-2">点击"播放视频流"按钮开始查看实时视频</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 视频控制 -->
|
||||
<div class="flex justify-between items-center mt-4">
|
||||
<div class="text-sm text-base-content/70">
|
||||
流地址: <code class="bg-base-300 px-2 py-1 rounded">{{ streamInfo.mjpegUrl }}</code>
|
||||
</div>
|
||||
<div class="space-x-2">
|
||||
<div class="dropdown dropdown-hover dropdown-top dropdown-end">
|
||||
<div tabindex="0" role="button" class="btn btn-sm btn-outline btn-accent">
|
||||
<svg class="w-4 h-4 mr-1" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
更多功能
|
||||
</div>
|
||||
<ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-200 rounded-box w-52">
|
||||
<li><a @click="openInNewTab(streamInfo.htmlUrl)">在新标签打开视频页面</a></li>
|
||||
<li><a @click="takeSnapshot">获取并下载快照</a></li>
|
||||
<li><a @click="copyToClipboard(streamInfo.mjpegUrl)">复制MJPEG地址</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<button
|
||||
class="btn btn-success btn-sm"
|
||||
@click="startStream"
|
||||
:disabled="isPlaying"
|
||||
>
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
播放视频流
|
||||
</button>
|
||||
<button
|
||||
class="btn btn-error btn-sm"
|
||||
@click="stopStream"
|
||||
:disabled="!isPlaying"
|
||||
>
|
||||
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"/>
|
||||
</svg>
|
||||
停止视频流
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日志区域 -->
|
||||
<div class="card bg-base-200 shadow-xl">
|
||||
<div class="card-body">
|
||||
<h2 class="card-title text-primary">
|
||||
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
|
||||
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
操作日志
|
||||
</h2>
|
||||
|
||||
<div class="bg-base-300 rounded-lg p-4 h-48 overflow-y-auto">
|
||||
<div v-for="(log, index) in logs" :key="index" class="text-sm font-mono mb-1">
|
||||
<span class="text-base-content/50">[{{ formatTime(log.time) }}]</span>
|
||||
<span :class="getLogClass(log.level)">{{ log.message }}</span>
|
||||
</div>
|
||||
<div v-if="logs.length === 0" class="text-base-content/50 text-center py-8">
|
||||
暂无日志记录
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-actions justify-end mt-2">
|
||||
<button class="btn btn-outline btn-sm" @click="clearLogs">
|
||||
清空日志
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import { VideoStreamClient } from '@/APIClient'
|
||||
|
||||
// 状态管理
|
||||
const loading = ref(false)
|
||||
const testing = ref(false)
|
||||
const isPlaying = ref(false)
|
||||
const hasVideoError = ref(false)
|
||||
const videoStatus = ref('点击"播放视频流"按钮开始查看实时视频')
|
||||
|
||||
// 数据
|
||||
const statusInfo = ref({
|
||||
isRunning: false,
|
||||
serverPort: 8080,
|
||||
streamUrl: '',
|
||||
mjpegUrl: '',
|
||||
snapshotUrl: '',
|
||||
connectedClients: 0,
|
||||
clientEndpoints: [] as string[]
|
||||
})
|
||||
|
||||
const streamInfo = ref({
|
||||
frameRate: 30,
|
||||
frameWidth: 640,
|
||||
frameHeight: 480,
|
||||
format: 'MJPEG',
|
||||
htmlUrl: '',
|
||||
mjpegUrl: '',
|
||||
snapshotUrl: ''
|
||||
})
|
||||
|
||||
const currentVideoSource = ref('')
|
||||
const logs = ref<Array<{time: Date, level: string, message: string}>>([])
|
||||
|
||||
// API 客户端
|
||||
const videoClient = new VideoStreamClient()
|
||||
|
||||
// 添加日志
|
||||
const addLog = (level: string, message: string) => {
|
||||
logs.value.push({
|
||||
time: new Date(),
|
||||
level,
|
||||
message
|
||||
})
|
||||
// 限制日志数量
|
||||
if (logs.value.length > 100) {
|
||||
logs.value.shift()
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化时间
|
||||
const formatTime = (time: Date) => {
|
||||
return time.toLocaleTimeString()
|
||||
}
|
||||
|
||||
// 获取日志样式
|
||||
const getLogClass = (level: string) => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-error'
|
||||
case 'warning': return 'text-warning'
|
||||
case 'success': return 'text-success'
|
||||
default: return 'text-base-content'
|
||||
}
|
||||
}
|
||||
|
||||
// 清空日志
|
||||
const clearLogs = () => {
|
||||
logs.value = []
|
||||
addLog('info', '日志已清空')
|
||||
}
|
||||
|
||||
// 复制到剪贴板
|
||||
const copyToClipboard = (text: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
.then(() => {
|
||||
addLog('success', '已复制到剪贴板');
|
||||
})
|
||||
.catch((err) => {
|
||||
addLog('error', `复制失败: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
// 在新标签中打开视频页面
|
||||
const openInNewTab = (url: string) => {
|
||||
window.open(url, '_blank');
|
||||
addLog('info', `已在新标签打开视频页面: ${url}`);
|
||||
}
|
||||
|
||||
// 获取并下载快照
|
||||
const takeSnapshot = async () => {
|
||||
try {
|
||||
addLog('info', '正在获取快照...');
|
||||
|
||||
// 使用当前的快照URL
|
||||
const snapshotUrl = streamInfo.value.snapshotUrl;
|
||||
if (!snapshotUrl) {
|
||||
addLog('error', '快照URL不可用');
|
||||
return;
|
||||
}
|
||||
|
||||
// 添加时间戳防止缓存
|
||||
const urlWithTimestamp = `${snapshotUrl}?t=${new Date().getTime()}`;
|
||||
|
||||
// 创建一个临时链接下载图片
|
||||
const a = document.createElement('a');
|
||||
a.href = urlWithTimestamp;
|
||||
a.download = `fpga-snapshot-${new Date().toISOString().replace(/:/g, '-')}.jpg`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
|
||||
addLog('success', '快照已下载');
|
||||
} catch (error) {
|
||||
addLog('error', `获取快照失败: ${error}`);
|
||||
console.error('获取快照失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 刷新状态
|
||||
const refreshStatus = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
addLog('info', '正在获取服务状态...')
|
||||
|
||||
const status = await videoClient.status()
|
||||
statusInfo.value = status
|
||||
|
||||
const info = await videoClient.streamInfo()
|
||||
streamInfo.value = info
|
||||
|
||||
addLog('success', '服务状态获取成功')
|
||||
} catch (error) {
|
||||
addLog('error', `获取状态失败: ${error}`)
|
||||
console.error('获取状态失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 测试连接
|
||||
const testConnection = async () => {
|
||||
testing.value = true
|
||||
try {
|
||||
addLog('info', '正在测试视频流连接...')
|
||||
|
||||
const result = await videoClient.testConnection()
|
||||
|
||||
if (result) {
|
||||
addLog('success', '视频流连接测试成功')
|
||||
} else {
|
||||
addLog('error', '视频流连接测试失败')
|
||||
}
|
||||
} catch (error) {
|
||||
addLog('error', `连接测试失败: ${error}`)
|
||||
console.error('连接测试失败:', error)
|
||||
} finally {
|
||||
testing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 视频错误处理
|
||||
const handleVideoError = () => {
|
||||
if (isPlaying.value) {
|
||||
hasVideoError.value = true
|
||||
addLog('error', '视频流加载失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 视频加载成功处理
|
||||
const handleVideoLoad = () => {
|
||||
hasVideoError.value = false
|
||||
addLog('success', '视频流加载成功')
|
||||
}
|
||||
|
||||
// 尝试重新连接
|
||||
const tryReconnect = () => {
|
||||
addLog('info', '尝试重新连接视频流...')
|
||||
hasVideoError.value = false
|
||||
|
||||
// 重新设置视频源,添加时间戳避免缓存问题
|
||||
currentVideoSource.value = `${streamInfo.value.mjpegUrl}?t=${new Date().getTime()}`
|
||||
}
|
||||
|
||||
// 启动视频流
|
||||
const startStream = async () => {
|
||||
try {
|
||||
addLog('info', '正在启动视频流...')
|
||||
videoStatus.value = '正在连接视频流...'
|
||||
|
||||
// 刷新状态
|
||||
await refreshStatus()
|
||||
|
||||
// 设置视频源
|
||||
currentVideoSource.value = streamInfo.value.mjpegUrl
|
||||
|
||||
// 设置播放状态
|
||||
isPlaying.value = true
|
||||
hasVideoError.value = false
|
||||
|
||||
addLog('success', '视频流已启动')
|
||||
} catch (error) {
|
||||
addLog('error', `启动视频流失败: ${error}`)
|
||||
videoStatus.value = '启动视频流失败'
|
||||
console.error('启动视频流失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 停止视频流
|
||||
const stopStream = () => {
|
||||
try {
|
||||
addLog('info', '正在停止视频流...')
|
||||
|
||||
// 清除视频源
|
||||
currentVideoSource.value = ''
|
||||
|
||||
// 更新状态
|
||||
isPlaying.value = false
|
||||
hasVideoError.value = false
|
||||
videoStatus.value = '点击"播放视频流"按钮开始查看实时视频'
|
||||
|
||||
addLog('success', '视频流已停止')
|
||||
} catch (error) {
|
||||
addLog('error', `停止视频流失败: ${error}`)
|
||||
console.error('停止视频流失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 生命周期
|
||||
onMounted(async () => {
|
||||
addLog('info', 'HTTP 视频流页面已加载')
|
||||
await refreshStatus()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
stopStream()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 自定义样式 */
|
||||
.stats {
|
||||
background-color: var(--b1);
|
||||
color: var(--bc); /* 添加适配文本颜色 */
|
||||
}
|
||||
|
||||
code {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
img {
|
||||
/* 确保视频流居中显示 */
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
* {
|
||||
transition: all 500ms ease-in-out;
|
||||
}
|
||||
</style>
|
Loading…
Reference in New Issue