Compare commits

...
Sign in to create a new pull request.

1 commit

Author SHA1 Message Date
Marco
387a6ac182 Scaffolded c# app 2026-10-16 15:36:51 +02:00
57 changed files with 3930 additions and 0 deletions

17
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,17 @@
{
"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
}
]
}

25
.vscode/tasks.json vendored Normal file
View file

@ -0,0 +1,25 @@
{
"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
SurveillancePlugin.exe Normal file

Binary file not shown.

1205
docs/installation.md Normal file

File diff suppressed because it is too large Load diff

View file

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

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>