Compare commits

..

1 commit

Author SHA1 Message Date
de077ca5d5 Add detailed analysis and documentation for RSNet.dll download functionality
- Introduced a comprehensive markdown document outlining the API surface of RSNet.dll related to downloading video files.
- Documented initialization, connection, record querying, and download processes.
- Provided insights into the exported functions, their parameters, and expected behaviors.
- Included practical implications and recommendations for implementing a downloader script using C# interop.
- Highlighted the necessary struct layouts and callback mechanisms for effective integration with the DLL.
2026-04-17 21:19:46 +02:00
91 changed files with 2084 additions and 4082 deletions

6
.github/copilot-instructions.md vendored Normal file
View file

@ -0,0 +1,6 @@
# Repository Instructions
- When using Ghidra MCP tools in this repository, do not run destructive actions unless the user explicitly asks for them.
- Treat these actions as destructive and forbidden by default during analysis: deleting functions, deleting data, patching bytes, applying edit plans that remove or overwrite program structures, or any other write operation that changes binary semantics.
- During analysis, allowed write actions are limited to renaming functions or data and adding comments.
- Prefer read-only inspection first. If a write action seems necessary beyond renames/comments, stop and ask the user before proceeding.

17
.vscode/launch.json vendored
View file

@ -1,17 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Surveillance Client",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build Surveillance Client",
"program": "${workspaceFolder}/managed-client/src/Surveillance.Client.App/bin/x64/Debug/net10.0/Surveillance.Client.App.dll",
"args": [],
"cwd": "${workspaceFolder}/managed-client",
"console": "internalConsole",
"stopAtEntry": false,
"justMyCode": true
}
]
}

9
.vscode/mcp.json vendored Normal file
View file

@ -0,0 +1,9 @@
{
"servers": {
"ghidra-web": {
"url": "http://127.0.0.1:8081/sse",
"type": "http"
}
},
"inputs": []
}

25
.vscode/tasks.json vendored
View file

@ -1,25 +0,0 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build Surveillance Client",
"type": "process",
"command": "dotnet",
"args": [
"build",
"src/Surveillance.Client.App/Surveillance.Client.App.csproj",
"--configuration",
"Debug",
"-p:Platform=x64"
],
"options": {
"cwd": "${workspaceFolder}/managed-client"
},
"problemMatcher": "$msCompile",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

BIN
RSNet.dll Normal file

Binary file not shown.

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<FILE_INFO>
<BASIC_INFO>
<STATE NAME="CONTENT_TYPE" TYPE="string" VALUE="Program" />
<STATE NAME="PARENT" TYPE="string" VALUE="/" />
<STATE NAME="FILE_ID" TYPE="string" VALUE="c0a86451d8fa89550806671100" />
<STATE NAME="FILE_TYPE" TYPE="int" VALUE="0" />
<STATE NAME="READ_ONLY" TYPE="boolean" VALUE="false" />
<STATE NAME="NAME" TYPE="string" VALUE="RSNet.dll" />
</BASIC_INFO>
</FILE_INFO>

Binary file not shown.

Binary file not shown.

View file

@ -1,4 +1,6 @@
VERSION=1 VERSION=1
/ /
NEXT-ID:0 00000001:RSNet.dll:c0a86451d8fa89550806671100
00000000:Surveillance_client.exe:c0a86480f39a29301594652600
NEXT-ID:2
MD5:d41d8cd98f00b204e9800998ecf8427e MD5:d41d8cd98f00b204e9800998ecf8427e

View file

@ -1,5 +1,6 @@
VERSION=1 VERSION=1
/ /
00000001:RSNet.dll:c0a86451d8fa89550806671100
00000000:Surveillance_client.exe:c0a86480f39a29301594652600 00000000:Surveillance_client.exe:c0a86480f39a29301594652600
NEXT-ID:1 NEXT-ID:2
MD5:d41d8cd98f00b204e9800998ecf8427e MD5:d41d8cd98f00b204e9800998ecf8427e

View file

@ -1,2 +0,0 @@
IADD:00000000:/Surveillance_client.exe
IDSET:/Surveillance_client.exe:c0a86480f39a29301594652600

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<FILE_INFO>
<BASIC_INFO>
<STATE NAME="CONTENT_TYPE" TYPE="string" VALUE="ProgramUserData" />
<STATE NAME="PARENT" TYPE="string" VALUE="/" />
<STATE NAME="FILE_ID" TYPE="string" VALUE="c0a86451e45f97977061057400" />
<STATE NAME="FILE_TYPE" TYPE="int" VALUE="0" />
<STATE NAME="READ_ONLY" TYPE="boolean" VALUE="false" />
<STATE NAME="NAME" TYPE="string" VALUE="udf_c0a86451d8fa89550806671100" />
</BASIC_INFO>
</FILE_INFO>

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,2 @@
IADD:00000001:/udf_c0a86451d8fa89550806671100
IDSET:/udf_c0a86451d8fa89550806671100:c0a86451e45f97977061057400

74
SurveillanceClient/.gitignore vendored Normal file
View file

@ -0,0 +1,74 @@
# Build results
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# User-specific files
*.user
*.suo
*.userosscache
*.sln.docstates
*.rsuser
# Visual Studio
.vs/
*.VisualState.xml
*.pidb
*.svclog
# JetBrains Rider
.idea/
*.DotSettings.user
# VS Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# NuGet
*.nupkg
*.snupkg
.nuget/
packages/
!packages/build/
project.lock.json
project.fragment.lock.json
artifacts/
# MSBuild Binary and Structured Log
*.binlog
# ReSharper
_ReSharper*/
*.[Rr]e[Ss]harper
# Test results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
coverage*.json
coverage*.xml
coverage*.info
# Local secrets / configuration overrides (NEVER COMMIT CREDENTIALS)
appsettings.Development.json
appsettings.Local.json
appsettings.*.Local.json
secrets.json
secrets.*.json
*.secrets
.env
.env.*
# OS
Thumbs.db
ehthumbs.db
Desktop.ini
.DS_Store
# Downloaded video output (local runtime artifact)
downloads/
output/

View file

@ -0,0 +1,14 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Required by source-generated P/Invoke (LibraryImport). -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- RSNet.dll is 32-bit (x86). Consumers of the native interop must run as x86. -->
<PlatformTarget>x86</PlatformTarget>
<Platforms>x86</Platforms>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,62 @@
# SurveillanceClient
.NET 10 host for driving the vendor `RSNet.dll` (32-bit) to download
recorded video from a surveillance NVR/DVR.
## Layout
- `src/SurveillanceClient.Core` — class library that wraps the `RSNet.dll`
native exports behind a service interface (`IRsNetClient`).
- `src/SurveillanceClient.Cli` — console host used for iterative,
manual testing of the Core library against a real device.
## Platform
`RSNet.dll` is a 32-bit Visual Studio DLL using `__stdcall`. Every
project in this solution targets `x86` via `Directory.Build.props`.
## Running
The vendor DLL and its dependencies live in
`i:\Apps\Surveillance_client`. The CLI sets that directory as the
native DLL search path at startup so the DLL and its `.ini` config
are found.
## Credentials
Credentials are **never committed**. Configure them via .NET user
secrets (recommended) or a `appsettings.Local.json` file (ignored by
`.gitignore`).
### User secrets (recommended)
```powershell
cd src/SurveillanceClient.Cli
dotnet user-secrets set "Device:Host" "192.168.100.92"
dotnet user-secrets set "Device:Port" "9000"
dotnet user-secrets set "Device:Username" "admin"
dotnet user-secrets set "Device:Password" "your-password-here"
```
### appsettings.Local.json (alternative)
Create `src/SurveillanceClient.Cli/appsettings.Local.json`:
```json
{
"Device": {
"Host": "192.168.100.92",
"Port": 9000,
"Username": "admin",
"Password": "your-password-here"
}
}
```
## Build / Run
```powershell
cd SurveillanceClient
dotnet build
dotnet run --project src/SurveillanceClient.Cli
```

View file

@ -0,0 +1,11 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/SurveillanceClient.Core/SurveillanceClient.Core.csproj" />
<Project Path="src/SurveillanceClient.Cli/SurveillanceClient.Cli.csproj" />
</Folder>
<Folder Name="/solution-items/">
<File Path=".gitignore" />
<File Path="Directory.Build.props" />
<File Path="README.md" />
</Folder>
</Solution>

View file

@ -0,0 +1,37 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SurveillanceClient.Cli;
using SurveillanceClient.Core;
var builder = Host.CreateApplicationBuilder(args);
// Local, never-committed overrides for credentials etc.
builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: false);
if (builder.Environment.IsDevelopment())
{
builder.Configuration.AddUserSecrets<Program>(optional: true);
}
builder.Services.AddSurveillanceClientCore();
builder.Services.AddHostedService<TestHarness>();
using var host = builder.Build();
try
{
await host.RunAsync();
}
catch (Exception ex)
{
host.Services.GetRequiredService<ILogger<Program>>()
.LogCritical(ex, "Unhandled exception");
return 1;
}
return 0;
/// <summary>Marker type used to anchor user-secrets and logger categories.</summary>
public partial class Program;

View file

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>SurveillanceClient.Cli</RootNamespace>
<AssemblyName>SurveillanceClient.Cli</AssemblyName>
<IsPackable>false</IsPackable>
<UserSecretsId>surveillance-client-cli-4f0a1c0d</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SurveillanceClient.Core\SurveillanceClient.Core.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,87 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SurveillanceClient.Core.Configuration;
using SurveillanceClient.Core.Services;
namespace SurveillanceClient.Cli;
/// <summary>
/// Iterative manual-test harness. Runs once at startup against the
/// configured device, logs status callbacks, then requests shutdown.
/// Extended step-by-step as the native API is proven out.
/// </summary>
internal sealed class TestHarness : BackgroundService
{
private readonly ILogger<TestHarness> _logger;
private readonly IRsNetClient _client;
private readonly DeviceOptions _device;
private readonly IHostApplicationLifetime _lifetime;
public TestHarness(
ILogger<TestHarness> logger,
IRsNetClient client,
IOptions<DeviceOptions> device,
IHostApplicationLifetime lifetime)
{
_logger = logger;
_client = client;
_device = device.Value;
_lifetime = lifetime;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await RunAsync(stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// graceful shutdown
}
catch (Exception ex)
{
_logger.LogError(ex, "Test harness failed");
}
finally
{
_lifetime.StopApplication();
}
}
private async Task RunAsync(CancellationToken ct)
{
_logger.LogInformation("=== Stage 1: Initialize RSNet.dll ===");
await _client.InitializeAsync(ct).ConfigureAwait(false);
_logger.LogInformation("RSNet initialized successfully.");
if (string.IsNullOrWhiteSpace(_device.Host) ||
string.IsNullOrWhiteSpace(_device.Username))
{
_logger.LogWarning(
"Device credentials not configured. Set them via user-secrets or appsettings.Local.json " +
"to run the connection stage. Skipping connect.");
return;
}
_logger.LogInformation(
"=== Stage 2: Connect to {Host}:{Port} as {User} ===",
_device.Host, _device.Port, _device.Username);
using var session = _client.Connect(_device);
session.StatusChanged += (_, e) =>
_logger.LogInformation("Session status callback: code=0x{Code:X} ({CodeDec})", e.Code, e.Code);
_logger.LogInformation("Session handle: 0x{Handle:X}. Waiting up to 15s for login callbacks...",
session.Handle.ToInt64());
try
{
await Task.Delay(TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { }
_logger.LogInformation("=== Stage 2 complete. Stop here until login status codes are mapped. ===");
}
}

View file

@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Warning",
"SurveillanceClient": "Debug"
}
},
"RsNet": {
"NativeDirectory": "i:\\Apps\\Surveillance_client"
},
"Device": {
"Host": "",
"Port": 9000,
"Username": "",
"Password": ""
}
}

View file

@ -0,0 +1,15 @@
namespace SurveillanceClient.Core.Configuration;
/// <summary>
/// Credentials and endpoint for a target surveillance device.
/// Supplied via user secrets or local config — never committed.
/// </summary>
public sealed class DeviceOptions
{
public const string SectionName = "Device";
public string Host { get; set; } = string.Empty;
public ushort Port { get; set; } = 9000;
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}

View file

@ -0,0 +1,22 @@
namespace SurveillanceClient.Core.Configuration;
/// <summary>
/// Runtime options for locating and loading <c>RSNet.dll</c>.
/// </summary>
public sealed class RsNetOptions
{
public const string SectionName = "RsNet";
/// <summary>
/// Absolute path to the directory that contains <c>RSNet.dll</c>
/// and its companion files (e.g. <c>RSNet.ini</c>, P2P helpers).
/// Typically the vendor install directory.
/// </summary>
public string NativeDirectory { get; set; } = @"i:\Apps\Surveillance_client";
/// <summary>
/// Optional encryption value passed to <c>RSNetSetEncription</c>.
/// <c>null</c> skips the call.
/// </summary>
public uint? Encryption { get; set; }
}

View file

@ -0,0 +1,69 @@
using System.Runtime.InteropServices;
namespace SurveillanceClient.Core.Native;
/// <summary>
/// Raw P/Invoke bindings for <c>RSNet.dll</c>.
///
/// ABI notes (see docs/surveillance-client-rsnet-download-analysis.md):
/// <list type="bullet">
/// <item>Architecture: x86/32-bit. The host process MUST run as x86.</item>
/// <item>Calling convention: <c>StdCall</c> (callee cleans stack).</item>
/// <item>Strings: ANSI (<c>char*</c>), not UTF-16.</item>
/// </list>
///
/// Request structs are intentionally passed as opaque <see cref="IntPtr"/>
/// during the reverse-engineering phase. Strongly-typed wrappers may be
/// introduced as the native layouts are confirmed.
/// </summary>
internal static partial class RsNetNative
{
private const string Dll = "RSNet.dll";
[LibraryImport(Dll, StringMarshalling = StringMarshalling.Utf8)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial void RSNetInit();
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial void RSNetRelease();
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial void RSNetSetEncription(uint value);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial IntPtr RSNetConnectionStart(IntPtr request);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial IntPtr RSNetConnectionStartEx(IntPtr request);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial int RSNetQueryRecord(IntPtr session, IntPtr queryRequest);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial int RSNetQueryRecordEx(IntPtr session, IntPtr queryRequest);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial IntPtr RSNetStartDownloadRecord(IntPtr session, IntPtr downloadRequest);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial IntPtr RSNetStartDownloadRecordEx(IntPtr session, IntPtr downloadRequest);
[LibraryImport(Dll)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])]
internal static partial void RSNetReqRecordData(IntPtr recordPlayHandle);
/// <summary>
/// Session/status callback dispatched by the DLL's login/worker thread.
/// Exact signature is provisional — see the analysis doc.
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void RsNetStatusCallback(uint code, IntPtr userContext);
}

View file

@ -0,0 +1,34 @@
using System.Runtime.InteropServices;
namespace SurveillanceClient.Core.Native;
/// <summary>
/// Provisional layout for <c>RSNetConnectionStart</c>'s request struct.
///
/// Based on decompilation of the copy-in path inside RSNet.dll:
/// <list type="bullet">
/// <item>+0x00 pointer to ANSI address string</item>
/// <item>+0x04 16-bit port</item>
/// <item>+0x08 pointer to ANSI username string</item>
/// <item>+0x0C pointer to ANSI password string</item>
/// <item>+0x10..+0x28 misc 32-bit fields (mode/callback-related)</item>
/// </list>
///
/// This is NOT fully validated. Treat as a best-effort starting point.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct RsNetConnectRequest
{
public IntPtr AddressAnsi;
public ushort Port;
public ushort Padding0;
public IntPtr UsernameAnsi;
public IntPtr PasswordAnsi;
public uint Field10;
public uint Field14;
public uint Field18;
public uint Field1C;
public uint Field20;
public uint Field24;
public uint Field28;
}

View file

@ -0,0 +1,26 @@
using System.Runtime.InteropServices;
namespace SurveillanceClient.Core.Native;
/// <summary>
/// Win32 entry points used to control the native DLL search path before
/// loading <c>RSNet.dll</c>. The vendor DLL expects its install directory
/// on the search path so it can find <c>RSNet.ini</c> and helper binaries.
/// </summary>
internal static partial class Win32
{
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool SetDllDirectoryW(string? lpPathName);
[LibraryImport("kernel32.dll", SetLastError = true)]
internal static partial IntPtr AddDllDirectory(
[MarshalAs(UnmanagedType.LPWStr)] string NewDirectory);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static partial bool SetDefaultDllDirectories(uint DirectoryFlags);
internal const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000;
internal const uint LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400;
}

View file

@ -0,0 +1,27 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SurveillanceClient.Core.Configuration;
using SurveillanceClient.Core.Services;
namespace SurveillanceClient.Core;
/// <summary>
/// DI registration helpers for the SurveillanceClient Core services.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Registers <see cref="IRsNetClient"/> and binds its options from
/// configuration. The client is a singleton because <c>RSNet.dll</c>
/// holds process-wide global state.
/// </summary>
public static IServiceCollection AddSurveillanceClientCore(this IServiceCollection services)
{
services.AddOptions<RsNetOptions>().BindConfiguration(RsNetOptions.SectionName);
services.AddOptions<DeviceOptions>().BindConfiguration(DeviceOptions.SectionName);
services.TryAddSingleton<IRsNetClient, RsNetClient>();
return services;
}
}

View file

@ -0,0 +1,46 @@
using SurveillanceClient.Core.Configuration;
namespace SurveillanceClient.Core.Services;
/// <summary>
/// High-level, managed facade over <c>RSNet.dll</c>. Intended lifetime:
/// singleton per process. <see cref="InitializeAsync"/> must be called
/// before any session is opened.
/// </summary>
public interface IRsNetClient : IAsyncDisposable
{
/// <summary>Whether <c>RSNetInit</c> has been called successfully.</summary>
bool IsInitialized { get; }
/// <summary>
/// Loads <c>RSNet.dll</c> from the configured directory and calls
/// <c>RSNetInit</c>. Safe to call more than once; subsequent calls are no-ops.
/// </summary>
Task InitializeAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Opens a direct-IP session by calling <c>RSNetConnectionStart</c>.
/// The returned session has not yet necessarily completed login — the
/// DLL performs login asynchronously on a worker thread.
/// </summary>
IRsNetSession Connect(DeviceOptions device);
}
/// <summary>
/// Handle-bearing wrapper around a single <c>RSNet.dll</c> session.
/// Disposing closes the native session and releases any pinned buffers.
/// </summary>
public interface IRsNetSession : IDisposable
{
/// <summary>Native session handle returned by <c>RSNetConnectionStart</c>.</summary>
IntPtr Handle { get; }
/// <summary>Raised for each native status/event callback.</summary>
event EventHandler<RsNetStatusEventArgs>? StatusChanged;
}
/// <summary>Status event payload forwarded from the native callback.</summary>
public sealed class RsNetStatusEventArgs(uint code) : EventArgs
{
public uint Code { get; } = code;
}

View file

@ -0,0 +1,122 @@
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SurveillanceClient.Core.Configuration;
using SurveillanceClient.Core.Native;
namespace SurveillanceClient.Core.Services;
/// <inheritdoc cref="IRsNetClient"/>
internal sealed class RsNetClient : IRsNetClient
{
private readonly ILogger<RsNetClient> _logger;
private readonly RsNetOptions _options;
private readonly SemaphoreSlim _initLock = new(1, 1);
private bool _initialized;
private bool _disposed;
public RsNetClient(ILogger<RsNetClient> logger, IOptions<RsNetOptions> options)
{
_logger = logger;
_options = options.Value;
}
public bool IsInitialized => _initialized;
public async Task InitializeAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_initialized) return;
await _initLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_initialized) return;
if (!OperatingSystem.IsWindows())
throw new PlatformNotSupportedException("RSNet.dll is Windows-only.");
if (RuntimeInformation.ProcessArchitecture != Architecture.X86)
throw new PlatformNotSupportedException(
$"RSNet.dll is 32-bit (x86). Current process is {RuntimeInformation.ProcessArchitecture}. " +
"Build and run the host as x86.");
var dir = _options.NativeDirectory;
if (string.IsNullOrWhiteSpace(dir) || !Directory.Exists(dir))
throw new DirectoryNotFoundException(
$"RsNetOptions.NativeDirectory not found: '{dir}'. " +
"Configure it to the vendor install directory containing RSNet.dll.");
var dllPath = Path.Combine(dir, "RSNet.dll");
if (!File.Exists(dllPath))
throw new FileNotFoundException("RSNet.dll not found in NativeDirectory.", dllPath);
_logger.LogInformation("Configuring native DLL search path: {Directory}", dir);
// Use the modern search list so both RSNet.dll and its implicit
// dependencies are resolved from the vendor directory.
Win32.SetDefaultDllDirectories(
Win32.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | Win32.LOAD_LIBRARY_SEARCH_USER_DIRS);
Win32.AddDllDirectory(dir);
// Legacy fallback for any implicit LoadLibrary calls by RSNet.dll itself.
Win32.SetDllDirectoryW(dir);
// Many vendor DLLs read <Name>.ini from the *current* working directory
// rather than the DLL's own directory. Switch CWD so RSNet.ini resolves.
var previousCwd = Environment.CurrentDirectory;
Environment.CurrentDirectory = dir;
_logger.LogDebug("CWD changed {Previous} -> {New}", previousCwd, dir);
_logger.LogInformation("Calling RSNetInit()");
RsNetNative.RSNetInit();
if (_options.Encryption is { } enc)
{
_logger.LogInformation("Calling RSNetSetEncription({Value})", enc);
RsNetNative.RSNetSetEncription(enc);
}
_initialized = true;
}
finally
{
_initLock.Release();
}
}
public IRsNetSession Connect(DeviceOptions device)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_initialized)
throw new InvalidOperationException(
$"{nameof(RsNetClient)} is not initialized. Call InitializeAsync first.");
ArgumentException.ThrowIfNullOrWhiteSpace(device.Host);
ArgumentException.ThrowIfNullOrWhiteSpace(device.Username);
return RsNetSession.Open(_logger, device);
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
if (_initialized)
{
try
{
_logger.LogInformation("Calling RSNetRelease()");
RsNetNative.RSNetRelease();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "RSNetRelease threw during shutdown");
}
}
_initLock.Dispose();
await Task.CompletedTask;
}
}

