Fix Linux MVS frame ABI by packaging the matching vendor binding

This commit is contained in:
sophelper 2026-11-08 20:14:15 +08:00
parent d3317a0cb2
commit 102fea1a9b
14 changed files with 329 additions and 11 deletions

1
.gitignore vendored
View File

@ -390,6 +390,7 @@ FodyWeavers.xsd
# 海康 MVS 托管 SDK 随项目提供;原生运行时由现场安装。
!/libs/
!/libs/MvCameraControl.Net.dll
!/libs/mvs/linux-x64/MvCameraControl.Net.dll
/libs/cuda/
/models

View File

@ -58,5 +58,6 @@ dotnet run --project tests/Avalonia.Smoke -c Release
2026-11-08:Windows 本地上述自动检查通过,Windows/Linux 发布构建通过。
本轮没有更新远端部署,也没有在 Linux 真机验收此统一版的 GUI、相机、标注或训练。
Linux 海康通过原生库名映射接入 `libMvCameraControl.so`;仍需匹配版本的 MVS 和相机硬件验证,
不能把成功交叉编译等同于海康硬件功能已通过。
Linux 海康使用 MVS 4.9 Linux 自带的 netstandard2.0 封装,并通过原生库名映射接入 `libMvCameraControl.so`。
2026-11-08 已在 LH-GC10-HS500 上验证 2448×2048 BayerRG8 转 BGR、归还缓冲和断开后重开。
Windows 继续使用原 Windows SDK;两平台应用和采集服务代码相同,仅供应商 SDK 绑定不同。

View File

@ -17,7 +17,7 @@ PYTHON=python3.12 bash tools/Setup-Python.sh /absolute/application/directory --s
相机接口、模型和 YAML 配方逻辑与 Windows 来自同一套源码。UVC 使用 V4L2;
海康需要匹配的 Linux MVS,并根据 SDK 安装位置设置 `MVS_LIB_DIR`、`LD_LIBRARY_PATH`。
Linux 的实际海康采集与标注训练尚待真机验收。
Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注训练仍待真机验收。
## 后续部署

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,15 @@
# Linux MVS managed binding
`MvCameraControl.Net.dll` is the vendor's x64/netstandard2.0 binding shipped with
Linux MVS 4.9.0.3, obtained from the user's installed SDK at
`/opt/MVS/Samples/64/C#/Dotnet/x64/netstandard2.0/MvCameraControl.Net.dll`.
SHA256: `952CB2ECABF397A117DB3E108DDAEEBB0E018B42B26265A3D1E33EE6B17E5912`.
The Windows binding in `libs/MvCameraControl.Net.dll` must not be reused on Linux:
its frame structure layout produces zero dimensions and an invalid buffer length
with Linux MVS 4.9. Both targets retain the same application/camera service source;
only the vendor SDK binding and native runtime differ.
Verified on 2026-11-08: LH-GC10-HS500, BayerRG8, 2448×2048; acquisition, BGR conversion,
buffer release and reopening the device passed against the installed Linux runtime.

View File

@ -9,9 +9,13 @@
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<!-- These two views are created by DI with constructor parameters, never by a runtime XAML URI. -->
<NoWarn>$(NoWarn);AVLN3001</NoWarn>
<NativePlatform Condition="'$(NativePlatform)' == '' and $([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('linux'))">Linux</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == '' and $([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('win'))">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" AdditionalProperties="NativePlatform=$(NativePlatform)" />
<PackageReference Include="Prism.DryIoc.Avalonia" Version="9.0.537.11130" />
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.22" />

View File

@ -17,7 +17,7 @@ internal static class MvsNativeBindings
}
private static IntPtr Resolve(string name,Assembly assembly,DllImportSearchPath? searchPath)
{
if(name!="MvCameraControl.dll")return IntPtr.Zero;
if(name!="MvCameraControl.dll"&&name!="MvCameraControl"&&name!="libMvCameraControl.so")return IntPtr.Zero;
var configured=Environment.GetEnvironmentVariable("MVS_LIB_DIR");
var candidates=new List<string>();
if(!string.IsNullOrWhiteSpace(configured))candidates.Add(Path.Combine(configured,"libMvCameraControl.so"));

View File

@ -9,11 +9,13 @@
<NativePlatform Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('win'))">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
<MvsManagedSdk Condition="'$(NativePlatform)' == 'Linux'">../../libs/mvs/linux-x64/MvCameraControl.Net.dll</MvsManagedSdk>
<MvsManagedSdk Condition="'$(MvsManagedSdk)' == ''">../../libs/MvCameraControl.Net.dll</MvsManagedSdk>
</PropertyGroup>
<ItemGroup>
<Compile Include="../SopHelper.Engine/**/*.cs" Exclude="../SopHelper.Engine/obj/**;../SopHelper.Engine/bin/**;../SopHelper.Engine/Camera/UvcCameraService.cs" Link="Engine/%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="*.cs" />
<Reference Include="MvCameraControl.Net"><HintPath>../../libs/MvCameraControl.Net.dll</HintPath><Private>true</Private></Reference>
<Reference Include="MvCameraControl.Net"><HintPath>$(MvsManagedSdk)</HintPath><Private>true</Private></Reference>
<PackageReference Include="OpenCvSharp4" Version="4.13.0.20260627" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.13.0.20260627" Condition="'$(NativePlatform)' == 'Windows'" />
<PackageReference Include="OpenCvSharp4.official.runtime.linux-x64" Version="4.13.0.20260627" Condition="'$(NativePlatform)' == 'Linux'" />

