Scaffolded c# app

This commit is contained in:
Marco 2026-10-16 15:36:51 +02:00
commit 387a6ac182
57 changed files with 3930 additions and 0 deletions

5
managed-client/.gitignore vendored Normal file
View file

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

View file

@ -0,0 +1,11 @@
<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

@ -0,0 +1,15 @@
<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>

24
managed-client/README.md Normal file
View file

@ -0,0 +1,24 @@
# 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

@ -0,0 +1,19 @@
<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

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

View file

@ -0,0 +1,8 @@
<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

@ -0,0 +1,79 @@
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

@ -0,0 +1,66 @@
<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

@ -0,0 +1,45 @@
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

@ -0,0 +1,248 @@
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

@ -0,0 +1,14 @@
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

@ -0,0 +1,28 @@
<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

@ -0,0 +1,10 @@
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

@ -0,0 +1,29 @@
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

@ -0,0 +1,272 @@
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

@ -0,0 +1,11 @@
<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

@ -0,0 +1,16 @@
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

@ -0,0 +1,10 @@
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

@ -0,0 +1,45 @@
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

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

View file

@ -0,0 +1,41 @@
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

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,27 @@
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

@ -0,0 +1,19 @@
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

@ -0,0 +1,16 @@
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

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

View file

@ -0,0 +1,12 @@
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

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

View file

@ -0,0 +1,10 @@
<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

@ -0,0 +1,34 @@
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

@ -0,0 +1,9 @@
<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

@ -0,0 +1,152 @@
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

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

View file

@ -0,0 +1,147 @@
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

@ -0,0 +1,10 @@
<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

@ -0,0 +1,284 @@
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

@ -0,0 +1,48 @@
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

@ -0,0 +1,11 @@
<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

@ -0,0 +1,139 @@
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

@ -0,0 +1,11 @@
<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

@ -0,0 +1,223 @@
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

@ -0,0 +1,11 @@
<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

@ -0,0 +1,34 @@
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

@ -0,0 +1,11 @@
<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

@ -0,0 +1,33 @@
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

@ -0,0 +1,11 @@
<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

@ -0,0 +1,181 @@
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

@ -0,0 +1,11 @@
<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>