View file

@ -0,0 +1,122 @@
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using SurveillanceClient.Core.Configuration;
using SurveillanceClient.Core.Native;
namespace SurveillanceClient.Core.Services;
/// <summary>
/// Owns a single <c>RSNetConnectionStart</c> session handle plus the
/// unmanaged buffers (ANSI strings, request struct) that the DLL reads
/// from during the asynchronous login worker's lifetime.
/// </summary>
internal sealed class RsNetSession : IRsNetSession
{
private readonly ILogger _logger;
private readonly List<IntPtr> _unmanagedAllocs = [];
private readonly RsNetNative.RsNetStatusCallback? _callback;
private IntPtr _handle;
private bool _disposed;
public IntPtr Handle => _handle;
public event EventHandler<RsNetStatusEventArgs>? StatusChanged;
private RsNetSession(ILogger logger, RsNetNative.RsNetStatusCallback callback)
{
_logger = logger;
_callback = callback;
}
internal static RsNetSession Open(ILogger logger, DeviceOptions device)
{
RsNetSession? session = null;
RsNetNative.RsNetStatusCallback callback = null!;
try
{
// The callback MUST be held by a managed field so the GC does not
// collect the thunk while the native worker still holds the pointer.
session = new RsNetSession(logger, (uint code, IntPtr ctx) =>
{
logger.LogDebug("RSNet status callback: code={Code} ctx={Ctx}", code, ctx);
session?.RaiseStatus(code);
});
callback = session._callback!;
var hostPtr = MarshalAnsi(session, device.Host);
var userPtr = MarshalAnsi(session, device.Username);
var passPtr = MarshalAnsi(session, device.Password);
var request = new RsNetConnectRequest
{
AddressAnsi = hostPtr,
Port = device.Port,
Padding0 = 0,
UsernameAnsi = userPtr,
PasswordAnsi = passPtr,
// Fields 0x10..0x28 are mode/callback-related and not yet
// fully validated. Leaving them zero matches the minimal
// direct-IP login path observed in Surveillance_client.exe.
};
var requestPtr = Marshal.AllocHGlobal(Marshal.SizeOf<RsNetConnectRequest>());
session._unmanagedAllocs.Add(requestPtr);
Marshal.StructureToPtr(request, requestPtr, fDeleteOld: false);
logger.LogInformation(
"RSNetConnectionStart host={Host} port={Port} user={User}",
device.Host, device.Port, device.Username);
var handle = RsNetNative.RSNetConnectionStart(requestPtr);
if (handle == IntPtr.Zero)
throw new InvalidOperationException("RSNetConnectionStart returned NULL.");
session._handle = handle;
return session;
}
catch
{
session?.Dispose();
GC.KeepAlive(callback);
throw;
}
}
private void RaiseStatus(uint code)
{
try
{
StatusChanged?.Invoke(this, new RsNetStatusEventArgs(code));
}
catch (Exception ex)
{
_logger.LogError(ex, "Status handler threw for code {Code}", code);
}
}
private static IntPtr MarshalAnsi(RsNetSession session, string? value)
{
var ptr = Marshal.StringToHGlobalAnsi(value ?? string.Empty);
session._unmanagedAllocs.Add(ptr);
return ptr;
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
// The exported stop-session API has not been positively identified in
// the current RSNet.dll symbol recovery (see analysis doc). For now
// we simply release native buffers and let RSNetRelease() at shutdown
// tear down session state. Once the stop export is confirmed, call it
// here with _handle before freeing buffers.
foreach (var p in _unmanagedAllocs)
{
if (p != IntPtr.Zero) Marshal.FreeHGlobal(p);
}
_unmanagedAllocs.Clear();
// Keep the callback alive until after native cleanup would have run.
GC.KeepAlive(_callback);
}
}

View file

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<RootNamespace>SurveillanceClient.Core</RootNamespace>
<AssemblyName>SurveillanceClient.Core</AssemblyName>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.0" />
</ItemGroup>
</Project>

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -1,187 +0,0 @@
# Live View and Recording Reimplementation Research
Date: 2026-10-16
## Goal
Assess a managed C# replacement for the minimum useful Surveillance Client workflows: persisted server credentials, one or more live camera views, and arbitrary recording-range downloads to MP4. Target .NET 10 and Avalonia for a possible Windows/macOS/Linux UI, and prefer FFmpeg for media decode, mux, and encode rather than the legacy playback DLL.
## Current Findings
### Native network API candidate
`RSNet.dll` is a native x86 PE library. REA's procedure-name search found an application-facing API surface that includes:
- Lifecycle and connection: `RSNetInit`, `RSNetRelease`, `RSNetConnectionStart`, `RSNetConnectionStartEx`, `RSNetConnectionStop`.
- Discovery and device configuration: `RSNetSearchDev`, `RSNetSetDevInfo`, `RSNetSetNewDevInfo`, `RSNetGetDevInfo`, `RSNetGetDevInfoEx`, `RSNetSetIPAndPort`.
- Live view: `RSNetStartPreview`, `RSNetStopPreview`, `RSNetGetPreviewBitRate`, `RSNetForceIFrame`.
- Recording search and retrieval: `RSNetQueryRecord`, async/Ex variants, `RSNetStartDownloadRecord` and `RSNetStartDownloadRecordEx`, record-playback controls, and `RSNetConnectionStop`.
- Additional functions include PTZ, audio talk, parameter queries, alarms, logs, upgrade, snapshot, and picture-download operations.
This is strong evidence that the installed network DLL contains useful operations for the requested feature set, but it is not yet a usable C# contract. Ghidra identifies the library as x86 and reports `RSNetConnectionStartEx` as `__stdcall` with an opaque integer argument and pointer-like return. The record-download Ex entry takes opaque pointer arguments. Its analyzed setup path allocates buffers, copies arrays with element sizes `0x1c` and `0x108`, then queues work with `QueueUserWorkItem`; the exact request structures, callback/event contract, ownership, and cancellation rules remain unresolved.
### Initial reuse recommendation
For a temporary Windows compatibility prototype, the x86 DLLs could live in a supervised x86 worker. For the requested managed multiplatform product, treat that only as a behavior oracle during reverse engineering, not as the final architecture. Keep protocol and media code managed/platform-neutral, and abstract credential storage behind per-OS secure stores; do not persist credentials in plaintext.
The presence of record query/download functions does not establish that the DLL emits a standard container or MP4. MP4 output should be treated as a separate remux/transcode stage until the downloaded bytes and codec/container contract are verified.
### Playback and MP4 boundary
`RSPlay.dll` is also x86. Its named procedure inventory includes play-instance create/destroy, window binding, `RSPlayInputNetFrame`, draw/decode callback registration, playback controls, and `RSPlay264ToAviStart/Stop`. The frame-input wrapper dispatches through an opaque instance vtable; the AVI conversion entry is another vtable dispatch and shares an address/name with `RSPlayConvertFileStart`. This is evidence of a native decode/render path and an AVI conversion path, not a documented managed ABI or proof of MP4 support. No MP4-named procedure appeared in the complete provider-defined procedure-name search for `RSPlay.dll`.
The bundled `hi_h264dec_w.dll` is x86 and exposes `Hi264DecCreate` and `Hi264DecFrame` names. Ghidra infers that creation accepts a pointer to an undocumented configuration structure and returns an opaque handle; the frame routine accepts seven low-level parameters. Avoid binding this decoder directly unless the SDK wrapper proves unusable.
For MP4, first capture the exact downloaded payload and inspect its codec, framing, timestamps, and audio. Then use a maintained FFmpeg-based remux when the source streams are compatible with MP4; transcode only when required. The legacy AVI conversion can be a compatibility fallback, not the preferred output path. Container behavior and whether arbitrary subranges can be cut without keyframe expansion remain runtime questions.
### P2P and initialization boundary
`RSNetInit` clears global state, derives the directory of the calling process, appends `\\RSNet.ini`, parses that file, and initializes Winsock 2.2. `RSNetInitLX2PPath` copies a caller-supplied path into global storage. The `RSNet.dll` string inventory includes `RSP2PClient.exe`, `RSP2PDaemon.exe`, and P2P/relay labels. These are static references; they do not prove which helper is launched or under what conditions.
The installation contains several vendor-specific P2P directories. The inspected `p2p/SY/PPCS_API.dll` has named initialize/connect/read/write/close/status procedures, but its connect entry aliases shared native code and the exact public parameter contract was not recovered. This makes it a potential provider-specific fallback, not a universal DVR transport. Prefer routing through `RSNet` unless testing establishes that direct use of a particular provider is necessary and supported.
### Main executable coverage
REA opened `Surveillance_client.exe` as an x86 PE with SHA-256 `dc6050f9c96fa68270b79b17d9c2127f0de4f3ddd3478a1c0c552134fff7de14`. The PE resource parser completed and identified a PE32 image. Ghidra's broad overview and focused procedure/string searches on this 10.8 MB executable timed out, including a sequential retry; therefore this pass does not establish the EXE's exact call sequence into `RSNet`/`RSPlay` or the import table. Existing DPI findings are recorded separately in [surveillance-client-dpi-analysis.md](surveillance-client-dpi-analysis.md): Qt 4-era widgets, no obvious static DPI-awareness logic, and persisted pixel geometry. A fresh managed UI should address DPI independently of the native worker.
## Managed Reimplementation Effort
### Bottom line
A .NET 10/Avalonia application is technically viable: Avalonia's upstream build currently targets `net10.0` across its desktop code ([target framework configuration](https://github.com/AvaloniaUI/Avalonia/blob/master/build/TargetFrameworks.props)). That establishes UI framework compatibility, not portability of this DVR's network protocol or the FFmpeg native binaries. FFmpeg can replace much of `RSPlay`'s decode/render and AVI conversion work; it cannot replace `RSNet`'s authentication, command protocol, recording index, or vendor P2P behavior.
The hardest work is discovering and reproducing the wire protocol and any P2P transport, not building the Avalonia screens or calling FFmpeg. REA found `RSNet` entry points that mostly forward opaque structures into internal stateful code. A record query snapshots session data, increments a shared request ID, coordinates through Windows event/critical-section machinery, and waits for a response with a 20-second timeout. The download path additionally allocates/copies native record arrays and queues asynchronous work. These behaviors need a managed protocol/state-machine design, not mechanical translation of export names.
### Planning estimate
Estimates are engineer-weeks for one experienced engineer, assuming access to a representative DVR and firmware. They are deliberately conditional: one successful original-client login and a bounded header-only capture are now observed, but managed-client authentication, live preview, recording, and the main executable's broad Ghidra analysis remain unverified.
| Scope | Effort | Assumptions |
|---|---:|---|
| Go/no-go discovery spike | 2-4 weeks | One device/firmware; establish credentials/auth, direct-LAN connection, one decodable live stream, record search, and a short export. |
| Limited MVP after a successful spike | 12-20 additional weeks | One device family, direct IP/TCP without vendor P2P, a standard H.264/H.265 plus optional AAC stream, agreed camera-count target, arbitrary range search/download, and MP4 output. |
| Add one P2P provider | 4-12+ additional weeks | Provider-specific protocol and relay behavior can be observed; vendor servers and credentials remain accessible. Could be blocked without a documented or observable protocol. |
| Reproduce broad RSNet/RSPlay feature parity | 24-52+ weeks | Includes non-requested surfaces such as PTZ, audio talk, alarms, parameter/config operations, upgrades, fisheye and legacy playback behaviors; excludes extensive multi-family certification. |
The spike plus limited MVP is roughly 14-24 engineer-weeks, or about 3.5-6 months for one full-time engineer. Allow at least +/-50% until a real connection and stream capture prove the framing, authentication, and time-range semantics. Each additional device/P2P family expands both implementation and certification; it is not safe to assume the named P2P DLLs share one protocol.
### What FFmpeg removes, and what it does not
- `RSPlay`'s H.264/H.265 decoding, frame conversion, audio decode, and AVI conversion can likely be replaced with FFmpeg plus Avalonia frame presentation. The RSNet-to-media packet framing, decryption, timestamps, and channel metadata still need to be understood before FFmpeg can consume the stream.
- Prefer stream-copy/remux for MP4 when downloaded packets use an MP4-compatible codec and carry usable timestamps. Transcode only when framing, codec, or timestamp constraints require it. Arbitrary range boundaries may need to expand to keyframes and then be trimmed/re-encoded for exact boundaries.
- Start with FFmpegCore, which drives the native FFmpeg executable through a C# process wrapper. Feed live media over redirected stdin/stdout pipes and use the same backend for MP4 exports; codec work still runs in native FFmpeg. The process boundary is not automatically a performance problem, but live latency, buffering, and extra copies must be measured.
- Keep FFmpegCore behind app-owned media interfaces so a later FFmpeg.AutoGen backend can call `libav*` in-process without changing protocol, view-model, or Avalonia code. Do not expose FFmpegCore command builders, process types, or FFmpeg native pointers outside the backend adapter.
- Model the adapter boundary around encoded packets and decoded frames: packets carry codec/stream metadata, owned payload bytes, PTS/DTS, time base, and keyframe flags; decoded frames carry dimensions, pixel format, and owned pixel memory. Live decode and MP4 mux/remux can be separate interfaces. This keeps packet parsing in the protocol layer and rendering in Avalonia.
- If FFmpegCore's pipe latency/copy cost is unacceptable, replace only the media adapter with FFmpeg.AutoGen. Benchmark with the target camera count and resolution before switching; in-process calls reduce process/pipe overhead but do not make the native codec work itself faster.
- Both approaches require compatible native FFmpeg builds for each RID and review of LGPL/GPL configuration and codec licensing.
- FFmpeg does not implement DVR login, command messages, record search, P2P rendezvous/NAT traversal, or proprietary encryption. Those are the dominant unknowns for a true managed RSNet replacement.
## Proposed .NET/Avalonia Shape
1. Use an Avalonia desktop app targeting `net10.0`, with protocol, device models, and recording logic in separate platform-neutral .NET libraries.
2. Define provider interfaces for direct TCP and each vendor P2P family; start with one direct-IP provider. Keep auth/session lifecycle, heartbeat, retry, cancellation, and protocol parsing independent from Avalonia.
3. Start with FFmpegCore behind app-owned `ILiveVideoDecoder` and `IRecordingMuxer`-style contracts. Keep the contracts independent of FFmpegCore and Avalonia; pass timestamped encoded packets in and owned decoded frames out. Feed FFmpeg only after DVR framing and timestamps are understood, and render frames in Avalonia without legacy Qt/Win32 window handles.
4. Define an `ICredentialStore` abstraction with Windows Credential Manager/DPAPI, macOS Keychain, and Linux Secret Service implementations. Avalonia itself does not make secret storage portable.
5. Keep the original x86 DLLs only as an optional Windows-side comparison oracle during development, subject to runtime access and redistribution terms. Do not make the final cross-platform app depend on them.
6. Validate one camera and one recorded range first; then test concurrent feeds, time zones/DST, keyframe boundaries, cancellation, reconnects, audio, and exported MP4s on each supported OS. Keep a fake media-adapter test and packet fixtures so FFmpegCore and a future FFmpeg.AutoGen implementation can be compared against the same contract.
Before redistribution, verify the vendor DLLs and P2P SDK licensing, supported Windows versions, and all native runtime dependencies. Their presence in the installation does not grant redistribution rights or establish ongoing security maintenance.
## MVP Technical Specification
### Project and dependency layout
Use separate class libraries for application logic, protocol contracts, the RSNet implementation, media contracts, and infrastructure adapters. The Avalonia executable is the composition root and references the concrete adapters; application and domain code do not reference Avalonia, FFmpegCore, or native vendor DLLs.
| Project | Responsibility | Project references |
|---|---|---|
| `Surveillance.Client.Domain` | Device endpoints, channel identity, connection/preview state, and domain errors. No UI or vendor types. | None |
| `Surveillance.Client.Protocol.Abstractions` | `IDeviceSessionFactory`, `IDeviceSession`, and preview-stream contracts, including typed login outcomes. | `Surveillance.Client.Domain` |
| `Surveillance.Client.Media.Abstractions` | Owned encoded-packet and decoded-frame DTOs; `ILiveVideoDecoder` and future `IRecordingMuxer` contracts. | None |
| `Surveillance.Client.Application` | Connect/authenticate, start/stop preview, and credential workflows. Defines the `ICredentialStore` port and coordinates protocol/media abstractions. | Domain, Protocol.Abstractions, Media.Abstractions |
| `Surveillance.Protocol.RSNet` | Managed direct-IP transport, framing, authentication, preview parsing, timeouts, and cancellation for one verified device family. | Domain, Protocol.Abstractions |
| `Surveillance.Media.FFmpegCore` | FFmpegCore process/pipe adapter implementing the app-owned media contracts. No FFmpegCore types escape this project. | Media.Abstractions |
| `Surveillance.Infrastructure.Credentials` | OS-backed secure credential-store adapters. | Application |
| `Surveillance.Client.App` | Avalonia Views and ViewModels, UI dispatch/frame presentation, logging, and DI composition root. | Application, Protocol.RSNet, Media.FFmpegCore, Infrastructure.Credentials |
Keep each later P2P implementation in its own provider project implementing `Protocol.Abstractions`; do not add P2P to the direct-IP MVP. Test projects reference only the layer they exercise: `Surveillance.Client.Domain.Tests`, `Surveillance.Client.Application.Tests`, `Surveillance.Protocol.RSNet.Tests`, `Surveillance.Media.FFmpegCore.Tests`, and `Surveillance.Client.App.Tests`.
### MVVM and dependency injection
- Use CommunityToolkit.Mvvm for observable ViewModels and commands. Views bind to ViewModel properties/commands; ViewModels do not call sockets, FFmpeg, credential APIs, or RSNet exports directly.
- Build the service provider in `Surveillance.Client.App` during Avalonia startup, using `Microsoft.Extensions.DependencyInjection` (and the Generic Host if host-managed logging/configuration is useful). Register application use cases and ports, then their concrete adapters. Resolve top-level windows through the composition root; use constructor injection below it, not a service locator.
- Keep a `DeviceConnectionViewModel` responsible for endpoint fields, saved-device selection, and connect errors. A `LiveViewViewModel` owns the selected channel and start/stop command state. Inject use-case services into both; no ViewModel owns a protocol handle or FFmpeg process.
- Keep Avalonia dispatcher and bitmap conversion in the presentation project. Application services publish app-owned frames; the presentation adapter marshals updates onto the UI thread and writes into a stable-size Avalonia image surface.
- Store the endpoint and username as device configuration and the password/token in an OS secure store behind `ICredentialStore`. Do not log credentials or include them in exception messages. Windows Credential Manager/DPAPI, macOS Keychain, and Linux Secret Service are implementation choices behind that port, not dependencies of the application layer.
### Auth-to-single-live-feed vertical slice
The first end-to-end slice is one direct-IP device, one selected channel, and live video only. Recording search/download, P2P, audio, PTZ, and multi-camera layouts remain later increments.
1. The user selects or enters a device endpoint and credentials.
2. The application saves secrets through `ICredentialStore` after successful authentication. Remembering is enabled by default and can be disabled; on reconnect saved values fill blank credential fields.
3. `ConnectDevice` opens a TCP session through `IDeviceSessionFactory` and sends the mode-0 login request. `FUN_100090e0` selects command `0x1f` with a 16-byte little-endian header and an `0x50`-byte payload: two 36-byte NUL-terminated narrow-string fields followed by two option dwords. Runtime capture of a successful original-client login confirmed `RSNetConnectionStartEx` mode 0 and the transformed-header flag `0x02`. The native worker applies its bit permutation to header bytes `2..15` and the full request payload; it reverses the permutation on the response header and response payload. The managed client now implements this mode-0 transform. Response status is at header offset `+2`; status zero is accepted only when the decoded response body has an `RS` marker at offset `+6`. The native receive helper places the response body at `16 + ((flags >> 2) * 4)`, so the managed reader skips any indicated extension words. The original-client UI reached its logged-in view; managed hardware authentication remains to be retested. The managed implementation uses UTF-8 for the native narrow-string fields, zeroes the uncharacterized option dwords, and leaves nonzero status codes unmapped; encoding, option values, and nonzero status meanings still need device validation. Alternate commands `0x269`/`0x26b` are not implemented. Credentials are sent in cleartext over TCP; use only on a trusted network or VPN until the transport is validated. Connection and authentication diagnostics are written by NLog under the platform's LocalApplicationData `SurveillanceClient/logs` directory, one file per day; credential values and packet payloads are not logged.
4. After authenticated state, `StartLivePreview` requests one channel from `IDeviceSession` and returns an owned async packet stream. The RSNet adapter must first establish the actual preview packet callback/source, framing, codec metadata, timestamps, and buffer ownership. Parse vendor framing in the protocol project; pass only verified elementary-stream access units to media code.
4. `ILiveVideoDecoder` consumes `EncodedVideoPacket` values and yields `DecodedVideoFrame` values. Packets carry codec/stream metadata, owned bytes, PTS/DTS, time base, and keyframe status. Frames carry dimensions, pixel format, row stride, and memory with explicit ownership/lifetime. Keep queues bounded and measure the backpressure policy; never queue unbounded frames on the UI thread.
5. The Avalonia presentation adapter converts frames to its image surface and dispatches updates to the UI thread. Neither protocol DTOs nor media contracts contain Avalonia or FFmpegCore types.
6. Stop is idempotent and cancellation-aware: cancel packet consumption, stop the preview, dispose decoder resources, then disconnect and dispose the device session. Clear displayed frame state and surface terminal errors without exposing secrets. Preserve this order even when preview startup or decoding fails partway through.
**Discovery gate before claiming hardware compatibility:** use a controlled session with one identified device model/firmware to confirm (a) managed authentication against the device, credential encoding, option fields, nonzero status mapping, and cleartext/TLS behavior, and (b) the preview-start handoff and encoded packet boundaries/timestamps. The original client has now authenticated successfully in the UI; a Frida capture observed mode 0, the 96-byte login send, and response traffic while reading no credential payload bytes. Produce sanitized deterministic fixtures and verify direct-IP behavior. The managed implementation is informed by that trace and local fake-server tests, but has not yet passed a hardware login. The UI can report authenticated state while preview remains explicitly unavailable.
### Test plan and acceptance
| Test project / level | Required coverage |
|---|---|
| `Surveillance.Client.Domain.Tests` | Valid/invalid session-state transitions; channel and endpoint invariants; error classification. |
| `Surveillance.Client.Application.Tests` | Connect/auth/start/stop orchestration with fake protocol, credential, and decoder ports; wrong credentials, timeout, cancellation, partial-start failure, and repeated stop; assert secrets never appear in logs. |
| `Surveillance.Protocol.RSNet.Tests` | Captured native mode-0 header golden vector, transformed login request/response loopback coverage, and status rejection; managed hardware auth, preview parsing, fragmentation/coalescing, timeout, and cancellation remain gated on runtime evidence. |
| `Surveillance.Media.FFmpegCore.Tests` | FFmpeg argument construction, pipe input/output, bounded stderr handling, process exit/error mapping, cancellation, and process cleanup. Use a small known media fixture for adapter integration; keep process invocation behind a narrow test seam if needed. |
| `Surveillance.Client.App.Tests` | ViewModel command/state/error behavior with fake use cases and frame presenters; no DVR or FFmpeg executable required. |
| Opt-in hardware integration | One supported model/firmware over direct IP: correct and incorrect login, one channel start, continuous decode, stop/restart, disconnect, and reconnect. Keep this separate from ordinary CI and sanitize any captured fixtures. |
The MVP is accepted when credentials survive app restart only through the OS secure store; one verified direct-IP login produces an authenticated state; one channel displays decoded frames for a 30-minute soak without unbounded queue growth; login/transport/decode failures are visible and recoverable; and stop/cancellation leaves no preview session, socket, or FFmpeg process behind. Record the tested model, firmware, OS, codec, latency, and reconnect behavior. These criteria are conditional on passing the discovery gate and do not imply broad device-family support.
## Evidence Ledger
Evidence below combines static analysis of the installed artifacts with bounded original-client runtime login captures. Credential fields were never read; follow-up captures sampled only the two mode-0 option dwords and decoded response bytes 6–7. The UI success result was user-reported.
| Evidence | Observation | Boundary |
| Original-client response marker (2026-10-16) | The native decoder returned a 1,232-byte body with bytes `53 52` at offsets 6-7; the native worker compares these as little-endian `0x5253`. A separate request capture observed zero-valued option dwords at payload offsets 72 and 76. | Only the two marker bytes and two non-credential option dwords were read; credential fields and all other payload bytes were not accessed. |
|---|---|---|
| Original-client Frida login capture (2026-10-16) | The x86 client called `RSNetConnectionStartEx` with mode bytes `0x35=0` and `0x36=0`, connected to `192.168.100.92:9000`, sent 96-byte login frames with transformed-header flag `0x02`, and received response traffic. The user confirmed the UI reached its logged-in view. | Captured only mode bytes, the first 16 bytes of 96-byte sends, response headers, socket results, and byte counts; request/response payload bytes were never read. UI outcome is user-reported. |
| `ev_0d183bb60c1fc079d8b16095cd7e6e0a89d4915bce519bcfb7327dabd7bc4ebd` (`search_procedures`, Ghidra 12.1.4) | `RSNet.dll` contains named connection, preview, record-query, record-play, and record-download procedures; Winsock imports include `connect`, `send`, and `recv`. | Procedure-name search over the provider's defined procedure inventory; names alone do not establish semantics or export ABI. |
| `ev_d42fbe012e26d4981a08e00ce46e70433e362db4ec26a3f14c685fe3a9e3bb00` (`analyze_function`, `RSNetConnectionStartEx`) | Ghidra reports an x86 `__stdcall` wrapper returning an opaque pointer and accepting one integer-like argument. | Decompiler-derived signature and body for this function; types are inferred from machine code, not vendor headers. |
| `ev_6c73effc02cb39d7d7b41c1d20d3d7b727c24848d206658e748862c0df8efb49` (`analyze_function`, `RSNetStartDownloadRecordEx`) | The wrapper accepts two opaque pointer-like arguments and delegates into native request setup. | Decompiled wrapper; the vendor request type and completion contract are unresolved. |
| `ev_1b112461309bd2e0f9d5d88f747eaf58bd118717148ca9f28e93fc37b9803db6` (`analyze_function`, `FUN_100056c0`) | Preview setup uses a critical section and searches/updates a native collection of session-like objects. | Decompiled function body; names and business meaning of fields are unknown. |
| `ev_e2f17ef25e28e6555e8f96d89b6fcf19d7bccdde1778533bf9dd46635ce2f3ad` (`analyze_function`, `FUN_100103b0`) | Record-download setup allocates/copies per-item buffers and submits a worker through `QueueUserWorkItem`. | Decompiled setup body; queued callback was not recovered as an independent procedure, so transfer and completion semantics remain open. |
| `ev_dc360c49f596100f1bf3d0a2a6df8978f3417a44a185b8a83fe980aa1f400565` (`analyze_function`, `RSNetConnectionStart`) | The public start entry allocates a `0xe98`-byte native object, initializes it through internal helpers, and returns an opaque pointer on success. | Decompiled wrapper; the object layout and actual login/session protocol remain unresolved. |
| `ev_99413f5c1c8b3db71a1b27f2b9859cfd6b9610b855f79975ba8ef145a8b50166` + `ev_04e06a1dfc520df682f516a62663b9ad28a0b825f2e2d3000897afcd80cdc8c0` + `ev_0cd45ef8fd8357e2c1afc1ade8845694727737f2c94e06ed4031810f88340ade` (`analyze_function` / referenced-strings view / xrefs, `FUN_100090e0`) | The x86 worker constructs default login command `0x1f`, a 16-byte header, and an `0x50`-byte payload. It copies two NUL-terminated strings into 36-byte fields, appends two option dwords, applies the native bit permutation for transformed mode, and validates a successful response with an `RS` marker. | Static worker analysis plus the mode-0 runtime capture above. Native narrow-string encoding, option-dword meanings/defaults, and managed-device acceptance remain unverified. |
| `ev_0316a50fa696dd6bbd9f4b84d255689bf6e731b61ec87213da4f80ba188d8393` (`procedure_pseudo_code`, `FUN_100205f0`) | The native helper concatenates a 16-byte header and payload, then calls TCP `send` once and requires the complete byte count. | Assembly/pseudocode of the shipped x86 DLL; it does not establish server acceptance or retry behavior. |
| `ev_66deb589c677f148df9dfede536881c7a90b2a3288901b1c09413e57649740bc` + `ev_6185a26b99ab42e3cfb3b79dc33c3e6b9decb86cf85478ed9777ca6ce6fd62aa` + `ev_6039a85e773b6e22118b90146d6c46fb91ce0c94d4cf64da303235bec0fbed6a` (`procedure_pseudo_code`, receive/header helpers) | The worker reads and reverses the transform on the response header; status is at offset `+2`, zero is success, and `FUN_10003d30` computes the body offset as `16 + ((flags >> 2) * 4)`. It also reverses the response-payload transform before checking `RS` at body offset `+6`; statuses `0x32`/`0x33` set native last-error values. | Static pseudocode plus one successful original-client UI result. Other modes and nonzero status meanings remain unresolved. |
| `ev_34b043c2cfc9f58d0f6ae6798e5531cc4ba34d7b85ab09f9888409b4beefebbe` (`analyze_function`, `RSNetStopPreview`) | The wrapper checks the context and preview handle, calls an internal stop helper, and clears the caller's handle. | Decompiled wrapper at `0x1001c4b0`; helper behavior and packet callback ownership remain unresolved. |
| `ev_c4d3300ea096044c2059e299fae4fd0e864ca62750f5953093405d5e73646a40` (`analyze_function`, `RSNetConnectionStop`) | The wrapper clears the caller's connection pointer and invokes internal shutdown/cleanup helpers for the opaque object. | Decompiled wrapper at `0x1001d0a0`; exact socket/thread shutdown ordering is not established by this wrapper alone. |
| `ev_79ede58629e436b4f454692234adec46614109fb731e7852fcf0454b17a10a4d` (`analyze_function`, `RSNetStartPreview`) | The named start wrapper accepts opaque arguments and delegates preview creation into native state. | It does not establish encoded packet format or the callback/handoff consumed by the original client. |
| `ev_71287e7cb6a061428ece1415f8bf430a5e489914d808cf3f9c37a27bbfa0172a` (`analyze_function`, `RSNetSetDevInfo`) | The function copies `0x48` bytes from its argument and submits a request through internal command machinery. | Structure fields and request purpose are unknown; this is not evidence that the call authenticates a user. |
| `ev_50ae9861dde2005e0a53bc34848c6fefa540a43cf02679531ffd6adfb208a3bf` (`analyze_function`, `RSNetQueryRecordEx`) | Record-query Ex is a short `__stdcall` wrapper taking two opaque pointers and calling an internal query routine. | Does not reveal the public request structure or returned record layout. |
| `ev_5efc588c56e04dc41e8c404e5cb2b74f67afc1e2e2828156e28403421e0bd18b` (`analyze_function`, `FUN_10005eb0`) | The internal record-query path snapshots native state, increments a shared ID, builds request data, and calls a helper with a 20,000 ms timeout. | Decompiled helper; protocol fields and response-to-record mapping are not fully recovered. |
| `ev_f0544388b10f903585f5a108d435109deffec0bda80822656f032d88dd2dd1f6` (`analyze_function`, `FUN_10007330`) | The shared operation queues work under a critical section and waits on a Windows event before returning completion state. | Decompiled synchronization path; it does not by itself identify all socket framing or error semantics. |
| `ev_f42bdfeee987ace213d45429f70c1b137c00fabda859cf6c109536402da45ad4` (`analyze_function`, `RSNetInit`) | Initialization derives the process directory, reads adjacent `RSNet.ini`, and configures Winsock 2.2. | Ghidra pseudocode; configuration parser semantics and runtime side effects remain untested. |
| `ev_de6bc45e95104efae090a5cc3bfac1b363e8e088b69ca529ad086e044e8c6f44` (`analyze_function`, `RSNetInitLX2PPath`) | The function copies a caller-provided path into global storage. | Decompiled function; the code selecting the path and loading any provider was not established. |
| `ev_e973cdc2def91d1adf12ca6361e11f311226f31df289e35bbe1c7646da1c6f6d` (`search_strings`, `RSNet.dll`) | Defined strings include `RSP2PClient.exe`, `RSP2PDaemon.exe`, and P2P/relay labels. | String inventory observations; do not prove process creation or actual provider selection. |
| `ev_a8fff3b40ce4ff520544fe21413db41a358162f4e119b9b11f7a7c36dd3e2769` (`search_procedures`, `RSPlay.dll`) | Named procedures include per-instance playback, network-frame input, decode/draw callbacks, and H.264-to-AVI conversion. | Complete matching defined procedure-name inventory; names do not establish a stable ABI or runtime support. |
| `ev_652be99a1040641c0e78b429cb0dd33846a83c41ab93ef894df5bbd266e7c3df` (`analyze_function`, `RSPlayInputNetFrame`) | The wrapper takes an opaque instance plus two untyped frame parameters and dispatches through a vtable. | Ghidra decompiler signature and body; frame format and ownership remain unknown. |
| `ev_5c28c886f02fe1e47c04ab27320b582d1cb97adf64028ae8c3625864a5e1d5af` (`analyze_function`, `RSPlay264ToAviStart`) | The named AVI conversion entry dispatches through an opaque instance vtable. | Does not establish input/output container details or MP4 capability. |
| `ev_45c4ccbaf121078046672af89dbe07be2d5547b5da13d2e758895977f6bf289d` (`analyze_function`, `Hi264DecCreate`) | H.264 decoder creation takes a pointer to an undocumented config structure and returns an opaque handle. | Ghidra-derived signature; config layout and decoder requirements are unknown. |
| `ev_5dd43643df5d5bd620a18f8da397e72be4dc30e3ed684741109cbee957d14866` (`analyze_function`, `Hi264DecFrame`) | H.264 frame decoding has seven low-level parameters and mutates decoder state. | Ghidra-derived signature; exact types and buffer contract are unknown. |
| `ev_df13bfe4608c52a275d7d6fdd87d924dfd2d1027ff465227fd6837bd35d786c9` (`search_procedures`, `p2p/SY/PPCS_API.dll`) | The SY P2P library contains initialize/connect/read/write/close and status procedure names. | One vendor-specific library only; the search does not establish device-family compatibility or a documented ABI. |
| `ev_522a24d172a10c66d2552f0567b22af89a1c2099c5861a9183d7ab405e590edc` (`inspect_pe_resources`, main EXE) | Resource inspection completed for the exact PE32 executable identity and file hash above. | Resource tree only; it does not establish code behavior or manifest loading. |
## Open Questions
- Do real devices accept the statically recovered default login frame, UTF-8 string encoding, and zero option dwords? What are the meanings of nonzero login statuses and alternate transformed/command modes?
- Where does the original EXE receive encoded preview packets from `RSNet`, and what are their framing, codec, timestamp, and ownership rules?
- Which exact `RSNet` structures and callback signatures does the original EXE pass for record search and download?
- Can a controlled run against one representative DVR confirm direct-IP authentication and one decodable channel before committing to the managed protocol implementation?
- Does the original client use `RSPlay.dll`, FFmpeg, or the HiSilicon decoder DLLs for live rendering and recorded playback, and can any of them write a standard MP4?
- Which of the vendor-specific P2P SDKs under `p2p/` is selected for each device family, and can a modern client load only the required provider?
- Can the executable and relevant DLLs be analyzed in one complete REA pass? The first broad queries on the 10.8 MB EXE timed out; the smaller `RSNet.dll` target was analyzable.