View File

@ -181,6 +181,8 @@ public sealed class HikvisionCameraService : ICameraService
private static Mat CopyBgr(IDevice device, IImage image)
{
if (image.Width == 0 || image.Height == 0 || image.Width > int.MaxValue || image.Height > int.MaxValue || image.PixelDataPtr == IntPtr.Zero)
throw new InvalidDataException($"海康返回无效帧尺寸 {image.Width}×{image.Height},请检查当前平台的托管 SDK 与原生运行库是否配套");
if (image.PixelType == MvGvspPixelType.PixelType_Gvsp_BGR8_Packed)
{
using var view = Mat.FromPixelData((int)image.Height, (int)image.Width, MatType.CV_8UC3, image.PixelDataPtr);
@ -197,7 +199,7 @@ public sealed class HikvisionCameraService : ICameraService
var result = device.PixelTypeConverter.ConvertPixelType(image, out var converted, MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
using (converted)
{
Check(result, "转换海康像素格式");
Check(result, $"转换海康像素格式({image.Width}×{image.Height},{image.PixelType})");
if (converted is null) throw new InvalidOperationException("海康像素转换未返回图像");
using var view = Mat.FromPixelData((int)converted.Height, (int)converted.Width, MatType.CV_8UC3, converted.PixelDataPtr);
return view.Clone(); // 深拷贝后才能释放 SDK 图像。
@ -250,6 +252,13 @@ public sealed class HikvisionCameraService : ICameraService
if (result != MvError.MV_OK) throw new InvalidOperationException($"{operation}失败(0x{result:X8})");
}
private void Report(Exception ex) => Error?.Invoke(
$"海康相机:{ex.Message}。请确认已安装 MVS 4.5 或以上的 x64 运行时,设备已连接且未被其他程序占用。");
private void Report(Exception ex)
{
var detail = ex is DllNotFoundException or BadImageFormatException or EntryPointNotFoundException
? "请检查 MVS 原生运行库、架构和 SDK 版本是否匹配。"
: "请根据上面的具体错误检查相机连接、占用状态及 SDK 兼容性。";
var message = $"海康相机:{ex.Message}。{detail}";
Console.Error.WriteLine(message);
Error?.Invoke(message);
}
}

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
<Reference Include="MvCameraControl.Net">
<HintPath Condition="'$(NativePlatform)' == 'Linux'">../../libs/mvs/linux-x64/MvCameraControl.Net.dll</HintPath>
<HintPath Condition="'$(NativePlatform)' != 'Linux'">../../libs/MvCameraControl.Net.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,54 @@
using MvCameraControl;
using SopHelper.Engine.Camera;
try
{
using var camera=new HikvisionCameraService();
var errors=new List<string>();
camera.Error+=message=>{errors.Add(message);Console.Error.WriteLine(message);};
Console.WriteLine("SDK: "+SDKSystem.GetSDKVersion());
var cameras=await camera.EnumerateAsync();
foreach(var device in cameras)Console.WriteLine($"DEVICE: {device.Name}");
if(errors.Count>0)throw new Exception("Camera enumeration reported an error");
Console.WriteLine($"PASS: SDK initialized and enumerated {cameras.Count} camera(s)");
if(args.Contains("--inspect-frame"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);
if(result!=MvError.MV_OK||infos.Count==0)throw new Exception("Enumeration failed");
using var device=DeviceFactory.CreateDevice(infos[0]);
Console.WriteLine($"OPEN: 0x{device.Open():X8}");
device.Parameters.SetEnumValueByString("TriggerMode","Off");
try
{
Console.WriteLine($"START: 0x{device.StreamGrabber.StartGrabbing():X8}");
result=device.StreamGrabber.GetImageBuffer(3000,out var buffer);
Console.WriteLine($"GET: 0x{result:X8}");
if(result==MvError.MV_OK)
{
try
{
foreach(var p in typeof(IImage).GetProperties().Where(p=>p.Name!="PixelData"))Console.WriteLine($"IMAGE {p.Name}: {p.GetValue(buffer.Image)}");
result=device.PixelTypeConverter.ConvertPixelType(buffer.Image,out var converted,MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
using(converted)Console.WriteLine($"CONVERT: 0x{result:X8}");
}
finally{device.StreamGrabber.FreeImageBuffer(buffer);}
}
}
finally{device.StreamGrabber.StopGrabbing();device.Close();}
}
if(args.Contains("--hardware"))
{
var device=cameras.FirstOrDefault()??throw new Exception("No camera found");
var ready=new TaskCompletionSource<(int W,int H)>(TaskCreationOptions.RunContinuationsAsynchronously);
var frames=0;
camera.FrameArrived+=frame=>{if(Interlocked.Increment(ref frames)>=5)ready.TrySetResult((frame.Bgr.Width,frame.Bgr.Height));};
if(!await camera.ConnectAsync(device)||!await camera.StartAsync())throw new Exception("Open/start failed");
var frame=await ready.Task.WaitAsync(TimeSpan.FromSeconds(10));
camera.Disconnect();
Console.WriteLine($"PASS: acquired {frames} {frame.W}x{frame.H} BGR frames and released camera");
if(!await camera.ConnectAsync(device))throw new Exception("Camera could not reopen after disconnect");
camera.Disconnect();Console.WriteLine("PASS: camera reopened after release");
}
return 0;
}
catch(Exception error){Console.Error.WriteLine(error);return 1;}

View File

@ -6,8 +6,12 @@ if ($Target -notmatch '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]+$') { throw 'Target must
$repo = Split-Path $PSScriptRoot -Parent
$release = 'avalonia-' + (Get-Date -Format 'yyyyMMdd-HHmmss')
$output = Join-Path $repo "artifacts/$release"
& dotnet publish (Join-Path $repo 'src/SopHelper.Avalonia') -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=false -o $output --nologo
& dotnet publish (Join-Path $repo 'src/SopHelper.Avalonia') -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=false -p:NativePlatform=Linux -o $output --nologo
if ($LASTEXITCODE) { throw 'Publish failed' }
$sdkExpected=Join-Path $repo 'libs/mvs/linux-x64/MvCameraControl.Net.dll'
if ((Get-FileHash $sdkExpected).Hash -ne (Get-FileHash (Join-Path $output 'MvCameraControl.Net.dll')).Hash) {
throw 'Linux package contains the wrong MVS managed binding'
}
$archive = Join-Path $repo "artifacts/$release.tar.gz"
& tar -czf $archive -C $output .
if ($LASTEXITCODE) { throw 'Packaging failed' }

View File

@ -15,8 +15,13 @@ $manifest=@($sources | ForEach-Object { [ordered]@{path=[IO.Path]::GetRelativePa
$sourceJson=ConvertTo-Json -InputObject $manifest -Depth 5
foreach ($rid in @('win-x64','linux-x64')) {
$destination=Join-Path $OutputRoot $rid
& dotnet publish $project -c Release -r $rid --self-contained true -p:PublishSingleFile=false -o $destination --nologo
$nativePlatform=if($rid -eq 'win-x64'){'Windows'}else{'Linux'}
& dotnet publish $project -c Release -r $rid --self-contained true -p:PublishSingleFile=false "-p:NativePlatform=$nativePlatform" -o $destination --nologo
if ($LASTEXITCODE) { throw "Publish failed: $rid" }
$sdkSource=if($rid -eq 'linux-x64'){'libs/mvs/linux-x64/MvCameraControl.Net.dll'}else{'libs/MvCameraControl.Net.dll'}
if ((Get-FileHash (Join-Path $repo $sdkSource)).Hash -ne (Get-FileHash (Join-Path $destination 'MvCameraControl.Net.dll')).Hash) {
throw "Wrong vendor MVS binding in $rid package"
}
[IO.File]::WriteAllText((Join-Path $destination 'source-manifest.json'),$sourceJson,[Text.UTF8Encoding]::new($false))
if ($rid -eq 'win-x64' -and !$SkipPython) {
$runtime=Join-Path $repo 'python'