View file

@ -1,234 +1,389 @@
# Surveillance Client DPI Analysis # Surveillance Client Server And Recorded Video Download Analysis
Date: 2026-03-25 Date: 2026-04-17
Target binary: `Surveillance_client.exe` Target binary: `Surveillance_client.exe`
Analysis method: Ghidra MCP against the already-imported and analyzed program database. Analysis method: Ghidra MCP against the already-open executable, with non-destructive analysis only. During this pass, allowed writes were limited to function renames and comments.
## Objective ## Objective
Determine how the client initializes its UI, whether it already contains any DPI-awareness logic, and what practical patch points exist for making the application usable on high-resolution displays. Determine how the client connects to remote devices and how it searches for and downloads recorded video, with the practical goal of building a small standalone downloader that can fetch an arbitrary duration from an arbitrary camera.
## Executive Summary ## Executive Summary
- The binary is a Qt Widgets desktop application, and the available imports strongly suggest an older Qt 4-era codebase. - The EXE is mostly UI, orchestration, and request-shaping code.
- No direct static use of Windows DPI-awareness APIs was found. - The real connection, record-query, playback-control, and download logic is implemented in `RSNET.DLL`.
- No obvious embedded DPI manifest strings were found in the loaded program strings. - Local playback and file rendering are implemented in `RSPLAY.DLL`.
- The application persists window geometry and display layout state through `QSettings`, including explicit `QRect` geometry records. - The EXE contains a clear playback/download workflow that prepares request structures and hands them to `RSNET.DLL` exports.
- That persistence layer is likely to matter for any DPI patch, because old pixel-based geometry can become incorrect or visually tiny once DPI behavior changes. - The current executable analysis is enough to map the high-level flow and the parameter shapes, but not enough to recover the on-the-wire protocol. For that, `RSNet.dll` needs to be loaded into Ghidra next.
## Confirmed Entry Flow ## Installed Module Layout
The startup chain currently identified is: The installed client directory contains the key vendor modules:
1. `___tmainCRTStartup` at `0x00708d44` - `RSNet.dll`
2. `qt_startup_dispatch` at `0x00709b00` - `RSPlay.dll`
3. `qWinMain` thunk at `0x00709c02` - `QRSosAdapter.dll`
4. Application main routine at `0x004c7260` - `QtNetwork4.dll`
Notes: This matches the import thunks present in the EXE.
- `qt_startup_dispatch` converts `GetCommandLineW()` output into a local 8-bit argv-style buffer and forwards execution into Qt startup. ## Confirmed DLL Boundary
- This is a useful early patch region if a future binary modification needs to happen before the first top-level window is created.
## Evidence This Is An Older Qt Widgets Application The following named functions in the EXE are import thunks, not native implementations:
The import table and strings include multiple indicators that this is not a modern Qt high-DPI-aware build: - `RSNetQueryParam` at `0x006e96f0`
- `RSNetQueryParamEx` at `0x006e9720`
- `RSNetAlarmSubscribe` at `0x006e99a0`
- `RSPlayGetPlayFileTimeRange` at `0x006ea760`
- `QApplication` Example:
- `QPlastiqueStyle`
- `QProxyStyle`
- `QStyleOptionViewItemV4`
- `desktop`
- `screenGeometry`
- `availableGeometry`
- `primaryScreen`
Why that matters: - `RSNetQueryParam` is just `JMP dword ptr [0x0076e648]`
- `QPlastiqueStyle` and `QStyleOptionViewItemV4` are strong Qt 4-era signals. External symbol resolution in the loaded EXE confirms these libraries and exports:
- A Qt 4-era app is much less likely to support automatic per-monitor DPI scaling cleanly.
- If DPI awareness is turned on without additional UI scaling work, the usual failure mode is a crisp but very small interface.
## What Was Not Found ### `RSNET.DLL`
The following searches did not produce evidence of a built-in DPI implementation: Relevant exports confirmed in the import table:
- `SetProcessDPIAware` - `RSNetConnectionStart`
- `SetProcessDpiAwareness` - `RSNetConnectionStartEx`
- `SetThreadDpiAwarenessContext` - `RSNetQueryRecordEx`
- `WM_DPICHANGED` - `RSNetStartRecordPlayEx`
- `devicePixelRatio` - `RSNetReqRecordPlayCtrol`
- `HighDpi` - `RSNetStartDownloadRecord`
- `QT_AUTO_SCREEN_SCALE_FACTOR` - `RSNetStartDownloadRecordEx`
- `AA_EnableHighDpiScaling` - `RSNetStopDownloadRecord`
- `RSNetReqRecordData`
- `RSNetStopRecordPlay`
- `RSNetReplayRecordData`
- `RSNetReposRecordData`
- `RSNetGetDevInfo`
- `RSNetSearchDev`
I also searched program strings for common manifest content such as: ### `RSPLAY.DLL`
- `dpiAware` Relevant playback exports confirmed in the import table:
- `asmv3`
- `requestedExecutionLevel`
- `trustInfo`
None of those were found in the loaded strings. - `RSPlayCreatePlayInstance`
- `RSPlaySetPlayWnd`
## Resource Layout - `RSPlayStartPlay`
- `RSPlaySetCallbackMessageEx`
The PE section layout includes a resource section: - `RSPlayImageCallback`
- `RSPlayOpenPlayFile`
- `.rsrc: 0x00dd7000 - 0x00df05ff` - `RSPlayOpenPlayFileListEx`
- `RSPlayGetPlayFileTimeRange`
Even with a resource section present, no obvious manifest or DPI-related XML strings surfaced through the Ghidra string search during this pass. - `RSPlaySetCurPlayedTimeEx`
- `RSPlayInputNetFrame`
## Settings And Geometry Findings - `RSPlayStartlocalrecord`
- `RSPlayStoplocalrecord`
Several settings-related functions were isolated and renamed in the Ghidra database for future work.
### `init_app_settings_defaults` at `0x0059ca30`
This function initializes many application settings keys and default values.
Relevant confirmed keys:
- `mainwindow/fullscreen`
- `mainwindow/size`
- `window_status`
- `gen/liveviewstatus`
- `gen/autolive`
- `screenAutoSwitch/interval`
- `screenAutoSwitch/forceSync`
- `screenAutoSwitch/isOn`
Relevant confirmed defaults:
- `mainwindow/size = 0x400 x 0x300` which is `1024 x 768`
- `mainwindow/fullscreen = false`
Interpretation: Interpretation:
- The main window has a fixed persisted default size in pixels. - `RSNET.DLL` is the module that matters for device login, remote record queries, remote playback, and remote download.
- That is a strong warning sign for DPI patching, because a legacy saved size can remain visually small after changing DPI behavior. - `RSPLAY.DLL` is mostly decode/render/local playback support, not the primary network protocol implementation.
### `load_window_status_from_settings` at `0x005a72b0` ## Confirmed EXE-Side Flow
This function reads a `QSettings` array named `window_status` and loads nested UI state. ### UI widgets involved
Confirmed per-window fields: The strings and handlers in the EXE show a playback and file-download workflow:
- `windowGeometry` - `Widget_Playback`
- `isCurWindow` - `Widget_Playback_FileDownload`
- `isFullScreen` - `Download By Date`
- `isMainWindow` - `Download By Files`
- `maxTabIndex` - `DownLoad Start Time`
- `MainStream`
- `SubStream`
- `playback-download`
- `QRSAdapterReqRecordPlayCtrol`
Confirmed nested view/screen fields: Relevant strings also show signals/slots for:
- `view_status` - `searchRequest(QString)`
- `mainview_status` - `playbackResponse()`
- `screenIndex` - `fileDownload()`
- `screenBeginIndex` - `download()`
- `isScreenEnlarge` - `stopdownload()`
- `autoSwitchInterval`
- `autoSwitchIndependent` ### Functions renamed during analysis
- `autoSwitchIsOn`
- `stream_status` The following EXE functions were renamed in the Ghidra database:
- `groupChannelID`
- `videoIndex` - `0x004a9690` -> `PlaybackFileDownloadWidget_connectSignals`
- `isCurSelected` - `0x0049f570` -> `RecordPlaybackControl_toggleMode`
- `isSoundOn` - `0x004afb30` -> `PlaybackFileDownloadWidget_download`
- `Emap_status` - `0x004b1be0` -> `PlaybackFileDownloadWidget_downloadByTime`
- `emapIDIndex`
These names reflect verified behavior from decompilation.
## What The Download UI Does
### `PlaybackFileDownloadWidget_connectSignals`
This function wires the file-download UI:
- download button -> `download()`
- stop button -> `stopdownload()`
- cancel button -> `cancel()`
- date/time selector changes -> `GetFileNumAndSize(QDateTime)`
That establishes the UI entrypoint cleanly.
### `PlaybackFileDownloadWidget_download`
This is the main dispatcher for the download dialog.
It has two modes:
1. File-based download mode
2. Time-range download mode
In file-based mode it:
- iterates rows in the record table
- checks selected rows
- tracks row state in a per-row metadata structure
- starts a timer to process queued download items
In time-range mode it:
- reads the selected start and end `QDateTime` values from the UI
- iterates available remote record segments
- compares the requested interval against each segment
- computes overlap windows
- schedules one or more download requests accordingly
The function logs several debug markers:
- `DownloadByTime 111111111111111111`
- `DownloadByTime 222222222222222222`
- `DownloadByTime 33333333333333333333`
- `DownloadByTime 444444444444444444444`
Those correspond to different interval-overlap cases between the selected range and a returned recording segment.
### `PlaybackFileDownloadWidget_downloadByTime`
This function handles the actual by-time iteration across remote record segments.
It reconstructs begin/end timestamps from record metadata, converts them to `QDateTime`, compares them against the user-selected range, then dispatches a lower-level download request for the relevant slice.
The logic strongly suggests the client does not ask the device for an arbitrary time range in one step unless the selected window aligns with a single record segment. Instead, it walks matching segments and issues one or more segment-bounded download requests.
Implication for a standalone tool:
- arbitrary time-range download likely requires:
- querying the device for record segments first
- intersecting those with the requested interval
- issuing one or more download requests
- stitching or sequencing the resulting data if needed
## EXE-Side RSNET Wrapper Layer
The EXE contains thin wrappers around the `RSNET.DLL` APIs. These wrappers are useful because they reveal request structure shapes and callback wiring even though the real protocol lives in the DLL.
### Connection wrapper
`FUN_006eaf70`
Behavior:
- copies fields from a caller-supplied struct into a local 0x38-byte request block
- stores two callback/context values into the owning object
- calls `RSNetConnectionStartEx(&local_38)`
Interpretation: Interpretation:
- The application stores a substantial amount of layout state in settings. - connection/login is performed through `RSNetConnectionStartEx`
- `windowGeometry` is especially important because it appears to be persisted as a `QRect`. - the caller passes a structured login/connect request, not loose scalar parameters
- If the process DPI mode changes, previously stored geometry may need migration, scaling, deletion, or selective reset. - the request likely includes address or P2P information, credentials, and callback context
### `save_window_status_to_settings` at `0x005a6170` ### Remote record query wrapper
This function writes back the same structures into `QSettings`. `FUN_006eb6f0`
Behavior:
- allocates a small 8-byte helper object from fields `param_2[0x12]` and `param_2[0x11]`
- copies roughly 0x60 bytes of request data into a local buffer
- assigns completion callbacks
- calls `RSNetQueryRecordEx(handle, &local_64)`
Interpretation: Interpretation:
- Even if a DPI hack works visually at first launch, the application can overwrite the new layout with old pixel-based assumptions on exit. - remote record search is performed with `RSNetQueryRecordEx`
- Any durable solution should consider both the load and save side of geometry persistence. - the query request is non-trivial and includes multiple fields beyond just channel and time
- two tail fields are treated specially and likely represent callback target/context or an auxiliary selection object
### `apply_mainwindow_fullscreen_setting` at `0x0047c1f0` ### Remote playback wrapper
This function compares a key against `mainwindow/fullscreen` and activates the matching `QAction` when the value is true. `FUN_006e9e00`
Behavior:
- creates an `RSPlay` instance via `RSPlayCreatePlayInstance(1)`
- optionally binds the playback window handle via `RSPlaySetPlayWnd`
- starts local rendering via `RSPlayStartPlay`
- registers callback handlers with `RSPlaySetCallbackMessageEx` and `RSPlayImageCallback`
- fills a request block from the provided playback parameters
- calls `RSNetStartRecordPlayEx(connectionHandle, &local_40)`
Interpretation: Interpretation:
- The UI state is driven through Qt actions, not direct Win32 window management. - remote recorded playback is a network operation through `RSNET.DLL`
- That reinforces the view that DPI fixes will likely need to be applied at Qt startup or Qt widget/layout level rather than through a narrow Win32 patch alone. - incoming data is then fed into an `RSPLAY.DLL` decode/render pipeline
- the standalone downloader probably does not need the `RSPLAY` path unless raw playback streaming is required instead of file download
## Implications For A DPI Fix ### Download wrappers
### Most likely current problem model `FUN_006e9810`
Based on the evidence, the binary looks like a legacy Qt Widgets application with no obvious modern DPI-awareness implementation. That creates two realistic scenarios: Behavior:
1. The process is effectively DPI-unaware and Windows bitmap scaling is not being applied in the way the user wants. - allocates a 12-byte state object
2. The process is being made DPI-aware somewhere outside the obvious static import path, causing the UI to render at legacy pixel sizes and appear tiny. - copies a compact request from the caller
- sets a callback function `FUN_006e8690`
- calls `RSNetStartDownloadRecord(handle, &local_14)`
This analysis did not prove which of those two runtime cases is active on the target system. It did establish that the executable itself does not appear to contain a straightforward built-in high-DPI implementation. `FUN_006e98b0`
### Why a simple `SetProcessDPIAware` patch is risky Behavior:
For an older Qt Widgets app: - allocates a 12-byte state object
- copies a slightly larger request including an extra byte field
- sets callback `FUN_006e8730`
- calls `RSNetStartDownloadRecordEx(handle, &local_20)`
- enabling DPI awareness alone often produces a sharp but tiny UI `FUN_006e9980`
- stored `QRect` geometry may restore undersized windows
- icon sizes, style metrics, and custom-painted controls may remain pixel-based
- there is no evidence yet of `WM_DPICHANGED` handling for per-monitor updates
### What a workable solution will probably require Behavior:
At minimum, a successful patch likely needs one of these paths: - calls `RSNetStopDownloadRecord(downloadHandle)`
- frees the associated state object
1. A compatibility-style solution that lets Windows scale the app acceptably. Interpretation:
2. An early startup patch plus application-wide Qt scaling adjustments before top-level widgets are shown.
3. A deeper patch that also normalizes saved geometry and possibly icon/font/style metrics.
## Ghidra Database Changes Made During Analysis - there are at least two remote download entrypoints: base and extended
- the extended form includes one extra byte field that may be stream type, record type, or a mode selector
- both return or populate a download handle that is later passed to `RSNetStopDownloadRecord`
The following functions were renamed in the active program database: ### Record data callback path
- `0x00709b00` -> `qt_startup_dispatch` `FUN_006e85b0`
- `0x0059ca30` -> `init_app_settings_defaults`
- `0x005a72b0` -> `load_window_status_from_settings`
- `0x005a6170` -> `save_window_status_to_settings`
- `0x0047c1f0` -> `apply_mainwindow_fullscreen_setting`
Decompiler comments were also added at those entrypoints summarizing their purpose. Behavior:
## Current Confidence Level - if callback state is valid and `param_1 == 1`, it calls `RSNetReqRecordData(*param_2)`
- otherwise it posts a Qt event with type `0x3ed` to a target object
High confidence: Interpretation:
- Qt-based GUI application - remote playback/download is at least partly callback-driven
- older Qt lineage is likely - one callback state value appears to be a target `QObject`
- no obvious static DPI-awareness implementation exists - `RSNetReqRecordData` is likely a pull/continue/read-next mechanism for record data transfer
- window geometry persistence is real and important
Medium confidence: ### Record playback control
- the best durable fix will require more than a manifest-only change `RecordPlaybackControl_toggleMode`
- geometry migration/reset will likely be necessary for a clean result
Low confidence without runtime testing: Behavior:
- whether the best final mode is DPI-unaware with OS scaling, system-DPI-aware, or a custom Qt-side scaling patch - toggles internal playback state based on UI mode values `0x10` through `0x13`
- logs `QRSAdapterReqRecordPlayCtrol`
- calls a helper that eventually dispatches `RSNetReqRecordPlayCtrol`
## Recommended Direction Interpretation:
Treat this as a legacy-Qt DPI retrofit problem, not just a missing API call problem. - pause/resume/seek/speed or similar playback controls go through `RSNetReqRecordPlayCtrol`
- this is playback control, not initial search or initial download setup
The next pass should focus on: ## Current Reconstructed Download Pipeline
- locating the `QApplication` construction site inside `0x004c7260` From the EXE alone, the likely pipeline is:
- locating first top-level window creation/show
- tracing where `windowGeometry` is applied to the main window 1. Establish device/session connection through `RSNetConnectionStartEx`
- deciding whether to pursue an OS-scaling strategy or a real application-side scaling patch 2. Query available recordings with `RSNetQueryRecordEx`
3. In the UI, present file/segment rows to the user
4. For time-based download, intersect the requested interval against returned record segments
5. For each needed segment or sub-range, call either `RSNetStartDownloadRecord` or `RSNetStartDownloadRecordEx`
6. Receive progress/data/completion via callback functions and Qt events
7. Stop transfer with `RSNetStopDownloadRecord` when complete or canceled
## What This Means For A Standalone Downloader
At a high level, the minimum downloader architecture is likely:
1. Login/connect request builder
2. Record query request builder
3. Segment intersection logic for arbitrary user time ranges
4. Download request builder
5. Callback/event loop or polling layer for transfer progress and completion
The most important unresolved details are all inside `RSNet.dll`:
- exact login request structure
- whether connection uses direct IP, media port, P2P ID, or multiple modes under one API
- exact query-record structure fields
- exact download request structure fields
- callback message formats and result codes
- file format or chunk framing of downloaded data
- authentication handshake and any encryption or session-key behavior
## What Is Known Versus Unknown
### Known from EXE analysis
- The EXE does not appear to implement the wire protocol itself.
- `RSNET.DLL` is the primary networking and remote-record module.
- `RSPLAY.DLL` handles playback/render support.
- The UI supports both file-based and time-based record download.
- Arbitrary time-range download is implemented as interval intersection over returned recording segments.
- The download path uses `RSNetStartDownloadRecord` or `RSNetStartDownloadRecordEx`.
- Record search uses `RSNetQueryRecordEx`.
- Record playback uses `RSNetStartRecordPlayEx` and `RSNetReqRecordPlayCtrol`.
### Unknown until `RSNet.dll` is analyzed
- packet layout and transport protocol
- exact authentication mechanism
- exact request structure fields
- whether the client speaks directly to the device, uses P2P relay logic, or switches transport modes internally
- how downloaded bytes are framed and persisted to disk
## Recommended Next Step
Load `RSNet.dll` into Ghidra next.
That is the correct next target if the goal is to build an independent downloader rather than automate the existing EXE.
After `RSNet.dll` is loaded, the next analysis pass should focus on:
- `RSNetConnectionStartEx`
- `RSNetQueryRecordEx`
- `RSNetStartDownloadRecord`
- `RSNetStartDownloadRecordEx`
- `RSNetReqRecordData`
- `RSNetStopDownloadRecord`
- any credential, P2P, relay, encryption, or session-management helpers they call
## Credentials And Live Validation
Credentials are not required yet for the current static pass.
They will become useful later for one of these reasons:
- validating a reconstructed downloader against a real target
- comparing dynamic behavior with captured traffic
- understanding whether connection mode changes based on device type, P2P ID, or network reachability
If live testing becomes necessary, credentials should be stored in an untracked local file such as a new `.gitignore`d notes/config file inside the repository or workspace.
## Analysis State Notes
- Earlier in the session, a few function definitions were accidentally deleted by using the wrong MCP endpoint on the writable program. Those functions were restored immediately.
- A repository instruction file now explicitly forbids destructive Ghidra actions during analysis unless the user explicitly requests them.
- Current repository instruction file: `.github/copilot-instructions.md`

View file

@ -0,0 +1,911 @@
# RSNet Download Analysis
Date: 2026-04-17
Target binary: `RSNet.dll`
Related binaries:
- `Surveillance_client.exe`
- `RSPlay.dll`
Analysis method: Ghidra MCP against the loaded `RSNet.dll`, using read-only inspection plus function renames/comments only.
## Objective
Determine enough of the `RSNet.dll` API and behavior to build a simple script that can:
1. initialize the DLL
2. connect/login to a device
3. query recorded segments for a camera
4. request download of a chosen interval or file segment
5. wait for completion and retrieve the saved file
## Bottom Line
At this point, the DLL has been analyzed far enough to outline a realistic first-pass downloader script that calls `RSNet.dll` directly with `ctypes` or similar FFI.
What is established:
- `RSNet.dll` owns the real connection, login, record-query, playback, and record-download logic.
- `RSNet.dll` performs its own socket I/O and background worker management.
- the EXE is mainly a UI and adapter layer that fills structs and hands them to `RSNet.dll`
- the download worker inside `RSNet.dll` writes data locally through an internal record-file layer rather than requiring the caller to manually process frame packets
- a simple standalone script is plausible without reversing the entire wire protocol, because the DLL already encapsulates the transport
What is not fully nailed down yet:
- exact C struct definitions for all exported APIs
- the full callback signature set and all event codes
- exact output container selection logic between AVI, MP4, or the vendor private format
Even with those gaps, there is now enough to define the likely call sequence and the minimum reverse-engineering targets for a first prototype.
## Exported API Surface Relevant To Downloading
Confirmed exports in `RSNet.dll`:
- `RSNetInit` at `0x1001ae30`
- `RSNetSetEncription` at `0x1001b570`
- `RSNetConnectionStart` at `0x1001c350`
- `RSNetConnectionStartEx` at `0x1001c3a0`
- `RSNetQueryRecord` at `0x1001c640`
- `RSNetAsyncQueryRecord` at `0x1001c660`
- `RSNetQueryRecordEx` at `0x1001c680`
- `RSNetAsyncQueryRecordEx` at `0x1001c6a0`
- `RSNetAsyncQueryRecordStop` at `0x1001c6c0`
- `RSNetStartDownloadRecord` at `0x1001c780`
- `RSNetStartDownloadRecordEx` at `0x1001c810`
- `RSNetStartRecordPlay` at `0x1001c870`
- `RSNetStartRecordPlayEx` at `0x1001c9a0`
- `RSNetReqRecordData` at `0x1001ca00`
- `RSNetReqRecordPlayCtrol` at `0x1001ca40`
- `RSNetRelease` at `0x1001b4e0`
Interpretation:
- a standalone downloader should use the DLL exports directly
- there is no need to reproduce the underlying socket protocol if the goal is just to automate download on Windows where the vendor DLL is available
## Initialization
### `RSNetInit`
`RSNetInit`:
- initializes logging from `RSNet.ini`
- calls `WSAStartup(0x202, ...)`
- prepares global DLL state
Practical implication:
- any standalone script must call `RSNetInit()` before any connection or query function
### `RSNetSetEncription`
`RSNetSetEncription(value)` simply stores a global value.
Practical implication:
- there is some configurable encryption mode or toggle
- it may need to be set explicitly for some device families, but this has not yet been proven necessary for the basic flow
## Connection / Login
### Public entry points
- `RSNetConnectionStart`
- `RSNetConnectionStartEx`
Both functions:
- allocate a per-device/session object of size `0xe98`
- initialize internal locks, events, strings, and worker state
- copy caller-provided login parameters into the session object
- queue a background login/connection worker
- return a session handle pointer on success, or `NULL` on failure
### `RSNetConnectionStart`
This is the simpler path and likely the better first target for a prototype.
From decompilation, the input struct used by `RSNetConnectionStart` appears to have this rough layout:
```c
struct RSNET_CONNECT_REQ_BASE {
char *address_or_id; // offset 0x00
uint16_t port; // offset 0x04
char *username; // offset 0x08
char *password; // offset 0x0c
uint32_t field10; // offset 0x10
uint32_t field14; // offset 0x14
uint32_t field18; // offset 0x18
uint32_t field1c; // offset 0x1c
uint32_t field20; // offset 0x20
uint32_t field24; // offset 0x24
uint32_t field28; // offset 0x28
};
```
The DLL copies these into its internal session object as:
- destination string at session `+0x04`
- port at session `+0x20`
- username at session `+0x28`
- password at session `+0x44`
- several mode or callback related fields at `+0x68 .. +0x80`
### `RSNetConnectionStartEx`
The extended path supports more than direct IP login. Decompiled behavior shows:
- a connection mode field at request index `0x0b`
- if that mode is zero, the DLL treats the first string as the device address directly
- if non-zero, it stores the first string in an alternate field and forces the target address to `127.0.0.1`
- when mode is `1` or `10`, it copies an additional string from request index `0x0c`
Interpretation:
- `RSNetConnectionStartEx` likely supports P2P / relay / localhost-tunneled connection modes
- the simple downloader should avoid the `Ex` path initially unless the target system requires P2P rather than direct device access
### Login worker behavior
The session worker at `0x100074b0`:
- attempts login / session setup
- posts state changes through callback or message mechanisms
- sends heartbeats every ~5 seconds after login
- dispatches status notifications with integer codes
Observed status/event codes from the worker:
- `2` on one failure path
- `3` on disconnect/connection-lost path
- `0x65`
- `0x79`
- `0x7a`
Strings in the DLL map login-related status messages to names such as:
- `RSNetMsgLoginRequest`
- `RSNetMsgLoginSuccess`
- `RSNetMsgLoginUserLogined`
- `RSNetMsgLoginNoUserName`
- `RSNetMsgLoginPasswordError`
- `RSNetMsgLoginNoRight`
- `RSNetMsgOverMaxUser`
- `RSNetMsgLoginUserDisable`
- `RSNetMsgLoginFail`
Practical implication:
- a script should assume login is asynchronous
- a callback or polling/wait mechanism is required before issuing record queries
## Record Query
### Public entry points
- `RSNetQueryRecord`
- `RSNetQueryRecordEx`
The simpler function is:
```c
RSNetQueryRecord(session, query_req)
```
which routes into `FUN_10005ca0`.
The extended function is:
```c
RSNetQueryRecordEx(session, query_req)
```
which routes into `FUN_10005eb0`.
### Behavior
Both paths:
- build a request message with message subtype `0x6f`
- send it through the session object
- wait up to 20 seconds for a response
- decode the returned payload into caller-facing record structures through callback helpers
The record-query dispatcher distinguishes at least two output styles using the first field of the query struct:
- `0x65`
- `0x66`
Those two cases use different callbacks:
- `FUN_100046b0`
- `FUN_10004750`
`FUN_100046b0` iterates a result array in units of `0x1c` bytes.
`FUN_10004750` iterates a result array in units of `0x0c` bytes.
Interpretation:
- one query result format is likely the full record segment list (`0x1c` bytes each)
- the other is likely a compact per-day/per-file summary format (`0x0c` bytes each)
For a downloader, the `0x1c` record entries are the important one because the EXE uses `0x1c`-byte records when building playback and download requests.
### Likely record entry format
The download worker consumes entries of size `0x1c` and treats them like timestamped record descriptors.
From earlier EXE analysis and DLL behavior, each `0x1c` entry likely contains:
- start date/time fields
- end date/time fields
- channel or stream selection data
- a record type flag or subtype
This matches how the EXE performed time-range intersection over returned recording segments.
## Download
### Public entry points
- `RSNetStartDownloadRecord`
- `RSNetStartDownloadRecordEx`
These are the core APIs for a standalone downloader.
### `RSNetStartDownloadRecord`
This is the simpler form.
The EXE-side wrapper showed this request shape:
```c
struct RSNET_DOWNLOAD_REQ_BASE {
uint32_t field00;
uint32_t field04;
uint32_t field08;
uint32_t callback_or_ctx;
uint32_t callback_user;
};
```
Inside `RSNet.dll`, `FUN_10010330` adapts this into the extended worker request by supplying defaults:
- count or mode fields are normalized
- an extra byte field is forced to zero
- a `local_14 = 1` flag is inserted before forwarding to the common worker builder
Interpretation:
- the base function is just a convenience wrapper around the extended worker
- for a script, `RSNetStartDownloadRecord` is probably easier to prototype first
### `RSNetStartDownloadRecordEx`
This is the common implementation target.
The decompiled request consumer `FUN_100103b0` proves the worker expects at least:
- two required non-zero fields at offsets `+0x04` and `+0x08`
- a count field at `+0x0c`
- an extra mode byte at `+0x10`
- a sequence of seven 32-bit values copied from offsets `+0x00 .. +0x18` into the worker object
Then it:
- allocates `count * 0x1c` bytes for one array
- allocates `count * 0x108` bytes for a second array
- copies source arrays from worker request indices `0x19` and `0x1a`
- queues a background worker thread beginning at `0x100105b0`
Interpretation:
- the extended request supports batch download of one or more `0x1c` record descriptors
- each record also has an associated `0x108` byte metadata block, likely including the destination path or output-file information
This is a strong indication that a standalone downloader can submit one selected record entry at a time rather than needing a large complex batch.
## Download Worker Behavior
The worker at `0x100105b0` is the core of remote file download.
Key verified behaviors:
- waits on session/login readiness
- opens a socket and configures timeouts
- sends a request with message subtype:
- `0x83` in one mode
- `0x196` in another mode
- copies one or more `0x1c` record entries into the outgoing message
- optionally handles an additional payload block depending on mode
- receives a response header and payload
- processes download status and progress messages
- writes or routes the resulting data into an internal record-file path
Important status/message strings in the DLL:
- `RSNetMsgDownloadRecordClosed`
- `RSNetMsgDownloadRecordStoreFail`
- `RSNetMsgDownloadRecordNoFile`
- `RSNetMsgDownloadRecordOK`
- `RSNetMsgDownloadRecordPercent`
- `RSNetMsgDownloadRecordFail`
Observed message codes in the worker:
- `0x132`
- `0x133`
- `0x142`
- `0x145`
Interpretation:
- the worker sends progress and completion back to the caller via callback/message dispatch
- success/failure is not just the return value of `RSNetStartDownloadRecord*`; the returned handle only means the worker was started
## Does The DLL Save The File Itself?
Yes, that appears to be the case.
Evidence:
- the download worker is large and manages long-running transfer state
- the DLL contains internal record-file classes:
- `.?AVCBaseRecordFile@@`
- `.?AVCRSAVIRecordFile@@`
- `.?AVCRSMP4RecordFile@@`
- `.?AVCRSPrivateRecordFile@@`
- the DLL also contains AVI-writing error strings
- cleanup paths include an object with a `FILE *` at offset `0x54` and a file/path buffer with small-string optimization behavior
Practical implication:
- the script most likely does not need to manually receive frame payloads and write them itself
- instead, it should provide the request/path metadata that the DLL expects, start the download, and wait for the worker to finish writing the file
## Callback And Handle Lifetime
### Session handle
The session handle returned by `RSNetConnectionStart*`:
- owns socket state
- runs a worker thread
- dispatches status via callback or window message
Important internal callback-related session fields:
- callback window/message at offsets around `+0x68` and `+0x6c`
- callback function at `+0x78`
- callback user/context at `+0x70`
### Download handle
The download handle returned by `RSNetStartDownloadRecord*` is a heap object with:
- session pointer at `+0x20`
- event handle at `+0x2c`
- worker state, copied record entries, and additional metadata
There is a tiny internal stop/cleanup wrapper around `0x1001ca81` that:
- validates the handle
- calls a stop routine
- destroys the download object via `FUN_1001cab0`
So a full script should ideally also locate or call the exported stop-download function when cleanup is needed. The original EXE import table proves that such an export exists, even though the current symbol recovery in this DLL session did not label it cleanly.
## Practical Downloader Strategy
The simplest viable approach is not to reverse the raw network protocol. It is to call the vendor DLL directly.
## C# Interop Feasibility
Yes. C# can load `RSNet.dll` as an unmanaged native library and call its exports directly.
The DLL is a good fit for `P/Invoke` or `NativeLibrary.GetExport`-based interop because the key exports are ordinary x86 functions, not COM interfaces or C++ object methods.
### ABI details confirmed from `RSNet.dll`
- architecture: `x86/little/32`
- pointer size: `4`
- compiler family: Visual Studio
- export names are undecorated in the import table used by the EXE
- the relevant exports use callee stack cleanup, which matches `StdCall`
Observed export epilogues:
- `RSNetInit` -> `RET`
- `RSNetRelease` -> `RET`
- `RSNetConnectionStart` -> `RET 0x4`
- `RSNetConnectionStartEx` -> `RET 0x4`
- `RSNetQueryRecord` -> `RET 0x8`
- `RSNetQueryRecordEx` -> `RET 0x8`
- `RSNetStartDownloadRecord` -> `RET 0x8`
- `RSNetStartDownloadRecordEx` -> `RET 0x8`
- `RSNetReqRecordData` -> `RET 0x4`
Practical implication:
- the first C# prototype should treat the exported functions as `CallingConvention.StdCall`
- the process must be 32-bit
### Runtime constraints for a C# host process
The managed host should be built and run as:
- `x86`, not `AnyCPU`
- Windows only
- from the vendor application directory, or with that directory added to the DLL search path
The safest deployment model is:
- place the C# test app in the same directory as `RSNet.dll`
- or launch it with the current directory set to `i:/Apps/Surveillance_client`
- or call `SetDllDirectory` / `AddDllDirectory` before loading `RSNet.dll`
Why that matters:
- `RSNet.dll` depends on the VC++ runtime and the rest of the vendor installation layout
- it also expects `RSNet.ini` nearby for logging/config initialization
- strings inside the DLL reference `RSP2PClient.exe` and `RSP2PDaemon.exe`, so P2P mode likely depends on those companion files being present
For direct-IP downloading, the minimum runtime context is likely smaller than the full client install, but the easiest first run is still to execute from the installed client folder.
## Recommended C# Loading Model
There are two realistic options.
### Option 1: Static `DllImport`
Use this once the calling convention and signatures are stable enough.
Advantages:
- simplest code
- easiest to read
- easiest to debug once structs are correct
Disadvantages:
- more brittle while struct layouts are still being discovered
### Option 2: `NativeLibrary.Load` plus delegates
Use this during the reverse-engineering phase.
Advantages:
- lets you experiment with signatures more safely
- avoids hard failure at process load if a dependency is missing
- makes it easy to log export resolution one function at a time
Disadvantages:
- more boilerplate
For the current stage, Option 2 is the better choice.
## C# Interop Types To Use
### Handles
Treat these as opaque `IntPtr` values:
- session handle returned by `RSNetConnectionStart*`
- download handle returned by `RSNetStartDownloadRecord*`
Do not model them as managed classes or attempt to dereference them directly in C#.
### Strings
Current evidence suggests the DLL uses ANSI `char *` strings, not UTF-16.
In C#:
- use `CharSet.Ansi`
- marshal strings as `LPStr`
- for uncertain layouts, prefer `IntPtr` plus `Marshal.StringToHGlobalAnsi`
### Struct packing
Use:
- `StructLayout(LayoutKind.Sequential, Pack = 4)`
Reason:
- this is a 32-bit Visual Studio binary using 4-byte pointers and ordinary 32-bit alignment
### Callbacks
Use delegates marked with:
```csharp
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
```
And keep the delegate alive for the entire native operation lifetime.
Practical rule:
- store callback delegates in fields, not local variables
Otherwise the GC may collect them while the native worker thread still holds the callback pointer.
## First-Pass C# API Shape
Based on the confirmed export behavior, a first interop layer can be modeled like this:
```csharp
internal static class RsNetNative
{
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
internal static extern void RSNetInit();
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern void RSNetRelease();
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern void RSNetSetEncription(uint value);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr RSNetConnectionStart(ref RsNetConnectRequest request);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr RSNetConnectionStartEx(IntPtr request);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern int RSNetQueryRecord(IntPtr session, IntPtr queryRequest);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern int RSNetQueryRecordEx(IntPtr session, IntPtr queryRequest);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr RSNetStartDownloadRecord(IntPtr session, IntPtr downloadRequest);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr RSNetStartDownloadRecordEx(IntPtr session, IntPtr downloadRequest);
[DllImport("RSNet.dll", CallingConvention = CallingConvention.StdCall)]
internal static extern void RSNetReqRecordData(IntPtr recordPlayHandle);
}
```
Notes:
- `RSNetConnectionStart` is the first function worth strongly typing
- `RSNetConnectionStartEx`, `RSNetQueryRecord*`, and `RSNetStartDownloadRecord*` should initially stay as `IntPtr` request pointers until the layouts are fully proven
- this reduces the chance of silent marshaling mistakes during the first prototype
## First Strongly-Typed C# Struct Worth Trying
The current best candidate for a partial typed struct is the direct-IP login request used by `RSNetConnectionStart`.
Best current guess:
```csharp
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct RsNetConnectRequest
{
public IntPtr AddressAnsi;
public ushort Port;
public ushort Padding0;
public IntPtr UsernameAnsi;
public IntPtr PasswordAnsi;
public uint Field10;
public uint Field14;
public uint Field18;
public uint Field1C;
public uint Field20;
public uint Field24;
public uint Field28;
}
```
Why this is reasonable:
- the decompiled function copies a pointer at offset `0x00`
- a 16-bit port value is read from offset `0x04`
- string pointers are copied from offsets `0x08` and `0x0c`
- the remaining fields are treated as 32-bit values or callback-related fields
This struct should still be treated as provisional.
## Likely C# Callback Shape
The session object stores either:
- a callback window handle and message ID
- or a callback function pointer plus a user/context value
The worker invokes the function callback in patterns like:
- `callback(code, userContext)`
- or posts a window message with `PostMessageA(hwnd, msgId, code, userContext)`
Best current guess for the login/status callback delegate:
```csharp
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate void RsNetStatusCallback(uint code, IntPtr userContext);
```
This is not fully proven, but it matches the currently observed call sites better than any multi-parameter alternative.
## Why C# Is A Better Fit Than Raw Packet Reimplementation
For the current objective, C# plus unmanaged interop is likely better than reimplementing the network protocol because:
- the vendor DLL already knows the login handshake
- the vendor DLL already knows P2P versus direct-IP behavior
- the vendor DLL already manages record-query formatting
- the vendor DLL already performs the actual download worker loop
- the vendor DLL appears to write the file itself
That cuts the problem down to:
- loading the DLL safely
- building the request structs correctly
- handling callbacks/events
- waiting for the output file to appear and complete
## Recommended C# Downloader Architecture
### Layer 1: Native bootstrap
Responsibilities:
- locate the vendor install directory
- set DLL search path
- call `RSNetInit`
- optionally call `RSNetSetEncription`
### Layer 2: Session wrapper
Responsibilities:
- allocate unmanaged ANSI strings for device address, username, password
- build the login request
- call `RSNetConnectionStart`
- keep the callback delegate alive
- expose a `Task` or `ManualResetEventSlim` for login completion
### Layer 3: Record query wrapper
Responsibilities:
- build an unmanaged query struct
- invoke `RSNetQueryRecord`
- collect returned `0x1c` entries into managed record models
- expose them to higher-level range selection code
### Layer 4: Download wrapper
Responsibilities:
- choose the target record entry or entries
- build the native download request and per-item metadata
- call `RSNetStartDownloadRecord`
- monitor status/progress callbacks
- resolve the final output file path
### Layer 5: Cleanup
Responsibilities:
- call the native stop/cleanup entrypoints when known
- free all unmanaged strings and unmanaged buffers
- call `RSNetRelease` on process shutdown
### What a minimal C# prototype should look like
The first prototype should not attempt the whole workflow at once.
Do it in stages:
1. Load `RSNet.dll` successfully from C# in an `x86` process.
2. Call `RSNetInit()` and verify it does not crash.
3. Call `RSNetConnectionStart(...)` with a direct-IP request and log callback codes.
4. Confirm which callback code means login success.
5. Add `RSNetQueryRecord(...)` and dump raw `0x1c` entries.
6. Only then attempt `RSNetStartDownloadRecord(...)`.
That staged approach is important because the unstable part is the native struct layout, not the export resolution.
## Risks Specific To C# Interop
The main failure modes are:
- running as `AnyCPU` or `x64` and failing to load the 32-bit DLL
- incorrect calling convention
- incorrect struct packing
- wrong ANSI versus Unicode marshaling
- GC moving or collecting delegates or unmanaged buffers too early
- freeing unmanaged strings before the async worker is finished using them
- assuming login is synchronous when it is not
Operational rule:
- keep every unmanaged buffer and every callback delegate alive until the native session or download handle has definitively finished
## Implementation Checklist For A C# Version
Before coding:
- confirm the C# host runs as `x86`
- run from the vendor install folder or configure DLL search paths explicitly
- keep a copy of the vendor folder structure intact for first tests
During interop setup:
- use `StdCall`
- use `CharSet.Ansi`
- use `Pack = 4`
- represent unknown native structs as `IntPtr` first
- keep callback delegates pinned by strong references
During login:
- prefer `RSNetConnectionStart` over `RSNetConnectionStartEx`
- use direct IP and media port first
- do not assume immediate success after the function returns a non-null session handle
During record query:
- expect asynchronous or callback-driven result delivery
- log raw bytes for each `0x1c` record entry before trying to reinterpret every field semantically
During download:
- start with one record entry, not a batch
- expect completion via status event rather than via the return value alone
- inspect the output directory for the file the DLL creates
## What Still Needs To Be Recovered For A Clean C# Implementation
The unresolved items are the same as for Python FFI, but C# can tolerate them if opaque pointers are used first.
The most important remaining tasks are:
1. exact `RSNetConnectionStart` request struct validation
2. exact query-request struct layout
3. exact query callback prototype
4. exact download-request struct layout
5. exact per-item `0x108` metadata layout
6. exact stop-download export signature
7. exact mapping from numeric event codes to login/query/download states
## Revised Assessment
Yes, a C# implementation is realistic.
It is probably one of the better options if the end goal is a Windows-only utility that uses the vendor binary as-is.
The current blocker is not `can C# do it?` but `how much of the request structs do we want to strongly type before writing the prototype?`
At this point, a cautious C# prototype is feasible if it:
- uses `x86`
- calls the DLL with `StdCall`
- uses direct IP login first
- treats most request blobs as unmanaged buffers until the layouts are fully validated
### Recommended first prototype flow
1. Load `RSNet.dll` with `ctypes.WinDLL`
2. Call `RSNetInit()`
3. Optionally call `RSNetSetEncription(...)` if required by the target device family
4. Build a direct-IP login struct for `RSNetConnectionStart`
5. Wait until the async login callback reports success
6. Build a record-query request for `RSNetQueryRecord`
7. Collect returned `0x1c` record entries
8. Pick the entries intersecting the user-requested time range
9. Build a single-entry download request and call `RSNetStartDownloadRecord`
10. Wait for `RSNetMsgDownloadRecordOK` or a terminal failure event
11. Locate the output file written by the DLL
12. Release/cleanup handles
### Why direct-IP first
The `Ex` login path clearly has extra logic for P2P or relay modes.
To keep the prototype small:
- use direct device IP / media port first
- defer P2P-only targets until after the basic downloader works
## Best Current Guess At Minimal Script Design
### Language
Python with `ctypes` is the fastest path.
C# is now a credible alternative for a Windows-only implementation that loads the vendor DLL directly.
### Components
1. DLL loader and function prototypes
2. callback function declared with `ctypes.WINFUNCTYPE`
3. login request struct for `RSNetConnectionStart`
4. query request struct for `RSNetQueryRecord`
5. query result callback handling `0x1c` entries
6. download request struct for `RSNetStartDownloadRecord`
7. event loop or polling wait for download completion
### Important caveat
The exact `ctypes.Structure` layouts are not fully proven yet.
So the first implementation should be treated as an iterative prototype, not a guaranteed drop-in script.
Still, the reverse engineering so far is enough to support the following plan:
- prototype direct login with `RSNetConnectionStart`
- verify callback codes for login success and failure
- prototype `RSNetQueryRecord` with a callback that logs each `0x1c` result entry
- once one real query works, use a single returned record entry as input to `RSNetStartDownloadRecord`
That is now a tractable task.
## Gaps That Still Matter Before Writing The Actual Script
These are the highest-value unresolved items:
1. Exact layout of the `RSNetConnectionStart` input struct
2. Exact layout of the `RSNetQueryRecord` request struct and callback prototype
3. Exact layout of the `RSNetStartDownloadRecord` request struct, especially the destination-file metadata
4. Exact numeric callback codes corresponding to:
- login success
- login failure types
- query complete
- download progress
- download success
- download failure
5. Exact output file naming and format-selection rules
## Recommended Next Reverse-Engineering Steps
The next pass should focus on making the prototype script concrete:
1. Rename key `RSNet.dll` internals:
- `FUN_100050a0`
- `FUN_100051f0`
- `FUN_10005ca0`
- `FUN_10005eb0`
- `FUN_10010330`
- `FUN_100103b0`
- `FUN_100105b0`
- `FUN_100074b0`
2. Recover the exact login callback prototype from the session object fields around `+0x68`, `+0x6c`, `+0x70`, and `+0x78`
3. Recover the exact query callback prototype used by result handlers `FUN_100046b0` and `FUN_10004750`
4. Identify the structure at size `0x108` associated with each download item
5. Identify where the output file path is copied into the download-item metadata
6. Validate the call sequence against a real device using credentials
## Current Assessment
The original objective was to analyze until it became possible to figure out how to make a simple script that downloads a video file.
That threshold has been reached in architectural terms:
- use `RSNet.dll` directly
- direct-IP login first
- query recordings first
- submit one record entry into the download API
- let the DLL write the file locally
- monitor callback/status events for completion
The remaining work is no longer “what is the path?” but “what are the exact struct layouts?”
That is a much narrower problem and should be solvable in a follow-up pass, especially with live credentials or one round of prototype-and-adjust testing.

View file

@ -1,5 +0,0 @@
bin/
obj/
.vs/
TestResults/
/dependencies/

View file

@ -1,11 +0,0 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>14</LangVersion>
<PlatformTarget>x64</PlatformTarget>
<Platforms>x64</Platforms>
<Deterministic>true</Deterministic>
</PropertyGroup>
</Project>

View file

@ -1,15 +0,0 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="Avalonia.Desktop" Version="12.1.4" />
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.4" />
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageVersion Include="FFMpegCore" Version="5.5.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.13" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="NLog" Version="6.2.2" />
<PackageVersion Include="xunit.v3" Version="4.0.2" />
</ItemGroup>
</Project>

View file

@ -1,24 +0,0 @@
# Surveillance Client (managed prototype)
SDK-style .NET 10 solution for a 64-bit Avalonia live-view prototype.
## Build and test
From this directory:
```powershell
dotnet restore Surveillance.Client.slnx
dotnet build Surveillance.Client.slnx -c Release
dotnet test --solution Surveillance.Client.slnx -c Release
dotnet run --project src/Surveillance.Client.App -c Debug
```
The shared build properties target `net10.0` and `x64`. The app declares `win-x64`, `linux-x64`, and `osx-x64` runtime identifiers. Files in the ignored `dependencies/` folder are copied to `ffmpeg/` beside the built or published app, and the app uses that folder for FFmpegCore. Replace those files in a published `ffmpeg/` folder to use a different FFmpeg build. The binaries are intentionally not committed.
Open the repository root in VS Code and press F5 to build and launch the x64 Debug app.
## Protocol status
The UI, application coordinator, media contracts, FFmpegCore decoder, and tests are implemented. `Surveillance.Protocol.RSNet` deliberately refuses network connections until the login request and preview packet framing are supported by verified fixtures. This avoids sending guessed credentials or presenting a generic protocol as compatible with the shipped client. The app will display that discovery gate when Connect is used.
The Windows credential adapter stores secrets in Windows Credential Manager. Other operating systems currently fail closed until their native secure-store adapters are implemented.

View file

@ -1,19 +0,0 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/Surveillance.Client.Domain/Surveillance.Client.Domain.csproj" />
<Project Path="src/Surveillance.Client.Protocol.Abstractions/Surveillance.Client.Protocol.Abstractions.csproj" />
<Project Path="src/Surveillance.Client.Media.Abstractions/Surveillance.Client.Media.Abstractions.csproj" />
<Project Path="src/Surveillance.Client.Application/Surveillance.Client.Application.csproj" />
<Project Path="src/Surveillance.Protocol.RSNet/Surveillance.Protocol.RSNet.csproj" />
<Project Path="src/Surveillance.Media.FFmpegCore/Surveillance.Media.FFmpegCore.csproj" />
<Project Path="src/Surveillance.Infrastructure.Credentials/Surveillance.Infrastructure.Credentials.csproj" />
<Project Path="src/Surveillance.Client.App/Surveillance.Client.App.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Surveillance.Client.Domain.Tests/Surveillance.Client.Domain.Tests.csproj" />
<Project Path="tests/Surveillance.Client.Application.Tests/Surveillance.Client.Application.Tests.csproj" />
<Project Path="tests/Surveillance.Protocol.RSNet.Tests/Surveillance.Protocol.RSNet.Tests.csproj" />
<Project Path="tests/Surveillance.Media.FFmpegCore.Tests/Surveillance.Media.FFmpegCore.Tests.csproj" />
<Project Path="tests/Surveillance.Client.App.Tests/Surveillance.Client.App.Tests.csproj" />
</Folder>
</Solution>

View file

@ -1,5 +0,0 @@
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}

View file

@ -1,8 +0,0 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Surveillance.Client.App.App"
RequestedThemeVariant="Default">
<Application.Styles>
<FluentTheme />
</Application.Styles>
</Application>

View file

@ -1,79 +0,0 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using FFMpegCore;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using NLog.Config;
using NLog.Targets;
using Surveillance.Client.Application;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
using Surveillance.Media.FFmpegCore;
using Surveillance.Infrastructure.Credentials;
using Surveillance.Protocol.RSNet;
namespace Surveillance.Client.App;
public sealed partial class App : Avalonia.Application
{
public override void Initialize() => AvaloniaXamlLoader.Load(this);
public override void OnFrameworkInitializationCompleted()
{
InitializeLogging();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var ffmpegFolder = Path.Combine(AppContext.BaseDirectory, "ffmpeg");
if (Directory.Exists(ffmpegFolder))
{
GlobalFFOptions.Configure(options => options.BinaryFolder = ffmpegFolder);
}
var services = new ServiceCollection();
services.AddSingleton<IDeviceSessionFactory, RsNetSessionFactory>();
services.AddSingleton<ICredentialStore, PlatformCredentialStore>();
services.AddSingleton<ILiveVideoDecoder, FfmpegCoreLiveVideoDecoder>();
services.AddSingleton<ILiveViewCoordinator, LiveViewCoordinator>();
services.AddSingleton<MainWindowViewModel>();
services.AddSingleton<MainWindow>();
var provider = services.BuildServiceProvider();
desktop.MainWindow = provider.GetRequiredService<MainWindow>();
desktop.Exit += async (_, _) =>
{
try
{
await provider.DisposeAsync();
}
finally
{
LogManager.Shutdown();
}
};
}
base.OnFrameworkInitializationCompleted();
}
private static void InitializeLogging()
{
var logDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"SurveillanceClient",
"logs");
Directory.CreateDirectory(logDirectory);
var fileTarget = new FileTarget("file")
{
FileName = Path.Combine(logDirectory, "surveillance-${shortdate}.log"),
Layout = "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}",
CreateDirs = true,
};
var configuration = new LoggingConfiguration();
configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);
LogManager.Configuration = configuration;
LogManager.GetCurrentClassLogger().Info("Application logging initialized at {LogDirectory}", logDirectory);
}
}

View file

@ -1,66 +0,0 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="using:Surveillance.Client.App"
x:Class="Surveillance.Client.App.MainWindow"
x:DataType="app:MainWindowViewModel"
Title="Surveillance Client"
Width="1200"
Height="760"
MinWidth="850"
MinHeight="540">
<Grid RowDefinitions="Auto,*,Auto" ColumnDefinitions="320,*">
<Border Grid.Row="0" Grid.ColumnSpan="2" Padding="20,14" Background="#202729">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="2">
<TextBlock FontSize="20" FontWeight="SemiBold" Text="Surveillance Client" />
<TextBlock Foreground="#B3C1C0" Text="Live view" />
</StackPanel>
<TextBlock Grid.Column="1" VerticalAlignment="Center" Foreground="#C2D5D1" Text="{Binding StatusMessage}" />
</Grid>
</Border>
<ScrollViewer Grid.Row="1" Grid.Column="0">
<StackPanel Margin="20" Spacing="12">
<TextBlock FontSize="17" FontWeight="SemiBold" Text="Device" />
<TextBlock Text="Host" />
<TextBox Text="{Binding Host}" PlaceholderText="IP address or host name" />
<Grid ColumnDefinitions="*,*" ColumnSpacing="12">
<StackPanel Spacing="6">
<TextBlock Text="Port" />
<TextBox Text="{Binding Port}" />
</StackPanel>
<StackPanel Grid.Column="1" Spacing="6">
<TextBlock Text="Channel" />
<TextBox Text="{Binding Channel}" />
</StackPanel>
</Grid>
<TextBlock Margin="0,8,0,0" FontSize="17" FontWeight="SemiBold" Text="Credentials" />
<TextBlock Text="User name" />
<TextBox Text="{Binding UserName}" />
<TextBlock Text="Password" />
<TextBox PasswordChar="●" Text="{Binding Password}" />
<CheckBox IsChecked="{Binding RememberCredentials}" Content="Remember on this device" />
<Grid Margin="0,8,0,0" ColumnDefinitions="*,*" ColumnSpacing="8">
<Button IsEnabled="{Binding CanConnect}" Command="{Binding ConnectCommand}" Content="Connect" />
<Button Grid.Column="1" IsEnabled="{Binding CanStop}" Command="{Binding StopCommand}" Content="Stop" />
</Grid>
</StackPanel>
</ScrollViewer>
<Border Grid.Row="1" Grid.Column="1" Margin="0,18,18,18" Background="#111718" BorderBrush="#394344" BorderThickness="1">
<Grid>
<Image Source="{Binding VideoFrame}" Stretch="Uniform" />
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="8" IsVisible="{Binding IsFrameUnavailable}">
<TextBlock HorizontalAlignment="Center" FontSize="18" Foreground="#D6E0DE" Text="No video" />
<TextBlock HorizontalAlignment="Center" Foreground="#91A09E" Text="Connect to a device to start live view." />
</StackPanel>
</Grid>
</Border>
<Border Grid.Row="2" Grid.ColumnSpan="2" Padding="12,8" Background="#E8EEEC">
<TextBlock Foreground="#344240" Text="{Binding DetailMessage}" TextWrapping="Wrap" />
</Border>
</Grid>
</Window>

View file

@ -1,45 +0,0 @@
using Avalonia.Controls;
using NLog;
namespace Surveillance.Client.App;
public sealed partial class MainWindow : Window
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private bool _closeAfterCredentialSave;
private bool _credentialSaveInProgress;
public MainWindow(MainWindowViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
Closing += async (_, eventArgs) =>
{
if (_closeAfterCredentialSave)
{
return;
}
eventArgs.Cancel = true;
if (_credentialSaveInProgress)
{
return;
}
_credentialSaveInProgress = true;
try
{
await viewModel.SaveCredentialsOnCloseAsync();
}
catch (Exception exception)
{
Logger.Error(exception, "Failed to save device credentials while closing the main window");
}
finally
{
_closeAfterCredentialSave = true;
Close();
}
};
}
}

View file

@ -1,248 +0,0 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Surveillance.Client.Application;
using Surveillance.Client.Domain;
using Surveillance.Client.Protocol;
namespace Surveillance.Client.App;
public sealed partial class MainWindowViewModel(ILiveViewCoordinator coordinator) : ObservableObject
{
private CancellationTokenSource? _frameCancellation;
private Task? _frameReader;
private WriteableBitmap? _frameBitmap;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanConnect))]
[NotifyPropertyChangedFor(nameof(CanStop))]
private bool isBusy;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanConnect))]
[NotifyPropertyChangedFor(nameof(CanStop))]
private bool isConnected;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsFrameUnavailable))]
private WriteableBitmap? videoFrame;
[ObservableProperty]
private string host = "192.168.1.100";
[ObservableProperty]
private string port = "34567";
[ObservableProperty]
private string channel = "0";
[ObservableProperty]
private string userName = string.Empty;
[ObservableProperty]
private string password = string.Empty;
[ObservableProperty]
private bool rememberCredentials = true;
[ObservableProperty]
private string statusMessage = "Not connected";
[ObservableProperty]
private string detailMessage = "";
public bool CanConnect => !IsBusy && !IsConnected;
public bool CanStop => !IsBusy && IsConnected;
public bool IsFrameUnavailable => VideoFrame is null;
public async ValueTask SaveCredentialsOnCloseAsync()
{
if (!RememberCredentials ||
string.IsNullOrWhiteSpace(UserName) ||
string.IsNullOrEmpty(Password) ||
!int.TryParse(Port, out var parsedPort) ||
parsedPort is < 1 or > 65535)
{
return;
}
DeviceEndpoint endpoint;
try
{
endpoint = new DeviceEndpoint(Host, parsedPort);
}
catch (ArgumentException)
{
return;
}
await coordinator.SaveCredentialsAsync(endpoint, new DeviceCredentials(UserName, Password));
}
[RelayCommand]
private async Task ConnectAsync()
{
if (!int.TryParse(Port, out var parsedPort) || parsedPort is < 1 or > 65535)
{
DetailMessage = "Enter a port between 1 and 65535.";
return;
}
if (!int.TryParse(Channel, out var parsedChannel) || parsedChannel < 0)
{
DetailMessage = "Enter a channel number of zero or greater.";
return;
}
IsBusy = true;
DetailMessage = string.Empty;
try
{
var endpoint = new DeviceEndpoint(Host, parsedPort);
var credentials = new DeviceCredentials(UserName, Password);
var authentication = await coordinator.ConnectAsync(endpoint, credentials, RememberCredentials);
if (!authentication.IsAuthenticated)
{
StatusMessage = "Authentication failed";
DetailMessage = $"Authentication rejected: {authentication.Failure}.";
return;
}
IsConnected = true;
StatusMessage = "Starting live view";
try
{
await coordinator.StartPreviewAsync(new ChannelId(parsedChannel));
}
catch (ProtocolNotVerifiedException exception)
{
StatusMessage = "Authenticated; live preview unavailable";
DetailMessage = exception.Message;
return;
}
_frameCancellation = new CancellationTokenSource();
_frameReader = ReadFramesAsync(_frameCancellation.Token);
StatusMessage = "Live view active";
}
catch (Exception exception)
{
StatusMessage = "Connection unavailable";
DetailMessage = exception.Message;
if (coordinator.IsConnected)
{
try
{
await coordinator.StopAsync();
}
catch (Exception stopException)
{
DetailMessage = $"{exception.Message} {stopException.Message}";
}
}
IsConnected = false;
}
finally
{
IsBusy = false;
}
}
[RelayCommand]
private async Task StopAsync()
{
IsBusy = true;
try
{
_frameCancellation?.Cancel();
await coordinator.StopAsync();
if (_frameReader is not null)
{
try
{
await _frameReader;
}
catch (OperationCanceledException)
{
}
}
_frameCancellation?.Dispose();
_frameCancellation = null;
_frameReader = null;
_frameBitmap?.Dispose();
_frameBitmap = null;
VideoFrame = null;
IsConnected = false;
StatusMessage = "Not connected";
DetailMessage = string.Empty;
}
catch (Exception exception)
{
StatusMessage = "Stop failed";
DetailMessage = exception.Message;
}
finally
{
IsBusy = false;
}
}
private async Task ReadFramesAsync(CancellationToken cancellationToken)
{
try
{
await foreach (var frame in coordinator.ReadFramesAsync(cancellationToken)
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
await Dispatcher.UIThread.InvokeAsync(() => PresentFrame(frame));
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception exception)
{
await Dispatcher.UIThread.InvokeAsync(() =>
{
StatusMessage = "Video stream ended";
DetailMessage = exception.Message;
});
}
}
private void PresentFrame(Media.DecodedVideoFrame frame)
{
if (_frameBitmap is null || _frameBitmap.PixelSize != new PixelSize(frame.Width, frame.Height))
{
_frameBitmap?.Dispose();
_frameBitmap = new WriteableBitmap(
new PixelSize(frame.Width, frame.Height),
new Vector(96, 96),
PixelFormats.Bgra8888,
AlphaFormat.Unpremul);
VideoFrame = _frameBitmap;
}
using var framebuffer = _frameBitmap.Lock();
var pixels = frame.Pixels.ToArray();
var rowLength = checked(frame.Width * 4);
for (var row = 0; row < frame.Height; row++)
{
Marshal.Copy(
pixels,
row * frame.Stride,
IntPtr.Add(framebuffer.Address, row * framebuffer.RowBytes),
rowLength);
}
}
}

View file

@ -1,14 +0,0 @@
using Avalonia;
namespace Surveillance.Client.App;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}

View file

@ -1,28 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<AssemblyName>Surveillance.Client.App</AssemblyName>
<RootNamespace>Surveillance.Client.App</RootNamespace>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<RuntimeIdentifiers>win-x64;linux-x64;osx-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Themes.Fluent" />
<PackageReference Include="CommunityToolkit.Mvvm" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="NLog" />
<ProjectReference Include="..\Surveillance.Client.Application\Surveillance.Client.Application.csproj" />
<ProjectReference Include="..\Surveillance.Protocol.RSNet\Surveillance.Protocol.RSNet.csproj" />
<ProjectReference Include="..\Surveillance.Media.FFmpegCore\Surveillance.Media.FFmpegCore.csproj" />
<ProjectReference Include="..\Surveillance.Infrastructure.Credentials\Surveillance.Infrastructure.Credentials.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\dependencies\**\*">
<Link>ffmpeg\%(RecursiveDir)%(Filename)%(Extension)</Link>
<TargetPath>ffmpeg\%(RecursiveDir)%(Filename)%(Extension)</TargetPath>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>

View file

@ -1,10 +0,0 @@
using Surveillance.Client.Domain;
namespace Surveillance.Client.Application;
public interface ICredentialStore
{
ValueTask<DeviceCredentials?> ReadAsync(string key, CancellationToken cancellationToken = default);
ValueTask WriteAsync(string key, DeviceCredentials credentials, CancellationToken cancellationToken = default);
}

View file

@ -1,29 +0,0 @@
using Surveillance.Client.Domain;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
namespace Surveillance.Client.Application;
public interface ILiveViewCoordinator : IAsyncDisposable
{
bool IsConnected { get; }
bool IsPreviewing { get; }
ValueTask<AuthenticationResult> ConnectAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
bool rememberCredentials,
CancellationToken cancellationToken = default);
ValueTask SaveCredentialsAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
CancellationToken cancellationToken = default);
ValueTask StartPreviewAsync(ChannelId channel, CancellationToken cancellationToken = default);
IAsyncEnumerable<DecodedVideoFrame> ReadFramesAsync(CancellationToken cancellationToken = default);
ValueTask StopAsync(CancellationToken cancellationToken = default);
}

View file

@ -1,272 +0,0 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Surveillance.Client.Domain;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
namespace Surveillance.Client.Application;
public sealed class LiveViewCoordinator(
IDeviceSessionFactory sessionFactory,
ICredentialStore credentialStore,
ILiveVideoDecoder decoder) : ILiveViewCoordinator
{
private readonly SemaphoreSlim _lifecycleGate = new(1, 1);
private IDeviceSession? _session;
private ILivePreview? _preview;
private CancellationTokenSource? _previewCancellation;
private Channel<DecodedVideoFrame>? _frames;
private Task? _framePump;
public bool IsConnected => _session is not null;
public bool IsPreviewing => _preview is not null;
public async ValueTask<AuthenticationResult> ConnectAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
bool rememberCredentials,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(credentials);
await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await StopCoreAsync().ConfigureAwait(false);
var effectiveCredentials = credentials;
if (string.IsNullOrEmpty(credentials.UserName) || string.IsNullOrEmpty(credentials.Password))
{
var savedCredentials = await credentialStore.ReadAsync(endpoint.CredentialKey, cancellationToken)
.ConfigureAwait(false);
if (savedCredentials is not null &&
string.IsNullOrEmpty(credentials.UserName) && string.IsNullOrEmpty(credentials.Password))
{
effectiveCredentials = savedCredentials;
}
else if (savedCredentials is not null)
{
effectiveCredentials = new DeviceCredentials(
string.IsNullOrEmpty(credentials.UserName) ? savedCredentials.UserName : credentials.UserName,
string.IsNullOrEmpty(credentials.Password) ? savedCredentials.Password : credentials.Password);
}
}
var session = await sessionFactory.ConnectAsync(endpoint, cancellationToken).ConfigureAwait(false);
try
{
var authentication = await session.AuthenticateAsync(effectiveCredentials, cancellationToken)
.ConfigureAwait(false);
if (!authentication.IsAuthenticated)
{
await session.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
await session.DisposeAsync().ConfigureAwait(false);
return authentication;
}
if (rememberCredentials)
{
await SaveCredentialsAsync(endpoint, effectiveCredentials, cancellationToken).ConfigureAwait(false);
}
_session = session;
return authentication;
}
catch
{
await DisposeSessionAsync(session).ConfigureAwait(false);
throw;
}
}
finally
{
_lifecycleGate.Release();
}
}
public ValueTask SaveCredentialsAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(endpoint);
ArgumentNullException.ThrowIfNull(credentials);
return credentialStore.WriteAsync(endpoint.CredentialKey, credentials, cancellationToken);
}
public async ValueTask StartPreviewAsync(ChannelId channel, CancellationToken cancellationToken = default)
{
await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_session is null)
{
throw new InvalidOperationException("Connect and authenticate before starting a preview.");
}
if (_preview is not null)
{
return;
}
var preview = await _session.StartPreviewAsync(channel, cancellationToken).ConfigureAwait(false);
var frames = Channel.CreateBounded<DecodedVideoFrame>(new BoundedChannelOptions(2)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = true
});
var previewCancellation = new CancellationTokenSource();
_preview = preview;
_frames = frames;
_previewCancellation = previewCancellation;
_framePump = PumpFramesAsync(preview, frames.Writer, previewCancellation.Token);
}
finally
{
_lifecycleGate.Release();
}
}
public async IAsyncEnumerable<DecodedVideoFrame> ReadFramesAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var frames = _frames ?? throw new InvalidOperationException("A preview has not been started.");
await foreach (var frame in frames.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
yield return frame;
}
}
public async ValueTask StopAsync(CancellationToken cancellationToken = default)
{
await _lifecycleGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await StopCoreAsync().ConfigureAwait(false);
}
finally
{
_lifecycleGate.Release();
}
}
public async ValueTask DisposeAsync()
{
await StopAsync().ConfigureAwait(false);
_lifecycleGate.Dispose();
}
private async Task PumpFramesAsync(
ILivePreview preview,
ChannelWriter<DecodedVideoFrame> writer,
CancellationToken cancellationToken)
{
try
{
await foreach (var frame in decoder.DecodeAsync(
preview.Stream,
preview.ReadPacketsAsync(cancellationToken),
cancellationToken)
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
await writer.WriteAsync(frame, cancellationToken).ConfigureAwait(false);
}
writer.TryComplete();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
writer.TryComplete();
}
catch (Exception exception)
{
writer.TryComplete(exception);
}
}
private async Task StopCoreAsync()
{
_previewCancellation?.Cancel();
var preview = _preview;
var framePump = _framePump;
var session = _session;
var frames = _frames;
_preview = null;
_framePump = null;
_session = null;
_frames = null;
Exception? failure = null;
if (preview is not null)
{
try
{
await preview.StopAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception exception)
{
failure = exception;
}
finally
{
await preview.DisposeAsync().ConfigureAwait(false);
}
}
if (framePump is not null)
{
try
{
await framePump.ConfigureAwait(false);
}
catch (Exception exception)
{
failure ??= exception;
}
}
frames?.Writer.TryComplete();
_previewCancellation?.Dispose();
_previewCancellation = null;
if (session is not null)
{
try
{
await session.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception exception)
{
failure ??= exception;
}
finally
{
await session.DisposeAsync().ConfigureAwait(false);
}
}
if (failure is not null)
{
throw new InvalidOperationException("The live session did not stop cleanly.", failure);
}
}
private static async ValueTask DisposeSessionAsync(IDeviceSession session)
{
try
{
await session.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
}
finally
{
await session.DisposeAsync().ConfigureAwait(false);
}
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Client.Application</AssemblyName>
<RootNamespace>Surveillance.Client.Application</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Surveillance.Client.Domain\Surveillance.Client.Domain.csproj" />
<ProjectReference Include="..\Surveillance.Client.Protocol.Abstractions\Surveillance.Client.Protocol.Abstractions.csproj" />
<ProjectReference Include="..\Surveillance.Client.Media.Abstractions\Surveillance.Client.Media.Abstractions.csproj" />
</ItemGroup>
</Project>

View file

@ -1,16 +0,0 @@
namespace Surveillance.Client.Domain;
public readonly record struct ChannelId
{
public ChannelId(int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
Value = value;
}
public int Value { get; }
}

View file

@ -1,10 +0,0 @@
namespace Surveillance.Client.Domain;
public sealed class DeviceCredentials(string userName, string password)
{
public string UserName { get; } = userName ?? throw new ArgumentNullException(nameof(userName));
public string Password { get; } = password ?? throw new ArgumentNullException(nameof(password));
public override string ToString() => "[redacted credentials]";
}

View file

@ -1,45 +0,0 @@
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace Surveillance.Client.Domain;
public sealed record DeviceEndpoint
{
public DeviceEndpoint(string host, int port)
{
if (string.IsNullOrWhiteSpace(host))
{
throw new ArgumentException("A device host is required.", nameof(host));
}
if (port is < 1 or > 65535)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
var normalizedHost = host.Trim();
if (!IPAddress.TryParse(normalizedHost, out _) && Uri.CheckHostName(normalizedHost) == UriHostNameType.Unknown)
{
throw new ArgumentException("The device host must be an IP address or DNS name.", nameof(host));
}
Host = normalizedHost;
Port = port;
}
public string Host { get; }
public int Port { get; }
public string CredentialKey
{
get
{
var bytes = Encoding.UTF8.GetBytes($"{Host.ToLowerInvariant()}:{Port}");
return $"SurveillanceClient/{Convert.ToHexString(SHA256.HashData(bytes))}";
}
}
public override string ToString() => $"{Host}:{Port}";
}

View file

@ -1,6 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Client.Domain</AssemblyName>
<RootNamespace>Surveillance.Client.Domain</RootNamespace>
</PropertyGroup>
</Project>

View file

@ -1,41 +0,0 @@
namespace Surveillance.Client.Media;
public sealed class DecodedVideoFrame
{
public DecodedVideoFrame(int width, int height, int stride, ReadOnlyMemory<byte> pixels)
{
if (width is < 1 or > 16384)
{
throw new ArgumentOutOfRangeException(nameof(width));
}
if (height is < 1 or > 16384)
{
throw new ArgumentOutOfRangeException(nameof(height));
}
if (stride < checked(width * 4))
{
throw new ArgumentOutOfRangeException(nameof(stride));
}
var requiredLength = checked(stride * height);
if (pixels.Length < requiredLength)
{
throw new ArgumentException("The frame buffer is shorter than its dimensions and stride.", nameof(pixels));
}
Width = width;
Height = height;
Stride = stride;
Pixels = pixels[..requiredLength];
}
public int Width { get; }
public int Height { get; }
public int Stride { get; }
public ReadOnlyMemory<byte> Pixels { get; }
}

View file

@ -1,9 +0,0 @@
namespace Surveillance.Client.Media;
public sealed record EncodedVideoPacket(
ReadOnlyMemory<byte> Data,
long? PresentationTimestamp,
long? DecodeTimestamp,
int TimeBaseNumerator,
int TimeBaseDenominator,
bool IsKeyFrame);

View file

@ -1,9 +0,0 @@
namespace Surveillance.Client.Media;
public interface ILiveVideoDecoder
{
IAsyncEnumerable<DecodedVideoFrame> DecodeAsync(
VideoStreamDescriptor stream,
IAsyncEnumerable<EncodedVideoPacket> packets,
CancellationToken cancellationToken = default);
}

View file

@ -1,6 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Client.Media.Abstractions</AssemblyName>
<RootNamespace>Surveillance.Client.Media</RootNamespace>
</PropertyGroup>
</Project>

View file

@ -1,7 +0,0 @@
namespace Surveillance.Client.Media;
public enum VideoCodec
{
H264,
H265
}

View file

@ -1,27 +0,0 @@
namespace Surveillance.Client.Media;
public sealed record VideoStreamDescriptor
{
public VideoStreamDescriptor(VideoCodec codec, int width, int height)
{
if (width is < 1 or > 16384)
{
throw new ArgumentOutOfRangeException(nameof(width));
}
if (height is < 1 or > 16384)
{
throw new ArgumentOutOfRangeException(nameof(height));
}
Codec = codec;
Width = width;
Height = height;
}
public VideoCodec Codec { get; }
public int Width { get; }
public int Height { get; }
}

View file

@ -1,19 +0,0 @@
namespace Surveillance.Client.Protocol;
public enum AuthenticationFailure
{
None,
InvalidCredentials,
NotAuthorized,
AccountDisabled,
DeviceBusy,
Unknown
}
public readonly record struct AuthenticationResult(bool IsAuthenticated, AuthenticationFailure Failure)
{
public static AuthenticationResult Success() => new(true, AuthenticationFailure.None);
public static AuthenticationResult Rejected(AuthenticationFailure failure) =>
new(false, failure == AuthenticationFailure.None ? AuthenticationFailure.Unknown : failure);
}

View file

@ -1,16 +0,0 @@
using Surveillance.Client.Domain;
namespace Surveillance.Client.Protocol;
public interface IDeviceSession : IAsyncDisposable
{
ValueTask<AuthenticationResult> AuthenticateAsync(
DeviceCredentials credentials,
CancellationToken cancellationToken = default);
ValueTask<ILivePreview> StartPreviewAsync(
ChannelId channel,
CancellationToken cancellationToken = default);
ValueTask DisconnectAsync(CancellationToken cancellationToken = default);
}

View file

@ -1,8 +0,0 @@
using Surveillance.Client.Domain;
namespace Surveillance.Client.Protocol;
public interface IDeviceSessionFactory
{
ValueTask<IDeviceSession> ConnectAsync(DeviceEndpoint endpoint, CancellationToken cancellationToken = default);
}

View file

@ -1,12 +0,0 @@
using Surveillance.Client.Media;
namespace Surveillance.Client.Protocol;
public interface ILivePreview : IAsyncDisposable
{
VideoStreamDescriptor Stream { get; }
IAsyncEnumerable<EncodedVideoPacket> ReadPacketsAsync(CancellationToken cancellationToken = default);
ValueTask StopAsync(CancellationToken cancellationToken = default);
}

View file

@ -1,3 +0,0 @@
namespace Surveillance.Client.Protocol;
public sealed class ProtocolNotVerifiedException(string message) : InvalidOperationException(message);

View file

@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Client.Protocol.Abstractions</AssemblyName>
<RootNamespace>Surveillance.Client.Protocol</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Surveillance.Client.Domain\Surveillance.Client.Domain.csproj" />
<ProjectReference Include="..\Surveillance.Client.Media.Abstractions\Surveillance.Client.Media.Abstractions.csproj" />
</ItemGroup>
</Project>

View file

@ -1,34 +0,0 @@
using Surveillance.Client.Application;
using Surveillance.Client.Domain;
namespace Surveillance.Infrastructure.Credentials;
public sealed class PlatformCredentialStore : ICredentialStore
{
private readonly ICredentialStore _store = OperatingSystem.IsWindows()
? new WindowsCredentialStore()
: new UnsupportedCredentialStore();
public ValueTask<DeviceCredentials?> ReadAsync(string key, CancellationToken cancellationToken = default) =>
_store.ReadAsync(key, cancellationToken);
public ValueTask WriteAsync(
string key,
DeviceCredentials credentials,
CancellationToken cancellationToken = default) =>
_store.WriteAsync(key, credentials, cancellationToken);
}
internal sealed class UnsupportedCredentialStore : ICredentialStore
{
public ValueTask<DeviceCredentials?> ReadAsync(string key, CancellationToken cancellationToken = default) =>
ValueTask.FromException<DeviceCredentials?>(new PlatformNotSupportedException(
"A native secure credential-store adapter is not implemented for this operating system."));
public ValueTask WriteAsync(
string key,
DeviceCredentials credentials,
CancellationToken cancellationToken = default) =>
ValueTask.FromException(new PlatformNotSupportedException(
"A native secure credential-store adapter is not implemented for this operating system."));
}

View file

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Infrastructure.Credentials</AssemblyName>
<RootNamespace>Surveillance.Infrastructure.Credentials</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Surveillance.Client.Application\Surveillance.Client.Application.csproj" />
</ItemGroup>
</Project>

View file

@ -1,152 +0,0 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Surveillance.Client.Application;
using Surveillance.Client.Domain;
namespace Surveillance.Infrastructure.Credentials;
internal sealed class WindowsCredentialStore : ICredentialStore
{
private const uint GenericCredential = 1;
private const uint LocalMachinePersistence = 2;
private const int NotFound = 1168;
private const int MaximumCredentialBytes = 2560;
public ValueTask<DeviceCredentials?> ReadAsync(string key, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
cancellationToken.ThrowIfCancellationRequested();
EnsureWindows();
if (!CredRead(key, GenericCredential, 0, out var credentialPointer))
{
var error = Marshal.GetLastWin32Error();
if (error == NotFound)
{
return ValueTask.FromResult<DeviceCredentials?>(null);
}
throw new Win32Exception(error, "Windows Credential Manager could not read the device credential.");
}
try
{
var credential = Marshal.PtrToStructure<NativeCredential>(credentialPointer);
var secretBytes = new byte[credential.CredentialBlobSize];
if (secretBytes.Length > 0)
{
Marshal.Copy(credential.CredentialBlob, secretBytes, 0, secretBytes.Length);
}
try
{
var password = Encoding.UTF8.GetString(secretBytes);
return ValueTask.FromResult<DeviceCredentials?>(new DeviceCredentials(credential.UserName ?? string.Empty, password));
}
finally
{
CryptographicOperations.ZeroMemory(secretBytes);
}
}
finally
{
CredFree(credentialPointer);
}
}
public ValueTask WriteAsync(
string key,
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
ArgumentNullException.ThrowIfNull(credentials);
cancellationToken.ThrowIfCancellationRequested();
EnsureWindows();
var secretBytes = Encoding.UTF8.GetBytes(credentials.Password);
if (secretBytes.Length > MaximumCredentialBytes)
{
CryptographicOperations.ZeroMemory(secretBytes);
throw new ArgumentException("The password exceeds the Windows Credential Manager size limit.", nameof(credentials));
}
var secretPointer = IntPtr.Zero;
try
{
if (secretBytes.Length > 0)
{
secretPointer = Marshal.AllocHGlobal(secretBytes.Length);
Marshal.Copy(secretBytes, 0, secretPointer, secretBytes.Length);
}
var credential = new NativeCredential
{
Type = GenericCredential,
TargetName = key,
UserName = credentials.UserName,
CredentialBlobSize = (uint)secretBytes.Length,
CredentialBlob = secretPointer,
Persist = LocalMachinePersistence
};
if (!CredWrite(ref credential, 0))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Windows Credential Manager could not store the device credential.");
}
return ValueTask.CompletedTask;
}
finally
{
CryptographicOperations.ZeroMemory(secretBytes);
if (secretPointer != IntPtr.Zero)
{
for (var index = 0; index < secretBytes.Length; index++)
{
Marshal.WriteByte(secretPointer, index, 0);
}
Marshal.FreeHGlobal(secretPointer);
}
}
}
private static void EnsureWindows()
{
if (!OperatingSystem.IsWindows())
{
throw new PlatformNotSupportedException("Windows Credential Manager is only available on Windows.");
}
}
[DllImport("Advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CredRead(string targetName, uint type, uint flags, out IntPtr credential);
[DllImport("Advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CredWrite(ref NativeCredential credential, uint flags);
[DllImport("Advapi32.dll", EntryPoint = "CredFree")]
private static extern void CredFree(IntPtr credential);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct NativeCredential
{
public uint Flags;
public uint Type;
[MarshalAs(UnmanagedType.LPWStr)] public string? TargetName;
[MarshalAs(UnmanagedType.LPWStr)] public string? Comment;
public long LastWritten;
public uint CredentialBlobSize;
public IntPtr CredentialBlob;
public uint Persist;
public uint AttributeCount;
public IntPtr Attributes;
[MarshalAs(UnmanagedType.LPWStr)] public string? TargetAlias;
[MarshalAs(UnmanagedType.LPWStr)] public string? UserName;
}
}

View file

@ -1,3 +0,0 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Surveillance.Media.FFmpegCore.Tests")]

View file

@ -1,147 +0,0 @@
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using FFMpegCore;
using FFMpegCore.Pipes;
using Surveillance.Client.Media;
namespace Surveillance.Media.FFmpegCore;
public sealed class FfmpegCoreLiveVideoDecoder : ILiveVideoDecoder
{
private const int FrameCapacity = 2;
private const int MaximumFrameBytes = 64 * 1024 * 1024;
public async IAsyncEnumerable<DecodedVideoFrame> DecodeAsync(
VideoStreamDescriptor stream,
IAsyncEnumerable<EncodedVideoPacket> packets,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(stream);
ArgumentNullException.ThrowIfNull(packets);
var frameBytes = checked(stream.Width * stream.Height * 4);
if (frameBytes > MaximumFrameBytes)
{
throw new ArgumentOutOfRangeException(nameof(stream), "The requested decoded frame exceeds the configured limit.");
}
using var processCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var frames = Channel.CreateBounded<DecodedVideoFrame>(new BoundedChannelOptions(FrameCapacity)
{
FullMode = BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = true
});
var source = new EncodedPacketPipeSource(stream.Codec, packets);
var sink = new StreamPipeSink((output, token) => ReadFramesAsync(output, stream, frames.Writer, token));
var processTask = RunProcessAsync(source, sink, frames.Writer, processCancellation.Token);
try
{
await foreach (var frame in frames.Reader.ReadAllAsync(processCancellation.Token).ConfigureAwait(false))
{
yield return frame;
}
await processTask.ConfigureAwait(false);
}
finally
{
processCancellation.Cancel();
await processTask.ConfigureAwait(false);
}
}
private static async Task RunProcessAsync(
EncodedPacketPipeSource source,
StreamPipeSink sink,
ChannelWriter<DecodedVideoFrame> writer,
CancellationToken cancellationToken)
{
try
{
var processor = FFMpegArguments
.FromPipeInput(source)
.OutputToPipe(sink, options => options
.WithVideoCodec("rawvideo")
.ForcePixelFormat("bgra")
.ForceFormat("rawvideo")
.WithCustomArgument("-an -sn -dn"));
await processor
.CancellableThrough(cancellationToken, timeout: 1000)
.ProcessAsynchronously()
.ConfigureAwait(false);
writer.TryComplete();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
writer.TryComplete();
}
catch (Exception exception)
{
writer.TryComplete(exception);
}
}
private static async Task ReadFramesAsync(
Stream output,
VideoStreamDescriptor stream,
ChannelWriter<DecodedVideoFrame> writer,
CancellationToken cancellationToken)
{
var stride = checked(stream.Width * 4);
var frameLength = checked(stride * stream.Height);
var buffer = new byte[frameLength];
while (true)
{
var offset = 0;
while (offset < frameLength)
{
var bytesRead = await output.ReadAsync(buffer.AsMemory(offset, frameLength - offset), cancellationToken)
.ConfigureAwait(false);
if (bytesRead == 0)
{
if (offset == 0)
{
return;
}
throw new InvalidDataException("FFmpeg ended in the middle of a raw video frame.");
}
offset += bytesRead;
}
await writer.WriteAsync(new DecodedVideoFrame(stream.Width, stream.Height, stride, buffer), cancellationToken)
.ConfigureAwait(false);
buffer = new byte[frameLength];
}
}
}
internal sealed class EncodedPacketPipeSource(
VideoCodec codec,
IAsyncEnumerable<EncodedVideoPacket> packets) : IPipeSource
{
public string GetStreamArguments() => codec switch
{
VideoCodec.H264 => "-f h264",
VideoCodec.H265 => "-f hevc",
_ => throw new ArgumentOutOfRangeException(nameof(codec))
};
public async Task WriteAsync(Stream outputStream, CancellationToken cancellationToken)
{
await foreach (var packet in packets.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (!packet.Data.IsEmpty)
{
await outputStream.WriteAsync(packet.Data, cancellationToken).ConfigureAwait(false);
}
}
}
}

View file

@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Media.FFmpegCore</AssemblyName>
<RootNamespace>Surveillance.Media.FFmpegCore</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FFMpegCore" />
<ProjectReference Include="..\Surveillance.Client.Media.Abstractions\Surveillance.Client.Media.Abstractions.csproj" />
</ItemGroup>
</Project>

View file

@ -1,284 +0,0 @@
using System.Buffers.Binary;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using NLog;
using Surveillance.Client.Domain;
using Surveillance.Client.Protocol;
namespace Surveillance.Protocol.RSNet;
internal sealed class RsNetDeviceSession(TcpClient client) : IDeviceSession
{
private const int HeaderLength = 16;
private const int LoginPayloadLength = 0x50;
private const int CredentialFieldLength = 0x24;
private const byte TransformedFrameFlag = 0x02;
private const uint LoginCommand = 0x1f;
private const uint MaximumResponseLength = 0x19000;
private const uint MaximumSuccessfulResponseLength = 0xcd0;
private static readonly UTF8Encoding CredentialEncoding = new(false, true);
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static long _requestId;
private readonly NetworkStream _stream = client.GetStream();
private bool _authenticationAttempted;
private bool _authenticated;
private bool _disposed;
public async ValueTask<AuthenticationResult> AuthenticateAsync(
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(credentials);
ObjectDisposedException.ThrowIf(_disposed, this);
if (_authenticationAttempted)
{
throw new InvalidOperationException("Authentication has already been attempted for this session.");
}
_authenticationAttempted = true;
var requestId = unchecked((uint)Interlocked.Increment(ref _requestId));
var request = BuildLoginRequest(credentials, requestId);
var stopwatch = Stopwatch.StartNew();
Logger.Info(
"Sending RSNet login request (RequestId={RequestId}, Command=0x{Command:X}, PayloadLength={PayloadLength})",
requestId,
LoginCommand,
LoginPayloadLength);
await WriteWithLoggingAsync(request, requestId, cancellationToken).ConfigureAwait(false);
var responseHeader = new byte[HeaderLength];
await ReadExactlyWithLoggingAsync(responseHeader, "login response header", requestId, cancellationToken)
.ConfigureAwait(false);
var additionalHeaderLength = (responseHeader[0] >> 2) * sizeof(uint);
if (additionalHeaderLength > 0)
{
var extendedResponseHeader = new byte[HeaderLength + additionalHeaderLength];
responseHeader.CopyTo(extendedResponseHeader, 0);
responseHeader = extendedResponseHeader;
await ReadExactlyWithLoggingAsync(
responseHeader.AsMemory(HeaderLength, additionalHeaderLength),
"login response header extension",
requestId,
cancellationToken)
.ConfigureAwait(false);
}
if ((responseHeader[0] & 0x03) == TransformedFrameFlag)
{
TransformBits(responseHeader.AsSpan(2), decode: true);
}
var status = BinaryPrimitives.ReadUInt16LittleEndian(responseHeader.AsSpan(2, 2));
var responseLength = BinaryPrimitives.ReadUInt32LittleEndian(responseHeader.AsSpan(8, 4));
Logger.Info(
"Received RSNet login response header (RequestId={RequestId}, Flags=0x{Flags:X2}, HeaderLength={HeaderLength}, Status=0x{Status:X4}, PayloadLength={PayloadLength})",
requestId,
responseHeader[0],
responseHeader.Length,
status,
responseLength);
if (responseLength > MaximumResponseLength)
{
Logger.Error("RSNet login response is oversized (RequestId={RequestId}, PayloadLength={PayloadLength})",
requestId, responseLength);
throw new ProtocolNotVerifiedException("The RSNet login response exceeds the supported frame size.");
}
if (status != 0 || responseLength < 8 || responseLength > MaximumSuccessfulResponseLength)
{
Logger.Warn(
"RSNet login was rejected or returned an unsupported payload (RequestId={RequestId}, Status=0x{Status:X4}, PayloadLength={PayloadLength})",
requestId,
status,
responseLength);
return AuthenticationResult.Rejected(AuthenticationFailure.Unknown);
}
var responsePayload = new byte[(int)responseLength];
await ReadExactlyWithLoggingAsync(responsePayload, "login response payload", requestId, cancellationToken)
.ConfigureAwait(false);
if ((responseHeader[0] & 0x03) == TransformedFrameFlag)
{
TransformBits(responsePayload, decode: true);
}
if (responsePayload[6] != (byte)'S' || responsePayload[7] != (byte)'R')
{
Logger.Warn("RSNet login response marker was invalid (RequestId={RequestId})", requestId);
return AuthenticationResult.Rejected(AuthenticationFailure.Unknown);
}
_authenticated = true;
Logger.Info(
"RSNet authentication succeeded (RequestId={RequestId}, ElapsedMilliseconds={ElapsedMilliseconds})",
requestId,
stopwatch.ElapsedMilliseconds);
return AuthenticationResult.Success();
}
public ValueTask<ILivePreview> StartPreviewAsync(
ChannelId channel,
CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_authenticated)
{
throw new InvalidOperationException("Authenticate before requesting a preview.");
}
return ValueTask.FromException<ILivePreview>(new ProtocolNotVerifiedException(
"RSNet preview commands and media framing are not yet verified."));
}
public ValueTask DisconnectAsync(CancellationToken cancellationToken = default)
{
if (!_disposed)
{
_disposed = true;
client.Dispose();
}
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => DisconnectAsync();
private static byte[] BuildLoginRequest(DeviceCredentials credentials, uint requestId)
{
var request = new byte[HeaderLength + LoginPayloadLength];
var header = request.AsSpan(0, HeaderLength);
var payload = request.AsSpan(HeaderLength, LoginPayloadLength);
BinaryPrimitives.WriteUInt32LittleEndian(header[4..8], LoginCommand);
BinaryPrimitives.WriteUInt32LittleEndian(header[8..12], LoginPayloadLength);
header[0] = TransformedFrameFlag;
BinaryPrimitives.WriteUInt32LittleEndian(header[12..16], requestId);
WriteCredential(payload[..CredentialFieldLength], credentials.UserName, nameof(credentials.UserName));
WriteCredential(payload.Slice(CredentialFieldLength, CredentialFieldLength), credentials.Password,
nameof(credentials.Password));
TransformBits(header[2..], decode: false);
TransformBits(payload, decode: false);
return request;
}
private static void TransformBits(Span<byte> data, bool decode)
{
var bitCount = checked(data.Length * 8);
if (bitCount == 0)
{
return;
}
var next = new int[bitCount];
for (var index = 0; index < bitCount; index++)
{
next[index] = (index + 1) % bitCount;
}
var current = bitCount - 1;
var remaining = bitCount;
for (var step = 0; step < 2 % remaining; step++)
{
current = next[current];
}
var transformed = new byte[data.Length];
for (var bitIndex = 0; bitIndex < bitCount; bitIndex++)
{
for (var step = 0; step < 2 % remaining; step++)
{
current = next[current];
}
var selected = next[current];
var sourceBitIndex = decode ? bitIndex : selected;
var destinationBitIndex = decode ? selected : bitIndex;
if ((data[sourceBitIndex / 8] & (0x80 >> (sourceBitIndex % 8))) != 0)
{
transformed[destinationBitIndex / 8] |= (byte)(0x80 >> (destinationBitIndex % 8));
}
next[current] = next[selected];
remaining--;
}
transformed.AsSpan().CopyTo(data);
}
private static void WriteCredential(Span<byte> destination, string value, string parameterName)
{
if (value.Contains('\0'))
{
throw new ArgumentException("Credentials cannot contain a NUL character.", parameterName);
}
var encoded = CredentialEncoding.GetBytes(value);
if (encoded.Length >= destination.Length)
{
throw new ArgumentException("Each RSNet credential must fit in 35 UTF-8 bytes.", parameterName);
}
encoded.CopyTo(destination);
}
private async ValueTask WriteWithLoggingAsync(
ReadOnlyMemory<byte> request,
uint requestId,
CancellationToken cancellationToken)
{
var stopwatch = Stopwatch.StartNew();
try
{
await _stream.WriteAsync(request, cancellationToken).ConfigureAwait(false);
Logger.Debug(
"Sent RSNet login request (RequestId={RequestId}, Bytes={ByteCount}, ElapsedMilliseconds={ElapsedMilliseconds})",
requestId,
request.Length,
stopwatch.ElapsedMilliseconds);
}
catch (Exception exception)
{
LogIoFailure("login request write", requestId, stopwatch, exception);
throw;
}
}
private async ValueTask ReadExactlyWithLoggingAsync(
Memory<byte> buffer,
string stage,
uint requestId,
CancellationToken cancellationToken)
{
var stopwatch = Stopwatch.StartNew();
try
{
await _stream.ReadExactlyAsync(buffer, cancellationToken).ConfigureAwait(false);
Logger.Debug(
"Read RSNet {Stage} (RequestId={RequestId}, Bytes={ByteCount}, ElapsedMilliseconds={ElapsedMilliseconds})",
stage,
requestId,
buffer.Length,
stopwatch.ElapsedMilliseconds);
}
catch (Exception exception)
{
LogIoFailure(stage, requestId, stopwatch, exception);
throw;
}
}
private static void LogIoFailure(string stage, uint requestId, Stopwatch stopwatch, Exception exception)
{
var socketException = exception as SocketException ?? exception.InnerException as SocketException;
Logger.Error(
exception,
"RSNet {Stage} failed (RequestId={RequestId}, ElapsedMilliseconds={ElapsedMilliseconds}, SocketError={SocketError})",
stage,
requestId,
stopwatch.ElapsedMilliseconds,
socketException?.SocketErrorCode.ToString() ?? "n/a");
}
}

View file

@ -1,48 +0,0 @@
using System.Diagnostics;
using Surveillance.Client.Domain;
using Surveillance.Client.Protocol;
using System.Net.Sockets;
using NLog;
namespace Surveillance.Protocol.RSNet;
public sealed class RsNetSessionFactory : IDeviceSessionFactory
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public async ValueTask<IDeviceSession> ConnectAsync(
DeviceEndpoint endpoint,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(endpoint);
cancellationToken.ThrowIfCancellationRequested();
var client = new TcpClient();
var stopwatch = Stopwatch.StartNew();
Logger.Info("Connecting to RSNet endpoint {Host}:{Port}", endpoint.Host, endpoint.Port);
try
{
await client.ConnectAsync(endpoint.Host, endpoint.Port, cancellationToken).ConfigureAwait(false);
client.NoDelay = true;
Logger.Info(
"Connected to RSNet endpoint {Host}:{Port} in {ElapsedMilliseconds} ms",
endpoint.Host,
endpoint.Port,
stopwatch.ElapsedMilliseconds);
return new RsNetDeviceSession(client);
}
catch (Exception exception)
{
var socketException = exception as SocketException ?? exception.InnerException as SocketException;
Logger.Error(
exception,
"RSNet connection to {Host}:{Port} failed after {ElapsedMilliseconds} ms (SocketError={SocketError})",
endpoint.Host,
endpoint.Port,
stopwatch.ElapsedMilliseconds,
socketException?.SocketErrorCode.ToString() ?? "n/a");
client.Dispose();
throw;
}
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Surveillance.Protocol.RSNet</AssemblyName>
<RootNamespace>Surveillance.Protocol.RSNet</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NLog" />
<ProjectReference Include="..\Surveillance.Client.Domain\Surveillance.Client.Domain.csproj" />
<ProjectReference Include="..\Surveillance.Client.Protocol.Abstractions\Surveillance.Client.Protocol.Abstractions.csproj" />
</ItemGroup>
</Project>

View file

@ -1,139 +0,0 @@
using Surveillance.Client.Application;
using Surveillance.Client.App;
using Surveillance.Client.Domain;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
using Xunit;
namespace Surveillance.Client.App.Tests;
public sealed class MainWindowViewModelTests
{
[Fact]
public void RemembersCredentialsByDefault()
{
var viewModel = new MainWindowViewModel(new CoordinatorStub());
Assert.True(viewModel.RememberCredentials);
}
[Fact]
public async Task KeepsAuthenticatedSessionWhenPreviewProtocolIsUnverified()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator);
await viewModel.ConnectCommand.ExecuteAsync(null);
Assert.True(viewModel.IsConnected);
Assert.True(coordinator.IsConnected);
Assert.Equal("Authenticated; live preview unavailable", viewModel.StatusMessage);
}
[Fact]
public async Task InvalidPortDoesNotAttemptToConnect()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator) { Port = "70000" };
await viewModel.ConnectCommand.ExecuteAsync(null);
Assert.Equal(0, coordinator.ConnectCount);
Assert.Contains("port", viewModel.DetailMessage, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SavesCredentialsOnCloseWhenRememberIsEnabled()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator)
{
Host = "camera.local",
Port = "9000",
UserName = "viewer",
Password = "secret"
};
await viewModel.SaveCredentialsOnCloseAsync();
Assert.Equal(1, coordinator.SaveCount);
Assert.Equal("camera.local", coordinator.SavedEndpoint?.Host);
Assert.Equal(9000, coordinator.SavedEndpoint?.Port);
Assert.Equal("viewer", coordinator.SavedCredentials?.UserName);
Assert.Equal("secret", coordinator.SavedCredentials?.Password);
}
[Fact]
public async Task DoesNotSaveIncompleteOrUnrememberedCredentialsOnClose()
{
var coordinator = new CoordinatorStub();
var viewModel = new MainWindowViewModel(coordinator)
{
UserName = "viewer",
Password = "secret",
RememberCredentials = false
};
await viewModel.SaveCredentialsOnCloseAsync();
viewModel.RememberCredentials = true;
viewModel.Password = string.Empty;
await viewModel.SaveCredentialsOnCloseAsync();
Assert.Equal(0, coordinator.SaveCount);
}
private sealed class CoordinatorStub : ILiveViewCoordinator
{
public int ConnectCount { get; private set; }
public int SaveCount { get; private set; }
public DeviceEndpoint? SavedEndpoint { get; private set; }
public DeviceCredentials? SavedCredentials { get; private set; }
public bool IsConnected { get; private set; }
public bool IsPreviewing => false;
public ValueTask<AuthenticationResult> ConnectAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
bool rememberCredentials,
CancellationToken cancellationToken = default)
{
ConnectCount++;
IsConnected = true;
return ValueTask.FromResult(AuthenticationResult.Success());
}
public ValueTask SaveCredentialsAsync(
DeviceEndpoint endpoint,
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
SaveCount++;
SavedEndpoint = endpoint;
SavedCredentials = credentials;
return ValueTask.CompletedTask;
}
public ValueTask StartPreviewAsync(ChannelId channel, CancellationToken cancellationToken = default) =>
ValueTask.FromException(new ProtocolNotVerifiedException("Preview protocol is not verified."));
public async IAsyncEnumerable<DecodedVideoFrame> ReadFramesAsync(
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
yield break;
}
public ValueTask StopAsync(CancellationToken cancellationToken = default)
{
IsConnected = false;
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Client.App\Surveillance.Client.App.csproj" />
</ItemGroup>
</Project>

View file

@ -1,223 +0,0 @@
using System.Runtime.CompilerServices;
using Surveillance.Client.Application;
using Surveillance.Client.Domain;
using Surveillance.Client.Media;
using Surveillance.Client.Protocol;
using Xunit;
namespace Surveillance.Client.Application.Tests;
public sealed class LiveViewCoordinatorTests
{
[Fact]
public async Task ConnectLoadsRememberedCredentialsAndPreviewCanBeStopped()
{
var savedCredentials = new DeviceCredentials("viewer", "secret");
var store = new FakeCredentialStore(savedCredentials);
var preview = new FakePreview();
var session = new FakeSession(preview, AuthenticationResult.Success());
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(session),
store,
new FakeDecoder());
var result = await coordinator.ConnectAsync(
new DeviceEndpoint("camera.local", 34567),
new DeviceCredentials(string.Empty, string.Empty),
rememberCredentials: true,
TestContext.Current.CancellationToken);
Assert.True(result.IsAuthenticated);
Assert.Same(savedCredentials, session.AuthenticatedCredentials);
Assert.Equal(1, store.ReadCount);
Assert.Equal(1, store.WriteCount);
Assert.True(coordinator.IsConnected);
await coordinator.StartPreviewAsync(new ChannelId(0), TestContext.Current.CancellationToken);
var receivedFrames = new List<DecodedVideoFrame>();
await foreach (var frame in coordinator.ReadFramesAsync(TestContext.Current.CancellationToken))
{
receivedFrames.Add(frame);
}
Assert.Single(receivedFrames);
Assert.True(coordinator.IsPreviewing);
await coordinator.StopAsync(TestContext.Current.CancellationToken);
Assert.False(coordinator.IsConnected);
Assert.False(coordinator.IsPreviewing);
Assert.True(preview.WasStopped);
Assert.True(session.WasDisconnected);
}
[Fact]
public async Task RejectedAuthenticationDoesNotPersistCredentials()
{
var store = new FakeCredentialStore(null);
var session = new FakeSession(
new FakePreview(),
AuthenticationResult.Rejected(AuthenticationFailure.InvalidCredentials));
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(session),
store,
new FakeDecoder());
var result = await coordinator.ConnectAsync(
new DeviceEndpoint("127.0.0.1", 34567),
new DeviceCredentials("viewer", "wrong"),
rememberCredentials: true,
TestContext.Current.CancellationToken);
Assert.False(result.IsAuthenticated);
Assert.False(coordinator.IsConnected);
Assert.Equal(0, store.WriteCount);
Assert.True(session.WasDisconnected);
await coordinator.DisposeAsync();
}
[Fact]
public async Task SaveCredentialsWritesToTheEndpointCredentialKey()
{
var store = new FakeCredentialStore(null);
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(new FakeSession(new FakePreview(), AuthenticationResult.Success())),
store,
new FakeDecoder());
var endpoint = new DeviceEndpoint("camera.local", 9000);
var credentials = new DeviceCredentials("viewer", "secret");
await coordinator.SaveCredentialsAsync(endpoint, credentials, TestContext.Current.CancellationToken);
Assert.Equal(endpoint.CredentialKey, store.LastKey);
Assert.Same(credentials, store.LastCredentials);
Assert.Equal(1, store.WriteCount);
await coordinator.DisposeAsync();
}
[Fact]
public async Task ConnectUsesSavedCredentialForBlankField()
{
var savedCredentials = new DeviceCredentials("saved-user", "saved-password");
var store = new FakeCredentialStore(savedCredentials);
var session = new FakeSession(new FakePreview(), AuthenticationResult.Success());
var coordinator = new LiveViewCoordinator(
new FakeSessionFactory(session),
store,
new FakeDecoder());
var result = await coordinator.ConnectAsync(
new DeviceEndpoint("127.0.0.1", 34567),
new DeviceCredentials("typed-user", string.Empty),
rememberCredentials: true,
TestContext.Current.CancellationToken);
Assert.True(result.IsAuthenticated);
Assert.Equal("typed-user", session.AuthenticatedCredentials?.UserName);
Assert.Equal("saved-password", session.AuthenticatedCredentials?.Password);
Assert.Equal(1, store.ReadCount);
Assert.Equal(1, store.WriteCount);
await coordinator.DisposeAsync();
}
private sealed class FakeCredentialStore(DeviceCredentials? credentials) : ICredentialStore
{
public int ReadCount { get; private set; }
public int WriteCount { get; private set; }
public string? LastKey { get; private set; }
public DeviceCredentials? LastCredentials { get; private set; }
public ValueTask<DeviceCredentials?> ReadAsync(string key, CancellationToken cancellationToken = default)
{
ReadCount++;
return ValueTask.FromResult(credentials);
}
public ValueTask WriteAsync(
string key,
DeviceCredentials value,
CancellationToken cancellationToken = default)
{
WriteCount++;
LastKey = key;
LastCredentials = value;
return ValueTask.CompletedTask;
}
}
private sealed class FakeSessionFactory(FakeSession session) : IDeviceSessionFactory
{
public ValueTask<IDeviceSession> ConnectAsync(
DeviceEndpoint endpoint,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<IDeviceSession>(session);
}
private sealed class FakeSession(FakePreview preview, AuthenticationResult authentication) : IDeviceSession
{
public DeviceCredentials? AuthenticatedCredentials { get; private set; }
public bool WasDisconnected { get; private set; }
public ValueTask<AuthenticationResult> AuthenticateAsync(
DeviceCredentials credentials,
CancellationToken cancellationToken = default)
{
AuthenticatedCredentials = credentials;
return ValueTask.FromResult(authentication);
}
public ValueTask<ILivePreview> StartPreviewAsync(
ChannelId channel,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<ILivePreview>(preview);
public ValueTask DisconnectAsync(CancellationToken cancellationToken = default)
{
WasDisconnected = true;
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class FakePreview : ILivePreview
{
public VideoStreamDescriptor Stream { get; } = new(VideoCodec.H264, 1, 1);
public bool WasStopped { get; private set; }
public async IAsyncEnumerable<EncodedVideoPacket> ReadPacketsAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
yield return new EncodedVideoPacket(new byte[] { 1 }, null, null, 1, 1, true);
await Task.CompletedTask;
}
public ValueTask StopAsync(CancellationToken cancellationToken = default)
{
WasStopped = true;
return ValueTask.CompletedTask;
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class FakeDecoder : ILiveVideoDecoder
{
public async IAsyncEnumerable<DecodedVideoFrame> DecodeAsync(
VideoStreamDescriptor stream,
IAsyncEnumerable<EncodedVideoPacket> packets,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var packet in packets.WithCancellation(cancellationToken))
{
yield return new DecodedVideoFrame(1, 1, 4, new byte[] { 0, 0, 0, 255 });
yield break;
}
}
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Client.Application\Surveillance.Client.Application.csproj" />
</ItemGroup>
</Project>

View file

@ -1,34 +0,0 @@
using Surveillance.Client.Domain;
using Xunit;
namespace Surveillance.Client.Domain.Tests;
public sealed class DeviceEndpointTests
{
[Fact]
public void CredentialKeyIsStableAcrossHostCaseAndWhitespace()
{
var first = new DeviceEndpoint(" camera.local ", 34567);
var second = new DeviceEndpoint("CAMERA.local", 34567);
Assert.Equal(first.CredentialKey, second.CredentialKey);
Assert.Equal("camera.local:34567", first.ToString());
}
[Theory]
[InlineData(0)]
[InlineData(65536)]
public void RejectsPortsOutsideTcpRange(int port)
{
Assert.Throws<ArgumentOutOfRangeException>(() => new DeviceEndpoint("127.0.0.1", port));
}
[Fact]
public void CredentialsNeverExposeTheirValuesInToString()
{
var credentials = new DeviceCredentials("viewer", "a-secret-value");
Assert.DoesNotContain("viewer", credentials.ToString(), StringComparison.Ordinal);
Assert.DoesNotContain("a-secret-value", credentials.ToString(), StringComparison.Ordinal);
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Client.Domain\Surveillance.Client.Domain.csproj" />
</ItemGroup>
</Project>

View file

@ -1,33 +0,0 @@
using System.Runtime.CompilerServices;
using Surveillance.Client.Media;
using Surveillance.Media.FFmpegCore;
using Xunit;
namespace Surveillance.Media.FFmpegCore.Tests;
public sealed class FfmpegCoreLiveVideoDecoderTests
{
[Fact]
public async Task RejectsDecodedFramesAboveConfiguredMemoryLimit()
{
var decoder = new FfmpegCoreLiveVideoDecoder();
var stream = new VideoStreamDescriptor(VideoCodec.H264, 4097, 4096);
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await foreach (var _ in decoder.DecodeAsync(
stream,
EmptyPackets(TestContext.Current.CancellationToken),
TestContext.Current.CancellationToken))
{
}
});
}
private static async IAsyncEnumerable<EncodedVideoPacket> EmptyPackets(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
yield break;
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Media.FFmpegCore\Surveillance.Media.FFmpegCore.csproj" />
</ItemGroup>
</Project>

View file

@ -1,181 +0,0 @@
using System.Buffers.Binary;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Surveillance.Client.Domain;
using Surveillance.Client.Protocol;
using Surveillance.Protocol.RSNet;
using Xunit;
namespace Surveillance.Protocol.RSNet.Tests;
public sealed class RsNetSessionFactoryTests
{
[Fact]
public void DecodesCapturedNativeModeZeroRequestHeader()
{
var header = Convert.FromHexString("02000601001000400100040082000083");
TransformBits(header.AsSpan(2), decode: true);
Assert.Equal(0x02u, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0, 4)));
Assert.Equal(0x1fu, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(4, 4)));
Assert.Equal(0x50u, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(8, 4)));
Assert.Equal(348u, BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(12, 4)));
}
[Fact]
public async Task SendsReconstructedLoginFrameAndAcceptsSuccessfulResponse()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var endpoint = new DeviceEndpoint(IPAddress.Loopback.ToString(), ((IPEndPoint)listener.LocalEndpoint).Port);
var serverTask = ReceiveLoginAndRespondAsync(listener, 0, SuccessfulResponsePayload(), timeout.Token);
var factory = new RsNetSessionFactory();
await using var session = await factory.ConnectAsync(endpoint, timeout.Token);
var result = await session.AuthenticateAsync(
new DeviceCredentials("viewer", "secret"),
timeout.Token);
var request = await serverTask;
Assert.True(result.IsAuthenticated);
Assert.Equal(0x02u, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(0, 4)));
Assert.Equal(0x1fu, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(4, 4)));
Assert.Equal(0x50u, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(8, 4)));
Assert.NotEqual(0u, BinaryPrimitives.ReadUInt32LittleEndian(request.Header.AsSpan(12, 4)));
var expectedPayload = new byte[0x50];
Encoding.UTF8.GetBytes("viewer").CopyTo(expectedPayload, 0);
Encoding.UTF8.GetBytes("secret").CopyTo(expectedPayload, 0x24);
Assert.Equal(expectedPayload, request.Payload);
}
[Fact]
public async Task RejectsNonzeroLoginStatus()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var endpoint = new DeviceEndpoint(IPAddress.Loopback.ToString(), ((IPEndPoint)listener.LocalEndpoint).Port);
var serverTask = ReceiveLoginAndRespondAsync(listener, 10, [], timeout.Token);
var factory = new RsNetSessionFactory();
await using var session = await factory.ConnectAsync(endpoint, timeout.Token);
var result = await session.AuthenticateAsync(new DeviceCredentials("viewer", "wrong"), timeout.Token);
await serverTask;
Assert.False(result.IsAuthenticated);
Assert.Equal(AuthenticationFailure.Unknown, result.Failure);
}
[Fact]
public async Task AcceptsResponseWithNativeModeFlagsAndExtendedHeader()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var endpoint = new DeviceEndpoint(IPAddress.Loopback.ToString(), ((IPEndPoint)listener.LocalEndpoint).Port);
var serverTask = ReceiveLoginAndRespondAsync(
listener,
0,
SuccessfulResponsePayload(),
timeout.Token,
responseFlags: 0x06);
var factory = new RsNetSessionFactory();
await using var session = await factory.ConnectAsync(endpoint, timeout.Token);
var result = await session.AuthenticateAsync(new DeviceCredentials("viewer", "secret"), timeout.Token);
await serverTask;
Assert.True(result.IsAuthenticated);
}
private static async Task<(byte[] Header, byte[] Payload)> ReceiveLoginAndRespondAsync(
TcpListener listener,
ushort status,
byte[] responsePayload,
CancellationToken cancellationToken,
byte responseFlags = 0)
{
using var client = await listener.AcceptTcpClientAsync(cancellationToken);
var stream = client.GetStream();
var header = new byte[16];
var payload = new byte[0x50];
await stream.ReadExactlyAsync(header, cancellationToken);
await stream.ReadExactlyAsync(payload, cancellationToken);
if ((header[0] & 0x03) == 0x02)
{
TransformBits(header.AsSpan(2), decode: true);
TransformBits(payload, decode: true);
}
var additionalHeaderLength = (responseFlags >> 2) * sizeof(uint);
var responseHeader = new byte[16 + additionalHeaderLength];
responseHeader[0] = responseFlags;
BinaryPrimitives.WriteUInt16LittleEndian(responseHeader.AsSpan(2, 2), status);
BinaryPrimitives.WriteUInt32LittleEndian(responseHeader.AsSpan(8, 4), (uint)responsePayload.Length);
var wireResponsePayload = responsePayload.ToArray();
if ((responseFlags & 0x03) == 0x02)
{
TransformBits(responseHeader.AsSpan(2), decode: false);
TransformBits(wireResponsePayload, decode: false);
}
await stream.WriteAsync(responseHeader, cancellationToken);
await stream.WriteAsync(wireResponsePayload, cancellationToken);
return (header, payload);
}
private static void TransformBits(Span<byte> data, bool decode)
{
var bitCount = data.Length * 8;
if (bitCount == 0)
{
return;
}
var next = new int[bitCount];
for (var index = 0; index < bitCount; index++)
{
next[index] = (index + 1) % bitCount;
}
var current = bitCount - 1;
var remaining = bitCount;
for (var step = 0; step < 2 % remaining; step++)
{
current = next[current];
}
var transformed = new byte[data.Length];
for (var bitIndex = 0; bitIndex < bitCount; bitIndex++)
{
for (var step = 0; step < 2 % remaining; step++)
{
current = next[current];
}
var selected = next[current];
var sourceBitIndex = decode ? bitIndex : selected;
var destinationBitIndex = decode ? selected : bitIndex;
if ((data[sourceBitIndex / 8] & (0x80 >> (sourceBitIndex % 8))) != 0)
{
transformed[destinationBitIndex / 8] |= (byte)(0x80 >> (destinationBitIndex % 8));
}
next[current] = next[selected];
remaining--;
}
transformed.AsSpan().CopyTo(data);
}
private static byte[] SuccessfulResponsePayload()
{
var payload = new byte[8];
payload[6] = (byte)'S';
payload[7] = (byte)'R';
return payload;
}
}

View file

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<ProjectReference Include="..\..\src\Surveillance.Protocol.RSNet\Surveillance.Protocol.RSNet.csproj" />
</ItemGroup>
</Project>