diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b196db9 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + pull_request: + branches: + - main + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + + - name: Set up Python 3.14 + run: uv python install 3.14 + + - name: Sync dependencies + run: uv sync + + - name: Lint + run: uv run ruff check . + + - name: Format check + run: uv run ruff format --check . + + - name: Type check + run: uv run ty check + + - name: Test + run: uv run pytest diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c2ade4f --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,110 @@ +name: Release + +on: + push: + branches: + - main + +permissions: + contents: write + +jobs: + release: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Sync locked dependencies + run: uv sync --locked + + - name: Detect version change + id: version + env: + GH_TOKEN: ${{ github.token }} + shell: pwsh + run: | + $current = (uv version --short).Trim() + if ([string]::IsNullOrWhiteSpace($current)) { + throw "Current project version is empty." + } + "version=$current" >> $env:GITHUB_OUTPUT + $tag = "v$current" + $tagResponse = gh api "repos/${{ github.repository }}/git/ref/tags/$tag" --include 2>&1 + $tagExitCode = $LASTEXITCODE + $LASTEXITCODE = 0 + if ($tagExitCode -eq 0) { + $tagExists = $true + } elseif ($tagResponse -match "404|Not Found") { + $tagExists = $false + } else { + throw "Failed to check tag $tag: $tagResponse" + } + + $releaseResponse = gh api "repos/${{ github.repository }}/releases/tags/$tag" --include 2>&1 + $releaseExitCode = $LASTEXITCODE + $LASTEXITCODE = 0 + if ($releaseExitCode -eq 0) { + $releaseExists = $true + } elseif ($releaseResponse -match "404|Not Found") { + $releaseExists = $false + } else { + throw "Failed to check release $tag: $releaseResponse" + } + + if ($releaseExists -and -not $tagExists) { + throw "Inconsistent release state: release $tag exists without its tag." + } + + $releaseRequired = -not $releaseExists + $tagRequired = -not $tagExists + "release_required=$($releaseRequired.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT + "tag_required=$($tagRequired.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT + Write-Host "Tag exists: $tagExists; release exists: $releaseExists" + + - name: Build Windows app + if: steps.version.outputs.release_required == 'true' + env: + PYTHONIOENCODING: utf-8 + run: | + uv run flet clean + uv run flet build windows --python-version 3.14 --yes + + - name: Create portable distribution ZIP + if: steps.version.outputs.release_required == 'true' + run: uv run python tools/package_windows_release.py + + - name: Verify release ZIP + if: steps.version.outputs.release_required == 'true' + shell: pwsh + run: | + $zip = "dist/QuickReplay-${{ steps.version.outputs.version }}-windows-x64.zip" + if (-not (Test-Path $zip)) { throw "Release ZIP was not generated: $zip" } + + - name: Create tag + if: steps.version.outputs.tag_required == 'true' + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git tag -a "v$env:VERSION" "${{ github.sha }}" -m "QuickReplay v$env:VERSION" + git push origin "v$env:VERSION" + + - name: Create GitHub Release + if: steps.version.outputs.release_required == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + $tag = "v${{ steps.version.outputs.version }}" + $zip = "dist/QuickReplay-${{ steps.version.outputs.version }}-windows-x64.zip" + gh release create $tag $zip --repo "${{ github.repository }}" --verify-tag --title "QuickReplay $tag" --generate-notes diff --git a/.github/workflows/windows-build.yml b/.github/workflows/windows-build.yml new file mode 100644 index 0000000..405691f --- /dev/null +++ b/.github/workflows/windows-build.yml @@ -0,0 +1,47 @@ +name: Windows Build + +on: + pull_request: + branches: + - main + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + + - name: Set up Python 3.14 + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Sync locked dependencies + run: uv sync --locked + + - name: Read project version + shell: pwsh + run: | + $version = uv run python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])" + "RELEASE_VERSION=$version" >> $env:GITHUB_ENV + + - name: Build Windows app + env: + PYTHONIOENCODING: utf-8 + run: | + uv run flet clean + uv run flet build windows --python-version 3.14 --yes + + - name: Create portable distribution ZIP + run: uv run python tools/package_windows_release.py + + - name: Upload Windows distribution + uses: actions/upload-artifact@v4 + with: + name: QuickReplay-${{ env.RELEASE_VERSION }}-windows-x64 + path: dist/QuickReplay-*-windows-x64.zip + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 8992be4..5c3c482 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,22 @@ -__pycache__ -*/__pycache__/* -tmp_video/*.mp4 -dist/* -build/* -*.spec -env/* -config.json +# Python +.venv/ +__pycache__/ +*.py[cod] +*.egg-info/ + +# Tooling caches +.pytest_cache/ +.ruff_cache/ + +# Build output +dist/ +build/ + +# Runtime recording data (keep intentional test fixtures tracked) +buffer/ +*.mkv +!tests/**/*.mkv + +# Local environment / editor +.env +.vscode/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..6324d40 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.14 diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 9732897..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - // IntelliSense を使用して利用可能な属性を学べます。 - // 既存の属性の説明をホバーして表示します。 - // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Python: 現在のファイル", - "type": "python", - "request": "launch", - "program": "${file}", - "console": "integratedTerminal", - "justMyCode": true - } - ] -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 1e0d648..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "python.linting.enabled": true, - "python.autoComplete.extraPaths": [ - "./src", - "./env/Lib/site-packages/", - ], -} \ No newline at end of file diff --git a/LICENSE_ThirdParty.md b/LICENSE_ThirdParty.md index 91ee25b..40e856b 100644 --- a/LICENSE_ThirdParty.md +++ b/LICENSE_ThirdParty.md @@ -1,27 +1,37 @@ -# Python -Python Software Foundation License +# Third-party notices + +This file lists the primary third-party components used by the QuickReplay +Version 2 runtime and Windows package. + +## Python + +Python Software Foundation License
https://docs.python.org/3/license.html#psf-license -# Numpy -BSD 3-Clause License +## Flet + +Apache License 2.0
+https://github.com/flet-dev/flet/blob/main/LICENSE + +## PyAV + +BSD 3-Clause License
+https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt + +## NumPy + +BSD 3-Clause License
https://github.com/numpy/numpy/blob/main/LICENSE.txt -# Opencv-Python -MIT License -https://github.com/opencv/opencv-python/blob/4.x/LICENSE.txt +## ndi-python -# Pillow / PIL -Historical Permission Notice and Disclaimer (HPND) -https://github.com/python-pillow/Pillow/blob/main/LICENSE +MIT License
+https://github.com/buresu/ndi-python/blob/master/LICENSE -# TCL/TK -Tcl/Tk License -https://fedoraproject.org/wiki/Licensing:TCL +## NDI SDK / NDI runtime -# ttkbootstrap -MIT License -https://github.com/israel-dryer/ttkbootstrap/blob/master/LICENSE +NDI SDK License
+https://ndi.video/for-developers/ndi-sdk/license/ -# windows-capture-device-list (python-capture-device-list) -MIT License -https://github.com/yushulx/python-capture-device-list/blob/master/LICENSE +QuickReplay does not bundle mpv. Replay playback uses the external mpv +executable configured by the user. diff --git a/README.md b/README.md index 1a50534..04f4623 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,119 @@ -[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE) -[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) - # QuickReplay -Webカメラの出力を記録し、簡単にリプレイなどを行えるソフト。 +QuickReplay Version 2 is a Windows desktop instant replay application for NDI +inputs. + +Version 2 is a rewrite of QuickReplay. The previous Version 1 implementation +has been removed from this repository. The core domain model, the segment +recording core, the ring storage / retention core, the replay asset +(stream-copy remux) core, the NDI input core and the +headless recorder worker (separate process, capture/encode threads, bounded +queues, replay preparation) and the mpv-based replay controller (external mpv +process, JSON IPC, frame-accurate stepping and seeking) are implemented. The +headless application controller orchestrates recording, replay preparation, mpv +playback and recording resume. Configuration persistence (versioned JSON +schema v1, NDI input selection, recorder buffer setting, mpv executable +setting, atomic save) is implemented. A Flet 1.0 desktop UI is implemented: +NDI input discovery and selection, recording state, +stream information and metrics, replay preparation, and the replay control UI +(Play/Pause, ±1 and ±20 frame steps, seek bar, Set Point, time and frame +difference, resume). A settings editor (explicit Apply/Cancel) edits the +persisted configuration: the recording buffer duration and the mpv executable. +Buffer duration and mpv executable changes are saved but need an application +restart to take effect. + +## Requirements + +- Python >= 3.14 +- [uv](https://docs.astral.sh/uv/) + +The local development baseline is Python 3.14 (see `.python-version`). This is +the development baseline, not an upper bound: Version 2 supports Python 3.14 +and later. + +## Development setup + +```powershell +uv sync +``` + +## Run the desktop app + +```powershell +uv run flet run src/main.py +``` -## 機能 -* リプレイ機能(コマ送り、コマ戻し、早送り、早戻し、等速再生) -* フレームカウンター(指定したフレームからのフレーム差、時間の差を表示する) +## Build for Windows -

+Windows packaging requires Visual Studio with **Desktop development with C++** +and Windows Developer Mode (for symlink support). Build the x64 desktop +application from a clean Flet build with: +```powershell +uv run flet clean +uv run flet build windows --python-version 3.14 +``` -# Setup +The packaged application is generated under `build/windows` as +`QuickReplay.exe`. The build uses the dependencies declared in +`pyproject.toml`; no separate `requirements.txt` is needed. -## Use Binary -[リリースページ](https://github.com/Nanahuse/QuickReplay/releases)から最新版のzipファイルをダウンロードしてください。 -インストール不要で解凍すれば使えます。 +### Runtime requirements -## Use Python -requiments.txtが用意してありますが、[yushulx/python-capture-device-list](https://github.com/yushulx/python-capture-device-list)がpip経由では上手くインストールできないため除いてあります。別途手動でインストールしてください。 +The packaged application does not require Python, uv, or Visual Studio to run. +Replay playback requires an external mpv executable, which can be configured +from Settings. mpv is not bundled in the distribution ZIP. -

+NDI input uses the NDI runtime available to the packaged application through +the existing `ndi-python` integration; this phase does not introduce a new NDI +distribution mechanism. -# 使い方 -## 設定画面 -### WebCameraに関する設定 -入力デバイス、解像度、フレームレートを指定してください。設定可能なフレームレートは入力デバイスによって異なるので確認してください。 -### Replayに関する設定 -リプレイ時間にはリプレイを保存する長さを秒単位で指定してください。リプレイ時間が長くなるほど大きな保存容量が必要になります。 +## Test -録画時プレビューでは録画時にプレビュー画面を開くかどうかを設定します。録画時にプレビュー画面を閉じることでドロステ効果を防止します。[ドロステ効果 - Wikipedia](https://ja.wikipedia.org/wiki/%E3%83%89%E3%83%AD%E3%82%B9%E3%83%86%E5%8A%B9%E6%9E%9C) +```powershell +uv run pytest +``` -### Save & Reset -「Save」を押すことで現在の設定を保存できます。次回実行時には自動で読み込まれます。 -「Reset」を押すと直前にSaveしたデータを読み込むことができます。 +## Lint -### Start -設定が終わったら「Start」を押すと実行画面に変わります。 -入力デバイスが開けなかった場合はエラー画面になります。 +```powershell +uv run ruff check . +``` +## Type check -![設定画面](docs/img/setting_window.png) +```powershell +uv run ty check +``` -
+`ty` is used for static type checking. `mypy` is intentionally not used. -## 実行画面 -### フレームカウンターの使用方法 -1. 録画、再生を行っていない状態で実行画面左下の「Set point」を押す。 -1. 「Set point」を0としたときの現在の表示フレームのフレーム数とタイムが表示される。 -### リプレイ中の画面 -![実行画面](docs/img/player_window_replay.png) +## Branch status -### 録画中の画面 -![実行画面](docs/img/player_window_recording.png) +Development is performed on short-lived branches and merged into `main` through +pull requests. -
+## Project layout -## OBSとの連携させて使用する場合のおすすめ +```text +src/ +└─ quickreplay/ + ├─ app/ # application state and view models + ├─ application/ # headless application controller (recording/replay lifecycle) + ├─ configuration/# versioned JSON configuration persistence + ├─ input/ # input config, stream info, frame models, InputSource + │ └─ ndi/ # NDI discovery, receiver and frame conversion + ├─ recording/ # segment/session models, segment recorder, worker protocol + ├─ replay/ # replay models, asset builder, remux and mpv controller + ├─ worker/ # recorder worker process, pipeline and frame queues + ├─ ui/ # Flet 1.0 desktop UI (bootstrap, bridge, session, view) + └─ units.py # nanosecond / Fraction helpers +tests/ +pyproject.toml +uv.lock +``` -OBSで使用する場合はobs-virtual-camというプラグインが便利です。 -画面全体をWebカメラとして出力したり、フィルタを使うことで映像ソースを直接Webカメラに出力できます。 -* [OBS 27まで](https://github.com/Fenrirthviti/obs-virtual-cam/releases) -* [OBS 28以降](https://github.com/Avasam/obs-virtual-cam/releases) +## License -※インストーラー版がおすすめです。zip版ではコマンドラインから作業が必要になります。 \ No newline at end of file +See `LICENSE`. Third-party license notices are listed in +`LICENSE_ThirdParty.md`. diff --git a/assets/LICENSE_ThirdParty.json b/assets/LICENSE_ThirdParty.json deleted file mode 100644 index 3e617b0..0000000 --- a/assets/LICENSE_ThirdParty.json +++ /dev/null @@ -1,38 +0,0 @@ -[ - { - "License": "PSF License", - "Name": "Python", - "Version": "3.9.13", - "Link": "https://docs.python.org/3/license.html#psf-license" - }, - { - "License": "BSD License", - "Name": "numpy", - "Version": "1.23.0", - "Link": "https://github.com/numpy/numpy/blob/main/LICENSE.txt" - }, - { - "License": "MIT License", - "Name": "opencv-python", - "Version": "4.5.5.64", - "Link": "https://github.com/opencv/opencv-python/blob/4.x/LICENSE.txt" - }, - { - "License": "HPND", - "Name": "Pillow", - "Version": "9.2.0", - "Link": "https://github.com/python-pillow/Pillow/blob/main/LICENSE" - }, - { - "License": "MIT License", - "Name": "ttkbootstrap", - "Version": "1.9.0", - "Link": "https://github.com/israel-dryer/ttkbootstrap/blob/master/LICENSE" - }, - { - "License": "MIT License", - "Name": "windows-capture-device-list", - "Version": "1.1.0", - "Link": "https://github.com/yushulx/python-capture-device-list/blob/master/LICENSE" - } -] \ No newline at end of file diff --git a/assets/default_setting.json b/assets/default_setting.json deleted file mode 100644 index 868b8a1..0000000 --- a/assets/default_setting.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "webcamera": { - "frame_rate": 60, - "input_device": "", - "resolution": "" - }, - "replay": { - "auto_restart": 120, - "length": 600, - "recording_preview": true - } -} \ No newline at end of file diff --git a/assets/forward.png b/assets/forward.png deleted file mode 100644 index bfc6b10..0000000 Binary files a/assets/forward.png and /dev/null differ diff --git a/assets/next.png b/assets/next.png deleted file mode 100644 index fb44dd3..0000000 Binary files a/assets/next.png and /dev/null differ diff --git a/assets/pause.png b/assets/pause.png deleted file mode 100644 index e75f749..0000000 Binary files a/assets/pause.png and /dev/null differ diff --git a/assets/play.png b/assets/play.png deleted file mode 100644 index 6f87346..0000000 Binary files a/assets/play.png and /dev/null differ diff --git a/assets/prev.png b/assets/prev.png deleted file mode 100644 index e41b272..0000000 Binary files a/assets/prev.png and /dev/null differ diff --git a/assets/record.png b/assets/record.png deleted file mode 100644 index 0ca5b04..0000000 Binary files a/assets/record.png and /dev/null differ diff --git a/assets/rewind.png b/assets/rewind.png deleted file mode 100644 index 04b3e5b..0000000 Binary files a/assets/rewind.png and /dev/null differ diff --git a/assets/software_infomation.json b/assets/software_infomation.json deleted file mode 100644 index 03d127f..0000000 --- a/assets/software_infomation.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Name":"Quick Replay", - "Auther": "Nanahuse", - "Version": "1.0", - "URL": "https://github.com/Nanahuse/QuickReplay", - "License": "MIT License", - "License_URL": "https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE" -} \ No newline at end of file diff --git a/assets/stop.png b/assets/stop.png deleted file mode 100644 index 3b3d7f1..0000000 Binary files a/assets/stop.png and /dev/null differ diff --git a/build.bat b/build.bat deleted file mode 100644 index 0f9f2ea..0000000 --- a/build.bat +++ /dev/null @@ -1,25 +0,0 @@ -@REM Copyright (c) 2022 Nanahuse -@REM This software is released under the MIT License -@REM https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE - - -pyinstaller ./src/quick_replay_controller.py ^ ---name QuickReplay ^ --p ./;./src ^ ---add-binary ./assets/forward.png;./assets ^ ---add-binary ./assets/rewind.png;./assets ^ ---add-binary ./assets/next.png;./assets ^ ---add-binary ./assets/prev.png;./assets ^ ---add-binary ./assets/play.png;./assets ^ ---add-binary ./assets/pause.png;./assets ^ ---add-binary ./assets/record.png;./assets ^ ---add-binary ./assets/stop.png;./assets ^ ---add-data ./assets/default_setting.json;./assets ^ ---add-data ./assets/software_infomation.json;./assets ^ ---add-data ./tmp_video/memo.txt;./tmp_video ^ ---add-data ./LICENSE;./ ^ ---add-data ./LICENSE_ThirdParty.md;./ ^ ---add-data ./assets/LICENSE_ThirdParty.json;./assets ^ ---noconsole ^ ---clean ^ --y diff --git a/docs/img/player_window_recording.png b/docs/img/player_window_recording.png deleted file mode 100644 index 06c4fa0..0000000 Binary files a/docs/img/player_window_recording.png and /dev/null differ diff --git a/docs/img/player_window_replay.png b/docs/img/player_window_replay.png deleted file mode 100644 index fa9483d..0000000 Binary files a/docs/img/player_window_replay.png and /dev/null differ diff --git a/docs/img/setting_window.png b/docs/img/setting_window.png deleted file mode 100644 index d033edd..0000000 Binary files a/docs/img/setting_window.png and /dev/null differ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..bdc033f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,59 @@ +[project] +name = "quickreplay" +version = "2.0.0" +description = "Desktop instant replay application for NDI inputs" +readme = "README.md" +requires-python = ">=3.14" +license = { file = "LICENSE" } +dependencies = [ + "av>=18.1.0", + "flet==1.0.0", + "ndi-python==6.3.2.4", + "numpy>=2.5.3", +] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/quickreplay"] + +[tool.flet] +product = "QuickReplay" + +[tool.flet.app] +path = "src" +module = "main" +hide_window_on_start = true + +[tool.flet.windows] +artifact = "QuickReplay" + +[tool.flet.windows.compile] +packages = false + +[tool.flet.windows.cleanup] +packages = false + +[dependency-groups] +dev = [ + "flet-cli==1.0.0", + "flet-desktop==1.0.0", + "pytest>=8.0", + "ruff>=0.9", + "ty>=0.0.1a", +] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ty.environment] +extra-paths = ["tests"] + +[tool.ruff] +target-version = "py314" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B", "W"] diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index ac25990..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -numpy==1.23.0 -opencv-python==4.5.5.64 -ttkbootstrap==1.9.0 \ No newline at end of file diff --git a/src/capture_device.py b/src/capture_device.py deleted file mode 100644 index 17ac231..0000000 --- a/src/capture_device.py +++ /dev/null @@ -1,49 +0,0 @@ -# Copyright (c) 2022 Nanahuse -# This software is released under the MIT License -# https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE - - -from dataclasses import dataclass -from typing import List - -import device # https://github.com/yushulx/python-capture-device-list - - -@dataclass -class Resolution(object): - x: int - y: int - - def to_string(self) -> str: - return f"{self.x} x {self.y}" - - -@dataclass -class CaptureDevice(object): - device_num: int - name: str - resolution: List[Resolution] - - -def get_devices() -> List[CaptureDevice]: - try: - device_list = device.getDeviceList() - except: - # デバッグ実行時にエラーになってしまうため - device_list = [ - ("これはサンプルです", [(1920, 1080), (1280, 720), (960, 540), (640, 360)]), - ("Debug2", [(1920, 1080), (1280, 720), (960, 540)]), - ("Debug3", [(1920, 1080), (1280, 720), (640, 360)]), - ("Debug4", [(960, 540), (640, 360)]), - ("Debug5", [(1920, 1080), (1280, 720), (960, 540)]), - ("Debug6", [(1920, 1080), (1280, 720), (960, 540)]), - ] - - return [ - CaptureDevice( - device_num, - capture_device[0], - [Resolution(resolution[0], resolution[1]) for resolution in capture_device[1]], - ) - for device_num, capture_device in enumerate(device_list) - ] diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..a4e52ac --- /dev/null +++ b/src/main.py @@ -0,0 +1,14 @@ +"""Packaged Flet entry point for QuickReplay.""" + +import multiprocessing +import sys + +from quickreplay.ui.about_window import run_about_from_command_line +from quickreplay.ui.app import run + +if __name__ == "__main__": + multiprocessing.freeze_support() + if sys.argv[1:] == ["--quickreplay-about"]: + run_about_from_command_line() + else: + run() diff --git a/src/quick_replay_controller.py b/src/quick_replay_controller.py deleted file mode 100644 index 594fe6c..0000000 --- a/src/quick_replay_controller.py +++ /dev/null @@ -1,819 +0,0 @@ -# Copyright (c) 2022 Nanahuse -# This software is released under the MIT License -# https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE - -from contextlib import contextmanager -from enum import Enum, auto -import json -import os -from queue import Queue -from time import sleep, time -from threading import Thread -import tkinter as tk -from typing import Callable, List, Optional -import webbrowser - -import cv2 -import ttkbootstrap as ttk - -from dataclasses import dataclass -from quick_replay_view import SettingView, ReplayerView, InfoView -from utils import tkvar_from_dict, tkvar_to_dict -from ring_video import RingVideoWriter, RingVideoCapture -from capture_device import get_devices - -FILE_LENGTH = 60 # 秒数 -FMT = cv2.VideoWriter_fourcc("m", "p", "4", "v") -WRITER_BUFFER_SIZE = 60 # フレーム数 - -VIDEO_FOLDER_PATH = "./tmp_video/" -VIDEO_NAME_PREFIX = "output" -VIDEO_NAME_EXTENSION = ".mp4" - - -class Model(object): - @dataclass - class VarSettingWebcamera(object): - input_device: tk.StringVar - resolution: tk.StringVar - frame_rate: tk.IntVar - - @dataclass - class VarSettingReplay(object): - length: tk.IntVar - auto_restart: tk.IntVar - recording_preview: tk.BooleanVar - - @dataclass - class UserSettings(object): - device_name: str - device_num: int - frame_rate: int - width: int - height: int - replay_time: int - replay_time: int - auto_restart: int - recording_preview: bool - - @dataclass - class RingVideoWriterSetting(object): - fmt: cv2.VideoWriter_fourcc - file_length_max: int - buffer_size_max: int - - -class ModeState(Enum): - PAUSE = auto() - PLAY = auto() - RECORDING = auto() - - -@contextmanager -def open_cv2VideoCapture(device_num: int, width: int, height: int) -> cv2.VideoCapture: - capture = cv2.VideoCapture(device_num, cv2.CAP_DSHOW) - if capture.isOpened(): - capture.set(cv2.CAP_PROP_FRAME_WIDTH, width) - capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height) - try: - yield capture - finally: - capture.release() - - -@contextmanager -def open_RingVideoCapture(file_list: List[str]) -> RingVideoCapture: - player = RingVideoCapture(file_list) - try: - yield player - finally: - player.release() - - -@contextmanager -def open_RingVideoWriter( - file_list: List[str], - user_settings: Model.UserSettings, - writer_settins: Model.RingVideoWriterSetting, - file_list_callback: Callable[[List[str]], None], -) -> RingVideoWriter: - writer = RingVideoWriter( - file_list, - writer_settins.fmt, - user_settings.frame_rate, - (user_settings.width, user_settings.height), - writer_settins.file_length_max, - writer_settins.buffer_size_max, - ) - try: - yield writer - finally: - files = writer.release() - file_list_callback(files) - - -class Cv2Display(object): - # cv2.imshowはメインスレッドでないと動作しないため、 - # 描写関数をtkinter.Window.afterに登録し、メインスレッドで実行する - def __init__(self, root: ttk.Window, window_name: str): - self.window_name = window_name - self.queue = Queue() - self.root = root - self.id = None - - def is_working(self) -> None: - return self.id is not None - - def start(self) -> None: - self.id = self.root.after(5, self.show) - - def stop(self) -> None: - if self.is_working(): - self.root.after_cancel(self.id) - self.id = None - self.root.after(5, self.close_window) - - def set_frame(self, frame: cv2.Mat) -> None: - if self.is_working(): - self.queue.put_nowait(frame) - - def show(self) -> None: - try: - while True: - frame = self.queue.get_nowait() - cv2.imshow(self.window_name, frame) - cv2.waitKey(1) - except: - # 描写するフレームがない場合 - pass - self.id = self.root.after(5, self.show) - - def close_window(self) -> None: - try: - cv2.destroyWindow(self.window_name) - except: - # windowが存在しなかった場合 - pass - - -class Repeater(object): - """ - start後、cancelされるまでintervalの間隔で関数を実行し続ける。 - """ - - def __init__(self, root: ttk.Window, function: Callable[[None], None], repeatdelay: int, repeatinterval: int): - self.root = root - self.function = function - self.repeatdelay = repeatdelay - self.repeatinterval = repeatinterval - self.id = None - - def cancel(self, event) -> None: # NOQA - if self.id is not None: - self.root.after_cancel(self.id) - self.id = None - - def start(self, event) -> None: # NOQA - # 開始とともに一回実行する。 - self.function() - self.id = self.root.after(self.repeatdelay, self._repeat_function) - - def _repeat_function(self) -> None: - # キャンセルされるまで一定時間ごとに実行され続ける - self.function() - self.id = self.root.after(self.repeatinterval, self._repeat_function) - - -class ReplayerModel(object): - def __init__( - self, - file_list: List[str], - frame_rate: int, - counter_callback: Callable[[int, float], None], - display: Cv2Display, - fast_diff: int, - ): - self.frame_rate = frame_rate - self.counter_callback = lambda frame_num: counter_callback(frame_num, self.frame_to_time(frame_num)) - self.capture = RingVideoCapture(file_list) - self.fast_diff = fast_diff - self.is_playing = False - self.play_thread: Optional[Thread] = None - self.display = display - - self.play_stop: Thread = None - - self.to_last() - - def release(self) -> None: - self.capture.release() - - def to_first(self) -> None: - self.capture.move_first() - self.prev_frame() - - def to_last(self) -> None: - self.capture.move_last() - self.next_frame() - - def next_frame(self) -> None: - frame = self.capture.read() - self.counter_callback(self.capture.get_now_frame()) - if frame is not None: - self.display.set_frame(frame) - - def prev_frame(self) -> None: - self.capture.move_diff(-2) - frame = self.capture.read() - self.counter_callback(self.capture.get_now_frame()) - if frame is not None: - self.display.set_frame(frame) - - def fast_foward(self) -> None: - self.capture.move_diff(self.fast_diff - 1) - frame = self.capture.read() - self.counter_callback(self.capture.get_now_frame()) - if frame is not None: - self.display.set_frame(frame) - - def rewind(self) -> None: - self.capture.move_diff(-self.fast_diff - 1) - frame = self.capture.read() - self.counter_callback(self.capture.get_now_frame()) - if frame is not None: - self.display.set_frame(frame) - - def move_to(self, frame_num: int) -> None: - self.capture.move_frame(frame_num) - frame = self.capture.read() - if frame is not None: - self.display.set_frame(frame) - - def start_play(self, play_stop_callback: Callable[[None], None]) -> None: - if not self.is_playing: - self.is_playing = True - self.play_thread = Thread(target=self._work_play, args=(play_stop_callback,)) - self.play_thread.start() - - def stop_play(self) -> None: - self.is_playing = False - if self.play_thread is not None: - self.play_thread = None - - def _work_play(self, play_stop_callback: Callable[[None], None]) -> None: - start_time = time() - i = 1 - counter = 0 - while self.is_playing: - tmp = i / self.frame_rate - tmp_time = time() - if tmp_time < start_time + tmp: - counter += 1 - sleep(start_time + tmp - tmp_time) - frame = self.capture.read() - self.counter_callback(self.capture.get_now_frame()) - if frame is not None: - self.display.set_frame(frame) - else: - self.is_playing = False - i += 1 - play_stop_callback() - - def frame_to_time(self, frame_counter: int) -> float: - return round((frame_counter) / self.frame_rate, 3) - - -class RecorderModel(object): - def __init__( - self, - file_list: List[str], - user_settings: Model.UserSettings, - writer_settings: Model.RingVideoWriterSetting, - display: Cv2Display, - ): - self.file_list = [file for file in file_list] - self.user_settings = user_settings - self.writer_settings = writer_settings - self.is_recording = False - self._recording_thread: Optional[Thread] = None - self.display = display - - def get_file_list(self) -> List[str]: - return self.file_list - - def get_frame_rate(self) -> int: - return self.user_settings.frame_rate - - def start(self) -> None: - if not self.is_recording: - if self.user_settings.recording_preview is False: - self.display.stop() - self.is_recording = True - self._recording_thread = Thread(target=self._work_recording) - self._recording_thread.start() - - def stop(self) -> None: - if self.is_recording: - self.is_recording = False - while self._recording_thread.is_alive(): - sleep(0.1) - self._recording_thread = None - self.display.start() - - def _work_recording(self) -> None: - with open_cv2VideoCapture( - self.user_settings.device_num, self.user_settings.width, self.user_settings.height - ) as capture: - writer = RingVideoWriter - with open_RingVideoWriter( - self.file_list, self.user_settings, self.writer_settings, self.update_file_list - ) as writer: - while self.is_recording: - _, frame = capture.read() - if frame is not None: - writer.write(frame) - self.display.set_frame(frame) - - def update_file_list(self, file_list: List[str]) -> None: - self.file_list = file_list - - -class _ControllerBase(object): - def __init__(self) -> None: - pass - - def enable(self) -> None: - # 画面を有効にする - pass - - def disable(self) -> None: - # 画面を無効にする - pass - - -class _InfomationWindow(object): - def __init__(self, root): - self.is_alive = False - self.root = root - - def show_window(self) -> None: - if self.is_alive: - return - self.is_alive = True - - self.window = ttk.Toplevel(self.root, resizable=(False, False)) - self.window.title("Infomation") - - self.info_frame = InfoView(self.window) - self.license_link_button_commands: List[Callable[[None], None]] = [] - - with open("./assets/software_infomation.json", encoding="UTF-8") as f: - infomation = json.load(f) - info_string = "\n".join([f"{tmp}\t: {infomation[tmp]}" for tmp in ["Name", "Auther", "Version", "License"]]) - self.info_frame.info_label.configure(text=info_string) - self.info_frame.github_link_button.configure( - command=lambda infomation=infomation: webbrowser.open(infomation["URL"]) - ) # infomation=infomationで実行時ではなく宣言時の値を使用するようにしている - self.info_frame.license_link_button.configure( - command=lambda infomation=infomation: webbrowser.open(infomation["License_URL"]) - ) - - with open("./assets/LICENSE_ThirdParty.json", encoding="UTF-8") as f: - licenses = json.load(f) - - for tmp_license in licenses: - button = self.info_frame.license_frame.add(tmp_license["Name"], tmp_license["License"]) - button.configure( - command=lambda tmp_license=tmp_license: webbrowser.open(tmp_license["Link"]) - ) # tmp_license=tmp_licenseで実行時ではなく宣言時の値を使用するようにしている - - self.info_frame.enable() - self.window.protocol("WM_DELETE_WINDOW", self.on_closing) - - def on_closing(self): - self.is_alive = False - self.window.destroy() - - -class _SettingController(_ControllerBase): - def __init__(self, root, press_start_callback: Callable[[None], None]): # NOQA - self.root = root - self.view = SettingView(self.root) - - self.infomation = _InfomationWindow(self.root) - - # 変数のbind - self.capture_devices = get_devices() - self.setting_webcamera = Model.VarSettingWebcamera( - tk.StringVar(self.root), tk.StringVar(self.root), tk.IntVar(self.root) - ) - self.setting_replay = Model.VarSettingReplay( - tk.IntVar(self.root), tk.IntVar(self.root), tk.BooleanVar(self.root) - ) - - self.view.webcam_select.configure(textvariable=self.setting_webcamera.input_device) - self.view.webcam_resolution.configure(textvariable=self.setting_webcamera.resolution) - self.view.webcam_framerate.configure(textvariable=self.setting_webcamera.frame_rate) - self.view.replay_length.configure(textvariable=self.setting_replay.length) - self.view.replay_auto_restart.configure(textvariable=self.setting_replay.auto_restart) - - self.view.webcam_select.configure(values=[device.name for device in self.capture_devices]) - self.view.webcam_select.bind("<>", self.on_change_device) - self.view.webcam_resolution.bind("<>", self.on_change_resolution) - - # ボタン動作のbind - self.view.button_reset.configure(command=self.load_settings) - self.view.button_save.configure(command=self.save_settings) - self.view.button_start.configure(command=press_start_callback) - self.view.button_info.configure(command=self.press_info) - - # 値が設定されるまでStartボタンを隠す。 - self.view.button_start.configure(state="disable") - - self.load_settings() - - def enable(self) -> None: - self.view.enable() - - def disable(self) -> None: - self.view.disable() - - def save_settings(self) -> None: - save_dist = {} - save_dist["webcamera"] = tkvar_to_dict(self.setting_webcamera) - save_dist["replay"] = tkvar_to_dict(self.setting_replay) - - with open("./assets/config.json", "w", encoding="UTF-8") as f: - json.dump(save_dist, f, indent=4) - - def load_settings(self) -> None: - try: - with open("./assets/config.json", "r", encoding="UTF-8") as f: - json_data = json.load(f) - except: - with open("assets/default_setting.json", "r", encoding="UTF-8") as f: - json_data = json.load(f) - - if json_data["webcamera"]["input_device"] not in [device.name for device in self.capture_devices]: - json_data["webcamera"]["input_device"] = "" - - tkvar_from_dict(json_data["webcamera"], self.setting_webcamera) - tkvar_from_dict(json_data["replay"], self.setting_replay) - - self.on_change_device(None) - # on_change_recording_preveiwを実行すると値が反転してしまうため予め逆にしておく - self.setting_replay.recording_preview.set(not self.setting_replay.recording_preview.get()) - self.on_change_recording_preview() - - def press_info(self, event=None) -> None: # NOQA - self.infomation.show_window() - - def on_change_device(self, event) -> None: # NOQA - now_resolution = self.setting_webcamera.resolution.get() - - device_name = self.setting_webcamera.input_device.get() - for device in self.capture_devices: - if device.name == device_name: - self.view.webcam_resolution.configure( - values=[resolution.to_string() for resolution in device.resolution] - ) - for resolution in device.resolution: - if resolution.to_string() == now_resolution: - self.view.button_start.configure(state="enable") - return - break - else: - self.view.webcam_resolution.configure(values=[]) - - # 指定解像度に対応してない、または選択肢がないときは空に戻す。 - self.setting_webcamera.resolution.set("") - self.view.button_start.configure(state="disable") - - def on_change_resolution(self, event=None) -> None: # NOQA - now_resolution = self.setting_webcamera.resolution.get() - - # 正しい解像度が設定されるまでStartボタンを隠す処理 - if now_resolution == "": - self.view.button_start.configure(state="disable") - else: - self.view.button_start.configure(state="enable") - - def get_settings(self) -> Model.UserSettings: - - device_name = self.setting_webcamera.input_device.get() - for device in self.capture_devices: - if device_name == device.name: - device_num = device.device_num - break - frame_rate = self.setting_webcamera.frame_rate.get() - resolution = [int(tmp) for tmp in self.setting_webcamera.resolution.get().split("x")] - replay_time = self.setting_replay.length.get() - auto_restart = self.setting_replay.auto_restart.get() - recording_preview = self.setting_replay.recording_preview.get() - - setting = Model.UserSettings( - device_name=device_name, - device_num=device_num, - frame_rate=frame_rate, - width=resolution[0], - height=resolution[1], - replay_time=replay_time, - auto_restart=auto_restart, - recording_preview=recording_preview, - ) - - # print(f"カメラ名    : {setting.device_name}") - # print(f"カメラ番号   : {setting.device_num}") - # print(f"解像度     : {setting.width}, {setting.height}") - # print(f"フレームレート : {setting.frame_rate}") - # print(f"保存長さ    : {setting.replay_time}") - # print(f"自動再開    : {setting.auto_restart}") - - return setting - - def on_change_recording_preview(self) -> None: - flag = not self.setting_replay.recording_preview.get() - self.setting_replay.recording_preview.set(flag) - - if flag: - self.view.recording_preview_check_enable.configure(bootstyle="default") - self.view.recording_preview_check_disable.configure(bootstyle="secondary") - - self.view.recording_preview_check_enable.configure(command=lambda: ()) - self.view.recording_preview_check_disable.configure(command=self.on_change_recording_preview) - else: - self.view.recording_preview_check_enable.configure(bootstyle="secondary") - self.view.recording_preview_check_disable.configure(bootstyle="light") - self.view.recording_preview_check_enable.configure(command=self.on_change_recording_preview) - self.view.recording_preview_check_disable.configure(command=lambda: ()) - - -class _ReplayerController(_ControllerBase): - REPEAT_DELAY = 500 - REPEAT_INTERVAL_FAST = 50 - REPEAT_INTERVAL = 85 - FAST_MOVE_FRAME = 20 - - def __init__(self, root: ttk.Window): - self.root = root - self.view = ReplayerView(self.root) - - self.var_seekbar = tk.IntVar() - self.var_frame_counter = tk.StringVar(value="FRAME COUNTER(from the point)") - self.view.seekbar.configure(variable=self.var_seekbar, command=self.on_seekbar_change) - self.view.counter_label.configure(textvariable=self.var_frame_counter) - - # ボタンを押しっぱなしのときに繰り返し実行するためのリピーターをかませる。 - self.repeat_rewind = Repeater(self.root, self.press_rewind, self.REPEAT_DELAY, self.REPEAT_INTERVAL_FAST) - self.repeat_forward = Repeater(self.root, self.press_forward, self.REPEAT_DELAY, self.REPEAT_INTERVAL_FAST) - self.repeat_prev = Repeater(self.root, self.press_prev, self.REPEAT_DELAY, self.REPEAT_INTERVAL) - self.repeat_next = Repeater(self.root, self.press_next, self.REPEAT_DELAY, self.REPEAT_INTERVAL) - - # ボタンを押したときの動作 - self.view.button_rewind.bind("", self.repeat_rewind.start) - self.view.button_forward.bind("", self.repeat_forward.start) - self.view.button_prev.bind("", self.repeat_prev.start) - self.view.button_next.bind("", self.repeat_next.start) - - # ボタンを離したときの動作 - self.view.button_rewind.bind("", self.repeat_rewind.cancel) - self.view.button_forward.bind("", self.repeat_forward.cancel) - self.view.button_prev.bind("", self.repeat_prev.cancel) - self.view.button_next.bind("", self.repeat_next.cancel) - - self.view.button_set_point.configure(command=self.press_set_point) - - self.display = Cv2Display(self.root, "Quick Replayer View") - self.display.start() - - self.replayer: Optional[ReplayerModel] = None - self.recorder: Optional[RecorderModel] = None - - self.origin_point_frame_num: Optional[int] = None - - def enable(self) -> None: - self.view.enable() - self._play_stop_callback() - self.start_recording() - - def disable(self) -> None: - self.view.disable() - raise NotImplementedError() - - def start_recording(self) -> None: - if self.mode == ModeState.PLAY: - self.replayer.stop_play() - - if self.replayer is not None: - self.replayer.release() - - if self.recorder is None: - # FIXME:ERROR DIALOG - return - - self.mode = ModeState.RECORDING - self.change_widget_state_for_recording(False) - self.view.button_recording.configure(image=self.view.icon_stop, command=self.stop_recording, bootstyle="danger") - self.view.seekbar_right_label.configure(text="Recording") - self.view.seekbar.configure(from_=-1, to=0, value=0, state="disable") - self.reset_frame_counter() - self.recorder.start() - - def stop_recording(self) -> None: - if self.mode != ModeState.RECORDING: - return - self.recorder.stop() - - self.replayer = ReplayerModel( - self.recorder.get_file_list(), - self.recorder.get_frame_rate(), - self.frame_update_callback, - self.display, - self.FAST_MOVE_FRAME, - ) - - self.change_widget_state_for_recording(True) - frame_num = self.replayer.capture.get_frame_num() - 1 - self.view.seekbar.config(from_=0, to=frame_num, state="enable") - self.var_seekbar.set(frame_num) - self.view.button_recording.configure( - image=self.view.icon_record, command=self.start_recording, bootstyle="danger" - ) - self.pause() - - def change_widget_state_for_recording(self, is_enabled: bool) -> None: - state = "enable" if is_enabled else "disable" - self.view.button_rewind.configure(state=state) - self.view.button_prev.configure(state=state) - self.view.button_play.configure(state=state) - self.view.button_next.configure(state=state) - self.view.button_forward.configure(state=state) - self.view.button_set_point.configure(state=state) - - def play(self) -> None: - if self.replayer is None: - return - self.mode = ModeState.PLAY - self.view.button_play.configure(image=self.view.icon_pause, command=self.pause, bootstyle="warning") - self.replayer.start_play(self._play_stop_callback) - pass - - def pause(self) -> None: - if self.replayer is None: - return - self.replayer.stop_play() - - def _play_stop_callback(self) -> None: - self.mode = ModeState.PAUSE - self.view.button_play.configure(image=self.view.icon_play, command=self.play, bootstyle="success") - - def press_rewind(self) -> None: - # print("press_rewind") - if self.replayer is None: - return - if self.mode == ModeState.PLAY: - self.replayer.stop_play() - self.replayer.rewind() - - def press_prev(self) -> None: - # print("press_prev") - if self.replayer is None: - return - if self.mode == ModeState.PLAY: - self.replayer.stop_play() - self.replayer.prev_frame() - - def press_next(self) -> None: - # print("press_next") - if self.replayer is None: - return - if self.mode == ModeState.PLAY: - self.replayer.stop_play() - self.replayer.next_frame() - - def press_forward(self) -> None: - # print("press_forward") - if self.replayer is None: - return - if self.mode == ModeState.PLAY: - self.replayer.stop_play() - self.replayer.fast_foward() - - def press_set_point(self) -> None: - # print("Set point") - if self.replayer is None: - return - now_frame = self.replayer.capture.get_now_frame() - self.origin_point_frame_num = now_frame - self.update_frame_counter_label(now_frame) - - def update_frame_counter_label(self, frame_num: int) -> None: - if self.origin_point_frame_num is None: - return - if self.replayer is None: - return - diff_frame = frame_num - self.origin_point_frame_num - - if diff_frame >= 0: - diff_time = self.replayer.frame_to_time(diff_frame) - minute = diff_time // 60 - sec = diff_time % 60 - else: - diff_time = self.replayer.frame_to_time(-diff_frame) - minute = -(diff_time // 60) - sec = diff_time % 60 - - self.var_frame_counter.set(f"{minute:03.0f}:{sec:06.3f} ( {diff_frame:8d} frame )") - - def frame_update_callback(self, frame_num: int, frame_time: float) -> None: - self.update_frame_counter_label(frame_num) - self.var_seekbar.set(frame_num) - self.update_seekbar_label(frame_time) - - def on_seekbar_change(self, event): # NOQA - frame_num = int(self.var_seekbar.get()) - if self.mode == ModeState.PLAY: - self.replayer.stop_play() - self.replayer.move_to(frame_num) - self.update_frame_counter_label(frame_num) - self.update_seekbar_label(self.replayer.frame_to_time(frame_num)) - - def update_seekbar_label(self, frame_time: float) -> None: - minute = frame_time // 60 - sec = frame_time % 60 - self.view.seekbar_right_label.configure(text=f"{minute:03.0f}:{sec:06.3f}") - - def reset_frame_counter(self) -> None: - self.origin_point_frame_num = None - self.var_frame_counter.set("FRAME COUNTER(from point)") - - def initialize_writer( - self, file_list: List[str], user_settings: Model.UserSettings, writer_settings: Model.RingVideoWriterSetting - ) -> None: - self.recorder = RecorderModel(file_list, user_settings, writer_settings, self.display) - - -class Controller(object): - def __init__(self, root: ttk.Window): - self.root = root - - # 画面の定義 - self._controller_setting = _SettingController(root, self.setting_to_replayer) - self._controller_replayer = _ReplayerController(root) - - self._error_label_input_device_error = ttk.Label( - root, - text=""" - 設定した入力デバイスを開いています。 - 30秒程度待ってもこの画面から切り替わらない場合はエラーです。 - - ・他のソフトで指定した入力デバイスを使用していないか - ・指定した解像度やフレームレートに対応しているか - 等を確認してください。 - 一度画面を閉じてやりなおしてください。 - """, - ) - - root.protocol("WM_DELETE_WINDOW", self.on_close) - - self._controller_setting.enable() - - def setting_to_replayer(self) -> None: - self._controller_setting.disable() - self._error_label_input_device_error.pack() - self.root.attributes("-topmost", True) - - user_setting = self._controller_setting.get_settings() - writer_setting = Model.RingVideoWriterSetting(FMT, FILE_LENGTH, WRITER_BUFFER_SIZE) - - file_num = int(user_setting.replay_time / FILE_LENGTH) + 1 - file_list = [f"{VIDEO_FOLDER_PATH}{VIDEO_NAME_PREFIX}{i}{VIDEO_NAME_EXTENSION}" for i in range(file_num)] - - # 動画保存用フォルダを空にする - for file in file_list: - # print(file) - try: - os.remove(file) - except FileNotFoundError: - pass - - self._controller_replayer.initialize_writer(file_list, user_setting, writer_setting) - self._error_label_input_device_error.pack_forget() - self._controller_replayer.enable() - - def on_close(self) -> None: - if self._controller_replayer.replayer is not None: - self._controller_replayer.replayer.release() - if self._controller_replayer.recorder is not None: - self._controller_replayer.recorder.stop() - self.root.destroy() - - -if __name__ == "__main__": - root = ttk.Window(title="Quick Replay", themename="superhero", resizable=(False, False)) - - controller = Controller(root) - - root.mainloop() - - cv2.destroyAllWindows() diff --git a/src/quick_replay_view.py b/src/quick_replay_view.py deleted file mode 100644 index 5af9ffb..0000000 --- a/src/quick_replay_view.py +++ /dev/null @@ -1,254 +0,0 @@ -# Copyright (c) 2022 Nanahuse -# This software is released under the MIT License -# https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE - - -from typing import List -import ttkbootstrap as ttk -import ttkbootstrap.tooltip as ttk_tooltip - - -class _ViewBase(object): - def enable(self) -> None: - # 画面を有効にする - pass - - def disable(self) -> None: - # 画面を無効にする - pass - - -class SettingView(ttk.Frame, _ViewBase): - def __init__(self, parent): # NOQA - super().__init__(parent) - self.parent = parent - - self.frame_setting = ttk.Frame(master=self) - row = 0 - # webcam---------------------------------------------------------------------------------------- - self.webcam_label = ttk.Label(master=self.frame_setting, text="Web Camera", bootstyle="primary") - self.webcam_label.grid(row=row, padx=5, pady=10) - - row += 1 - - self.webcam_select_label = ttk.Label(master=self.frame_setting, text="入力デバイス") - self.webcam_select_label.grid(row=row, column=0, padx=5, pady=5) - self.webcam_select = ttk.Combobox(master=self.frame_setting, state="readonly") - self.webcam_select.grid(row=row, column=1, padx=5, pady=5, sticky=ttk.W + ttk.E) - - row += 1 - - self.webcam_resolution_label = ttk.Label(master=self.frame_setting, text="解像度") - self.webcam_resolution_label.grid(row=row, column=0, padx=5, pady=5) - self.webcam_resolution = ttk.Combobox(master=self.frame_setting, state="readonly") - self.webcam_resolution.grid(row=row, column=1, padx=5, pady=5, sticky=ttk.W + ttk.E) - - row += 1 - - self.webcam_framerate_label = ttk.Label(master=self.frame_setting, text="フレームレート [Hz]") - self.webcam_framerate_label.grid(row=row, column=0, padx=5, pady=5) - self.webcam_framerate = ttk.Spinbox(master=self.frame_setting, from_=1, to=120, state="readonly") - self.webcam_framerate.grid(row=row, column=1, padx=5, pady=5, sticky=ttk.W + ttk.E) - - row += 1 - - # replay---------------------------------------------------------------------------------------- - self.replay_label = ttk.Label(master=self.frame_setting, text="Replay", bootstyle="primary") - self.replay_label.grid(row=row, padx=5, pady=10) - - row += 1 - - self.replay_length_label = ttk.Label(master=self.frame_setting, text="リプレイ時間 [s]") - self.replay_length_label.grid(row=row, column=0, padx=5, pady=5) - self.replay_length = ttk.Spinbox(master=self.frame_setting, from_=10, to=86400, increment=10, state="readonly") - self.replay_length.grid(row=row, column=1, padx=5, pady=5, sticky=ttk.W + ttk.E) - - # row += 1 - - self.replay_auto_restart_label = ttk.Label(master=self.frame_setting, text="自動再開 [s]") - # self.replay_auto_restart_label.grid(row=row, column=0, padx=5, pady=5) - self.replay_auto_restart = ttk.Spinbox( - master=self.frame_setting, from_=10, to=86400, increment=10, state="readonly" - ) - # self.replay_auto_restart.grid(row=row, column=1, padx=5, pady=5, sticky=ttk.W + ttk.E) - - row += 1 - - self.recording_preview_label = ttk.Label(master=self.frame_setting, text="録画時プレビュー") - self.recording_preview_label.grid(row=row, padx=5, pady=10) - - self.recording_preview_frame = ttk.Frame(master=self.frame_setting) - self.recording_preview_frame.grid(row=row, column=1, padx=5, pady=10, sticky=ttk.W + ttk.E) - self.recording_preview_check_enable = ttk.Button(master=self.recording_preview_frame, text="Enable") - self.recording_preview_check_enable.pack(side=ttk.LEFT, expand=True, fill=ttk.X) - self.recording_preview_check_disable = ttk.Button( - master=self.recording_preview_frame, text="disable", bootstyle="secondary" - ) - self.recording_preview_check_disable.pack(side=ttk.RIGHT, expand=True, fill=ttk.X) - - row += 1 - - self.frame_setting.columnconfigure(1, weight=1) - self.frame_setting.pack(padx=5, pady=5, fill=ttk.X) - - # --------------------------------------------------------------------------------------------------- - # --------------------------------------------------------------------------------------------------- - - row = 0 - - self.frame_button = ttk.Frame(master=self) - self.button_reset = ttk.Button(master=self.frame_button, text="Reset", bootstyle="warning", width=8) - self.button_reset.grid(row=row, column=0, padx=15, pady=15) - self.button_save = ttk.Button(master=self.frame_button, text="Save", bootstyle="success", width=8) - self.button_save.grid(row=row, column=1, padx=15, pady=15) - self.button_start = ttk.Button(master=self.frame_button, text="Start", bootstyle="default", width=8) - self.button_start.grid(row=row, column=2, padx=15, pady=15) - - row += 1 - self.button_info = ttk.Button(master=self.frame_button, text="Info", width=8, bootstyle="secondary") - self.button_info.grid(row=row, column=0, padx=15, pady=15) - - self.frame_button.pack(padx=5, pady=5, anchor=ttk.S) - - def enable(self) -> None: - self.pack(padx=5, pady=5, fill=ttk.X) - - def disable(self) -> None: - self.pack_forget() - - -class ReplayerView(ttk.Frame): - CONTROL_BUTTON_CLEARANCE = 10 - - def __init__(self, parent): # NOQA - super().__init__(parent) - self.parent = parent - - # シークバー - self.frame_seekbar = ttk.Frame(master=self) - self.frame_seekbar.pack(padx=5, pady=15, fill=ttk.X) - self.seekbar = ttk.Scale(master=self.frame_seekbar, bootstyle="default") - self.seekbar.pack(padx=15, pady=5, side=ttk.LEFT, expand=True, fill=ttk.X) - self.seekbar_right_label = ttk.Label(master=self.frame_seekbar, text="0:00/ -0:00") - self.seekbar_right_label.pack(padx=5, side=ttk.RIGHT) - - self.icon_play = ttk.PhotoImage(file=r"./assets/play.png") - self.icon_pause = ttk.PhotoImage(file=r"./assets/pause.png") - self.icon_next = ttk.PhotoImage(file=r"./assets/next.png") - self.icon_prev = ttk.PhotoImage(file=r"./assets/prev.png") - self.icon_forward = ttk.PhotoImage(file=r"./assets/forward.png") - self.icon_rewind = ttk.PhotoImage(file=r"./assets/rewind.png") - self.icon_record = ttk.PhotoImage(file=r"./assets/record.png") - self.icon_stop = ttk.PhotoImage(file=r"./assets/stop.png") - - # 再生用ボタン - self.frame_video_button = ttk.Frame(master=self) - self.frame_video_button.pack(padx=15, pady=10) - self.button_rewind = ttk.Button(master=self.frame_video_button, image=self.icon_rewind, bootstyle="primary") - self.button_rewind.pack(padx=self.CONTROL_BUTTON_CLEARANCE, pady=5, ipady=10, side=ttk.LEFT) - self.button_prev = ttk.Button(master=self.frame_video_button, image=self.icon_prev, bootstyle="primary") - self.button_prev.pack(padx=self.CONTROL_BUTTON_CLEARANCE, pady=5, ipady=10, side=ttk.LEFT, anchor=ttk.CENTER) - self.button_play = ttk.Button(master=self.frame_video_button, image=self.icon_play, bootstyle="success") - self.button_play.pack(padx=self.CONTROL_BUTTON_CLEARANCE, pady=5, ipady=10, side=ttk.LEFT) - self.button_next = ttk.Button(master=self.frame_video_button, image=self.icon_next, bootstyle="primary") - self.button_next.pack(padx=self.CONTROL_BUTTON_CLEARANCE, pady=5, ipady=10, side=ttk.LEFT) - self.button_forward = ttk.Button(master=self.frame_video_button, image=self.icon_forward, bootstyle="primary") - self.button_forward.pack(padx=self.CONTROL_BUTTON_CLEARANCE, pady=5, ipady=10, side=ttk.LEFT) - - separator = ttk.Separator(self.frame_video_button, orient="vertical") - separator.pack(padx=10, pady=5, side=ttk.LEFT) - - self.button_recording = ttk.Button(master=self.frame_video_button, image=self.icon_record, bootstyle="danger") - self.button_recording.pack(padx=self.CONTROL_BUTTON_CLEARANCE, pady=5, ipady=10, side=ttk.LEFT) - - # フレームカウンター - self.frame_option_button = ttk.Frame(master=self) - self.frame_option_button.pack(padx=5, pady=5, anchor=ttk.W, fill=ttk.X) - self.button_set_point = ttk.Button(master=self.frame_option_button, text="Set point", bootstyle="secondary") - self.button_set_point.pack(padx=20, pady=5, side=ttk.LEFT) - self.counter_label = ttk.Label(master=self.frame_option_button, text="FRAME COUNTER(from point)") - self.counter_label.pack(padx=20, pady=5, side=ttk.LEFT, fill=ttk.X) - - ttk_tooltip.ToolTip(self.button_rewind, text="早戻し") - ttk_tooltip.ToolTip(self.button_prev, text="1コマ戻る") - ttk_tooltip.ToolTip(self.button_play, text="再生") - ttk_tooltip.ToolTip(self.button_next, text="1コマ進める") - ttk_tooltip.ToolTip(self.button_forward, text="早送り") - ttk_tooltip.ToolTip(self.button_set_point, text="タイマーの基点を設定") - - def enable(self) -> None: - self.pack(padx=5, pady=5, fill=ttk.X) - - def disable(self) -> None: - self.pack_forget() - - -class LicenseFrame(ttk.Frame): - def __init__(self, parent): # NOQA - super().__init__(parent) - self.parent = parent - self.row = 0 - self.license_link_buttons: List[ttk.Button] = [] - - def add(self, library_name: str, license_name: str) -> ttk.Button: - self.name_label = ttk.Label(master=self, text=library_name) - self.name_label.grid(row=self.row, column=0, padx=5, pady=5, sticky=ttk.W + ttk.E) - self.license_link_buttons.append(ttk.Button(master=self, text=license_name, bootstyle="light-outline")) - self.license_link_buttons[-1].grid(row=self.row, column=1, padx=10, pady=5, sticky=ttk.W + ttk.E) - self.row += 1 - return self.license_link_buttons[-1] - - -class InfoView(ttk.Frame): - def __init__(self, parent): # NOQA - super().__init__(parent) - self.parent = parent - self.info_label = ttk.Label(master=self, text="About this", bootstyle="success") - self.info_label.pack(padx=10, pady=5, anchor=ttk.W) - - self.info_label = ttk.Label(master=self, text="Name\t: Quick Replay\nAuther\t: Nanahuse\nVersion\t: 1.0") - self.info_label.pack(padx=10, pady=5, anchor=ttk.W) - self.button_frame = ttk.Frame(master=self) - self.button_frame.pack(anchor=ttk.W) - self.github_link_button = ttk.Button(master=self.button_frame, text="Github", bootstyle="info-outline") - self.github_link_button.pack(padx=10, pady=5, anchor=ttk.W, side=ttk.LEFT) - self.license_link_button = ttk.Button(master=self.button_frame, text="MIT License", bootstyle="info-outline") - self.license_link_button.pack(padx=10, pady=5, anchor=ttk.W, side=ttk.LEFT) - - self.thirdparty_label = ttk.Label(master=self, text="Third Party Licenses", bootstyle="success") - self.thirdparty_label.pack(padx=10, pady=5, anchor=ttk.W) - self.license_frame = LicenseFrame(self) - self.license_frame.pack(padx=5, pady=5, fill=ttk.BOTH, anchor=ttk.W) - - def enable(self) -> None: - self.pack(padx=5, pady=5, fill=ttk.BOTH) - - def disable(self) -> None: - self.pack_forget() - - -if __name__ == "__main__": - main_window = ttk.Window(themename="superhero", resizable=(False, False)) - main_window.title("Quick Replay") - main_view = SettingView(main_window) - main_view.enable() - - sub_window = ttk.Toplevel(main_window, resizable=(False, False)) - sub_window.title("Controller") - sub_view = ReplayerView(sub_window) - sub_view.enable() - - info_window = ttk.Toplevel(main_window, resizable=(False, False)) - info_window.title("Infomation") - info = InfoView(info_window) - - import json - - with open("./assets/LICENSE_ThirdParty.json", encoding="UTF-8") as f: - licenses = json.load(f) - - for tmp_license in licenses: - info.license_frame.add(tmp_license["Name"], tmp_license["License"]) - - info.enable() - main_window.mainloop() diff --git a/src/quickreplay/__init__.py b/src/quickreplay/__init__.py new file mode 100644 index 0000000..b0a1cfb --- /dev/null +++ b/src/quickreplay/__init__.py @@ -0,0 +1 @@ +"""QuickReplay Version 2 package.""" diff --git a/src/quickreplay/app/__init__.py b/src/quickreplay/app/__init__.py new file mode 100644 index 0000000..201a01d --- /dev/null +++ b/src/quickreplay/app/__init__.py @@ -0,0 +1,6 @@ +"""Application state and view models. + +This package holds the UI-independent application state machine and the +read-only view state that a future UI layer will render. It must not import +any native or UI library. +""" diff --git a/src/quickreplay/app/models.py b/src/quickreplay/app/models.py new file mode 100644 index 0000000..d2fe983 --- /dev/null +++ b/src/quickreplay/app/models.py @@ -0,0 +1,28 @@ +"""Read-only application view models. + +A future UI layer renders these instead of holding references to runtime +workers or native objects. +""" + +from dataclasses import dataclass + +from quickreplay.app.state import ApplicationState +from quickreplay.input.models import StreamInfo +from quickreplay.replay.models import SetPoint + + +@dataclass(frozen=True, slots=True) +class ApplicationViewState: + """Snapshot of everything a UI needs to render the current state.""" + + state: ApplicationState + + input_name: str | None = None + stream_info: StreamInfo | None = None + + buffer_duration_ns: int = 0 + + replay_position_ns: int | None = None + set_point: SetPoint | None = None + + error_message: str | None = None diff --git a/src/quickreplay/app/state.py b/src/quickreplay/app/state.py new file mode 100644 index 0000000..f800f6f --- /dev/null +++ b/src/quickreplay/app/state.py @@ -0,0 +1,81 @@ +"""Application-level state machine. + +The application has a single top-level state. Transitions are described by a +small, explicit table; this is not a general state machine engine. +""" + +from enum import StrEnum + + +class ApplicationState(StrEnum): + """Top-level application state.""" + + STARTING = "starting" + IDLE = "idle" + RECORDING = "recording" + PREPARING_REPLAY = "preparing_replay" + REPLAY = "replay" + STOPPING = "stopping" + RESUMING = "resuming" + ERROR = "error" + SHUTTING_DOWN = "shutting_down" + + +_ALLOWED_TRANSITIONS: dict[ApplicationState, frozenset[ApplicationState]] = { + ApplicationState.STARTING: frozenset( + {ApplicationState.IDLE, ApplicationState.ERROR, ApplicationState.SHUTTING_DOWN} + ), + ApplicationState.IDLE: frozenset( + { + ApplicationState.RECORDING, + ApplicationState.ERROR, + ApplicationState.SHUTTING_DOWN, + } + ), + ApplicationState.RECORDING: frozenset( + { + ApplicationState.PREPARING_REPLAY, + ApplicationState.STOPPING, + ApplicationState.IDLE, + ApplicationState.ERROR, + ApplicationState.SHUTTING_DOWN, + } + ), + ApplicationState.PREPARING_REPLAY: frozenset( + { + ApplicationState.REPLAY, + ApplicationState.RECORDING, + ApplicationState.ERROR, + ApplicationState.SHUTTING_DOWN, + } + ), + ApplicationState.REPLAY: frozenset( + { + ApplicationState.RESUMING, + ApplicationState.STOPPING, + ApplicationState.IDLE, + ApplicationState.ERROR, + ApplicationState.SHUTTING_DOWN, + } + ), + ApplicationState.STOPPING: frozenset({ApplicationState.IDLE, ApplicationState.ERROR}), + ApplicationState.RESUMING: frozenset( + { + ApplicationState.RECORDING, + ApplicationState.ERROR, + ApplicationState.SHUTTING_DOWN, + } + ), + ApplicationState.ERROR: frozenset({ApplicationState.IDLE, ApplicationState.SHUTTING_DOWN}), + ApplicationState.SHUTTING_DOWN: frozenset(), +} + + +def allowed_transitions(state: ApplicationState) -> frozenset[ApplicationState]: + """States reachable from *state*.""" + return _ALLOWED_TRANSITIONS[state] + + +def can_transition(current: ApplicationState, target: ApplicationState) -> bool: + """Return ``True`` if ``current -> target`` is an allowed transition.""" + return target in _ALLOWED_TRANSITIONS[current] diff --git a/src/quickreplay/application/__init__.py b/src/quickreplay/application/__init__.py new file mode 100644 index 0000000..677e86d --- /dev/null +++ b/src/quickreplay/application/__init__.py @@ -0,0 +1,53 @@ +"""Headless application layer. + +The application controller coordinates the recorder worker process and the mpv +replay controller, and exposes a UI-independent state, snapshot and event API. +""" + +from quickreplay.app.state import ApplicationState +from quickreplay.application.controller import ( + ApplicationController, + ReplayControllerLike, + WorkerHandle, +) +from quickreplay.application.errors import ( + ApplicationControllerError, + ApplicationShutdownError, + InvalidApplicationStateError, + WorkerExitedError, + WorkerStartupError, +) +from quickreplay.application.events import ( + ApplicationError, + ApplicationEvent, + ApplicationStateChanged, + InputsChanged, + RecordingMetricsChanged, + RecordingStarted, + ReplayStarted, +) +from quickreplay.application.models import ( + ApplicationControllerSettings, + ApplicationSnapshot, +) + +__all__ = [ + "ApplicationController", + "ApplicationControllerError", + "ApplicationControllerSettings", + "ApplicationError", + "ApplicationEvent", + "ApplicationShutdownError", + "ApplicationSnapshot", + "ApplicationState", + "ApplicationStateChanged", + "InputsChanged", + "InvalidApplicationStateError", + "RecordingMetricsChanged", + "RecordingStarted", + "ReplayControllerLike", + "ReplayStarted", + "WorkerExitedError", + "WorkerHandle", + "WorkerStartupError", +] diff --git a/src/quickreplay/application/controller.py b/src/quickreplay/application/controller.py new file mode 100644 index 0000000..846d4ac --- /dev/null +++ b/src/quickreplay/application/controller.py @@ -0,0 +1,634 @@ +"""Headless application controller. + +Coordinates the recorder worker process and the mpv replay controller. It owns +both components, translates the worker protocol into UI-independent application +events, correlates asynchronous responses by request id and drives the +recording/replay/resume lifecycle. It never captures frames, encodes, builds +replay assets or talks to mpv directly. +""" + +import functools +import time +from collections.abc import Callable +from typing import Protocol, TypeVar +from uuid import UUID, uuid4 + +from quickreplay.app.state import ApplicationState +from quickreplay.application.errors import ( + ApplicationControllerError, + InvalidApplicationStateError, + WorkerStartupError, +) +from quickreplay.application.events import ( + ApplicationError, + ApplicationEvent, + ApplicationStateChanged, + InputsChanged, + RecordingMetricsChanged, + RecordingStarted, + ReplayStarted, +) +from quickreplay.application.models import ( + ApplicationControllerSettings, + ApplicationSnapshot, +) +from quickreplay.input.models import InputConfig +from quickreplay.recording.commands import ( + ChangeInput, + DiscoverInputs, + PrepareReplay, + ResumeRecording, + Shutdown, + StartRecording, + StopSession, + WorkerCommand, +) +from quickreplay.recording.events import ( + InputsDiscovered, + RecordingMetricsUpdated, + ReplayPrepared, + SessionStopped, + StreamStarted, + WorkerError, + WorkerEvent, + WorkerStateChanged, +) +from quickreplay.recording.models import RecordingMetrics, WorkerErrorCode, WorkerState +from quickreplay.replay.controller import ReplayController +from quickreplay.replay.errors import MpvProcessExitedError +from quickreplay.replay.models import ReplayAsset, SetPoint +from quickreplay.worker.process import RecorderWorkerProcess +from quickreplay.worker.settings import RecorderWorkerSettings + +_START = "start" +_CHANGE = "change" + +_T = TypeVar("_T") + + +class WorkerHandle(Protocol): + """The worker operations the application controller needs.""" + + def start(self) -> None: ... + + def send(self, command: WorkerCommand) -> None: ... + + def get_event(self, timeout: float | None = None) -> WorkerEvent | None: ... + + def is_alive(self) -> bool: ... + + @property + def exitcode(self) -> int | None: ... + + def join(self, timeout: float | None = None) -> None: ... + + def terminate(self) -> None: ... + + def close(self) -> None: ... + + +class ReplayControllerLike(Protocol): + """The replay playback operations the application controller delegates.""" + + def open(self, asset: ReplayAsset) -> None: ... + + def close(self) -> None: ... + + @property + def asset(self) -> ReplayAsset | None: ... + + @property + def is_open(self) -> bool: ... + + def check_alive(self) -> None: ... + + def play(self) -> None: ... + + def pause(self) -> None: ... + + def is_paused(self) -> bool: ... + + def step_forward(self) -> None: ... + + def step_backward(self) -> None: ... + + def seek_frames(self, frames: int) -> None: ... + + def seek_absolute_ns(self, position_ns: int) -> None: ... + + def position_ns(self) -> int: ... + + def set_point(self) -> SetPoint: ... + + def time_difference_ns(self, point: SetPoint) -> int: ... + + def frame_difference(self, point: SetPoint) -> int: ... + + +def _default_worker_factory(settings: ApplicationControllerSettings) -> WorkerHandle: + worker_settings: RecorderWorkerSettings | None = settings.worker + if worker_settings is None: + raise ApplicationControllerError( + "RecorderWorkerSettings are required to build the recorder worker" + ) + return RecorderWorkerProcess(worker_settings) + + +def _default_replay_factory(settings: ApplicationControllerSettings) -> ReplayControllerLike: + return ReplayController(settings.replay) + + +class ApplicationController: + """Coordinate recording and replay for a headless QuickReplay core.""" + + def __init__( + self, + settings: ApplicationControllerSettings | None = None, + *, + worker_factory: Callable[[], WorkerHandle] | None = None, + replay_controller_factory: Callable[[], ReplayControllerLike] | None = None, + request_id_factory: Callable[[], UUID] = uuid4, + ) -> None: + self._settings = settings or ApplicationControllerSettings() + self._worker_factory = worker_factory or functools.partial( + _default_worker_factory, self._settings + ) + self._replay_factory = replay_controller_factory or functools.partial( + _default_replay_factory, self._settings + ) + self._request_id_factory = request_id_factory + + self._state = ApplicationState.STARTING + self._worker: WorkerHandle | None = None + self._replay: ReplayControllerLike | None = None + + self._stream_info = None + self._metrics: RecordingMetrics | None = None + self._replay_asset: ReplayAsset | None = None + self._error_message: str | None = None + + self._pending_kind: str | None = None + self._pending_start_request_id: UUID | None = None + self._pending_stream_request_id: UUID | None = None + self._pending_replay_request_id: UUID | None = None + self._pending_resume_request_id: UUID | None = None + self._pending_stop_request_id: UUID | None = None + self._pending_discovery_ids: set[UUID] = set() + + self._events: list[ApplicationEvent] = [] + self._started = False + + # -- queries ----------------------------------------------------------- + @property + def state(self) -> ApplicationState: + return self._state + + @property + def stream_info(self): + return self._stream_info + + @property + def replay_asset(self) -> ReplayAsset | None: + return self._replay_asset + + def snapshot(self) -> ApplicationSnapshot: + """A read-only view of the current application state.""" + return ApplicationSnapshot( + state=self._state, + stream_info=self._stream_info, + metrics=self._metrics, + replay_asset=self._replay_asset, + error_message=self._error_message, + ) + + # -- lifecycle --------------------------------------------------------- + def start(self) -> None: + """Start the recorder worker and wait until it is idle.""" + if self._worker is not None or self._started: + raise InvalidApplicationStateError("the application has already been started") + self._started = True + self._set_state(ApplicationState.STARTING) + worker = self._worker_factory() + self._worker = worker + try: + worker.start() + self._wait_for_worker_idle() + except BaseException as exc: + self._fail(str(exc), source="worker") + raise WorkerStartupError(str(exc)) from exc + self._set_state(ApplicationState.IDLE) + + def start_recording(self, input_config: InputConfig) -> None: + """Start a fresh recording session from *input_config*.""" + self._require_state(ApplicationState.IDLE, "start_recording") + request_id = self._request_id_factory() + self._stream_info = None + self._metrics = None + self._replay_asset = None + self._error_message = None + self._pending_replay_request_id = None + self._pending_resume_request_id = None + self._pending_start_request_id = request_id + self._pending_kind = _START + self._pending_stream_request_id = request_id + self._set_state(ApplicationState.STARTING) + self._send(StartRecording(request_id=request_id, input_config=input_config)) + + def request_replay(self) -> UUID: + """Freeze the buffer and build a replay asset.""" + self._require_state(ApplicationState.RECORDING, "request_replay") + if self._pending_replay_request_id is not None: + raise InvalidApplicationStateError("a replay request is already pending") + request_id = self._request_id_factory() + self._pending_replay_request_id = request_id + self._metrics = None + self._set_state(ApplicationState.PREPARING_REPLAY) + self._send(PrepareReplay(request_id)) + return request_id + + def resume_recording(self) -> UUID: + """Close the replay and resume recording.""" + self._require_state(ApplicationState.REPLAY, "resume_recording") + if self._pending_resume_request_id is not None: + raise InvalidApplicationStateError("a resume request is already pending") + self._close_replay() + return self._begin_resume() + + def stop_session(self) -> UUID: + """Discard the current session and return to idle without stopping the worker.""" + self._require_state_any( + (ApplicationState.RECORDING, ApplicationState.REPLAY), "stop_session" + ) + if self._pending_stop_request_id is not None: + raise InvalidApplicationStateError("a stop session request is already pending") + request_id = self._request_id_factory() + self._pending_stop_request_id = request_id + self._set_state(ApplicationState.STOPPING) + self._close_replay() + self._send(StopSession(request_id)) + return request_id + + def change_input(self, input_config: InputConfig) -> UUID: + """Switch the active input while recording.""" + self._require_state(ApplicationState.RECORDING, "change_input") + request_id = self._request_id_factory() + self._pending_kind = _CHANGE + self._pending_stream_request_id = request_id + self._set_state(ApplicationState.STARTING) + self._send(ChangeInput(request_id, input_config)) + return request_id + + def discover_inputs(self) -> UUID: + """Request the list of available inputs (allowed while recording/replaying).""" + if self._state not in ( + ApplicationState.IDLE, + ApplicationState.RECORDING, + ApplicationState.REPLAY, + ): + raise InvalidApplicationStateError( + f"discover_inputs is not allowed in state {self._state}" + ) + request_id = self._request_id_factory() + self._pending_discovery_ids.add(request_id) + self._send(DiscoverInputs(request_id)) + return request_id + + def shutdown(self) -> None: + """Stop replay and the worker, then release the IPC queues.""" + if self._state == ApplicationState.SHUTTING_DOWN: + return + self._set_state(ApplicationState.SHUTTING_DOWN) + self._close_replay() + worker = self._worker + if worker is None: + return + try: + worker.send(Shutdown()) + except Exception: # noqa: BLE001 - best effort + pass + timeout = self._settings.worker_shutdown_timeout_seconds + worker.join(timeout=timeout) + if worker.is_alive(): + worker.terminate() + worker.join(timeout=timeout) + if not worker.is_alive(): + try: + worker.close() + except Exception: # noqa: BLE001 - best effort + pass + self._worker = None + + # -- event loop -------------------------------------------------------- + def poll(self, timeout: float = 0.0) -> tuple[ApplicationEvent, ...]: + """Process worker events and return the application events produced.""" + self._drain_worker_events(timeout) + self._check_worker_liveness() + self._check_replay_liveness() + events = tuple(self._events) + self._events.clear() + return events + + # -- replay delegation ------------------------------------------------- + def play(self) -> None: + self._call_replay(lambda replay: replay.play()) + + def pause(self) -> None: + self._call_replay(lambda replay: replay.pause()) + + def is_paused(self) -> bool: + return self._call_replay(lambda replay: replay.is_paused()) + + def step_forward(self) -> None: + self._call_replay(lambda replay: replay.step_forward()) + + def step_backward(self) -> None: + self._call_replay(lambda replay: replay.step_backward()) + + def seek_frames(self, frames: int) -> None: + self._call_replay(lambda replay: replay.seek_frames(frames)) + + def seek_absolute_ns(self, position_ns: int) -> None: + self._call_replay(lambda replay: replay.seek_absolute_ns(position_ns)) + + def replay_position_ns(self) -> int: + return self._call_replay(lambda replay: replay.position_ns()) + + def set_point(self) -> SetPoint: + return self._call_replay(lambda replay: replay.set_point()) + + def time_difference_ns(self, point: SetPoint) -> int: + return self._call_replay(lambda replay: replay.time_difference_ns(point)) + + def frame_difference(self, point: SetPoint) -> int: + return self._call_replay(lambda replay: replay.frame_difference(point)) + + # -- worker event handling --------------------------------------------- + def _drain_worker_events(self, timeout: float) -> None: + worker = self._worker + if worker is None: + return + first = worker.get_event(timeout=timeout) + if first is not None: + self._handle_worker_event(first) + while True: + event = worker.get_event(timeout=0) + if event is None: + return + self._handle_worker_event(event) + + def _handle_worker_event(self, event: WorkerEvent) -> None: + match event: + case WorkerStateChanged(): + self._handle_worker_state(event.state) + case StreamStarted(): + self._handle_stream_started(event) + case ReplayPrepared(): + self._handle_replay_prepared(event) + case SessionStopped(): + self._handle_session_stopped(event) + case RecordingMetricsUpdated(): + self._handle_metrics(event.metrics) + case InputsDiscovered(): + self._handle_inputs_discovered(event) + case WorkerError(): + self._handle_worker_error(event) + + def _handle_worker_state(self, state: WorkerState) -> None: + if state == WorkerState.ERROR and self._state not in ( + ApplicationState.ERROR, + ApplicationState.SHUTTING_DOWN, + ): + self._fail("the recorder worker entered an error state", source="worker") + + def _handle_stream_started(self, event: StreamStarted) -> None: + if self._state == ApplicationState.STARTING: + if self._pending_kind == _START and event.request_id == self._pending_start_request_id: + self._accept_stream(event) + return + if ( + self._pending_kind == _CHANGE + and event.request_id == self._pending_stream_request_id + ): + self._accept_stream(event) + return + return + if ( + self._state == ApplicationState.RESUMING + and event.request_id == self._pending_resume_request_id + ): + self._pending_resume_request_id = None + self._metrics = None + self._accept_stream(event) + + def _accept_stream(self, event: StreamStarted) -> None: + self._stream_info = event.stream_info + self._pending_kind = None + self._pending_start_request_id = None + self._pending_stream_request_id = None + self._set_state(ApplicationState.RECORDING) + self._emit(RecordingStarted(stream_info=event.stream_info)) + + def _handle_replay_prepared(self, event: ReplayPrepared) -> None: + if self._state != ApplicationState.PREPARING_REPLAY: + return + if event.request_id != self._pending_replay_request_id: + return + replay = self._replay_factory() + try: + replay.open(event.asset) + except BaseException as exc: # noqa: BLE001 - reported as an application error + try: + replay.close() + except Exception: # noqa: BLE001 - best effort + pass + self._fail(f"could not open the replay: {exc}", source="replay") + return + self._replay = replay + self._replay_asset = event.asset + self._pending_replay_request_id = None + self._metrics = None + self._set_state(ApplicationState.REPLAY) + self._emit(ReplayStarted(asset=event.asset)) + + def _handle_session_stopped(self, event: SessionStopped) -> None: + if event.request_id != self._pending_stop_request_id: + return + self._pending_stop_request_id = None + self._stream_info = None + self._metrics = None + self._replay_asset = None + self._pending_kind = None + self._pending_start_request_id = None + self._pending_stream_request_id = None + self._pending_replay_request_id = None + self._pending_resume_request_id = None + self._error_message = None + self._set_state(ApplicationState.IDLE) + + def _handle_metrics(self, metrics: RecordingMetrics) -> None: + if self._state != ApplicationState.RECORDING: + return + self._metrics = metrics + self._emit(RecordingMetricsChanged(metrics=metrics)) + + def _handle_inputs_discovered(self, event: InputsDiscovered) -> None: + if event.request_id not in self._pending_discovery_ids: + return + self._pending_discovery_ids.discard(event.request_id) + self._emit(InputsChanged(request_id=event.request_id, inputs=event.inputs)) + + def _handle_worker_error(self, event: WorkerError) -> None: + request_id = event.request_id + if request_id is not None and request_id in self._pending_discovery_ids: + self._pending_discovery_ids.discard(request_id) + self._emit( + ApplicationError( + message=event.message, + source="worker", + code=event.code, + request_id=request_id, + ) + ) + return + if request_id is not None: + if self._state == ApplicationState.STARTING: + expected_id = ( + self._pending_start_request_id + if self._pending_kind == _START + else self._pending_stream_request_id + ) + if request_id != expected_id: + return + elif self._state == ApplicationState.RESUMING: + if request_id != self._pending_resume_request_id: + return + elif self._state == ApplicationState.PREPARING_REPLAY: + if request_id != self._pending_replay_request_id: + return + elif self._state == ApplicationState.STOPPING: + if request_id != self._pending_stop_request_id: + return + else: + return + self._fail(event.message, source="worker", code=event.code, request_id=request_id) + + # -- replay liveness --------------------------------------------------- + def _call_replay(self, action: Callable[[ReplayControllerLike], _T]) -> _T: + replay = self._require_replay() + try: + return action(replay) + except MpvProcessExitedError: + self._handle_replay_exit() + raise + + def _check_replay_liveness(self) -> None: + if self._state != ApplicationState.REPLAY or self._replay is None: + return + try: + self._replay.check_alive() + except MpvProcessExitedError: + self._handle_replay_exit() + + def _handle_replay_exit(self) -> None: + if self._state != ApplicationState.REPLAY: + return + self._close_replay() + self._begin_resume() + + def _begin_resume(self) -> UUID: + request_id = self._request_id_factory() + self._pending_resume_request_id = request_id + self._set_state(ApplicationState.RESUMING) + self._send(ResumeRecording(request_id)) + return request_id + + def _close_replay(self) -> None: + replay = self._replay + self._replay = None + self._replay_asset = None + if replay is not None: + try: + replay.close() + except Exception: # noqa: BLE001 - best effort + pass + + # -- worker liveness --------------------------------------------------- + def _check_worker_liveness(self) -> None: + worker = self._worker + if worker is None: + return + if self._state in (ApplicationState.ERROR, ApplicationState.SHUTTING_DOWN): + return + if not worker.is_alive(): + self._fail(f"the recorder worker exited with code {worker.exitcode}", source="worker") + + # -- helpers ----------------------------------------------------------- + def _wait_for_worker_idle(self) -> None: + worker = self._worker + if worker is None: # pragma: no cover - defensive + raise WorkerStartupError("the recorder worker is not available") + deadline = time.monotonic() + self._settings.worker_start_timeout_seconds + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise WorkerStartupError("timed out waiting for the worker to start") + event = worker.get_event(timeout=remaining) + if event is None: + if not worker.is_alive(): + raise WorkerStartupError( + f"the recorder worker exited with code {worker.exitcode}" + ) + continue + if isinstance(event, WorkerStateChanged) and event.state == WorkerState.IDLE: + return + if isinstance(event, WorkerError): + raise WorkerStartupError(event.message) + + def _require_state(self, expected: ApplicationState, operation: str) -> None: + if self._state != expected: + raise InvalidApplicationStateError(f"{operation} is not allowed in state {self._state}") + + def _require_state_any(self, expected: tuple[ApplicationState, ...], operation: str) -> None: + if self._state not in expected: + raise InvalidApplicationStateError(f"{operation} is not allowed in state {self._state}") + + def _require_replay(self) -> ReplayControllerLike: + if self._state != ApplicationState.REPLAY or self._replay is None: + raise InvalidApplicationStateError("replay is not active") + try: + self._replay.check_alive() + except MpvProcessExitedError: + self._handle_replay_exit() + raise + return self._replay + + def _send(self, command: WorkerCommand) -> None: + worker = self._worker + if worker is None: + raise ApplicationControllerError("the recorder worker is not running") + worker.send(command) + + def _set_state(self, state: ApplicationState) -> None: + if self._state == state: + return + self._state = state + self._emit(ApplicationStateChanged(state=state)) + + def _fail( + self, + message: str, + *, + source: str, + code: WorkerErrorCode | None = None, + request_id: UUID | None = None, + ) -> None: + if self._state in (ApplicationState.ERROR, ApplicationState.SHUTTING_DOWN): + return + self._error_message = message + self._emit( + ApplicationError(message=message, source=source, code=code, request_id=request_id) + ) + self._set_state(ApplicationState.ERROR) + + def _emit(self, event: ApplicationEvent) -> None: + self._events.append(event) diff --git a/src/quickreplay/application/errors.py b/src/quickreplay/application/errors.py new file mode 100644 index 0000000..100088e --- /dev/null +++ b/src/quickreplay/application/errors.py @@ -0,0 +1,25 @@ +"""Errors raised by the application controller. + +These are UI-independent; a future UI renders the application error events +instead of catching these exceptions directly. +""" + + +class ApplicationControllerError(RuntimeError): + """Base class for application controller errors.""" + + +class InvalidApplicationStateError(ApplicationControllerError): + """An operation was requested in a state that does not allow it.""" + + +class WorkerStartupError(ApplicationControllerError): + """The recorder worker did not become ready.""" + + +class WorkerExitedError(ApplicationControllerError): + """The recorder worker exited unexpectedly.""" + + +class ApplicationShutdownError(ApplicationControllerError): + """The application could not be shut down cleanly.""" diff --git a/src/quickreplay/application/events.py b/src/quickreplay/application/events.py new file mode 100644 index 0000000..a5d2df8 --- /dev/null +++ b/src/quickreplay/application/events.py @@ -0,0 +1,69 @@ +"""UI-independent events emitted by the application controller. + +The worker protocol (``WorkerStateChanged`` / ``WorkerError`` / ``ReplayPrepared``) +is never exposed directly; it is translated into these application events. +""" + +from dataclasses import dataclass +from uuid import UUID + +from quickreplay.app.state import ApplicationState +from quickreplay.input.models import InputDescriptor, StreamInfo +from quickreplay.recording.models import RecordingMetrics, WorkerErrorCode +from quickreplay.replay.models import ReplayAsset + + +@dataclass(frozen=True, slots=True) +class ApplicationStateChanged: + """The application changed its top-level state.""" + + state: ApplicationState + + +@dataclass(frozen=True, slots=True) +class RecordingStarted: + """Recording started and the input stream format is known.""" + + stream_info: StreamInfo + + +@dataclass(frozen=True, slots=True) +class RecordingMetricsChanged: + """Recording metrics were updated.""" + + metrics: RecordingMetrics + + +@dataclass(frozen=True, slots=True) +class ReplayStarted: + """A replay asset was opened for playback.""" + + asset: ReplayAsset + + +@dataclass(frozen=True, slots=True) +class InputsChanged: + """Input discovery completed.""" + + request_id: UUID + inputs: tuple[InputDescriptor, ...] + + +@dataclass(frozen=True, slots=True) +class ApplicationError: + """A human-readable application error, with optional correlation data.""" + + message: str + source: str = "application" + code: WorkerErrorCode | None = None + request_id: UUID | None = None + + +type ApplicationEvent = ( + ApplicationStateChanged + | RecordingStarted + | RecordingMetricsChanged + | ReplayStarted + | InputsChanged + | ApplicationError +) diff --git a/src/quickreplay/application/models.py b/src/quickreplay/application/models.py new file mode 100644 index 0000000..e2f0273 --- /dev/null +++ b/src/quickreplay/application/models.py @@ -0,0 +1,36 @@ +"""Application-level settings and read-only snapshots.""" + +from dataclasses import dataclass, field + +from quickreplay.app.state import ApplicationState +from quickreplay.input.models import StreamInfo +from quickreplay.recording.models import RecordingMetrics +from quickreplay.replay.controller import ReplayControllerSettings +from quickreplay.replay.models import ReplayAsset +from quickreplay.worker.settings import RecorderWorkerSettings + + +@dataclass(frozen=True, slots=True) +class ApplicationControllerSettings: + """Runtime settings for the application controller. + + The recorder/replay component settings are embedded, not duplicated. They + are only needed when the controller builds the components itself; tests + inject ready-made fakes instead. + """ + + worker: RecorderWorkerSettings | None = None + replay: ReplayControllerSettings = field(default_factory=ReplayControllerSettings) + worker_start_timeout_seconds: float = 5.0 + worker_shutdown_timeout_seconds: float = 5.0 + + +@dataclass(frozen=True, slots=True) +class ApplicationSnapshot: + """A read-only view of the current application state for a UI.""" + + state: ApplicationState + stream_info: StreamInfo | None = None + metrics: RecordingMetrics | None = None + replay_asset: ReplayAsset | None = None + error_message: str | None = None diff --git a/src/quickreplay/configuration/__init__.py b/src/quickreplay/configuration/__init__.py new file mode 100644 index 0000000..68cf066 --- /dev/null +++ b/src/quickreplay/configuration/__init__.py @@ -0,0 +1,46 @@ +"""Version 2 configuration: versioned, validated JSON persistence. + +The configuration layer maps a JSON file to typed immutable models and then to +the existing runtime settings. It never performs application lifecycle, UI or +platform directory policy work. +""" + +from quickreplay.configuration.codec import ( + config_from_json_object, + config_to_json_object, +) +from quickreplay.configuration.errors import ( + ConfigurationError, + ConfigurationParseError, + ConfigurationReadError, + ConfigurationValidationError, + ConfigurationWriteError, + UnsupportedConfigVersionError, +) +from quickreplay.configuration.models import ( + CURRENT_SCHEMA_VERSION, + QuickReplayConfig, + RecordingConfig, + ReplayConfig, + UiConfig, +) +from quickreplay.configuration.runtime import build_application_settings +from quickreplay.configuration.store import ConfigurationStore + +__all__ = [ + "CURRENT_SCHEMA_VERSION", + "ConfigurationError", + "ConfigurationParseError", + "ConfigurationReadError", + "ConfigurationStore", + "ConfigurationValidationError", + "ConfigurationWriteError", + "QuickReplayConfig", + "RecordingConfig", + "ReplayConfig", + "UiConfig", + "UnsupportedConfigVersionError", + "build_application_settings", + "config_from_json_object", + "config_to_json_object", +] diff --git a/src/quickreplay/configuration/codec.py b/src/quickreplay/configuration/codec.py new file mode 100644 index 0000000..f952599 --- /dev/null +++ b/src/quickreplay/configuration/codec.py @@ -0,0 +1,154 @@ +"""JSON object <-> typed configuration conversion. + +The codec is pure: it performs strict type validation, rejects unknown fields +and builds the existing domain models (whose own validation runs too). It does +no file I/O. +""" + +from collections.abc import Callable +from typing import Any, TypeVar + +from quickreplay.configuration.errors import ( + ConfigurationValidationError, + UnsupportedConfigVersionError, +) +from quickreplay.configuration.models import ( + CURRENT_SCHEMA_VERSION, + QuickReplayConfig, + RecordingConfig, + ReplayConfig, + UiConfig, +) +from quickreplay.input.models import InputConfig, NdiInputConfig + +_T = TypeVar("_T") + +_TOP_LEVEL_FIELDS = {"schema_version", "input", "recording", "replay", "ui"} +_NDI_FIELDS = {"type", "source_name"} +_RECORDING_FIELDS = {"buffer_duration_seconds"} +_REPLAY_FIELDS = {"mpv_executable"} + + +def config_from_json_object(value: object) -> QuickReplayConfig: + """Parse a JSON object into a validated :class:`QuickReplayConfig`.""" + obj = _require_object(value, "config") + if "schema_version" not in obj: + raise ConfigurationValidationError("schema_version is required") + version = _require_int(obj["schema_version"], "schema_version") + if version != CURRENT_SCHEMA_VERSION: + raise UnsupportedConfigVersionError( + f"unsupported schema_version {version}; expected {CURRENT_SCHEMA_VERSION}" + ) + _reject_unknown(obj, _TOP_LEVEL_FIELDS, "") + + input_config = _parse_input(obj["input"]) if "input" in obj else None + recording = _parse_recording(obj.get("recording", {})) + replay = _parse_replay(obj.get("replay", {})) + ui = _parse_ui(obj.get("ui", {})) + return QuickReplayConfig( + schema_version=version, + input=input_config, + recording=recording, + replay=replay, + ui=ui, + ) + + +def config_to_json_object(config: QuickReplayConfig) -> dict[str, object]: + """Serialize a configuration into its canonical JSON object.""" + return { + "schema_version": config.schema_version, + "input": _input_to_json_object(config.input), + "recording": {"buffer_duration_seconds": config.recording.buffer_duration_seconds}, + "replay": {"mpv_executable": config.replay.mpv_executable}, + "ui": {}, + } + + +# -- parsing --------------------------------------------------------------- +def _parse_input(value: object) -> InputConfig | None: + if value is None: + return None + obj = _require_object(value, "input") + kind = _require_str(_required(obj, "type", "input"), "input.type") + if kind == "ndi": + _reject_unknown(obj, _NDI_FIELDS, "input") + source_name = _require_str(_required(obj, "source_name", "input"), "input.source_name") + return _domain(lambda: NdiInputConfig(source_name), "input") + raise ConfigurationValidationError(f"input.type {kind!r} is not supported") + + +def _parse_recording(value: object) -> RecordingConfig: + obj = _require_object(value, "recording") + _reject_unknown(obj, _RECORDING_FIELDS, "recording") + seconds = _require_int( + obj.get("buffer_duration_seconds", RecordingConfig().buffer_duration_seconds), + "recording.buffer_duration_seconds", + ) + return RecordingConfig(seconds) + + +def _parse_replay(value: object) -> ReplayConfig: + obj = _require_object(value, "replay") + _reject_unknown(obj, _REPLAY_FIELDS, "replay") + executable = _require_str( + obj.get("mpv_executable", ReplayConfig().mpv_executable), "replay.mpv_executable" + ) + return ReplayConfig(executable) + + +def _parse_ui(value: object) -> UiConfig: + obj = _require_object(value, "ui") + _reject_unknown(obj, set(), "ui") + return UiConfig() + + +# -- serialization --------------------------------------------------------- +def _input_to_json_object(input_config: InputConfig | None) -> dict[str, object] | None: + if input_config is None: + return None + if isinstance(input_config, NdiInputConfig): + return {"type": "ndi", "source_name": input_config.source_name} + raise TypeError(f"unsupported input configuration: {input_config!r}") + + +# -- helpers --------------------------------------------------------------- +def _required(obj: dict[str, Any], key: str, path: str) -> object: + if key not in obj: + raise ConfigurationValidationError(f"{_path(path, key)} is required") + return obj[key] + + +def _path(parent: str, key: str) -> str: + return f"{parent}.{key}" if parent else key + + +def _require_object(value: object, path: str) -> dict[str, Any]: + if not isinstance(value, dict): + raise ConfigurationValidationError(f"{path} must be an object") + return value + + +def _require_str(value: object, path: str) -> str: + if not isinstance(value, str): + raise ConfigurationValidationError(f"{path} must be a string") + return value + + +def _require_int(value: object, path: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ConfigurationValidationError(f"{path} must be an integer") + return value + + +def _reject_unknown(mapping: dict[str, Any], allowed: set[str], path: str) -> None: + for key in mapping: + if key not in allowed: + raise ConfigurationValidationError(f"unknown field {key!r} in {path or 'config'}") + + +def _domain[T](builder: Callable[[], T], path: str) -> T: + try: + return builder() + except ValueError as exc: + raise ConfigurationValidationError(f"{path}: {exc}") from exc diff --git a/src/quickreplay/configuration/errors.py b/src/quickreplay/configuration/errors.py new file mode 100644 index 0000000..ba6a31b --- /dev/null +++ b/src/quickreplay/configuration/errors.py @@ -0,0 +1,25 @@ +"""Errors raised by the configuration component.""" + + +class ConfigurationError(RuntimeError): + """Base class for configuration errors.""" + + +class ConfigurationReadError(ConfigurationError): + """Reading the configuration file failed.""" + + +class ConfigurationParseError(ConfigurationError): + """The configuration file is not valid JSON.""" + + +class ConfigurationValidationError(ConfigurationError): + """The configuration does not match the schema.""" + + +class UnsupportedConfigVersionError(ConfigurationError): + """The configuration schema version is not supported.""" + + +class ConfigurationWriteError(ConfigurationError): + """Writing the configuration file failed.""" diff --git a/src/quickreplay/configuration/models.py b/src/quickreplay/configuration/models.py new file mode 100644 index 0000000..5c89030 --- /dev/null +++ b/src/quickreplay/configuration/models.py @@ -0,0 +1,72 @@ +"""Immutable persisted configuration models. + +These models describe the stable user-facing configuration. Internal runtime +tuning (queue capacities, timeouts, hold-back windows, ...) is deliberately not +part of them; it lives in the runtime settings models instead. +""" + +from dataclasses import dataclass, field + +from quickreplay.configuration.errors import ( + ConfigurationValidationError, + UnsupportedConfigVersionError, +) +from quickreplay.input.models import InputConfig + +CURRENT_SCHEMA_VERSION = 1 +"""The configuration schema version written by this application.""" + + +@dataclass(frozen=True, slots=True) +class RecordingConfig: + """Persisted recording settings.""" + + buffer_duration_seconds: int = 120 + + def __post_init__(self) -> None: + if isinstance(self.buffer_duration_seconds, bool) or not isinstance( + self.buffer_duration_seconds, int + ): + raise ConfigurationValidationError( + "recording.buffer_duration_seconds must be an integer" + ) + if self.buffer_duration_seconds <= 0: + raise ConfigurationValidationError("recording.buffer_duration_seconds must be positive") + + +@dataclass(frozen=True, slots=True) +class ReplayConfig: + """Persisted replay settings.""" + + mpv_executable: str = "mpv" + + def __post_init__(self) -> None: + if not isinstance(self.mpv_executable, str): + raise ConfigurationValidationError("replay.mpv_executable must be a string") + if not self.mpv_executable: + raise ConfigurationValidationError("replay.mpv_executable must not be empty") + + +@dataclass(frozen=True, slots=True) +class UiConfig: + """Reserved UI settings section (populated by a later UI phase).""" + + +@dataclass(frozen=True, slots=True) +class QuickReplayConfig: + """The complete persisted configuration.""" + + schema_version: int = CURRENT_SCHEMA_VERSION + input: InputConfig | None = None + recording: RecordingConfig = field(default_factory=RecordingConfig) + replay: ReplayConfig = field(default_factory=ReplayConfig) + ui: UiConfig = field(default_factory=UiConfig) + + def __post_init__(self) -> None: + if isinstance(self.schema_version, bool) or not isinstance(self.schema_version, int): + raise ConfigurationValidationError("schema_version must be an integer") + if self.schema_version != CURRENT_SCHEMA_VERSION: + raise UnsupportedConfigVersionError( + f"unsupported schema_version {self.schema_version}; " + f"expected {CURRENT_SCHEMA_VERSION}" + ) diff --git a/src/quickreplay/configuration/runtime.py b/src/quickreplay/configuration/runtime.py new file mode 100644 index 0000000..72726f7 --- /dev/null +++ b/src/quickreplay/configuration/runtime.py @@ -0,0 +1,31 @@ +"""Conversion from persisted configuration to runtime settings. + +Only stable user settings are mapped. Internal runtime tuning (queue +capacities, hold-back windows, timeouts, segment duration, ...) keeps its +existing defaults. ``working_directory`` comes from the runtime environment, +never from the configuration file. +""" + +from pathlib import Path + +from quickreplay.application.models import ApplicationControllerSettings +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.replay.controller import ReplayControllerSettings +from quickreplay.units import NANOSECONDS_PER_SECOND +from quickreplay.worker.settings import RecorderWorkerSettings + + +def build_application_settings( + config: QuickReplayConfig, + *, + working_directory: Path, +) -> ApplicationControllerSettings: + """Build runtime settings from *config* and a runtime working directory.""" + worker_settings = RecorderWorkerSettings( + working_directory=working_directory, + buffer_duration_ns=config.recording.buffer_duration_seconds * NANOSECONDS_PER_SECOND, + ) + replay_settings = ReplayControllerSettings( + mpv_executable=config.replay.mpv_executable, + ) + return ApplicationControllerSettings(worker=worker_settings, replay=replay_settings) diff --git a/src/quickreplay/configuration/store.py b/src/quickreplay/configuration/store.py new file mode 100644 index 0000000..471985b --- /dev/null +++ b/src/quickreplay/configuration/store.py @@ -0,0 +1,75 @@ +"""File persistence for the configuration. + +The store knows only about JSON files and the configuration codec; it never +imports the application controller, the recorder worker or the replay +controller. Saves are atomic: the new file is written to a temporary sibling, +flushed, fsynced, closed and then ``os.replace``d over the destination. +""" + +import json +import os +from pathlib import Path + +from quickreplay.configuration.codec import ( + config_from_json_object, + config_to_json_object, +) +from quickreplay.configuration.errors import ( + ConfigurationParseError, + ConfigurationReadError, + ConfigurationWriteError, +) +from quickreplay.configuration.models import QuickReplayConfig + + +class ConfigurationStore: + """Load and save a :class:`QuickReplayConfig` at a fixed path.""" + + def __init__(self, path: Path) -> None: + self._path = Path(path) + + @property + def path(self) -> Path: + return self._path + + def load(self) -> QuickReplayConfig: + """Return the stored configuration, or defaults when the file is absent.""" + if not self._path.exists(): + return QuickReplayConfig() + try: + text = self._path.read_text(encoding="utf-8") + except OSError as exc: + raise ConfigurationReadError( + f"could not read the configuration file {self._path}: {exc}" + ) from exc + try: + value = json.loads(text) + except json.JSONDecodeError as exc: + raise ConfigurationParseError( + f"the configuration file {self._path} is not valid JSON: {exc}" + ) from exc + return config_from_json_object(value) + + def save(self, config: QuickReplayConfig) -> None: + """Write *config* atomically as canonical UTF-8 JSON.""" + payload = json.dumps(config_to_json_object(config), indent=2, ensure_ascii=False) + "\n" + tmp_path = self._path.with_name(self._path.name + ".tmp") + try: + self._path.parent.mkdir(parents=True, exist_ok=True) + with open(tmp_path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp_path, self._path) + except OSError as exc: + _remove_quietly(tmp_path) + raise ConfigurationWriteError( + f"could not write the configuration file {self._path}: {exc}" + ) from exc + + +def _remove_quietly(path: Path) -> None: + try: + path.unlink() + except OSError: + pass diff --git a/src/quickreplay/input/__init__.py b/src/quickreplay/input/__init__.py new file mode 100644 index 0000000..f291e19 --- /dev/null +++ b/src/quickreplay/input/__init__.py @@ -0,0 +1,5 @@ +"""Input configuration and stream/frame domain models. + +Supports NDI input. This package only defines types; +no discovery or capture implementation lives here. +""" diff --git a/src/quickreplay/input/models.py b/src/quickreplay/input/models.py new file mode 100644 index 0000000..3063ee1 --- /dev/null +++ b/src/quickreplay/input/models.py @@ -0,0 +1,122 @@ +"""Input configuration, stream information and frame models. + +Time is integer nanoseconds and frame rates are :class:`~fractions.Fraction`. +``data`` on the frame models is intentionally typed as :class:`object`; the +concrete buffer type is decided once a native implementation exists. +""" + +from dataclasses import dataclass +from fractions import Fraction + + +@dataclass(frozen=True, slots=True) +class NdiInputConfig: + """NDI input identified by its advertised source name.""" + + source_name: str + + def __post_init__(self) -> None: + if not self.source_name: + raise ValueError("source_name must not be empty") + + +type InputConfig = NdiInputConfig + + +@dataclass(frozen=True, slots=True) +class VideoStreamInfo: + """Declared video stream format.""" + + width: int + height: int + fps: Fraction + pixel_format: str + + def __post_init__(self) -> None: + if self.width <= 0: + raise ValueError(f"width must be positive, got {self.width}") + if self.height <= 0: + raise ValueError(f"height must be positive, got {self.height}") + if self.fps <= 0: + raise ValueError(f"fps must be positive, got {self.fps}") + + +@dataclass(frozen=True, slots=True) +class AudioStreamInfo: + """Declared audio stream format.""" + + sample_rate: int + channels: int + + def __post_init__(self) -> None: + if self.sample_rate <= 0: + raise ValueError(f"sample_rate must be positive, got {self.sample_rate}") + if self.channels <= 0: + raise ValueError(f"channels must be positive, got {self.channels}") + + +@dataclass(frozen=True, slots=True) +class StreamInfo: + """Declared stream format of an input. + + ``audio`` is ``None`` when the active stream has no audio. + """ + + video: VideoStreamInfo + audio: AudioStreamInfo | None = None + + +@dataclass(frozen=True, slots=True) +class VideoFrame: + """One captured video frame handed to later stages.""" + + timestamp_ns: int + + width: int + height: int + fps: Fraction + + pixel_format: str + data: object + + def __post_init__(self) -> None: + if self.width <= 0: + raise ValueError(f"width must be positive, got {self.width}") + if self.height <= 0: + raise ValueError(f"height must be positive, got {self.height}") + if self.fps <= 0: + raise ValueError(f"fps must be positive, got {self.fps}") + + +@dataclass(frozen=True, slots=True) +class AudioFrame: + """One captured audio frame handed to later stages.""" + + timestamp_ns: int + + sample_rate: int + channels: int + sample_count: int + + data: object + + def __post_init__(self) -> None: + if self.sample_rate <= 0: + raise ValueError(f"sample_rate must be positive, got {self.sample_rate}") + if self.channels <= 0: + raise ValueError(f"channels must be positive, got {self.channels}") + if self.sample_count < 0: + raise ValueError(f"sample_count must not be negative, got {self.sample_count}") + + +type CaptureItem = VideoFrame | AudioFrame + + +@dataclass(frozen=True, slots=True) +class NdiInputDescriptor: + """A discoverable NDI source, safe to send over IPC.""" + + source_name: str + + +type InputDescriptor = NdiInputDescriptor diff --git a/src/quickreplay/input/ndi/__init__.py b/src/quickreplay/input/ndi/__init__.py new file mode 100644 index 0000000..f1c3e55 --- /dev/null +++ b/src/quickreplay/input/ndi/__init__.py @@ -0,0 +1,32 @@ +"""NDI input implementation. + +Everything that depends on the native ``NDIlib`` binding lives in this package +and is imported lazily, so the rest of QuickReplay never initializes NDI unless +an NDI source is actually used. +""" + +from quickreplay.input.ndi.backend import ndi_available +from quickreplay.input.ndi.discovery import discover_ndi_sources +from quickreplay.input.ndi.errors import ( + NdiCaptureError, + NdiFormatChangeError, + NdiInitializationError, + NdiInputError, + NdiReceiverError, + NdiSourceNotFoundError, + NdiUnsupportedFormatError, +) +from quickreplay.input.ndi.source import NdiInputSource + +__all__ = [ + "NdiCaptureError", + "NdiFormatChangeError", + "NdiInitializationError", + "NdiInputError", + "NdiInputSource", + "NdiReceiverError", + "NdiSourceNotFoundError", + "NdiUnsupportedFormatError", + "discover_ndi_sources", + "ndi_available", +] diff --git a/src/quickreplay/input/ndi/backend.py b/src/quickreplay/input/ndi/backend.py new file mode 100644 index 0000000..f76bedd --- /dev/null +++ b/src/quickreplay/input/ndi/backend.py @@ -0,0 +1,281 @@ +"""Thin backend around the ``ndi-python`` binding. + +This module is the only place that touches native NDI types. The rest of the +package depends on :class:`NdiBackend` / :class:`NdiReceiver` and on the plain +:class:`RawVideo` / :class:`RawAudio` / :class:`RawMetadata` dataclasses, so a +fake backend can exercise every code path without an NDI runtime or an NDI +source (see ``tests/fake_ndi.py``). + +``NDIlib`` itself is imported lazily, so importing the core package never +initializes NDI or fails on a machine without the runtime. +""" + +import threading +from dataclasses import dataclass +from fractions import Fraction +from typing import Any, Protocol + +import numpy as np + +from quickreplay.input.ndi.errors import ( + NdiCaptureError, + NdiInitializationError, + NdiReceiverError, + NdiUnsupportedFormatError, +) + +NDI_TIMESTAMP_TICK_NS = 100 +"""NDI timestamps are expressed in 100-nanosecond ticks.""" + +NDI_RECEIVER_NAME = "QuickReplay" + + +def ndi_timestamp_to_ns(timestamp_100ns: int) -> int: + """Convert an NDI 100-nanosecond timestamp to integer nanoseconds.""" + return timestamp_100ns * NDI_TIMESTAMP_TICK_NS + + +@dataclass(slots=True) +class RawVideo: + """A captured video frame still backed by native memory. + + ``data`` may be a view onto the native buffer; it must be copied before the + matching :meth:`NdiReceiver.free_video` call. + """ + + width: int + height: int + line_stride: int + pixel_format: str + fps: Fraction + timestamp_ns: int + data: np.ndarray + handle: Any + + +@dataclass(slots=True) +class RawAudio: + """A captured planar float audio frame still backed by native memory.""" + + sample_rate: int + channels: int + samples: int + channel_stride: int + audio_format: str + timestamp_ns: int + data: np.ndarray + handle: Any + + +@dataclass(slots=True) +class RawMetadata: + """A captured metadata frame. Always discarded by the input source.""" + + handle: Any + + +type RawCapture = RawVideo | RawAudio | RawMetadata | None + + +class NdiReceiver(Protocol): + """One receiver carrying both the video and the audio of a source.""" + + def capture(self, *, timeout_ms: int) -> RawCapture: ... + + def free_video(self, frame: RawVideo) -> None: ... + + def free_audio(self, frame: RawAudio) -> None: ... + + def free_metadata(self, frame: RawMetadata) -> None: ... + + def source_name(self) -> str: ... + + def destroy(self) -> None: ... + + +class NdiBackend(Protocol): + """The native operations the NDI input source needs.""" + + def initialize(self) -> None: ... + + def shutdown(self) -> None: ... + + def discover(self, *, timeout_ms: int) -> tuple[str, ...]: ... + + def create_receiver(self, *, source_name: str, timeout_ms: int) -> NdiReceiver: ... + + +def import_ndi() -> Any: + """Import and return the ``NDIlib`` module, or raise if unavailable.""" + try: + import NDIlib # noqa: PLC0415 - deliberately lazy + except Exception as exc: # noqa: BLE001 - ImportError / OSError / DLL errors + raise NdiInitializationError(f"the NDI runtime is not available: {exc}") from exc + return NDIlib + + +def ndi_available() -> bool: + """Whether the NDI runtime can be imported on this machine.""" + try: + import_ndi() + except NdiInitializationError: + return False + return True + + +class _NdiRuntime: + """Reference-counted ownership of the process-wide NDI runtime. + + ``NDIlib.initialize`` / ``NDIlib.destroy`` are global. Reference counting + keeps discovery, receivers and a future second source from destroying the + runtime while another component still needs it. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self._references = 0 + + def acquire(self) -> None: + ndi = import_ndi() + with self._lock: + if self._references == 0 and not ndi.initialize(): + raise NdiInitializationError("NDIlib.initialize() failed") + self._references += 1 + + def release(self) -> None: + with self._lock: + if self._references == 0: + return + self._references -= 1 + if self._references == 0: + import_ndi().destroy() + + +_runtime = _NdiRuntime() + + +class PyNdiBackend: + """The real backend, backed by the bundled NDI runtime.""" + + def initialize(self) -> None: + _runtime.acquire() + + def shutdown(self) -> None: + _runtime.release() + + def discover(self, *, timeout_ms: int) -> tuple[str, ...]: + ndi = import_ndi() + finder = ndi.find_create_v2() + if not finder: + raise NdiInitializationError("could not create an NDI finder") + try: + ndi.find_wait_for_sources(finder, timeout_ms) + sources = ndi.find_get_current_sources(finder) + return tuple(source.ndi_name for source in sources) + finally: + ndi.find_destroy(finder) + + def create_receiver(self, *, source_name: str, timeout_ms: int) -> NdiReceiver: + ndi = import_ndi() + settings = ndi.RecvCreateV3() + source = ndi.Source() + source.ndi_name = source_name + settings.source_to_connect_to = source + settings.color_format = ndi.RECV_COLOR_FORMAT_UYVY_BGRA + settings.bandwidth = ndi.RECV_BANDWIDTH_HIGHEST + settings.allow_video_fields = False + settings.ndi_recv_name = NDI_RECEIVER_NAME + receiver = ndi.recv_create_v3(settings) + if not receiver: + raise NdiReceiverError(f"could not create an NDI receiver for {source_name!r}") + return PyNdiReceiver(receiver) + + +class PyNdiReceiver: + """The real receiver. One instance owns exactly one native receiver.""" + + def __init__(self, receiver: Any) -> None: + self._receiver = receiver + self._destroyed = False + + def capture(self, *, timeout_ms: int) -> RawCapture: + ndi = import_ndi() + frame_type, video, audio, metadata = ndi.recv_capture_v3( + self._receiver, timeout_ms, True, True, True + ) + kind = int(frame_type) + if kind == int(ndi.FRAME_TYPE_VIDEO): + return self._video(ndi, video) if video is not None else None + if kind == int(ndi.FRAME_TYPE_AUDIO): + return self._audio(ndi, audio) if audio is not None else None + if kind == int(ndi.FRAME_TYPE_METADATA): + return RawMetadata(handle=metadata) if metadata is not None else None + if kind == int(ndi.FRAME_TYPE_ERROR): + raise NdiCaptureError("the NDI source reported a capture error") + # FRAME_TYPE_NONE / SOURCE_CHANGE / STATUS_CHANGE carry no payload. + return None + + def _video(self, ndi: Any, video: Any) -> RawVideo: + timestamp = int(video.timestamp) + if timestamp == int(ndi.RECV_TIMESTAMP_UNDEFINED): + ndi.recv_free_video_v2(self._receiver, video) + raise NdiCaptureError("the NDI video frame has no timestamp") + fourcc = int(video.FourCC) + if fourcc == int(ndi.FOURCC_VIDEO_TYPE_UYVY): + pixel_format = "UYVY" + elif fourcc == int(ndi.FOURCC_VIDEO_TYPE_BGRA): + pixel_format = "BGRA" + else: + ndi.recv_free_video_v2(self._receiver, video) + raise NdiUnsupportedFormatError( + f"unsupported NDI video format {video.FourCC!r}; supported: UYVY, BGRA" + ) + return RawVideo( + width=int(video.xres), + height=int(video.yres), + line_stride=int(video.line_stride_in_bytes), + pixel_format=pixel_format, + fps=Fraction(int(video.frame_rate_N), int(video.frame_rate_D)), + timestamp_ns=ndi_timestamp_to_ns(timestamp), + data=np.asarray(video.data), + handle=video, + ) + + def _audio(self, ndi: Any, audio: Any) -> RawAudio: + timestamp = int(audio.timestamp) + if timestamp == int(ndi.RECV_TIMESTAMP_UNDEFINED): + ndi.recv_free_audio_v3(self._receiver, audio) + raise NdiCaptureError("the NDI audio frame has no timestamp") + if int(audio.FourCC) != int(ndi.FOURCC_AUDIO_TYPE_FLTP): + ndi.recv_free_audio_v3(self._receiver, audio) + raise NdiUnsupportedFormatError( + f"unsupported NDI audio format {audio.FourCC!r}; expected planar float32" + ) + return RawAudio( + sample_rate=int(audio.sample_rate), + channels=int(audio.no_channels), + samples=int(audio.no_samples), + channel_stride=int(audio.channel_stride_in_bytes), + audio_format="FLTP", + timestamp_ns=ndi_timestamp_to_ns(timestamp), + data=np.asarray(audio.data), + handle=audio, + ) + + def free_video(self, frame: RawVideo) -> None: + import_ndi().recv_free_video_v2(self._receiver, frame.handle) + + def free_audio(self, frame: RawAudio) -> None: + import_ndi().recv_free_audio_v3(self._receiver, frame.handle) + + def free_metadata(self, frame: RawMetadata) -> None: + import_ndi().recv_free_metadata(self._receiver, frame.handle) + + def source_name(self) -> str: + return import_ndi().recv_get_source_name(self._receiver) + + def destroy(self) -> None: + if self._destroyed: + return + self._destroyed = True + import_ndi().recv_destroy(self._receiver) diff --git a/src/quickreplay/input/ndi/converter.py b/src/quickreplay/input/ndi/converter.py new file mode 100644 index 0000000..abd9b7b --- /dev/null +++ b/src/quickreplay/input/ndi/converter.py @@ -0,0 +1,134 @@ +"""Convert raw NDI frames into Python-owned domain frames. + +Every payload is copied out of the native buffer here, before the caller frees +the NDI frame. Video is normalised to a padding-free ``(height, width * 2)`` +UYVY buffer; audio to a contiguous ``(channels, samples)`` float32 buffer. +""" + +import numpy as np + +from quickreplay.input.models import AudioFrame, VideoFrame +from quickreplay.input.ndi.backend import RawAudio, RawVideo +from quickreplay.input.ndi.errors import NdiUnsupportedFormatError + + +def to_video_frame(raw: RawVideo) -> VideoFrame: + """Copy a raw UYVY or BGRA frame into an owned domain video frame.""" + pixel_format = raw.pixel_format.upper() + if pixel_format == "UYVY": + data = _uyvy_payload(raw) + elif pixel_format == "BGRA": + data = _bgra_payload(raw) + else: + raise NdiUnsupportedFormatError(f"unsupported NDI video format {raw.pixel_format!r}") + return VideoFrame( + timestamp_ns=raw.timestamp_ns, + width=raw.width, + height=raw.height, + fps=raw.fps, + pixel_format=pixel_format, + data=data, + ) + + +def to_audio_frame(raw: RawAudio) -> AudioFrame: + """Copy a raw planar float frame into an owned domain audio frame.""" + if raw.audio_format.upper() != "FLTP": + raise NdiUnsupportedFormatError(f"unsupported NDI audio format {raw.audio_format!r}") + if raw.channels not in (1, 2): + raise NdiUnsupportedFormatError( + f"unsupported NDI audio channel count {raw.channels}; only mono/stereo are supported" + ) + return AudioFrame( + timestamp_ns=raw.timestamp_ns, + sample_rate=raw.sample_rate, + channels=raw.channels, + sample_count=raw.samples, + data=_audio_payload(raw), + ) + + +def _uyvy_payload(raw: RawVideo) -> np.ndarray: + """Return a contiguous ``(height, width * 2)`` uint8 copy without padding.""" + row_bytes = raw.width * 2 + array = np.asarray(raw.data) + if array.ndim == 0: + raise NdiUnsupportedFormatError("the NDI video frame carries no data") + if array.ndim == 1: + if array.size < raw.height: + raise NdiUnsupportedFormatError( + f"NDI UYVY buffer of {array.size} bytes is too small for height {raw.height}" + ) + array = array.reshape(raw.height, -1) + rows = array.reshape(array.shape[0], -1) + if rows.shape[0] != raw.height or rows.shape[1] < row_bytes: + raise NdiUnsupportedFormatError( + f"NDI UYVY frame {array.shape} is not compatible with {raw.width}x{raw.height}" + ) + return np.array(rows[:, :row_bytes], dtype=np.uint8, copy=True) + + +def _bgra_payload(raw: RawVideo) -> np.ndarray: + """Return an owned contiguous ``(height, width, 4)`` uint8 copy.""" + row_bytes = raw.width * 4 + if raw.width <= 0 or raw.height <= 0 or raw.line_stride < row_bytes: + raise NdiUnsupportedFormatError( + f"NDI BGRA frame {raw.width}x{raw.height} has invalid line stride " + f"{raw.line_stride} (need at least {row_bytes})" + ) + array = np.asarray(raw.data) + if array.ndim == 0: + raise NdiUnsupportedFormatError("the NDI video frame carries no data") + if array.dtype != np.uint8: + raise NdiUnsupportedFormatError( + f"NDI BGRA buffer must contain uint8 bytes, got {array.dtype}" + ) + if array.ndim == 1: + required_bytes = raw.height * raw.line_stride + if array.size < required_bytes: + raise NdiUnsupportedFormatError( + f"NDI BGRA buffer of {array.size} bytes is too small for " + f"{raw.height} rows with stride {raw.line_stride}" + ) + rows = array[:required_bytes].reshape(raw.height, raw.line_stride) + elif array.ndim == 2: + rows = array + if rows.shape[0] != raw.height or rows.shape[1] < raw.line_stride: + raise NdiUnsupportedFormatError( + f"NDI BGRA frame {array.shape} is not compatible with " + f"{raw.width}x{raw.height} and stride {raw.line_stride}" + ) + pixels = rows[:, :row_bytes].reshape(raw.height, raw.width, 4) + elif array.ndim == 3: + if array.shape[0] != raw.height or array.shape[1] < raw.width or array.shape[2] != 4: + raise NdiUnsupportedFormatError( + f"NDI BGRA frame {array.shape} is not compatible with " + f"{raw.width}x{raw.height} pixels" + ) + pixels = array[: raw.height, : raw.width, :] + else: + raise NdiUnsupportedFormatError( + f"NDI BGRA frame has unsupported shape {array.shape}; expected flat bytes, " + "row matrix, or (height, width, 4) BGRA pixels" + ) + if array.ndim == 1: + pixels = rows[:, :row_bytes].reshape(raw.height, raw.width, 4) + return np.array(pixels, dtype=np.uint8, copy=True, order="C") + + +def _audio_payload(raw: RawAudio) -> np.ndarray: + """Return a contiguous ``(channels, samples)`` float32 copy.""" + array = np.asarray(raw.data) + if array.ndim == 1: + if array.size != raw.channels * raw.samples: + raise NdiUnsupportedFormatError( + f"NDI audio buffer of {array.size} samples does not match " + f"{raw.channels} channels x {raw.samples} samples" + ) + array = array.reshape(raw.channels, raw.samples) + if array.ndim != 2 or array.shape[0] != raw.channels or array.shape[1] != raw.samples: + raise NdiUnsupportedFormatError( + f"NDI audio frame {array.shape} is not compatible with " + f"{raw.channels} channels x {raw.samples} samples" + ) + return np.array(array, dtype=np.float32, copy=True) diff --git a/src/quickreplay/input/ndi/discovery.py b/src/quickreplay/input/ndi/discovery.py new file mode 100644 index 0000000..4025007 --- /dev/null +++ b/src/quickreplay/input/ndi/discovery.py @@ -0,0 +1,27 @@ +"""Discover NDI sources without leaking native objects. + +The finder is created, waited on, copied into plain +:class:`~quickreplay.input.models.NdiInputDescriptor` values and destroyed +before returning. No native source object escapes this module. +""" + +from quickreplay.input.models import NdiInputDescriptor +from quickreplay.input.ndi.backend import NdiBackend, PyNdiBackend + +DEFAULT_DISCOVERY_TIMEOUT_MS = 2000 +"""How long discovery waits for sources to appear.""" + + +def discover_ndi_sources( + *, + timeout_ms: int = DEFAULT_DISCOVERY_TIMEOUT_MS, + backend: NdiBackend | None = None, +) -> tuple[NdiInputDescriptor, ...]: + """Return the NDI sources currently advertised on the network.""" + active = backend or PyNdiBackend() + active.initialize() + try: + names = active.discover(timeout_ms=timeout_ms) + finally: + active.shutdown() + return tuple(NdiInputDescriptor(source_name=name) for name in names) diff --git a/src/quickreplay/input/ndi/errors.py b/src/quickreplay/input/ndi/errors.py new file mode 100644 index 0000000..b9a8dfc --- /dev/null +++ b/src/quickreplay/input/ndi/errors.py @@ -0,0 +1,34 @@ +"""Errors raised by the NDI input component. + +These wrap low-level binding/runtime failures so that the application layer +never sees raw library exceptions. Mapping to +:class:`~quickreplay.recording.models.WorkerErrorCode` happens in a later phase. +""" + + +class NdiInputError(RuntimeError): + """Base class for NDI input errors.""" + + +class NdiInitializationError(NdiInputError): + """The NDI runtime could not be loaded or initialized.""" + + +class NdiSourceNotFoundError(NdiInputError): + """The requested NDI source was not present during discovery.""" + + +class NdiReceiverError(NdiInputError): + """Creating, using or destroying an NDI receiver failed.""" + + +class NdiCaptureError(NdiInputError): + """Capturing a frame failed, for example after a source disconnect.""" + + +class NdiUnsupportedFormatError(NdiInputError): + """A captured frame uses a format the recording pipeline cannot consume.""" + + +class NdiFormatChangeError(NdiInputError): + """The stream format changed mid-session and cannot be silently mixed.""" diff --git a/src/quickreplay/input/ndi/source.py b/src/quickreplay/input/ndi/source.py new file mode 100644 index 0000000..dfffdd0 --- /dev/null +++ b/src/quickreplay/input/ndi/source.py @@ -0,0 +1,180 @@ +"""NDI input source. + +One :class:`NdiInputSource` owns exactly one NDI receiver, which carries both +the video and the audio of the source. ``read`` is non-blocking by default and +returns domain frames whose payload is already copied out of native memory. + +The stream format is not known before the first frames arrive, so +``stream_info`` becomes available once the source has observed its first video +frame (and its first audio frame, if the source has audio). +""" + +from fractions import Fraction + +from quickreplay.input.models import ( + AudioFrame, + AudioStreamInfo, + CaptureItem, + NdiInputConfig, + StreamInfo, + VideoFrame, + VideoStreamInfo, +) +from quickreplay.input.ndi.backend import ( + NdiBackend, + NdiReceiver, + PyNdiBackend, + RawAudio, + RawMetadata, + RawVideo, +) +from quickreplay.input.ndi.converter import to_audio_frame, to_video_frame +from quickreplay.input.ndi.errors import ( + NdiFormatChangeError, + NdiReceiverError, + NdiSourceNotFoundError, +) + +DEFAULT_DISCOVERY_TIMEOUT_MS = 2000 +"""How long ``open`` waits for the requested source to appear.""" + +DEFAULT_CAPTURE_TIMEOUT_MS = 0 +"""``0`` means non-blocking capture; the caller polls ``read``.""" + + +def source_name_matches(requested: str, discovered: str) -> bool: + """Whether *discovered* refers to the requested source name. + + NDI advertises names as ``"MACHINE (Source name)"``, so an exact match or a + ``"(requested)"`` suffix both address the same source. + """ + return discovered == requested or discovered.endswith(f"({requested})") + + +class NdiInputSource: + """An :class:`~quickreplay.input.source.InputSource` backed by NDI.""" + + def __init__( + self, + config: NdiInputConfig, + *, + backend: NdiBackend | None = None, + discovery_timeout_ms: int = DEFAULT_DISCOVERY_TIMEOUT_MS, + capture_timeout_ms: int = DEFAULT_CAPTURE_TIMEOUT_MS, + ) -> None: + self._config = config + self._backend: NdiBackend = backend or PyNdiBackend() + self._discovery_timeout_ms = discovery_timeout_ms + self._capture_timeout_ms = capture_timeout_ms + self._receiver: NdiReceiver | None = None + self._initialized = False + self._video_info: tuple[int, int, Fraction, str] | None = None + self._audio_info: tuple[int, int] | None = None + self._stream_info: StreamInfo | None = None + + @property + def stream_info(self) -> StreamInfo | None: + """The established format, or ``None`` until the first video frame.""" + return self._stream_info + + def open(self) -> None: + """Resolve the configured source and create its single receiver.""" + if self._receiver is not None: + raise NdiReceiverError("the NDI source is already open") + self._video_info = None + self._audio_info = None + self._stream_info = None + self._backend.initialize() + self._initialized = True + try: + names = self._backend.discover(timeout_ms=self._discovery_timeout_ms) + resolved = next( + (name for name in names if source_name_matches(self._config.source_name, name)), + None, + ) + if resolved is None: + raise NdiSourceNotFoundError( + f"NDI source {self._config.source_name!r} was not found; available: {names}" + ) + self._receiver = self._backend.create_receiver( + source_name=resolved, timeout_ms=self._discovery_timeout_ms + ) + except BaseException: + self._cleanup() + raise + + def read(self) -> CaptureItem | None: + """Return the next domain frame, or ``None`` when nothing is ready.""" + receiver = self._require_open() + raw = receiver.capture(timeout_ms=self._capture_timeout_ms) + if raw is None: + return None + if isinstance(raw, RawVideo): + try: + return self._video_frame(raw) + finally: + receiver.free_video(raw) + if isinstance(raw, RawAudio): + try: + return self._audio_frame(raw) + finally: + receiver.free_audio(raw) + if isinstance(raw, RawMetadata): + receiver.free_metadata(raw) + return None + + def close(self) -> None: + """Release the receiver and the runtime reference. Idempotent.""" + self._cleanup() + + # -- internals --------------------------------------------------------- + def _video_frame(self, raw: RawVideo) -> VideoFrame: + frame = to_video_frame(raw) + info = (frame.width, frame.height, frame.fps, frame.pixel_format.upper()) + if self._video_info is None: + self._video_info = info + self._refresh_stream_info() + elif info != self._video_info: + raise NdiFormatChangeError( + f"NDI video format changed from {self._video_info} to {info}" + ) + return frame + + def _audio_frame(self, raw: RawAudio) -> AudioFrame: + frame = to_audio_frame(raw) + info = (frame.sample_rate, frame.channels) + if self._audio_info is None: + self._audio_info = info + self._refresh_stream_info() + elif info != self._audio_info: + raise NdiFormatChangeError( + f"NDI audio format changed from {self._audio_info} to {info}" + ) + return frame + + def _refresh_stream_info(self) -> None: + if self._video_info is None: + return + width, height, fps, pixel_format = self._video_info + audio = None + if self._audio_info is not None: + sample_rate, channels = self._audio_info + audio = AudioStreamInfo(sample_rate=sample_rate, channels=channels) + self._stream_info = StreamInfo( + video=VideoStreamInfo(width=width, height=height, fps=fps, pixel_format=pixel_format), + audio=audio, + ) + + def _require_open(self) -> NdiReceiver: + if self._receiver is None: + raise NdiReceiverError("the NDI source is not open") + return self._receiver + + def _cleanup(self) -> None: + receiver = self._receiver + self._receiver = None + if receiver is not None: + receiver.destroy() + if self._initialized: + self._initialized = False + self._backend.shutdown() diff --git a/src/quickreplay/input/source.py b/src/quickreplay/input/source.py new file mode 100644 index 0000000..5acaaf1 --- /dev/null +++ b/src/quickreplay/input/source.py @@ -0,0 +1,36 @@ +"""Common input source abstraction shared by the input implementations. + +Input implementations share this protocol so they can be connected to the +same recording pipeline. + +``open`` prepares the source but does not necessarily establish the stream +format: NDI cannot report resolution or frame rate before the first frame +arrives. ``stream_info`` therefore becomes available only after enough frames +have been read. Every item returned by ``read`` must own its data; native +buffers are copied before being exposed and never handed out directly. +""" + +from typing import Protocol + +from quickreplay.input.models import CaptureItem, StreamInfo + + +class InputSource(Protocol): + """A capture source that produces domain frames.""" + + def open(self) -> None: + """Acquire the source. Must be idempotent-safe via ``close``.""" + ... + + @property + def stream_info(self) -> StreamInfo | None: + """The established stream format, or ``None`` before the first frame.""" + ... + + def read(self) -> CaptureItem | None: + """Return the next frame, or ``None`` when nothing is available yet.""" + ... + + def close(self) -> None: + """Release every native resource. Safe to call multiple times.""" + ... diff --git a/src/quickreplay/recording/__init__.py b/src/quickreplay/recording/__init__.py new file mode 100644 index 0000000..314e2b1 --- /dev/null +++ b/src/quickreplay/recording/__init__.py @@ -0,0 +1,5 @@ +"""Recording domain models and the worker command / event protocol. + +Value models (segments, sessions, metrics) and the messages exchanged with the +recorder worker process. Nothing in this package performs real recording. +""" diff --git a/src/quickreplay/recording/commands.py b/src/quickreplay/recording/commands.py new file mode 100644 index 0000000..e8de517 --- /dev/null +++ b/src/quickreplay/recording/commands.py @@ -0,0 +1,71 @@ +"""Commands sent to the recorder worker process. + +Every command is an immutable, picklable value object. It must never contain a +multiprocessing object, native handle or open file. Command handling is not +implemented in this phase. +""" + +from dataclasses import dataclass +from uuid import UUID + +from quickreplay.input.models import InputConfig + + +@dataclass(frozen=True, slots=True) +class StartRecording: + """Start recording from the given input.""" + + request_id: UUID + input_config: InputConfig + + +@dataclass(frozen=True, slots=True) +class PrepareReplay: + """Freeze the current buffer and build a replay asset.""" + + request_id: UUID + + +@dataclass(frozen=True, slots=True) +class ResumeRecording: + """Resume recording after a replay has finished.""" + + request_id: UUID + + +@dataclass(frozen=True, slots=True) +class ChangeInput: + """Switch the active input.""" + + request_id: UUID + input_config: InputConfig + + +@dataclass(frozen=True, slots=True) +class DiscoverInputs: + """Request the list of available inputs.""" + + request_id: UUID + + +@dataclass(frozen=True, slots=True) +class Shutdown: + """Terminate the worker process.""" + + +@dataclass(frozen=True, slots=True) +class StopSession: + """Discard the active recording/replay session but keep the worker alive.""" + + request_id: UUID + + +type WorkerCommand = ( + StartRecording + | PrepareReplay + | ResumeRecording + | ChangeInput + | DiscoverInputs + | StopSession + | Shutdown +) diff --git a/src/quickreplay/recording/errors.py b/src/quickreplay/recording/errors.py new file mode 100644 index 0000000..48782f4 --- /dev/null +++ b/src/quickreplay/recording/errors.py @@ -0,0 +1,48 @@ +"""Errors raised by the recording component. + +These wrap low-level PyAV/IO failures so that the application layer never sees +raw library exceptions. Mapping to :class:`~quickreplay.recording.models.WorkerErrorCode` +happens in a later phase. +""" + +from pathlib import Path + + +class RecordingError(RuntimeError): + """Base class for recording component errors.""" + + +class SegmentRecorderError(RecordingError): + """Base class for segment recording errors.""" + + +class SegmentFormatError(SegmentRecorderError): + """An input frame does not match the recording session's stream format.""" + + +class SegmentTimestampError(SegmentRecorderError): + """A frame timestamp violates the session timeline constraints.""" + + +class SegmentEncodingError(SegmentRecorderError): + """Encoding a segment failed.""" + + +class SegmentMuxError(SegmentRecorderError): + """Writing or finalizing a segment container failed.""" + + +class RingStorageError(RecordingError): + """Base class for ring storage errors.""" + + +class SegmentOrderError(RingStorageError): + """A segment was added out of chronological order or with a duplicate id.""" + + +class SegmentDeleteError(RingStorageError): + """Deleting one or more expired segment files failed.""" + + def __init__(self, paths: tuple[Path, ...]) -> None: + super().__init__(f"failed to delete {len(paths)} segment file(s): {paths}") + self.paths = paths diff --git a/src/quickreplay/recording/events.py b/src/quickreplay/recording/events.py new file mode 100644 index 0000000..ac49ed0 --- /dev/null +++ b/src/quickreplay/recording/events.py @@ -0,0 +1,87 @@ +"""Events emitted by the recorder worker process. + +Every event is an immutable, picklable value object safe to send over a +multiprocessing queue. Events carry only plain data or other domain models; +never native objects or video/audio frames. +""" + +from dataclasses import dataclass +from uuid import UUID + +from quickreplay.input.models import InputDescriptor, StreamInfo +from quickreplay.recording.models import ( + RecordingMetrics, + WorkerErrorCode, + WorkerState, +) +from quickreplay.replay.models import ReplayAsset + + +@dataclass(frozen=True, slots=True) +class WorkerStateChanged: + """The worker changed state.""" + + state: WorkerState + + +@dataclass(frozen=True, slots=True) +class InputsDiscovered: + """Result of an input discovery request.""" + + request_id: UUID + inputs: tuple[InputDescriptor, ...] + + +@dataclass(frozen=True, slots=True) +class StreamStarted: + """The input stream has started and its format is known. + + ``request_id`` correlates the event with a ``StartRecording``, + ``ResumeRecording`` or ``ChangeInput`` command so stale responses can be + ignored. + """ + + stream_info: StreamInfo + request_id: UUID | None = None + + +@dataclass(frozen=True, slots=True) +class RecordingMetricsUpdated: + """Periodic recording metrics update.""" + + metrics: RecordingMetrics + + +@dataclass(frozen=True, slots=True) +class ReplayPrepared: + """A replay asset is ready; the application may enter replay.""" + + request_id: UUID + asset: ReplayAsset + + +@dataclass(frozen=True, slots=True) +class SessionStopped: + """The worker finished discarding the active session.""" + + request_id: UUID + + +@dataclass(frozen=True, slots=True) +class WorkerError: + """A worker error, identified by a machine-readable code.""" + + code: WorkerErrorCode + message: str + request_id: UUID | None = None + + +type WorkerEvent = ( + WorkerStateChanged + | InputsDiscovered + | StreamStarted + | RecordingMetricsUpdated + | ReplayPrepared + | SessionStopped + | WorkerError +) diff --git a/src/quickreplay/recording/frame_converter.py b/src/quickreplay/recording/frame_converter.py new file mode 100644 index 0000000..66b4f24 --- /dev/null +++ b/src/quickreplay/recording/frame_converter.py @@ -0,0 +1,125 @@ +"""Conversion from domain frames to PyAV frames. + +This is the recording layer's boundary to PyAV. Domain models stay free of +PyAV types; the concrete payload contract lives here. + +Video payload contract + ``VideoFrame.data`` is a :class:`numpy.ndarray` of ``uint8`` whose shape + depends on ``VideoFrame.pixel_format``: + + * ``RGB24`` / ``BGR24`` -- ``(height, width, 3)`` + * ``RGBA`` / ``BGRA`` -- ``(height, width, 4)`` + * ``GRAY8`` -- ``(height, width)`` + * ``UYVY`` -- ``(height, width * 2)`` packed 4:2:2 (NDI) + + The packed ``UYVY`` payload is written straight into a PyAV ``uyvy422`` + frame and reformatted to ``yuv420p``, so no intermediate RGB conversion is + performed. + +Audio payload contract + ``AudioFrame.data`` is a :class:`numpy.ndarray` of ``float32`` with shape + ``(channels, samples)`` (planar). +""" + +import av +import numpy as np + +from quickreplay.input.models import VideoFrame +from quickreplay.recording.errors import SegmentFormatError + +# pixel_format -> (PyAV format name, components per pixel) +_VIDEO_FORMATS: dict[str, tuple[str, int]] = { + "RGB24": ("rgb24", 3), + "BGR24": ("bgr24", 3), + "RGBA": ("rgba", 4), + "BGRA": ("bgra", 4), + "GRAY8": ("gray", 1), +} + +_AUDIO_LAYOUTS = {1: "mono", 2: "stereo"} + +_UYVY_FORMAT = "uyvy422" + + +class FrameConverter: + """Convert domain frames into PyAV frames. + + Converters are cheap and may be created per segment. + """ + + def to_av_video(self, frame: VideoFrame) -> av.VideoFrame: + """Build a ``yuv420p`` PyAV frame from a domain video frame.""" + pixel_format = frame.pixel_format.upper() + data = frame.data + if not isinstance(data, np.ndarray): + raise SegmentFormatError("VideoFrame.data must be a numpy.ndarray") + if pixel_format == "UYVY": + return self._uyvy_to_av_video(frame, data) + entry = _VIDEO_FORMATS.get(pixel_format) + if entry is None: + raise SegmentFormatError( + f"unsupported pixel format {frame.pixel_format!r}; " + f"supported: {sorted([*_VIDEO_FORMATS, 'UYVY'])}" + ) + av_format, components = entry + expected = ( + (frame.height, frame.width) + if components == 1 + else (frame.height, frame.width, components) + ) + if data.shape != expected: + raise SegmentFormatError( + f"VideoFrame.data shape {data.shape} does not match {expected} " + f"for {frame.pixel_format}" + ) + if data.dtype != np.uint8: + raise SegmentFormatError(f"VideoFrame.data dtype must be uint8, got {data.dtype}") + av_frame = av.VideoFrame.from_ndarray(np.ascontiguousarray(data), format=av_format) + return av_frame.reformat(format="yuv420p") + + def _uyvy_to_av_video(self, frame: VideoFrame, data: np.ndarray) -> av.VideoFrame: + """Write a packed UYVY payload into a ``uyvy422`` frame and reformat it. + + PyAV cannot build packed YUV frames from a numpy array, so the payload + is copied into the frame's first plane directly. The result is + converted to ``yuv420p`` for the encoder without an RGB round trip. + """ + expected = (frame.height, frame.width * 2) + if data.shape != expected: + raise SegmentFormatError( + f"VideoFrame.data shape {data.shape} does not match {expected} for UYVY" + ) + if data.dtype != np.uint8: + raise SegmentFormatError(f"VideoFrame.data dtype must be uint8, got {data.dtype}") + av_frame = av.VideoFrame(frame.width, frame.height, format=_UYVY_FORMAT) + plane = av_frame.planes[0] + row_bytes = frame.width * 2 + if plane.line_size == row_bytes: + buffer = np.ascontiguousarray(data) + else: + # PyAV may align the line size beyond width * 2; pad each row. + buffer = np.zeros((frame.height, plane.line_size), dtype=np.uint8) + buffer[:, :row_bytes] = data + # PyAV's stub types ``update`` as ``bytes`` but accepts any buffer. + plane.update(buffer) # ty: ignore[invalid-argument-type] + return av_frame.reformat(format="yuv420p") + + def to_av_audio(self, data: np.ndarray, sample_rate: int, channels: int) -> av.AudioFrame: + """Build a planar float PyAV audio frame from raw samples.""" + layout = _AUDIO_LAYOUTS.get(channels) + if layout is None: + raise SegmentFormatError( + f"unsupported channel count {channels}; only mono/stereo are supported" + ) + if not isinstance(data, np.ndarray): + raise SegmentFormatError("audio data must be a numpy.ndarray") + if data.dtype != np.float32 or data.ndim != 2 or data.shape[0] != channels: + raise SegmentFormatError( + f"audio data must be float32 (channels, samples); got shape {data.shape} " + f"dtype {data.dtype}" + ) + av_frame = av.AudioFrame.from_ndarray( + np.ascontiguousarray(data), format="fltp", layout=layout + ) + av_frame.sample_rate = sample_rate + return av_frame diff --git a/src/quickreplay/recording/models.py b/src/quickreplay/recording/models.py new file mode 100644 index 0000000..42739ec --- /dev/null +++ b/src/quickreplay/recording/models.py @@ -0,0 +1,133 @@ +"""Recording domain models: segments, sessions, metrics and worker state.""" + +from dataclasses import dataclass +from enum import StrEnum +from pathlib import Path +from uuid import UUID + +from quickreplay.input.models import StreamInfo + + +@dataclass(frozen=True, slots=True) +class Segment: + """Metadata of one finalised segment file. + + ``duration_ns`` is derived from the session range rather than stored, so it + cannot drift from the start/end fields. + """ + + id: int + path: Path + + session_start_ns: int + session_end_ns: int + + video_frames: int + audio_samples: int + + def __post_init__(self) -> None: + if self.session_end_ns < self.session_start_ns: + raise ValueError( + "session_end_ns must be >= session_start_ns " + f"({self.session_end_ns} < {self.session_start_ns})" + ) + if self.video_frames < 0: + raise ValueError(f"video_frames must not be negative, got {self.video_frames}") + if self.audio_samples < 0: + raise ValueError(f"audio_samples must not be negative, got {self.audio_samples}") + + @property + def duration_ns(self) -> int: + """Segment duration in nanoseconds.""" + return self.session_end_ns - self.session_start_ns + + +@dataclass(frozen=True, slots=True) +class RecordingSession: + """One continuous recording session. + + Resuming recording after a replay creates a new session rather than + extending this one. The lifecycle itself is not implemented yet. + """ + + id: UUID + stream_info: StreamInfo + epoch_ns: int + directory: Path + + +@dataclass(frozen=True, slots=True) +class RecordingMetrics: + """Measured recording metrics, suitable for display. + + ``input_fps`` / ``recording_fps`` are measured values for the UI. They are + distinct from the declared stream FPS (which is a :class:`~fractions.Fraction` + in :class:`~quickreplay.input.models.StreamInfo`). + """ + + captured_video_frames: int + recorded_video_frames: int + + captured_audio_samples: int + recorded_audio_samples: int + + video_queue_drops: int + audio_queue_drops: int + + buffer_duration_ns: int + segment_count: int + + input_fps: float + recording_fps: float + + def __post_init__(self) -> None: + for name in ( + "captured_video_frames", + "recorded_video_frames", + "captured_audio_samples", + "recorded_audio_samples", + "video_queue_drops", + "audio_queue_drops", + "buffer_duration_ns", + "segment_count", + ): + if getattr(self, name) < 0: + raise ValueError(f"{name} must not be negative, got {getattr(self, name)}") + if self.input_fps < 0: + raise ValueError(f"input_fps must not be negative, got {self.input_fps}") + if self.recording_fps < 0: + raise ValueError(f"recording_fps must not be negative, got {self.recording_fps}") + + +class WorkerState(StrEnum): + """Internal state of the recorder worker process.""" + + IDLE = "idle" + STARTING = "starting" + RECORDING = "recording" + FREEZING = "freezing" + FROZEN = "frozen" + STOPPING = "stopping" + ERROR = "error" + SHUTTING_DOWN = "shutting_down" + + +class WorkerErrorCode(StrEnum): + """Machine-readable worker error codes.""" + + INPUT_NOT_FOUND = "input_not_found" + INPUT_OPEN_FAILED = "input_open_failed" + INPUT_DISCONNECTED = "input_disconnected" + + UNSUPPORTED_FORMAT = "unsupported_format" + + CAPTURE_FAILED = "capture_failed" + ENCODER_FAILED = "encoder_failed" + MUXER_FAILED = "muxer_failed" + + REPLAY_ASSET_FAILED = "replay_asset_failed" + + DISK_FULL = "disk_full" + FILE_IO_ERROR = "file_io_error" + + INTERNAL_ERROR = "internal_error" diff --git a/src/quickreplay/recording/ring_storage.py b/src/quickreplay/recording/ring_storage.py new file mode 100644 index 0000000..f74a247 --- /dev/null +++ b/src/quickreplay/recording/ring_storage.py @@ -0,0 +1,228 @@ +"""Time-bounded ring storage for finalized segments. + +:class:`RingStorage` owns the lifetime of finalized +:class:`~quickreplay.recording.models.Segment` files produced by the segment +recorder. It keeps segments in chronological order, deletes segments that fall +outside the configured buffer duration, and hands out snapshot leases that pin +segment files so a replay asset can be built without the files disappearing. + +Retention is **timeline based**: the cutoff is derived from the newest +segment's ``session_end_ns`` and the configured buffer duration. Whole +segments are kept or deleted; a segment is never partially trimmed. + +The storage is intended for a single-threaded owner (the future encoder side of +the worker) and uses no internal locks. +""" + +from collections import deque +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +from quickreplay.recording.errors import ( + RingStorageError, + SegmentDeleteError, + SegmentOrderError, +) +from quickreplay.recording.models import Segment + +DeleteFile = Callable[[Path], None] + + +def _default_delete_file(path: Path) -> None: + path.unlink() + + +@dataclass(slots=True) +class _RingEntry: + """Internal ring entry. Never exposed to callers.""" + + segment: Segment + pin_count: int = 0 + expired: bool = False + last_delete_error: OSError | None = None + + +class RingStorage: + """Chronological, time-bounded storage of finalized segments.""" + + def __init__( + self, + *, + buffer_duration_ns: int, + delete_file: DeleteFile | None = None, + ) -> None: + if buffer_duration_ns <= 0: + raise ValueError(f"buffer_duration_ns must be positive, got {buffer_duration_ns}") + self._buffer_duration_ns = buffer_duration_ns + self._delete_file: DeleteFile = delete_file or _default_delete_file + self._entries: deque[_RingEntry] = deque() + + # -- queries ----------------------------------------------------------- + @property + def buffer_duration_ns(self) -> int: + """Configured retention window.""" + return self._buffer_duration_ns + + @property + def segments(self) -> tuple[Segment, ...]: + """Active (non-expired) segments, oldest first.""" + return tuple(entry.segment for entry in self._entries if not entry.expired) + + @property + def segment_count(self) -> int: + """Number of active segments.""" + return sum(1 for entry in self._entries if not entry.expired) + + @property + def duration_ns(self) -> int: + """Timeline span of the active segments (0 when empty).""" + active = [entry.segment for entry in self._entries if not entry.expired] + if not active: + return 0 + return active[-1].session_end_ns - active[0].session_start_ns + + # -- mutation ---------------------------------------------------------- + def add(self, segment: Segment) -> None: + """Register a finalized segment and apply retention. + + The new segment is always registered. If retention cannot delete an + expired file, a :class:`SegmentDeleteError` is raised after the segment + has been registered, and the failed entry is kept so that a later + operation can retry. + """ + self._validate(segment) + if not segment.path.exists(): + raise RingStorageError(f"segment file does not exist: {segment.path}") + self._entries.append(_RingEntry(segment=segment)) + self._apply_retention() + failed = self._retry_pending_deletions() + if failed: + raise SegmentDeleteError(tuple(failed)) + + def snapshot(self) -> RingSnapshotLease: + """Freeze the currently active segments and pin them. + + Expired segments are never included. An empty snapshot is allowed. + """ + entries = tuple(entry for entry in self._entries if not entry.expired) + for entry in entries: + entry.pin_count += 1 + return RingSnapshotLease(self, entries) + + def clear(self) -> None: + """Expire and delete every segment, respecting active leases. + + Pinned segments are not deleted until their lease is released. If any + deletion fails, a :class:`SegmentDeleteError` is raised and the + affected entry is kept for a later retry. + """ + for entry in self._entries: + entry.expired = True + failed = self._retry_pending_deletions() + if failed: + raise SegmentDeleteError(tuple(failed)) + + # -- internals --------------------------------------------------------- + def _validate(self, segment: Segment) -> None: + if not self._entries: + return + previous = self._entries[-1].segment + if segment.id <= previous.id: + raise SegmentOrderError( + f"segment id {segment.id} is not greater than the previous id {previous.id}" + ) + if segment.session_start_ns != previous.session_end_ns: + raise SegmentOrderError( + f"segment {segment.id} start {segment.session_start_ns} does not continue " + f"the previous end {previous.session_end_ns}" + ) + + def _apply_retention(self) -> None: + if not self._entries: + return + newest_end_ns = self._entries[-1].segment.session_end_ns + cutoff_ns = newest_end_ns - self._buffer_duration_ns + for entry in self._entries: + if entry.segment.session_end_ns <= cutoff_ns: + entry.expired = True + + def _retry_pending_deletions(self) -> list[Path]: + failed: list[Path] = [] + survivors: deque[_RingEntry] = deque() + for entry in self._entries: + if entry.expired and entry.pin_count == 0: + if self._delete_entry(entry): + continue + failed.append(entry.segment.path) + survivors.append(entry) + self._entries = survivors + return failed + + def _delete_entry(self, entry: _RingEntry) -> bool: + try: + self._delete_file(entry.segment.path) + except FileNotFoundError: + # Already gone: treat as a successful cleanup. + entry.last_delete_error = None + return True + except OSError as exc: + entry.last_delete_error = exc + return False + entry.last_delete_error = None + return True + + def _release_entries(self, entries: tuple[_RingEntry, ...]) -> None: + for entry in entries: + if entry.pin_count > 0: + entry.pin_count -= 1 + failed = self._retry_pending_deletions() + if failed: + raise SegmentDeleteError(tuple(failed)) + + +class RingSnapshotLease: + """A lease that pins a fixed set of segments while replay is prepared. + + ``segments`` stays readable after :meth:`release`, but the underlying files + may already be deleted, so post-release file access is not guaranteed. + """ + + def __init__(self, storage: RingStorage, entries: tuple[_RingEntry, ...]) -> None: + self._storage = storage + self._entries = entries + self._released = False + + @property + def segments(self) -> tuple[Segment, ...]: + """The pinned segments (immutable).""" + return tuple(entry.segment for entry in self._entries) + + @property + def released(self) -> bool: + """Whether the lease has been released.""" + return self._released + + def release(self) -> None: + """Release the pins. Idempotent; deletion failures are raised.""" + if self._released: + return + self._released = True + self._storage._release_entries(self._entries) + + def __enter__(self) -> RingSnapshotLease: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: object, + ) -> bool: + try: + self.release() + except SegmentDeleteError: + # Do not mask an exception already propagating out of the with-block. + if exc_type is None: + raise + return False diff --git a/src/quickreplay/recording/segment_recorder.py b/src/quickreplay/recording/segment_recorder.py new file mode 100644 index 0000000..24e4fb3 --- /dev/null +++ b/src/quickreplay/recording/segment_recorder.py @@ -0,0 +1,358 @@ +"""Rotation and lifecycle for short MKV segments. + +:class:`SegmentRecorder` consumes domain :class:`~quickreplay.input.models.VideoFrame` +/ :class:`~quickreplay.input.models.AudioFrame` values in a single-threaded +owner and produces finalised :class:`~quickreplay.recording.models.Segment` +files. It does not own a thread; it is meant to run on the encoder side of a +future capture queue. + +Segment boundaries are driven by **video timestamps**: the first video frame +whose session time reaches ``segment_start + segment_duration`` starts the next +segment. Audio never drives rotation; audio frames that straddle a boundary +are split at sample precision once the boundary is known, and a small amount of +audio ahead of the video boundary is held pending. +""" + +from collections.abc import Callable +from fractions import Fraction +from pathlib import Path + +import numpy as np + +from quickreplay.input.models import AudioFrame, StreamInfo, VideoFrame +from quickreplay.recording.errors import ( + SegmentEncodingError, + SegmentFormatError, + SegmentRecorderError, + SegmentTimestampError, +) +from quickreplay.recording.models import RecordingSession, Segment +from quickreplay.recording.segment_writer import SegmentWriter, SegmentWriterLike +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction + +DEFAULT_SEGMENT_DURATION_NS = 2_000_000_000 +"""Default segment duration: two seconds.""" + +WriterFactory = Callable[[int, Path, StreamInfo], SegmentWriterLike] + + +def _default_writer_factory( + segment_id: int, directory: Path, stream_info: StreamInfo +) -> SegmentWriterLike: + return SegmentWriter(segment_id, directory, stream_info) + + +class SegmentRecorder: + """Split a continuous frame stream into independently decodable segments.""" + + def __init__( + self, + *, + segment_duration_ns: int = DEFAULT_SEGMENT_DURATION_NS, + writer_factory: WriterFactory | None = None, + ) -> None: + if segment_duration_ns <= 0: + raise ValueError(f"segment_duration_ns must be positive, got {segment_duration_ns}") + self._segment_duration_ns = segment_duration_ns + self._writer_factory: WriterFactory = writer_factory or _default_writer_factory + + self._session: RecordingSession | None = None + self._stream_info: StreamInfo | None = None + self._epoch_ns: int | None = None + self._fps: Fraction | None = None + self._sample_rate: int | None = None + self._channels: int | None = None + + self._current_writer: SegmentWriterLike | None = None + self._current_id = 0 + self._segment_start_ns: int | None = None + self._segment_video_frames = 0 + self._segment_audio_samples = 0 + self._last_video_pts = -1 + + self._last_video_session_ns: int | None = None + self._last_audio_session_ns: int | None = None + # End of the accepted audio sample timeline for the whole session. + # This intentionally survives segment rotation. + self._accepted_audio_end_sample: int | None = None + # Buffered audio chunks: (start_sample, float32 planar data). + self._audio_chunks: list[tuple[int, np.ndarray]] = [] + + self._finished = False + self._closed = False + + # -- lifecycle --------------------------------------------------------- + def start(self, session: RecordingSession) -> None: + """Begin a recording session.""" + if self._session is not None: + raise SegmentRecorderError("recorder has already been started") + if self._closed: + raise SegmentRecorderError("recorder has been closed") + self._session = session + self._stream_info = session.stream_info + self._epoch_ns = session.epoch_ns + self._fps = session.stream_info.video.fps + audio = session.stream_info.audio + if audio is not None: + self._sample_rate = audio.sample_rate + self._channels = audio.channels + self._accepted_audio_end_sample = None + + def push_video(self, frame: VideoFrame) -> tuple[Segment, ...]: + """Feed a video frame, returning any segment finalized by rotation.""" + self._require_active() + epoch_ns = self._epoch_ns + assert epoch_ns is not None + assert self._stream_info is not None + self._validate_video_format(frame) + self._validate_epoch(frame.timestamp_ns) + session_ns = frame.timestamp_ns - epoch_ns + + if self._last_video_session_ns is not None and session_ns < self._last_video_session_ns: + raise SegmentTimestampError( + f"video timestamp regressed: {session_ns} < {self._last_video_session_ns}" + ) + + finalized: list[Segment] = [] + if self._current_writer is None: + self._begin_segment(session_ns, drop_audio_before_ns=session_ns) + else: + assert self._segment_start_ns is not None + threshold_ns = self._segment_start_ns + self._segment_duration_ns + if session_ns >= threshold_ns: + finalized.append(self._end_segment(session_ns)) + self._begin_segment(session_ns, drop_audio_before_ns=None) + + assert self._segment_start_ns is not None + position = self._video_position(session_ns) + pts = position - self._video_position(self._segment_start_ns) + if pts > self._last_video_pts: + writer = self._current_writer + assert writer is not None + writer.write_video(frame, pts) + self._segment_video_frames += 1 + self._last_video_pts = pts + # A duplicate CFR slot (equal position) is dropped to keep PTS + # strictly increasing. + + self._last_video_session_ns = session_ns + return tuple(finalized) + + def push_audio(self, frame: AudioFrame) -> int: + """Feed an audio frame and return the number of accepted samples.""" + self._require_active() + epoch_ns = self._epoch_ns + assert epoch_ns is not None + assert self._stream_info is not None + if self._stream_info.audio is None: + raise SegmentFormatError("the recording session has no audio stream") + self._validate_audio_format(frame) + self._validate_epoch(frame.timestamp_ns) + + session_ns = frame.timestamp_ns - epoch_ns + if self._last_audio_session_ns is not None and session_ns < self._last_audio_session_ns: + raise SegmentTimestampError( + f"audio timestamp regressed: {session_ns} < {self._last_audio_session_ns}" + ) + self._last_audio_session_ns = session_ns + + data = frame.data + if not isinstance(data, np.ndarray): + raise SegmentFormatError("AudioFrame.data must be a numpy.ndarray") + if data.ndim != 2 or data.shape[0] != self._channels or data.shape[1] != frame.sample_count: + raise SegmentFormatError( + f"AudioFrame.data shape {data.shape} does not match " + f"({self._channels}, {frame.sample_count})" + ) + start_sample = self._sample_position(session_ns) + end_sample = start_sample + frame.sample_count + accepted_start = start_sample + accepted_data = np.ascontiguousarray(data, dtype=np.float32) + accepted_end = self._accepted_audio_end_sample + if accepted_end is not None: + if end_sample <= accepted_end: + return 0 + if start_sample < accepted_end: + overlap = accepted_end - start_sample + accepted_start = accepted_end + accepted_data = accepted_data[:, overlap:] + + accepted_samples = int(accepted_data.shape[1]) + if accepted_samples == 0: + return 0 + self._accepted_audio_end_sample = accepted_start + accepted_samples + self._audio_chunks.append((accepted_start, accepted_data)) + + if self._current_writer is not None: + # Audio before the current last video frame is definitely part of + # this segment. Audio after it is held until the next video frame + # fixes the boundary (or until finish trims it). + assert self._last_video_session_ns is not None + self._flush_audio_until(self._last_video_session_ns) + return accepted_samples + + def finish(self) -> Segment | None: + """Finalize the last segment and return it (or ``None`` if no video).""" + self._require_started() + if self._finished: + return None + self._finished = True + + if self._current_writer is None or self._segment_video_frames == 0: + if self._current_writer is not None: + self._current_writer.abort() + self._current_writer = None + self._audio_chunks.clear() + return None + + assert self._last_video_session_ns is not None + fps = self._fps + assert fps is not None + frame_duration_ns = Fraction(NANOSECONDS_PER_SECOND, 1) / fps + final_end_ns = round_fraction(Fraction(self._last_video_session_ns, 1) + frame_duration_ns) + segment = self._end_segment(final_end_ns) + self._audio_chunks.clear() # trim trailing audio beyond the final video + return segment + + def close(self) -> None: + """Abort any unfinished segment. Safe to call multiple times.""" + if self._closed: + return + self._closed = True + if self._current_writer is not None: + self._current_writer.abort() + self._current_writer = None + self._audio_chunks.clear() + + # -- segment lifecycle ------------------------------------------------- + def _begin_segment(self, start_ns: int, *, drop_audio_before_ns: int | None) -> None: + if drop_audio_before_ns is not None: + self._drop_audio_before(drop_audio_before_ns) + assert self._session is not None and self._stream_info is not None + self._current_writer = self._writer_factory( + self._current_id, self._session.directory, self._stream_info + ) + self._segment_start_ns = start_ns + self._segment_video_frames = 0 + self._segment_audio_samples = 0 + self._last_video_pts = -1 + + def _end_segment(self, boundary_ns: int) -> Segment: + assert self._current_writer is not None and self._segment_start_ns is not None + self._flush_audio_until(boundary_ns) + writer = self._current_writer + try: + path = writer.finalize() + except SegmentRecorderError: + writer.abort() + raise + except Exception as exc: # noqa: BLE001 - wrap unexpected writer failures + writer.abort() + raise SegmentEncodingError(f"segment finalize failed: {exc}") from exc + + segment = Segment( + id=self._current_id, + path=path, + session_start_ns=self._segment_start_ns, + session_end_ns=boundary_ns, + video_frames=self._segment_video_frames, + audio_samples=self._segment_audio_samples, + ) + self._current_id += 1 + self._current_writer = None + self._segment_start_ns = None + self._segment_video_frames = 0 + self._segment_audio_samples = 0 + return segment + + # -- audio routing ----------------------------------------------------- + def _drop_audio_before(self, limit_ns: int) -> None: + if self._sample_rate is None: + return + limit_sample = self._sample_position(limit_ns) + while self._audio_chunks: + start_sample, data = self._audio_chunks[0] + length = int(data.shape[1]) + if start_sample >= limit_sample: + break + if start_sample + length <= limit_sample: + self._audio_chunks.pop(0) + else: + take = limit_sample - start_sample + self._audio_chunks[0] = (limit_sample, data[:, take:]) + break + + def _flush_audio_until(self, limit_ns: int) -> None: + if self._current_writer is None or self._sample_rate is None: + return + limit_sample = self._sample_position(limit_ns) + while self._audio_chunks: + start_sample, data = self._audio_chunks[0] + length = int(data.shape[1]) + if start_sample >= limit_sample: + break + if start_sample + length <= limit_sample: + self._write_audio_chunk(start_sample, data) + self._audio_chunks.pop(0) + else: + take = limit_sample - start_sample + self._write_audio_chunk(start_sample, data[:, :take]) + self._audio_chunks[0] = (limit_sample, data[:, take:]) + break + + def _write_audio_chunk(self, start_sample: int, data: np.ndarray) -> None: + if self._current_writer is None or data.shape[1] == 0: + return + assert self._segment_start_ns is not None + pts = start_sample - self._sample_position(self._segment_start_ns) + if pts < 0: + raise SegmentTimestampError( + "audio sample precedes the current segment start; " + "out-of-order audio is not supported" + ) + self._current_writer.write_audio(np.ascontiguousarray(data, dtype=np.float32), pts) + self._segment_audio_samples += int(data.shape[1]) + + # -- validation / math ------------------------------------------------- + def _require_started(self) -> None: + if self._session is None: + raise SegmentRecorderError("recorder has not been started") + + def _require_active(self) -> None: + self._require_started() + if self._closed: + raise SegmentRecorderError("recorder has been closed") + if self._finished: + raise SegmentRecorderError("recorder has been finished") + + def _validate_epoch(self, timestamp_ns: int) -> None: + assert self._epoch_ns is not None + if timestamp_ns < self._epoch_ns: + raise SegmentTimestampError( + f"frame timestamp {timestamp_ns} precedes session epoch {self._epoch_ns}" + ) + + def _validate_video_format(self, frame: VideoFrame) -> None: + assert self._stream_info is not None + expected = self._stream_info.video + actual = (frame.width, frame.height, frame.fps, frame.pixel_format.upper()) + wanted = (expected.width, expected.height, expected.fps, expected.pixel_format.upper()) + if actual != wanted: + raise SegmentFormatError(f"video frame format {actual} does not match session {wanted}") + + def _validate_audio_format(self, frame: AudioFrame) -> None: + assert self._stream_info is not None and self._stream_info.audio is not None + expected = self._stream_info.audio + if (frame.sample_rate, frame.channels) != (expected.sample_rate, expected.channels): + raise SegmentFormatError( + f"audio frame format {(frame.sample_rate, frame.channels)} does not match " + f"session {(expected.sample_rate, expected.channels)}" + ) + + def _video_position(self, session_ns: int) -> int: + assert self._fps is not None + return round_fraction(Fraction(session_ns, NANOSECONDS_PER_SECOND) * self._fps) + + def _sample_position(self, session_ns: int) -> int: + assert self._sample_rate is not None + return round_fraction(Fraction(session_ns, NANOSECONDS_PER_SECOND) * self._sample_rate) diff --git a/src/quickreplay/recording/segment_writer.py b/src/quickreplay/recording/segment_writer.py new file mode 100644 index 0000000..e0491ef --- /dev/null +++ b/src/quickreplay/recording/segment_writer.py @@ -0,0 +1,213 @@ +"""Encode and mux a single MKV segment with PyAV. + +A :class:`SegmentWriter` owns exactly one segment (one container and a fresh +encoder per stream). Encoders and containers are never reused across +segments, which keeps every segment independently decodable. + +The writer publishes its output atomically: it encodes into +``segment_000000.tmp.mkv`` and only replaces it with ``segment_000000.mkv`` +after the container has closed cleanly. A failed writer removes its temporary +file and never exposes a partial segment. +""" + +import os +from fractions import Fraction +from pathlib import Path +from typing import Protocol + +import av +import numpy as np + +from quickreplay.input.models import StreamInfo, VideoFrame +from quickreplay.recording.errors import ( + SegmentEncodingError, + SegmentMuxError, + SegmentRecorderError, +) +from quickreplay.recording.frame_converter import FrameConverter + + +class SegmentWriterLike(Protocol): + """Protocol implemented by :class:`SegmentWriter` (and test doubles).""" + + def write_video(self, frame: VideoFrame, pts: int) -> None: ... + + def write_audio(self, data: np.ndarray, pts: int) -> None: ... + + def finalize(self) -> Path: ... + + def abort(self) -> None: ... + + +class SegmentWriter: + """Write one segment file.""" + + def __init__( + self, + segment_id: int, + directory: Path, + stream_info: StreamInfo, + *, + converter: FrameConverter | None = None, + ) -> None: + self.segment_id = segment_id + self.directory = Path(directory) + self.stream_info = stream_info + self._converter = converter or FrameConverter() + + self._final_path = self.directory / f"segment_{segment_id:06d}.mkv" + self._tmp_path = self.directory / f"segment_{segment_id:06d}.tmp.mkv" + + self._finalized = False + self._aborted = False + self._first_video = True + + video = stream_info.video + self._video_time_base = Fraction(video.fps.denominator, video.fps.numerator) + self._audio_time_base: Fraction | None = None + + self._container = av.open(str(self._tmp_path), mode="w", format="matroska") + + video_stream = self._container.add_stream("libx264", rate=video.fps) + video_stream.width = video.width + video_stream.height = video.height + video_stream.pix_fmt = "yuv420p" + video_stream.time_base = self._video_time_base + gop = max(1, round(float(video.fps) * 2)) + video_stream.options = { + "preset": "veryfast", + "tune": "zerolatency", + "crf": "20", + "g": str(gop), + "keyint_min": "1", + "sc_threshold": "0", + "forced-idr": "1", + } + self._video_stream = video_stream + + audio = stream_info.audio + self._audio_stream: av.AudioStream | None = None + if audio is not None: + if audio.channels not in (1, 2): + self._abort_files() + raise SegmentEncodingError( + f"unsupported channel count {audio.channels}; only mono/stereo are supported" + ) + audio_stream = self._container.add_stream("pcm_f32le", rate=audio.sample_rate) + audio_stream.layout = "mono" if audio.channels == 1 else "stereo" + audio_stream.time_base = Fraction(1, audio.sample_rate) + self._audio_time_base = Fraction(1, audio.sample_rate) + self._audio_stream = audio_stream + + # -- properties -------------------------------------------------------- + @property + def tmp_path(self) -> Path: + return self._tmp_path + + @property + def final_path(self) -> Path: + return self._final_path + + # -- data -------------------------------------------------------------- + def write_video(self, frame: VideoFrame, pts: int) -> None: + if self._finalized or self._aborted: + raise SegmentEncodingError("writer is closed") + try: + av_frame = self._converter.to_av_video(frame) + av_frame.pts = pts + av_frame.time_base = self._video_time_base + if self._first_video: + # Force the first frame of the segment to be an IDR keyframe. + av_frame.pict_type = av.video.frame.PictureType.I + self._first_video = False + for packet in self._video_stream.encode(av_frame): + self._container.mux(packet) + except SegmentRecorderError: + self.abort() + raise + except Exception as exc: # noqa: BLE001 - wrap any PyAV failure + self.abort() + raise SegmentEncodingError(f"video encode failed: {exc}") from exc + + def write_audio(self, data: np.ndarray, pts: int) -> None: + if self._finalized or self._aborted: + raise SegmentEncodingError("writer is closed") + if self._audio_stream is None: + raise SegmentEncodingError("segment has no audio stream") + audio = self.stream_info.audio + assert audio is not None + sample_count = int(data.shape[1]) + time_base = self._audio_time_base + try: + av_frame = self._converter.to_av_audio(data, audio.sample_rate, audio.channels) + av_frame.pts = pts + av_frame.time_base = time_base + packets = list(self._audio_stream.encode(av_frame)) + except SegmentRecorderError: + self.abort() + raise + except Exception as exc: # noqa: BLE001 - wrap any PyAV failure + self.abort() + raise SegmentEncodingError( + "audio encode failed " + f"(segment_id={self.segment_id}, pts={pts}, sample_count={sample_count}, " + f"time_base={time_base}): {exc}" + ) from exc + try: + for packet in packets: + self._container.mux(packet) + except SegmentRecorderError: + self.abort() + raise + except Exception as exc: # noqa: BLE001 - wrap any PyAV failure + self.abort() + raise SegmentEncodingError( + "audio mux failed " + f"(segment_id={self.segment_id}, pts={pts}, sample_count={sample_count}, " + f"time_base={time_base}, packet_pts={packet.pts}, packet_dts={packet.dts}, " + f"packet_duration={packet.duration}, packet_time_base={packet.time_base}): {exc}" + ) from exc + + # -- lifecycle --------------------------------------------------------- + def finalize(self) -> Path: + """Flush, close and atomically publish the segment file.""" + if self._finalized: + return self._final_path + if self._aborted: + raise SegmentMuxError("writer was aborted") + try: + for packet in self._video_stream.encode(None): + self._container.mux(packet) + if self._audio_stream is not None: + for packet in self._audio_stream.encode(None): + self._container.mux(packet) + self._container.close() + except Exception as exc: # noqa: BLE001 - wrap any PyAV failure + self._abort_files() + raise SegmentMuxError(f"segment finalize failed: {exc}") from exc + + try: + os.replace(self._tmp_path, self._final_path) + except OSError as exc: + self._abort_files() + raise SegmentMuxError(f"segment publish failed: {exc}") from exc + self._finalized = True + return self._final_path + + def abort(self) -> None: + """Best-effort cleanup of an unfinished segment.""" + if self._finalized or self._aborted: + return + self._aborted = True + self._abort_files() + + def _abort_files(self) -> None: + try: + self._container.close() + except Exception: # noqa: BLE001 - best effort + pass + try: + if self._tmp_path.exists(): + self._tmp_path.unlink() + except OSError: + pass diff --git a/src/quickreplay/replay/__init__.py b/src/quickreplay/replay/__init__.py new file mode 100644 index 0000000..29c3635 --- /dev/null +++ b/src/quickreplay/replay/__init__.py @@ -0,0 +1,5 @@ +"""Replay domain models: snapshots, assets and set-point frame math. + +The replay asset is a single stream-copied MKV. No replay player or mpv +integration lives here. +""" diff --git a/src/quickreplay/replay/asset_builder.py b/src/quickreplay/replay/asset_builder.py new file mode 100644 index 0000000..36ec8ef --- /dev/null +++ b/src/quickreplay/replay/asset_builder.py @@ -0,0 +1,96 @@ +"""Build a single-file replay asset from a frozen replay snapshot. + +:class:`ReplayAssetBuilder` stream-copies the finalized segments of a +:class:`~quickreplay.replay.models.ReplaySnapshot` into one MKV. It does not +decode, encode or touch the source segment files, and it does not own ring +storage: the caller keeps a snapshot lease alive while :meth:`build` runs. + +The output is published atomically. The remux writes ``replay.tmp.mkv`` and a +successful build replaces ``replay.mkv`` with it via :func:`os.replace`, so an +existing completed asset is never overwritten with an incomplete one. +""" + +import os +from pathlib import Path + +from quickreplay.recording.models import Segment +from quickreplay.replay.errors import ( + EmptyReplaySnapshotError, + ReplaySegmentError, +) +from quickreplay.replay.models import ReplayAsset, ReplaySnapshot +from quickreplay.replay.remux import Remux, remux_segments, validate_segment_layouts + +REPLAY_FILENAME = "replay.mkv" +"""File name of a completed replay asset.""" + +REPLAY_TMP_FILENAME = "replay.tmp.mkv" +"""Temporary file name used while a replay asset is being built.""" + + +class ReplayAssetBuilder: + """Turn a :class:`ReplaySnapshot` into a stream-copied ``replay.mkv``.""" + + def __init__(self, *, remux: Remux | None = None) -> None: + self._remux: Remux = remux or remux_segments + + def build(self, snapshot: ReplaySnapshot, output_directory: Path) -> ReplayAsset: + """Build the replay asset in *output_directory* and return its metadata. + + The snapshot's segments are only read; they are never modified or + deleted. On failure no partial ``replay.mkv`` is published and any + temporary file is removed. + """ + segments = snapshot.segments + _validate_snapshot(segments) + validate_segment_layouts(segments) + + output_directory = Path(output_directory) + output_directory.mkdir(parents=True, exist_ok=True) + final_path = output_directory / REPLAY_FILENAME + tmp_path = output_directory / REPLAY_TMP_FILENAME + + try: + self._remux(segments, tmp_path) + os.replace(tmp_path, final_path) + except BaseException: + _remove_quietly(tmp_path) + raise + + duration_ns = segments[-1].session_end_ns - segments[0].session_start_ns + return ReplayAsset( + path=final_path, + duration_ns=duration_ns, + fps=snapshot.stream_info.video.fps, + ) + + +def _validate_snapshot(segments: tuple[Segment, ...]) -> None: + if not segments: + raise EmptyReplaySnapshotError("replay snapshot contains no segments") + previous: Segment | None = None + for segment in segments: + if segment.duration_ns < 0: + raise ReplaySegmentError(f"segment {segment.id} has a negative duration") + if not segment.path.exists(): + raise ReplaySegmentError(f"segment file does not exist: {segment.path}") + if previous is not None: + if segment.id <= previous.id: + raise ReplaySegmentError( + f"segment id {segment.id} is not greater than the previous id {previous.id}" + ) + if segment.session_start_ns != previous.session_end_ns: + raise ReplaySegmentError( + f"segment {segment.id} start {segment.session_start_ns} does not continue " + f"the previous end {previous.session_end_ns}" + ) + previous = segment + + +def _remove_quietly(path: Path) -> None: + try: + path.unlink() + except FileNotFoundError: + pass + except OSError: + pass diff --git a/src/quickreplay/replay/controller.py b/src/quickreplay/replay/controller.py new file mode 100644 index 0000000..d481012 --- /dev/null +++ b/src/quickreplay/replay/controller.py @@ -0,0 +1,315 @@ +"""Replay playback controller backed by an external mpv process. + +The controller owns the mpv process lifecycle and the JSON IPC channel. The +playback position always comes from mpv's ``time-pos`` property; the controller +keeps no frame counter and no playback clock of its own. It does not touch the +recorder worker, the ring buffer or the replay asset lifecycle. +""" + +import time +from collections.abc import Callable +from dataclasses import dataclass +from decimal import Decimal +from fractions import Fraction +from pathlib import Path + +from quickreplay.replay.errors import ( + MpvExecutableNotFoundError, + MpvIpcError, + MpvProcessExitedError, + MpvPropertyUnavailableError, + MpvStartupError, + ReplayControllerError, +) +from quickreplay.replay.models import ReplayAsset, SetPoint, frame_difference +from quickreplay.replay.mpv_ipc import ( + MpvIpcClient, + MpvIpcTransport, + default_transport_factory, + make_ipc_endpoint, + seconds_to_ns, +) +from quickreplay.replay.mpv_process import ( + MpvProcess, + ProcessFactory, + mpv_launch_arguments, + spawn_mpv_process, +) + +_NANOSECONDS = Decimal(1_000_000_000) + + +@dataclass(frozen=True, slots=True) +class ReplayControllerSettings: + """Runtime settings for the replay controller (not persisted).""" + + mpv_executable: Path | str = "mpv" + startup_timeout_seconds: float = 5.0 + command_timeout_seconds: float = 2.0 + shutdown_timeout_seconds: float = 2.0 + connect_retry_interval_seconds: float = 0.05 + + +def frame_offset_seconds(frames: int, fps: Fraction) -> Fraction: + """Exact playback offset for *frames* at *fps* (never a float).""" + return Fraction(frames, 1) / fps + + +def fraction_to_seconds_text(value: Fraction) -> str: + """Render an exact fraction as a decimal string for the IPC boundary.""" + return format(Decimal(value.numerator) / Decimal(value.denominator), "f") + + +class ReplayController: + """Control one replay asset through an external mpv process.""" + + def __init__( + self, + settings: ReplayControllerSettings, + *, + process_factory: ProcessFactory = spawn_mpv_process, + transport_factory: Callable[[], MpvIpcTransport] = default_transport_factory, + sleep: Callable[[float], None] = time.sleep, + ) -> None: + self._settings = settings + self._process_factory = process_factory + self._transport_factory = transport_factory + self._sleep = sleep + + self._asset: ReplayAsset | None = None + self._process: MpvProcess | None = None + self._ipc: MpvIpcClient | None = None + self._endpoint: str | None = None + self._cleanup_path: str | None = None + + # -- lifecycle --------------------------------------------------------- + def open(self, asset: ReplayAsset) -> None: + """Start mpv for *asset* and leave the replay paused at the start.""" + if self._asset is not None: + raise ReplayControllerError("a replay is already open") + self._validate_asset(asset) + endpoint, cleanup_path = make_ipc_endpoint() + self._endpoint = endpoint + self._cleanup_path = cleanup_path + try: + arguments = mpv_launch_arguments(self._settings.mpv_executable, endpoint, asset.path) + self._process = self._spawn_process(arguments) + transport = self._connect_with_retry(endpoint) + self._ipc = MpvIpcClient( + transport, + process=self._process, + command_timeout_seconds=self._settings.command_timeout_seconds, + ) + self._wait_until_loaded() + self._ipc.set_property("pause", True) + self._asset = asset + except BaseException: + self._cleanup() + raise + + def close(self) -> None: + """Quit mpv and release every resource. Safe to call repeatedly.""" + if self._asset is None and self._process is None: + return + try: + if self._ipc is not None: + try: + self._ipc.command("quit", wait=False) + except Exception: # noqa: BLE001 - best effort quit + pass + self._shutdown_process() + finally: + self._cleanup() + + @property + def asset(self) -> ReplayAsset | None: + return self._asset + + @property + def is_open(self) -> bool: + return self._asset is not None + + def is_alive(self) -> bool: + """Whether the mpv process is still running (``False`` when closed).""" + if self._asset is None or self._process is None: + return False + return self._process.poll() is None + + def check_alive(self) -> None: + """Raise :class:`MpvProcessExitedError` if mpv has exited.""" + if self._asset is None or self._process is None: + return + if self._process.poll() is not None: + raise MpvProcessExitedError("the mpv process has exited") + + # -- playback control -------------------------------------------------- + def play(self) -> None: + self._require_open().set_property("pause", False) + + def pause(self) -> None: + self._require_open().set_property("pause", True) + + def is_paused(self) -> bool: + data = self._require_open().get_property("pause") + if data is None: + raise MpvPropertyUnavailableError("mpv pause is not available") + return bool(data) + + def step_forward(self) -> None: + self._require_open().command("frame-step") + + def step_backward(self) -> None: + self._require_open().command("frame-back-step") + + def seek_frames(self, frames: int) -> None: + """Move *frames* forward (positive) or backward (negative).""" + if frames == 0: + return + if frames == 1: + self.step_forward() + return + if frames == -1: + self.step_backward() + return + asset = self._asset_or_raise() + offset = frame_offset_seconds(frames, asset.fps) + self._require_open().command("seek", fraction_to_seconds_text(offset), "relative+exact") + + def seek_absolute_ns(self, position_ns: int) -> None: + """Seek to an absolute position, clamped to the asset timeline.""" + asset = self._asset_or_raise() + clamped = min(max(position_ns, 0), asset.duration_ns) + seconds = format(Decimal(clamped) / _NANOSECONDS, "f") + self._require_open().command("seek", seconds, "absolute+exact") + + # -- position ---------------------------------------------------------- + def position_ns(self) -> int: + data = self._require_open().get_property("time-pos") + if data is None: + raise MpvPropertyUnavailableError("mpv time-pos is not available") + return seconds_to_ns(data) + + def set_point(self) -> SetPoint: + return SetPoint(position_ns=self.position_ns()) + + def time_difference_ns(self, point: SetPoint) -> int: + return self.position_ns() - point.position_ns + + def frame_difference(self, point: SetPoint) -> int: + asset = self._asset_or_raise() + return frame_difference( + current_position_ns=self.position_ns(), + origin_position_ns=point.position_ns, + fps=asset.fps, + ) + + # -- internals --------------------------------------------------------- + def _validate_asset(self, asset: ReplayAsset) -> None: + if not asset.path.exists(): + raise ReplayControllerError(f"the replay asset does not exist: {asset.path}") + if asset.fps <= 0: + raise ReplayControllerError(f"the replay asset has an invalid fps: {asset.fps}") + if asset.duration_ns < 0: + raise ReplayControllerError( + f"the replay asset has a negative duration: {asset.duration_ns}" + ) + + def _spawn_process(self, arguments: list[str]) -> MpvProcess: + try: + return self._process_factory(arguments) + except FileNotFoundError as exc: + raise MpvExecutableNotFoundError( + f"the mpv executable was not found: {arguments[0]!r}" + ) from exc + + def _connect_with_retry(self, endpoint: str) -> MpvIpcTransport: + process = self._process + deadline = time.monotonic() + self._settings.startup_timeout_seconds + last_error: Exception | None = None + while True: + if process is not None and process.poll() is not None: + raise MpvStartupError("mpv exited before the IPC endpoint became available") + transport = self._transport_factory() + try: + transport.connect(endpoint) + return transport + except (OSError, MpvIpcError) as exc: + last_error = exc + transport.close() + if time.monotonic() >= deadline: + raise MpvStartupError( + f"timed out waiting for the mpv IPC endpoint: {last_error}" + ) from last_error + self._sleep(self._settings.connect_retry_interval_seconds) + + def _wait_until_loaded(self) -> None: + ipc = self._ipc + process = self._process + if ipc is None: # pragma: no cover - defensive + raise MpvStartupError("the mpv IPC channel is not connected") + deadline = time.monotonic() + self._settings.startup_timeout_seconds + while True: + if ipc.get_property("duration") is not None: + return + if process is not None and process.poll() is not None: + raise MpvStartupError("mpv exited before the replay file was loaded") + if time.monotonic() >= deadline: + raise MpvStartupError("timed out waiting for the replay file to load") + self._sleep(self._settings.connect_retry_interval_seconds) + + def _shutdown_process(self) -> None: + process = self._process + if process is None: + return + timeout = self._settings.shutdown_timeout_seconds + if process.poll() is not None: + return + if process.wait(timeout=timeout) is not None: + return + process.terminate() + if process.wait(timeout=timeout) is not None: + return + process.kill() + process.wait(timeout=timeout) + + def _cleanup(self) -> None: + if self._ipc is not None: + try: + self._ipc.close() + except Exception: # noqa: BLE001 - best effort + pass + self._ipc = None + process = self._process + if process is not None: + try: + if process.poll() is None: + process.terminate() + process.wait(timeout=self._settings.shutdown_timeout_seconds) + except Exception: # noqa: BLE001 - best effort + pass + self._process = None + self._remove_endpoint() + self._asset = None + + def _remove_endpoint(self) -> None: + path = self._cleanup_path + self._cleanup_path = None + self._endpoint = None + if path is not None: + try: + Path(path).unlink() + except OSError: + pass + + def _require_open(self) -> MpvIpcClient: + if self._asset is None or self._ipc is None: + raise ReplayControllerError("no replay is open") + process = self._process + if process is not None and process.poll() is not None: + raise MpvProcessExitedError("the mpv process has exited") + return self._ipc + + def _asset_or_raise(self) -> ReplayAsset: + if self._asset is None: + raise ReplayControllerError("no replay is open") + return self._asset diff --git a/src/quickreplay/replay/errors.py b/src/quickreplay/replay/errors.py new file mode 100644 index 0000000..f2694c7 --- /dev/null +++ b/src/quickreplay/replay/errors.py @@ -0,0 +1,63 @@ +"""Errors raised by the replay asset component. + +These wrap low-level PyAV/IO failures so that the application layer never sees +raw library exceptions. Mapping to +:class:`~quickreplay.recording.models.WorkerErrorCode` happens in a later phase. +""" + + +class ReplayAssetError(RuntimeError): + """Base class for replay asset component errors.""" + + +class EmptyReplaySnapshotError(ReplayAssetError): + """A replay snapshot without segments cannot produce a replay asset.""" + + +class ReplaySegmentError(ReplayAssetError): + """A source segment is missing, unreadable or out of chronological order.""" + + +class ReplayStreamMismatchError(ReplayAssetError): + """Segments do not share a stream-copy compatible layout.""" + + +class ReplayRemuxError(ReplayAssetError): + """Remuxing or publishing a replay asset failed.""" + + +class ReplayControllerError(RuntimeError): + """Base class for replay playback (mpv) controller errors.""" + + +class MpvExecutableNotFoundError(ReplayControllerError): + """The configured mpv executable could not be started.""" + + +class MpvStartupError(ReplayControllerError): + """mpv did not become ready for playback within the startup timeout.""" + + +class MpvIpcError(ReplayControllerError): + """The mpv JSON IPC connection failed.""" + + +class MpvCommandError(ReplayControllerError): + """mpv returned a non-success response to a command.""" + + def __init__(self, error: str, command: object) -> None: + super().__init__(f"mpv command {command!r} failed: {error}") + self.error = error + self.command = command + + +class MpvCommandTimeoutError(ReplayControllerError): + """mpv did not answer a command within the command timeout.""" + + +class MpvProcessExitedError(ReplayControllerError): + """The mpv process exited while the controller still expected it.""" + + +class MpvPropertyUnavailableError(ReplayControllerError): + """An mpv property is not available (for example ``time-pos`` before load).""" diff --git a/src/quickreplay/replay/models.py b/src/quickreplay/replay/models.py new file mode 100644 index 0000000..0e7fca6 --- /dev/null +++ b/src/quickreplay/replay/models.py @@ -0,0 +1,53 @@ +"""Replay domain models and exact frame-difference math.""" + +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path + +from quickreplay.input.models import StreamInfo +from quickreplay.recording.models import Segment +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction + + +@dataclass(frozen=True, slots=True) +class ReplaySnapshot: + """Immutable set of segments frozen from the ring buffer for replay.""" + + segments: tuple[Segment, ...] + stream_info: StreamInfo + + +@dataclass(frozen=True, slots=True) +class ReplayAsset: + """A completed, single-file, stream-copied replay asset (for example replay.mkv).""" + + path: Path + duration_ns: int + fps: Fraction + + def __post_init__(self) -> None: + if self.duration_ns < 0: + raise ValueError(f"duration_ns must not be negative, got {self.duration_ns}") + if self.fps <= 0: + raise ValueError(f"fps must be positive, got {self.fps}") + + +@dataclass(frozen=True, slots=True) +class SetPoint: + """A replay set point, identified only by its timeline position.""" + + position_ns: int + + +def frame_difference( + current_position_ns: int, + origin_position_ns: int, + fps: Fraction, +) -> int: + """Number of frames between two replay positions, computed without floats. + + ``diff_ns`` is converted to a :class:`~fractions.Fraction` of seconds, + multiplied by *fps* and rounded to the nearest frame. + """ + diff_ns = current_position_ns - origin_position_ns + return round_fraction(Fraction(diff_ns, NANOSECONDS_PER_SECOND) * fps) diff --git a/src/quickreplay/replay/mpv_ipc.py b/src/quickreplay/replay/mpv_ipc.py new file mode 100644 index 0000000..dc56b38 --- /dev/null +++ b/src/quickreplay/replay/mpv_ipc.py @@ -0,0 +1,325 @@ +"""mpv JSON IPC: endpoint generation, transports and a request/response client. + +Only the JSON IPC channel is used to control mpv; stdout/stderr are never +parsed. A dedicated reader thread turns the blocking pipe/socket into timed +line reads so command responses can be awaited without ever blocking forever. +""" + +import json +import os +import queue +import socket +import tempfile +import threading +import time +import uuid +from decimal import ROUND_HALF_UP, Decimal +from typing import Any, Protocol + +from quickreplay.replay.errors import ( + MpvCommandError, + MpvCommandTimeoutError, + MpvIpcError, + MpvProcessExitedError, +) + +_NANOSECONDS = Decimal(1_000_000_000) + + +class _IpcEof: + """Sentinel returned when the IPC reader reaches end-of-file.""" + + +IPC_EOF = _IpcEof() + + +def seconds_to_ns(value: Any) -> int: + """Convert an mpv seconds value to integer nanoseconds. + + mpv numbers arrive as :class:`~decimal.Decimal` (parsed without a binary + float round trip); integers and numeric strings are accepted too. + """ + if value is None or isinstance(value, bool): + raise MpvIpcError(f"cannot convert {value!r} to nanoseconds") + if isinstance(value, Decimal): + seconds = value + elif isinstance(value, int | str): + seconds = Decimal(value) + elif isinstance(value, float): + seconds = Decimal(str(value)) + else: + raise MpvIpcError(f"cannot convert {type(value).__name__} to nanoseconds") + return int((seconds * _NANOSECONDS).to_integral_value(rounding=ROUND_HALF_UP)) + + +def make_ipc_endpoint() -> tuple[str, str | None]: + """Return a unique ``(endpoint, cleanup_path)`` for one mpv instance.""" + token = uuid.uuid4() + if os.name == "nt": + return rf"\\.\pipe\quickreplay-mpv-{token}", None + path = os.path.join(tempfile.gettempdir(), f"quickreplay-mpv-{token}.sock") + return path, path + + +class MpvIpcTransport(Protocol): + """A line-oriented, byte transport to the mpv IPC endpoint.""" + + def connect(self, endpoint: str) -> None: ... + + def write_line(self, data: bytes) -> None: ... + + def read_line(self, timeout: float) -> bytes | _IpcEof | None: ... + + def close(self) -> None: ... + + +class _LineReaderMixin: + """Turns a blocking byte source into timed ``read_line`` calls. + + Reading happens on a daemon thread so ``read_line`` can honour a timeout + without blocking the command dispatch. Reading and writing use separate + handles (or raw ``os.read``/``os.write``) so a blocked read can never hold + a lock that a write needs. + """ + + _lines: queue.Queue[bytes | _IpcEof] + _reader: threading.Thread | None + + def _start_reader(self) -> None: + self._reader = threading.Thread(target=self._pump, name="qr-mpv-ipc", daemon=True) + self._reader.start() + + def _read_chunk(self) -> bytes: + raise NotImplementedError + + def _pump(self) -> None: + buffer = b"" + try: + while True: + chunk = self._read_chunk() + if not chunk: + break + buffer += chunk + while b"\n" in buffer: + line, buffer = buffer.split(b"\n", 1) + self._lines.put(line + b"\n") + if buffer: + self._lines.put(buffer + b"\n") + except Exception: # noqa: BLE001 - stream closed during shutdown + pass + finally: + self._lines.put(IPC_EOF) + + def read_line(self, timeout: float) -> bytes | _IpcEof | None: + try: + return self._lines.get(timeout=timeout) + except queue.Empty: + return None + + +class WindowsPipeTransport(_LineReaderMixin): + """mpv IPC over a Windows named pipe.""" + + def __init__(self) -> None: + self._file: Any = None + self._fd: int | None = None + self._lines: queue.Queue[bytes | _IpcEof] = queue.Queue() + self._reader = None + self._closed = False + + def connect(self, endpoint: str) -> None: + try: + self._file = open(endpoint, "r+b", buffering=0) # noqa: SIM115 - kept open + except OSError as exc: + raise MpvIpcError(f"could not connect to the mpv IPC pipe: {exc}") from exc + self._fd = self._file.fileno() + self._start_reader() + + def _read_chunk(self) -> bytes: + assert self._fd is not None + # A blocking ReadFile on a synchronous pipe handle also blocks writes, + # so poll for available bytes with PeekNamedPipe before reading. + while not self._closed: + if _pipe_bytes_available(self._fd) > 0: + return os.read(self._fd, 65536) + time.sleep(0.002) + return b"" + + def write_line(self, data: bytes) -> None: + fd = self._fd + if fd is None: + raise MpvIpcError("the mpv IPC pipe is not connected") + try: + view = memoryview(data) + while view: + written = os.write(fd, view) + view = view[written:] + except OSError as exc: + raise MpvIpcError(f"could not write to the mpv IPC pipe: {exc}") from exc + + def close(self) -> None: + if self._closed: + return + self._closed = True + if self._file is not None: + try: + self._file.close() + except OSError: + pass + + +class UnixSocketTransport(_LineReaderMixin): + """mpv IPC over a Unix domain socket.""" + + def __init__(self) -> None: + self._socket: socket.socket | None = None + self._stream: Any = None + self._lines: queue.Queue[bytes | _IpcEof] = queue.Queue() + self._reader = None + self._closed = False + + def connect(self, endpoint: str) -> None: + address_family = getattr(socket, "AF_UNIX", None) + if address_family is None: # pragma: no cover - platform guard + raise MpvIpcError("Unix domain sockets are not available on this platform") + sock = socket.socket(address_family, socket.SOCK_STREAM) + try: + sock.connect(endpoint) + except OSError as exc: + sock.close() + raise MpvIpcError(f"could not connect to the mpv IPC socket: {exc}") from exc + self._socket = sock + self._stream = sock.makefile("rb") + self._start_reader() + + def _read_chunk(self) -> bytes: + return self._stream.readline() + + def write_line(self, data: bytes) -> None: + if self._socket is None: + raise MpvIpcError("the mpv IPC socket is not connected") + try: + self._socket.sendall(data) + except OSError as exc: + raise MpvIpcError(f"could not write to the mpv IPC socket: {exc}") from exc + + def close(self) -> None: + if self._closed: + return + self._closed = True + if self._stream is not None: + try: + self._stream.close() + except OSError: + pass + if self._socket is not None: + try: + self._socket.close() + except OSError: + pass + + +def _pipe_bytes_available(fd: int) -> int: + """Bytes ready to read on a Windows pipe, without blocking the handle.""" + import ctypes # noqa: PLC0415 - Windows-only helper + + msvcrt = __import__("msvcrt") + windll = getattr(ctypes, "WinDLL") # noqa: B009 - Windows-only attribute + kernel32 = windll("kernel32", use_last_error=True) + handle = getattr(msvcrt, "get_osfhandle")(fd) # noqa: B009 - Windows-only + available = ctypes.c_ulong(0) + ok = kernel32.PeekNamedPipe(handle, None, 0, None, ctypes.byref(available), None) + if not ok: + get_last_error = getattr(ctypes, "get_last_error") # noqa: B009 - Windows-only + raise OSError(get_last_error(), "PeekNamedPipe failed") + return int(available.value) + + +def default_transport_factory() -> MpvIpcTransport: + """Create the platform IPC transport.""" + if os.name == "nt": + return WindowsPipeTransport() + return UnixSocketTransport() + + +class MpvIpcClient: + """Correlates JSON IPC requests with their responses by ``request_id``.""" + + def __init__( + self, + transport: MpvIpcTransport, + *, + process: Any, + command_timeout_seconds: float, + ) -> None: + self._transport = transport + self._process = process + self._command_timeout_seconds = command_timeout_seconds + self._request_id = 0 + self._pending: dict[int, dict[str, Any]] = {} + self._lock = threading.Lock() + + def close(self) -> None: + self._transport.close() + + def command(self, *args: object, wait: bool = True) -> Any: + """Send a command and (by default) return its ``data`` payload.""" + with self._lock: + if wait: + self._raise_if_exited() + self._request_id += 1 + request_id = self._request_id + payload = {"command": list(args), "request_id": request_id} + self._transport.write_line(json.dumps(payload).encode("utf-8") + b"\n") + if not wait: + return None + return self._await_response(request_id, list(args)) + + def get_property(self, name: str) -> Any: + return self.command("get_property", name) + + def set_property(self, name: str, value: object) -> None: + self.command("set_property", name, value) + + def _await_response(self, request_id: int, command: list[object]) -> Any: + deadline = time.monotonic() + self._command_timeout_seconds + while True: + pending = self._pending.pop(request_id, None) + if pending is not None: + return self._unwrap(pending, command) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise MpvCommandTimeoutError( + f"mpv did not answer {command!r} within {self._command_timeout_seconds}s" + ) + line = self._transport.read_line(remaining) + if line is None: + if self._process.poll() is not None: + raise MpvProcessExitedError("the mpv process exited during a command") + continue + if isinstance(line, _IpcEof): + raise MpvProcessExitedError("the mpv IPC channel reached EOF") + self._handle_line(line, request_id, command) + + def _handle_line(self, line: bytes, request_id: int, command: list[object]) -> None: + try: + message = json.loads(line, parse_float=Decimal) + except ValueError as exc: + raise MpvIpcError(f"invalid mpv IPC message: {exc}") from exc + if not isinstance(message, dict) or "request_id" not in message: + return # an asynchronous event: ignore it + response_id = message.get("request_id") + if response_id == request_id: + self._pending[request_id] = message + elif isinstance(response_id, int): + self._pending[response_id] = message + + def _unwrap(self, message: dict[str, Any], command: list[object]) -> Any: + error = message.get("error", "success") + if error != "success": + raise MpvCommandError(str(error), command) + return message.get("data") + + def _raise_if_exited(self) -> None: + if self._process.poll() is not None: + raise MpvProcessExitedError("the mpv process has exited") diff --git a/src/quickreplay/replay/mpv_process.py b/src/quickreplay/replay/mpv_process.py new file mode 100644 index 0000000..155a22f --- /dev/null +++ b/src/quickreplay/replay/mpv_process.py @@ -0,0 +1,92 @@ +"""External mpv process management. + +mpv runs as a separate process; QuickReplay never embeds libmpv. stdout and +stderr are discarded, so all control flows through the JSON IPC channel. +""" + +import subprocess +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Protocol + +from quickreplay.replay.errors import MpvExecutableNotFoundError + + +class MpvProcess(Protocol): + """The process operations the replay controller needs.""" + + def poll(self) -> int | None: ... + + def wait(self, timeout: float | None = None) -> int | None: ... + + def terminate(self) -> None: ... + + def kill(self) -> None: ... + + @property + def returncode(self) -> int | None: ... + + +ProcessFactory = Callable[[Sequence[str]], MpvProcess] + + +def mpv_launch_arguments(executable: Path | str, endpoint: str, asset_path: Path) -> list[str]: + """Build the mpv command line used for replay playback.""" + return [ + str(executable), + "--no-config", + "--terminal=no", + "--osc=no", + f"--input-ipc-server={endpoint}", + "--pause=yes", + "--keep-open=yes", + "--force-window=yes", + "--hr-seek=yes", + "--hr-seek-framedrop=no", + "--hwdec=no", + str(asset_path), + ] + + +class SubprocessMpvProcess: + """Thin wrapper around :class:`subprocess.Popen`.""" + + def __init__(self, process: subprocess.Popen) -> None: + self._process = process + + def poll(self) -> int | None: + return self._process.poll() + + def wait(self, timeout: float | None = None) -> int | None: + try: + return self._process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + return None + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + @property + def returncode(self) -> int | None: + return self._process.returncode + + +def spawn_mpv_process(arguments: Sequence[str]) -> MpvProcess: + """Start mpv with *arguments*, mapping a missing executable to an error.""" + try: + process = subprocess.Popen( # noqa: S603 - explicit, validated arguments + list(arguments), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + except FileNotFoundError as exc: + raise MpvExecutableNotFoundError( + f"the mpv executable was not found: {arguments[0]!r}" + ) from exc + except OSError as exc: + raise MpvExecutableNotFoundError(f"could not start mpv: {exc}") from exc + return SubprocessMpvProcess(process) diff --git a/src/quickreplay/replay/remux.py b/src/quickreplay/replay/remux.py new file mode 100644 index 0000000..e340ec1 --- /dev/null +++ b/src/quickreplay/replay/remux.py @@ -0,0 +1,211 @@ +"""Stream-copy remux of finalized segments into a single replay MKV. + +No decoding or encoding happens here. Packets are copied from the source +segments and their timestamps are rebased onto one continuous replay timeline +that starts at zero. Each segment already starts its own packets at ``0``, so +the builder adds the segment's timeline offset to every packet. + +All timeline math uses :class:`~fractions.Fraction` and integers. Float seconds +are never used as a source of truth. +""" + +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +from typing import Protocol + +import av +import av.audio.stream +import av.stream +import av.video.stream + +from quickreplay.recording.models import Segment +from quickreplay.replay.errors import ( + ReplayAssetError, + ReplayRemuxError, + ReplaySegmentError, + ReplayStreamMismatchError, +) +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction + + +@dataclass(frozen=True, slots=True) +class VideoLayout: + """Stream-copy relevant video properties of a segment.""" + + codec: str + width: int + height: int + pixel_format: str | None + time_base: Fraction | None + rate: Fraction | None + extradata: bytes + + +@dataclass(frozen=True, slots=True) +class AudioLayout: + """Stream-copy relevant audio properties of a segment.""" + + codec: str + sample_rate: int + channels: int + channel_layout: str | None + time_base: Fraction | None + extradata: bytes + + +@dataclass(frozen=True, slots=True) +class SegmentLayout: + """The stream layout of one segment file.""" + + video: VideoLayout + audio: AudioLayout | None + + +class Remux(Protocol): + """Remux *segments* into the (not yet published) file *tmp_path*.""" + + def __call__(self, segments: tuple[Segment, ...], tmp_path: Path) -> None: ... + + +def probe_layout(path: Path) -> SegmentLayout: + """Read the stream layout of a segment file without decoding it.""" + try: + with av.open(str(path)) as container: + if not container.streams.video: + raise ReplaySegmentError(f"segment has no video stream: {path}") + audio = None + if container.streams.audio: + audio = _audio_layout(container.streams.audio[0]) + return SegmentLayout(video=_video_layout(container.streams.video[0]), audio=audio) + except ReplaySegmentError: + raise + except Exception as exc: # noqa: BLE001 - wrap any PyAV/IO failure + raise ReplaySegmentError(f"failed to read segment layout {path}: {exc}") from exc + + +def _video_layout(stream: av.video.stream.VideoStream) -> VideoLayout: + codec = stream.codec_context + return VideoLayout( + codec=codec.name, + width=codec.width, + height=codec.height, + pixel_format=codec.pix_fmt, + time_base=stream.time_base, + rate=stream.average_rate, + extradata=bytes(codec.extradata or b""), + ) + + +def _audio_layout(stream: av.audio.stream.AudioStream) -> AudioLayout: + codec = stream.codec_context + layout = getattr(codec, "layout", None) + return AudioLayout( + codec=codec.name, + sample_rate=codec.sample_rate, + channels=codec.channels, + channel_layout=getattr(layout, "name", None), + time_base=stream.time_base, + extradata=bytes(codec.extradata or b""), + ) + + +def validate_segment_layouts(segments: tuple[Segment, ...]) -> None: + """Ensure every segment can be stream-copied into the same output streams.""" + reference = probe_layout(segments[0].path) + for segment in segments[1:]: + layout = probe_layout(segment.path) + if layout != reference: + raise ReplayStreamMismatchError( + f"segment {segment.id} layout does not match the first segment: " + f"{layout} != {reference}" + ) + + +def remux_segments(segments: tuple[Segment, ...], tmp_path: Path) -> None: + """Stream-copy all *segments* into *tmp_path* as one continuous MKV.""" + if not segments: + raise ReplayRemuxError("cannot remux an empty segment list") + base_ns = segments[0].session_start_ns + container = av.open(str(tmp_path), mode="w", format="matroska") + try: + output_streams: dict[str, av.stream.Stream] = {} + last_ticks: dict[str, int] = {} + for segment in segments: + offset_ns = segment.session_start_ns - base_ns + _mux_segment(container, output_streams, last_ticks, segment.path, offset_ns) + except BaseException as exc: + _close_quietly(container) + if isinstance(exc, ReplayAssetError): + raise + raise ReplayRemuxError(f"failed to remux replay asset: {exc}") from exc + try: + container.close() + except Exception as exc: # noqa: BLE001 - wrap any PyAV/IO failure + _close_quietly(container) + raise ReplayRemuxError(f"failed to finalize replay container: {exc}") from exc + + +def _mux_segment( + container: av.container.OutputContainer, + output_streams: dict[str, av.stream.Stream], + last_ticks: dict[str, int], + path: Path, + offset_ns: int, +) -> None: + with av.open(str(path)) as source: + for in_stream in source.streams: + if in_stream.type not in output_streams: + output_streams[in_stream.type] = container.add_stream_from_template( + in_stream, opaque=True + ) + for packet in source.demux(): + if packet.dts is None and packet.pts is None: + # PyAV yields one final packet without timestamps per demux(). + continue + out_stream = output_streams[packet.stream.type] + _rebase_packet(packet, out_stream, offset_ns) + _check_forward(packet, last_ticks) + container.mux(packet) + + +def _rebase_packet(packet: av.Packet, out_stream: av.stream.Stream, offset_ns: int) -> None: + source_time_base = packet.time_base + packet.stream = out_stream + output_time_base = out_stream.time_base + if output_time_base is None: + raise ReplayRemuxError("replay output stream has no time base") + if source_time_base is not None and source_time_base != output_time_base: + packet.pts = _rescale(packet.pts, source_time_base, output_time_base) + packet.dts = _rescale(packet.dts, source_time_base, output_time_base) + offset_ticks = round_fraction(Fraction(offset_ns, NANOSECONDS_PER_SECOND) / output_time_base) + if packet.pts is not None: + packet.pts += offset_ticks + if packet.dts is not None: + packet.dts += offset_ticks + + +def _rescale(value: int | None, from_time_base: Fraction, to_time_base: Fraction) -> int | None: + if value is None: + return None + return round_fraction(Fraction(value) * from_time_base / to_time_base) + + +def _check_forward(packet: av.Packet, last_ticks: dict[str, int]) -> None: + stream_type = packet.stream.type + timestamp = packet.dts if packet.dts is not None else packet.pts + if timestamp is None: + return + previous = last_ticks.get(stream_type) + if previous is not None and timestamp < previous: + raise ReplayRemuxError( + f"{stream_type} timestamp regressed across a segment boundary: {timestamp} < {previous}" + ) + last_ticks[stream_type] = timestamp + + +def _close_quietly(container: av.container.OutputContainer) -> None: + try: + container.close() + except Exception: # noqa: BLE001 - best effort cleanup + pass diff --git a/src/quickreplay/ui/__init__.py b/src/quickreplay/ui/__init__.py new file mode 100644 index 0000000..af5fa01 --- /dev/null +++ b/src/quickreplay/ui/__init__.py @@ -0,0 +1,5 @@ +"""Flet desktop UI. + +This package is split so that everything except :mod:`quickreplay.ui.app` and +:mod:`quickreplay.ui.main_view` is Flet-independent and testable headlessly. +""" diff --git a/src/quickreplay/ui/about.py b/src/quickreplay/ui/about.py new file mode 100644 index 0000000..7f714cf --- /dev/null +++ b/src/quickreplay/ui/about.py @@ -0,0 +1,257 @@ +"""Offline About window content for QuickReplay.""" + +import ctypes +import sys +from ctypes import POINTER, Structure, byref, c_void_p, cast, create_string_buffer +from importlib.metadata import PackageNotFoundError, version + +import flet as ft + +GITHUB_URL = "https://github.com/Nanahuse/QuickReplay" +THIRD_PARTY_NOTICE = """# Third-party notices + +This file lists the primary third-party components used by the QuickReplay +Version 2 runtime and Windows package. + +## Python + +Python Software Foundation License
+https://docs.python.org/3/license.html#psf-license + +## Flet + +Apache License 2.0
+https://github.com/flet-dev/flet/blob/main/LICENSE + +## PyAV + +BSD 3-Clause License
+https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt + +## NumPy + +BSD 3-Clause License
+https://github.com/numpy/numpy/blob/main/LICENSE.txt + +## ndi-python + +MIT License
+https://github.com/buresu/ndi-python/blob/master/LICENSE + +## NDI SDK / NDI runtime + +NDI SDK License
+https://ndi.video/for-developers/ndi-sdk/license/ + +QuickReplay does not bundle mpv. Replay playback uses the external mpv +executable configured by the user.""" + +THIRD_PARTY_LICENSES = ( + ( + "Python", + "Python Software Foundation License", + "https://docs.python.org/3/license.html#psf-license", + ), + ("Flet", "Apache License 2.0", "https://github.com/flet-dev/flet/blob/main/LICENSE"), + ("PyAV", "BSD 3-Clause License", "https://github.com/PyAV-Org/PyAV/blob/main/LICENSE.txt"), + ("NumPy", "BSD 3-Clause License", "https://github.com/numpy/numpy/blob/main/LICENSE.txt"), + ("ndi-python", "MIT License", "https://github.com/buresu/ndi-python/blob/master/LICENSE"), + ( + "NDI SDK / NDI Runtime", + "NDI SDK License", + "https://ndi.video/for-developers/ndi-sdk/license/", + ), +) + +MIT_LICENSE = """MIT License + +Copyright (c) 2022 Nanahuse + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.""" + + +def application_version() -> str: + """Read the project version from package metadata or the packaged Windows executable.""" + try: + return version("quickreplay") + except PackageNotFoundError: + return _windows_executable_version() or "Unknown" + + +def _windows_executable_version() -> str | None: + """Read the ProductVersion embedded by Flet from the Windows executable.""" + if sys.platform != "win32": + return None + + class FixedFileInfo(Structure): + _fields_ = [ + ("signature", ctypes.c_uint32), + ("structure_version", ctypes.c_uint32), + ("file_version_ms", ctypes.c_uint32), + ("file_version_ls", ctypes.c_uint32), + ("product_version_ms", ctypes.c_uint32), + ("product_version_ls", ctypes.c_uint32), + ("flags_mask", ctypes.c_uint32), + ("flags", ctypes.c_uint32), + ("file_os", ctypes.c_uint32), + ("file_type", ctypes.c_uint32), + ("file_subtype", ctypes.c_uint32), + ("file_date_ms", ctypes.c_uint32), + ("file_date_ls", ctypes.c_uint32), + ] + + library = ctypes.WinDLL("version", use_last_error=True) + for executable in dict.fromkeys((sys.argv[0], sys.executable)): + if not executable: + continue + ignored_handle = ctypes.c_uint32() + size = library.GetFileVersionInfoSizeW(executable, byref(ignored_handle)) + if not size: + continue + + data = create_string_buffer(size) + if not library.GetFileVersionInfoW(executable, 0, size, data): + continue + + value = c_void_p() + value_length = ctypes.c_uint32() + if not library.VerQueryValueW(data, "\\", byref(value), byref(value_length)): + continue + + info = cast(value, POINTER(FixedFileInfo)).contents + major, minor = info.product_version_ms >> 16, info.product_version_ms & 0xFFFF + patch, build = info.product_version_ls >> 16, info.product_version_ls & 0xFFFF + version_text = f"{major}.{minor}.{patch}" + return f"{version_text}.{build}" if build else version_text + return None + + +def build_about_ui(page: ft.Page) -> ft.Control: + """Build the standalone About window body with local license views.""" + content = ft.Container(expand=True) + + def show_quickreplay_license(_event: ft.Event | None = None) -> None: + content.content = ft.Column( + controls=[ + ft.Text("QuickReplay License", size=18, weight=ft.FontWeight.BOLD), + ft.Text(MIT_LICENSE, selectable=True), + ], + spacing=12, + scroll=ft.ScrollMode.AUTO, + expand=True, + ) + page.update() + + def show_third_party_notices(_event: ft.Event | None = None) -> None: + content.content = ft.Column( + controls=[ + ft.Row( + controls=[ + ft.Text("Third-party notices", size=18, weight=ft.FontWeight.BOLD), + ft.TextButton( + content="Back to licenses", on_click=show_third_party_licenses + ), + ], + alignment=ft.MainAxisAlignment.SPACE_BETWEEN, + ), + ft.Text(THIRD_PARTY_NOTICE, selectable=True, expand=True), + ], + spacing=12, + scroll=ft.ScrollMode.AUTO, + expand=True, + ) + page.update() + + def show_third_party_licenses(_event: ft.Event | None = None) -> None: + rows = [ + ft.Row( + controls=[ + ft.Column( + controls=[ft.Text(name, weight=ft.FontWeight.BOLD), ft.Text(license_name)], + spacing=0, + expand=True, + ), + ft.TextButton(content="Website", url=url), + ], + vertical_alignment=ft.CrossAxisAlignment.CENTER, + ) + for name, license_name, url in THIRD_PARTY_LICENSES + ] + content.content = ft.Column( + controls=[ + ft.Row( + controls=[ + ft.Text("Third-party Licenses", size=18, weight=ft.FontWeight.BOLD), + ft.TextButton( + content="View third-party notices", + on_click=show_third_party_notices, + ), + ], + alignment=ft.MainAxisAlignment.SPACE_BETWEEN, + ), + *rows, + ], + spacing=8, + scroll=ft.ScrollMode.AUTO, + expand=True, + ) + page.update() + + content.content = ft.Column( + controls=[ + ft.Text("QuickReplay License", size=18, weight=ft.FontWeight.BOLD), + ft.Text(MIT_LICENSE, selectable=True), + ], + spacing=12, + scroll=ft.ScrollMode.AUTO, + expand=True, + ) + return ft.Column( + controls=[ + ft.Row( + controls=[ + ft.Column( + controls=[ + ft.Text("QuickReplay", size=26, weight=ft.FontWeight.BOLD), + ft.Text(f"Version {application_version()} · © 2022 Nanahuse"), + ], + spacing=2, + expand=True, + ), + ft.TextButton(content="GitHub", url=GITHUB_URL), + ], + vertical_alignment=ft.CrossAxisAlignment.CENTER, + ), + ft.Divider(), + ft.Row( + controls=[ + ft.OutlinedButton( + content="QuickReplay License", on_click=show_quickreplay_license + ), + ft.OutlinedButton( + content="Third-party Licenses", on_click=show_third_party_licenses + ), + ], + spacing=8, + ), + content, + ], + spacing=8, + expand=True, + ) diff --git a/src/quickreplay/ui/about_window.py b/src/quickreplay/ui/about_window.py new file mode 100644 index 0000000..6167f89 --- /dev/null +++ b/src/quickreplay/ui/about_window.py @@ -0,0 +1,49 @@ +"""Standalone Flet window process for QuickReplay About and license information.""" + +import os + +import flet as ft + +from quickreplay.ui.about import build_about_ui + +ABOUT_WINDOW_SIZE = (680, 540) +ABOUT_WINDOW_MIN_SIZE = (560, 400) + + +async def about_page(page: ft.Page) -> None: + """Configure the standalone About window.""" + page.title = "QuickReplay — About" + page.window.width, page.window.height = ABOUT_WINDOW_SIZE + page.window.min_width, page.window.min_height = ABOUT_WINDOW_MIN_SIZE + page.window.resizable = True + page.window.maximizable = True + page.window.visible = False + page.add(ft.Container(content=build_about_ui(page), expand=True, padding=16)) + await page.window.wait_until_ready_to_show() + page.window.visible = True + page.update() + + +def run_about_window(*, embedded: bool) -> None: + """Run About in a dedicated app process or a standalone development view.""" + if not embedded: + # A development subprocess should create its own desktop client instead + # of attaching to the Flet runner's embedded bridge. + for name in tuple(os.environ): + if name.startswith("FLET_"): + os.environ.pop(name, None) + + async def main(page: ft.Page) -> None: + await about_page(page) + + ft.run(main, view=ft.AppView.FLET_APP) + + +def run_about_from_command_line() -> None: + """Entry point used by a separately launched packaged app instance.""" + run_about_window(embedded=True) + + +if __name__ == "__main__": + # ``python -m quickreplay.ui.about_window`` development entry point. + run_about_window(embedded=False) diff --git a/src/quickreplay/ui/app.py b/src/quickreplay/ui/app.py new file mode 100644 index 0000000..b31c2d5 --- /dev/null +++ b/src/quickreplay/ui/app.py @@ -0,0 +1,99 @@ +"""Flet desktop entry point. + +Run with:: + + uv run flet run src/quickreplay/ui/app.py + +The application is not started on import; only ``run`` (under the +``__main__`` guard) starts it, together with ``multiprocessing.freeze_support`` +for the spawned recorder worker process. +""" + +import multiprocessing + +import flet as ft + +from quickreplay.ui.bootstrap import bootstrap_application +from quickreplay.ui.main_view import ( + WINDOW_SIZES, + MainView, + is_destroyed_session_error, +) +from quickreplay.ui.paths import StoragePathError, storage_paths_from_environment +from quickreplay.ui.session import UiSession + + +def _startup_error(message: str) -> ft.Control: + return ft.Column( + controls=[ + ft.Text("QuickReplay", size=24, weight=ft.FontWeight.BOLD), + ft.Text("Startup failed", color=ft.Colors.RED, weight=ft.FontWeight.BOLD), + ft.Text(message), + ], + spacing=10, + ) + + +def _show_startup_error(page: ft.Page, message: str) -> None: + """Render a startup error, tolerating an already destroyed Flet session.""" + try: + page.window.visible = True + page.add(_startup_error(message)) + page.update() + except RuntimeError as exc: + if not is_destroyed_session_error(exc): + raise + + +def _configure_window(page: ft.Page) -> None: + """Apply the fixed-size desktop window policy before the first render.""" + page.title = "QuickReplay" + page.window.width, page.window.height = WINDOW_SIZES["setup"] + page.window.visible = False + page.window.resizable = False + page.window.maximizable = False + + +async def main(page: ft.Page) -> None: + """Flet entry point.""" + _configure_window(page) + + try: + paths = storage_paths_from_environment() + bootstrap = bootstrap_application(paths=paths) + except StoragePathError as exc: + _show_startup_error(page, str(exc)) + return + except Exception as exc: # noqa: BLE001 - show configuration/startup errors in the UI + _show_startup_error(page, str(exc)) + return + + session = UiSession(bootstrap.bridge, bootstrap.store, bootstrap.config) + view = MainView(page, session) + page.add(view.control) + page.window.prevent_close = True + page.window.on_event = view.on_window_event + page.on_disconnect = view.on_page_disconnect + + try: + await view.start() + except Exception as exc: # noqa: BLE001 - view.start already cleaned the core up + _show_startup_error(page, f"Could not start the application: {exc}") + return + + await page.window.wait_until_ready_to_show() + page.window.visible = True + page.update() + + if view.is_active: + view.start_polling() + + +def run() -> None: + """Start the Flet desktop application.""" + ft.run(main, view=ft.AppView.FLET_APP_HIDDEN) + + +if __name__ == "__main__": + multiprocessing.freeze_support() + run() diff --git a/src/quickreplay/ui/bootstrap.py b/src/quickreplay/ui/bootstrap.py new file mode 100644 index 0000000..2aa8abb --- /dev/null +++ b/src/quickreplay/ui/bootstrap.py @@ -0,0 +1,48 @@ +"""Desktop bootstrap: configuration, runtime settings and the application. + +This module never imports Flet, so it can be exercised headlessly. +""" + +from collections.abc import Callable +from dataclasses import dataclass + +from quickreplay.application.controller import ApplicationController +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.configuration.runtime import build_application_settings +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.ui.bridge import ApplicationUiBridge +from quickreplay.ui.paths import StoragePaths + + +@dataclass(frozen=True, slots=True) +class ApplicationBootstrap: + """The assembled application objects for a desktop session.""" + + paths: StoragePaths + store: ConfigurationStore + config: QuickReplayConfig + controller: ApplicationController + bridge: ApplicationUiBridge + + +def bootstrap_application( + *, + paths: StoragePaths, + controller_factory: Callable[[object], ApplicationController] | None = None, + bridge_factory: Callable[[ApplicationController], ApplicationUiBridge] | None = None, +) -> ApplicationBootstrap: + """Load configuration and build the application controller and bridge. + + Configuration errors propagate to the caller so the UI can show a startup + error instead of silently replacing a broken configuration with defaults. + """ + store = ConfigurationStore(paths.config_path) + config = store.load() + settings = build_application_settings(config, working_directory=paths.runtime_directory) + controller = ( + controller_factory(settings) if controller_factory else ApplicationController(settings) + ) + bridge = bridge_factory(controller) if bridge_factory else ApplicationUiBridge(controller) + return ApplicationBootstrap( + paths=paths, store=store, config=config, controller=controller, bridge=bridge + ) diff --git a/src/quickreplay/ui/bridge.py b/src/quickreplay/ui/bridge.py new file mode 100644 index 0000000..f1f3853 --- /dev/null +++ b/src/quickreplay/ui/bridge.py @@ -0,0 +1,154 @@ +"""Async boundary between the Flet event loop and the blocking application core. + +Every :class:`~quickreplay.application.controller.ApplicationController` call +runs on a dedicated single-worker executor, so the asyncio loop is never +blocked and controller calls are serialized (never two at once). +""" + +import asyncio +import functools +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from typing import Protocol +from uuid import UUID + +from quickreplay.application.events import ApplicationEvent +from quickreplay.application.models import ApplicationSnapshot +from quickreplay.input.models import InputConfig +from quickreplay.replay.models import SetPoint + +EXECUTOR_THREAD_PREFIX = "QuickReplayApplication" + + +class ControllerLike(Protocol): + """The blocking controller operations the bridge forwards.""" + + def start(self) -> None: ... + + def start_recording(self, input_config: InputConfig) -> None: ... + + def discover_inputs(self) -> UUID: ... + + def request_replay(self) -> UUID: ... + + def resume_recording(self) -> UUID: ... + + def stop_session(self) -> UUID: ... + + def poll(self, timeout: float = 0.0) -> tuple[ApplicationEvent, ...]: ... + + def snapshot(self) -> ApplicationSnapshot: ... + + def shutdown(self) -> None: ... + + # -- replay delegate --------------------------------------------------- + def play(self) -> None: ... + + def pause(self) -> None: ... + + def is_paused(self) -> bool: ... + + def step_forward(self) -> None: ... + + def step_backward(self) -> None: ... + + def seek_frames(self, frames: int) -> None: ... + + def seek_absolute_ns(self, position_ns: int) -> None: ... + + def replay_position_ns(self) -> int: ... + + def set_point(self) -> SetPoint: ... + + def time_difference_ns(self, point: SetPoint) -> int: ... + + def frame_difference(self, point: SetPoint) -> int: ... + + +class ApplicationUiBridge: + """Serializes blocking controller calls onto one worker thread.""" + + def __init__( + self, + controller: ControllerLike, + *, + executor: ThreadPoolExecutor | None = None, + ) -> None: + self._controller = controller + self._executor = executor or ThreadPoolExecutor( + max_workers=1, thread_name_prefix=EXECUTOR_THREAD_PREFIX + ) + self._closed = False + + async def _run[T](self, func: Callable[..., T], *args, **kwargs) -> T: + loop = asyncio.get_running_loop() + call = functools.partial(func, *args, **kwargs) + return await loop.run_in_executor(self._executor, call) + + async def start(self) -> None: + await self._run(self._controller.start) + + async def start_recording(self, input_config: InputConfig) -> None: + await self._run(self._controller.start_recording, input_config) + + async def discover_inputs(self) -> UUID: + return await self._run(self._controller.discover_inputs) + + async def request_replay(self) -> UUID: + return await self._run(self._controller.request_replay) + + async def resume_recording(self) -> UUID: + return await self._run(self._controller.resume_recording) + + async def stop_session(self) -> UUID: + return await self._run(self._controller.stop_session) + + async def poll(self, timeout: float = 0.0) -> tuple[ApplicationEvent, ...]: + return await self._run(self._controller.poll, timeout) + + async def snapshot(self) -> ApplicationSnapshot: + return await self._run(self._controller.snapshot) + + async def shutdown(self) -> None: + await self._run(self._controller.shutdown) + + # -- replay delegate --------------------------------------------------- + async def play(self) -> None: + await self._run(self._controller.play) + + async def pause(self) -> None: + await self._run(self._controller.pause) + + async def is_paused(self) -> bool: + return await self._run(self._controller.is_paused) + + async def step_forward(self) -> None: + await self._run(self._controller.step_forward) + + async def step_backward(self) -> None: + await self._run(self._controller.step_backward) + + async def seek_frames(self, frames: int) -> None: + await self._run(self._controller.seek_frames, frames) + + async def seek_absolute_ns(self, position_ns: int) -> None: + await self._run(self._controller.seek_absolute_ns, position_ns) + + async def replay_position_ns(self) -> int: + return await self._run(self._controller.replay_position_ns) + + async def set_point(self) -> SetPoint: + return await self._run(self._controller.set_point) + + async def time_difference_ns(self, point: SetPoint) -> int: + return await self._run(self._controller.time_difference_ns, point) + + async def frame_difference(self, point: SetPoint) -> int: + return await self._run(self._controller.frame_difference, point) + + async def close(self) -> None: + """Shut the executor down. Call only after :meth:`shutdown`.""" + if self._closed: + return + self._closed = True + self._executor.shutdown(wait=True) diff --git a/src/quickreplay/ui/main_view.py b/src/quickreplay/ui/main_view.py new file mode 100644 index 0000000..9c46d7d --- /dev/null +++ b/src/quickreplay/ui/main_view.py @@ -0,0 +1,923 @@ +"""Flet 1.0 controls for the QuickReplay main window. + +The view is intentionally thin: it renders a +:class:`~quickreplay.ui.session.UiViewState` and forwards user actions to +:class:`~quickreplay.ui.session.UiSession`. All application state lives in the +session; the view holds only transient widget state. +""" + +import asyncio +import subprocess +import sys +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from decimal import Decimal +from enum import Enum, auto +from pathlib import Path +from typing import Any, cast + +import flet as ft + +from quickreplay.app.state import ApplicationState +from quickreplay.ui.presentation import format_duration_ns +from quickreplay.ui.replay_repeat import ReplayActionRepeater +from quickreplay.ui.session import ( + ReplayView, + UiSession, + UiViewState, +) +from quickreplay.ui.settings import SettingsDraft + +POLL_INTERVAL_SECONDS = 0.1 +POLL_INTERVAL_REPLAY_SECONDS = 0.05 +_EMPTY = "—" +_NANOSECONDS_PER_SECOND = 1_000_000_000 +_DESTROYED_SESSION_MARKER = "destroyed session" +REPLAY_REPEAT_FRAME_INTERVAL_SECONDS = 0.085 +REPLAY_REPEAT_FAST_INTERVAL_SECONDS = 0.050 +REPLAY_FAST_MOVE_FRAMES = 20 +SESSION_WINDOW_WIDTH = 420 +SETUP_WINDOW_SIZE = (640, 320) +RECORDING_WINDOW_HEIGHT = 120 +REPLAY_WINDOW_HEIGHT = 300 +REPLAY_CONTENT_WIDTH = 380 +REPLAY_TRANSPORT_BUTTON_WIDTH = 68 +REPLAY_TRANSPORT_BUTTON_HEIGHT = 40 +REPLAY_TRANSPORT_SPACING = 10 +WINDOW_SIZES = { + "setup": SETUP_WINDOW_SIZE, + "recording": (SESSION_WINDOW_WIDTH, RECORDING_WINDOW_HEIGHT), + "replay": (SESSION_WINDOW_WIDTH, REPLAY_WINDOW_HEIGHT), +} + + +class ViewLifecycle(Enum): + """MainView lifecycle state. + + Only :attr:`RUNNING` accepts new UI work and page updates; :attr:`CLOSING` + rejects them while core cleanup runs, and :attr:`CLOSED` is terminal. + """ + + RUNNING = auto() + CLOSING = auto() + CLOSED = auto() + + +def is_destroyed_session_error(exc: RuntimeError) -> bool: + """Whether *exc* is Flet's known "session destroyed" teardown error. + + Flet raises this when the page's session has been torn down (window + destroyed or client disconnected). Only this specific error is treated as + a lifecycle event; every other :class:`RuntimeError` is a real bug and is + left to propagate. The string check is deliberately confined here. + """ + return _DESTROYED_SESSION_MARKER in str(exc) + + +def slider_seconds_to_ns(value: float) -> int: + """Convert a Slider value (seconds) to integer nanoseconds at the UI boundary.""" + return int(Decimal(str(value)) * _NANOSECONDS_PER_SECOND) + + +@dataclass(slots=True) +class SeekDrag: + """Pure seek-bar drag state (no Flet types), so it can be tested headlessly. + + While ``active`` the view must not overwrite the slider thumb with the + polled position, and no seek command is sent until :meth:`end`. + """ + + active: bool = False + preview_ns: int | None = None + + def start(self, value: float) -> None: + self.active = True + self.preview_ns = slider_seconds_to_ns(value) + + def update_preview(self, value: float) -> None: + self.preview_ns = slider_seconds_to_ns(value) + + def end(self, value: float) -> int: + target_ns = slider_seconds_to_ns(value) + self.preview_ns = target_ns + self.active = False + return target_ns + + +class MainView: + """The single main screen of the QuickReplay desktop UI.""" + + def __init__(self, page: ft.Page, session: UiSession) -> None: + self.page = page + self.session = session + self._lifecycle = ViewLifecycle.RUNNING + self._session_lost = False + self._close_started = False + self._poll_task: asyncio.Task[None] | None = None + self._about_process: Any | None = None + self._starting = False + self._start_done = asyncio.Event() + self._replay_repeater = ReplayActionRepeater() + self._replay_repeat_active = False + self._window_mode: str | None = None + self._stable_session_mode: str | None = None + self._resume_in_progress = False + + self.state_text = ft.Text("", weight=ft.FontWeight.BOLD) + self.source_dropdown = ft.Dropdown( + label="NDI source", options=[], width=440, on_select=self._on_source_select + ) + self.refresh_button = ft.FilledButton(content="Refresh", on_click=self._on_refresh) + self.start_button = ft.FilledButton(content="Start Recording", on_click=self._on_start) + self.mode_button = ft.FilledButton(content="Replay", on_click=self._on_mode_button) + + self.replay_fps_text = ft.Text(_EMPTY) + + # Replay panel (only visible while replaying). + self._seek_drag = SeekDrag() + self.replay_position_text = ft.Text(_EMPTY) + self.replay_slider = ft.Slider( + min=0, + max=1, + value=0, + on_change_start=self._on_seek_start, + on_change=self._on_seek_change, + on_change_end=self._on_seek_end, + ) + self.replay_play_button = self._transport_button("Play", self._on_play_pause) + self.replay_back20_button, self.replay_back20_gesture = self._repeat_button( + "-20f", + lambda: self.session.seek_frames(-REPLAY_FAST_MOVE_FRAMES), + REPLAY_REPEAT_FAST_INTERVAL_SECONDS, + ) + self.replay_back1_button, self.replay_back1_gesture = self._repeat_button( + "-1f", self.session.step_backward, REPLAY_REPEAT_FRAME_INTERVAL_SECONDS + ) + self.replay_forward1_button, self.replay_forward1_gesture = self._repeat_button( + "+1f", self.session.step_forward, REPLAY_REPEAT_FRAME_INTERVAL_SECONDS + ) + self.replay_forward20_button, self.replay_forward20_gesture = self._repeat_button( + "+20f", + lambda: self.session.seek_frames(REPLAY_FAST_MOVE_FRAMES), + REPLAY_REPEAT_FAST_INTERVAL_SECONDS, + ) + self.set_point_text = ft.Text(_EMPTY) + self.time_difference_text = ft.Text(_EMPTY) + self.frame_difference_text = ft.Text(_EMPTY) + self.set_point_button = ft.FilledButton(content="Set Point", on_click=self._on_set_point) + self.replay_panel = ft.Column( + controls=[ + ft.Row(controls=[self.replay_position_text, ft.Text("·"), self.replay_fps_text]), + self.replay_slider, + ft.Row( + controls=[ + self.replay_back20_gesture, + self.replay_back1_gesture, + self.replay_play_button, + self.replay_forward1_gesture, + self.replay_forward20_gesture, + ], + spacing=REPLAY_TRANSPORT_SPACING, + ), + ft.Row( + controls=[self.time_difference_text, ft.Text("·"), self.frame_difference_text] + ), + self.set_point_button, + ], + spacing=10, + width=REPLAY_CONTENT_WIDTH, + visible=False, + ) + + self.input_section = ft.Column( + controls=[ + ft.Text("Input", weight=ft.FontWeight.BOLD), + ft.Row(controls=[self.source_dropdown, self.refresh_button]), + ], + spacing=10, + ) + self.recording_status_text = ft.Text("", color=ft.Colors.BLUE_GREY) + self.recording_section = ft.Column( + controls=[self.recording_status_text], spacing=4, tight=True + ) + + # Setup settings fields (validation and persistence remain in UiSession). + self.settings_buffer_field = ft.TextField(label="Buffer duration", width=180) + self.settings_mpv_field = ft.TextField(label="mpv executable") + self.settings_error_text = ft.Text("", color=ft.Colors.RED, visible=False) + self.setup_status_text = ft.Text("", color=ft.Colors.BLUE_GREY, visible=False) + self.setup_error_text = ft.Text("", color=ft.Colors.RED, visible=False) + self.settings_apply_button = ft.FilledButton( + content="Apply", on_click=self._on_settings_apply + ) + self.about_button = ft.IconButton( + icon=ft.Icons.INFO_OUTLINE, + tooltip="About", + on_click=self._on_about, + ) + + self.setup_button = ft.IconButton( + icon=ft.Icons.ARROW_BACK, + tooltip="Setup", + on_click=self._on_setup, + ) + recording_settings = ft.Column( + controls=[ + ft.Text("Recording", weight=ft.FontWeight.BOLD), + ft.Row(controls=[self.settings_buffer_field, ft.Text("seconds")]), + ], + spacing=6, + tight=True, + expand=True, + ) + replay_settings = ft.Column( + controls=[ + ft.Text("Replay", weight=ft.FontWeight.BOLD), + self.settings_mpv_field, + ], + spacing=6, + tight=True, + expand=True, + horizontal_alignment=ft.CrossAxisAlignment.STRETCH, + ) + self.settings_row = ft.Row( + controls=[recording_settings, replay_settings], + spacing=24, + vertical_alignment=ft.CrossAxisAlignment.START, + ) + self.settings_restart_note = ft.Text( + "Restart required after changing these settings", italic=True + ) + self.setup_body = ft.Column( + controls=[ + self.input_section, + ft.Divider(), + self.settings_row, + self.settings_restart_note, + self.settings_error_text, + self.setup_status_text, + self.setup_error_text, + ], + spacing=6, + expand=True, + scroll=ft.ScrollMode.AUTO, + ) + left_actions = ft.Container( + expand=True, + content=ft.Row( + controls=[self.about_button], + alignment=ft.MainAxisAlignment.START, + ), + ) + right_actions = ft.Row( + controls=[self.settings_apply_button, self.start_button], + alignment=ft.MainAxisAlignment.END, + spacing=8, + expand=True, + ) + self.setup_actions = ft.Row( + controls=[left_actions, right_actions], + spacing=self.settings_row.spacing, + height=52, + ) + self.setup_section = ft.Column( + controls=[self.setup_body, self.setup_actions], spacing=4, expand=True + ) + self.session_section = ft.Column( + controls=[ + ft.Row( + controls=[ + ft.Row(controls=[self.setup_button, self.mode_button]), + self.state_text, + ], + alignment=ft.MainAxisAlignment.SPACE_BETWEEN, + vertical_alignment=ft.CrossAxisAlignment.CENTER, + ), + self.recording_section, + self.replay_panel, + ], + spacing=4, + tight=True, + ) + + self.status_text = ft.Text("", color=ft.Colors.BLUE_GREY) + self.error_text = ft.Text("", color=ft.Colors.RED) + + self.footer = ft.Column(controls=[self.status_text, self.error_text], spacing=4, tight=True) + self.control = ft.Column( + controls=[self.setup_section, self.session_section, self.footer], + spacing=4, + expand=True, + ) + self._populate_settings_fields() + + # -- lifecycle --------------------------------------------------------- + @property + def lifecycle(self) -> ViewLifecycle: + """The current view lifecycle state.""" + return self._lifecycle + + @property + def is_active(self) -> bool: + """Whether the view still accepts UI work and page updates.""" + return self._lifecycle is ViewLifecycle.RUNNING and not self._session_lost + + async def start(self) -> None: + """Start the application and render the first frame. + + If starting fails, the partially created core resources are shut down + before the error propagates, so no worker or executor is leaked. A + close requested while starting waits for this to finish. + """ + if not self.is_active: + return + self._starting = True + try: + await self.session.start() + except Exception: + self._starting = False + self._start_done.set() + await self.close(destroy_window=False) + raise + else: + self._starting = False + self._start_done.set() + self._populate_settings_fields() + await self._render_and_update() + + def start_polling(self) -> None: + """Start the background poll task (idempotent, RUNNING only).""" + if not self.is_active or self._poll_task is not None: + return + self.page.run_task(self._poll_entry) + + async def _poll_entry(self) -> None: + self._poll_task = asyncio.current_task() + try: + await self.poll_loop() + finally: + self._poll_task = None + + async def poll_loop(self) -> None: + try: + while self.is_active: + try: + await self.session.poll() + except Exception as exc: # noqa: BLE001 - surface poll failures in the UI + if not self.is_active: + break + self.session.note_error(f"UI poll failed: {exc}") + if not self.is_active: + break + state = self.session.view_state() + self.render(state) + if not self._update_page(): + break + interval = ( + POLL_INTERVAL_REPLAY_SECONDS + if state.state is ApplicationState.REPLAY + else POLL_INTERVAL_SECONDS + ) + await asyncio.sleep(interval) + except asyncio.CancelledError: + # Explicit cancellation is the normal way to stop polling; it is + # not a UI error. + pass + finally: + if self._session_lost: + await self.close(destroy_window=False) + + def on_window_event(self, event: ft.WindowEvent) -> None: + if getattr(event, "type", None) == ft.WindowEventType.CLOSE: + self._launch_close(destroy_window=True) + + def on_page_disconnect(self, *_args: object) -> None: + """Supplementary cleanup trigger for Flet session disconnects. + + The primary desktop path is :meth:`on_window_event`; this only exists + because Flet may report a client disconnect first. + """ + self._session_lost = True + self._launch_close(destroy_window=False) + + async def close(self, *, destroy_window: bool = True) -> None: + """Shut the application down once, then optionally destroy the window. + + Core cleanup (session/bridge/controller/worker/mpv) and the Flet window + destruction are separate phases: a lost session skips the window step. + Repeated or concurrent calls are no-ops after the first one starts. + """ + if self._lifecycle is not ViewLifecycle.RUNNING: + return + self._lifecycle = ViewLifecycle.CLOSING + errors: list[Exception] = [] + try: + await self._replay_repeater.stop() + if self._starting and not self._start_done.is_set(): + # Never tear the core down in the middle of a start. + await self._start_done.wait() + try: + await self._stop_polling() + except Exception as exc: # noqa: BLE001 - keep cleaning up + errors.append(exc) + try: + await self.session.shutdown() + except Exception as exc: # noqa: BLE001 - keep cleaning up + errors.append(exc) + try: + await self._stop_about_process() + except Exception as exc: # noqa: BLE001 - continue window teardown + errors.append(exc) + finally: + self._lifecycle = ViewLifecycle.CLOSED + if destroy_window: + try: + await self._destroy_window() + except Exception as exc: # noqa: BLE001 - core cleanup already done + errors.append(exc) + if errors: + raise errors[0] + + async def _stop_polling(self) -> None: + task = self._poll_task + if task is None or task.done(): + return + if task is asyncio.current_task(): + # The poll loop itself initiated the close; it finishes on return. + return + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + async def _stop_about_process(self) -> None: + process = self._about_process + self._about_process = None + if process is None: + return + if process.poll() is not None: + return + try: + await asyncio.to_thread(process.wait, timeout=2.0) + return + except subprocess.TimeoutExpired: + pass + process.terminate() + try: + await asyncio.to_thread(process.wait, timeout=1.0) + return + except subprocess.TimeoutExpired: + process.kill() + await asyncio.to_thread(process.wait, timeout=1.0) + if process.poll() is None: + raise RuntimeError("About process did not exit during application shutdown") + + async def _destroy_window(self) -> None: + if self._session_lost: + return + try: + await self.page.window.destroy() + except RuntimeError as exc: + if not is_destroyed_session_error(exc): + raise + self._session_lost = True + + def _launch_close(self, *, destroy_window: bool) -> None: + if self._lifecycle is not ViewLifecycle.RUNNING or self._close_started: + return + self._close_started = True + try: + self.page.run_task(self.close, destroy_window=destroy_window) + except RuntimeError as exc: + if not is_destroyed_session_error(exc): + raise + self._session_lost = True + asyncio.ensure_future(self.close(destroy_window=False)) + + # -- page access ------------------------------------------------------- + def _update_page(self) -> bool: + """Update the page unless closing/closed. + + A destroyed Flet session is treated as a lifecycle event: the view + stops accepting work and the caller (poll loop / action helper) runs + the core shutdown. Any other ``RuntimeError`` propagates. + """ + if not self.is_active: + return False + try: + self.page.update() + except RuntimeError as exc: + if not is_destroyed_session_error(exc): + raise + self._session_lost = True + self._launch_close(destroy_window=False) + return False + return True + + def _refresh_view(self) -> None: + """Render and update from a synchronous handler.""" + if not self.is_active: + return + self.render(self.session.view_state()) + if not self._update_page() and self._session_lost: + self._launch_close(destroy_window=False) + + def _run_task(self, handler: Callable[..., Awaitable[None]], *args: object) -> None: + """Launch an async UI action unless the view is closing/closed.""" + if not self.is_active: + return + try: + self.page.run_task(handler, *args) + except RuntimeError as exc: + if not is_destroyed_session_error(exc): + raise + self._session_lost = True + self._launch_close(destroy_window=False) + + async def _render_and_update(self) -> None: + """Render after an action, or run core cleanup if the session was lost.""" + if not self.is_active: + if self._session_lost: + await self.close(destroy_window=False) + return + self.render(self.session.view_state()) + if not self._update_page() and self._session_lost: + await self.close(destroy_window=False) + + async def _run_action(self, operation: Callable[[], Awaitable[None]]) -> None: + """Run an async UI action and refresh the view only while running.""" + if not self.is_active: + return + await operation() + await self._render_and_update() + + # -- rendering --------------------------------------------------------- + def render(self, state: UiViewState) -> None: + self._update_window_size(state.state) + if not state.replay_active: + self._replay_repeater.release() + self._replay_repeat_active = False + self.state_text.value = ( + "Starting..." + if self._resume_in_progress + else "● REC" + if state.state is ApplicationState.RECORDING + else "● REPLAY" + if state.state is ApplicationState.REPLAY + else state.state_label + ) + self.state_text.animate_opacity = 500 if state.state is ApplicationState.RECORDING else None + self.state_text.opacity = ( + 1.0 + if int(time.monotonic() * 2) % 2 == 0 + else 0.55 + if state.state is ApplicationState.RECORDING + else 1.0 + ) + + self.source_dropdown.options = [ + ft.DropdownOption(key=option.key, text=option.label) for option in state.input_options + ] + self.source_dropdown.value = state.selected_key + self.source_dropdown.disabled = not state.controls.input_enabled + + self.refresh_button.content = "Discovering..." if state.discovering else "Refresh" + self.refresh_button.disabled = not state.controls.refresh_enabled + self.start_button.disabled = not state.controls.start_enabled + setup_visible = state.state in (ApplicationState.IDLE, ApplicationState.STARTING) + self.setup_section.visible = setup_visible + self.about_button.disabled = state.state is not ApplicationState.IDLE + self.session_section.visible = not setup_visible + self.input_section.visible = setup_visible + self.recording_section.visible = state.state is ApplicationState.RECORDING + session_disabled = state.state is ApplicationState.STOPPING + + if state.state is ApplicationState.RECORDING: + self._stable_session_mode = "recording" + elif state.state is ApplicationState.REPLAY: + self._stable_session_mode = "replay" + stable_mode = self._stable_session_mode or "recording" + self.mode_button.content = "Record" if stable_mode == "replay" else "Replay" + session_disabled = session_disabled or self._resume_in_progress + self.mode_button.disabled = session_disabled or state.state not in ( + ApplicationState.RECORDING, + ApplicationState.REPLAY, + ) + self.setup_button.disabled = session_disabled or state.state not in ( + ApplicationState.RECORDING, + ApplicationState.REPLAY, + ) + + self._render_replay(state.replay) + if self._resume_in_progress: + self.replay_panel.visible = False + self.replay_play_button.disabled = session_disabled or self.replay_play_button.disabled + self.set_point_button.disabled = session_disabled or self.set_point_button.disabled + self.replay_slider.disabled = session_disabled or self.replay_slider.disabled + for gesture in ( + self.replay_back20_gesture, + self.replay_back1_gesture, + self.replay_forward1_gesture, + self.replay_forward20_gesture, + ): + gesture.disabled = session_disabled + + metrics = state.metrics + if metrics: + drops = ( + f" · ⚠ Drops V:{metrics.video_drops} A:{metrics.audio_drops}" + if metrics.has_drops + else "" + ) + self.recording_status_text.value = ( + f"Input {metrics.input_fps} · Rec {metrics.recording_fps} fps · " + f"Seg {metrics.segments} · Buf {metrics.buffer}{drops}" + ) + else: + self.recording_status_text.value = "" + + status_message = None if state.discovering else state.status_message + self.status_text.value = status_message or "" + self.status_text.visible = bool(status_message) + self.error_text.value = state.error_message or "" + self.error_text.visible = bool(state.error_message) + self.setup_status_text.value = status_message or "" + self.setup_status_text.visible = bool(status_message) + self.setup_error_text.value = state.error_message or "" + self.setup_error_text.visible = bool(state.error_message) + self.footer.visible = bool(status_message or state.error_message) and not setup_visible + + def _update_window_size(self, state: ApplicationState) -> None: + if state in (ApplicationState.IDLE, ApplicationState.STARTING): + self._resume_in_progress = False + mode = "setup" + elif state is ApplicationState.RECORDING: + self._resume_in_progress = False + self._stable_session_mode = "recording" + mode = "recording" + elif state is ApplicationState.REPLAY: + if self._resume_in_progress: + mode = "recording" + else: + self._stable_session_mode = "replay" + mode = "replay" + elif state is ApplicationState.RESUMING: + self._resume_in_progress = True + mode = "recording" + elif state is ApplicationState.ERROR: + self._resume_in_progress = False + mode = "replay" if self._stable_session_mode == "replay" else "recording" + elif self._stable_session_mode == "replay": + mode = "replay" + else: + mode = "recording" + if mode == self._window_mode: + return + self._window_mode = mode + if not hasattr(self.page, "window"): + return + size = WINDOW_SIZES[mode] + self.page.window.width, self.page.window.height = size + + def _render_replay(self, replay: ReplayView | None) -> None: + self.replay_panel.visible = replay is not None + if replay is None: + self._seek_drag = SeekDrag() + return + + if self._seek_drag.active: + preview_ns = self._seek_drag.preview_ns or 0 + self.replay_position_text.value = ( + f"{format_duration_ns(preview_ns)} / {replay.duration_text}" + ) + else: + self.replay_position_text.value = f"{replay.position_text} / {replay.duration_text}" + duration_seconds = replay.duration_ns / _NANOSECONDS_PER_SECOND + self.replay_slider.max = duration_seconds if duration_seconds > 0 else 0 + self.replay_slider.value = replay.position_ns / _NANOSECONDS_PER_SECOND + + duration_seconds = replay.duration_ns / _NANOSECONDS_PER_SECOND + self.replay_slider.disabled = duration_seconds <= 0 or self._replay_repeat_active + self.replay_fps_text.value = f"{replay.fps_text} fps" + cast(ft.Text, self.replay_play_button.content).value = "Play" if replay.paused else "Pause" + self.replay_play_button.disabled = self._replay_repeat_active + self.set_point_button.disabled = self._replay_repeat_active + self.set_point_text.value = replay.set_point_text + self.time_difference_text.value = replay.time_difference_text + self.frame_difference_text.value = replay.frame_difference_text + + def _transport_button( + self, + label: str, + on_click: Callable[[ft.Event], None] | None = None, + ) -> ft.Container: + return ft.Container( + content=ft.Text( + label, + color=ft.Colors.ON_PRIMARY, + size=14, + text_align=ft.TextAlign.CENTER, + ), + width=REPLAY_TRANSPORT_BUTTON_WIDTH, + height=REPLAY_TRANSPORT_BUTTON_HEIGHT, + alignment=ft.Alignment.CENTER, + bgcolor=ft.Colors.PRIMARY, + padding=0, + border_radius=ft.BorderRadius(top_left=4, top_right=4, bottom_left=4, bottom_right=4), + on_click=on_click, + ) + + def _repeat_button( + self, label: str, action: Callable[[], Awaitable[None]], interval: float + ) -> tuple[ft.Container, ft.GestureDetector]: + button = self._transport_button(label) + gesture = ft.GestureDetector( + content=button, + on_tap=lambda _event: self._run_task(self._run_replay_action_async, action), + on_long_press_start=lambda _event: self._start_replay_repeat(action, interval), + on_long_press_end=lambda _event: self._stop_replay_repeat(), + on_long_press_cancel=lambda _event: self._stop_replay_repeat(), + ) + return button, gesture + + def _start_replay_repeat(self, action: Callable[[], Awaitable[None]], interval: float) -> None: + self._replay_repeater.start( + lambda: self._run_replay_action_async(action), + interval=interval, + ) + self._replay_repeat_active = True + self._refresh_replay_controls() + + def _stop_replay_repeat(self) -> None: + self._replay_repeater.release() + self._replay_repeat_active = False + self._refresh_replay_controls() + + def _refresh_replay_controls(self) -> None: + disabled = self._replay_repeat_active + self.replay_play_button.disabled = disabled + self.set_point_button.disabled = disabled + self.replay_slider.disabled = disabled + + async def _run_replay_action_async(self, action: Callable[[], Awaitable[None]]) -> None: + if self.is_active: + await action() + + # -- action handlers --------------------------------------------------- + def _on_source_select(self, event: ft.Event) -> None: + if not self.is_active: + return + self.session.select(self.source_dropdown.value) + self._refresh_view() + + def _on_about(self, event: ft.Event) -> None: + if not self.is_active: + return + if self.session.view_state().state is not ApplicationState.IDLE: + return + if self._about_process is not None: + if self._about_process.poll() is None: + return + + is_packaged = Path(sys.argv[0]).suffix.casefold() == ".exe" + command = ( + [sys.executable, "--quickreplay-about"] + if is_packaged + else [sys.executable, "-m", "quickreplay.ui.about_window"] + ) + self._about_process = subprocess.Popen(command) + + def _on_refresh(self, event: ft.Event) -> None: + self._run_task(self._refresh) + + async def _refresh(self) -> None: + await self._run_action(self.session.refresh) + + def _on_start(self, event: ft.Event) -> None: + self._run_task(self._start) + + async def _start(self) -> None: + await self._run_action(self.session.start_recording) + + def _on_mode_button(self, event: ft.Event) -> None: + self._stop_replay_repeat() + self._run_task(self._switch_session_mode) + + async def _switch_session_mode(self) -> None: + state = self.session.view_state().state + if state is ApplicationState.RECORDING: + await self._run_action(self.session.request_replay) + elif state is ApplicationState.REPLAY: + self._resume_in_progress = True + self._update_window_size(ApplicationState.RESUMING) + self._refresh_view() + try: + await self._run_action(self.session.resume_recording) + except Exception: + self._resume_in_progress = False + self._refresh_view() + raise + + # -- replay handlers --------------------------------------------------- + def _run_replay_action(self, action: str, frames: int | None = None) -> None: + self._run_task(self._do_replay_action, action, frames) + + async def _do_replay_action(self, action: str, frames: int | None) -> None: + if not self.is_active: + return + if action == "seek" and frames is not None: + await self.session.seek_frames(frames) + elif action == "step_forward": + await self.session.step_forward() + elif action == "step_backward": + await self.session.step_backward() + await self._render_and_update() + + def _on_play_pause(self, event: ft.Event) -> None: + self._run_task(self._do_play_pause) + + async def _do_play_pause(self) -> None: + await self._run_action(self.session.toggle_play_pause) + + def _on_set_point(self, event: ft.Event) -> None: + self._run_task(self._do_set_point) + + async def _do_set_point(self) -> None: + await self._run_action(self.session.set_replay_point) + + def _on_seek_start(self, event: ft.Event) -> None: + if not self.is_active: + return + # While dragging, poll must not move the thumb. + self._seek_drag.start(self.replay_slider.value or 0) + + def _on_seek_change(self, event: ft.Event) -> None: + if not self.is_active: + return + # Preview only; no seek command is sent while dragging. + self._seek_drag.update_preview(self.replay_slider.value or 0) + self._refresh_view() + + def _on_seek_end(self, event: ft.Event) -> None: + if not self.is_active: + # A close during the drag discards the pending seek. + return + target_ns = self._seek_drag.end(self.replay_slider.value or 0) + self._run_task(self._do_seek_absolute, target_ns) + + async def _do_seek_absolute(self, target_ns: int) -> None: + await self._run_action(lambda: self.session.seek_absolute_ns(target_ns)) + + # -- settings handlers ------------------------------------------------- + def _on_setup(self, event: ft.Event) -> None: + self._stop_replay_repeat() + self._run_task(self._stop_session) + + async def _stop_session(self) -> None: + await self.session.stop_session() + await self._render_and_update() + + def _populate_settings_fields(self) -> None: + draft = self.session.settings_draft() + self.settings_buffer_field.value = draft.buffer_duration_seconds + self.settings_mpv_field.value = draft.mpv_executable + self.settings_error_text.value = "" + self.settings_error_text.visible = False + + def _settings_draft(self) -> SettingsDraft: + return SettingsDraft( + buffer_duration_seconds=self.settings_buffer_field.value or "", + mpv_executable=self.settings_mpv_field.value or "", + ) + + def _on_settings_apply(self, event: ft.Event) -> None: + self._run_task(self._apply_settings) + + async def _apply_settings(self) -> None: + if not self.is_active: + return + draft = self._settings_draft() + self.settings_apply_button.disabled = True + self._update_page() + try: + result = await self.session.apply_settings(draft) + finally: + if self.is_active: + self.settings_apply_button.disabled = False + if not self.is_active: + # A close began while the configuration was saving: the dialog is + # gone with the session and the draft is discarded, never applied. + return + if result.ok: + self.settings_error_text.value = "" + self.settings_error_text.visible = False + self.render(self.session.view_state()) + else: + messages = [error.message for error in result.errors] + if result.message: + messages.insert(0, result.message) + self.settings_error_text.value = "\n".join(messages) + self.settings_error_text.visible = bool(self.settings_error_text.value) + self._update_page() diff --git a/src/quickreplay/ui/paths.py b/src/quickreplay/ui/paths.py new file mode 100644 index 0000000..ace7148 --- /dev/null +++ b/src/quickreplay/ui/paths.py @@ -0,0 +1,56 @@ +"""Flet storage path resolution. + +Durable configuration lives under ``FLET_APP_STORAGE_DATA``; regenerable runtime +data (segment buffer, replay assets) lives under ``FLET_APP_STORAGE_CACHE``. +The production resolver never falls back to the current working directory. +""" + +import os +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path + +DATA_ENVIRONMENT_VARIABLE = "FLET_APP_STORAGE_DATA" +CACHE_ENVIRONMENT_VARIABLE = "FLET_APP_STORAGE_CACHE" + + +class StoragePathError(RuntimeError): + """The Flet storage directories could not be resolved.""" + + +@dataclass(frozen=True, slots=True) +class StoragePaths: + """Resolved durable and cache directories.""" + + data_directory: Path + cache_directory: Path + + @property + def config_path(self) -> Path: + """Path of the durable ``config.json``.""" + return self.data_directory / "config.json" + + @property + def runtime_directory(self) -> Path: + """Working directory for the recorder buffer and replay assets.""" + return self.cache_directory / "runtime" + + +def resolve_storage_paths(*, data_directory: Path, cache_directory: Path) -> StoragePaths: + """Build storage paths from explicit directories (used by tests and bootstrap).""" + return StoragePaths(data_directory=Path(data_directory), cache_directory=Path(cache_directory)) + + +def storage_paths_from_environment( + environ: Mapping[str, str] | None = None, +) -> StoragePaths: + """Resolve storage paths from the Flet storage environment variables.""" + source = os.environ if environ is None else environ + data = source.get(DATA_ENVIRONMENT_VARIABLE) + cache = source.get(CACHE_ENVIRONMENT_VARIABLE) + if not data or not cache: + raise StoragePathError( + "could not resolve storage directories: " + f"{DATA_ENVIRONMENT_VARIABLE} and {CACHE_ENVIRONMENT_VARIABLE} must be set" + ) + return resolve_storage_paths(data_directory=Path(data), cache_directory=Path(cache)) diff --git a/src/quickreplay/ui/presentation.py b/src/quickreplay/ui/presentation.py new file mode 100644 index 0000000..312f059 --- /dev/null +++ b/src/quickreplay/ui/presentation.py @@ -0,0 +1,172 @@ +"""Pure presentation helpers: domain values to display text and control states. + +Nothing here imports Flet. Display formatting may use floats, but the domain +values (:class:`~fractions.Fraction`, nanoseconds) stay the source of truth. +""" + +from dataclasses import dataclass +from fractions import Fraction + +from quickreplay.app.state import ApplicationState +from quickreplay.input.models import StreamInfo +from quickreplay.recording.models import RecordingMetrics +from quickreplay.units import NANOSECONDS_PER_SECOND + +_EMPTY = "—" + +_STATE_LABELS: dict[ApplicationState, str] = { + ApplicationState.STARTING: "Starting", + ApplicationState.IDLE: "Idle", + ApplicationState.RECORDING: "Recording", + ApplicationState.PREPARING_REPLAY: "Preparing Replay", + ApplicationState.REPLAY: "Replay", + ApplicationState.STOPPING: "Stopping", + ApplicationState.RESUMING: "Resuming", + ApplicationState.ERROR: "Error", + ApplicationState.SHUTTING_DOWN: "Shutting Down", +} + + +def state_label(state: ApplicationState) -> str: + """Human-readable label for an application state.""" + return _STATE_LABELS[state] + + +def format_fps(fps: Fraction) -> str: + """Format a frame rate for display (``60``, ``59.94``, ``29.97``).""" + if fps.denominator == 1: + return str(fps.numerator) + return f"{float(fps):.2f}" + + +def format_stream_info(stream_info: StreamInfo | None) -> str: + """Format the video stream summary line.""" + if stream_info is None: + return _EMPTY + video = stream_info.video + return f"{video.width} × {video.height} | {format_fps(video.fps)} fps | {video.pixel_format}" + + +def format_audio(stream_info: StreamInfo | None) -> str: + """Format the audio summary line.""" + if stream_info is None: + return _EMPTY + audio = stream_info.audio + if audio is None: + return "Audio: None" + if audio.channels == 1: + layout = "Mono" + elif audio.channels == 2: + layout = "Stereo" + else: + layout = f"{audio.channels} ch" + return f"Audio: {audio.sample_rate / 1000:g} kHz / {layout}" + + +def format_buffer(current_ns: int, maximum_seconds: int) -> str: + """Format the buffer usage as ``current / maximum s``.""" + return f"{current_ns / NANOSECONDS_PER_SECOND:.1f} / {maximum_seconds} s" + + +def format_duration_ns(value_ns: int) -> str: + """Format nanoseconds as ``MM:SS.mmm`` (or ``H:MM:SS.mmm`` for long values).""" + total_ms = abs(value_ns) // 1_000_000 + millis = total_ms % 1000 + total_seconds = total_ms // 1000 + seconds = total_seconds % 60 + total_minutes = total_seconds // 60 + minutes = total_minutes % 60 + hours = total_minutes // 60 + if hours: + return f"{hours}:{minutes:02d}:{seconds:02d}.{millis:03d}" + return f"{minutes:02d}:{seconds:02d}.{millis:03d}" + + +def format_signed_duration_ns(value_ns: int) -> str: + """Format a signed duration: ``+00:00.750`` / ``-00:00.750`` / ``00:00.000``.""" + if value_ns > 0: + return f"+{format_duration_ns(value_ns)}" + if value_ns < 0: + return f"-{format_duration_ns(value_ns)}" + return format_duration_ns(0) + + +def format_signed_frames(value: int) -> str: + """Format a frame difference: ``+45`` / ``-12`` / ``0``.""" + if value > 0: + return f"+{value}" + return str(value) + + +def buffer_fraction(current_ns: int, maximum_seconds: int) -> float: + """Buffer usage clamped to ``0.0 .. 1.0``.""" + if maximum_seconds <= 0: + return 0.0 + value = (current_ns / NANOSECONDS_PER_SECOND) / maximum_seconds + return min(1.0, max(0.0, value)) + + +@dataclass(frozen=True, slots=True) +class MetricsView: + """Display-ready recording metrics.""" + + input_fps: str + recording_fps: str + buffer: str + buffer_fraction: float + segments: str + drops: str + video_drops: int + audio_drops: int + has_drops: bool + + +def metrics_view( + metrics: RecordingMetrics | None, *, buffer_max_seconds: int +) -> MetricsView | None: + """Build a :class:`MetricsView`, or ``None`` when no metrics are available.""" + if metrics is None: + return None + return MetricsView( + input_fps=f"{metrics.input_fps:.1f}", + recording_fps=f"{metrics.recording_fps:.1f}", + buffer=format_buffer(metrics.buffer_duration_ns, buffer_max_seconds), + buffer_fraction=buffer_fraction(metrics.buffer_duration_ns, buffer_max_seconds), + segments=str(metrics.segment_count), + drops=f"Video {metrics.video_queue_drops} / Audio {metrics.audio_queue_drops}", + video_drops=metrics.video_queue_drops, + audio_drops=metrics.audio_queue_drops, + has_drops=metrics.video_queue_drops > 0 or metrics.audio_queue_drops > 0, + ) + + +@dataclass(frozen=True, slots=True) +class ControlState: + """Which actions the UI should offer for the current state.""" + + input_enabled: bool + refresh_enabled: bool + start_enabled: bool + replay_enabled: bool + resume_enabled: bool + settings_enabled: bool + discovering: bool + + +def control_state( + state: ApplicationState, *, has_selection: bool, discovering: bool +) -> ControlState: + """Derive control enablement from the application state.""" + idle = state == ApplicationState.IDLE + recording = state == ApplicationState.RECORDING + replay = state == ApplicationState.REPLAY + discovery_allowed = idle or recording or replay + return ControlState( + input_enabled=idle, + refresh_enabled=discovery_allowed and not discovering, + start_enabled=idle and has_selection and not discovering, + replay_enabled=recording, + resume_enabled=replay, + settings_enabled=state != ApplicationState.SHUTTING_DOWN, + discovering=discovering, + ) diff --git a/src/quickreplay/ui/replay_repeat.py b/src/quickreplay/ui/replay_repeat.py new file mode 100644 index 0000000..a18a36e --- /dev/null +++ b/src/quickreplay/ui/replay_repeat.py @@ -0,0 +1,57 @@ +"""Async press-and-hold repetition for Replay frame actions.""" + +import asyncio +from collections.abc import Awaitable, Callable + +Action = Callable[[], Awaitable[None]] +Sleep = Callable[[float], Awaitable[None]] + + +class ReplayActionRepeater: + """Run an action immediately and repeat it until released.""" + + def __init__(self, *, sleep: Sleep = asyncio.sleep) -> None: + self._sleep = sleep + self._task: asyncio.Task[None] | None = None + self._held = False + + @property + def active(self) -> bool: + return self._task is not None and not self._task.done() and self._held + + def start(self, action: Action, *, interval: float) -> None: + self.release() + self._held = True + self._task = asyncio.create_task(self._run(action, interval=interval)) + + def release(self) -> None: + """Stop future repetitions without interrupting the current action.""" + self._held = False + + def cancel(self) -> None: + """Cancel the task immediately for application shutdown.""" + self._held = False + if self._task is not None: + self._task.cancel() + self._task = None + + async def stop(self) -> None: + task = self._task + self._task = None + self._held = False + if task is None: + return + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + async def _run(self, action: Action, *, interval: float) -> None: + await action() + if not self._held: + return + while self._held: + await self._sleep(interval) + if self._held: + await action() diff --git a/src/quickreplay/ui/session.py b/src/quickreplay/ui/session.py new file mode 100644 index 0000000..3f94113 --- /dev/null +++ b/src/quickreplay/ui/session.py @@ -0,0 +1,509 @@ +"""Flet-independent UI session logic. + +:class:`UiSession` holds the UI's own state (selected input, discovery +correlation, transient status) and drives the application through +:class:`~quickreplay.ui.bridge.ApplicationUiBridge`. It contains no Flet +imports so it can be tested headlessly. +""" + +import asyncio +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, replace +from typing import Protocol +from uuid import UUID + +from quickreplay.app.state import ApplicationState +from quickreplay.application.events import ( + ApplicationError, + ApplicationEvent, + InputsChanged, + RecordingStarted, +) +from quickreplay.application.models import ApplicationSnapshot +from quickreplay.configuration.errors import ConfigurationError +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.input.models import ( + InputConfig, + InputDescriptor, + NdiInputConfig, +) +from quickreplay.replay.errors import MpvProcessExitedError +from quickreplay.replay.models import SetPoint +from quickreplay.ui.presentation import ( + ControlState, + MetricsView, + control_state, + format_audio, + format_duration_ns, + format_fps, + format_signed_duration_ns, + format_signed_frames, + format_stream_info, + metrics_view, + state_label, +) +from quickreplay.ui.settings import ( + SettingsApplyResult, + SettingsDraft, + apply_message, + build_settings_config, + draft_from_config, + restart_required, +) + +NDI_KIND = "ndi" + + +class BridgeLike(Protocol): + """The async bridge operations the UI session needs.""" + + async def start(self) -> None: ... + + async def start_recording(self, input_config: InputConfig) -> None: ... + + async def discover_inputs(self) -> UUID: ... + + async def request_replay(self) -> UUID: ... + + async def resume_recording(self) -> UUID: ... + + async def stop_session(self) -> UUID: ... + + async def poll(self, timeout: float = 0.0) -> tuple[ApplicationEvent, ...]: ... + + async def snapshot(self) -> ApplicationSnapshot: ... + + async def shutdown(self) -> None: ... + + async def close(self) -> None: ... + + # -- replay delegate --------------------------------------------------- + async def play(self) -> None: ... + + async def pause(self) -> None: ... + + async def is_paused(self) -> bool: ... + + async def step_forward(self) -> None: ... + + async def step_backward(self) -> None: ... + + async def seek_frames(self, frames: int) -> None: ... + + async def seek_absolute_ns(self, position_ns: int) -> None: ... + + async def replay_position_ns(self) -> int: ... + + async def set_point(self) -> SetPoint: ... + + async def time_difference_ns(self, point: SetPoint) -> int: ... + + async def frame_difference(self, point: SetPoint) -> int: ... + + +@dataclass(frozen=True, slots=True) +class InputOption: + """A selectable discovered input.""" + + key: str + label: str + descriptor: InputDescriptor + + +@dataclass(frozen=True, slots=True) +class ReplayView: + """Display-ready replay playback state (only populated while replaying).""" + + position_ns: int + duration_ns: int + paused: bool + position_text: str + duration_text: str + fps_text: str + set_point_text: str + time_difference_text: str + frame_difference_text: str + has_set_point: bool + action_pending: bool + + +@dataclass(frozen=True, slots=True) +class UiViewState: + """Everything the Flet view needs to render one frame.""" + + state: ApplicationState + state_label: str + stream_text: str + audio_text: str + metrics: MetricsView | None + controls: ControlState + status_message: str | None + error_message: str | None + replay_active: bool + replay: ReplayView | None + input_options: tuple[InputOption, ...] + selected_key: str | None + discovering: bool + + +def _option_key(descriptor: InputDescriptor) -> str: + return f"{NDI_KIND}:{descriptor.source_name}" + + +def _option_label(descriptor: InputDescriptor) -> str: + return descriptor.source_name + + +def _config_matches(configured: InputConfig, descriptor: InputDescriptor) -> bool: + return configured.source_name == descriptor.source_name + + +class UiSession: + """UI state and actions over an :class:`ApplicationUiBridge`.""" + + def __init__( + self, + bridge: BridgeLike, + store: ConfigurationStore, + config: QuickReplayConfig, + ) -> None: + self._bridge = bridge + self._store = store + self._config = config + + self._snapshot = ApplicationSnapshot(state=ApplicationState.STARTING) + self._descriptors: tuple[InputDescriptor, ...] = () + self._selected_key: str | None = None + self._pending_discovery_id: UUID | None = None + self._discovering = False + self._pending_start_input: InputConfig | None = None + self._status: str | None = None + self._error: str | None = None + + self._replay_position_ns: int | None = None + self._replay_paused: bool | None = None + self._frame_navigation_active = False + self._set_point: SetPoint | None = None + self._time_difference_ns: int | None = None + self._frame_difference: int | None = None + self._replay_action_pending = False + self._settings_applying = False + self._shutdown_task: asyncio.Task[None] | None = None + self._shutdown_complete = False + + # -- queries ----------------------------------------------------------- + @property + def config(self) -> QuickReplayConfig: + return self._config + + def view_state(self) -> UiViewState: + stream_info = self._snapshot.stream_info + has_selection = self.selected_option() is not None + return UiViewState( + state=self._snapshot.state, + state_label=state_label(self._snapshot.state), + stream_text=format_stream_info(stream_info), + audio_text=format_audio(stream_info), + metrics=metrics_view( + self._snapshot.metrics, + buffer_max_seconds=self._config.recording.buffer_duration_seconds, + ), + controls=control_state( + self._snapshot.state, + has_selection=has_selection, + discovering=self._discovering, + ), + status_message=self._status, + error_message=self._error or self._snapshot.error_message, + replay_active=self._snapshot.state == ApplicationState.REPLAY, + replay=self._replay_view(), + input_options=self._options(), + selected_key=self._selected_key, + discovering=self._discovering, + ) + + def selected_option(self) -> InputOption | None: + for option in self._options(): + if option.key == self._selected_key: + return option + return None + + def build_input_config(self) -> InputConfig | None: + """Build the domain input config for the current selection.""" + option = self.selected_option() + if option is None: + return None + descriptor = option.descriptor + return NdiInputConfig(descriptor.source_name) + + # -- actions ----------------------------------------------------------- + async def start(self) -> None: + await self._bridge.start() + await self.refresh() + + async def refresh(self) -> None: + self._discovering = True + self._status = "Discovering..." + self._pending_discovery_id = await self._bridge.discover_inputs() + + async def poll(self) -> None: + events = await self._bridge.poll() + for event in events: + self._handle_event(event) + previous_state = self._snapshot.state + self._snapshot = await self._bridge.snapshot() + if self._snapshot.state in (ApplicationState.IDLE, ApplicationState.ERROR): + self._pending_start_input = None + if self._snapshot.state == ApplicationState.REPLAY: + if previous_state != ApplicationState.REPLAY: + self._reset_replay_state() + await self.refresh_replay_status(refresh_pause=not self._frame_navigation_active) + elif previous_state == ApplicationState.REPLAY: + # Leaving replay clears the transient replay UI state. + self._reset_replay_state() + if self._snapshot.state != ApplicationState.ERROR: + self._error = None + + def select(self, key: str | None) -> None: + self._selected_key = key + + async def start_recording(self) -> None: + config = self.build_input_config() + if config is None: + return + self._error = None + self._status = None + self._reset_replay_state() + self._pending_start_input = config + await self._bridge.start_recording(config) + + async def request_replay(self) -> None: + await self._bridge.request_replay() + + async def resume_recording(self) -> None: + await self._bridge.resume_recording() + + async def stop_session(self) -> None: + await self._bridge.stop_session() + + async def shutdown(self) -> None: + """Shut the application down exactly once. + + Repeated and concurrent calls share a single shutdown task, so the + bridge/controller/worker are never torn down twice. + """ + if self._shutdown_complete: + return + if self._shutdown_task is None: + self._shutdown_task = asyncio.ensure_future(self._shutdown_bridge()) + await self._shutdown_task + self._shutdown_complete = True + + async def _shutdown_bridge(self) -> None: + await self._bridge.shutdown() + await self._bridge.close() + + def note_error(self, message: str) -> None: + """Record a UI-side error (for example a failed poll iteration).""" + self._error = message + + # -- settings ---------------------------------------------------------- + def settings_draft(self) -> SettingsDraft: + """Snapshot the persisted config and current selection into a draft.""" + return draft_from_config(self._config) + + async def apply_settings(self, draft: SettingsDraft) -> SettingsApplyResult: + """Validate and persist *draft*, replacing the session config on success. + + The candidate configuration is written first and the in-memory config is + only replaced after the store write succeeded, so a failed save never + leaves the session pointing at an unsaved configuration. + """ + if self._settings_applying: + return SettingsApplyResult(ok=False, message="Settings are already being applied") + self._settings_applying = True + try: + validation = build_settings_config(draft, self._config) + if validation.config is None: + return SettingsApplyResult(ok=False, errors=validation.errors) + candidate = validation.config + restart = restart_required(self._config, candidate) + try: + await asyncio.to_thread(self._store.save, candidate) + except ConfigurationError as exc: + return SettingsApplyResult(ok=False, message=f"Could not save settings: {exc}") + self._config = candidate + self._status = apply_message(restart=restart) + return SettingsApplyResult(ok=True, restart_required=restart, message=self._status) + finally: + self._settings_applying = False + + # -- replay actions ---------------------------------------------------- + async def toggle_play_pause(self) -> None: + """Toggle using the core pause state as the source of truth.""" + + async def action() -> None: + if self._replay_paused is True: + await self._bridge.play() + self._replay_paused = False + else: + await self._bridge.pause() + self._replay_paused = True + + self._frame_navigation_active = False + await self._run_replay_action(action) + + async def step_backward(self) -> None: + await self._run_frame_action(self._bridge.step_backward) + + async def step_forward(self) -> None: + await self._run_frame_action(self._bridge.step_forward) + + async def seek_frames(self, frames: int) -> None: + await self._run_frame_action(lambda: self._bridge.seek_frames(frames)) + + async def seek_absolute_ns(self, position_ns: int) -> None: + await self._run_replay_action(lambda: self._bridge.seek_absolute_ns(position_ns)) + + async def set_replay_point(self) -> None: + async def action() -> None: + self._set_point = await self._bridge.set_point() + + await self._run_replay_action(action) + + async def refresh_replay_status(self, *, refresh_pause: bool = True) -> None: + """Refresh position, pause state and differences while replaying.""" + if self._snapshot.state != ApplicationState.REPLAY: + return + try: + self._replay_position_ns = await self._bridge.replay_position_ns() + if refresh_pause and not self._frame_navigation_active: + self._replay_paused = await self._bridge.is_paused() + if self._set_point is not None: + self._time_difference_ns = await self._bridge.time_difference_ns(self._set_point) + self._frame_difference = await self._bridge.frame_difference(self._set_point) + except MpvProcessExitedError: + # The application controller already treats this as the replay + # ending; do not surface it as a UI error. + pass + except Exception as exc: # noqa: BLE001 - transient replay control error + self._error = f"Replay control failed: {exc}" + + async def _run_replay_action(self, action: Callable[[], Awaitable[None]]) -> None: + if self._replay_action_pending: + return + self._replay_action_pending = True + try: + await action() + except MpvProcessExitedError: + pass + except Exception as exc: # noqa: BLE001 - transient replay control error + self._error = f"Replay control failed: {exc}" + finally: + self._replay_action_pending = False + await self.refresh_replay_status() + + async def _run_frame_action(self, action: Callable[[], Awaitable[None]]) -> None: + """Pause playback before applying a frame-relative replay action.""" + + async def paused_action() -> None: + self._frame_navigation_active = True + if self._replay_paused is not True: + await self._bridge.pause() + self._replay_paused = True + await action() + + await self._run_replay_action(paused_action) + + # -- internals --------------------------------------------------------- + def _reset_replay_state(self) -> None: + self._replay_position_ns = None + self._replay_paused = None + self._frame_navigation_active = False + self._set_point = None + self._time_difference_ns = None + self._frame_difference = None + + def _replay_view(self) -> ReplayView | None: + if self._snapshot.state != ApplicationState.REPLAY: + return None + asset = self._snapshot.replay_asset + duration_ns = asset.duration_ns if asset is not None else 0 + position_ns = self._replay_position_ns if self._replay_position_ns is not None else 0 + set_point = self._set_point + return ReplayView( + position_ns=position_ns, + duration_ns=duration_ns, + paused=bool(self._replay_paused), + position_text=format_duration_ns(position_ns), + duration_text=format_duration_ns(duration_ns), + fps_text=format_fps(asset.fps) if asset is not None else "—", + set_point_text=format_duration_ns(set_point.position_ns) if set_point else "—", + time_difference_text=( + format_signed_duration_ns(self._time_difference_ns) + if self._time_difference_ns is not None + else "—" + ), + frame_difference_text=( + format_signed_frames(self._frame_difference) + if self._frame_difference is not None + else "—" + ), + has_set_point=set_point is not None, + action_pending=self._replay_action_pending, + ) + + # -- event handling ---------------------------------------------------- + def _handle_event(self, event: ApplicationEvent) -> None: + if isinstance(event, InputsChanged): + self._handle_inputs(event) + elif isinstance(event, RecordingStarted): + self._persist_started_input() + elif isinstance(event, ApplicationError): + self._error = event.message + + def _handle_inputs(self, event: InputsChanged) -> None: + if event.request_id != self._pending_discovery_id: + return # stale discovery result + self._pending_discovery_id = None + self._discovering = False + self._status = None + self._descriptors = event.inputs + self._resolve_selection() + + def _persist_started_input(self) -> None: + started = self._pending_start_input + self._pending_start_input = None + if started is None: + return + updated = replace(self._config, input=started) + try: + self._store.save(updated) + except ConfigurationError as exc: + self._status = f"Recording started, but configuration could not be saved: {exc}" + return + self._config = updated + + def _resolve_selection(self) -> None: + options = self._options() + configured = self._config.input + if configured is not None: + for option in options: + if _config_matches(configured, option.descriptor): + self._selected_key = option.key + return + self._selected_key = None + self._status = "Configured input is not currently available" + return + self._selected_key = options[0].key if options else None + + def _options(self) -> tuple[InputOption, ...]: + return tuple( + InputOption( + key=_option_key(descriptor), + label=_option_label(descriptor), + descriptor=descriptor, + ) + for descriptor in self._descriptors + ) diff --git a/src/quickreplay/ui/settings.py b/src/quickreplay/ui/settings.py new file mode 100644 index 0000000..4b9e342 --- /dev/null +++ b/src/quickreplay/ui/settings.py @@ -0,0 +1,115 @@ +"""Flet-independent settings editing and validation logic.""" + +import re +from dataclasses import dataclass, replace + +from quickreplay.configuration.errors import ConfigurationValidationError +from quickreplay.configuration.models import QuickReplayConfig, RecordingConfig, ReplayConfig + +_INTEGER_PATTERN = re.compile(r"^[+-]?[0-9]+$") + +RESTART_REQUIRED_MESSAGE = ( + "Settings saved. Restart QuickReplay to apply recording/replay runtime changes." +) +SETTINGS_SAVED_MESSAGE = "Settings saved." + + +@dataclass(slots=True) +class SettingsDraft: + """Raw text values mirrored from the settings fields until Apply.""" + + buffer_duration_seconds: str = "" + mpv_executable: str = "" + + +@dataclass(frozen=True, slots=True) +class SettingsFieldError: + """A validation error tied to a draft field.""" + + field: str + message: str + + +@dataclass(frozen=True, slots=True) +class SettingsValidation: + """The outcome of validating a settings draft.""" + + config: QuickReplayConfig | None + errors: tuple[SettingsFieldError, ...] + + +@dataclass(frozen=True, slots=True) +class SettingsApplyResult: + """The outcome of applying a draft (validation, save and status).""" + + ok: bool + message: str = "" + restart_required: bool = False + errors: tuple[SettingsFieldError, ...] = () + + +def draft_from_config(config: QuickReplayConfig) -> SettingsDraft: + """Build a draft from the persisted configuration.""" + return SettingsDraft( + buffer_duration_seconds=str(config.recording.buffer_duration_seconds), + mpv_executable=config.replay.mpv_executable, + ) + + +def build_settings_config(draft: SettingsDraft, config: QuickReplayConfig) -> SettingsValidation: + """Validate a draft and build a candidate preserving the selected input.""" + errors: list[SettingsFieldError] = [] + buffer_seconds = _parse_positive_int( + draft.buffer_duration_seconds, + "buffer_duration_seconds", + "Buffer duration", + errors, + ) + mpv_executable = draft.mpv_executable.strip() + if not mpv_executable: + errors.append(SettingsFieldError("mpv_executable", "mpv executable must not be empty")) + + recording: RecordingConfig | None = None + if buffer_seconds is not None: + try: + recording = RecordingConfig(buffer_seconds) + except ConfigurationValidationError as exc: + errors.append(SettingsFieldError("buffer_duration_seconds", str(exc))) + + replay: ReplayConfig | None = None + if mpv_executable: + try: + replay = ReplayConfig(mpv_executable) + except ConfigurationValidationError as exc: + errors.append(SettingsFieldError("mpv_executable", str(exc))) + + if errors or recording is None or replay is None: + return SettingsValidation(config=None, errors=tuple(errors)) + return SettingsValidation(config=replace(config, recording=recording, replay=replay), errors=()) + + +def restart_required(current: QuickReplayConfig, candidate: QuickReplayConfig) -> bool: + """Whether the runtime recording/replay settings require a restart.""" + return current.recording != candidate.recording or current.replay != candidate.replay + + +def apply_message(*, restart: bool) -> str: + """Status text shown after a successful settings apply.""" + return RESTART_REQUIRED_MESSAGE if restart else SETTINGS_SAVED_MESSAGE + + +def _parse_positive_int( + raw: str, + field: str, + label: str, + errors: list[SettingsFieldError], +) -> int | None: + text = raw.strip() + if not _INTEGER_PATTERN.match(text): + errors.append(SettingsFieldError(field, f"{label} must be a positive integer")) + return None + value = int(text) + if value <= 0: + errors.append(SettingsFieldError(field, f"{label} must be a positive integer")) + return None + return value diff --git a/src/quickreplay/units.py b/src/quickreplay/units.py new file mode 100644 index 0000000..1d0d599 --- /dev/null +++ b/src/quickreplay/units.py @@ -0,0 +1,23 @@ +"""Shared unit constants and exact (non-float) rounding helpers. + +All internal time in Version 2 is expressed as integer nanoseconds and all +frame rates as :class:`fractions.Fraction`. These helpers keep conversions +exact; float is never used as the source of truth. +""" + +import math +from fractions import Fraction + +NANOSECONDS_PER_SECOND = 1_000_000_000 +"""Number of nanoseconds in one second.""" + + +def round_fraction(value: Fraction) -> int: + """Round a :class:`~fractions.Fraction` to the nearest int. + + Ties are rounded away from zero. Rounding is explicit so that timestamp to + frame conversion is deterministic and independently testable. + """ + if value >= 0: + return math.floor(value + Fraction(1, 2)) + return -math.floor(-value + Fraction(1, 2)) diff --git a/src/quickreplay/worker/__init__.py b/src/quickreplay/worker/__init__.py new file mode 100644 index 0000000..3322207 --- /dev/null +++ b/src/quickreplay/worker/__init__.py @@ -0,0 +1,33 @@ +"""Recorder worker: a long-lived process that records segments and builds replays. + +The worker owns all native resources (input receivers, encoders, muxers) and +communicates with the main process only through picklable commands and events. +""" + +from quickreplay.worker.inputs import ( + InputSourceHandle, + create_input_source, + discover_inputs, + input_supports_audio, + open_input_source, +) +from quickreplay.worker.process import ( + RecorderWorkerProcess, + spawn_context, + worker_process_main, +) +from quickreplay.worker.runtime import RecorderWorkerRuntime +from quickreplay.worker.settings import RecorderWorkerSettings + +__all__ = [ + "InputSourceHandle", + "RecorderWorkerProcess", + "RecorderWorkerRuntime", + "RecorderWorkerSettings", + "create_input_source", + "discover_inputs", + "input_supports_audio", + "open_input_source", + "spawn_context", + "worker_process_main", +] diff --git a/src/quickreplay/worker/errors.py b/src/quickreplay/worker/errors.py new file mode 100644 index 0000000..85a724b --- /dev/null +++ b/src/quickreplay/worker/errors.py @@ -0,0 +1,86 @@ +"""Worker-internal pipeline errors and component-to-code error mapping.""" + +import errno + +from quickreplay.input.ndi.errors import ( + NdiCaptureError, + NdiFormatChangeError, + NdiInitializationError, + NdiReceiverError, + NdiSourceNotFoundError, + NdiUnsupportedFormatError, +) +from quickreplay.recording.errors import ( + RingStorageError, + SegmentEncodingError, + SegmentFormatError, + SegmentMuxError, +) +from quickreplay.recording.models import WorkerErrorCode +from quickreplay.replay.errors import ReplayAssetError + + +class WorkerPipelineError(RuntimeError): + """Base class for internal recorder pipeline failures.""" + + +class PipelineStartupError(WorkerPipelineError): + """The input did not produce a usable stream before the startup timeout.""" + + +class PipelineOrderingError(WorkerPipelineError): + """A frame arrived too late to be placed on the recording timeline.""" + + +class PipelineFormatChangeError(WorkerPipelineError): + """The active session format changed in a way that cannot be mixed.""" + + +class PipelineShutdownError(WorkerPipelineError): + """A pipeline thread did not stop within its grace period.""" + + +def map_worker_error(error: BaseException) -> WorkerErrorCode: + """Map a component exception to a machine-readable worker error code.""" + if _contains_disk_full(error): + return WorkerErrorCode.DISK_FULL + if isinstance(error, NdiSourceNotFoundError): + return WorkerErrorCode.INPUT_NOT_FOUND + if isinstance( + error, + (NdiInitializationError, NdiReceiverError), + ): + return WorkerErrorCode.INPUT_OPEN_FAILED + if isinstance(error, (NdiCaptureError, PipelineStartupError)): + return WorkerErrorCode.INPUT_DISCONNECTED + if isinstance( + error, + ( + NdiUnsupportedFormatError, + NdiFormatChangeError, + SegmentFormatError, + PipelineFormatChangeError, + ), + ): + return WorkerErrorCode.UNSUPPORTED_FORMAT + if isinstance(error, SegmentEncodingError): + return WorkerErrorCode.ENCODER_FAILED + if isinstance(error, SegmentMuxError): + return WorkerErrorCode.MUXER_FAILED + if isinstance(error, ReplayAssetError): + return WorkerErrorCode.REPLAY_ASSET_FAILED + if isinstance(error, (RingStorageError, OSError)): + return WorkerErrorCode.FILE_IO_ERROR + return WorkerErrorCode.INTERNAL_ERROR + + +def _contains_disk_full(error: BaseException) -> bool: + """Whether any exception in the cause chain is an ``ENOSPC`` OSError.""" + seen: set[int] = set() + current: BaseException | None = error + while current is not None and id(current) not in seen: + seen.add(id(current)) + if isinstance(current, OSError) and current.errno == errno.ENOSPC: + return True + current = current.__cause__ or current.__context__ + return False diff --git a/src/quickreplay/worker/frame_queues.py b/src/quickreplay/worker/frame_queues.py new file mode 100644 index 0000000..ed84385 --- /dev/null +++ b/src/quickreplay/worker/frame_queues.py @@ -0,0 +1,117 @@ +"""Bounded per-stream frame queues with drop-oldest and A/V ordering. + +Video and audio are held in separate deques. When a queue is full the oldest +frame is dropped so the capture side never blocks; drops are counted, not +silent. The encode side pulls the oldest frame across both streams, holding +frames back until a configurable window has elapsed so a late stream can catch +up. +""" + +import threading +from collections import deque + +from quickreplay.input.models import AudioFrame, CaptureItem, VideoFrame + + +class FrameQueues: + """Thread-safe bounded video/audio queues with drop-oldest behaviour.""" + + def __init__(self, *, video_capacity: int, audio_capacity: int) -> None: + if video_capacity <= 0 or audio_capacity <= 0: + raise ValueError("queue capacities must be positive") + self._lock = threading.Lock() + self._ready = threading.Condition(self._lock) + self._video: deque[VideoFrame] = deque() + self._audio: deque[AudioFrame] = deque() + self._video_capacity = video_capacity + self._audio_capacity = audio_capacity + self._draining = False + self._video_drops = 0 + self._audio_drops = 0 + self._latest_video_ts: int | None = None + self._latest_audio_ts: int | None = None + + # -- producer side ----------------------------------------------------- + def put_video(self, frame: VideoFrame) -> None: + with self._ready: + if len(self._video) >= self._video_capacity: + self._video.popleft() + self._video_drops += 1 + self._video.append(frame) + self._latest_video_ts = _newer(self._latest_video_ts, frame.timestamp_ns) + self._ready.notify_all() + + def put_audio(self, frame: AudioFrame) -> None: + with self._ready: + if len(self._audio) >= self._audio_capacity: + self._audio.popleft() + self._audio_drops += 1 + self._audio.append(frame) + self._latest_audio_ts = _newer(self._latest_audio_ts, frame.timestamp_ns) + self._ready.notify_all() + + def begin_drain(self) -> None: + """Release the hold-back so the encode side processes everything.""" + with self._ready: + self._draining = True + self._ready.notify_all() + + # -- consumer side ----------------------------------------------------- + @property + def draining(self) -> bool: + with self._lock: + return self._draining + + def empty(self) -> bool: + with self._lock: + return not self._video and not self._audio + + def drop_counts(self) -> tuple[int, int]: + with self._lock: + return self._video_drops, self._audio_drops + + def wait(self, timeout: float) -> None: + with self._ready: + if not self._video and not self._audio and not self._draining: + self._ready.wait(timeout) + + def take_next(self, *, holdback_ns: int, expect_audio: bool) -> CaptureItem | None: + """Return the oldest ready frame, or ``None`` if none may be emitted yet. + + ``expect_audio`` disables the hold-back for video-only sources so a + Video-only input never pays an A/V latency. When draining, everything is emitted + immediately. + """ + with self._ready: + if not self._video and not self._audio: + return None + take_video = self._pick_video() + if not self._draining and expect_audio: + oldest_ts = ( + self._video[0].timestamp_ns if take_video else self._audio[0].timestamp_ns + ) + newest = _newer_newest(self._latest_video_ts, self._latest_audio_ts) + if newest is not None and oldest_ts > newest - holdback_ns: + return None + if take_video: + return self._video.popleft() + return self._audio.popleft() + + def _pick_video(self) -> bool: + if self._video and self._audio: + return self._video[0].timestamp_ns <= self._audio[0].timestamp_ns + return bool(self._video) + + +def _newer(current: int | None, candidate: int) -> int: + if current is None or candidate > current: + return candidate + return current + + +def _newer_newest(first: int | None, second: int | None) -> int | None: + if first is None: + return second + if second is None: + return first + return max(first, second) diff --git a/src/quickreplay/worker/fs.py b/src/quickreplay/worker/fs.py new file mode 100644 index 0000000..efc62dc --- /dev/null +++ b/src/quickreplay/worker/fs.py @@ -0,0 +1,52 @@ +"""Filesystem helpers for recording-session cleanup. + +On Windows, deleting a directory immediately after ``os.replace`` can +transiently fail with a sharing violation or "directory not empty" even though +every writer has closed its file and the directory is already empty: the +platform can briefly report a stale directory entry for the replaced +temporary file. :func:`remove_tree` performs a small, bounded retry for those +specific transient errors only; on other platforms it deletes once. +""" + +import os +import shutil +import time +from pathlib import Path + +_TRANSIENT_WINDOWS_ERRORS = frozenset({5, 32, 145}) # ACCESS_DENIED / SHARING / NOT_EMPTY +DEFAULT_ATTEMPTS = 6 +DEFAULT_DELAY_SECONDS = 0.05 + + +def remove_tree( + path: Path, + *, + attempts: int = DEFAULT_ATTEMPTS, + delay_seconds: float = DEFAULT_DELAY_SECONDS, +) -> None: + """Remove a directory tree, retrying transient Windows delete failures. + + A missing path is treated as already removed. Raises the last ``OSError`` + if the directory cannot be removed within the bounded attempt budget. + """ + if not path.exists(): + return + if os.name != "nt": + shutil.rmtree(path) + return + + last_error: OSError | None = None + for attempt in range(attempts): + try: + shutil.rmtree(path) + return + except FileNotFoundError: + return # a previous partial delete already removed it + except OSError as exc: + last_error = exc + transient = getattr(exc, "winerror", None) in _TRANSIENT_WINDOWS_ERRORS + if not transient or attempt + 1 >= attempts or not path.exists(): + raise + time.sleep(delay_seconds * (attempt + 1)) + if last_error is not None: # pragma: no cover - defensive + raise last_error diff --git a/src/quickreplay/worker/inputs.py b/src/quickreplay/worker/inputs.py new file mode 100644 index 0000000..dd9453b --- /dev/null +++ b/src/quickreplay/worker/inputs.py @@ -0,0 +1,47 @@ +"""Input source creation and discovery for the worker process. + +Native NDI objects are created here, inside the worker process only. Main +never receives a native handle or a frame. +""" + +from dataclasses import dataclass + +from quickreplay.input.models import InputConfig, InputDescriptor +from quickreplay.input.ndi.discovery import discover_ndi_sources +from quickreplay.input.ndi.source import NdiInputSource +from quickreplay.input.source import InputSource + + +@dataclass(frozen=True, slots=True) +class InputSourceHandle: + """An opened-capable source together with whether it can carry audio.""" + + source: InputSource + supports_audio: bool + + +def create_input_source(config: InputConfig) -> InputSource: + """Create the production input source for *config*.""" + return NdiInputSource(config) + + +def input_supports_audio(config: InputConfig) -> bool: + """NDI sources can carry audio; stream probing detects video-only inputs.""" + del config + return True + + +def open_input_source(config: InputConfig) -> InputSourceHandle: + """Create a source and describe its audio capability.""" + return InputSourceHandle( + source=create_input_source(config), + supports_audio=input_supports_audio(config), + ) + + +def discover_inputs() -> tuple[InputDescriptor, ...]: + """Discover NDI inputs, treating discovery failure as an empty result.""" + try: + return discover_ndi_sources() + except Exception: # noqa: BLE001 - provider failures are non-fatal + return () diff --git a/src/quickreplay/worker/pipeline.py b/src/quickreplay/worker/pipeline.py new file mode 100644 index 0000000..d9f1893 --- /dev/null +++ b/src/quickreplay/worker/pipeline.py @@ -0,0 +1,430 @@ +"""Recording pipeline: capture thread + encode thread. + +The capture thread owns the :class:`~quickreplay.input.source.InputSource`. +The encode thread owns the +:class:`~quickreplay.recording.segment_recorder.SegmentRecorder` and the +:class:`~quickreplay.recording.ring_storage.RingStorage`. Frames travel +between them through bounded in-process queues only. +""" + +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass +from uuid import uuid4 + +from quickreplay.input.models import AudioFrame, CaptureItem, InputConfig, StreamInfo, VideoFrame +from quickreplay.input.source import InputSource +from quickreplay.recording.models import RecordingMetrics, RecordingSession, Segment +from quickreplay.recording.ring_storage import RingStorage +from quickreplay.recording.segment_recorder import SegmentRecorder, WriterFactory +from quickreplay.worker.errors import ( + PipelineFormatChangeError, + PipelineOrderingError, + PipelineShutdownError, + PipelineStartupError, +) +from quickreplay.worker.frame_queues import FrameQueues +from quickreplay.worker.inputs import InputSourceHandle, open_input_source +from quickreplay.worker.settings import RecorderWorkerSettings + +CLOCK = time.perf_counter_ns +"""Monotonic control clock; never used as a media timestamp.""" + +_IDLE_SLEEP_SECONDS = 0.001 +_WAIT_SLICE_SECONDS = 0.02 + + +@dataclass(slots=True) +class _MetricsState: + captured_video_frames: int = 0 + recorded_video_frames: int = 0 + captured_audio_samples: int = 0 + recorded_audio_samples: int = 0 + segment_count: int = 0 + buffer_duration_ns: int = 0 + + +class RecordingPipeline: + """Runs one recording session across a capture and an encode thread.""" + + def __init__( + self, + settings: RecorderWorkerSettings, + *, + input_factory: Callable[[InputConfig], InputSourceHandle] = open_input_source, + writer_factory: WriterFactory | None = None, + clock: Callable[[], int] = CLOCK, + ) -> None: + self._settings = settings + self._input_factory = input_factory + self._writer_factory = writer_factory + self._clock = clock + + self._source: InputSource | None = None + self._queues: FrameQueues | None = None + self._capture_thread: threading.Thread | None = None + self._encode_thread: threading.Thread | None = None + + self._stop_event = threading.Event() + self._format_ready = threading.Event() + self._session_ready = threading.Event() + + self._stream_info: StreamInfo | None = None + self._first_video_ts: int | None = None + self._session: RecordingSession | None = None + self._ring: RingStorage | None = None + + self._fatal: BaseException | None = None + self._active = False + self._stopped = False + + self._metrics = _MetricsState() + self._metrics_lock = threading.Lock() + self._last_metrics_ns: int | None = None + self._last_captured_video = 0 + self._last_recorded_video = 0 + + # -- queries ----------------------------------------------------------- + @property + def is_active(self) -> bool: + return self._active + + @property + def stream_info(self) -> StreamInfo | None: + return self._stream_info + + @property + def session(self) -> RecordingSession | None: + return self._session + + @property + def ring(self) -> RingStorage | None: + return self._ring + + def poll_fatal(self) -> BaseException | None: + """The first fatal failure seen by either thread, if any.""" + return self._fatal + + def take_ring(self) -> RingStorage | None: + """Relinquish ownership of the ring buffer to the caller.""" + ring = self._ring + self._ring = None + return ring + + # -- lifecycle --------------------------------------------------------- + def start(self, config: InputConfig) -> StreamInfo: + """Open the input and start both threads. Blocks until format is known.""" + if self._active: + raise PipelineStartupError("the pipeline is already active") + settings = self._settings + settings.buffer_root.mkdir(parents=True, exist_ok=True) + + handle = self._input_factory(config) + self._source = handle.source + self._queues = FrameQueues( + video_capacity=settings.video_queue_capacity, + audio_capacity=settings.audio_queue_capacity, + ) + self._capture_thread = threading.Thread( + target=self._capture_loop, + args=(handle.supports_audio,), + name="qr-capture", + daemon=True, + ) + self._capture_thread.start() + + try: + # The capture thread owns both input open and startup timing. In + # particular, source discovery/open time is not first-frame wait. + self._format_ready.wait() + if self._fatal is not None: + raise self._fatal + info = self._stream_info + first_video_ts = self._first_video_ts + if info is None or first_video_ts is None: + raise PipelineStartupError("the input did not provide a video frame") + + session_id = uuid4() + directory = settings.buffer_root / str(session_id) + directory.mkdir(parents=True, exist_ok=True) + session = RecordingSession(session_id, info, first_video_ts, directory) + ring = RingStorage(buffer_duration_ns=settings.buffer_duration_ns) + recorder = SegmentRecorder( + segment_duration_ns=settings.segment_duration_ns, + writer_factory=self._writer_factory, + ) + recorder.start(session) + + self._session = session + self._ring = ring + self._encode_thread = threading.Thread( + target=self._encode_loop, + args=(recorder, ring, info.audio is not None), + name="qr-encode", + daemon=True, + ) + self._encode_thread.start() + self._session_ready.set() + self._active = True + self._last_metrics_ns = self._clock() + return info + except BaseException: + self._active = False + self.abort() + raise + + def stop(self) -> None: + """Stop capture, drain the queues, finalize and stop encoding. + + On return, no capture/encode thread is running and the recorder and its + writers have been finalized and closed, so the session directory is + safe to remove. If finalization failed during the stop, that first + failure is raised instead of being treated as a clean stop. + """ + if self._stopped: + return + if self._source is None and self._capture_thread is None: + self._stopped = True + return + self._stop_event.set() + self._join_capture() + queues = self._queues + if queues is not None: + queues.begin_drain() + self._join_encode() + self._active = False + self._stopped = True + fatal = self._fatal + if fatal is not None: + raise fatal + + def abort(self) -> None: + """Best-effort stop used on failure paths. Never raises.""" + if self._stopped: + return + self._stopped = True + self._stop_event.set() + try: + self._join_capture() + except Exception: # noqa: BLE001 - best effort + pass + queues = self._queues + if queues is not None: + try: + queues.begin_drain() + except Exception: # noqa: BLE001 - best effort + pass + try: + self._join_encode() + except Exception: # noqa: BLE001 - best effort + pass + self._active = False + + # -- metrics ----------------------------------------------------------- + def metrics(self) -> RecordingMetrics: + """Current recording metrics; fps values are measured, not declared.""" + now = self._clock() + with self._metrics_lock: + captured_video = self._metrics.captured_video_frames + recorded_video = self._metrics.recorded_video_frames + captured_audio = self._metrics.captured_audio_samples + recorded_audio = self._metrics.recorded_audio_samples + segment_count = self._metrics.segment_count + buffer_duration_ns = self._metrics.buffer_duration_ns + + input_fps = 0.0 + recording_fps = 0.0 + if self._last_metrics_ns is not None and now > self._last_metrics_ns: + elapsed_seconds = (now - self._last_metrics_ns) / 1_000_000_000 + input_fps = (captured_video - self._last_captured_video) / elapsed_seconds + recording_fps = (recorded_video - self._last_recorded_video) / elapsed_seconds + self._last_metrics_ns = now + self._last_captured_video = captured_video + self._last_recorded_video = recorded_video + + video_drops, audio_drops = self._queues.drop_counts() if self._queues else (0, 0) + return RecordingMetrics( + captured_video_frames=captured_video, + recorded_video_frames=recorded_video, + captured_audio_samples=captured_audio, + recorded_audio_samples=recorded_audio, + video_queue_drops=video_drops, + audio_queue_drops=audio_drops, + buffer_duration_ns=buffer_duration_ns, + segment_count=segment_count, + input_fps=input_fps, + recording_fps=recording_fps, + ) + + # -- capture thread ---------------------------------------------------- + def _capture_loop(self, supports_audio: bool) -> None: + source = self._source + queues = self._queues + if source is None or queues is None: # pragma: no cover - defensive + return + buffer: list[CaptureItem] = [] + forwarding = False + first_video_ts: int | None = None + first_video_control_time: int | None = None + try: + source.open() + source_opened_at = self._clock() + while not self._stop_event.is_set(): + if first_video_control_time is None and ( + self._clock() - source_opened_at >= self._settings.stream_start_timeout_ns + ): + raise PipelineStartupError("timed out waiting for the first video frame") + item = source.read() + if item is not None and not forwarding: + buffer.append(item) + if isinstance(item, VideoFrame): + if first_video_ts is None: + first_video_ts = item.timestamp_ns + first_video_control_time = self._clock() + elif item is not None: + self._forward(item, first_video_ts, queues) + + if ( + not forwarding + and first_video_control_time is not None + and self._bootstrap_complete(supports_audio, first_video_control_time) + ): + info = source.stream_info + if info is None: + raise PipelineStartupError("the input did not report stream info") + self._stream_info = info + self._first_video_ts = first_video_ts + self._format_ready.set() + + if item is None: + time.sleep(_IDLE_SLEEP_SECONDS) + if not forwarding: + if self._format_ready.is_set() and self._session_ready.wait(timeout=0.01): + forwarding = True + for buffered in buffer: + self._forward(buffered, first_video_ts, queues) + buffer.clear() + if not forwarding: + continue + except BaseException as exc: # noqa: BLE001 - reported through poll_fatal + self._set_fatal(exc) + finally: + try: + source.close() + except Exception: # noqa: BLE001 - best effort + pass + self._format_ready.set() + + def _bootstrap_complete(self, supports_audio: bool, first_video_control_time: int) -> bool: + if not supports_audio: + return True + source = self._source + info = source.stream_info if source is not None else None + if info is not None and info.audio is not None: + return True + return self._clock() - first_video_control_time >= self._settings.stream_probe_window_ns + + def _forward(self, item: CaptureItem, first_video_ts: int | None, queues: FrameQueues) -> None: + if isinstance(item, VideoFrame): + self._increment("captured_video_frames", 1) + queues.put_video(item) + return + if not isinstance(item, AudioFrame): # pragma: no cover - defensive + return + if first_video_ts is not None and item.timestamp_ns < first_video_ts: + return # audio before the session epoch + if self._stream_info is not None and self._stream_info.audio is None: + raise PipelineFormatChangeError( + "audio arrived after the session was fixed as video-only" + ) + self._increment("captured_audio_samples", item.sample_count) + queues.put_audio(item) + + # -- encode thread ----------------------------------------------------- + def _encode_loop( + self, recorder: SegmentRecorder, ring: RingStorage, expect_audio: bool + ) -> None: + queues = self._queues + if queues is None: # pragma: no cover - defensive + return + last_ts: int | None = None + try: + while True: + item = queues.take_next( + holdback_ns=self._settings.av_reorder_holdback_ns, expect_audio=expect_audio + ) + if item is None: + if queues.draining and queues.empty(): + break + queues.wait(_WAIT_SLICE_SECONDS) + continue + if last_ts is not None and item.timestamp_ns < last_ts: + raise PipelineOrderingError( + f"frame timestamp {item.timestamp_ns} is older than the " + f"last encoded {last_ts}" + ) + self._encode_item(recorder, ring, item) + last_ts = item.timestamp_ns + except BaseException as exc: # noqa: BLE001 - reported through poll_fatal + self._set_fatal(exc) + finally: + try: + final = recorder.finish() + if final is not None: + self._add_segment(ring, final) + except BaseException as exc: # noqa: BLE001 - reported through poll_fatal + self._set_fatal(exc) + finally: + recorder.close() + + def _encode_item(self, recorder: SegmentRecorder, ring: RingStorage, item: CaptureItem) -> None: + if isinstance(item, VideoFrame): + for segment in recorder.push_video(item): + self._add_segment(ring, segment) + self._increment("recorded_video_frames", 1) + return + accepted_samples = recorder.push_audio(item) + self._increment("recorded_audio_samples", accepted_samples) + + def _add_segment(self, ring: RingStorage, segment: Segment) -> None: + ring.add(segment) + with self._metrics_lock: + self._metrics.segment_count = ring.segment_count + self._metrics.buffer_duration_ns = ring.duration_ns + + # -- helpers ----------------------------------------------------------- + def _join_capture(self) -> None: + thread = self._capture_thread + if thread is None: + return + grace = self._settings.freeze_grace_seconds + thread.join(timeout=grace) + if thread.is_alive(): + source = self._source + if source is not None: + try: + source.close() + except Exception: # noqa: BLE001 - best effort interrupt + pass + thread.join(timeout=grace) + if thread.is_alive(): + raise PipelineShutdownError("the capture thread did not stop") + self._capture_thread = None + + def _join_encode(self) -> None: + thread = self._encode_thread + if thread is None: + return + thread.join(timeout=self._settings.drain_timeout_seconds) + if thread.is_alive(): + raise PipelineShutdownError("the encode thread did not stop") + self._encode_thread = None + + def _set_fatal(self, exc: BaseException) -> None: + if self._fatal is None: + self._fatal = exc + + def _increment(self, field: str, amount: int) -> None: + with self._metrics_lock: + setattr(self._metrics, field, getattr(self._metrics, field) + amount) diff --git a/src/quickreplay/worker/process.py b/src/quickreplay/worker/process.py new file mode 100644 index 0000000..e00d2df --- /dev/null +++ b/src/quickreplay/worker/process.py @@ -0,0 +1,92 @@ +"""Spawn-based wrapper around the recorder worker process. + +The worker runs in its own process created with an explicit ``spawn`` context +so no ``fork`` semantics are relied on (Windows packaging). The process target +is a module-level function; importing this module never starts a process. +""" + +import multiprocessing +import queue +from multiprocessing.process import BaseProcess +from typing import Any + +from quickreplay.input.ndi.backend import PyNdiBackend +from quickreplay.recording.commands import WorkerCommand +from quickreplay.recording.events import WorkerEvent +from quickreplay.worker.runtime import RecorderWorkerRuntime +from quickreplay.worker.settings import RecorderWorkerSettings + + +def worker_process_main( + command_queue: Any, event_queue: Any, settings: RecorderWorkerSettings +) -> None: + """Entry point of the worker process (module level, picklable).""" + ndi_runtime_owner = PyNdiBackend() + ndi_runtime_owner.initialize() + try: + runtime = RecorderWorkerRuntime(settings, command_queue=command_queue, emit=event_queue.put) + runtime.run() + finally: + ndi_runtime_owner.shutdown() + + +def spawn_context() -> Any: + """The explicit spawn context used for the worker process.""" + return multiprocessing.get_context("spawn") + + +class RecorderWorkerProcess: + """Main-process handle for one long-lived recorder worker.""" + + def __init__(self, settings: RecorderWorkerSettings, *, context: Any | None = None) -> None: + self._settings = settings + self._context = context if context is not None else spawn_context() + self._command_queue = self._context.Queue() + self._event_queue = self._context.Queue() + self._process: BaseProcess | None = None + + def start(self) -> None: + """Start the worker process.""" + if self._process is not None: + raise RuntimeError("the worker process has already been started") + self._process = self._context.Process( + target=worker_process_main, + args=(self._command_queue, self._event_queue, self._settings), + name="QuickReplayRecorderWorker", + ) + self._process.start() + + def send(self, command: WorkerCommand) -> None: + """Send a command to the worker.""" + self._command_queue.put(command) + + def get_event(self, timeout: float | None = None) -> WorkerEvent | None: + """Return the next worker event, or ``None`` when the timeout elapses.""" + try: + return self._event_queue.get(timeout=timeout) + except queue.Empty: + return None + + def is_alive(self) -> bool: + """Whether the worker process is still running.""" + return self._process is not None and self._process.is_alive() + + @property + def exitcode(self) -> int | None: + """The process exit code, or ``None`` while it is still running.""" + return None if self._process is None else self._process.exitcode + + def join(self, timeout: float | None = None) -> None: + """Wait for the worker process to exit.""" + if self._process is not None: + self._process.join(timeout) + + def terminate(self) -> None: + """Forcefully terminate the worker process.""" + if self._process is not None and self._process.is_alive(): + self._process.terminate() + + def close(self) -> None: + """Close the IPC queues. Call after the process has exited.""" + self._command_queue.close() + self._event_queue.close() diff --git a/src/quickreplay/worker/runtime.py b/src/quickreplay/worker/runtime.py new file mode 100644 index 0000000..b7d1249 --- /dev/null +++ b/src/quickreplay/worker/runtime.py @@ -0,0 +1,325 @@ +"""Recorder worker runtime: the command loop running inside the worker process. + +``RecorderWorkerRuntime`` owns the recording pipeline lifecycle, the replay +asset lifecycle, worker state and event emission. It receives picklable +``WorkerCommand`` values and emits picklable ``WorkerEvent`` values; no frames +or native objects cross this boundary. +""" + +import queue +from collections.abc import Callable +from pathlib import Path +from typing import Protocol +from uuid import UUID + +from quickreplay.input.models import InputConfig, InputDescriptor +from quickreplay.recording.commands import ( + ChangeInput, + DiscoverInputs, + PrepareReplay, + ResumeRecording, + Shutdown, + StartRecording, + StopSession, + WorkerCommand, +) +from quickreplay.recording.events import ( + InputsDiscovered, + RecordingMetricsUpdated, + ReplayPrepared, + SessionStopped, + StreamStarted, + WorkerError, + WorkerEvent, + WorkerStateChanged, +) +from quickreplay.recording.models import RecordingSession, WorkerErrorCode, WorkerState +from quickreplay.replay.asset_builder import ReplayAssetBuilder +from quickreplay.replay.models import ReplaySnapshot +from quickreplay.worker.errors import WorkerPipelineError, map_worker_error +from quickreplay.worker.fs import remove_tree +from quickreplay.worker.inputs import InputSourceHandle, discover_inputs, open_input_source +from quickreplay.worker.pipeline import CLOCK, RecordingPipeline +from quickreplay.worker.settings import RecorderWorkerSettings + + +class CommandSource(Protocol): + """A blocking command source (``multiprocessing.Queue`` or ``queue.Queue``).""" + + def get(self, block: bool = True, timeout: float | None = None) -> WorkerCommand: ... + + +_POLL_SECONDS = 0.05 + + +class RecorderWorkerRuntime: + """Command loop for the recorder worker.""" + + def __init__( + self, + settings: RecorderWorkerSettings, + *, + command_queue: CommandSource, + emit: Callable[[WorkerEvent], None], + input_factory: Callable[[InputConfig], InputSourceHandle] = open_input_source, + discovery: Callable[..., tuple[InputDescriptor, ...]] = discover_inputs, + builder_factory: Callable[[], ReplayAssetBuilder] = ReplayAssetBuilder, + clock: Callable[[], int] = CLOCK, + ) -> None: + self._settings = settings + self._command_queue = command_queue + self._emit = emit + self._input_factory = input_factory + self._discovery = discovery + self._builder_factory = builder_factory + self._clock = clock + + self._state: WorkerState | None = None + self._pipeline: RecordingPipeline | None = None + self._config: InputConfig | None = None + self._running = True + self._last_metrics_ns = 0 + + @property + def state(self) -> WorkerState | None: + return self._state + + # -- main loop --------------------------------------------------------- + def run(self) -> None: + """Process commands until ``Shutdown`` is received.""" + self._set_state(WorkerState.IDLE) + while self._running: + try: + command = self._command_queue.get(timeout=_POLL_SECONDS) + except queue.Empty: + command = None + if command is not None: + self._dispatch(command) + if self._running: + self._tick() + + def _dispatch(self, command: WorkerCommand) -> None: + match command: + case StartRecording(): + self._on_start(command) + case PrepareReplay(): + self._on_prepare(command) + case ResumeRecording(): + self._on_resume(command) + case ChangeInput(): + self._on_change(command) + case DiscoverInputs(): + self._on_discover(command) + case Shutdown(): + self._on_shutdown() + case StopSession(): + self._on_stop_session(command) + case _: # pragma: no cover - future commands + self._emit( + WorkerError( + WorkerErrorCode.INTERNAL_ERROR, f"unknown command {command!r}", None + ) + ) + + def _tick(self) -> None: + pipeline = self._pipeline + if pipeline is not None and self._state in (WorkerState.RECORDING, WorkerState.STARTING): + fatal = pipeline.poll_fatal() + if fatal is not None: + self._fail(fatal, None) + return + if self._state == WorkerState.RECORDING and pipeline is not None: + now = self._clock() + if now - self._last_metrics_ns >= self._settings.metrics_interval_ns: + self._last_metrics_ns = now + self._emit(RecordingMetricsUpdated(metrics=pipeline.metrics())) + + # -- command handlers -------------------------------------------------- + def _on_start(self, command: StartRecording) -> None: + if self._state != WorkerState.IDLE: + self._reject(None, "StartRecording is only valid while idle") + return + self._set_state(WorkerState.STARTING) + self._begin_session(command.input_config, command.request_id) + + def _on_prepare(self, command: PrepareReplay) -> None: + pipeline = self._pipeline + if self._state != WorkerState.RECORDING or pipeline is None: + self._reject(command.request_id, "PrepareReplay requires an active recording") + return + self._set_state(WorkerState.FREEZING) + replay_directory = self._settings.replay_root / str(command.request_id) + try: + pipeline.stop() + ring = pipeline.take_ring() + info = pipeline.stream_info + if ring is None or info is None: + raise WorkerPipelineError("the recording pipeline is not ready to freeze") + builder = self._builder_factory() + with ring.snapshot() as lease: + snapshot = ReplaySnapshot(segments=lease.segments, stream_info=info) + asset = builder.build(snapshot, replay_directory) + ring.clear() + self._remove_session_directory(pipeline.session) + self._pipeline = None + except BaseException as exc: # noqa: BLE001 - reported as a worker error + self._remove_path_quietly(replay_directory) + self._fail(exc, command.request_id) + return + self._set_state(WorkerState.FROZEN) + self._emit(ReplayPrepared(request_id=command.request_id, asset=asset)) + + def _on_resume(self, command: ResumeRecording) -> None: + if self._state != WorkerState.FROZEN: + self._reject(command.request_id, "ResumeRecording requires a frozen worker") + return + self._set_state(WorkerState.STARTING) + try: + self._purge_replay_root() + except BaseException as exc: # noqa: BLE001 - reported as a worker error + self._fail(exc, command.request_id) + return + if self._config is None: + self._fail( + WorkerPipelineError("no input configuration available to resume"), + command.request_id, + ) + return + self._begin_session(self._config, command.request_id) + + def _on_change(self, command: ChangeInput) -> None: + pipeline = self._pipeline + if self._state != WorkerState.RECORDING or pipeline is None: + self._reject(command.request_id, "ChangeInput requires an active recording") + return + self._set_state(WorkerState.STOPPING) + try: + pipeline.stop() + ring = pipeline.take_ring() + if ring is not None: + ring.clear() + self._remove_session_directory(pipeline.session) + except BaseException as exc: # noqa: BLE001 - reported as a worker error + self._fail(exc, command.request_id) + return + self._pipeline = None + self._config = command.input_config + self._set_state(WorkerState.STARTING) + self._begin_session(command.input_config, command.request_id) + + def _on_discover(self, command: DiscoverInputs) -> None: + try: + inputs = self._discovery() + except BaseException as exc: # noqa: BLE001 - discovery failure is non-fatal + self._emit(WorkerError(map_worker_error(exc), str(exc), command.request_id)) + return + self._emit(InputsDiscovered(request_id=command.request_id, inputs=tuple(inputs))) + + def _on_shutdown(self) -> None: + self._set_state(WorkerState.SHUTTING_DOWN) + self._cleanup_all() + self._running = False + + def _on_stop_session(self, command: StopSession) -> None: + if self._state not in (WorkerState.RECORDING, WorkerState.FROZEN): + self._reject(command.request_id, "StopSession requires recording or frozen state") + return + self._set_state(WorkerState.STOPPING) + try: + if self._state == WorkerState.STOPPING and self._pipeline is not None: + self._pipeline.stop() + ring = self._pipeline.take_ring() + if ring is not None: + ring.clear() + self._remove_session_directory(self._pipeline.session) + self._pipeline = None + self._purge_replay_root() + self._config = None + except BaseException as exc: # noqa: BLE001 - reported to the controller + self._fail(exc, command.request_id) + return + self._set_state(WorkerState.IDLE) + self._emit(SessionStopped(request_id=command.request_id)) + + # -- session lifecycle ------------------------------------------------- + def _begin_session(self, config: InputConfig, request_id: UUID | None) -> None: + pipeline = RecordingPipeline( + self._settings, input_factory=self._input_factory, clock=self._clock + ) + try: + info = pipeline.start(config) + except BaseException as exc: # noqa: BLE001 - reported as a worker error + pipeline.abort() + self._fail(exc, request_id) + return + self._pipeline = pipeline + self._config = config + self._last_metrics_ns = self._clock() + self._set_state(WorkerState.RECORDING) + self._emit(StreamStarted(stream_info=info, request_id=request_id)) + + # -- helpers ----------------------------------------------------------- + def _set_state(self, state: WorkerState) -> None: + if self._state == state: + return + self._state = state + self._emit(WorkerStateChanged(state=state)) + + def _reject(self, request_id: UUID | None, message: str) -> None: + self._emit(WorkerError(WorkerErrorCode.INTERNAL_ERROR, message, request_id)) + + def _fail(self, exc: BaseException, request_id: UUID | None) -> None: + code = map_worker_error(exc) + if self._pipeline is not None: + try: + self._pipeline.abort() + except Exception: # noqa: BLE001 - best effort + pass + self._pipeline = None + self._emit(WorkerError(code=code, message=str(exc), request_id=request_id)) + if self._state != WorkerState.SHUTTING_DOWN: + self._set_state(WorkerState.ERROR) + + def _cleanup_all(self) -> None: + pipeline = self._pipeline + if pipeline is not None: + try: + pipeline.stop() + except Exception: # noqa: BLE001 - best effort + pass + try: + ring = pipeline.take_ring() + if ring is not None: + ring.clear() + except Exception: # noqa: BLE001 - best effort + pass + try: + self._remove_session_directory(pipeline.session) + except Exception: # noqa: BLE001 - best effort + pass + self._pipeline = None + try: + self._purge_replay_root() + except Exception: # noqa: BLE001 - best effort + pass + + def _remove_session_directory(self, session: RecordingSession | None) -> None: + if session is None: + return + remove_tree(session.directory) + + def _purge_replay_root(self) -> None: + root = self._settings.replay_root + if not root.exists(): + return + for entry in root.iterdir(): + if entry.is_dir(): + remove_tree(entry) + else: + entry.unlink() + + def _remove_path_quietly(self, path: Path) -> None: + try: + remove_tree(path) + except OSError: + pass diff --git a/src/quickreplay/worker/settings.py b/src/quickreplay/worker/settings.py new file mode 100644 index 0000000..deeb403 --- /dev/null +++ b/src/quickreplay/worker/settings.py @@ -0,0 +1,63 @@ +"""Runtime settings for the recorder worker. + +These are runtime knobs, not persisted configuration. Every value can be +injected from tests so timing-sensitive behaviour stays deterministic. +""" + +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True, slots=True) +class RecorderWorkerSettings: + """Tunables for one recorder worker process.""" + + working_directory: Path + + buffer_duration_ns: int = 120_000_000_000 + """Ring buffer retention window (default 120 seconds).""" + + segment_duration_ns: int = 2_000_000_000 + """Target duration of one segment file.""" + + video_queue_capacity: int = 64 + audio_queue_capacity: int = 64 + + av_reorder_holdback_ns: int = 500_000_000 + """How long the encode side waits for the other stream before emitting.""" + + stream_probe_window_ns: int = 500_000_000 + """Control-time window after first video before fixing video-only format.""" + + stream_start_timeout_ns: int = 5_000_000_000 + """Control timeout for the first video frame, measured after source.open().""" + + metrics_interval_ns: int = 1_000_000_000 + + freeze_grace_ns: int = 1_500_000_000 + """How long ``stop`` waits for the capture thread before interrupting it.""" + + drain_timeout_ns: int = 5_000_000_000 + """How long ``stop`` waits for the encode thread to finish draining.""" + + @property + def buffer_root(self) -> Path: + """Root directory holding per-session segment directories.""" + return self.working_directory / "buffer" + + @property + def replay_root(self) -> Path: + """Root directory holding per-request replay asset directories.""" + return self.working_directory / "replay" + + @property + def freeze_grace_seconds(self) -> float: + return self.freeze_grace_ns / 1_000_000_000 + + @property + def drain_timeout_seconds(self) -> float: + return self.drain_timeout_ns / 1_000_000_000 + + @property + def stream_start_timeout_seconds(self) -> float: + return self.stream_start_timeout_ns / 1_000_000_000 diff --git a/src/ring_video.py b/src/ring_video.py deleted file mode 100644 index 6030a10..0000000 --- a/src/ring_video.py +++ /dev/null @@ -1,183 +0,0 @@ -# Copyright (c) 2022 Nanahuse -# This software is released under the MIT License -# https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE - -import queue -from typing import List, Tuple -import cv2 -from threading import Thread -import os - - -class RingCounter(object): - def __init__(self, max: int, min: int = 0): - self._counter_max = max - self._counter_min = min - self._counter = 0 - - def increment(self, diff: int = 1) -> None: - self._counter += diff - - def decrement(self, diff: int = -1) -> None: - self._counter += diff - - def __getitem__(self, index: int): - return (index + self._counter) % (self._counter_max - self._counter_min) + self._counter_min - - -class RingVideoWriter(object): - class BufferOverflowException(Exception): - pass - - class Param(object): - def __init__(self, fmt: cv2.VideoWriter_fourcc, frame_rate: float, frame_size: Tuple[int, int]): - self.fmt = fmt - self.frame_rate = frame_rate - self.frame_size = frame_size - - def __init__( - self, - file_list: List[str], - fmt: cv2.VideoWriter_fourcc, - frame_rate: float, - frame_size: Tuple[int, int], - file_length_max: int = 10, - max_buffer_num: int = 60, - ): - self._buffer = queue.Queue(maxsize=max_buffer_num) - self._file_frame_max = int(frame_rate * file_length_max) - self._file_list = file_list - self._writer = cv2.VideoWriter(file_list[0], fmt, frame_rate, frame_size) - self._param = RingVideoWriter.Param(fmt, frame_rate, frame_size) - self._writer_thread = Thread(target=self._writer_task) - self._counter = RingCounter(len(file_list)) - self._is_run = True - self._writer_thread.start() - - def write(self, frame: cv2.Mat) -> None: - try: - self._buffer.put_nowait(frame) - except queue.Full: - raise RingVideoWriter.BufferOverflowException(f"overflow -> buffer max : {self._buffer.maxsize}") - - def release(self) -> List[str]: - if self._is_run: - self._is_run = False - self._writer_thread.join() - self._writer.release() - return [self._file_list[self._counter[i + 1]] for i in range(len(self._file_list))] - - def _writer_task(self) -> None: - counter = 0 - while True: - try: - frame = self._buffer.get(timeout=0.5) - self._writer.write(frame) - counter += 1 - if counter >= self._file_frame_max: - counter = 0 - self._counter.increment() - self._writer = cv2.VideoWriter( - self._file_list[self._counter[0]], - self._param.fmt, - self._param.frame_rate, - self._param.frame_size, - ) - except queue.Empty: - if self._is_run is False: - break - - -class RingVideoCapture(object): - class _Capture: - def __init__(self, file_path: str): - self.capture = cv2.VideoCapture(file_path) - self.frame_num = int(self.capture.get(cv2.CAP_PROP_FRAME_COUNT)) - - def __init__(self, file_list: List[str]): - self._caps = [RingVideoCapture._Capture(file) for file in file_list if os.path.exists(file)] - self._cap_cursor = 0 - self._frame_cursor = 0 - self._frame_num = sum([cap.frame_num for cap in self._caps]) - - def release(self) -> None: - for cap in self._caps: - cap.capture.release() - - def read(self) -> cv2.Mat: - tmp_cap = self._caps[self._cap_cursor] - _, frame = tmp_cap.capture.read() - if self._frame_cursor < tmp_cap.frame_num: - self._frame_cursor += 1 - if self._frame_cursor >= tmp_cap.frame_num: - if self._cap_cursor != len(self._caps) - 1 and self._caps[self._cap_cursor + 1].frame_num != 0: - self._cap_cursor += 1 - self._frame_cursor = 0 - return frame - - def move_first(self) -> None: - # 0フレーム目に移動 - self._cap_cursor = 0 - self._frame_cursor = 0 - self._caps[0].capture.set(cv2.CAP_PROP_POS_FRAMES, 0) - - def move_last(self) -> None: - # 最終フレームへ移動 - for i, cap in enumerate(self._caps[-1::-1]): - if cap.frame_num != 0: - self._cap_cursor = len(self._caps) - 1 - i - break - self._frame_cursor = self._caps[self._cap_cursor].frame_num - 1 - self._caps[self._cap_cursor].capture.set(cv2.CAP_PROP_POS_FRAMES, self._frame_cursor) - - def move_diff(self, diff: int) -> None: - self._frame_cursor += diff - if diff < 0: - if self._cap_cursor != 0: - for i, cap in enumerate(self._caps[self._cap_cursor - 1 :: -1]): - if self._frame_cursor >= 0: - self._cap_cursor -= i - self._caps[self._cap_cursor].capture.set(cv2.CAP_PROP_POS_FRAMES, self._frame_cursor) - return - else: - self._frame_cursor += cap.frame_num - - # self._cap_cursor == 0になったときの処理 - if self._frame_cursor < 0: - self.move_first() - return - else: - self._cap_cursor = 0 # self._cap_cursor = 0と実質同じ - self._caps[self._cap_cursor].capture.set(cv2.CAP_PROP_POS_FRAMES, self._frame_cursor) - return - - elif diff > 0: - for i, cap in enumerate(self._caps[self._cap_cursor : :]): - if self._frame_cursor < cap.frame_num: - self._cap_cursor += i - self._caps[self._cap_cursor].capture.set(cv2.CAP_PROP_POS_FRAMES, self._frame_cursor) - return - else: - self._frame_cursor -= cap.frame_num - else: - self.move_last() - - def move_frame(self, frame_num: int) -> None: - # 指定のフレームに移動する。 - # 範囲オーバーの場合もエラーにならず端で止まる - self.move_first() - self.move_diff(frame_num) - - def get_frame_num(self) -> int: - return self._frame_num - - def get_now_frame(self) -> int: - # cv2.VideoCaptureは読み込んだフレームの次のフレームにカーソルがあった状態になるため内部的には1ずらした状態になるが、 - # 使用する際には直前に読み込んだフレームの数字が表示された方が便利なので1マイナスしている。 - frame_cursor = 0 - if self._cap_cursor > 0: - for cap in self._caps[: self._cap_cursor :]: - frame_cursor += cap.frame_num - - frame_cursor += self._frame_cursor - return frame_cursor - 1 diff --git a/src/utils.py b/src/utils.py deleted file mode 100644 index 1c3a5ba..0000000 --- a/src/utils.py +++ /dev/null @@ -1,48 +0,0 @@ -# Copyright (c) 2022 Nanahuse -# This software is released under the MIT License -# https://github.com/Nanahuse/QuickReplay/blob/main/LICENSE - -from inspect import getmembers - - -def tkvar_to_dict(setting) -> dict: # NOQA - return_dict = {} - for method in getmembers(setting): - if "__" in method[0]: - continue - if hasattr(method[1], "get"): - return_dict[method[0]] = method[1].get() - return return_dict - - -def tkvar_from_dict(input_dict, output) -> None: # NOQA - for method in getmembers(output): - if hasattr(method[1], "set"): - if method[0] in input_dict: - method[1].set(input_dict[method[0]]) - - -if __name__ == "__main__": - import tkinter as tk - from dataclasses import dataclass - - @dataclass - class SettingReplay(object): - length: tk.IntVar - auto_restart: tk.IntVar - - frame = tk.Frame() - replay = SettingReplay(tk.IntVar(frame), tk.IntVar(frame)) - - replay.length.set(100) - replay.auto_restart.set(120) - - tmp = tkvar_to_dict(replay) - print(tmp) - - tmp["length"] = -10 - tmp["auto_restart"] = 200 - replay = SettingReplay(tk.IntVar(frame), tk.IntVar(frame)) - tkvar_from_dict(tmp, replay) - print(replay.length.get()) - print(replay.auto_restart.get()) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..5389c85 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,422 @@ +"""Shared fixtures for synthetic media used by the segment recorder tests.""" + +from collections.abc import Callable +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +from uuid import uuid4 + +import av +import numpy as np +import pytest + +from quickreplay.input.models import ( + AudioFrame, + AudioStreamInfo, + StreamInfo, + VideoFrame, + VideoStreamInfo, +) +from quickreplay.recording.models import RecordingSession, Segment +from quickreplay.recording.segment_recorder import SegmentRecorder +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction + +_VIDEO_COMPONENTS = {"RGB24": 3, "BGR24": 3, "RGBA": 4, "BGRA": 4, "GRAY8": 1} + + +class MediaFactory: + """Generate timestamped domain frames without any hardware.""" + + def video( + self, + *, + index: int, + fps: Fraction, + width: int, + height: int, + pixel_format: str = "RGB24", + value: int | None = None, + ) -> VideoFrame: + timestamp_ns = round_fraction(Fraction(index * NANOSECONDS_PER_SECOND, 1) / fps) + components = _VIDEO_COMPONENTS[pixel_format] + shape = (height, width) if components == 1 else (height, width, components) + if value is None: + value = index % 256 + data = np.full(shape, value, dtype=np.uint8) + return VideoFrame(timestamp_ns, width, height, fps, pixel_format, data) + + def video_at( + self, + *, + timestamp_ns: int, + fps: Fraction, + width: int, + height: int, + pixel_format: str = "RGB24", + ) -> VideoFrame: + components = _VIDEO_COMPONENTS[pixel_format] + shape = (height, width) if components == 1 else (height, width, components) + data = np.zeros(shape, dtype=np.uint8) + return VideoFrame(timestamp_ns, width, height, fps, pixel_format, data) + + def audio( + self, + *, + start_sample: int, + sample_rate: int, + channels: int, + count: int, + value: float = 0.0, + ) -> AudioFrame: + timestamp_ns = round_fraction(Fraction(start_sample, sample_rate) * NANOSECONDS_PER_SECOND) + data = np.full((channels, count), value, dtype=np.float32) + return AudioFrame(timestamp_ns, sample_rate, channels, count, data) + + def stream_info( + self, + *, + fps: Fraction, + width: int, + height: int, + pixel_format: str = "RGB24", + sample_rate: int | None = None, + channels: int | None = None, + ) -> StreamInfo: + audio = None + if sample_rate is not None and channels is not None: + audio = AudioStreamInfo(sample_rate, channels) + return StreamInfo(VideoStreamInfo(width, height, fps, pixel_format), audio) + + def session( + self, directory: Path, stream_info: StreamInfo, epoch_ns: int = 0 + ) -> RecordingSession: + return RecordingSession(uuid4(), stream_info, epoch_ns, directory) + + def frames( + self, + *, + duration_ns: int, + fps: Fraction, + width: int, + height: int, + pixel_format: str = "RGB24", + sample_rate: int | None = None, + channels: int | None = None, + audio_frame_samples: int = 1024, + ) -> list[VideoFrame | AudioFrame]: + """Return video and audio frames interleaved in timestamp order.""" + events: list[tuple[int, int, VideoFrame | AudioFrame]] = [] + + total_video = int(Fraction(duration_ns) * fps / NANOSECONDS_PER_SECOND) + 1 + for index in range(total_video): + timestamp_ns = round_fraction(Fraction(index * NANOSECONDS_PER_SECOND, 1) / fps) + if timestamp_ns > duration_ns: + break + events.append( + ( + timestamp_ns, + 0, + self.video( + index=index, fps=fps, width=width, height=height, pixel_format=pixel_format + ), + ) + ) + + if sample_rate is not None and channels is not None: + total_samples = int(Fraction(duration_ns) * sample_rate / NANOSECONDS_PER_SECOND) + position = 0 + while position < total_samples: + count = min(audio_frame_samples, total_samples - position) + timestamp_ns = round_fraction( + Fraction(position * NANOSECONDS_PER_SECOND, sample_rate) + ) + events.append( + ( + timestamp_ns, + 1, + self.audio( + start_sample=position, + sample_rate=sample_rate, + channels=channels, + count=count, + ), + ) + ) + position += count + + # Video sorts before audio at equal timestamps so the boundary (driven + # by video) is known before the audio that straddles it. + events.sort(key=lambda event: (event[0], event[1])) + return [frame for _ts, _kind, frame in events] + + +@pytest.fixture +def media() -> MediaFactory: + return MediaFactory() + + +@pytest.fixture +def make_segment(tmp_path: Path) -> Callable[..., Segment]: + """Create a finalized-looking segment with a real (dummy) file.""" + + def _make(segment_id: int, start_ns: int, end_ns: int) -> Segment: + path = tmp_path / f"segment_{segment_id:06d}.mkv" + path.write_bytes(b"segment") + return Segment( + id=segment_id, + path=path, + session_start_ns=start_ns, + session_end_ns=end_ns, + video_frames=120, + audio_samples=96000, + ) + + return _make + + +@pytest.fixture +def record_segments(media: MediaFactory) -> Callable[..., tuple[tuple[Segment, ...], StreamInfo]]: + """Record synthetic frames into finalized segments plus their stream info.""" + + def _record( + directory: Path, + *, + duration_ns: int, + fps: Fraction, + width: int, + height: int, + pixel_format: str = "RGB24", + sample_rate: int | None = None, + channels: int | None = None, + segment_duration_ns: int = 2_000_000_000, + ) -> tuple[tuple[Segment, ...], StreamInfo]: + stream_info = media.stream_info( + fps=fps, + width=width, + height=height, + pixel_format=pixel_format, + sample_rate=sample_rate, + channels=channels, + ) + recorder = SegmentRecorder(segment_duration_ns=segment_duration_ns) + recorder.start(media.session(directory, stream_info)) + segments: list[Segment] = [] + for frame in media.frames( + duration_ns=duration_ns, + fps=fps, + width=width, + height=height, + pixel_format=pixel_format, + sample_rate=sample_rate, + channels=channels, + ): + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + if last is not None: + segments.append(last) + recorder.close() + return tuple(segments), stream_info + + return _record + + +@dataclass(frozen=True) +class SegmentProbe: + """Facts read back from a written segment file.""" + + path: Path + video_codec: str + width: int + height: int + pixel_format: str | None + video_time_base: Fraction | None + video_rate: Fraction | None + video_packets: int + first_video_pts: int | None + keyframe_count: int + decoded_video_frames: int + audio_present: bool + audio_codec: str | None + audio_sample_rate: int | None + audio_channels: int | None + audio_time_base: Fraction | None + audio_samples: int + first_audio_pts: int | None + + +def probe_segment(path: Path) -> SegmentProbe: + """Open *path* and read stream info, packet layout and decoded facts.""" + path = Path(path) + with av.open(str(path)) as container: + video = container.streams.video[0] + audio_present = bool(container.streams.audio) + + video_packets = 0 + first_video_pts: int | None = None + keyframe_count = 0 + for packet in container.demux(): + if packet.dts is None or packet.stream.type != "video": + continue + video_packets += 1 + if first_video_pts is None: + first_video_pts = packet.pts + if packet.is_keyframe: + keyframe_count += 1 + + video_codec = video.codec_context + video_meta = ( + video_codec.name, + video_codec.width, + video_codec.height, + video_codec.pix_fmt, + video.time_base, + video.average_rate, + ) + + with av.open(str(path)) as container: + video = container.streams.video[0] + decoded_video_frames = sum(1 for _ in container.decode(video)) + + audio_codec: str | None = None + audio_sample_rate: int | None = None + audio_channels: int | None = None + audio_time_base: Fraction | None = None + audio_samples = 0 + first_audio_pts: int | None = None + if audio_present: + with av.open(str(path)) as container: + audio_stream = container.streams.audio[0] + codec_context = audio_stream.codec_context + audio_codec = codec_context.name + audio_sample_rate = codec_context.sample_rate + audio_channels = codec_context.channels + audio_time_base = audio_stream.time_base + for frame in container.decode(audio_stream): + if isinstance(frame, av.AudioFrame): + if first_audio_pts is None: + first_audio_pts = frame.pts + audio_samples += frame.samples + + codec, width, height, pix_fmt, time_base, rate = video_meta + return SegmentProbe( + path=path, + video_codec=codec, + width=width, + height=height, + pixel_format=pix_fmt, + video_time_base=time_base, + video_rate=rate, + video_packets=video_packets, + first_video_pts=first_video_pts, + keyframe_count=keyframe_count, + decoded_video_frames=decoded_video_frames, + audio_present=audio_present, + audio_codec=audio_codec, + audio_sample_rate=audio_sample_rate, + audio_channels=audio_channels, + audio_time_base=audio_time_base, + audio_samples=audio_samples, + first_audio_pts=first_audio_pts, + ) + + +@pytest.fixture +def probe() -> Callable[[Path], SegmentProbe]: + return probe_segment + + +@dataclass(frozen=True) +class ReplayProbe: + """Facts read back from a built replay asset.""" + + video_codec: str + video_time_base: Fraction | None + video_rate: Fraction | None + video_packet_pts: tuple[int, ...] + video_packet_dts: tuple[int, ...] + keyframe_pts: tuple[int, ...] + decoded_video_pts: tuple[int, ...] + audio_codec: str | None + audio_sample_rate: int | None + audio_channels: int | None + audio_packet_pts: tuple[int, ...] + audio_packet_dts: tuple[int, ...] + decoded_audio_samples: int + + +def probe_replay(path: Path) -> ReplayProbe: + """Open a replay asset and read packet, keyframe and decode facts.""" + path = Path(path) + with av.open(str(path)) as container: + video = container.streams.video[0] + video_codec = video.codec_context.name + video_time_base = video.time_base + video_rate = video.average_rate + video_pts: list[int] = [] + video_dts: list[int] = [] + keyframe_pts: list[int] = [] + for packet in container.demux(video): + if packet.dts is None or packet.pts is None: + continue + video_pts.append(packet.pts) + video_dts.append(packet.dts) + if packet.is_keyframe: + keyframe_pts.append(packet.pts) + audio_present = bool(container.streams.audio) + + with av.open(str(path)) as container: + decoded_video_pts = tuple( + frame.pts + for frame in container.decode(container.streams.video[0]) + if frame.pts is not None + ) + + audio_codec: str | None = None + audio_sample_rate: int | None = None + audio_channels: int | None = None + audio_pts: tuple[int, ...] = () + audio_dts: tuple[int, ...] = () + decoded_audio_samples = 0 + if audio_present: + with av.open(str(path)) as container: + audio = container.streams.audio[0] + audio_codec = audio.codec_context.name + audio_sample_rate = audio.codec_context.sample_rate + audio_channels = audio.codec_context.channels + pts: list[int] = [] + dts: list[int] = [] + for packet in container.demux(audio): + if packet.dts is None or packet.pts is None: + continue + pts.append(packet.pts) + dts.append(packet.dts) + audio_pts = tuple(pts) + audio_dts = tuple(dts) + with av.open(str(path)) as container: + decoded_audio_samples = sum( + frame.samples for frame in container.decode(container.streams.audio[0]) + ) + + return ReplayProbe( + video_codec=video_codec, + video_time_base=video_time_base, + video_rate=video_rate, + video_packet_pts=tuple(video_pts), + video_packet_dts=tuple(video_dts), + keyframe_pts=tuple(keyframe_pts), + decoded_video_pts=decoded_video_pts, + audio_codec=audio_codec, + audio_sample_rate=audio_sample_rate, + audio_channels=audio_channels, + audio_packet_pts=audio_pts, + audio_packet_dts=audio_dts, + decoded_audio_samples=decoded_audio_samples, + ) + + +@pytest.fixture +def replay_probe() -> Callable[[Path], ReplayProbe]: + return probe_replay diff --git a/tests/fake_application.py b/tests/fake_application.py new file mode 100644 index 0000000..9d4c350 --- /dev/null +++ b/tests/fake_application.py @@ -0,0 +1,179 @@ +"""Fake worker and replay controller for application controller tests.""" + +import queue +from fractions import Fraction +from typing import Any +from uuid import uuid4 + +from quickreplay.recording.commands import WorkerCommand +from quickreplay.recording.events import WorkerEvent, WorkerStateChanged +from quickreplay.recording.models import WorkerState +from quickreplay.replay.errors import MpvProcessExitedError +from quickreplay.replay.models import ReplayAsset, SetPoint, frame_difference + + +class FakeWorker: + """A scripted :class:`WorkerHandle`.""" + + def __init__(self, *, auto_idle: bool = True, exit_on_shutdown: bool = True) -> None: + self.commands: list[WorkerCommand] = [] + self.events: queue.Queue[WorkerEvent] = queue.Queue() + self.order: list[tuple[str, str | None]] = [] + self.started = False + self.alive = True + self.exitcode_value: int | None = None + self.auto_idle = auto_idle + self.exit_on_shutdown = exit_on_shutdown + self.join_calls = 0 + self.terminate_calls = 0 + self.closed = False + + def start(self) -> None: + self.started = True + if self.auto_idle: + self.push(WorkerStateChanged(state=WorkerState.IDLE)) + + def send(self, command: WorkerCommand) -> None: + self.commands.append(command) + self.order.append(("worker.send", type(command).__name__)) + + def get_event(self, timeout: float | None = None) -> WorkerEvent | None: + try: + return self.events.get(timeout=timeout) + except queue.Empty: + return None + + def push(self, event: WorkerEvent) -> None: + self.events.put(event) + + def is_alive(self) -> bool: + return self.alive + + @property + def exitcode(self) -> int | None: + return self.exitcode_value + + def join(self, timeout: float | None = None) -> None: + self.join_calls += 1 + if self.exit_on_shutdown: + self.alive = False + if self.exitcode_value is None: + self.exitcode_value = 0 + + def terminate(self) -> None: + self.terminate_calls += 1 + self.alive = False + self.exitcode_value = -9 + + def close(self) -> None: + self.closed = True + + def die(self, code: int = 1) -> None: + self.alive = False + self.exitcode_value = code + + def commands_of(self, command_type: type) -> list[Any]: + return [command for command in self.commands if isinstance(command, command_type)] + + +class FakeReplayController: + """A scripted :class:`ReplayControllerLike`.""" + + def __init__( + self, + *, + open_error: BaseException | None = None, + dead: bool = False, + order: list[tuple[str, str | None]] | None = None, + ) -> None: + self.open_error = open_error + self.dead = dead + self.order = order if order is not None else [] + self.calls: list[Any] = [] + self.asset: ReplayAsset | None = None + self.is_open = False + self.paused = True + self.position = 0 + + def open(self, asset: ReplayAsset) -> None: + self.calls.append("open") + if self.open_error is not None: + raise self.open_error + self.asset = asset + self.is_open = True + + def close(self) -> None: + self.calls.append("close") + self.order.append(("replay.close", None)) + self.is_open = False + + def check_alive(self) -> None: + if self.dead: + raise MpvProcessExitedError("the mpv process has exited") + + def play(self) -> None: + self.calls.append("play") + self.paused = False + + def pause(self) -> None: + self.calls.append("pause") + self.paused = True + + def is_paused(self) -> bool: + return self.paused + + def step_forward(self) -> None: + self.calls.append("step_forward") + + def step_backward(self) -> None: + self.calls.append("step_backward") + + def seek_frames(self, frames: int) -> None: + self.calls.append(("seek_frames", frames)) + + def seek_absolute_ns(self, position_ns: int) -> None: + self.calls.append(("seek_absolute_ns", position_ns)) + + def position_ns(self) -> int: + return self.position + + def set_point(self) -> SetPoint: + return SetPoint(position_ns=self.position) + + def time_difference_ns(self, point: SetPoint) -> int: + return self.position - point.position_ns + + def frame_difference(self, point: SetPoint) -> int: + fps = self.asset.fps if self.asset is not None else Fraction(60, 1) + return frame_difference(self.position, point.position_ns, fps) + + +class FakeReplayFactory: + """Creates :class:`FakeReplayController` instances and records them.""" + + def __init__( + self, + *, + open_error: BaseException | None = None, + order: list[tuple[str, str | None]] | None = None, + ) -> None: + self.open_error = open_error + self.order = order if order is not None else [] + self.controllers: list[FakeReplayController] = [] + + def __call__(self) -> FakeReplayController: + controller = FakeReplayController(open_error=self.open_error, order=self.order) + self.controllers.append(controller) + return controller + + +class SequenceRequestIds: + """Deterministic request id factory, falling back to random UUIDs.""" + + def __init__(self, *request_ids: Any) -> None: + self._ids = list(request_ids) + + def __call__(self) -> Any: + if self._ids: + return self._ids.pop(0) + return uuid4() diff --git a/tests/fake_mpv.py b/tests/fake_mpv.py new file mode 100644 index 0000000..9ecf2ce --- /dev/null +++ b/tests/fake_mpv.py @@ -0,0 +1,227 @@ +"""Fake mpv process and IPC transport for controller tests.""" + +import json +import queue +from collections.abc import Callable, Sequence +from typing import Any + +from quickreplay.replay.controller import ReplayController, ReplayControllerSettings + + +class FakeProcess: + """A scripted mpv process.""" + + def __init__( + self, + *, + running: bool = True, + exit_on_quit: bool = True, + wait_results: Sequence[int | None] | None = None, + terminate_works: bool = True, + kill_works: bool = True, + ) -> None: + self._running = running + self._returncode: int | None = 0 if not running else None + self._wait_results = list(wait_results or []) + self.exit_on_quit = exit_on_quit + self.terminate_works = terminate_works + self.kill_works = kill_works + self.terminate_calls = 0 + self.kill_calls = 0 + self.wait_calls = 0 + + def poll(self) -> int | None: + return None if self._running else self._returncode + + def wait(self, timeout: float | None = None) -> int | None: + self.wait_calls += 1 + if not self._running: + return self._returncode + if self._wait_results: + result = self._wait_results.pop(0) + if result is None: + return None + self.mark_exited(result) + return result + return None + + def terminate(self) -> None: + self.terminate_calls += 1 + if self.terminate_works: + self.mark_exited(-15) + + def kill(self) -> None: + self.kill_calls += 1 + if self.kill_works: + self.mark_exited(-9) + + def mark_exited(self, code: int = 0) -> None: + self._running = False + self._returncode = code + + @property + def returncode(self) -> int | None: + return self._returncode + + +Handler = Callable[[list[Any], int], dict[str, Any] | None] + + +class FakeTransport: + """A scripted, line-oriented mpv IPC transport.""" + + def __init__( + self, + *, + process: FakeProcess | None = None, + handler: Handler | None = None, + connect_error: BaseException | None = None, + ) -> None: + self._lines: queue.Queue[bytes | None] = queue.Queue() + self._process = process + self._handler: Handler = handler or (lambda _command, _rid: {"error": "success"}) + self._connect_error = connect_error + self.sent: list[dict[str, Any]] = [] + self.raw: list[bytes] = [] + self.connected = False + self.closed = False + + def connect(self, endpoint: str) -> None: + if self._connect_error is not None: + raise self._connect_error + self.connected = True + + def write_line(self, data: bytes) -> None: + self.raw.append(data) + message = json.loads(data.decode("utf-8")) + self.sent.append(message) + request_id = message.get("request_id") + command = message.get("command", []) + response = self._handler(command, request_id) + if response is not None: + payload = dict(response) + payload.setdefault("request_id", request_id) + self.inject_line((json.dumps(payload) + "\n").encode("utf-8")) + if command and command[0] == "quit" and self._process is not None: + if self._process.exit_on_quit: + self._process.mark_exited(0) + + def inject_line(self, line: bytes) -> None: + self._lines.put(line) + + def inject_json(self, message: dict[str, Any]) -> None: + self.inject_line((json.dumps(message) + "\n").encode("utf-8")) + + def read_line(self, timeout: float) -> bytes | None: + try: + return self._lines.get(timeout=timeout) + except queue.Empty: + return None + + def close(self) -> None: + self.closed = True + + def commands(self) -> list[list[Any]]: + return [message.get("command", []) for message in self.sent] + + +class FakeMpvState: + """Mutable mpv property state used by the default handler.""" + + def __init__(self) -> None: + self.time_pos: float | None = 0.0 + self.pause = True + self.duration: float | None = 2.0 + self.pause_changes: list[bool] = [] + self.frame_step_seconds = 0.0 + """Amount ``time-pos`` advances per frame-step (0 = no simulated advance).""" + + def handler(self, command: list[Any], request_id: int) -> dict[str, Any] | None: + if command and command[0] == "frame-step": + self.time_pos = (self.time_pos or 0.0) + self.frame_step_seconds + elif command and command[0] == "frame-back-step": + self.time_pos = (self.time_pos or 0.0) - self.frame_step_seconds + elif command and command[0] == "get_property": + name = command[1] if len(command) > 1 else "" + if name == "duration": + return {"error": "success", "data": self.duration} + if name == "time-pos": + return {"error": "success", "data": self.time_pos} + if name == "pause": + return {"error": "success", "data": self.pause} + elif command and command[0] == "set_property": + if len(command) > 2 and command[1] == "pause": + self.pause = bool(command[2]) + self.pause_changes.append(self.pause) + return {"error": "success"} + + +class FakeMpv: + """A fake mpv instance plus a controller wired to it.""" + + def __init__( + self, + *, + running: bool = True, + exit_on_quit: bool = True, + wait_results: Sequence[int | None] | None = None, + terminate_works: bool = True, + kill_works: bool = True, + handler: Handler | None = None, + connect_error: BaseException | None = None, + startup_timeout_seconds: float = 1.0, + command_timeout_seconds: float = 1.0, + shutdown_timeout_seconds: float = 0.5, + mpv_executable: str = "mpv", + ) -> None: + self.state = FakeMpvState() + self.process = FakeProcess( + running=running, + exit_on_quit=exit_on_quit, + wait_results=wait_results, + terminate_works=terminate_works, + kill_works=kill_works, + ) + self.transport = FakeTransport( + process=self.process, + handler=handler or self.state.handler, + connect_error=connect_error, + ) + self.arguments: list[str] | None = None + self._settings = ReplayControllerSettings( + mpv_executable=mpv_executable, + startup_timeout_seconds=startup_timeout_seconds, + command_timeout_seconds=command_timeout_seconds, + shutdown_timeout_seconds=shutdown_timeout_seconds, + connect_retry_interval_seconds=0.0, + ) + + def process_factory(self, arguments: Sequence[str]) -> FakeProcess: + self.arguments = list(arguments) + return self.process + + def transport_factory(self) -> FakeTransport: + return self.transport + + def controller(self, **overrides: Any) -> ReplayController: + settings = self._settings + if overrides: + settings = ReplayControllerSettings( + mpv_executable=overrides.get("mpv_executable", settings.mpv_executable), + startup_timeout_seconds=overrides.get( + "startup_timeout_seconds", settings.startup_timeout_seconds + ), + command_timeout_seconds=overrides.get( + "command_timeout_seconds", settings.command_timeout_seconds + ), + shutdown_timeout_seconds=overrides.get( + "shutdown_timeout_seconds", settings.shutdown_timeout_seconds + ), + connect_retry_interval_seconds=0.0, + ) + return ReplayController( + settings, + process_factory=self.process_factory, + transport_factory=self.transport_factory, + sleep=lambda _seconds: None, + ) diff --git a/tests/fake_ndi.py b/tests/fake_ndi.py new file mode 100644 index 0000000..c8421ad --- /dev/null +++ b/tests/fake_ndi.py @@ -0,0 +1,211 @@ +"""Fake NDI backend for tests. + +It implements the :class:`~quickreplay.input.ndi.backend.NdiBackend` protocol +with plain Python objects, so discovery, receiver lifecycle, capture, frame +freeing and timestamp handling can all be exercised in CI without an NDI +runtime or a real source. +""" + +from collections.abc import Sequence +from fractions import Fraction +from typing import Any + +import numpy as np + +from quickreplay.input.ndi.backend import RawAudio, RawMetadata, RawVideo +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction + +DEFAULT_SCRIPT_LENGTH = 6000 +"""Upper bound on the number of raw frames a fake script may hold.""" + + +class FakeNativeBuffer: + """Stands in for native NDI memory. ``freed`` records the free step.""" + + def __init__(self, data: Any) -> None: + self.data = data + self.freed = False + + +class FakeReceiver: + """A scripted receiver. Items are returned in order, then ``None``.""" + + def __init__(self, script: Sequence[Any], source_name: str) -> None: + self._script = list(script) + self._source_name = source_name + self.destroyed = False + self.video_frees = 0 + self.audio_frees = 0 + self.metadata_frees = 0 + + def capture(self, *, timeout_ms: int) -> Any: + if not self._script: + return None + item = self._script.pop(0) + if isinstance(item, BaseException): + raise item + return item + + def free_video(self, frame: RawVideo) -> None: + self.video_frees += 1 + if isinstance(frame.handle, FakeNativeBuffer): + frame.handle.freed = True + + def free_audio(self, frame: RawAudio) -> None: + self.audio_frees += 1 + if isinstance(frame.handle, FakeNativeBuffer): + frame.handle.freed = True + + def free_metadata(self, frame: RawMetadata) -> None: + self.metadata_frees += 1 + if isinstance(frame.handle, FakeNativeBuffer): + frame.handle.freed = True + + def source_name(self) -> str: + return self._source_name + + def destroy(self) -> None: + self.destroyed = True + + +class FakeBackend: + """A scripted :class:`NdiBackend`.""" + + def __init__( + self, + *, + sources: Sequence[str] = (), + script: Sequence[Any] = (), + receiver_error: BaseException | None = None, + ) -> None: + self.sources = tuple(sources) + self._script = list(script) + self._receiver_error = receiver_error + self.initialize_calls = 0 + self.shutdown_calls = 0 + self.create_receiver_calls = 0 + self.receivers: list[FakeReceiver] = [] + + def initialize(self) -> None: + self.initialize_calls += 1 + + def shutdown(self) -> None: + self.shutdown_calls += 1 + + def discover(self, *, timeout_ms: int) -> tuple[str, ...]: + return self.sources + + def create_receiver(self, *, source_name: str, timeout_ms: int) -> FakeReceiver: + self.create_receiver_calls += 1 + if self._receiver_error is not None: + raise self._receiver_error + receiver = FakeReceiver(self._script, source_name) + self.receivers.append(receiver) + return receiver + + +def fake_video( + *, + width: int = 4, + height: int = 2, + stride: int | None = None, + timestamp_ns: int = 0, + fps: Fraction = Fraction(60, 1), + data: np.ndarray | None = None, + pixel_format: str = "UYVY", +) -> RawVideo: + if stride is None: + stride = width * (4 if pixel_format.upper() == "BGRA" else 2) + if data is None: + data = np.arange(height * stride, dtype=np.uint8).reshape(height, stride) + return RawVideo( + width=width, + height=height, + line_stride=stride, + pixel_format=pixel_format, + fps=fps, + timestamp_ns=timestamp_ns, + data=data, + handle=FakeNativeBuffer(data), + ) + + +def fake_audio( + *, + sample_rate: int = 48000, + channels: int = 2, + samples: int = 800, + timestamp_ns: int = 0, + data: np.ndarray | None = None, + audio_format: str = "FLTP", +) -> RawAudio: + if data is None: + data = np.zeros((channels, samples), dtype=np.float32) + return RawAudio( + sample_rate=sample_rate, + channels=channels, + samples=samples, + channel_stride=samples * 4, + audio_format=audio_format, + timestamp_ns=timestamp_ns, + data=data, + handle=FakeNativeBuffer(data), + ) + + +def fake_metadata() -> RawMetadata: + return RawMetadata(handle=FakeNativeBuffer(b"")) + + +def fake_stream_script( + *, + duration_ns: int, + fps: Fraction, + width: int, + height: int, + sample_rate: int | None = None, + channels: int | None = None, + audio_frame_samples: int = 1024, + script_length: int = DEFAULT_SCRIPT_LENGTH, +) -> list[Any]: + """Build an interleaved video/audio script like the media fixture.""" + events: list[tuple[int, int, Any]] = [] + + total_video = int(Fraction(duration_ns) * fps / NANOSECONDS_PER_SECOND) + 1 + for index in range(total_video): + offset = round_fraction(Fraction(index * NANOSECONDS_PER_SECOND, 1) / fps) + if offset > duration_ns: + break + payload = np.full((height, width * 2), index % 256, dtype=np.uint8) + events.append( + ( + offset, + 0, + fake_video(width=width, height=height, fps=fps, timestamp_ns=offset, data=payload), + ) + ) + + if sample_rate is not None and channels is not None: + total_samples = int(Fraction(duration_ns) * sample_rate / NANOSECONDS_PER_SECOND) + position = 0 + while position < total_samples: + count = min(audio_frame_samples, total_samples - position) + offset = round_fraction(Fraction(position * NANOSECONDS_PER_SECOND, sample_rate)) + data = np.zeros((channels, count), dtype=np.float32) + events.append( + ( + offset, + 1, + fake_audio( + sample_rate=sample_rate, + channels=channels, + samples=count, + timestamp_ns=offset, + data=data, + ), + ) + ) + position += count + + events.sort(key=lambda event: (event[0], event[1])) + return [item for _offset, _kind, item in events[:script_length]] diff --git a/tests/fake_ui.py b/tests/fake_ui.py new file mode 100644 index 0000000..eb15cbb --- /dev/null +++ b/tests/fake_ui.py @@ -0,0 +1,224 @@ +"""Fakes for headless UI tests (no Flet, no display).""" + +import threading +import time +from uuid import UUID, uuid4 + +from quickreplay.app.state import ApplicationState +from quickreplay.application.events import ApplicationEvent +from quickreplay.application.models import ApplicationSnapshot +from quickreplay.input.models import InputConfig +from quickreplay.replay.models import SetPoint + + +class FakeController: + """Records calls, the calling thread and the maximum concurrency.""" + + def __init__(self, *, fail_on: str | None = None, delay: float = 0.01) -> None: + self.calls: list[str] = [] + self.threads: list[int] = [] + self.fail_on = fail_on + self.delay = delay + self.active = 0 + self.max_active = 0 + + def _record(self, name: str): + self.calls.append(name) + self.threads.append(threading.get_ident()) + self.active += 1 + self.max_active = max(self.max_active, self.active) + try: + time.sleep(self.delay) + if self.fail_on == name: + raise RuntimeError(f"{name} failed") + return name + finally: + self.active -= 1 + + def start(self) -> None: + self._record("start") + + def start_recording(self, input_config: InputConfig) -> None: + self._record("start_recording") + + def discover_inputs(self) -> UUID: + self._record("discover_inputs") + return uuid4() + + def request_replay(self) -> UUID: + self._record("request_replay") + return uuid4() + + def resume_recording(self) -> UUID: + self._record("resume_recording") + return uuid4() + + def stop_session(self) -> UUID: + self._record("stop_session") + return uuid4() + + def poll(self, timeout: float = 0.0) -> tuple[ApplicationEvent, ...]: + self._record("poll") + return () + + def snapshot(self) -> ApplicationSnapshot: + self._record("snapshot") + return ApplicationSnapshot(state=ApplicationState.IDLE) + + def shutdown(self) -> None: + self._record("shutdown") + + # -- replay delegate --------------------------------------------------- + def play(self) -> None: + self._record("play") + + def pause(self) -> None: + self._record("pause") + + def is_paused(self) -> bool: + self._record("is_paused") + return True + + def step_forward(self) -> None: + self._record("step_forward") + + def step_backward(self) -> None: + self._record("step_backward") + + def seek_frames(self, frames: int) -> None: + self._record("seek_frames") + + def seek_absolute_ns(self, position_ns: int) -> None: + self._record("seek_absolute_ns") + + def replay_position_ns(self) -> int: + self._record("replay_position_ns") + return 0 + + def set_point(self) -> SetPoint: + self._record("set_point") + return SetPoint(position_ns=0) + + def time_difference_ns(self, point: SetPoint) -> int: + self._record("time_difference_ns") + return 0 + + def frame_difference(self, point: SetPoint) -> int: + self._record("frame_difference") + return 0 + + +class FakeBridge: + """A scripted :class:`~quickreplay.ui.bridge.ApplicationUiBridge`.""" + + def __init__(self) -> None: + self.started = False + self.recording_configs: list[InputConfig] = [] + self.discovery_requests: list[str] = [] + self.replay_requests = 0 + self.resume_requests = 0 + self.stop_requests = 0 + self.events: list[ApplicationEvent] = [] + self.snapshot_value = ApplicationSnapshot(state=ApplicationState.IDLE) + self.next_discovery_id = uuid4() + self.shutdown_called = False + self.closed = False + + # -- replay recording -- + self.play_calls = 0 + self.pause_calls = 0 + self.step_forward_calls = 0 + self.step_backward_calls = 0 + self.seek_frames_calls: list[int] = [] + self.seek_absolute_calls: list[int] = [] + self.set_point_calls = 0 + self.position_calls = 0 + self.is_paused_calls = 0 + self.time_difference_points: list[SetPoint] = [] + self.frame_difference_points: list[SetPoint] = [] + self.position_value = 0 + self.paused_value = True + self.set_point_value = 0 + self.time_difference_value = 0 + self.frame_difference_value = 0 + self.position_error: BaseException | None = None + + async def start(self) -> None: + self.started = True + + async def start_recording(self, input_config: InputConfig) -> None: + self.recording_configs.append(input_config) + + async def discover_inputs(self) -> UUID: + self.discovery_requests.append("ndi") + self.next_discovery_id = uuid4() + return self.next_discovery_id + + async def request_replay(self) -> UUID: + self.replay_requests += 1 + return uuid4() + + async def resume_recording(self) -> UUID: + self.resume_requests += 1 + return uuid4() + + async def stop_session(self) -> UUID: + self.stop_requests += 1 + return uuid4() + + async def poll(self, timeout: float = 0.0) -> tuple[ApplicationEvent, ...]: + events = tuple(self.events) + self.events = [] + return events + + async def snapshot(self) -> ApplicationSnapshot: + return self.snapshot_value + + async def shutdown(self) -> None: + self.shutdown_called = True + + async def close(self) -> None: + self.closed = True + + # -- replay delegate --------------------------------------------------- + async def play(self) -> None: + self.play_calls += 1 + self.paused_value = False + + async def pause(self) -> None: + self.pause_calls += 1 + self.paused_value = True + + async def is_paused(self) -> bool: + self.is_paused_calls += 1 + return self.paused_value + + async def step_forward(self) -> None: + self.step_forward_calls += 1 + + async def step_backward(self) -> None: + self.step_backward_calls += 1 + + async def seek_frames(self, frames: int) -> None: + self.seek_frames_calls.append(frames) + + async def seek_absolute_ns(self, position_ns: int) -> None: + self.seek_absolute_calls.append(position_ns) + + async def replay_position_ns(self) -> int: + self.position_calls += 1 + if self.position_error is not None: + raise self.position_error + return self.position_value + + async def set_point(self) -> SetPoint: + self.set_point_calls += 1 + return SetPoint(position_ns=self.set_point_value) + + async def time_difference_ns(self, point: SetPoint) -> int: + self.time_difference_points.append(point) + return self.time_difference_value + + async def frame_difference(self, point: SetPoint) -> int: + self.frame_difference_points.append(point) + return self.frame_difference_value diff --git a/tests/fake_worker_input.py b/tests/fake_worker_input.py new file mode 100644 index 0000000..4b9c5b8 --- /dev/null +++ b/tests/fake_worker_input.py @@ -0,0 +1,284 @@ +"""Fake InputSource and worker test harness for the recorder worker tests.""" + +import queue +import threading +import time +from collections.abc import Callable, Sequence +from fractions import Fraction +from typing import Any, TypeVar + +import numpy as np + +from quickreplay.input.models import ( + AudioFrame, + AudioStreamInfo, + InputConfig, + StreamInfo, + VideoFrame, + VideoStreamInfo, +) +from quickreplay.recording.events import WorkerEvent, WorkerStateChanged +from quickreplay.recording.models import WorkerState +from quickreplay.replay.asset_builder import ReplayAssetBuilder +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction +from quickreplay.worker.inputs import InputSourceHandle +from quickreplay.worker.runtime import RecorderWorkerRuntime +from quickreplay.worker.settings import RecorderWorkerSettings + +EventT = TypeVar("EventT", bound=WorkerEvent) + + +def video_info( + fps: Fraction, width: int = 64, height: int = 36, pixel_format: str = "BGR24" +) -> VideoStreamInfo: + return VideoStreamInfo(width, height, fps, pixel_format) + + +def audio_info(sample_rate: int = 48000, channels: int = 2) -> AudioStreamInfo: + return AudioStreamInfo(sample_rate, channels) + + +def video_frame( + timestamp_ns: int, *, fps: Fraction, width: int = 64, height: int = 36, value: int = 0 +) -> VideoFrame: + data = np.full((height, width, 3), value % 256, dtype=np.uint8) + return VideoFrame(timestamp_ns, width, height, fps, "BGR24", data) + + +def audio_frame( + timestamp_ns: int, *, sample_rate: int = 48000, channels: int = 2, samples: int = 1024 +) -> AudioFrame: + data = np.zeros((channels, samples), dtype=np.float32) + return AudioFrame(timestamp_ns, sample_rate, channels, samples, data) + + +def build_script( + *, + duration_ns: int, + fps: Fraction, + base_ns: int = 0, + width: int = 64, + height: int = 36, + sample_rate: int | None = None, + channels: int | None = None, + audio_frame_samples: int = 1024, + audio_delay_ns: int = 0, +) -> tuple[list[Any], int, int]: + """Build an interleaved arrival script. + + Returns ``(script, video_frames, audio_samples)``. Audio events are placed + in arrival order at ``timestamp + audio_delay_ns`` while keeping their real + timestamps, which models audio arriving later than video. + """ + events: list[tuple[int, int, Any]] = [] + video_frames = 0 + index = 0 + while True: + offset = round_fraction(Fraction(index * NANOSECONDS_PER_SECOND, 1) / fps) + if offset > duration_ns: + break + timestamp_ns = base_ns + offset + events.append( + (offset, 0, video_frame(timestamp_ns, fps=fps, width=width, height=height, value=index)) + ) + video_frames += 1 + index += 1 + + audio_samples = 0 + if sample_rate is not None and channels is not None: + total = int(Fraction(duration_ns) * sample_rate / NANOSECONDS_PER_SECOND) + position = 0 + while position < total: + count = min(audio_frame_samples, total - position) + offset = round_fraction(Fraction(position * NANOSECONDS_PER_SECOND, sample_rate)) + events.append( + ( + offset + audio_delay_ns, + 1, + audio_frame( + base_ns + offset, + sample_rate=sample_rate, + channels=channels, + samples=count, + ), + ) + ) + audio_samples += count + position += count + + events.sort(key=lambda event: (event[0], event[1])) + return [item for _key, _kind, item in events], video_frames, audio_samples + + +class FakeInputSource: + """A scripted :class:`~quickreplay.input.source.InputSource`.""" + + def __init__( + self, + script: Sequence[Any], + *, + video_stream: VideoStreamInfo, + audio_stream: AudioStreamInfo | None = None, + ) -> None: + self._script = list(script) + self._video_stream = video_stream + self._audio_stream = audio_stream + self._seen_video = False + self._seen_audio = False + self.open_count = 0 + self.close_count = 0 + + def open(self) -> None: + self.open_count += 1 + + def read(self) -> VideoFrame | AudioFrame | None: + while True: + if not self._script: + return None + item = self._script.pop(0) + if isinstance(item, BaseException): + raise item + if callable(item) and not isinstance(item, (VideoFrame, AudioFrame)): + item() + continue + if isinstance(item, VideoFrame): + self._seen_video = True + elif isinstance(item, AudioFrame): + self._seen_audio = True + return item + + @property + def stream_info(self) -> StreamInfo | None: + if not self._seen_video: + return None + audio = self._audio_stream if self._seen_audio else None + return StreamInfo(video=self._video_stream, audio=audio) + + def close(self) -> None: + self.close_count += 1 + + +class ScriptedInputFactory: + """Creates a fresh :class:`FakeInputSource` per call with a new epoch.""" + + def __init__( + self, + *, + fps: Fraction = Fraction(60, 1), + width: int = 64, + height: int = 36, + duration_ns: int = 1_500_000_000, + supports_audio: bool = True, + audio: bool = True, + audio_delay_ns: int = 0, + ) -> None: + self.fps = fps + self.width = width + self.height = height + self.duration_ns = duration_ns + self.supports_audio = supports_audio + self.audio = audio and supports_audio + self.audio_delay_ns = audio_delay_ns + self.calls = 0 + self.sources: list[FakeInputSource] = [] + self.video_frames = 0 + self.audio_samples = 0 + + def __call__(self, _config: InputConfig) -> InputSourceHandle: + base_ns = 1_000_000_000 + self.calls * 100_000_000_000 + self.calls += 1 + script, video_frames, audio_samples = build_script( + duration_ns=self.duration_ns, + fps=self.fps, + base_ns=base_ns, + width=self.width, + height=self.height, + sample_rate=48000 if self.audio else None, + channels=2 if self.audio else None, + audio_delay_ns=self.audio_delay_ns, + ) + self.video_frames += video_frames + self.audio_samples += audio_samples + source = FakeInputSource( + script, + video_stream=video_info(self.fps, self.width, self.height), + audio_stream=audio_info() if self.audio else None, + ) + self.sources.append(source) + return InputSourceHandle(source=source, supports_audio=self.supports_audio) + + +class WorkerHarness: + """Runs :class:`RecorderWorkerRuntime` in-process over thread queues.""" + + def __init__( + self, + settings: RecorderWorkerSettings, + *, + input_factory: Callable[[InputConfig], InputSourceHandle], + discovery: Callable[..., tuple[Any, ...]] | None = None, + builder_factory: Callable[[], ReplayAssetBuilder] = ReplayAssetBuilder, + ) -> None: + self.commands: queue.Queue[Any] = queue.Queue() + self.events: queue.Queue[WorkerEvent] = queue.Queue() + self.seen: list[WorkerEvent] = [] + self.runtime = RecorderWorkerRuntime( + settings, + command_queue=self.commands, + emit=self._emit, + input_factory=input_factory, + discovery=discovery or (lambda **_kwargs: ()), + builder_factory=builder_factory, + ) + self.thread = threading.Thread(target=self.runtime.run, daemon=True) + + def _emit(self, event: WorkerEvent) -> None: + self.seen.append(event) + self.events.put(event) + + def join(self, timeout: float = 10.0) -> None: + self.thread.join(timeout) + + def start(self) -> None: + self.thread.start() + + def send(self, command: Any) -> None: + self.commands.put(command) + + def wait_event( + self, + event_type: type[EventT], + *, + predicate: Callable[[EventT], bool] | None = None, + timeout: float = 10.0, + description: str | None = None, + ) -> EventT: + label = description or event_type.__name__ + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + event = self.events.get(timeout=0.05) + except queue.Empty: + continue + if isinstance(event, event_type) and (predicate is None or predicate(event)): + return event + recent = [type(event).__name__ for event in self.seen[-8:]] + raise AssertionError(f"timed out waiting for {label}; recent events: {recent}") + + def wait_state(self, state: WorkerState, *, timeout: float = 10.0) -> None: + self.wait_event( + WorkerStateChanged, + predicate=lambda event: event.state == state, + timeout=timeout, + description=f"state {state}", + ) + + def shutdown(self) -> None: + self.send(_shutdown()) + self.thread.join(timeout=10.0) + + +def _shutdown() -> Any: + from quickreplay.recording.commands import Shutdown + + return Shutdown() diff --git a/tests/test_app_state.py b/tests/test_app_state.py new file mode 100644 index 0000000..e84318c --- /dev/null +++ b/tests/test_app_state.py @@ -0,0 +1,32 @@ +"""Tests for the application state machine.""" + +from quickreplay.app.state import ApplicationState, can_transition + + +def test_all_states_exist() -> None: + assert {state.name for state in ApplicationState} == { + "STARTING", + "IDLE", + "RECORDING", + "PREPARING_REPLAY", + "REPLAY", + "STOPPING", + "RESUMING", + "ERROR", + "SHUTTING_DOWN", + } + + +def test_replay_cycle_transitions_are_allowed() -> None: + assert can_transition(ApplicationState.RECORDING, ApplicationState.PREPARING_REPLAY) + assert can_transition(ApplicationState.PREPARING_REPLAY, ApplicationState.REPLAY) + assert can_transition(ApplicationState.REPLAY, ApplicationState.RESUMING) + assert can_transition(ApplicationState.RECORDING, ApplicationState.STOPPING) + assert can_transition(ApplicationState.REPLAY, ApplicationState.STOPPING) + assert can_transition(ApplicationState.RESUMING, ApplicationState.RECORDING) + + +def test_invalid_transition_is_rejected() -> None: + assert not can_transition(ApplicationState.IDLE, ApplicationState.REPLAY) + assert not can_transition(ApplicationState.RECORDING, ApplicationState.REPLAY) + assert not can_transition(ApplicationState.SHUTTING_DOWN, ApplicationState.IDLE) diff --git a/tests/test_application_controller.py b/tests/test_application_controller.py new file mode 100644 index 0000000..30c7d42 --- /dev/null +++ b/tests/test_application_controller.py @@ -0,0 +1,728 @@ +"""ApplicationController: lifecycle, correlation, delegation and shutdown.""" + +from fractions import Fraction +from pathlib import Path +from uuid import uuid4 + +import pytest +from fake_application import ( + FakeReplayFactory, + FakeWorker, + SequenceRequestIds, +) + +from quickreplay.app.state import ApplicationState +from quickreplay.application.controller import ApplicationController +from quickreplay.application.errors import InvalidApplicationStateError, WorkerStartupError +from quickreplay.application.events import ( + ApplicationError, + ApplicationStateChanged, + InputsChanged, + RecordingMetricsChanged, + RecordingStarted, + ReplayStarted, +) +from quickreplay.application.models import ApplicationControllerSettings +from quickreplay.input.models import ( + AudioStreamInfo, + NdiInputConfig, + NdiInputDescriptor, + StreamInfo, + VideoStreamInfo, +) +from quickreplay.recording.commands import ( + ChangeInput, + DiscoverInputs, + PrepareReplay, + ResumeRecording, + Shutdown, + StartRecording, + StopSession, +) +from quickreplay.recording.events import ( + InputsDiscovered, + RecordingMetricsUpdated, + ReplayPrepared, + SessionStopped, + StreamStarted, + WorkerError, + WorkerStateChanged, +) +from quickreplay.recording.models import RecordingMetrics, WorkerErrorCode, WorkerState +from quickreplay.replay.errors import MpvProcessExitedError, MpvStartupError +from quickreplay.replay.models import ReplayAsset, frame_difference + +FPS = Fraction(60, 1) + + +def _info(fps: Fraction = FPS) -> StreamInfo: + return StreamInfo( + video=VideoStreamInfo(64, 36, fps, "BGR24"), + audio=AudioStreamInfo(48000, 2), + ) + + +def _metrics(frames: int = 10) -> RecordingMetrics: + return RecordingMetrics( + captured_video_frames=frames, + recorded_video_frames=frames, + captured_audio_samples=0, + recorded_audio_samples=0, + video_queue_drops=0, + audio_queue_drops=0, + buffer_duration_ns=1_000_000_000, + segment_count=1, + input_fps=60.0, + recording_fps=60.0, + ) + + +def _ids_after_start(*request_ids): + """Reserve the first deterministic ID for the initial StartRecording.""" + return SequenceRequestIds(uuid4(), *request_ids) + + +def _asset() -> ReplayAsset: + return ReplayAsset(Path("replay.mkv"), 1_000_000_000, FPS) + + +def _app( + worker: FakeWorker, + replay_factory: FakeReplayFactory | None = None, + *, + request_id_factory=uuid4, + settings: ApplicationControllerSettings | None = None, +) -> ApplicationController: + return ApplicationController( + settings or ApplicationControllerSettings(), + worker_factory=lambda: worker, + replay_controller_factory=replay_factory or FakeReplayFactory(), + request_id_factory=request_id_factory, + ) + + +def _to_recording( + worker: FakeWorker, + replay_factory: FakeReplayFactory | None = None, + **kwargs, +) -> ApplicationController: + app = _app(worker, replay_factory, **kwargs) + app.start() + app.poll() + app.start_recording(NdiInputConfig("fake")) + start_request = worker.commands_of(StartRecording)[0] + worker.push(StreamStarted(stream_info=_info(), request_id=start_request.request_id)) + app.poll() + assert app.state == ApplicationState.RECORDING + return app + + +def _to_replay( + worker: FakeWorker, replay_factory: FakeReplayFactory, replay_id +) -> ApplicationController: + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + app.request_replay() + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + app.poll() + assert app.state == ApplicationState.REPLAY + return app + + +def test_start_reaches_idle() -> None: + worker = FakeWorker() + app = _app(worker) + + app.start() + + assert app.state == ApplicationState.IDLE + assert worker.started + events = app.poll() + assert ApplicationStateChanged(ApplicationState.IDLE) in events + + +def test_double_start_is_rejected() -> None: + worker = FakeWorker() + app = _app(worker) + app.start() + with pytest.raises(InvalidApplicationStateError): + app.start() + + +def test_start_timeout_enters_error() -> None: + worker = FakeWorker(auto_idle=False) + settings = ApplicationControllerSettings(worker_start_timeout_seconds=0.05) + app = _app(worker, settings=settings) + + with pytest.raises(WorkerStartupError): + app.start() + + assert app.state == ApplicationState.ERROR + + +def test_start_process_exit_enters_error() -> None: + worker = FakeWorker(auto_idle=False) + worker.die(2) + app = _app(worker) + + with pytest.raises(WorkerStartupError): + app.start() + + assert app.state == ApplicationState.ERROR + + +def test_start_recording() -> None: + start_id = uuid4() + worker = FakeWorker() + app = _app(worker, request_id_factory=SequenceRequestIds(start_id)) + app.start() + app.poll() + + app.start_recording(NdiInputConfig("fake")) + + assert app.state == ApplicationState.STARTING + starts = worker.commands_of(StartRecording) + assert starts and starts[0].request_id == start_id + + worker.push(StreamStarted(stream_info=_info(), request_id=start_id)) + events = app.poll() + + assert app.state == ApplicationState.RECORDING + assert app.snapshot().stream_info == _info() + assert any(isinstance(event, RecordingStarted) for event in events) + + +def test_restart_uses_fresh_start_id_and_ignores_stale_start_result() -> None: + start_a, stop_id, start_b = uuid4(), uuid4(), uuid4() + worker = FakeWorker() + app = _app(worker, request_id_factory=SequenceRequestIds(start_a, stop_id, start_b)) + app.start() + app.poll() + + app.start_recording(NdiInputConfig("same source")) + worker.push(StreamStarted(stream_info=_info(), request_id=start_a)) + app.poll() + worker.push(RecordingMetricsUpdated(metrics=_metrics())) + app.poll() + assert app.snapshot().metrics == _metrics() + + assert app.stop_session() == stop_id + worker.push(SessionStopped(request_id=stop_id)) + app.poll() + assert app.state == ApplicationState.IDLE + assert app.snapshot().stream_info is None + assert app.snapshot().metrics is None + assert app.snapshot().replay_asset is None + + app.start_recording(NdiInputConfig("same source")) + starts = worker.commands_of(StartRecording) + assert [command.request_id for command in starts] == [start_a, start_b] + assert app.snapshot().stream_info is None + assert app.snapshot().metrics is None + assert app.snapshot().error_message is None + + worker.push(StreamStarted(stream_info=_info(Fraction(30, 1)), request_id=start_a)) + worker.push(WorkerError(WorkerErrorCode.ENCODER_FAILED, "stale failure", request_id=start_a)) + app.poll() + assert app.state == ApplicationState.STARTING + assert app.snapshot().stream_info is None + assert app.snapshot().error_message is None + + new_info = _info(Fraction(30, 1)) + worker.push(StreamStarted(stream_info=new_info, request_id=start_b)) + app.poll() + assert app.state == ApplicationState.RECORDING + assert app.snapshot().stream_info == new_info + + +def test_replay_lifecycle() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + + app.request_replay() + + assert app.state == ApplicationState.PREPARING_REPLAY + prepared = worker.commands_of(PrepareReplay) + assert prepared and prepared[0].request_id == replay_id + + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + events = app.poll() + + assert app.state == ApplicationState.REPLAY + assert replay_factory.controllers[0].calls[0] == "open" + assert app.snapshot().replay_asset == _asset() + assert any(isinstance(event, ReplayStarted) for event in events) + + +def test_stale_replay_prepared_is_ignored() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + app.request_replay() + + worker.push(ReplayPrepared(request_id=uuid4(), asset=_asset())) + app.poll() + + assert app.state == ApplicationState.PREPARING_REPLAY + assert replay_factory.controllers == [] + + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + app.poll() + + assert app.state == ApplicationState.REPLAY + + +def test_replay_open_failure_enters_error() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory(open_error=MpvStartupError("mpv missing")) + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + app.request_replay() + + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + events = app.poll() + + assert app.state == ApplicationState.ERROR + assert replay_factory.controllers[0].calls == ["open", "close"] + assert any(isinstance(event, ApplicationError) for event in events) + + +def test_stop_session_from_recording_waits_for_worker_completion() -> None: + worker = FakeWorker() + app = _to_recording(worker) + + request_id = app.stop_session() + assert app.state == ApplicationState.STOPPING + assert worker.commands_of(StopSession)[0].request_id == request_id + with pytest.raises(InvalidApplicationStateError): + app.request_replay() + + worker.push(SessionStopped(request_id=request_id)) + events = app.poll() + + assert app.state == ApplicationState.IDLE + assert app.stream_info is None + assert app.snapshot().metrics is None + assert any(isinstance(event, ApplicationStateChanged) for event in events) + + +def test_stop_session_from_replay_closes_without_resuming() -> None: + worker = FakeWorker() + replay_factory = FakeReplayFactory() + replay_id = uuid4() + app = _to_replay(worker, replay_factory, replay_id) + replay = replay_factory.controllers[0] + + request_id = app.stop_session() + assert replay.calls[-1] == "close" + assert not worker.commands_of(ResumeRecording) + assert worker.commands_of(StopSession)[0].request_id == request_id + assert app.state == ApplicationState.STOPPING + with pytest.raises(InvalidApplicationStateError): + app.replay_position_ns() + + worker.push(SessionStopped(request_id=request_id)) + app.poll() + + assert app.state == ApplicationState.IDLE + assert app.replay_asset is None + + +def test_stop_session_is_rejected_during_replay_preparation() -> None: + worker = FakeWorker() + app = _to_recording(worker) + app.request_replay() + + with pytest.raises(InvalidApplicationStateError): + app.stop_session() + + +def test_resume_lifecycle() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + + app.resume_recording() + + assert app.state == ApplicationState.RESUMING + assert replay_factory.controllers[0].calls[-1] == "close" + resumes = worker.commands_of(ResumeRecording) + assert resumes + + worker.push(StreamStarted(stream_info=_info(), request_id=resumes[0].request_id)) + app.poll() + + assert app.state == ApplicationState.RECORDING + assert app.snapshot().replay_asset is None + + +def test_replay_is_closed_before_resume_is_sent() -> None: + order: list[tuple[str, str | None]] = [] + replay_id = uuid4() + worker = FakeWorker() + worker.order = order + replay_factory = FakeReplayFactory(order=order) + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + app.request_replay() + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + app.poll() + + app.resume_recording() + + assert order.index(("replay.close", None)) < order.index(("worker.send", "ResumeRecording")) + + +def test_stale_resume_response_is_ignored() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + app.resume_recording() + + worker.push(StreamStarted(stream_info=_info(), request_id=uuid4())) + app.poll() + assert app.state == ApplicationState.RESUMING + + resume_id = worker.commands_of(ResumeRecording)[0].request_id + worker.push(StreamStarted(stream_info=_info(), request_id=resume_id)) + app.poll() + assert app.state == ApplicationState.RECORDING + + +def test_change_input() -> None: + change_id = uuid4() + worker = FakeWorker() + app = _to_recording(worker, request_id_factory=_ids_after_start(change_id)) + new_info = _info() + + returned = app.change_input(NdiInputConfig("cam")) + + assert returned == change_id + assert app.state == ApplicationState.STARTING + changes = worker.commands_of(ChangeInput) + assert changes and changes[0].request_id == change_id + + worker.push(StreamStarted(stream_info=new_info, request_id=change_id)) + app.poll() + + assert app.state == ApplicationState.RECORDING + assert app.snapshot().stream_info == new_info + + +def test_stale_change_input_response_does_not_override() -> None: + change_id = uuid4() + worker = FakeWorker() + app = _to_recording(worker, request_id_factory=_ids_after_start(change_id)) + original = app.snapshot().stream_info + app.change_input(NdiInputConfig("cam")) + + worker.push(StreamStarted(stream_info=_info(), request_id=uuid4())) + app.poll() + + assert app.state == ApplicationState.STARTING + assert app.snapshot().stream_info == original + + +def test_discovery_does_not_change_state() -> None: + discovery_id = uuid4() + worker = FakeWorker() + app = _to_recording(worker, request_id_factory=_ids_after_start(discovery_id)) + descriptor = NdiInputDescriptor("PC (OBS)") + + returned = app.discover_inputs() + + assert returned == discovery_id + assert app.state == ApplicationState.RECORDING + assert worker.commands_of(DiscoverInputs) + + worker.push(InputsDiscovered(request_id=discovery_id, inputs=(descriptor,))) + events = app.poll() + + assert app.state == ApplicationState.RECORDING + assert InputsChanged(request_id=discovery_id, inputs=(descriptor,)) in events + + +def test_discovery_error_is_non_fatal() -> None: + discovery_id = uuid4() + worker = FakeWorker() + app = _to_recording(worker, request_id_factory=_ids_after_start(discovery_id)) + app.discover_inputs() + + worker.push( + WorkerError( + code=WorkerErrorCode.INTERNAL_ERROR, + message="discovery failed", + request_id=discovery_id, + ) + ) + events = app.poll() + + assert app.state == ApplicationState.RECORDING + assert any(isinstance(event, ApplicationError) for event in events) + + +def test_metrics_are_recorded_and_emitted() -> None: + worker = FakeWorker() + app = _to_recording(worker) + metrics = _metrics(120) + + worker.push(RecordingMetricsUpdated(metrics=metrics)) + events = app.poll() + + assert app.snapshot().metrics == metrics + assert RecordingMetricsChanged(metrics=metrics) in events + + +def test_metrics_after_replay_request_are_ignored() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + worker.push(RecordingMetricsUpdated(metrics=_metrics(50))) + app.poll() + app.request_replay() + + worker.push(RecordingMetricsUpdated(metrics=_metrics(999))) + app.poll() + + assert app.snapshot().metrics is None + + +def test_worker_error_enters_error() -> None: + worker = FakeWorker() + app = _to_recording(worker) + + worker.push(WorkerError(code=WorkerErrorCode.CAPTURE_FAILED, message="capture failed")) + events = app.poll() + + assert app.state == ApplicationState.ERROR + assert any(isinstance(event, ApplicationError) for event in events) + + +def test_worker_error_state_enters_error() -> None: + worker = FakeWorker() + app = _to_recording(worker) + + worker.push(WorkerStateChanged(state=WorkerState.ERROR)) + app.poll() + + assert app.state == ApplicationState.ERROR + + +def test_worker_process_death_enters_error() -> None: + worker = FakeWorker() + app = _to_recording(worker) + + worker.die(3) + app.poll() + + assert app.state == ApplicationState.ERROR + assert "3" in (app.snapshot().error_message or "") + + +def test_mpv_unexpected_exit_resumes_recording() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + replay_factory.controllers[0].dead = True + + app.poll() + + assert app.state == ApplicationState.RESUMING + assert replay_factory.controllers[0].calls[-1] == "close" + resumes = worker.commands_of(ResumeRecording) + assert resumes + + worker.push(StreamStarted(stream_info=_info(), request_id=resumes[0].request_id)) + app.poll() + assert app.state == ApplicationState.RECORDING + + +def test_replay_operation_on_dead_mpv_resumes() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + replay_factory.controllers[0].dead = True + + with pytest.raises(MpvProcessExitedError): + app.play() + + assert app.state == ApplicationState.RESUMING + + +def test_resume_failure_enters_error() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + app.resume_recording() + resume_id = worker.commands_of(ResumeRecording)[0].request_id + + worker.push( + WorkerError( + code=WorkerErrorCode.INTERNAL_ERROR, message="resume failed", request_id=resume_id + ) + ) + app.poll() + + assert app.state == ApplicationState.ERROR + + +def test_replay_operations_are_delegated() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + replay = replay_factory.controllers[0] + + app.play() + app.pause() + app.step_forward() + app.step_backward() + app.seek_frames(5) + app.seek_absolute_ns(1_000_000) + + assert replay.calls == [ + "open", + "play", + "pause", + "step_forward", + "step_backward", + ("seek_frames", 5), + ("seek_absolute_ns", 1_000_000), + ] + + replay.position = 2_000_000_000 + assert app.replay_position_ns() == 2_000_000_000 + point = app.set_point() + assert point.position_ns == 2_000_000_000 + replay.position = 2_050_000_000 + assert app.time_difference_ns(point) == 50_000_000 + assert app.frame_difference(point) == frame_difference(2_050_000_000, 2_000_000_000, FPS) + + +def test_invalid_operations_are_rejected() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _app(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + + with pytest.raises(InvalidApplicationStateError): + app.request_replay() + + app.start() + app.poll() + with pytest.raises(InvalidApplicationStateError): + app.resume_recording() + + app.start_recording(NdiInputConfig("fake")) + start_request = worker.commands_of(StartRecording)[0] + worker.push(StreamStarted(stream_info=_info(), request_id=start_request.request_id)) + app.poll() + with pytest.raises(InvalidApplicationStateError): + app.play() + with pytest.raises(InvalidApplicationStateError): + app.resume_recording() + + app.request_replay() + with pytest.raises(InvalidApplicationStateError): + app.request_replay() + + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + app.poll() + with pytest.raises(InvalidApplicationStateError): + app.change_input(NdiInputConfig("cam")) + + app.resume_recording() + with pytest.raises(InvalidApplicationStateError): + app.resume_recording() + with pytest.raises(InvalidApplicationStateError): + app.play() + + +def test_shutdown_from_idle() -> None: + worker = FakeWorker() + app = _app(worker) + app.start() + app.poll() + + app.shutdown() + + assert app.state == ApplicationState.SHUTTING_DOWN + assert worker.commands_of(Shutdown) + assert worker.join_calls >= 1 + assert worker.closed + + app.shutdown() # idempotent + assert worker.join_calls == 1 + + +def test_shutdown_from_recording_is_graceful() -> None: + worker = FakeWorker() + app = _to_recording(worker) + + app.shutdown() + + assert app.state == ApplicationState.SHUTTING_DOWN + assert worker.terminate_calls == 0 + assert worker.closed + + +def test_shutdown_terminates_when_worker_does_not_exit() -> None: + worker = FakeWorker(exit_on_shutdown=False) + app = _to_recording(worker) + + app.shutdown() + + assert worker.terminate_calls == 1 + + +def test_shutdown_from_replay_closes_replay_first() -> None: + order: list[tuple[str, str | None]] = [] + replay_id = uuid4() + worker = FakeWorker() + worker.order = order + replay_factory = FakeReplayFactory(order=order) + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + app.request_replay() + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + app.poll() + + app.shutdown() + + assert order.index(("replay.close", None)) < order.index(("worker.send", "Shutdown")) + + +def test_shutdown_during_preparing_replay_ignores_late_prepared() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_recording(worker, replay_factory, request_id_factory=_ids_after_start(replay_id)) + app.request_replay() + + app.shutdown() + worker.push(ReplayPrepared(request_id=replay_id, asset=_asset())) + app.poll() + + assert app.state == ApplicationState.SHUTTING_DOWN + assert replay_factory.controllers == [] + + +def test_shutdown_during_resuming_ignores_late_stream_started() -> None: + replay_id = uuid4() + worker = FakeWorker() + replay_factory = FakeReplayFactory() + app = _to_replay(worker, replay_factory, replay_id) + app.resume_recording() + resume_id = worker.commands_of(ResumeRecording)[0].request_id + + app.shutdown() + worker.push(StreamStarted(stream_info=_info(), request_id=resume_id)) + app.poll() + + assert app.state == ApplicationState.SHUTTING_DOWN diff --git a/tests/test_application_integration.py b/tests/test_application_integration.py new file mode 100644 index 0000000..2b6ca0f --- /dev/null +++ b/tests/test_application_integration.py @@ -0,0 +1,119 @@ +"""ApplicationController with the real in-process recorder runtime. + +The recorder worker runs its real command loop, capture/encode threads, +SegmentRecorder, RingStorage and ReplayAssetBuilder, driven by a fake input +source. Only the replay controller (mpv) is faked, so no mpv or hardware is +required. +""" + +import queue +import time +from collections.abc import Callable +from pathlib import Path + +from fake_application import FakeReplayFactory +from fake_worker_input import ScriptedInputFactory, WorkerHarness + +from quickreplay.app.state import ApplicationState +from quickreplay.application.controller import ApplicationController +from quickreplay.application.models import ApplicationControllerSettings +from quickreplay.input.models import NdiInputConfig +from quickreplay.worker.settings import RecorderWorkerSettings + + +class InProcessWorkerHandle: + """Adapts the Phase 7 in-process worker harness to the WorkerHandle API.""" + + def __init__(self, settings: RecorderWorkerSettings, input_factory) -> None: + self._harness = WorkerHarness(settings, input_factory=input_factory) + + def start(self) -> None: + self._harness.start() + + def send(self, command) -> None: + self._harness.send(command) + + def get_event(self, timeout: float | None = None): + try: + return self._harness.events.get(timeout=timeout) + except queue.Empty: + return None + + def is_alive(self) -> bool: + return self._harness.thread.is_alive() + + @property + def exitcode(self) -> int | None: + return None if self._harness.thread.is_alive() else 0 + + def join(self, timeout: float | None = None) -> None: + self._harness.thread.join(timeout) + + def terminate(self) -> None: + return None + + def close(self) -> None: + return None + + +def _captured_at_least(app: ApplicationController, minimum: int) -> bool: + metrics = app.snapshot().metrics + return metrics is not None and metrics.captured_video_frames >= minimum + + +def _poll_until( + app: ApplicationController, predicate: Callable[[], bool], timeout: float = 5.0 +) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + app.poll(timeout=0.02) + if predicate(): + return + raise AssertionError("condition was not met in time") + + +def test_application_recording_replay_resume(tmp_path: Path) -> None: + worker_settings = RecorderWorkerSettings( + working_directory=tmp_path, + metrics_interval_ns=20_000_000, + stream_start_timeout_ns=2_000_000_000, + video_queue_capacity=4096, + audio_queue_capacity=4096, + ) + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + handle = InProcessWorkerHandle(worker_settings, factory) + replay_factory = FakeReplayFactory() + app = ApplicationController( + ApplicationControllerSettings(worker=worker_settings), + worker_factory=lambda: handle, + replay_controller_factory=replay_factory, + ) + + app.start() + assert app.state == ApplicationState.IDLE + + app.start_recording(NdiInputConfig("fake")) + _poll_until(app, lambda: app.state == ApplicationState.RECORDING) + assert app.snapshot().stream_info is not None + + _poll_until(app, lambda: _captured_at_least(app, factory.video_frames), timeout=10.0) + + app.request_replay() + assert app.state == ApplicationState.PREPARING_REPLAY + _poll_until(app, lambda: app.state == ApplicationState.REPLAY, timeout=10.0) + + asset = app.snapshot().replay_asset + assert asset is not None + assert asset.path.exists() + assert replay_factory.controllers[0].calls[0] == "open" + + app.resume_recording() + assert app.state == ApplicationState.RESUMING + _poll_until(app, lambda: app.state == ApplicationState.RECORDING, timeout=10.0) + + assert app.snapshot().replay_asset is None + assert factory.calls == 2 + + app.shutdown() + assert app.state == ApplicationState.SHUTTING_DOWN + assert not handle.is_alive() diff --git a/tests/test_configuration_codec.py b/tests/test_configuration_codec.py new file mode 100644 index 0000000..61e3afd --- /dev/null +++ b/tests/test_configuration_codec.py @@ -0,0 +1,126 @@ +"""Configuration JSON codec: strict validation and round trips.""" + +import pytest + +from quickreplay.configuration.codec import ( + config_from_json_object, + config_to_json_object, +) +from quickreplay.configuration.errors import ( + ConfigurationValidationError, + UnsupportedConfigVersionError, +) +from quickreplay.configuration.models import ( + QuickReplayConfig, + RecordingConfig, + ReplayConfig, +) +from quickreplay.input.models import NdiInputConfig + + +def test_default_round_trip() -> None: + config = QuickReplayConfig() + restored = config_from_json_object(config_to_json_object(config)) + assert restored == config + + +def test_canonical_json_object() -> None: + obj = config_to_json_object(QuickReplayConfig()) + assert list(obj) == ["schema_version", "input", "recording", "replay", "ui"] + assert obj == { + "schema_version": 1, + "input": None, + "recording": {"buffer_duration_seconds": 120}, + "replay": {"mpv_executable": "mpv"}, + "ui": {}, + } + + +def test_ndi_round_trip() -> None: + config = QuickReplayConfig(input=NdiInputConfig("OBS")) + restored = config_from_json_object(config_to_json_object(config)) + assert restored.input == NdiInputConfig("OBS") + + +def test_unicode_ndi_round_trip() -> None: + source = "配信用PC (NDI ソース)" + config = QuickReplayConfig(input=NdiInputConfig(source)) + obj = config_to_json_object(config) + assert obj["input"] == {"type": "ndi", "source_name": source} + assert config_from_json_object(obj).input == NdiInputConfig(source) + + +def test_missing_sections_use_defaults() -> None: + restored = config_from_json_object({"schema_version": 1}) + assert restored == QuickReplayConfig() + + +def test_unknown_input_type_is_rejected() -> None: + with pytest.raises(ConfigurationValidationError): + config_from_json_object({"schema_version": 1, "input": {"type": "foo"}}) + + +def test_camera_input_type_is_unsupported() -> None: + with pytest.raises(ConfigurationValidationError, match="input.type 'camera' is not supported"): + config_from_json_object({"schema_version": 1, "input": {"type": "camera"}}) + + +@pytest.mark.parametrize( + "value", + [ + {"schema_version": 1, "extra": 1}, + {"schema_version": 1, "recording": {"buffer_duration_seconds": 120, "x": 1}}, + {"schema_version": 1, "replay": {"mpv_executable": "mpv", "x": 1}}, + {"schema_version": 1, "ui": {"x": 1}}, + {"schema_version": 1, "input": {"type": "ndi", "source_name": "x", "y": 1}}, + ], +) +def test_unknown_fields_are_rejected(value: object) -> None: + with pytest.raises(ConfigurationValidationError): + config_from_json_object(value) + + +@pytest.mark.parametrize("version", [0, 2, 999, "1", True, None, 1.0]) +def test_invalid_schema_version_is_rejected(version: object) -> None: + with pytest.raises((UnsupportedConfigVersionError, ConfigurationValidationError)): + config_from_json_object({"schema_version": version}) + + +def test_missing_schema_version_is_rejected() -> None: + with pytest.raises(ConfigurationValidationError): + config_from_json_object({}) + + +@pytest.mark.parametrize( + "value", + [ + {"schema_version": 1, "recording": {"buffer_duration_seconds": True}}, + {"schema_version": 1, "recording": {"buffer_duration_seconds": "120"}}, + {"schema_version": 1, "recording": {"buffer_duration_seconds": 0}}, + {"schema_version": 1, "recording": {"buffer_duration_seconds": -5}}, + {"schema_version": 1, "replay": {"mpv_executable": ""}}, + {"schema_version": 1, "replay": {"mpv_executable": 5}}, + {"schema_version": 1, "input": {"type": "ndi", "source_name": ""}}, + {"schema_version": 1, "input": {"type": "ndi", "source_name": 5}}, + ], +) +def test_wrong_types_and_values_are_rejected(value: object) -> None: + with pytest.raises(ConfigurationValidationError): + config_from_json_object(value) + + +def test_validation_error_includes_field_path() -> None: + with pytest.raises(ConfigurationValidationError) as info: + config_from_json_object( + {"schema_version": 1, "recording": {"buffer_duration_seconds": True}} + ) + assert "recording.buffer_duration_seconds" in str(info.value) + + +def test_recording_and_replay_defaults_can_be_overridden() -> None: + config = QuickReplayConfig( + recording=RecordingConfig(buffer_duration_seconds=300), + replay=ReplayConfig(mpv_executable="C:\\Tools\\mpv\\mpv.exe"), + ) + restored = config_from_json_object(config_to_json_object(config)) + assert restored == config diff --git a/tests/test_configuration_runtime.py b/tests/test_configuration_runtime.py new file mode 100644 index 0000000..2f44860 --- /dev/null +++ b/tests/test_configuration_runtime.py @@ -0,0 +1,49 @@ +"""Configuration to runtime settings conversion.""" + +from pathlib import Path + +from quickreplay.configuration.codec import config_to_json_object +from quickreplay.configuration.models import QuickReplayConfig, RecordingConfig, ReplayConfig +from quickreplay.configuration.runtime import build_application_settings +from quickreplay.replay.controller import ReplayControllerSettings +from quickreplay.worker.settings import RecorderWorkerSettings + + +def test_buffer_duration_is_converted_to_nanoseconds(tmp_path: Path) -> None: + config = QuickReplayConfig(recording=RecordingConfig(buffer_duration_seconds=120)) + + settings = build_application_settings(config, working_directory=tmp_path) + + assert settings.worker is not None + assert settings.worker.buffer_duration_ns == 120_000_000_000 + + +def test_internal_worker_defaults_are_preserved(tmp_path: Path) -> None: + config = QuickReplayConfig(recording=RecordingConfig(buffer_duration_seconds=300)) + + settings = build_application_settings(config, working_directory=tmp_path) + + assert settings.worker is not None + defaults = RecorderWorkerSettings(working_directory=tmp_path) + assert settings.worker.segment_duration_ns == defaults.segment_duration_ns + assert settings.worker.video_queue_capacity == defaults.video_queue_capacity + assert settings.worker.audio_queue_capacity == defaults.audio_queue_capacity + assert settings.worker.av_reorder_holdback_ns == defaults.av_reorder_holdback_ns + assert settings.worker.working_directory == tmp_path + + +def test_mpv_executable_is_converted(tmp_path: Path) -> None: + config = QuickReplayConfig(replay=ReplayConfig(mpv_executable="C:\\Tools\\mpv\\mpv.exe")) + + settings = build_application_settings(config, working_directory=tmp_path) + + assert settings.replay.mpv_executable == "C:\\Tools\\mpv\\mpv.exe" + defaults = ReplayControllerSettings() + assert settings.replay.startup_timeout_seconds == defaults.startup_timeout_seconds + assert settings.replay.command_timeout_seconds == defaults.command_timeout_seconds + assert settings.replay.shutdown_timeout_seconds == defaults.shutdown_timeout_seconds + + +def test_working_directory_is_not_persisted() -> None: + obj = config_to_json_object(QuickReplayConfig()) + assert "working_directory" not in str(obj) diff --git a/tests/test_configuration_store.py b/tests/test_configuration_store.py new file mode 100644 index 0000000..8058714 --- /dev/null +++ b/tests/test_configuration_store.py @@ -0,0 +1,153 @@ +"""ConfigurationStore: load defaults, parse errors, atomic save and Unicode.""" + +import dataclasses +import os +from pathlib import Path + +import pytest + +from quickreplay.configuration.errors import ( + ConfigurationParseError, + ConfigurationReadError, + ConfigurationWriteError, +) +from quickreplay.configuration.models import QuickReplayConfig, ReplayConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.input.models import NdiInputConfig + + +def test_missing_file_returns_defaults_without_creating_it(tmp_path: Path) -> None: + path = tmp_path / "config.json" + store = ConfigurationStore(path) + + config = store.load() + + assert config == QuickReplayConfig() + assert not path.exists() + + +def test_minimal_file_uses_default_sections(tmp_path: Path) -> None: + path = tmp_path / "config.json" + path.write_text('{"schema_version": 1}', encoding="utf-8") + + config = ConfigurationStore(path).load() + + assert config == QuickReplayConfig() + + +def test_malformed_json_is_rejected(tmp_path: Path) -> None: + path = tmp_path / "config.json" + path.write_text('{"schema_version": 1,', encoding="utf-8") + + with pytest.raises(ConfigurationParseError): + ConfigurationStore(path).load() + + +def test_read_error_is_wrapped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = tmp_path / "config.json" + path.write_text('{"schema_version": 1}', encoding="utf-8") + + def boom(self: Path, *args, **kwargs) -> str: + raise OSError("permission denied") + + monkeypatch.setattr(Path, "read_text", boom) + with pytest.raises(ConfigurationReadError): + ConfigurationStore(path).load() + + +def test_save_and_load_round_trip(tmp_path: Path) -> None: + path = tmp_path / "config.json" + store = ConfigurationStore(path) + config = QuickReplayConfig(input=NdiInputConfig("OBS")) + + store.save(config) + + assert store.load() == config + + +def test_save_is_canonical_utf8(tmp_path: Path) -> None: + path = tmp_path / "config.json" + store = ConfigurationStore(path) + store.save(QuickReplayConfig(input=NdiInputConfig("配信用PC"))) + + text = path.read_text(encoding="utf-8") + assert text.endswith("\n") + assert '\n "schema_version": 1,' in text + assert "配信用PC" in text # ensure_ascii=False + assert "\\u" not in text + assert not (tmp_path / "config.json.tmp").exists() + + +def test_save_creates_parent_directories(tmp_path: Path) -> None: + path = tmp_path / "nested" / "dir" / "config.json" + store = ConfigurationStore(path) + + store.save(QuickReplayConfig()) + + assert path.exists() + + +def test_save_over_existing_file(tmp_path: Path) -> None: + path = tmp_path / "config.json" + store = ConfigurationStore(path) + store.save(QuickReplayConfig(input=NdiInputConfig("first"))) + store.save(QuickReplayConfig(input=NdiInputConfig("second"))) + + assert store.load().input == NdiInputConfig("second") + assert not (tmp_path / "config.json.tmp").exists() + + +def test_atomic_save_failure_preserves_existing_config( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "config.json" + store = ConfigurationStore(path) + store.save(QuickReplayConfig(input=NdiInputConfig("original"))) + original = path.read_text(encoding="utf-8") + + def boom(src, dst) -> None: + raise OSError("replace failed") + + monkeypatch.setattr(os, "replace", boom) + with pytest.raises(ConfigurationWriteError): + store.save(QuickReplayConfig(input=NdiInputConfig("new"))) + + assert path.read_text(encoding="utf-8") == original + assert store.load().input == NdiInputConfig("original") + assert not (tmp_path / "config.json.tmp").exists() + + +def test_write_error_is_wrapped(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = tmp_path / "config.json" + + def boom(fd: int) -> None: + raise OSError("disk full") + + monkeypatch.setattr(os, "fsync", boom) + + with pytest.raises(ConfigurationWriteError): + ConfigurationStore(path).save(QuickReplayConfig()) + + assert not (tmp_path / "config.json.tmp").exists() + + +def test_unicode_filesystem_path(tmp_path: Path) -> None: + path = tmp_path / "設定" / "クイックリプレイ" / "config.json" + store = ConfigurationStore(path) + + store.save(QuickReplayConfig(input=NdiInputConfig("配信"))) + + assert store.load().input == NdiInputConfig("配信") + + +def test_windows_mpv_path_round_trip(tmp_path: Path) -> None: + path = tmp_path / "config.json" + store = ConfigurationStore(path) + config = dataclasses.replace( + QuickReplayConfig(), + replay=ReplayConfig(mpv_executable="C:\\Users\\名前\\Apps\\mpv\\mpv.exe"), + ) + + store.save(config) + + assert store.load().replay.mpv_executable == "C:\\Users\\名前\\Apps\\mpv\\mpv.exe" diff --git a/tests/test_input_models.py b/tests/test_input_models.py new file mode 100644 index 0000000..7ca124a --- /dev/null +++ b/tests/test_input_models.py @@ -0,0 +1,44 @@ +"""Tests for input configuration, stream info and frame models.""" + +from fractions import Fraction + +import pytest + +from quickreplay.input.models import ( + AudioFrame, + AudioStreamInfo, + NdiInputConfig, + VideoStreamInfo, +) + + +def test_ndi_input_config() -> None: + config = NdiInputConfig(source_name="PC-A (OBS)") + assert config.source_name == "PC-A (OBS)" + with pytest.raises(ValueError): + NdiInputConfig(source_name="") + + +def test_fps_is_fraction_not_float() -> None: + info = VideoStreamInfo(width=1920, height=1080, fps=Fraction(60000, 1001), pixel_format="UYVY") + assert isinstance(info.fps, Fraction) + assert info.fps == Fraction(60000, 1001) + assert info.fps.numerator == 60000 + assert info.fps.denominator == 1001 + + +@pytest.mark.parametrize("width,height", [(0, 1080), (1920, 0), (-1, 1080)]) +def test_video_stream_info_validation(width: int, height: int) -> None: + with pytest.raises(ValueError): + VideoStreamInfo(width=width, height=height, fps=Fraction(60, 1), pixel_format="UYVY") + + +@pytest.mark.parametrize("sample_rate,channels", [(0, 2), (48000, 0)]) +def test_audio_stream_info_validation(sample_rate: int, channels: int) -> None: + with pytest.raises(ValueError): + AudioStreamInfo(sample_rate=sample_rate, channels=channels) + + +def test_audio_frame_rejects_negative_sample_count() -> None: + with pytest.raises(ValueError): + AudioFrame(timestamp_ns=0, sample_rate=48000, channels=2, sample_count=-1, data=object()) diff --git a/tests/test_mpv_ipc.py b/tests/test_mpv_ipc.py new file mode 100644 index 0000000..c6b3aa8 --- /dev/null +++ b/tests/test_mpv_ipc.py @@ -0,0 +1,144 @@ +"""mpv JSON IPC: endpoint generation, framing and request correlation.""" + +import json +import os +from decimal import Decimal +from typing import cast + +import pytest +from fake_mpv import FakeProcess, FakeTransport + +from quickreplay.replay.errors import ( + MpvCommandError, + MpvCommandTimeoutError, + MpvIpcError, + MpvProcessExitedError, +) +from quickreplay.replay.mpv_ipc import IPC_EOF, MpvIpcClient, make_ipc_endpoint, seconds_to_ns + + +def _client(transport: FakeTransport, process: FakeProcess) -> MpvIpcClient: + return MpvIpcClient(transport, process=process, command_timeout_seconds=0.2) + + +def test_seconds_to_ns_is_exact() -> None: + assert seconds_to_ns(Decimal("1.983")) == 1_983_000_000 + assert seconds_to_ns(Decimal("1.468135")) == 1_468_135_000 + assert seconds_to_ns(0) == 0 + assert seconds_to_ns(1) == 1_000_000_000 + assert seconds_to_ns(2.5) == 2_500_000_000 + assert seconds_to_ns("0.05") == 50_000_000 + + +@pytest.mark.parametrize("value", [None, True, False, object()]) +def test_seconds_to_ns_rejects_invalid(value: object) -> None: + with pytest.raises(MpvIpcError): + seconds_to_ns(value) + + +def test_endpoint_is_unique() -> None: + first, _ = make_ipc_endpoint() + second, _ = make_ipc_endpoint() + assert first != second + if os.name == "nt": + assert first.startswith(r"\\.\pipe\quickreplay-mpv-") + else: + assert first.endswith(".sock") + + +def test_command_is_newline_terminated_json_with_integer_request_id() -> None: + process = FakeProcess() + transport = FakeTransport(process=process) + client = _client(transport, process) + + client.command("get_property", "time-pos") + + raw = transport.raw[0] + assert raw.endswith(b"\n") + message = json.loads(raw.decode("utf-8")) + assert message["command"] == ["get_property", "time-pos"] + assert isinstance(message["request_id"], int) + assert client.command("frame-step") is None + + +def test_interleaved_event_before_response() -> None: + process = FakeProcess() + + def handler(command: list, request_id: int) -> dict: + transport.inject_json({"event": "property-change", "name": "time-pos"}) + return {"error": "success", "data": 1.5} + + transport = FakeTransport(process=process, handler=handler) + client = _client(transport, process) + + assert client.get_property("time-pos") == Decimal("1.5") + + +def test_wrong_request_id_is_not_mistaken_for_the_response() -> None: + process = FakeProcess() + sent_stale = {"done": False} + + def handler(command: list, request_id: int) -> dict: + if not sent_stale["done"]: + sent_stale["done"] = True + transport.inject_json({"request_id": request_id + 1000, "error": "failure"}) + return {"error": "success", "data": 7} + + transport = FakeTransport(process=process, handler=handler) + client = _client(transport, process) + + assert client.get_property("duration") == 7 + + +def test_command_error_is_raised() -> None: + process = FakeProcess() + transport = FakeTransport( + process=process, handler=lambda _c, _r: {"error": "property unavailable"} + ) + client = _client(transport, process) + + with pytest.raises(MpvCommandError) as info: + client.get_property("time-pos") + assert info.value.error == "property unavailable" + + +def test_command_timeout() -> None: + process = FakeProcess() + transport = FakeTransport(process=process, handler=lambda _c, _r: None) + client = _client(transport, process) + + with pytest.raises(MpvCommandTimeoutError): + client.get_property("time-pos") + + +def test_process_exit_during_command() -> None: + process = FakeProcess() + + def handler(command: list, request_id: int) -> None: + process.mark_exited(1) + return None + + transport = FakeTransport(process=process, handler=handler) + client = _client(transport, process) + + with pytest.raises(MpvProcessExitedError): + client.get_property("time-pos") + + +def test_ipc_eof_is_not_treated_as_a_command_timeout() -> None: + process = FakeProcess() + transport = FakeTransport(process=process) + transport._lines.put(cast(bytes | None, IPC_EOF)) + client = _client(transport, process) + + with pytest.raises(MpvProcessExitedError, match="IPC channel reached EOF"): + client.get_property("time-pos") + + +def test_command_before_send_after_process_exit() -> None: + process = FakeProcess(running=False) + transport = FakeTransport(process=process) + client = _client(transport, process) + + with pytest.raises(MpvProcessExitedError): + client.get_property("time-pos") diff --git a/tests/test_ndi_backend.py b/tests/test_ndi_backend.py new file mode 100644 index 0000000..ecd3225 --- /dev/null +++ b/tests/test_ndi_backend.py @@ -0,0 +1,82 @@ +"""Native NDI FourCC mapping and rejected-frame cleanup.""" + +from fractions import Fraction +from types import SimpleNamespace + +import numpy as np +import pytest + +from quickreplay.input.ndi import backend +from quickreplay.input.ndi.backend import PyNdiReceiver, _NdiRuntime +from quickreplay.input.ndi.errors import NdiUnsupportedFormatError + + +@pytest.fixture +def fake_ndi(): + freed = [] + ndi = SimpleNamespace( + RECV_TIMESTAMP_UNDEFINED=-1, + FOURCC_VIDEO_TYPE_UYVY=1, + FOURCC_VIDEO_TYPE_BGRA=2, + recv_free_video_v2=lambda receiver, frame: freed.append((receiver, frame)), + ) + return ndi, freed + + +@pytest.mark.parametrize(("fourcc", "expected"), [(1, "UYVY"), (2, "BGRA")]) +def test_native_video_fourcc_maps_to_raw_pixel_format(fake_ndi, fourcc, expected) -> None: + ndi, freed = fake_ndi + native = SimpleNamespace( + timestamp=123, + FourCC=fourcc, + xres=2, + yres=1, + line_stride_in_bytes=8, + frame_rate_N=60, + frame_rate_D=1, + data=np.zeros(8, dtype=np.uint8), + ) + receiver = object() + + raw = PyNdiReceiver(receiver)._video(ndi, native) + + assert raw.pixel_format == expected + assert raw.fps == Fraction(60, 1) + assert raw.handle is native + assert freed == [] + + +def test_unsupported_native_video_is_freed_before_rejection(fake_ndi) -> None: + ndi, freed = fake_ndi + native = SimpleNamespace(timestamp=123, FourCC=99) + receiver = object() + + with pytest.raises(NdiUnsupportedFormatError, match="supported: UYVY, BGRA"): + PyNdiReceiver(receiver)._video(ndi, native) + + assert freed == [(receiver, native)] + + +def test_ndi_runtime_owner_keeps_runtime_alive_between_sessions(monkeypatch) -> None: + initialized = [] + destroyed = [] + ndi = SimpleNamespace( + initialize=lambda: initialized.append("initialize") or True, + destroy=lambda: destroyed.append("destroy"), + ) + monkeypatch.setattr(backend, "import_ndi", lambda: ndi) + runtime = _NdiRuntime() + + runtime.acquire() # worker process owner + runtime.acquire() # first session + runtime.release() + assert destroyed == [] + + runtime.acquire() # second session + runtime.release() + assert destroyed == [] + + runtime.release() # worker process exit + + assert initialized == ["initialize"] + assert destroyed == ["destroy"] diff --git a/tests/test_ndi_converter.py b/tests/test_ndi_converter.py new file mode 100644 index 0000000..83d2dbf --- /dev/null +++ b/tests/test_ndi_converter.py @@ -0,0 +1,214 @@ +"""Raw NDI frame conversion: copy-before-free, stride and payload contracts.""" + +from fractions import Fraction + +import numpy as np +import pytest +from fake_ndi import fake_audio, fake_video + +from quickreplay.input.ndi.backend import ndi_timestamp_to_ns +from quickreplay.input.ndi.converter import to_audio_frame, to_video_frame +from quickreplay.input.ndi.errors import NdiUnsupportedFormatError + + +def _payload(frame) -> np.ndarray: + data = frame.data + assert isinstance(data, np.ndarray) + return data + + +def test_timestamp_conversion_is_integer_100ns() -> None: + assert ndi_timestamp_to_ns(12_345_678) == 1_234_567_800 + assert ndi_timestamp_to_ns(0) == 0 + + +@pytest.mark.parametrize("fps", [Fraction(60, 1), Fraction(60000, 1001)]) +def test_fps_is_exact_fraction(fps: Fraction) -> None: + frame = to_video_frame(fake_video(width=4, height=2, fps=fps)) + + assert frame.fps == fps + assert isinstance(frame.fps, Fraction) + + +def test_video_copy_before_free() -> None: + raw = fake_video(width=4, height=2) + original = raw.data.copy() + + frame = to_video_frame(raw) + raw.data[:] = 200 # mutate the native buffer after conversion + + payload = _payload(frame) + assert frame.pixel_format == "UYVY" + assert payload.shape == (2, 8) + assert payload.dtype == np.uint8 + assert np.array_equal(payload, original) + assert not np.shares_memory(payload, raw.data) + + +def test_video_stride_padding_is_removed() -> None: + width, height = 4, 3 + stride = width * 2 + 6 + native = np.arange(height * stride, dtype=np.uint8).reshape(height, stride) + raw = fake_video(width=width, height=height, stride=stride, data=native) + + frame = to_video_frame(raw) + payload = _payload(frame) + + assert payload.shape == (height, width * 2) + assert np.array_equal(payload, native[:, : width * 2]) + assert not np.array_equal(payload, native) + + +def test_audio_copy_before_free_and_stereo_shape() -> None: + raw = fake_audio(channels=2, samples=1600) + raw.data[:] = 0.5 + original = raw.data.copy() + + frame = to_audio_frame(raw) + raw.data[:] = -0.25 # mutate the native buffer after conversion + + payload = _payload(frame) + assert payload.shape == (2, 1600) + assert payload.dtype == np.float32 + assert np.array_equal(payload, original) + assert not np.shares_memory(payload, raw.data) + assert frame.sample_count == 1600 + assert frame.channels == 2 + assert frame.sample_rate == 48000 + + +def test_audio_mono_is_supported() -> None: + frame = to_audio_frame(fake_audio(channels=1, samples=100)) + + assert _payload(frame).shape == (1, 100) + assert frame.channels == 1 + + +def test_audio_unsupported_channel_count() -> None: + with pytest.raises(NdiUnsupportedFormatError): + to_audio_frame(fake_audio(channels=3, samples=100)) + + +def test_bgra_frame_is_copied_without_padding() -> None: + width, height = 2, 2 + native = np.arange(height * width * 4, dtype=np.uint8).reshape(height, width * 4) + raw = fake_video(width=width, height=height, pixel_format="BGRA", data=native) + + frame = to_video_frame(raw) + + assert frame.pixel_format == "BGRA" + payload = _payload(frame) + assert payload.shape == (height, width, 4) + assert payload.dtype == np.uint8 + assert np.array_equal(payload, native.reshape(height, width, 4)) + assert payload.flags.c_contiguous + assert not np.shares_memory(payload, native) + + +def test_bgra_padding_is_removed_and_payload_is_owned() -> None: + width, height, stride = 2, 2, 12 + native = np.arange(height * stride, dtype=np.uint8).reshape(height, stride) + raw = fake_video(width=width, height=height, stride=stride, data=native, pixel_format="BGRA") + expected = native[:, : width * 4].copy() + + frame = to_video_frame(raw) + native[:] = 255 + + payload = _payload(frame) + assert payload.shape == (height, width, 4) + assert np.array_equal(payload.reshape(height, width * 4), expected) + assert not np.shares_memory(payload, native) + + +def test_bgra_3d_pixels_are_copied_into_owned_contiguous_array() -> None: + width, height = 3, 2 + native = np.arange(height * width * 4, dtype=np.uint8).reshape(height, width, 4) + original = native.copy() + raw = fake_video( + width=width, + height=height, + stride=width * 4, + pixel_format="BGRA", + data=native, + ) + + frame = to_video_frame(raw) + native[:] = 255 + + payload = _payload(frame) + assert frame.pixel_format == "BGRA" + assert payload.shape == (height, width, 4) + assert payload.dtype == np.uint8 + assert payload.flags.c_contiguous + assert np.array_equal(payload, original) + assert not np.shares_memory(payload, native) + + +def test_bgra_3d_non_contiguous_view_is_normalized() -> None: + width, height = 3, 2 + base = np.arange(height * (width + 2) * 4, dtype=np.uint8).reshape(height, width + 2, 4) + view = base[:, :width, :] + raw = fake_video( + width=width, + height=height, + stride=width * 4, + pixel_format="BGRA", + data=view, + ) + + payload = _payload(to_video_frame(raw)) + + assert np.array_equal(payload, view) + assert payload.flags.c_contiguous + assert not np.shares_memory(payload, base) + + +@pytest.mark.parametrize( + "data", + [ + np.zeros((1, 3, 4), dtype=np.uint8), + np.zeros((2, 2, 4), dtype=np.uint8), + np.zeros((2, 3, 3), dtype=np.uint8), + np.zeros((2, 3, 5), dtype=np.uint8), + np.zeros((2, 3, 4), dtype=np.uint16), + ], +) +def test_malformed_bgra_3d_shape_or_dtype_is_rejected(data: np.ndarray) -> None: + raw = fake_video( + width=3, + height=2, + stride=12, + pixel_format="BGRA", + data=data, + ) + + with pytest.raises(NdiUnsupportedFormatError): + to_video_frame(raw) + + +@pytest.mark.parametrize( + ("width", "height", "stride", "data"), + [ + (2, 2, 8, np.zeros((1, 8), dtype=np.uint8)), + (2, 2, 7, np.zeros((2, 8), dtype=np.uint8)), + (2, 2, 8, np.zeros(15, dtype=np.uint8)), + (2, 2, 8, np.asarray(1, dtype=np.uint8)), + ], +) +def test_malformed_bgra_frames_are_rejected( + width: int, height: int, stride: int, data: np.ndarray +) -> None: + raw = fake_video(width=width, height=height, stride=stride, data=data, pixel_format="BGRA") + + with pytest.raises(NdiUnsupportedFormatError): + to_video_frame(raw) + + +def test_unsupported_video_format_rejected() -> None: + with pytest.raises(NdiUnsupportedFormatError): + to_video_frame(fake_video(pixel_format="P216")) + + +def test_unsupported_audio_format_rejected() -> None: + with pytest.raises(NdiUnsupportedFormatError): + to_audio_frame(fake_audio(audio_format="S16")) diff --git a/tests/test_ndi_discovery.py b/tests/test_ndi_discovery.py new file mode 100644 index 0000000..76cefa9 --- /dev/null +++ b/tests/test_ndi_discovery.py @@ -0,0 +1,26 @@ +"""NDI source discovery and runtime availability.""" + +from fake_ndi import FakeBackend + +from quickreplay.input.models import NdiInputDescriptor +from quickreplay.input.ndi.discovery import discover_ndi_sources + + +def test_discovery_returns_descriptors_and_cleans_up() -> None: + backend = FakeBackend(sources=("HOST (Cam A)", "HOST (Cam B)")) + + descriptors = discover_ndi_sources(backend=backend, timeout_ms=0) + + assert descriptors == ( + NdiInputDescriptor(source_name="HOST (Cam A)"), + NdiInputDescriptor(source_name="HOST (Cam B)"), + ) + assert backend.initialize_calls == 1 + assert backend.shutdown_calls == 1 + + +def test_discovery_returns_empty_tuple() -> None: + backend = FakeBackend(sources=()) + + assert discover_ndi_sources(backend=backend, timeout_ms=0) == () + assert backend.shutdown_calls == 1 diff --git a/tests/test_ndi_segment_integration.py b/tests/test_ndi_segment_integration.py new file mode 100644 index 0000000..f8b16ae --- /dev/null +++ b/tests/test_ndi_segment_integration.py @@ -0,0 +1,129 @@ +"""Fake NDI -> NdiInputSource -> SegmentRecorder -> MKV integration.""" + +from fractions import Fraction +from pathlib import Path +from uuid import uuid4 + +from fake_ndi import FakeBackend, fake_stream_script + +from quickreplay.input.models import NdiInputConfig, VideoFrame +from quickreplay.input.ndi.source import NdiInputSource +from quickreplay.recording.models import RecordingSession, Segment +from quickreplay.recording.segment_recorder import SegmentRecorder + +SEGMENT_DURATION_NS = 2_000_000_000 + + +def _record( + directory: Path, + *, + fps: Fraction, + width: int, + height: int, + sample_rate: int | None, + channels: int | None, + duration_ns: int, +) -> tuple[list[Segment], object]: + script = fake_stream_script( + duration_ns=duration_ns, + fps=fps, + width=width, + height=height, + sample_rate=sample_rate, + channels=channels, + ) + backend = FakeBackend(sources=("HOST (Fake Source)",), script=script) + source = NdiInputSource( + NdiInputConfig(source_name="Fake Source"), backend=backend, discovery_timeout_ms=0 + ) + source.open() + + pending = [] + while source.stream_info is None or source.stream_info.audio is None: + item = source.read() + if item is None: + break + pending.append(item) + info = source.stream_info + assert info is not None + + recorder = SegmentRecorder(segment_duration_ns=SEGMENT_DURATION_NS) + recorder.start(RecordingSession(uuid4(), info, 0, directory)) + segments: list[Segment] = [] + + def feed(frame) -> None: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + + for frame in pending: + feed(frame) + while True: + item = source.read() + if item is None: + break + feed(item) + + last = recorder.finish() + if last is not None: + segments.append(last) + recorder.close() + source.close() + return segments, info + + +def _check_segments(segments: list[Segment], info, probe, fps: Fraction) -> None: + assert info.video.pixel_format == "UYVY" + assert segments + for segment in segments: + facts = probe(segment.path) + assert facts.video_codec == "h264" + assert facts.first_video_pts == 0 + assert facts.keyframe_count >= 1 + assert facts.decoded_video_frames == segment.video_frames + assert facts.audio_present + assert facts.first_audio_pts == 0 + assert facts.audio_samples == segment.audio_samples + assert abs(float(facts.video_rate) - float(fps)) < 0.01 + + layouts = {probe(segment.path).video_time_base for segment in segments} + assert len(layouts) == 1 + + +def test_ndi_to_segment_recorder_60fps(tmp_path: Path, probe) -> None: + fps = Fraction(60, 1) + + segments, info = _record( + tmp_path, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + duration_ns=4_500_000_000, + ) + + assert len(segments) == 3 + assert sum(segment.video_frames for segment in segments) == 271 + assert sum(segment.audio_samples for segment in segments) == 216000 + _check_segments(segments, info, probe, fps) + + +def test_ndi_to_segment_recorder_5994fps(tmp_path: Path, probe) -> None: + fps = Fraction(60000, 1001) + + segments, info = _record( + tmp_path, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + duration_ns=4_500_000_000, + ) + + assert len(segments) == 3 + assert sum(segment.video_frames for segment in segments) == 270 + assert sum(segment.audio_samples for segment in segments) == 216000 + _check_segments(segments, info, probe, fps) diff --git a/tests/test_ndi_source.py b/tests/test_ndi_source.py new file mode 100644 index 0000000..03b0a48 --- /dev/null +++ b/tests/test_ndi_source.py @@ -0,0 +1,270 @@ +"""NdiInputSource behaviour: lifecycle, capture, errors and format changes.""" + +from fractions import Fraction + +import numpy as np +import pytest +from fake_ndi import FakeBackend, fake_audio, fake_metadata, fake_video + +from quickreplay.input.models import AudioFrame, NdiInputConfig, VideoFrame +from quickreplay.input.ndi.errors import ( + NdiCaptureError, + NdiFormatChangeError, + NdiReceiverError, + NdiSourceNotFoundError, +) +from quickreplay.input.ndi.source import NdiInputSource + + +def _source(backend: FakeBackend, name: str = "My Source") -> NdiInputSource: + return NdiInputSource(NdiInputConfig(source_name=name), backend=backend, discovery_timeout_ms=0) + + +def test_source_not_found_cleans_up() -> None: + backend = FakeBackend(sources=()) + source = _source(backend) + + with pytest.raises(NdiSourceNotFoundError): + source.open() + + assert backend.initialize_calls == 1 + assert backend.shutdown_calls == 1 + assert backend.create_receiver_calls == 0 + + +def test_open_resolves_machine_prefixed_name() -> None: + backend = FakeBackend(sources=("HOST (My Source)",)) + source = _source(backend) + + source.open() + try: + assert backend.receivers[0].source_name() == "HOST (My Source)" + finally: + source.close() + + +def test_reopen_resets_observed_stream_formats() -> None: + backend = FakeBackend(sources=("My Source",), script=[fake_video(), fake_audio()]) + source = _source(backend) + source.open() + assert isinstance(source.read(), VideoFrame) + assert isinstance(source.read(), AudioFrame) + assert source.stream_info is not None + assert source.stream_info.audio is not None + source.close() + + source.open() + + assert source.stream_info is None + frame = source.read() + assert isinstance(frame, VideoFrame) + assert source.stream_info is not None + assert source.stream_info.audio is None + source.close() + + +def test_read_returns_none_when_nothing_is_available() -> None: + backend = FakeBackend(sources=("My Source",), script=[]) + source = _source(backend) + source.open() + try: + assert source.read() is None + finally: + source.close() + + +def test_stream_info_is_lazy_and_includes_audio_once_seen() -> None: + video = fake_video(width=8, height=4, fps=Fraction(60000, 1001), timestamp_ns=1_234_567_800) + audio = fake_audio(timestamp_ns=1_234_567_800) + backend = FakeBackend(sources=("My Source",), script=[video, audio]) + source = _source(backend) + source.open() + try: + assert source.stream_info is None + + video_frame = source.read() + assert isinstance(video_frame, VideoFrame) + assert source.stream_info is not None + assert source.stream_info.audio is None + assert source.stream_info.video.width == 8 + assert source.stream_info.video.height == 4 + assert source.stream_info.video.fps == Fraction(60000, 1001) + assert source.stream_info.video.pixel_format == "UYVY" + + audio_frame = source.read() + assert isinstance(audio_frame, AudioFrame) + assert source.stream_info.audio is not None + assert source.stream_info.audio.sample_rate == 48000 + assert source.stream_info.audio.channels == 2 + finally: + source.close() + + +def test_timestamp_is_taken_from_the_frame() -> None: + backend = FakeBackend(sources=("My Source",), script=[fake_video(timestamp_ns=1_234_567_800)]) + source = _source(backend) + source.open() + try: + frame = source.read() + assert frame is not None + assert frame.timestamp_ns == 1_234_567_800 + finally: + source.close() + + +def test_metadata_is_discarded_and_freed() -> None: + backend = FakeBackend(sources=("My Source",), script=[fake_metadata()]) + source = _source(backend) + source.open() + try: + assert source.read() is None + receiver = backend.receivers[0] + assert receiver.metadata_frees == 1 + assert receiver.video_frees == 0 + assert receiver.audio_frees == 0 + finally: + source.close() + + +def test_native_buffers_are_freed_after_conversion() -> None: + video = fake_video() + audio = fake_audio() + backend = FakeBackend(sources=("My Source",), script=[video, audio]) + source = _source(backend) + source.open() + try: + source.read() + source.read() + assert video.handle.freed + assert audio.handle.freed + assert backend.receivers[0].video_frees == 1 + assert backend.receivers[0].audio_frees == 1 + finally: + source.close() + + +def test_video_format_change_is_rejected() -> None: + backend = FakeBackend( + sources=("My Source",), + script=[fake_video(width=1920, height=1080), fake_video(width=1280, height=720)], + ) + source = _source(backend) + source.open() + try: + source.read() + with pytest.raises(NdiFormatChangeError): + source.read() + finally: + source.close() + + +def test_bgra_video_and_audio_are_exposed_in_stream_info() -> None: + backend = FakeBackend( + sources=("My Source",), + script=[ + fake_video( + width=8, + height=4, + pixel_format="BGRA", + data=np.zeros((4, 8, 4), dtype=np.uint8), + ), + fake_audio(), + ], + ) + source = _source(backend) + source.open() + try: + video = source.read() + assert isinstance(video, VideoFrame) + assert video.pixel_format == "BGRA" + assert isinstance(video.data, np.ndarray) + assert video.data.shape == (4, 8, 4) + assert source.stream_info is not None + assert source.stream_info.video.pixel_format == "BGRA" + + audio = source.read() + assert isinstance(audio, AudioFrame) + assert source.stream_info.audio is not None + assert source.stream_info.audio.channels == 2 + finally: + source.close() + + +def test_bgra_frames_are_accepted_but_mid_session_format_change_is_rejected() -> None: + backend = FakeBackend( + sources=("My Source",), + script=[ + fake_video(width=8, height=4, pixel_format="BGRA"), + fake_video(width=8, height=4, pixel_format="BGRA", timestamp_ns=1), + fake_video(width=8, height=4, pixel_format="UYVY", timestamp_ns=2), + ], + ) + source = _source(backend) + source.open() + try: + assert isinstance(source.read(), VideoFrame) + assert isinstance(source.read(), VideoFrame) + with pytest.raises(NdiFormatChangeError): + source.read() + finally: + source.close() + + +def test_audio_format_change_is_rejected() -> None: + backend = FakeBackend( + sources=("My Source",), + script=[fake_audio(channels=2), fake_audio(channels=1)], + ) + source = _source(backend) + source.open() + try: + source.read() + with pytest.raises(NdiFormatChangeError): + source.read() + finally: + source.close() + + +def test_capture_error_propagates() -> None: + backend = FakeBackend( + sources=("My Source",), script=[fake_video(), NdiCaptureError("disconnected")] + ) + source = _source(backend) + source.open() + try: + source.read() + with pytest.raises(NdiCaptureError): + source.read() + finally: + source.close() + + +def test_close_is_idempotent_and_destroys_receiver_once() -> None: + backend = FakeBackend(sources=("My Source",)) + source = _source(backend) + source.open() + receiver = backend.receivers[0] + + source.close() + source.close() + + assert receiver.destroyed + assert backend.shutdown_calls == 1 + with pytest.raises(NdiReceiverError): + source.read() + + +def test_open_failure_cleans_up_the_runtime_reference() -> None: + backend = FakeBackend( + sources=("My Source",), receiver_error=NdiReceiverError("could not create receiver") + ) + source = _source(backend) + + with pytest.raises(NdiReceiverError): + source.open() + + assert backend.initialize_calls == 1 + assert backend.shutdown_calls == 1 + + source.close() # safe after a failed open + assert backend.shutdown_calls == 1 diff --git a/tests/test_recording_models.py b/tests/test_recording_models.py new file mode 100644 index 0000000..82e750e --- /dev/null +++ b/tests/test_recording_models.py @@ -0,0 +1,88 @@ +"""Tests for recording domain models.""" + +from dataclasses import FrozenInstanceError +from pathlib import Path + +import pytest + +from quickreplay.recording.models import ( + RecordingMetrics, + Segment, +) + + +def _segment() -> Segment: + return Segment( + id=1, + path=Path("segment_000001.mkv"), + session_start_ns=2_000_000_000, + session_end_ns=4_000_000_000, + video_frames=120, + audio_samples=96000, + ) + + +def test_segment_fields_and_duration() -> None: + segment = _segment() + assert segment.id == 1 + assert segment.path == Path("segment_000001.mkv") + assert segment.duration_ns == 2_000_000_000 + assert segment.video_frames == 120 + assert segment.audio_samples == 96000 + + +def test_segment_is_immutable() -> None: + segment = _segment() + attribute = "video_frames" + with pytest.raises(FrozenInstanceError): + setattr(segment, attribute, 121) + + +def test_segment_rejects_invalid_values() -> None: + with pytest.raises(ValueError): + Segment( + id=0, + path=Path("x.mkv"), + session_start_ns=2_000_000_000, + session_end_ns=1_000_000_000, + video_frames=0, + audio_samples=0, + ) + with pytest.raises(ValueError): + Segment( + id=0, + path=Path("x.mkv"), + session_start_ns=0, + session_end_ns=1, + video_frames=-1, + audio_samples=0, + ) + + +def test_recording_metrics() -> None: + metrics = RecordingMetrics( + captured_video_frames=120, + recorded_video_frames=120, + captured_audio_samples=96000, + recorded_audio_samples=96000, + video_queue_drops=0, + audio_queue_drops=0, + buffer_duration_ns=30_000_000_000, + segment_count=15, + input_fps=59.94, + recording_fps=60.0, + ) + assert metrics.input_fps == pytest.approx(59.94) + with pytest.raises(ValueError): + RecordingMetrics( + captured_video_frames=-1, + recorded_video_frames=0, + captured_audio_samples=0, + recorded_audio_samples=0, + video_queue_drops=0, + audio_queue_drops=0, + buffer_duration_ns=0, + segment_count=0, + input_fps=0.0, + recording_fps=0.0, + ) diff --git a/tests/test_release_packaging.py b/tests/test_release_packaging.py new file mode 100644 index 0000000..876a45d --- /dev/null +++ b/tests/test_release_packaging.py @@ -0,0 +1,43 @@ +"""Headless tests for the portable Windows distribution staging helper.""" + +import tomllib +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path +from zipfile import ZipFile + +_SPEC = spec_from_file_location( + "package_windows_release", Path(__file__).parents[1] / "tools" / "package_windows_release.py" +) +assert _SPEC is not None and _SPEC.loader is not None +_MODULE = module_from_spec(_SPEC) +_SPEC.loader.exec_module(_MODULE) +create_distribution = _MODULE.create_distribution +read_project_version = _MODULE.read_project_version + + +def test_project_version_is_read_from_pyproject() -> None: + assert ( + read_project_version() + == tomllib.loads( + (Path(__file__).parents[1] / "pyproject.toml").read_text(encoding="utf-8") + )["project"]["version"] + ) + + +def test_distribution_contains_versioned_zip_and_notices(tmp_path: Path) -> None: + build_dir = tmp_path / "build" / "windows" + build_dir.mkdir(parents=True) + (build_dir / "QuickReplay.exe").write_bytes(b"test executable") + (build_dir / "runtime.dll").write_bytes(b"test runtime") + + archive = create_distribution(build_dir=build_dir, output_dir=tmp_path / "dist") + + version = read_project_version() + assert archive.name == f"QuickReplay-{version}-windows-x64.zip" + with ZipFile(archive) as zip_file: + assert set(zip_file.namelist()) == { + "QuickReplay/QuickReplay.exe", + "QuickReplay/runtime.dll", + "QuickReplay/LICENSE", + "QuickReplay/LICENSE_ThirdParty.md", + } diff --git a/tests/test_replay_asset_builder.py b/tests/test_replay_asset_builder.py new file mode 100644 index 0000000..5033ba2 --- /dev/null +++ b/tests/test_replay_asset_builder.py @@ -0,0 +1,229 @@ +"""ReplayAssetBuilder validation, atomic finalize and failure cleanup.""" + +from dataclasses import replace +from fractions import Fraction +from pathlib import Path + +import pytest + +from quickreplay.recording.models import Segment +from quickreplay.replay.asset_builder import ( + REPLAY_FILENAME, + REPLAY_TMP_FILENAME, + ReplayAssetBuilder, +) +from quickreplay.replay.errors import ( + EmptyReplaySnapshotError, + ReplayRemuxError, + ReplaySegmentError, + ReplayStreamMismatchError, +) +from quickreplay.replay.models import ReplaySnapshot + +SECOND = 1_000_000_000 +FPS = Fraction(60, 1) + + +def _snapshot(segments: tuple[Segment, ...], info) -> ReplaySnapshot: + return ReplaySnapshot(segments=segments, stream_info=info) + + +def _shift(segment: Segment, *, segment_id: int, start_ns: int) -> Segment: + return replace( + segment, + id=segment_id, + session_start_ns=start_ns, + session_end_ns=start_ns + segment.duration_ns, + ) + + +def test_empty_snapshot_rejected(media, tmp_path: Path) -> None: + info = media.stream_info(fps=FPS, width=64, height=36) + output = tmp_path / "out" + + with pytest.raises(EmptyReplaySnapshotError): + ReplayAssetBuilder().build(_snapshot((), info), output) + + assert not output.exists() + + +def test_missing_segment_rejected(media, tmp_path: Path, make_segment) -> None: + info = media.stream_info(fps=FPS, width=64, height=36) + first = make_segment(0, 0, 2 * SECOND) + second = make_segment(1, 2 * SECOND, 4 * SECOND) + second.path.unlink() + output = tmp_path / "out" + + with pytest.raises(ReplaySegmentError): + ReplayAssetBuilder().build(_snapshot((first, second), info), output) + + assert not (output / REPLAY_FILENAME).exists() + assert not (output / REPLAY_TMP_FILENAME).exists() + + +def test_chronology_gap_rejected(media, tmp_path: Path, make_segment) -> None: + info = media.stream_info(fps=FPS, width=64, height=36) + first = make_segment(0, 0, 2 * SECOND) + second = make_segment(1, 3 * SECOND, 5 * SECOND) + + with pytest.raises(ReplaySegmentError): + ReplayAssetBuilder().build(_snapshot((first, second), info), tmp_path / "out") + + +def test_chronology_overlap_rejected(media, tmp_path: Path, make_segment) -> None: + info = media.stream_info(fps=FPS, width=64, height=36) + first = make_segment(0, 0, 2 * SECOND) + second = make_segment(1, SECOND, 3 * SECOND) + + with pytest.raises(ReplaySegmentError): + ReplayAssetBuilder().build(_snapshot((first, second), info), tmp_path / "out") + + +def test_non_increasing_id_rejected(media, tmp_path: Path, make_segment) -> None: + info = media.stream_info(fps=FPS, width=64, height=36) + first = make_segment(1, 0, 2 * SECOND) + second = make_segment(0, 2 * SECOND, 4 * SECOND) + + with pytest.raises(ReplaySegmentError): + ReplayAssetBuilder().build(_snapshot((first, second), info), tmp_path / "out") + + +def test_stream_resolution_mismatch_rejected(media, tmp_path: Path, record_segments) -> None: + first_dir = tmp_path / "a" + second_dir = tmp_path / "b" + first_dir.mkdir() + second_dir.mkdir() + first_segments, info = record_segments( + first_dir, duration_ns=SECOND, fps=FPS, width=64, height=36 + ) + second_segments, _ = record_segments( + second_dir, duration_ns=SECOND, fps=FPS, width=128, height=72 + ) + first = first_segments[0] + second = _shift(second_segments[0], segment_id=1, start_ns=first.session_end_ns) + output = tmp_path / "out" + + with pytest.raises(ReplayStreamMismatchError): + ReplayAssetBuilder().build(_snapshot((first, second), info), output) + + assert not (output / REPLAY_FILENAME).exists() + assert not (output / REPLAY_TMP_FILENAME).exists() + + +def test_stream_audio_presence_mismatch_rejected(media, tmp_path: Path, record_segments) -> None: + first_dir = tmp_path / "a" + second_dir = tmp_path / "b" + first_dir.mkdir() + second_dir.mkdir() + first_segments, info = record_segments( + first_dir, duration_ns=SECOND, fps=FPS, width=64, height=36, sample_rate=48000, channels=2 + ) + second_segments, _ = record_segments( + second_dir, duration_ns=SECOND, fps=FPS, width=64, height=36 + ) + first = first_segments[0] + second = _shift(second_segments[0], segment_id=1, start_ns=first.session_end_ns) + + with pytest.raises(ReplayStreamMismatchError): + ReplayAssetBuilder().build(_snapshot((first, second), info), tmp_path / "out") + + +def test_success_publishes_atomically(media, tmp_path: Path, record_segments) -> None: + segments, info = record_segments( + tmp_path, duration_ns=SECOND, fps=FPS, width=64, height=36, sample_rate=48000, channels=2 + ) + output = tmp_path / "out" + + asset = ReplayAssetBuilder().build(_snapshot(segments, info), output) + + assert asset.path == output / REPLAY_FILENAME + assert asset.path.exists() + assert not (output / REPLAY_TMP_FILENAME).exists() + assert asset.duration_ns == segments[-1].session_end_ns - segments[0].session_start_ns + + +def test_success_replaces_existing_asset(media, tmp_path: Path, record_segments) -> None: + segments, info = record_segments( + tmp_path, duration_ns=SECOND, fps=FPS, width=64, height=36, sample_rate=48000, channels=2 + ) + output = tmp_path / "out" + output.mkdir() + (output / REPLAY_FILENAME).write_bytes(b"stale") + + asset = ReplayAssetBuilder().build(_snapshot(segments, info), output) + + assert asset.path.read_bytes() != b"stale" + assert not (output / REPLAY_TMP_FILENAME).exists() + + +def test_failure_cleans_up_partial_output(media, tmp_path: Path, record_segments) -> None: + segments, info = record_segments( + tmp_path, duration_ns=SECOND, fps=FPS, width=64, height=36, sample_rate=48000, channels=2 + ) + output = tmp_path / "out" + + def failing_remux(segments, tmp_path): + Path(tmp_path).write_bytes(b"partial") + raise ReplayRemuxError("injected failure") + + with pytest.raises(ReplayRemuxError): + ReplayAssetBuilder(remux=failing_remux).build(_snapshot(segments, info), output) + + assert not (output / REPLAY_TMP_FILENAME).exists() + assert not (output / REPLAY_FILENAME).exists() + for segment in segments: + assert segment.path.exists() + + +def test_failure_preserves_existing_asset(media, tmp_path: Path, record_segments) -> None: + segments, info = record_segments( + tmp_path, duration_ns=SECOND, fps=FPS, width=64, height=36, sample_rate=48000, channels=2 + ) + output = tmp_path / "out" + output.mkdir() + (output / REPLAY_FILENAME).write_bytes(b"completed") + + def failing_remux(segments, tmp_path): + raise ReplayRemuxError("injected failure") + + with pytest.raises(ReplayRemuxError): + ReplayAssetBuilder(remux=failing_remux).build(_snapshot(segments, info), output) + + assert (output / REPLAY_FILENAME).read_bytes() == b"completed" + assert not (output / REPLAY_TMP_FILENAME).exists() + + +def test_source_segments_are_not_modified(media, tmp_path: Path, record_segments) -> None: + segments, info = record_segments( + tmp_path, + duration_ns=4_500_000_000, + fps=FPS, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + before = {segment.path: segment.path.read_bytes() for segment in segments} + + ReplayAssetBuilder().build(_snapshot(segments, info), tmp_path / "out") + + for segment in segments: + assert segment.path.read_bytes() == before[segment.path] + + +def test_asset_fps_is_exact_fraction(media, tmp_path: Path, record_segments) -> None: + fps = Fraction(60000, 1001) + segments, info = record_segments( + tmp_path, + duration_ns=4_500_000_000, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + + asset = ReplayAssetBuilder().build(_snapshot(segments, info), tmp_path / "out") + + assert asset.fps == fps + assert isinstance(asset.fps, Fraction) diff --git a/tests/test_replay_asset_integration.py b/tests/test_replay_asset_integration.py new file mode 100644 index 0000000..4245c23 --- /dev/null +++ b/tests/test_replay_asset_integration.py @@ -0,0 +1,77 @@ +"""End-to-end pipeline: capture -> segments -> ring -> snapshot -> replay asset.""" + +from fractions import Fraction +from pathlib import Path + +from quickreplay.recording.ring_storage import RingStorage +from quickreplay.replay.asset_builder import ReplayAssetBuilder +from quickreplay.replay.models import ReplaySnapshot + +SECOND = 1_000_000_000 +FPS = Fraction(60, 1) + + +def test_full_pipeline(tmp_path: Path, record_segments, replay_probe) -> None: + segments, info = record_segments( + tmp_path, + duration_ns=4_500_000_000, + fps=FPS, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + ring = RingStorage(buffer_duration_ns=60 * SECOND) + for segment in segments: + ring.add(segment) + + output = tmp_path / "replay-session" + with ring.snapshot() as lease: + snapshot = ReplaySnapshot(segments=lease.segments, stream_info=info) + asset = ReplayAssetBuilder().build(snapshot, output) + assert lease.released is False + + assert lease.released is True + assert asset.path == output / "replay.mkv" + facts = replay_probe(asset.path) + assert len(facts.decoded_video_pts) == sum(segment.video_frames for segment in segments) + assert facts.decoded_audio_samples == sum(segment.audio_samples for segment in segments) + assert asset.duration_ns == ring.duration_ns + + +def test_lease_pins_expired_segments_during_build(tmp_path: Path, record_segments) -> None: + segments, info = record_segments( + tmp_path, + duration_ns=6 * SECOND, + fps=FPS, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + assert len(segments) >= 3 + first, second, third = segments[0], segments[1], segments[2] + + ring = RingStorage(buffer_duration_ns=4 * SECOND) + ring.add(first) + ring.add(second) + + lease = ring.snapshot() + snapshot = ReplaySnapshot(segments=lease.segments, stream_info=info) + + # The third segment pushes the first out of the retention window, but the + # lease keeps its file alive while the replay asset is built. + ring.add(third) + assert first.path.exists() + assert second.path.exists() + + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + assert asset.path.exists() + assert first.path.exists() + assert second.path.exists() + + # Once the asset is complete the segments are independent of it. + lease.release() + assert not first.path.exists() + assert second.path.exists() + assert third.path.exists() diff --git a/tests/test_replay_controller.py b/tests/test_replay_controller.py new file mode 100644 index 0000000..2a9f753 --- /dev/null +++ b/tests/test_replay_controller.py @@ -0,0 +1,389 @@ +"""ReplayController: lifecycle, playback control, position and shutdown.""" + +from fractions import Fraction +from pathlib import Path +from typing import NoReturn + +import pytest +from fake_mpv import FakeMpv, FakeTransport + +from quickreplay.replay.controller import ( + ReplayController, + ReplayControllerSettings, + frame_offset_seconds, +) +from quickreplay.replay.errors import ( + MpvExecutableNotFoundError, + MpvProcessExitedError, + MpvPropertyUnavailableError, + MpvStartupError, + ReplayControllerError, +) +from quickreplay.replay.models import ReplayAsset + +FPS_60 = Fraction(60, 1) +FPS_5994 = Fraction(60000, 1001) + + +def _asset( + tmp_path: Path, + *, + fps: Fraction = FPS_60, + duration_ns: int = 2_000_000_000, + name: str = "replay.mkv", +) -> ReplayAsset: + path = tmp_path / name + path.write_bytes(b"replay") + return ReplayAsset(path=path, duration_ns=duration_ns, fps=fps) + + +def test_open_launches_mpv_with_expected_arguments(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + asset = _asset(tmp_path) + + controller.open(asset) + try: + arguments = mpv.arguments + assert arguments is not None + for flag in ( + "--no-config", + "--terminal=no", + "--osc=no", + "--pause=yes", + "--keep-open=yes", + "--force-window=yes", + "--hr-seek=yes", + "--hr-seek-framedrop=no", + "--hwdec=no", + ): + assert flag in arguments + assert any(argument.startswith("--input-ipc-server=") for argument in arguments) + assert arguments[-1] == str(asset.path) + finally: + controller.close() + + +def test_open_leaves_replay_paused(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + assert controller.is_open + assert controller.asset is not None + assert ["set_property", "pause", True] in mpv.transport.commands() + assert controller.is_paused() is True + finally: + controller.close() + + +def test_double_open_is_rejected(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path, name="a.mkv")) + try: + with pytest.raises(ReplayControllerError): + controller.open(_asset(tmp_path, name="b.mkv")) + finally: + controller.close() + + +def test_missing_asset_does_not_start_mpv(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + missing = ReplayAsset(tmp_path / "missing.mkv", 1_000_000_000, FPS_60) + + with pytest.raises(ReplayControllerError): + controller.open(missing) + + assert mpv.arguments is None + assert not controller.is_open + + +def test_missing_executable_is_mapped(tmp_path: Path) -> None: + def factory(_arguments) -> NoReturn: + raise FileNotFoundError("mpv") + + controller = ReplayController( + ReplayControllerSettings(mpv_executable="does-not-exist"), + process_factory=factory, + transport_factory=FakeTransport, + sleep=lambda _seconds: None, + ) + with pytest.raises(MpvExecutableNotFoundError): + controller.open(_asset(tmp_path)) + + +def test_play_and_pause_send_set_property(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + controller.play() + controller.pause() + commands = mpv.transport.commands() + assert ["set_property", "pause", False] in commands + assert ["set_property", "pause", True] in commands + finally: + controller.close() + + +def test_is_paused_queries_mpv_property(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + mpv.state.pause = False + assert controller.is_paused() is False + mpv.state.pause = True + assert controller.is_paused() is True + assert ["get_property", "pause"] in mpv.transport.commands() + finally: + controller.close() + + +def test_step_forward_and_backward(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + controller.step_forward() + controller.step_backward() + commands = mpv.transport.commands() + assert ["frame-step"] in commands + assert ["frame-back-step"] in commands + finally: + controller.close() + + +def test_seek_frames_single_step_delegates(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + controller.seek_frames(1) + controller.seek_frames(-1) + commands = mpv.transport.commands() + assert ["frame-step"] in commands + assert ["frame-back-step"] in commands + assert not any(command and command[0] == "seek" for command in commands) + finally: + controller.close() + + +def test_seek_frames_zero_is_a_noop(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + before = len(mpv.transport.sent) + controller.seek_frames(0) + assert len(mpv.transport.sent) == before + finally: + controller.close() + + +def test_frame_offset_seconds_is_exact() -> None: + assert frame_offset_seconds(20, FPS_60) == Fraction(1, 3) + assert frame_offset_seconds(20, FPS_5994) == Fraction(20, 1) / Fraction(60000, 1001) + assert frame_offset_seconds(-20, FPS_60) == Fraction(-1, 3) + + +def test_seek_frames_relative_exact(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + controller.seek_frames(20) + seek = [command for command in mpv.transport.commands() if command[0] == "seek"][-1] + assert seek[2] == "relative+exact" + assert abs(float(seek[1]) - 1 / 3) < 1e-9 + finally: + controller.close() + + +def test_seek_frames_negative_relative(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + controller.seek_frames(-20) + seek = [command for command in mpv.transport.commands() if command[0] == "seek"][-1] + assert seek[2] == "relative+exact" + assert abs(float(seek[1]) + 1 / 3) < 1e-9 + finally: + controller.close() + + +def test_seek_frames_5994_uses_exact_fraction(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path, fps=FPS_5994)) + try: + controller.seek_frames(20) + seek = [command for command in mpv.transport.commands() if command[0] == "seek"][-1] + expected = float(Fraction(20, 1) / FPS_5994) + assert abs(float(seek[1]) - expected) < 1e-9 + finally: + controller.close() + + +def test_seek_absolute_is_clamped(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path, duration_ns=2_000_000_000)) + try: + controller.seek_absolute_ns(-5) + controller.seek_absolute_ns(5_000_000_000) + controller.seek_absolute_ns(1_500_000_000) + seeks = [command for command in mpv.transport.commands() if command[0] == "seek"] + assert seeks[0] == ["seek", "0", "absolute+exact"] + assert seeks[1] == ["seek", "2", "absolute+exact"] + assert seeks[2] == ["seek", "1.5", "absolute+exact"] + finally: + controller.close() + + +def test_position_ns_conversion(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + mpv.state.time_pos = 1.983 + assert controller.position_ns() == 1_983_000_000 + mpv.state.time_pos = 1.468135 + assert controller.position_ns() == 1_468_135_000 + finally: + controller.close() + + +def test_position_unavailable_is_explicit(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + mpv.state.time_pos = None + with pytest.raises(MpvPropertyUnavailableError): + controller.position_ns() + finally: + controller.close() + + +def test_set_point_and_time_difference(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + mpv.state.time_pos = 2.0 + point = controller.set_point() + assert point.position_ns == 2_000_000_000 + mpv.state.time_pos = 2.05 + assert controller.time_difference_ns(point) == 50_000_000 + finally: + controller.close() + + +def test_frame_difference_at_60fps(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + mpv.state.time_pos = 2.0 + point = controller.set_point() + mpv.state.time_pos = 2.05 + assert controller.frame_difference(point) == 3 + finally: + controller.close() + + +def test_frame_difference_at_5994fps(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path, fps=FPS_5994)) + try: + mpv.state.time_pos = 2.0 + point = controller.set_point() + mpv.state.time_pos = 2.05 + assert controller.frame_difference(point) == 3 + finally: + controller.close() + + +def test_operation_after_unexpected_exit(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + controller.open(_asset(tmp_path)) + try: + mpv.process.mark_exited(3) + with pytest.raises(MpvProcessExitedError): + controller.play() + finally: + controller.close() + + +def test_close_is_idempotent_and_keeps_the_asset(tmp_path: Path) -> None: + mpv = FakeMpv() + controller = mpv.controller() + asset = _asset(tmp_path) + controller.open(asset) + + controller.close() + controller.close() + + assert mpv.transport.closed + assert not controller.is_open + assert asset.path.exists() + + +def test_graceful_shutdown_does_not_terminate(tmp_path: Path) -> None: + mpv = FakeMpv(exit_on_quit=True) + controller = mpv.controller() + controller.open(_asset(tmp_path)) + + controller.close() + + assert mpv.process.terminate_calls == 0 + assert mpv.process.kill_calls == 0 + + +def test_forced_shutdown_terminates(tmp_path: Path) -> None: + mpv = FakeMpv(exit_on_quit=False, wait_results=[None, 0]) + controller = mpv.controller() + controller.open(_asset(tmp_path)) + + controller.close() + + assert mpv.process.terminate_calls == 1 + assert mpv.process.kill_calls == 0 + + +def test_forced_shutdown_falls_back_to_kill(tmp_path: Path) -> None: + mpv = FakeMpv(exit_on_quit=False, wait_results=[None, None, 0], terminate_works=False) + controller = mpv.controller() + controller.open(_asset(tmp_path)) + + controller.close() + + assert mpv.process.terminate_calls == 1 + assert mpv.process.kill_calls == 1 + + +def test_startup_timeout_cleans_up(tmp_path: Path) -> None: + mpv = FakeMpv(connect_error=OSError("pipe not ready"), startup_timeout_seconds=0.01) + controller = mpv.controller(startup_timeout_seconds=0.01) + + with pytest.raises(MpvStartupError): + controller.open(_asset(tmp_path)) + + assert not controller.is_open + assert mpv.process.terminate_calls >= 1 + + +def test_process_exit_before_connect_fails_fast(tmp_path: Path) -> None: + mpv = FakeMpv(running=False) + controller = mpv.controller() + + with pytest.raises(MpvStartupError): + controller.open(_asset(tmp_path)) + + assert mpv.process.terminate_calls == 0 diff --git a/tests/test_replay_models.py b/tests/test_replay_models.py new file mode 100644 index 0000000..bf14512 --- /dev/null +++ b/tests/test_replay_models.py @@ -0,0 +1,82 @@ +"""Tests for replay domain models and frame-difference math.""" + +from dataclasses import FrozenInstanceError +from fractions import Fraction +from pathlib import Path + +import pytest + +from quickreplay.input.models import AudioStreamInfo, StreamInfo, VideoStreamInfo +from quickreplay.recording.models import Segment +from quickreplay.replay.models import ReplayAsset, ReplaySnapshot, SetPoint, frame_difference + + +def _segment(segment_id: int, start_ns: int, end_ns: int) -> Segment: + return Segment( + id=segment_id, + path=Path(f"segment_{segment_id:06d}.mkv"), + session_start_ns=start_ns, + session_end_ns=end_ns, + video_frames=120, + audio_samples=96000, + ) + + +def _stream_info() -> StreamInfo: + return StreamInfo( + video=VideoStreamInfo(1920, 1080, Fraction(60, 1), "UYVY"), + audio=AudioStreamInfo(48000, 2), + ) + + +def test_replay_snapshot_holds_tuple_of_segments() -> None: + segments = (_segment(0, 0, 2_000_000_000), _segment(1, 2_000_000_000, 4_000_000_000)) + snapshot = ReplaySnapshot(segments=segments, stream_info=_stream_info()) + assert isinstance(snapshot.segments, tuple) + assert len(snapshot.segments) == 2 + assert snapshot.stream_info.video.fps == Fraction(60, 1) + + +def test_replay_snapshot_is_immutable() -> None: + snapshot = ReplaySnapshot(segments=(), stream_info=_stream_info()) + attribute = "segments" + with pytest.raises(FrozenInstanceError): + setattr(snapshot, attribute, ()) + + +def test_replay_asset() -> None: + asset = ReplayAsset(path=Path("replay.mkv"), duration_ns=30_000_000_000, fps=Fraction(60, 1)) + assert asset.path == Path("replay.mkv") + assert asset.duration_ns == 30_000_000_000 + with pytest.raises(ValueError): + ReplayAsset(path=Path("replay.mkv"), duration_ns=-1, fps=Fraction(60, 1)) + + +def test_set_point_holds_only_position() -> None: + point = SetPoint(position_ns=1_950_000_000) + assert point.position_ns == 1_950_000_000 + + +def test_frame_difference_60fps() -> None: + origin_ns = 1_950_000_000 + current_ns = 2_050_000_000 + assert frame_difference(current_ns, origin_ns, Fraction(60, 1)) == 6 + + +def test_frame_difference_5994fps() -> None: + # 20 frames at 60000/1001 fps is 20 * 1001/60000 s = 333666.66... us. + fps = Fraction(60000, 1001) + origin_ns = 0 + current_ns = round(20 * 1001 / 60000 * 1_000_000_000) + assert frame_difference(current_ns, origin_ns, fps) == 20 + + +def test_frame_difference_is_symmetric() -> None: + fps = Fraction(60, 1) + assert frame_difference(0, 2_050_000_000, fps) == -123 + + +def test_frame_difference_ties_away_from_zero() -> None: + half_frame_ns = 250_000_000 + assert frame_difference(half_frame_ns, 0, Fraction(2, 1)) == 1 + assert frame_difference(-half_frame_ns, 0, Fraction(2, 1)) == -1 diff --git a/tests/test_replay_remux.py b/tests/test_replay_remux.py new file mode 100644 index 0000000..b6d4a38 --- /dev/null +++ b/tests/test_replay_remux.py @@ -0,0 +1,272 @@ +"""Media-level verification of the stream-copy replay remux.""" + +import math +from fractions import Fraction +from pathlib import Path + +import av + +from quickreplay.recording.models import Segment +from quickreplay.replay.asset_builder import ReplayAssetBuilder +from quickreplay.replay.models import ReplaySnapshot +from quickreplay.replay.remux import probe_layout, validate_segment_layouts +from quickreplay.units import round_fraction + +FPS_60 = Fraction(60, 1) +FPS_5994 = Fraction(60000, 1001) + + +def _snapshot(record_segments, directory: Path, **kwargs): + segments, info = record_segments(directory, **kwargs) + return ReplaySnapshot(segments=segments, stream_info=info), segments, info + + +def _boundary_ms(segments: tuple[Segment, ...]) -> set[int]: + return {round_fraction(Fraction(segment.session_start_ns, 1_000_000)) for segment in segments} + + +def _decoded_frames(segment: Segment) -> int: + """Decoded video frame count of a single segment file.""" + with av.open(str(segment.path)) as container: + return sum(1 for _ in container.decode(container.streams.video[0])) + + +def test_remux_60fps(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + assert asset.fps == FPS_60 + assert facts.video_codec == "h264" + assert facts.audio_codec == "pcm_f32le" + assert len(facts.decoded_video_pts) == sum(segment.video_frames for segment in segments) + assert facts.decoded_audio_samples == sum(segment.audio_samples for segment in segments) + assert asset.duration_ns == segments[-1].session_end_ns - segments[0].session_start_ns + + +def test_remux_5994fps(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_5994, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + assert asset.fps == FPS_5994 + assert len(facts.decoded_video_pts) == sum(segment.video_frames for segment in segments) + assert facts.decoded_audio_samples == sum(segment.audio_samples for segment in segments) + + +def test_remux_video_and_audio_streams( + tmp_path: Path, record_segments, replay_probe, probe +) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + source = probe(segments[0].path) + + assert facts.audio_codec is not None + assert facts.audio_sample_rate == source.audio_sample_rate + assert facts.audio_channels == source.audio_channels + assert facts.video_codec == source.video_codec + assert facts.video_codec == "h264" + assert facts.audio_codec == "pcm_f32le" + + +def test_remux_video_only(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_60, + width=64, + height=36, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + assert facts.audio_codec is None + assert facts.decoded_audio_samples == 0 + assert facts.audio_packet_pts == () + assert len(facts.decoded_video_pts) == sum(segment.video_frames for segment in segments) + + +def test_frame_count_matches_segments(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=6_500_000_000, + fps=FPS_5994, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + per_segment = [_decoded_frames(segment) for segment in segments] + assert len(facts.decoded_video_pts) == sum(per_segment) + assert facts.decoded_audio_samples == sum(segment.audio_samples for segment in segments) + + +def test_packet_timestamps_are_monotonic(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, _segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + assert facts.video_packet_dts[0] == 0 + assert facts.video_packet_pts[0] == 0 + assert all( + b > a for a, b in zip(facts.video_packet_dts, facts.video_packet_dts[1:], strict=False) + ) + assert all( + b > a for a, b in zip(facts.video_packet_pts, facts.video_packet_pts[1:], strict=False) + ) + assert facts.audio_packet_dts[0] == 0 + assert all( + b >= a for a, b in zip(facts.audio_packet_dts, facts.audio_packet_dts[1:], strict=False) + ) + assert all( + b >= a for a, b in zip(facts.audio_packet_pts, facts.audio_packet_pts[1:], strict=False) + ) + + +def test_boundary_continuity(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + pts = facts.decoded_video_pts + + nominal_ms = Fraction(1000, 1) / FPS_60 + low = math.floor(nominal_ms) + high = math.ceil(nominal_ms) + deltas = [b - a for a, b in zip(pts, pts[1:], strict=False)] + assert deltas + assert all(low <= delta <= high for delta in deltas) + + boundaries = _boundary_ms(segments) + assert boundaries <= set(pts) + + +def test_keyframes_survive_at_segment_boundaries( + tmp_path: Path, record_segments, replay_probe +) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=4_500_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + assert facts.keyframe_pts[0] == 0 + assert _boundary_ms(segments) <= set(facts.keyframe_pts) + + +def test_seek_into_later_segment(tmp_path: Path, record_segments) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=6_500_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + + target_ns = segments[2].session_start_ns + 100_000_000 + target_ms = round_fraction(Fraction(target_ns, 1_000_000)) + with av.open(str(asset.path)) as container: + container.seek(target_ms, backward=True, stream=container.streams.video[0]) + decoded = [ + frame.pts + for frame in container.decode(container.streams.video[0]) + if frame.pts is not None + ] + + assert decoded + assert decoded[0] <= target_ms + assert decoded[-1] >= target_ms + + +def test_single_segment(tmp_path: Path, record_segments, replay_probe) -> None: + snapshot, segments, _info = _snapshot( + record_segments, + tmp_path, + duration_ns=1_000_000_000, + fps=FPS_60, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + assert len(segments) == 1 + asset = ReplayAssetBuilder().build(snapshot, tmp_path / "out") + facts = replay_probe(asset.path) + + assert asset.path.exists() + assert len(facts.decoded_video_pts) == segments[0].video_frames + assert facts.decoded_audio_samples == segments[0].audio_samples + + +def test_probe_layout_and_validation(tmp_path: Path, record_segments) -> None: + segments, _info = record_segments( + tmp_path, duration_ns=4_500_000_000, fps=FPS_60, width=64, height=36 + ) + + layout = probe_layout(segments[0].path) + assert layout.video.codec == "h264" + assert layout.video.width == 64 + assert layout.video.height == 36 + assert layout.audio is None + validate_segment_layouts(segments) diff --git a/tests/test_replay_repeat.py b/tests/test_replay_repeat.py new file mode 100644 index 0000000..a393d39 --- /dev/null +++ b/tests/test_replay_repeat.py @@ -0,0 +1,40 @@ +"""Tests for Replay press-and-hold repetition.""" + +import asyncio + +from quickreplay.ui.replay_repeat import ReplayActionRepeater + + +def test_repeater_runs_immediately_and_stops_after_release() -> None: + async def scenario() -> None: + actions: list[str] = [] + gates: list[asyncio.Event] = [] + + async def sleep(_seconds: float) -> None: + gate = asyncio.Event() + gates.append(gate) + await gate.wait() + + async def action() -> None: + actions.append("action") + + repeater = ReplayActionRepeater(sleep=sleep) + repeater.start(action, interval=0.085) + await asyncio.sleep(0) + assert actions == ["action"] + assert len(gates) == 1 + + gates[0].set() + await asyncio.sleep(0) + await asyncio.sleep(0) + assert actions == ["action", "action"] + assert len(gates) == 2 + + repeater.release() + gates[1].set() + await asyncio.sleep(0) + assert actions == ["action", "action"] + + await repeater.stop() + + asyncio.run(scenario()) diff --git a/tests/test_ring_snapshot.py b/tests/test_ring_snapshot.py new file mode 100644 index 0000000..84b2f5d --- /dev/null +++ b/tests/test_ring_snapshot.py @@ -0,0 +1,159 @@ +"""Tests for RingStorage snapshot leases, pinning and clear.""" + +from collections.abc import Callable + +import pytest + +from quickreplay.recording.models import Segment +from quickreplay.recording.ring_storage import RingStorage + +SECOND = 1_000_000_000 + + +def _ring_with_two(make_segment: Callable[..., Segment]) -> tuple[RingStorage, Segment, Segment]: + ring = RingStorage(buffer_duration_ns=100 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + ring.add(s0) + ring.add(s1) + return ring, s0, s1 + + +def test_snapshot_returns_current_segments(make_segment: Callable[..., Segment]) -> None: + ring, s0, s1 = _ring_with_two(make_segment) + with ring.snapshot() as lease: + assert lease.segments == (s0, s1) + + +def test_snapshot_is_immutable_after_add(make_segment: Callable[..., Segment]) -> None: + ring, s0, s1 = _ring_with_two(make_segment) + lease = ring.snapshot() + ring.add(make_segment(2, 4 * SECOND, 6 * SECOND)) + try: + assert lease.segments == (s0, s1) + finally: + lease.release() + + +def test_snapshot_pins_and_defers_deletion(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + ring.add(s0) + ring.add(s1) + + lease = ring.snapshot() # pins s0 and s1 + ring.add(make_segment(2, 4 * SECOND, 6 * SECOND)) # cutoff = 2s -> s0 expires + + assert s0.path.exists() # pinned, so not deleted + assert s0 not in ring.segments # but excluded from the active ring + assert s1 in ring.segments + + lease.release() + assert not s0.path.exists() + + +def test_snapshot_excludes_expired_segments(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + s2 = make_segment(2, 4 * SECOND, 6 * SECOND) + ring.add(s0) + ring.add(s1) + ring.add(s2) # s0 expires (unpinned) and is deleted + + with ring.snapshot() as lease: + assert s0 not in lease.segments + assert lease.segments == (s1, s2) + + +def test_multiple_leases_keep_file_until_last_release( + make_segment: Callable[..., Segment], +) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + ring.add(s0) + ring.add(s1) + + lease_a = ring.snapshot() + lease_b = ring.snapshot() + ring.add(make_segment(2, 4 * SECOND, 6 * SECOND)) # s0 expires while pinned twice + + lease_a.release() + assert s0.path.exists() # still pinned by lease_b + + lease_b.release() + assert not s0.path.exists() + + +def test_empty_snapshot_is_allowed() -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + with ring.snapshot() as lease: + assert lease.segments == () + assert lease.released + + +def test_double_release_is_safe(make_segment: Callable[..., Segment]) -> None: + ring, _s0, _s1 = _ring_with_two(make_segment) + lease = ring.snapshot() + lease.release() + lease.release() + assert lease.released + # The segments are still fine (no negative pin counts). + assert ring.segment_count == 2 + + +def test_released_snapshot_segments_remain_readable( + make_segment: Callable[..., Segment], +) -> None: + ring, s0, s1 = _ring_with_two(make_segment) + lease = ring.snapshot() + lease.release() + assert lease.segments == (s0, s1) + + +def test_context_manager_releases_on_exception(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + ring.add(s0) + ring.add(s1) + + class BoomError(Exception): + pass + + with pytest.raises(BoomError): + with ring.snapshot(): + raise BoomError + + # The lease was released, so the next retention can delete s0. + ring.add(make_segment(2, 4 * SECOND, 6 * SECOND)) + assert not s0.path.exists() + + +def test_clear_respects_active_lease(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=100 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + ring.add(s0) + ring.add(s1) + + lease = ring.snapshot() + ring.clear() + + assert ring.segments == () + assert s0.path.exists() + assert s1.path.exists() + + lease.release() + assert not s0.path.exists() + assert not s1.path.exists() + + +def test_clear_without_lease_deletes_everything(make_segment: Callable[..., Segment]) -> None: + ring, s0, s1 = _ring_with_two(make_segment) + ring.clear() + assert not s0.path.exists() + assert not s1.path.exists() + assert ring.duration_ns == 0 diff --git a/tests/test_ring_storage.py b/tests/test_ring_storage.py new file mode 100644 index 0000000..1620dfd --- /dev/null +++ b/tests/test_ring_storage.py @@ -0,0 +1,236 @@ +"""Tests for RingStorage: add, retention, deletion, chronology and integration.""" + +from collections.abc import Callable +from fractions import Fraction +from pathlib import Path + +import pytest + +from quickreplay.input.models import VideoFrame +from quickreplay.recording.errors import ( + RingStorageError, + SegmentDeleteError, + SegmentOrderError, +) +from quickreplay.recording.models import Segment +from quickreplay.recording.ring_storage import RingStorage +from quickreplay.recording.segment_recorder import SegmentRecorder + +SECOND = 1_000_000_000 + + +def test_add_and_properties(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=10 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + + ring.add(s0) + ring.add(s1) + + assert ring.segments == (s0, s1) + assert ring.segment_count == 2 + assert ring.duration_ns == 4 * SECOND + + +def test_empty_ring_properties() -> None: + ring = RingStorage(buffer_duration_ns=10 * SECOND) + assert ring.segments == () + assert ring.segment_count == 0 + assert ring.duration_ns == 0 + + +def test_retention_boundary_deletes_expired_file(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + s2 = make_segment(2, 4 * SECOND, 6 * SECOND) + + ring.add(s0) + ring.add(s1) + ring.add(s2) + + # cutoff = 6s - 4s = 2s, and s0.end == cutoff -> expired. + assert ring.segments == (s1, s2) + assert not s0.path.exists() + assert s1.path.exists() + assert s2.path.exists() + + +def test_retention_keeps_whole_segments(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=5 * SECOND) + for index in range(3): + ring.add(make_segment(index, index * 2 * SECOND, (index + 1) * 2 * SECOND)) + + # cutoff = 1s: nothing expires, so the buffer may exceed the configured span. + assert ring.segment_count == 3 + assert ring.duration_ns == 6 * SECOND + + +def test_retention_is_time_based_not_count_based(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=2 * SECOND) + s0 = make_segment(0, 0, 1 * SECOND) + s1 = make_segment(1, 1 * SECOND, 5 * SECOND) + s2 = make_segment(2, 5 * SECOND, 6 * SECOND) + + ring.add(s0) + ring.add(s1) + ring.add(s2) + + # cutoff = 6s - 2s = 4s: only s0 (end 1s) expires. + assert ring.segments == (s1, s2) + assert not s0.path.exists() + + +def test_chronology_rejects_overlap(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=100 * SECOND) + ring.add(make_segment(0, 0, 2 * SECOND)) + with pytest.raises(SegmentOrderError): + ring.add(make_segment(1, 1 * SECOND, 3 * SECOND)) + + +def test_chronology_rejects_gap(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=100 * SECOND) + ring.add(make_segment(0, 0, 2 * SECOND)) + with pytest.raises(SegmentOrderError): + ring.add(make_segment(1, 3 * SECOND, 5 * SECOND)) + + +def test_chronology_rejects_duplicate_and_backward_id(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=100 * SECOND) + ring.add(make_segment(5, 0, 2 * SECOND)) + with pytest.raises(SegmentOrderError): + ring.add(make_segment(5, 2 * SECOND, 4 * SECOND)) + with pytest.raises(SegmentOrderError): + ring.add(make_segment(4, 2 * SECOND, 4 * SECOND)) + + +def test_add_missing_file_raises(tmp_path: Path) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + missing = Segment( + id=0, + path=tmp_path / "missing.mkv", + session_start_ns=0, + session_end_ns=2 * SECOND, + video_frames=1, + audio_samples=0, + ) + with pytest.raises(RingStorageError): + ring.add(missing) + + +def test_clear_deletes_all_segments(make_segment: Callable[..., Segment]) -> None: + ring = RingStorage(buffer_duration_ns=100 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + ring.add(s0) + ring.add(s1) + + ring.clear() + + assert ring.segments == () + assert ring.duration_ns == 0 + assert not s0.path.exists() + assert not s1.path.exists() + + +def test_delete_failure_is_not_silent_and_keeps_entry( + make_segment: Callable[..., Segment], +) -> None: + def delete(_path: Path) -> None: + raise OSError("injected delete failure") + + ring = RingStorage(buffer_duration_ns=4 * SECOND, delete_file=delete) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + s2 = make_segment(2, 4 * SECOND, 6 * SECOND) + ring.add(s0) + ring.add(s1) + + with pytest.raises(SegmentDeleteError) as excinfo: + ring.add(s2) # s0 expires but cannot be deleted + + assert s0.path in excinfo.value.paths + + # The new segment is registered and the failed entry is not lost. + assert ring.segments == (s1, s2) + assert s0.path.exists() + # The failure is retryable through a later add. + assert ring.segment_count == 2 + + +def test_delete_retry_succeeds_on_later_operation( + make_segment: Callable[..., Segment], +) -> None: + state = {"fail": True} + + def delete(path: Path) -> None: + if state["fail"]: + state["fail"] = False + raise OSError("injected first failure") + path.unlink() + + ring = RingStorage(buffer_duration_ns=4 * SECOND, delete_file=delete) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + s2 = make_segment(2, 4 * SECOND, 6 * SECOND) + ring.add(s0) + ring.add(s1) + + with pytest.raises(SegmentDeleteError): + ring.add(s2) + assert s0.path.exists() + + # A later add retries the pending deletion and now succeeds. + ring.add(make_segment(3, 6 * SECOND, 8 * SECOND)) + assert not s0.path.exists() + + +def test_externally_deleted_file_is_treated_as_success( + make_segment: Callable[..., Segment], +) -> None: + ring = RingStorage(buffer_duration_ns=4 * SECOND) + s0 = make_segment(0, 0, 2 * SECOND) + s1 = make_segment(1, 2 * SECOND, 4 * SECOND) + s2 = make_segment(2, 4 * SECOND, 6 * SECOND) + ring.add(s0) + ring.add(s1) + + s0.path.unlink() # external deletion + + ring.add(s2) # retention treats FileNotFoundError as a successful cleanup + + assert ring.segments == (s1, s2) + + +def test_segment_recorder_integration(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + frames = media.frames(duration_ns=6_500_000_000, fps=fps, width=64, height=36) + segments: list[Segment] = [] + for frame in frames: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + if last is not None: + segments.append(last) + recorder.close() + + assert len(segments) >= 3 + assert all(segment.path.exists() for segment in segments) + + ring = RingStorage(buffer_duration_ns=4 * SECOND) + for segment in segments: + ring.add(segment) + + newest_end_ns = segments[-1].session_end_ns + cutoff_ns = newest_end_ns - 4 * SECOND + for segment in segments: + if segment.session_end_ns <= cutoff_ns: + assert not segment.path.exists() + else: + assert segment.path.exists() + assert segment in ring.segments diff --git a/tests/test_segment_audio.py b/tests/test_segment_audio.py new file mode 100644 index 0000000..465d1e6 --- /dev/null +++ b/tests/test_segment_audio.py @@ -0,0 +1,276 @@ +"""Tests for audio routing, boundary splitting and continuity.""" + +from fractions import Fraction +from pathlib import Path + +import pytest + +from quickreplay.input.models import AudioFrame, StreamInfo, VideoFrame +from quickreplay.recording.errors import SegmentFormatError +from quickreplay.recording.models import Segment +from quickreplay.recording.segment_recorder import SegmentRecorder + +SAMPLE_RATE = 48000 +CHANNELS = 2 +FPS = Fraction(60, 1) + + +class _AudioCaptureWriter: + def __init__(self, segment_id: int, directory: Path, _stream_info: StreamInfo) -> None: + self.path = directory / f"segment_{segment_id:06d}.mkv" + self.audio_writes: list[tuple[int, int]] = [] + + def write_video(self, frame: VideoFrame, pts: int) -> None: + pass + + def write_audio(self, data, pts: int) -> None: + self.audio_writes.append((pts, int(data.shape[1]))) + + def finalize(self) -> Path: + self.path.write_bytes(b"segment") + return self.path + + def abort(self) -> None: + self.path.unlink(missing_ok=True) + + +def _push_audio_range(media, recorder: SegmentRecorder, start_sample: int, end_sample: int) -> None: + position = start_sample + while position < end_sample: + count = min(1024, end_sample - position) + recorder.push_audio( + media.audio( + start_sample=position, + sample_rate=SAMPLE_RATE, + channels=CHANNELS, + count=count, + ) + ) + position += count + + +def test_audio_split_is_sample_exact(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + # Large audio frames deliberately straddle the 2 s boundary. + frames = media.frames( + duration_ns=4_000_000_000, + fps=FPS, + width=64, + height=36, + sample_rate=SAMPLE_RATE, + channels=CHANNELS, + audio_frame_samples=4096, + ) + segments: list[Segment] = [] + for frame in frames: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + assert segments[0].audio_samples == 96000 + assert segments[1].audio_samples == 96000 + assert sum(segment.audio_samples for segment in segments) == 192000 + + +def test_audio_overlap_is_trimmed_and_duplicate_is_dropped(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + writers: list[_AudioCaptureWriter] = [] + + def factory(segment_id: int, directory: Path, stream_info: StreamInfo) -> _AudioCaptureWriter: + writer = _AudioCaptureWriter(segment_id, directory, stream_info) + writers.append(writer) + return writer + + recorder = SegmentRecorder(writer_factory=factory) + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video(index=0, fps=FPS, width=64, height=36)) + + assert ( + recorder.push_audio( + media.audio(start_sample=0, sample_rate=SAMPLE_RATE, channels=2, count=1024) + ) + == 1024 + ) + assert ( + recorder.push_audio( + media.audio(start_sample=1023, sample_rate=SAMPLE_RATE, channels=2, count=1024) + ) + == 1023 + ) + assert ( + recorder.push_audio( + media.audio(start_sample=1500, sample_rate=SAMPLE_RATE, channels=2, count=100) + ) + == 0 + ) + assert ( + recorder.push_audio( + media.audio(start_sample=2100, sample_rate=SAMPLE_RATE, channels=2, count=100) + ) + == 100 + ) + + recorder.push_video(media.video_at(timestamp_ns=1_000_000_000, fps=FPS, width=64, height=36)) + recorder.finish() + recorder.close() + + assert writers[0].audio_writes == [(0, 1024), (1024, 1023), (2100, 100)] + + +def test_audio_continuity_and_local_pts(media, tmp_path: Path, probe) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + frames = media.frames( + duration_ns=4_000_000_000, + fps=FPS, + width=64, + height=36, + sample_rate=SAMPLE_RATE, + channels=CHANNELS, + ) + segments: list[Segment] = [] + for frame in frames: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + for segment in segments: + facts = probe(segment.path) + assert facts.audio_present + assert facts.audio_samples == segment.audio_samples + if segment.audio_samples > 0: + assert facts.first_audio_pts == 0 + # No gap or overlap: the session-wide sample count is the sum of the parts. + assert sum(segment.audio_samples for segment in segments) == 192000 + + +def test_trailing_audio_is_trimmed(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + + # Video ends at 2.0 s (frame 120 starts the second segment); audio runs to 3 s. + segments: list[Segment] = [] + total_audio = 3 * SAMPLE_RATE + audio_pos = 0 + for index in range(121): + video_ts = round(index * 1e9 / 60) + while audio_pos < total_audio: + frame = media.audio( + start_sample=audio_pos, + sample_rate=SAMPLE_RATE, + channels=CHANNELS, + count=min(1024, total_audio - audio_pos), + ) + if frame.timestamp_ns > video_ts: + break + recorder.push_audio(frame) + audio_pos += frame.sample_count + segments.extend(recorder.push_video(media.video(index=index, fps=FPS, width=64, height=36))) + # Audio after the last video frame (2.0 s .. 3.0 s). + _push_audio_range(media, recorder, audio_pos, total_audio) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + # final end = 2.0 s + 1/60 s -> 96800 samples; the rest is trimmed. + assert sum(segment.audio_samples for segment in segments) == 96800 + + +def test_audio_before_first_video_is_trimmed(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + + # Audio arrives before any video; all of it is before the first video (1.0 s). + _push_audio_range(media, recorder, 0, 19200) + + segments: list[Segment] = [] + for index in range(3): + timestamp_ns = 1_000_000_000 + index * round(1e9 / 60) + segments.extend( + recorder.push_video( + media.video_at(timestamp_ns=timestamp_ns, fps=FPS, width=64, height=36) + ) + ) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + assert sum(segment.audio_samples for segment in segments) == 0 + + +def test_audio_ahead_of_video_splits_at_actual_boundary(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + + segments: list[Segment] = [] + # Video up to 1.95 s. + for index in range(118): + segments.extend(recorder.push_video(media.video(index=index, fps=FPS, width=64, height=36))) + + # Audio rushes ahead past the nominal 2 s boundary, up to 2.05 s. + boundary_sample = round(2_050_000_000 / 1e9 * SAMPLE_RATE) + _push_audio_range(media, recorder, 0, boundary_sample) + + # The actual boundary is the first video frame >= 2 s, at 2.05 s. + segments.extend( + recorder.push_video( + media.video_at(timestamp_ns=2_050_000_000, fps=FPS, width=64, height=36) + ) + ) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + # Segment 0 must contain audio up to the *video* boundary, not the nominal one. + assert segments[0].session_end_ns == 2_050_000_000 + assert segments[0].audio_samples == boundary_sample == 98400 + + +def test_audio_frame_shape_mismatch_raises(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=FPS, width=64, height=36, sample_rate=SAMPLE_RATE, channels=CHANNELS + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video(index=0, fps=FPS, width=64, height=36)) + + # sample_count does not match the payload shape. + payload = media.audio( + start_sample=0, sample_rate=SAMPLE_RATE, channels=CHANNELS, count=1024 + ).data + bad = AudioFrame(0, SAMPLE_RATE, CHANNELS, 999, payload) + + with pytest.raises(SegmentFormatError): + recorder.push_audio(bad) + recorder.close() diff --git a/tests/test_segment_media.py b/tests/test_segment_media.py new file mode 100644 index 0000000..cf28760 --- /dev/null +++ b/tests/test_segment_media.py @@ -0,0 +1,182 @@ +"""Media-level verification: decode, keyframes, PTS and stream layout.""" + +from collections.abc import Iterable +from dataclasses import replace +from fractions import Fraction +from pathlib import Path + +import pytest + +from quickreplay.input.models import AudioFrame, VideoFrame +from quickreplay.recording.models import Segment +from quickreplay.recording.segment_recorder import SegmentRecorder + + +def _record(media, recorder: SegmentRecorder, **kwargs) -> list[Segment]: + frames: Iterable[VideoFrame | AudioFrame] = media.frames(**kwargs) + segments: list[Segment] = [] + for frame in frames: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + if last is not None: + segments.append(last) + return segments + + +def test_media_60fps(media, tmp_path: Path, probe) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36, sample_rate=48000, channels=2) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + segments = _record( + media, + recorder, + duration_ns=4_500_000_000, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + recorder.close() + + assert len(segments) == 3 + for segment in segments: + facts = probe(segment.path) + assert facts.first_video_pts == 0 + assert facts.keyframe_count >= 1 + assert facts.decoded_video_frames == segment.video_frames + assert facts.video_rate == fps + assert facts.audio_present + assert facts.first_audio_pts == 0 + assert facts.audio_samples == segment.audio_samples + + +def test_media_5994fps(media, tmp_path: Path, probe) -> None: + fps = Fraction(60000, 1001) + info = media.stream_info(fps=fps, width=64, height=36, sample_rate=48000, channels=2) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + segments = _record( + media, + recorder, + duration_ns=4_500_000_000, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + recorder.close() + + assert len(segments) == 3 + for segment in segments: + facts = probe(segment.path) + assert facts.first_video_pts == 0 + assert facts.keyframe_count >= 1 + assert facts.decoded_video_frames == segment.video_frames + # Matroska stores the rate approximately (19001/317 ~= 60000/1001). + assert facts.video_rate is not None + assert abs(float(facts.video_rate) - float(fps)) < 0.01 + + +@pytest.mark.parametrize("fps", [Fraction(60, 1), Fraction(60000, 1001)]) +def test_jittered_audio_timeline_is_decodable(media, tmp_path: Path, probe, fps) -> None: + info = media.stream_info(fps=fps, width=64, height=36, sample_rate=48000, channels=2) + frames = media.frames( + duration_ns=6_500_000_000, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + jitter_start = 50 * 1024 + jitter_ns = round(1_000_000_000 / 48000) + jittered = [] + changed = False + for frame in frames: + if isinstance(frame, AudioFrame) and frame.timestamp_ns == round( + jitter_start * 1_000_000_000 / 48000 + ): + frame = replace(frame, timestamp_ns=frame.timestamp_ns - jitter_ns) + changed = True + jittered.append(frame) + assert changed + + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + segments: list[Segment] = [] + for frame in jittered: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + assert len(segments) >= 3 + for segment in segments: + facts = probe(segment.path) + assert facts.audio_present + assert facts.audio_samples == segment.audio_samples + + +def test_stream_layout_consistent_across_segments(media, tmp_path: Path, probe) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36, sample_rate=48000, channels=2) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + segments = _record( + media, + recorder, + duration_ns=6_500_000_000, + fps=fps, + width=64, + height=36, + sample_rate=48000, + channels=2, + ) + recorder.close() + + assert len(segments) >= 3 + layouts = { + ( + facts.video_codec, + facts.width, + facts.height, + facts.pixel_format, + facts.video_time_base, + facts.video_rate, + facts.audio_codec, + facts.audio_sample_rate, + facts.audio_channels, + facts.audio_time_base, + ) + for facts in (probe(segment.path) for segment in segments) + } + assert len(layouts) == 1 + + +def test_video_only_media(media, tmp_path: Path, probe) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + segments = _record(media, recorder, duration_ns=4_500_000_000, fps=fps, width=64, height=36) + recorder.close() + + assert segments + for segment in segments: + facts = probe(segment.path) + assert not facts.audio_present + assert facts.audio_samples == 0 + assert segment.audio_samples == 0 + assert facts.decoded_video_frames == segment.video_frames + assert facts.first_video_pts == 0 + assert facts.keyframe_count >= 1 diff --git a/tests/test_segment_recorder.py b/tests/test_segment_recorder.py new file mode 100644 index 0000000..ed2ccd3 --- /dev/null +++ b/tests/test_segment_recorder.py @@ -0,0 +1,287 @@ +"""Tests for segment rotation, metadata and recorder lifecycle.""" + +from collections.abc import Iterable +from fractions import Fraction +from pathlib import Path + +import pytest + +from quickreplay.input.models import AudioFrame, VideoFrame +from quickreplay.recording.errors import ( + SegmentEncodingError, + SegmentFormatError, + SegmentTimestampError, +) +from quickreplay.recording.models import Segment +from quickreplay.recording.segment_recorder import SegmentRecorder + + +def _record(recorder: SegmentRecorder, frames: Iterable[VideoFrame | AudioFrame]) -> list[Segment]: + produced: list[Segment] = [] + for frame in frames: + if isinstance(frame, VideoFrame): + produced.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + last = recorder.finish() + if last is not None: + produced.append(last) + return produced + + +def test_rotation_is_time_based(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36, sample_rate=48000, channels=2) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + frames = media.frames( + duration_ns=4_500_000_000, fps=fps, width=64, height=36, sample_rate=48000, channels=2 + ) + segments = _record(recorder, frames) + recorder.close() + + assert [segment.id for segment in segments] == [0, 1, 2] + assert segments[0].session_start_ns == 0 + assert segments[0].session_end_ns == 2_000_000_000 + assert segments[1].session_start_ns == 2_000_000_000 + assert segments[1].session_end_ns == 4_000_000_000 + assert segments[2].session_start_ns == 4_000_000_000 + assert 0 < segments[2].duration_ns < 2_000_000_000 + for previous, following in zip(segments, segments[1:], strict=False): + assert previous.session_end_ns == following.session_start_ns + assert segments[0].video_frames == 120 + assert segments[1].video_frames == 120 + assert [segment.path.name for segment in segments] == [ + "segment_000000.mkv", + "segment_000001.mkv", + "segment_000002.mkv", + ] + assert all(segment.path.exists() for segment in segments) + assert not list(tmp_path.glob("*.tmp.mkv")) + + +def test_rotation_uses_timestamps_not_frame_count(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + + # The threshold is crossed on the 6th frame, not at a fixed count. + timestamps_ns = [ + 0, + 950_000_000, + 1_900_000_000, + 1_950_000_000, + 1_983_000_000, + 2_050_000_000, + 2_100_000_000, + ] + segments: list[Segment] = [] + for timestamp_ns in timestamps_ns: + frame = media.video_at(timestamp_ns=timestamp_ns, fps=fps, width=64, height=36) + segments.extend(recorder.push_video(frame)) + last = recorder.finish() + assert last is not None + segments.append(last) + recorder.close() + + assert len(segments) == 2 + assert segments[0].video_frames == 5 + assert segments[1].video_frames == 2 + assert segments[0].session_end_ns == 2_050_000_000 + assert segments[1].session_start_ns == 2_050_000_000 + + +def test_rotation_5994fps(media, tmp_path: Path) -> None: + fps = Fraction(60000, 1001) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + frames = media.frames(duration_ns=4_500_000_000, fps=fps, width=64, height=36) + segments = _record(recorder, frames) + recorder.close() + + assert len(segments) == 3 + frame_120 = media.video(index=120, fps=fps, width=64, height=36) + assert segments[1].session_start_ns == frame_120.timestamp_ns + assert segments[1].session_start_ns >= 2_000_000_000 + assert segments[0].video_frames == 120 + + +def test_partial_final_segment_is_kept(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + frames = media.frames(duration_ns=4_500_000_000, fps=fps, width=64, height=36) + segments = _record(recorder, frames) + recorder.close() + + assert len(segments) == 3 + assert segments[2].duration_ns < 2_000_000_000 + assert segments[2].video_frames > 0 + + +def test_video_only_recording(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + frames = media.frames(duration_ns=4_500_000_000, fps=fps, width=64, height=36) + segments = _record(recorder, frames) + recorder.close() + + assert segments + assert all(segment.audio_samples == 0 for segment in segments) + assert all(segment.path.exists() for segment in segments) + + +def test_no_video_returns_none(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=Fraction(60, 1), width=64, height=36, sample_rate=48000, channels=2 + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + for index in range(5): + recorder.push_audio( + media.audio(start_sample=index * 1024, sample_rate=48000, channels=2, count=1024) + ) + + assert recorder.finish() is None + recorder.close() + assert not list(tmp_path.glob("*.mkv")) + assert not list(tmp_path.glob("*.tmp.mkv")) + + +def test_close_without_finish_does_not_publish(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video(index=0, fps=fps, width=64, height=36)) + recorder.close() + recorder.close() # idempotent + + assert not list(tmp_path.glob("*.mkv")) + assert not list(tmp_path.glob("*.tmp.mkv")) + + +@pytest.mark.parametrize( + "width,height,fps,pixel_format", + [ + (128, 36, Fraction(60, 1), "RGB24"), + (64, 72, Fraction(60, 1), "RGB24"), + (64, 36, Fraction(30, 1), "RGB24"), + (64, 36, Fraction(60, 1), "BGR24"), + ], +) +def test_video_format_mismatch_raises( + media, tmp_path: Path, width: int, height: int, fps: Fraction, pixel_format: str +) -> None: + info = media.stream_info(fps=Fraction(60, 1), width=64, height=36, pixel_format="RGB24") + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video(index=0, fps=Fraction(60, 1), width=64, height=36)) + + bad = media.video_at( + timestamp_ns=20_000_000, fps=fps, width=width, height=height, pixel_format=pixel_format + ) + with pytest.raises(SegmentFormatError): + recorder.push_video(bad) + recorder.close() + + +def test_audio_format_mismatch_raises(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=Fraction(60, 1), width=64, height=36, sample_rate=48000, channels=2 + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video(index=0, fps=Fraction(60, 1), width=64, height=36)) + + with pytest.raises(SegmentFormatError): + recorder.push_audio(media.audio(start_sample=0, sample_rate=44100, channels=2, count=1024)) + with pytest.raises(SegmentFormatError): + recorder.push_audio(media.audio(start_sample=0, sample_rate=48000, channels=1, count=1024)) + recorder.close() + + +def test_video_timestamp_regression_raises(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video_at(timestamp_ns=1_000_000_000, fps=fps, width=64, height=36)) + + with pytest.raises(SegmentTimestampError): + recorder.push_video(media.video_at(timestamp_ns=500_000_000, fps=fps, width=64, height=36)) + recorder.close() + + +def test_audio_timestamp_regression_raises(media, tmp_path: Path) -> None: + info = media.stream_info( + fps=Fraction(60, 1), width=64, height=36, sample_rate=48000, channels=2 + ) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info)) + recorder.push_video(media.video(index=0, fps=Fraction(60, 1), width=64, height=36)) + recorder.push_audio(media.audio(start_sample=2048, sample_rate=48000, channels=2, count=1024)) + + with pytest.raises(SegmentTimestampError): + recorder.push_audio(media.audio(start_sample=0, sample_rate=48000, channels=2, count=1024)) + recorder.close() + + +def test_timestamp_before_epoch_raises(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + recorder = SegmentRecorder() + recorder.start(media.session(tmp_path, info, epoch_ns=1_000_000_000)) + + with pytest.raises(SegmentTimestampError): + recorder.push_video(media.video_at(timestamp_ns=0, fps=fps, width=64, height=36)) + recorder.close() + + +class ExplodingWriter: + """Test double that fails while finalizing and cleans up after itself.""" + + def __init__(self, segment_id: int, directory: Path, stream_info: object) -> None: + self.tmp_path = Path(directory) / f"segment_{segment_id:06d}.tmp.mkv" + self.tmp_path.write_bytes(b"partial") + + def write_video(self, frame: VideoFrame, pts: int) -> None: + pass + + def write_audio(self, data: object, pts: int) -> None: + pass + + def finalize(self) -> Path: + raise SegmentEncodingError("injected finalize failure") + + def abort(self) -> None: + self.tmp_path.unlink(missing_ok=True) + + +def test_failure_cleanup_leaves_no_partial_segment(media, tmp_path: Path) -> None: + fps = Fraction(60, 1) + info = media.stream_info(fps=fps, width=64, height=36) + + def factory(segment_id: int, directory: Path, stream_info: object) -> ExplodingWriter: + return ExplodingWriter(segment_id, directory, stream_info) + + recorder = SegmentRecorder(writer_factory=factory) + recorder.start(media.session(tmp_path, info)) + + segments: list[Segment] = [] + with pytest.raises(SegmentEncodingError): + # Frame 120 crosses the 2 s boundary, forcing finalize of segment 0. + for index in range(121): + segments.extend( + recorder.push_video(media.video(index=index, fps=fps, width=64, height=36)) + ) + recorder.close() + + assert segments == [] + assert not list(tmp_path.glob("*.mkv")) + assert not list(tmp_path.glob("*.tmp.mkv")) diff --git a/tests/test_ui_about.py b/tests/test_ui_about.py new file mode 100644 index 0000000..37b71e4 --- /dev/null +++ b/tests/test_ui_about.py @@ -0,0 +1,117 @@ +"""Standalone About window content, navigation and metadata tests.""" + +from collections.abc import Callable +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from typing import cast + +import flet as ft +import pytest + +from quickreplay.ui import about +from quickreplay.ui.about import ( + GITHUB_URL, + MIT_LICENSE, + THIRD_PARTY_LICENSES, + THIRD_PARTY_NOTICE, + application_version, + build_about_ui, +) + + +class StubPage: + def __init__(self) -> None: + self.updates = 0 + + def update(self) -> None: + self.updates += 1 + + +def _controls(control: ft.Control) -> list[ft.Control]: + result = [control] + if isinstance(control, (ft.Column, ft.Row)): + for child in control.controls: + result.extend(_controls(child)) + if isinstance(control, ft.Container) and control.content is not None: + result.extend(_controls(control.content)) + return result + + +def _click(button: ft.Control) -> None: + handler = getattr(button, "on_click", None) + assert handler is not None + cast(Callable[[ft.Event], object], handler)(cast(ft.Event, object())) + + +def _make_about() -> tuple[ft.Control, StubPage]: + page = StubPage() + return build_about_ui(cast(ft.Page, page)), page + + +def _text_values(control: ft.Control) -> list[str]: + return [child.value for child in _controls(control) if isinstance(child, ft.Text)] + + +def test_about_identity_and_quickreplay_license_are_available_offline() -> None: + ui, _page = _make_about() + texts = _text_values(ui) + buttons = [child for child in _controls(ui) if isinstance(child, ft.TextButton)] + + assert "QuickReplay" in texts + assert f"Version {version('quickreplay')} · © 2022 Nanahuse" in texts + assert any(button.url == GITHUB_URL for button in buttons) + assert MIT_LICENSE in texts + assert any(isinstance(child, ft.OutlinedButton) for child in _controls(ui)) + + +def test_third_party_license_list_and_notice_view_are_navigable() -> None: + ui, page = _make_about() + third_party_tab = next( + control + for control in _controls(ui) + if isinstance(control, ft.OutlinedButton) and control.content == "Third-party Licenses" + ) + _click(third_party_tab) + + texts = _text_values(ui) + assert "Third-party Licenses" in texts + for name, license_name, _url in THIRD_PARTY_LICENSES: + assert name in texts + assert license_name in texts + assert sum( + isinstance(child, ft.TextButton) and child.content == "Website" for child in _controls(ui) + ) == len(THIRD_PARTY_LICENSES) + + notices_button = next( + child + for child in _controls(ui) + if isinstance(child, ft.TextButton) and child.content == "View third-party notices" + ) + _click(notices_button) + assert THIRD_PARTY_NOTICE in _text_values(ui) + assert page.updates == 2 + + +def test_local_license_text_matches_distributed_license_files() -> None: + repository = Path(__file__).parents[1] + assert MIT_LICENSE == (repository / "LICENSE").read_text(encoding="utf-8").rstrip() + assert ( + THIRD_PARTY_NOTICE + == (repository / "LICENSE_ThirdParty.md").read_text(encoding="utf-8").rstrip() + ) + + +def test_application_version_comes_from_installed_project_metadata() -> None: + assert application_version() == version("quickreplay") + + +def test_application_version_uses_packaged_windows_version_when_metadata_is_missing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def missing_metadata(_distribution_name: str) -> str: + raise PackageNotFoundError + + monkeypatch.setattr(about, "version", missing_metadata) + monkeypatch.setattr(about, "_windows_executable_version", lambda: "2.0.0") + + assert application_version() == "2.0.0" diff --git a/tests/test_ui_about_window.py b/tests/test_ui_about_window.py new file mode 100644 index 0000000..ed49c52 --- /dev/null +++ b/tests/test_ui_about_window.py @@ -0,0 +1,97 @@ +"""Standalone About window Flet entry-point tests.""" + +import asyncio +import inspect +import os +from typing import Any, cast + +import flet as ft + +from quickreplay.ui import about_window + + +class _Window: + width: int | None = None + height: int | None = None + min_width: int | None = None + min_height: int | None = None + resizable = False + maximizable = False + visible = True + + async def wait_until_ready_to_show(self) -> None: + pass + + async def destroy(self) -> None: + pass + + +class _Page: + def __init__(self) -> None: + self.window = _Window() + self.title = "" + self.controls: list[ft.Control] = [] + self.updates = 0 + + def add(self, control: ft.Control) -> None: + self.controls.append(control) + + def update(self) -> None: + self.updates += 1 + + +def test_packaged_about_process_uses_embedded_flet_window(monkeypatch) -> None: + captured: dict[str, Any] = {} + + def fake_run(main, *, view) -> None: + captured["main"] = main + captured["view"] = view + + monkeypatch.setattr(about_window.ft, "run", fake_run) + about_window.run_about_window(embedded=True) + + main = captured["main"] + assert inspect.iscoroutinefunction(main) + assert captured["view"] is ft.AppView.FLET_APP + + page = _Page() + asyncio.run(main(cast(ft.Page, page))) + + assert page.title == "QuickReplay — About" + assert (page.window.width, page.window.height) == about_window.ABOUT_WINDOW_SIZE + assert (page.window.min_width, page.window.min_height) == about_window.ABOUT_WINDOW_MIN_SIZE + assert page.window.resizable is True + assert page.window.maximizable is True + assert page.window.visible is True + assert page.controls + + +def test_development_about_process_clears_inherited_flet_environment(monkeypatch) -> None: + captured: dict[str, Any] = {} + + def fake_run(main, *, view) -> None: + captured["main"] = main + captured["view"] = view + + monkeypatch.setattr(about_window.ft, "run", fake_run) + monkeypatch.setenv("FLET_PLATFORM", "windows") + monkeypatch.setenv("FLET_DART_BRIDGE_PORT", "12345") + monkeypatch.setenv("FLET_FORCE_WEB_SERVER", "true") + monkeypatch.setenv("FLET_DISPLAY_URL_PREFIX", "http://parent.invalid") + monkeypatch.setenv("QUICKREPLAY_TEST_VALUE", "preserved") + + about_window.run_about_window(embedded=False) + + assert not any(name.startswith("FLET_") for name in os.environ) + assert os.environ["QUICKREPLAY_TEST_VALUE"] == "preserved" + + +def test_packaged_about_process_preserves_its_native_bridge(monkeypatch) -> None: + monkeypatch.setenv("FLET_PLATFORM", "windows") + monkeypatch.setenv("FLET_DART_BRIDGE_PORT", "12345") + + monkeypatch.setattr(about_window.ft, "run", lambda *_args, **_kwargs: None) + about_window.run_about_window(embedded=True) + + assert os.environ["FLET_PLATFORM"] == "windows" + assert os.environ["FLET_DART_BRIDGE_PORT"] == "12345" diff --git a/tests/test_ui_bootstrap.py b/tests/test_ui_bootstrap.py new file mode 100644 index 0000000..822e58e --- /dev/null +++ b/tests/test_ui_bootstrap.py @@ -0,0 +1,145 @@ +"""Desktop bootstrap: configuration, settings and application wiring.""" + +import tomllib +from pathlib import Path +from typing import Any, cast + +import flet as ft +import pytest + +from quickreplay.application.controller import ApplicationController +from quickreplay.configuration.errors import ConfigurationParseError +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.input.models import NdiInputConfig +from quickreplay.ui.app import _configure_window, _show_startup_error, run +from quickreplay.ui.bootstrap import bootstrap_application +from quickreplay.ui.bridge import ApplicationUiBridge +from quickreplay.ui.main_view import WINDOW_SIZES +from quickreplay.ui.paths import resolve_storage_paths + + +def _paths(tmp_path: Path): + return resolve_storage_paths( + data_directory=tmp_path / "data", cache_directory=tmp_path / "cache" + ) + + +def test_bootstrap_builds_defaults(tmp_path: Path) -> None: + paths = _paths(tmp_path) + + boot = bootstrap_application(paths=paths) + + assert boot.store.path == paths.config_path + assert boot.config == QuickReplayConfig() + assert isinstance(boot.controller, ApplicationController) + assert isinstance(boot.bridge, ApplicationUiBridge) + assert not paths.config_path.exists() # first run does not create the file + + +def test_bootstrap_loads_existing_config(tmp_path: Path) -> None: + paths = _paths(tmp_path) + paths.data_directory.mkdir(parents=True) + ConfigurationStore(paths.config_path).save(QuickReplayConfig(input=NdiInputConfig("OBS"))) + + boot = bootstrap_application(paths=paths) + + assert boot.config.input == NdiInputConfig("OBS") + + +def test_bootstrap_broken_config_raises(tmp_path: Path) -> None: + paths = _paths(tmp_path) + paths.data_directory.mkdir(parents=True) + paths.config_path.write_text('{"schema_version": 1,', encoding="utf-8") + + with pytest.raises(ConfigurationParseError): + bootstrap_application(paths=paths) + + +def test_bootstrap_runtime_directory(tmp_path: Path) -> None: + paths = _paths(tmp_path) + captured: list[Any] = [] + + def controller_factory(settings: Any) -> Any: + captured.append(settings) + return object() + + bootstrap_application(paths=paths, controller_factory=controller_factory) + + assert len(captured) == 1 + settings = captured[0] + assert settings.worker is not None + assert settings.worker.working_directory == paths.runtime_directory + + +def test_initial_window_uses_setup_size_and_disables_resize() -> None: + class Window: + width = 0 + height = 0 + visible = True + resizable = True + maximizable = True + + class Page: + title = "" + window = Window() + + page = Page() + + _configure_window(cast(ft.Page, page)) + + assert page.title == "QuickReplay" + assert (page.window.width, page.window.height) == WINDOW_SIZES["setup"] + assert page.window.visible is False + assert page.window.resizable is False + assert page.window.maximizable is False + + +def test_startup_error_shows_window_at_configured_size() -> None: + class Window: + width = WINDOW_SIZES["setup"][0] + height = WINDOW_SIZES["setup"][1] + visible = False + + class Page: + window = Window() + controls: list[ft.Control] = [] + updates = 0 + + def add(self, control: ft.Control) -> None: + self.controls.append(control) + + def update(self) -> None: + self.updates += 1 + + page = Page() + + _show_startup_error(cast(ft.Page, page), "startup failed") + + assert page.window.visible is True + assert len(page.controls) == 1 + assert page.updates == 1 + + +def test_run_starts_desktop_view_hidden(monkeypatch: pytest.MonkeyPatch) -> None: + captured: dict[str, object] = {} + + def fake_run(main, **kwargs) -> None: + captured["main"] = main + captured.update(kwargs) + + monkeypatch.setattr(ft, "run", fake_run) + + run() + + assert captured["main"] is not None + assert captured["view"] is ft.AppView.FLET_APP_HIDDEN + + +def test_built_windows_runner_hides_its_initial_native_window() -> None: + project_file = Path(__file__).parents[1] / "pyproject.toml" + + with project_file.open("rb") as config_file: + config = tomllib.load(config_file) + + assert config["tool"]["flet"]["app"]["hide_window_on_start"] is True diff --git a/tests/test_ui_bridge.py b/tests/test_ui_bridge.py new file mode 100644 index 0000000..e4515c0 --- /dev/null +++ b/tests/test_ui_bridge.py @@ -0,0 +1,120 @@ +"""ApplicationUiBridge: serialization, exception propagation and cleanup.""" + +import asyncio + +import pytest +from fake_ui import FakeController + +from quickreplay.input.models import NdiInputConfig +from quickreplay.replay.models import SetPoint +from quickreplay.ui.bridge import ApplicationUiBridge + + +def test_calls_are_serialized_on_one_thread() -> None: + controller = FakeController() + bridge = ApplicationUiBridge(controller) + + async def run() -> None: + await asyncio.gather( + bridge.start(), + bridge.poll(), + bridge.discover_inputs(), + bridge.request_replay(), + bridge.resume_recording(), + bridge.snapshot(), + bridge.shutdown(), + ) + await bridge.close() + + asyncio.run(run()) + + assert len(set(controller.threads)) == 1 + assert controller.max_active == 1 + assert set(controller.calls) == { + "start", + "poll", + "discover_inputs", + "request_replay", + "resume_recording", + "snapshot", + "shutdown", + } + + +def test_exception_propagates_and_executor_survives() -> None: + controller = FakeController(fail_on="start_recording") + bridge = ApplicationUiBridge(controller) + + async def run() -> None: + with pytest.raises(RuntimeError): + await bridge.start_recording(NdiInputConfig("x")) + # The executor thread is still usable afterwards. + await bridge.poll() + await bridge.close() + + asyncio.run(run()) + + assert "poll" in controller.calls + + +def test_close_is_idempotent() -> None: + controller = FakeController() + bridge = ApplicationUiBridge(controller) + + async def run() -> None: + await bridge.close() + await bridge.close() + + asyncio.run(run()) + + +def test_start_recording_forwards_config() -> None: + controller = FakeController() + bridge = ApplicationUiBridge(controller) + + async def run() -> None: + await bridge.start_recording(NdiInputConfig("OBS")) + await bridge.close() + + asyncio.run(run()) + + assert controller.calls == ["start_recording"] + + +def test_replay_calls_are_delegated_and_serialized() -> None: + controller = FakeController() + bridge = ApplicationUiBridge(controller) + + async def run() -> None: + await asyncio.gather( + bridge.play(), + bridge.pause(), + bridge.is_paused(), + bridge.step_forward(), + bridge.step_backward(), + bridge.seek_frames(20), + bridge.seek_absolute_ns(1_250_000_000), + bridge.replay_position_ns(), + bridge.set_point(), + bridge.time_difference_ns(SetPoint(0)), + bridge.frame_difference(SetPoint(0)), + ) + await bridge.close() + + asyncio.run(run()) + + assert len(set(controller.threads)) == 1 + assert controller.max_active == 1 + assert set(controller.calls) == { + "play", + "pause", + "is_paused", + "step_forward", + "step_backward", + "seek_frames", + "seek_absolute_ns", + "replay_position_ns", + "set_point", + "time_difference_ns", + "frame_difference", + } diff --git a/tests/test_ui_discovery.py b/tests/test_ui_discovery.py new file mode 100644 index 0000000..667489b --- /dev/null +++ b/tests/test_ui_discovery.py @@ -0,0 +1,49 @@ +"""NDI discovery command forwarding and worker execution.""" + +from pathlib import Path +from uuid import uuid4 + +from fake_application import FakeReplayFactory, FakeWorker +from fake_worker_input import ScriptedInputFactory, WorkerHarness + +from quickreplay.application.controller import ApplicationController +from quickreplay.application.models import ApplicationControllerSettings +from quickreplay.recording.commands import DiscoverInputs +from quickreplay.recording.events import InputsDiscovered +from quickreplay.recording.models import WorkerState +from quickreplay.worker.settings import RecorderWorkerSettings + + +def test_application_controller_sends_discovery_request() -> None: + worker = FakeWorker() + app = ApplicationController( + ApplicationControllerSettings(), + worker_factory=lambda: worker, + replay_controller_factory=FakeReplayFactory(), + ) + app.start() + app.poll() + request_id = app.discover_inputs() + + command = worker.commands_of(DiscoverInputs)[0] + assert command.request_id == request_id + + +def test_worker_discovery_callback_has_no_arguments(tmp_path: Path) -> None: + calls: list[bool] = [] + + def discovery() -> tuple: + calls.append(True) + return () + + settings = RecorderWorkerSettings(working_directory=tmp_path, metrics_interval_ns=20_000_000) + harness = WorkerHarness(settings, input_factory=ScriptedInputFactory(), discovery=discovery) + try: + harness.start() + harness.wait_state(WorkerState.IDLE) + request_id = uuid4() + harness.send(DiscoverInputs(request_id)) + harness.wait_event(InputsDiscovered, predicate=lambda event: event.request_id == request_id) + assert calls == [True] + finally: + harness.shutdown() diff --git a/tests/test_ui_lifecycle.py b/tests/test_ui_lifecycle.py new file mode 100644 index 0000000..8716131 --- /dev/null +++ b/tests/test_ui_lifecycle.py @@ -0,0 +1,613 @@ +"""MainView lifecycle: poll ownership, close idempotency and race guards. + +Everything runs headlessly with a stub page and fake bridge, so no native Flet +window is created. +""" + +import asyncio +import subprocess +import threading +from pathlib import Path +from typing import Any, cast + +import flet as ft +import pytest +from fake_ui import FakeBridge + +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.ui.main_view import MainView, ViewLifecycle +from quickreplay.ui.session import UiSession + +DESTROYED_SESSION = "An attempt to fetch destroyed session." + + +class _Event: + """A stand-in for a Flet event object.""" + + +class _CloseEvent: + type = ft.WindowEventType.CLOSE + + +def _event() -> ft.Event: + return cast(ft.Event, _Event()) + + +def _close_event() -> ft.WindowEvent: + return cast(ft.WindowEvent, _CloseEvent()) + + +class LifecyclePage: + """The slice of :class:`flet.Page` used by MainView, with failure injection.""" + + def __init__( + self, + *, + update_error: BaseException | None = None, + run_task_error: BaseException | None = None, + ) -> None: + self.updates = 0 + self.dialogs: list[object] = [] + self.destroyed = 0 + self.update_error = update_error + self.run_task_error = run_task_error + self.tasks: list[asyncio.Task[object]] = [] + self.window = self + + def update(self) -> None: + if self.update_error is not None: + raise self.update_error + self.updates += 1 + + def show_dialog(self, dialog: object) -> None: + self.dialogs.append(dialog) + + def pop_dialog(self) -> object | None: + return self.dialogs.pop() if self.dialogs else None + + def run_task(self, handler, *args, **kwargs): + if self.run_task_error is not None: + raise self.run_task_error + task = asyncio.ensure_future(handler(*args, **kwargs)) + self.tasks.append(task) + return task + + async def destroy(self) -> None: + self.destroyed += 1 + + +class CountingBridge(FakeBridge): + """FakeBridge that counts shutdown/close calls and records their order.""" + + def __init__(self) -> None: + super().__init__() + self.shutdown_count = 0 + self.close_count = 0 + self.order: list[str] = [] + + async def shutdown(self) -> None: + self.shutdown_count += 1 + self.order.append("shutdown") + await super().shutdown() + + async def close(self) -> None: + self.close_count += 1 + self.order.append("close") + await super().close() + + +class BlockingBridge(CountingBridge): + """Bridge whose operations can be blocked deterministically.""" + + def __init__(self) -> None: + super().__init__() + self.poll_entered = asyncio.Event() + self.poll_release = asyncio.Event() + self.start_entered = asyncio.Event() + self.start_release = asyncio.Event() + self.discover_entered = asyncio.Event() + self.discover_release = asyncio.Event() + self.step_entered = asyncio.Event() + self.step_release = asyncio.Event() + + async def poll(self, timeout: float = 0.0): + self.poll_entered.set() + await self.poll_release.wait() + return () + + async def start(self) -> None: + self.start_entered.set() + await self.start_release.wait() + self.started = True + + async def discover_inputs(self): + self.discover_entered.set() + await self.discover_release.wait() + return await super().discover_inputs() + + async def step_forward(self) -> None: + self.step_entered.set() + await self.step_release.wait() + await super().step_forward() + + +class BlockingStore(ConfigurationStore): + """Store whose save can be blocked from the test thread.""" + + def __init__(self, path: Path) -> None: + super().__init__(path) + self.entered = threading.Event() + self.release = threading.Event() + + def save(self, config: QuickReplayConfig) -> None: + self.entered.set() + self.release.wait(timeout=10) + super().save(config) + + +async def _wait_for(predicate, *, attempts: int = 200) -> None: + """Yield to the event loop until *predicate* holds (bounded).""" + for _ in range(attempts): + if predicate(): + return + await asyncio.sleep(0) + raise AssertionError("condition was not met") + + +def _make( + tmp_path: Path, + *, + bridge: FakeBridge | None = None, + page: LifecyclePage | None = None, + store: ConfigurationStore | None = None, +) -> tuple[MainView, UiSession, CountingBridge, LifecyclePage]: + active_bridge = bridge or CountingBridge() + active_store = store or ConfigurationStore(tmp_path / "config.json") + session = UiSession(active_bridge, active_store, QuickReplayConfig()) + active_page = page or LifecyclePage() + view = MainView(cast(ft.Page, active_page), session) + assert isinstance(active_bridge, CountingBridge) + return view, session, active_bridge, active_page + + +# -- poll task ownership --------------------------------------------------- + + +def test_start_polling_stores_task_and_close_cancels_it(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, bridge, page = _make(tmp_path) + await view.start() + view.start_polling() + await asyncio.sleep(0) + + assert view._poll_task is not None + assert not view._poll_task.done() + + await view.close() + + assert view.lifecycle is ViewLifecycle.CLOSED + assert view._poll_task is None + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + assert page.destroyed == 1 + + asyncio.run(scenario()) + + +def test_poll_cancellation_is_not_reported_as_an_error(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = BlockingBridge() + view, session, _bridge, page = _make(tmp_path, bridge=bridge) + view.start_polling() + await bridge.poll_entered.wait() + updates_before = page.updates + + await view.close() + + assert view.lifecycle is ViewLifecycle.CLOSED + assert page.updates == updates_before + assert session.view_state().error_message is None + + asyncio.run(scenario()) + + +def test_poll_loop_stops_on_close_without_further_updates(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, _bridge, page = _make(tmp_path) + view.start_polling() + await asyncio.sleep(0) + await view.close() + updates_after_close = page.updates + + await asyncio.sleep(0.05) + + assert page.updates == updates_after_close + assert view._poll_task is None + + asyncio.run(scenario()) + + +# -- destroyed session ----------------------------------------------------- + + +def test_destroyed_session_runs_core_cleanup(tmp_path: Path) -> None: + async def scenario() -> None: + page = LifecyclePage(update_error=RuntimeError(DESTROYED_SESSION)) + view, session, bridge, _page = _make(tmp_path, page=page) + view.start_polling() + await _wait_for(lambda: view.lifecycle is ViewLifecycle.CLOSED) + + assert view._session_lost + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + assert page.destroyed == 0 + assert session.view_state().error_message is None + + asyncio.run(scenario()) + + +def test_destroyed_session_is_not_an_application_error(tmp_path: Path) -> None: + async def scenario() -> None: + page = LifecyclePage(update_error=RuntimeError(DESTROYED_SESSION)) + view, session, _bridge, _page = _make(tmp_path, page=page) + + assert view._update_page() is False + + assert view._session_lost + assert session.view_state().error_message is None + + asyncio.run(scenario()) + + +def test_unrelated_runtime_error_is_not_swallowed(tmp_path: Path) -> None: + async def scenario() -> None: + page = LifecyclePage(update_error=RuntimeError("render failed")) + view, _session, _bridge, _page = _make(tmp_path, page=page) + + with pytest.raises(RuntimeError, match="render failed"): + view._update_page() + + assert not view._session_lost + assert view.lifecycle is ViewLifecycle.RUNNING + + asyncio.run(scenario()) + + +def test_unrelated_runtime_error_propagates_from_action_refresh(tmp_path: Path) -> None: + async def scenario() -> None: + page = LifecyclePage(update_error=RuntimeError("render failed")) + view, _session, _bridge, _page = _make(tmp_path, page=page) + + with pytest.raises(RuntimeError, match="render failed"): + await view._render_and_update() + + asyncio.run(scenario()) + + +# -- close idempotency ----------------------------------------------------- + + +def test_double_close_runs_shutdown_once(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, bridge, page = _make(tmp_path) + + await view.close() + await view.close() + + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + assert page.destroyed == 1 + + asyncio.run(scenario()) + + +def test_main_close_waits_for_about_process_after_core_shutdown(tmp_path: Path) -> None: + class FakeProcess: + def __init__(self, order: list[str]) -> None: + self.order = order + self.returncode: int | None = None + self.wait_timeouts: list[float] = [] + + def poll(self) -> int | None: + return self.returncode + + def wait(self, timeout: float) -> int: + self.wait_timeouts.append(timeout) + self.order.append("about_wait") + self.returncode = 0 + return self.returncode + + def terminate(self) -> None: + self.order.append("about_terminate") + self.returncode = 0 + + def kill(self) -> None: + self.order.append("about_kill") + self.returncode = -9 + + async def scenario() -> None: + view, _session, bridge, _page = _make(tmp_path) + process = FakeProcess(bridge.order) + view._about_process = cast(Any, process) + await view.close() + + assert bridge.order.index("shutdown") < bridge.order.index("about_wait") + assert process.wait_timeouts == [2.0] + assert "about_terminate" not in bridge.order + assert "about_kill" not in bridge.order + assert view._about_process is None + + asyncio.run(scenario()) + + +def test_about_process_shutdown_terminates_process_when_graceful_wait_times_out( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + class FakeProcess: + def __init__(self) -> None: + self.returncode: int | None = None + self.wait_timeouts: list[float] = [] + self.terminated = False + self.killed = False + + def poll(self) -> int | None: + return self.returncode + + def wait(self, timeout: float) -> int: + self.wait_timeouts.append(timeout) + if not self.terminated: + raise subprocess.TimeoutExpired("about", timeout) + self.returncode = 0 + return 0 + + def terminate(self) -> None: + self.terminated = True + + def kill(self) -> None: + self.killed = True + self.returncode = -9 + + async def scenario() -> None: + view, _session, _bridge, _page = _make(tmp_path) + process = FakeProcess() + view._about_process = cast(Any, process) + await view.close() + assert process.terminated + assert not process.killed + assert process.wait_timeouts == [2.0, 1.0] + + async def fake_to_thread(func, *args, **kwargs): + return func(*args, **kwargs) + + monkeypatch.setattr(asyncio, "to_thread", fake_to_thread) + asyncio.run(scenario()) + + +def test_concurrent_close_runs_shutdown_once(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, bridge, page = _make(tmp_path) + + await asyncio.gather(view.close(), view.close()) + + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + assert page.destroyed == 1 + + asyncio.run(scenario()) + + +def test_window_close_and_disconnect_run_shutdown_once(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, bridge, _page = _make(tmp_path) + + view.on_window_event(_close_event()) + view.on_page_disconnect() + await _wait_for(lambda: view.lifecycle is ViewLifecycle.CLOSED) + + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + + asyncio.run(scenario()) + + +def test_run_task_failure_during_close_falls_back_to_cleanup(tmp_path: Path) -> None: + async def scenario() -> None: + page = LifecyclePage(run_task_error=RuntimeError(DESTROYED_SESSION)) + view, _session, bridge, _page = _make(tmp_path, page=page) + + view.on_window_event(_close_event()) + await _wait_for(lambda: view.lifecycle is ViewLifecycle.CLOSED) + + assert bridge.shutdown_count == 1 + assert page.destroyed == 0 + + asyncio.run(scenario()) + + +# -- action guards --------------------------------------------------------- + + +def test_actions_after_close_do_not_call_core(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, bridge, page = _make(tmp_path) + await view.close() + updates_after_close = page.updates + + view._on_start(_event()) + view._on_refresh(_event()) + view._on_mode_button(_event()) + view._run_replay_action("step_forward") + view._on_settings_apply(_event()) + view._on_source_select(_event()) + view._on_seek_start(_event()) + view._on_seek_change(_event()) + view._on_seek_end(_event()) + await asyncio.sleep(0) + + assert bridge.recording_configs == [] + assert bridge.discovery_requests == [] + assert bridge.replay_requests == 0 + assert bridge.resume_requests == 0 + assert bridge.step_forward_calls == 0 + assert bridge.seek_absolute_calls == [] + assert page.updates == updates_after_close + + asyncio.run(scenario()) + + +def test_action_completion_after_close_does_not_update_page(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = BlockingBridge() + view, _session, _bridge, page = _make(tmp_path, bridge=bridge) + + task = asyncio.ensure_future(view._refresh()) + await bridge.discover_entered.wait() + updates_before = page.updates + + await view.close() + bridge.discover_release.set() + await task + + assert page.updates == updates_before + assert view.lifecycle is ViewLifecycle.CLOSED + + asyncio.run(scenario()) + + +def test_replay_action_completion_after_close_does_not_update_page(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = BlockingBridge() + view, _session, _bridge, page = _make(tmp_path, bridge=bridge) + + task = asyncio.ensure_future(view._do_replay_action("step_forward", None)) + await bridge.step_entered.wait() + updates_before = page.updates + + await view.close() + bridge.step_release.set() + await task + + assert page.updates == updates_before + assert view.lifecycle is ViewLifecycle.CLOSED + + asyncio.run(scenario()) + + +def test_settings_apply_race_does_not_touch_the_page(tmp_path: Path) -> None: + async def scenario() -> None: + store = BlockingStore(tmp_path / "config.json") + view, _session, _bridge, page = _make(tmp_path, store=store) + task = asyncio.ensure_future(view._apply_settings()) + await asyncio.to_thread(store.entered.wait) + updates_before = page.updates + + await view.close() + store.release.set() + await task + + assert page.updates == updates_before + assert view.settings_error_text.value == "" + + asyncio.run(scenario()) + + +def test_seek_drag_close_does_not_send_seek(tmp_path: Path) -> None: + async def scenario() -> None: + view, _session, bridge, _page = _make(tmp_path) + view._on_seek_start(_event()) + assert view._seek_drag.active + + await view.close() + view._on_seek_end(_event()) + await asyncio.sleep(0) + + assert bridge.seek_absolute_calls == [] + + asyncio.run(scenario()) + + +# -- startup --------------------------------------------------------------- + + +def test_close_during_start_does_not_start_polling(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = BlockingBridge() + bridge.discover_release.set() + view, _session, _bridge, page = _make(tmp_path, bridge=bridge) + + task = asyncio.ensure_future(view.start()) + await bridge.start_entered.wait() + + view.on_window_event(_close_event()) + await asyncio.sleep(0) + bridge.start_release.set() + await task + await _wait_for(lambda: view.lifecycle is ViewLifecycle.CLOSED) + + assert not view.is_active + + view.start_polling() + assert view._poll_task is None + + assert bridge.shutdown_count == 1 + assert page.destroyed == 1 + + asyncio.run(scenario()) + + +def test_start_failure_cleans_up_core(tmp_path: Path) -> None: + class FailingStartBridge(CountingBridge): + async def start(self) -> None: + raise RuntimeError("worker spawn failed") + + async def scenario() -> None: + bridge = FailingStartBridge() + view, _session, _bridge, page = _make(tmp_path, bridge=bridge) + + with pytest.raises(RuntimeError, match="worker spawn failed"): + await view.start() + + assert view.lifecycle is ViewLifecycle.CLOSED + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + assert page.destroyed == 0 + + asyncio.run(scenario()) + + +# -- state-specific close -------------------------------------------------- + + +# -- UiSession shutdown idempotency --------------------------------------- + + +def test_session_shutdown_is_idempotent(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = CountingBridge() + session = UiSession( + bridge, ConfigurationStore(tmp_path / "config.json"), QuickReplayConfig() + ) + + await session.shutdown() + await session.shutdown() + + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + + asyncio.run(scenario()) + + +def test_session_shutdown_is_concurrency_safe(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = CountingBridge() + session = UiSession( + bridge, ConfigurationStore(tmp_path / "config.json"), QuickReplayConfig() + ) + + await asyncio.gather(session.shutdown(), session.shutdown()) + + assert bridge.shutdown_count == 1 + assert bridge.close_count == 1 + + asyncio.run(scenario()) diff --git a/tests/test_ui_main_view.py b/tests/test_ui_main_view.py new file mode 100644 index 0000000..1d9a64a --- /dev/null +++ b/tests/test_ui_main_view.py @@ -0,0 +1,396 @@ +"""Headless Flet view wiring for the settings dialog. + +Flet controls are constructed but never attached to a native window, so this +runs in CI without a display. Widget behaviour is exercised through the view's +own handlers with a stub page. +""" + +import asyncio +import subprocess +import sys +from dataclasses import replace +from fractions import Fraction +from pathlib import Path +from typing import cast + +import flet as ft +import pytest +from fake_ui import FakeBridge + +from quickreplay.app.state import ApplicationState +from quickreplay.application.events import InputsChanged +from quickreplay.application.models import ApplicationSnapshot +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.input.models import NdiInputDescriptor +from quickreplay.replay.models import ReplayAsset +from quickreplay.ui.main_view import ( + REPLAY_CONTENT_WIDTH, + REPLAY_TRANSPORT_BUTTON_HEIGHT, + REPLAY_TRANSPORT_BUTTON_WIDTH, + REPLAY_TRANSPORT_SPACING, + WINDOW_SIZES, + MainView, +) +from quickreplay.ui.presentation import MetricsView +from quickreplay.ui.session import UiSession + + +class _StubPage: + """The small slice of :class:`flet.Page` the view uses.""" + + def __init__(self) -> None: + self.updates = 0 + self.shown: list[object] = [] + self.popped = 0 + + def update(self) -> None: + self.updates += 1 + + def show_dialog(self, dialog: object) -> None: + self.shown.append(dialog) + + def pop_dialog(self) -> object | None: + self.popped += 1 + return self.shown.pop() if self.shown else None + + def run_task(self, handler: object, *args: object) -> None: + raise AssertionError("run_task is not used by the headless view tests") + + +def _session( + tmp_path: Path, config: QuickReplayConfig | None = None +) -> tuple[UiSession, FakeBridge]: + bridge = FakeBridge() + store = ConfigurationStore(tmp_path / "config.json") + session = UiSession(bridge, store, config or QuickReplayConfig()) + asyncio.run(session.start()) + return session, bridge + + +async def _discover(session: UiSession, bridge: FakeBridge, inputs: tuple) -> None: + bridge.events = [InputsChanged(request_id=bridge.next_discovery_id, inputs=inputs)] + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.IDLE) + await session.poll() + + +def _view(session: UiSession) -> tuple[MainView, _StubPage]: + page = _StubPage() + return MainView(cast(ft.Page, page), session), page + + +def test_setup_is_ndi_only_and_compact(tmp_path: Path) -> None: + session, _ = _session(tmp_path) + view, _page = _view(session) + view._populate_settings_fields() + + assert view.source_dropdown.label == "NDI source" + assert not hasattr(view, "kind_button") + assert not hasattr(view, "backend_dropdown") + assert WINDOW_SIZES["setup"] == (640, 320) + assert view.input_section in view.setup_body.controls + assert view.settings_row in view.setup_body.controls + assert view.setup_actions in view.setup_section.controls + assert view.setup_actions not in view.setup_body.controls + assert len(view.setup_actions.controls) == 2 + assert view.setup_actions.spacing == view.settings_row.spacing + assert view.setup_actions.alignment != ft.MainAxisAlignment.SPACE_BETWEEN + assert view.setup_body.expand is True + assert view.setup_section.expand is True + assert view.control.expand is True + + recording, replay = (cast(ft.Column, control) for control in view.settings_row.controls) + left_actions = cast(ft.Container, view.setup_actions.controls[0]) + right_actions = cast(ft.Row, view.setup_actions.controls[1]) + assert left_actions.expand is True + assert right_actions.expand is True + left_action_row = cast(ft.Row, left_actions.content) + assert left_action_row.controls == [view.about_button] + assert left_action_row.alignment == ft.MainAxisAlignment.START + assert right_actions.expand is True + assert right_actions.controls == [view.settings_apply_button, view.start_button] + assert right_actions.alignment == ft.MainAxisAlignment.END + assert replay.horizontal_alignment == ft.CrossAxisAlignment.STRETCH + assert view.settings_mpv_field.expand is not True + assert cast(ft.Text, recording.controls[0]).value == "Recording" + assert cast(ft.Text, replay.controls[0]).value == "Replay" + assert view.about_button.icon == ft.Icons.INFO_OUTLINE + assert view.about_button.tooltip == "About" + assert ( + sum( + child.value.startswith("Restart required") + for child in view.setup_body.controls + if isinstance(child, ft.Text) + ) + == 1 + ) + + +def test_apply_success_closes_dialog_and_shows_status(tmp_path: Path) -> None: + session, bridge = _session(tmp_path) + asyncio.run(_discover(session, bridge, ())) + view, page = _view(session) + + asyncio.run(view._apply_settings()) + + assert view.status_text.value == "Settings saved." + + +def test_apply_validation_failure_keeps_dialog_open(tmp_path: Path) -> None: + session, _ = _session(tmp_path) + view, page = _view(session) + before = session.config + view._populate_settings_fields() + view.settings_buffer_field.value = "0" + + asyncio.run(view._apply_settings()) + + assert session.config == before + assert "Buffer duration" in view.settings_error_text.value + # The edited draft stays visible for the user to correct. + assert view.settings_buffer_field.value == "0" + + +def test_settings_button_disabled_while_shutting_down(tmp_path: Path) -> None: + session, bridge = _session(tmp_path) + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.SHUTTING_DOWN) + asyncio.run(session.poll()) + view, _page = _view(session) + + view.render(session.view_state()) + + assert view.session_section.visible is True + + +def test_replay_controls_are_visible_and_prioritized(tmp_path: Path) -> None: + session, bridge = _session(tmp_path) + view, _page = _view(session) + + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.REPLAY, + replay_asset=ReplayAsset(Path("replay.mkv"), 10_000_000_000, Fraction(60, 1)), + ) + asyncio.run(session.poll()) + view.render(session.view_state()) + + assert view.input_section.visible is False + assert view.recording_section.visible is False + assert view.replay_panel.visible is True + assert cast(ft.Text, view.replay_back20_button.content).value == "-20f" + assert cast(ft.Text, view.replay_back1_button.content).value == "-1f" + assert cast(ft.Text, view.replay_play_button.content).value == "Play" + assert cast(ft.Text, view.replay_forward1_button.content).value == "+1f" + assert cast(ft.Text, view.replay_forward20_button.content).value == "+20f" + assert view.set_point_button.content == "Set Point" + assert view.mode_button.content == "Record" + assert isinstance(view.setup_button, ft.IconButton) + assert view.setup_button.icon == ft.Icons.ARROW_BACK + assert view.setup_button.tooltip == "Setup" + assert view.control.scroll is None + assert view.setup_body.scroll == ft.ScrollMode.AUTO + assert view.setup_actions in view.setup_section.controls + assert view.setup_actions not in view.setup_body.controls + header = cast(ft.Row, view.session_section.controls[0]) + button_group = cast(ft.Row, header.controls[0]) + assert view.mode_button in button_group.controls + assert view.setup_button in button_group.controls + assert header.vertical_alignment == ft.CrossAxisAlignment.CENTER + assert WINDOW_SIZES["recording"][0] == WINDOW_SIZES["replay"][0] + + +@pytest.mark.parametrize("state", [ApplicationState.RECORDING, ApplicationState.REPLAY]) +def test_about_entry_is_not_in_session_screens(tmp_path: Path, state: ApplicationState) -> None: + session, bridge = _session(tmp_path) + bridge.snapshot_value = ApplicationSnapshot( + state=state, + replay_asset=( + ReplayAsset(Path("replay.mkv"), 10_000_000_000, Fraction(60, 1)) + if state is ApplicationState.REPLAY + else None + ), + ) + asyncio.run(session.poll()) + view, _page = _view(session) + + view.render(session.view_state()) + + assert view.setup_section.visible is False + assert isinstance(view.setup_button, ft.IconButton) + assert view.about_button not in view.session_section.controls + if state is ApplicationState.RECORDING: + assert view.mode_button.content == "Replay" + assert view.state_text.value == "● REC" + + +def test_resuming_uses_recording_size_before_recording_starts(tmp_path: Path) -> None: + session, _bridge = _session(tmp_path) + view, page = _view(session) + window = type("Window", (), {"width": 0, "height": 0})() + page.__dict__["window"] = window + + view._update_window_size(ApplicationState.RECORDING) + assert (window.width, window.height) == WINDOW_SIZES["recording"] + view._update_window_size(ApplicationState.PREPARING_REPLAY) + assert (window.width, window.height) == WINDOW_SIZES["recording"] + + view._update_window_size(ApplicationState.REPLAY) + assert (window.width, window.height) == WINDOW_SIZES["replay"] + view._update_window_size(ApplicationState.RESUMING) + assert (window.width, window.height) == WINDOW_SIZES["recording"] + + +def test_discovery_status_is_limited_to_input_row(tmp_path: Path) -> None: + session, _bridge = _session(tmp_path) + view, _page = _view(session) + + view.render(replace(session.view_state(), discovering=True, status_message="Discovering...")) + + assert view.refresh_button.content == "Discovering..." + assert view.refresh_button.disabled is True + assert view.footer.visible is False + assert view.status_text.visible is False + + +def test_about_process_starts_once_and_restarts_after_exit( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + session, bridge = _session(tmp_path) + inputs = (NdiInputDescriptor("Studio NDI"),) + asyncio.run(_discover(session, bridge, inputs)) + session.select("ndi:Studio NDI") + view, _page = _view(session) + view.settings_buffer_field.value = "45" + view.settings_mpv_field.value = "custom-mpv.exe" + draft_before = view._settings_draft() + state_before = session.view_state() + selected_before = state_before.selected_key + bridge_calls_before = ( + len(bridge.discovery_requests), + len(bridge.recording_configs), + bridge.replay_requests, + ) + + class FakeProcess: + def __init__(self, command: list[str]) -> None: + self.command = command + self.returncode: int | None = None + + def poll(self) -> int | None: + return self.returncode + + processes: list[FakeProcess] = [] + + def fake_popen(command: list[str]) -> FakeProcess: + process = FakeProcess(command) + processes.append(process) + return process + + monkeypatch.setattr(subprocess, "Popen", fake_popen) + monkeypatch.setattr(sys, "argv", ["QuickReplay.exe"]) + view._on_about(cast(ft.Event, object())) + + process = processes[0] + assert process.command == [sys.executable, "--quickreplay-about"] + view._on_about(cast(ft.Event, object())) + + process.returncode = 0 + first_process = process + view._on_about(cast(ft.Event, object())) + assert view._about_process is not first_process + assert view._about_process is not None + assert processes[1].command == [sys.executable, "--quickreplay-about"] + assert view._settings_draft() == draft_before + assert session.view_state().state is state_before.state + assert session.view_state().selected_key == selected_before + assert ( + len(bridge.discovery_requests), + len(bridge.recording_configs), + bridge.replay_requests, + ) == bridge_calls_before + + +def test_about_is_disabled_outside_idle_setup_state(tmp_path: Path) -> None: + session, bridge = _session(tmp_path) + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.RECORDING) + asyncio.run(session.poll()) + view, _page = _view(session) + + view.render(session.view_state()) + view._on_about(cast(ft.Event, object())) + + assert view.about_button.disabled is True + + +def test_replay_transport_buttons_share_fixed_dimensions_and_style(tmp_path: Path) -> None: + session, _bridge = _session(tmp_path) + view, _page = _view(session) + transport_buttons = ( + view.replay_back20_button, + view.replay_back1_button, + view.replay_play_button, + view.replay_forward1_button, + view.replay_forward20_button, + ) + + assert {button.width for button in transport_buttons} == {REPLAY_TRANSPORT_BUTTON_WIDTH} + assert {button.height for button in transport_buttons} == {REPLAY_TRANSPORT_BUTTON_HEIGHT} + assert all( + button.border_radius == transport_buttons[0].border_radius for button in transport_buttons + ) + assert all(button.padding == transport_buttons[0].padding for button in transport_buttons) + assert view.replay_panel.width == REPLAY_CONTENT_WIDTH + assert cast(ft.Row, view.replay_panel.controls[2]).spacing == REPLAY_TRANSPORT_SPACING + assert REPLAY_CONTENT_WIDTH == ( + len(transport_buttons) * REPLAY_TRANSPORT_BUTTON_WIDTH + + (len(transport_buttons) - 1) * REPLAY_TRANSPORT_SPACING + ) + assert WINDOW_SIZES["recording"][0] == REPLAY_CONTENT_WIDTH + 40 + + play_label = cast(ft.Text, view.replay_play_button.content) + play_label.value = "Pause" + assert view.replay_play_button.width == REPLAY_TRANSPORT_BUTTON_WIDTH + assert view.replay_play_button.height == REPLAY_TRANSPORT_BUTTON_HEIGHT + + +def test_record_button_enters_compact_pending_layout(tmp_path: Path) -> None: + session, bridge = _session(tmp_path) + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.REPLAY, + replay_asset=ReplayAsset(Path("replay.mkv"), 10_000_000_000, Fraction(60, 1)), + ) + asyncio.run(session.poll()) + view, page = _view(session) + window = type("Window", (), {"width": 0, "height": 0})() + page.__dict__["window"] = window + view.render(session.view_state()) + + asyncio.run(view._switch_session_mode()) + + assert bridge.resume_requests == 1 + assert (window.width, window.height) == WINDOW_SIZES["recording"] + assert view.state_text.value == "Starting..." + assert view.replay_panel.visible is False + assert view.mode_button.content == "Record" + assert view.mode_button.disabled is True + + +def test_recording_metrics_show_fps_suffix_once_and_preserve_drops(tmp_path: Path) -> None: + session, _bridge = _session(tmp_path) + view, _page = _view(session) + metrics = MetricsView( + input_fps="59.4", + recording_fps="59.3", + buffer="4.0 / 60 s", + buffer_fraction=4 / 60, + segments="2", + drops="Video 1 / Audio 0", + video_drops=1, + audio_drops=0, + has_drops=True, + ) + + view.render(replace(session.view_state(), metrics=metrics)) + + assert view.recording_status_text.value == ( + "Input 59.4 · Rec 59.3 fps · Seg 2 · Buf 4.0 / 60 s · ⚠ Drops V:1 A:0" + ) diff --git a/tests/test_ui_paths.py b/tests/test_ui_paths.py new file mode 100644 index 0000000..20f03b5 --- /dev/null +++ b/tests/test_ui_paths.py @@ -0,0 +1,45 @@ +"""Flet storage path resolution.""" + +from pathlib import Path + +import pytest + +from quickreplay.ui.paths import ( + CACHE_ENVIRONMENT_VARIABLE, + DATA_ENVIRONMENT_VARIABLE, + StoragePathError, + resolve_storage_paths, + storage_paths_from_environment, +) + + +def test_injected_paths_build_config_and_runtime(tmp_path: Path) -> None: + data = tmp_path / "data" + cache = tmp_path / "cache" + + paths = resolve_storage_paths(data_directory=data, cache_directory=cache) + + assert paths.config_path == data / "config.json" + assert paths.runtime_directory == cache / "runtime" + + +def test_environment_paths(tmp_path: Path) -> None: + environ = { + DATA_ENVIRONMENT_VARIABLE: str(tmp_path / "d"), + CACHE_ENVIRONMENT_VARIABLE: str(tmp_path / "c"), + } + + paths = storage_paths_from_environment(environ) + + assert paths.config_path == tmp_path / "d" / "config.json" + assert paths.runtime_directory == tmp_path / "c" / "runtime" + + +def test_missing_environment_is_an_error() -> None: + with pytest.raises(StoragePathError): + storage_paths_from_environment({}) + + +def test_partial_environment_is_an_error(tmp_path: Path) -> None: + with pytest.raises(StoragePathError): + storage_paths_from_environment({DATA_ENVIRONMENT_VARIABLE: str(tmp_path)}) diff --git a/tests/test_ui_presentation.py b/tests/test_ui_presentation.py new file mode 100644 index 0000000..1b11c7d --- /dev/null +++ b/tests/test_ui_presentation.py @@ -0,0 +1,155 @@ +"""Pure presentation helpers.""" + +from fractions import Fraction + +from quickreplay.app.state import ApplicationState +from quickreplay.input.models import ( + AudioStreamInfo, + StreamInfo, + VideoStreamInfo, +) +from quickreplay.recording.models import RecordingMetrics +from quickreplay.ui.presentation import ( + buffer_fraction, + control_state, + format_audio, + format_buffer, + format_duration_ns, + format_fps, + format_signed_duration_ns, + format_signed_frames, + format_stream_info, + metrics_view, + state_label, +) + + +def _stream_info(*, audio: AudioStreamInfo | None) -> StreamInfo: + return StreamInfo(VideoStreamInfo(1920, 1080, Fraction(60, 1), "UYVY"), audio) + + +def _metrics() -> RecordingMetrics: + return RecordingMetrics( + captured_video_frames=100, + recorded_video_frames=100, + captured_audio_samples=0, + recorded_audio_samples=0, + video_queue_drops=1, + audio_queue_drops=2, + buffer_duration_ns=57_800_000_000, + segment_count=29, + input_fps=60.0, + recording_fps=59.9, + ) + + +def test_format_fps() -> None: + assert format_fps(Fraction(60, 1)) == "60" + assert format_fps(Fraction(60000, 1001)) == "59.94" + assert format_fps(Fraction(30000, 1001)) == "29.97" + + +def test_format_stream_info() -> None: + assert format_stream_info(_stream_info(audio=None)) == "1920 × 1080 | 60 fps | UYVY" + assert format_stream_info(None) == "—" + + +def test_format_audio() -> None: + assert format_audio(_stream_info(audio=AudioStreamInfo(48000, 2))) == ("Audio: 48 kHz / Stereo") + assert format_audio(_stream_info(audio=AudioStreamInfo(48000, 1))) == ("Audio: 48 kHz / Mono") + assert format_audio(_stream_info(audio=None)) == "Audio: None" + + +def test_format_buffer_and_fraction() -> None: + assert format_buffer(57_800_000_000, 120) == "57.8 / 120 s" + assert buffer_fraction(60_000_000_000, 120) == 0.5 + assert buffer_fraction(240_000_000_000, 120) == 1.0 + assert buffer_fraction(-1, 120) == 0.0 + + +def test_metrics_view() -> None: + view = metrics_view(_metrics(), buffer_max_seconds=120) + assert view is not None + assert view.input_fps == "60.0" + assert view.recording_fps == "59.9" + assert view.buffer == "57.8 / 120 s" + assert view.segments == "29" + assert view.drops == "Video 1 / Audio 2" + + +def test_metrics_view_none() -> None: + assert metrics_view(None, buffer_max_seconds=120) is None + + +def test_state_labels_cover_all_states() -> None: + for state in ApplicationState: + assert state_label(state) + + +def test_control_state() -> None: + idle = control_state(ApplicationState.IDLE, has_selection=True, discovering=False) + assert idle.start_enabled + assert idle.input_enabled + assert not idle.replay_enabled + + no_selection = control_state(ApplicationState.IDLE, has_selection=False, discovering=False) + assert not no_selection.start_enabled + + recording = control_state(ApplicationState.RECORDING, has_selection=True, discovering=False) + assert recording.replay_enabled + assert not recording.start_enabled + assert not recording.input_enabled + + replay = control_state(ApplicationState.REPLAY, has_selection=True, discovering=False) + assert replay.resume_enabled + assert not replay.replay_enabled + + preparing = control_state( + ApplicationState.PREPARING_REPLAY, has_selection=True, discovering=False + ) + assert not preparing.start_enabled + assert not preparing.replay_enabled + assert not preparing.resume_enabled + + error = control_state(ApplicationState.ERROR, has_selection=True, discovering=False) + assert not error.start_enabled + assert not error.input_enabled + + discovering = control_state(ApplicationState.IDLE, has_selection=True, discovering=True) + assert not discovering.start_enabled + assert not discovering.refresh_enabled + + +def test_control_state_settings_enabled_except_when_shutting_down() -> None: + for state in ( + ApplicationState.IDLE, + ApplicationState.RECORDING, + ApplicationState.REPLAY, + ApplicationState.ERROR, + ): + assert control_state(state, has_selection=True, discovering=False).settings_enabled + + shutting_down = control_state( + ApplicationState.SHUTTING_DOWN, has_selection=True, discovering=False + ) + assert not shutting_down.settings_enabled + + +def test_format_duration_ns() -> None: + assert format_duration_ns(0) == "00:00.000" + assert format_duration_ns(1_000_000) == "00:00.001" + assert format_duration_ns(1_000_000_000) == "00:01.000" + assert format_duration_ns(61_234_000_000) == "01:01.234" + assert format_duration_ns(3_723_456_000_000) == "1:02:03.456" + + +def test_format_signed_duration_ns() -> None: + assert format_signed_duration_ns(750_000_000) == "+00:00.750" + assert format_signed_duration_ns(-750_000_000) == "-00:00.750" + assert format_signed_duration_ns(0) == "00:00.000" + + +def test_format_signed_frames() -> None: + assert format_signed_frames(45) == "+45" + assert format_signed_frames(-12) == "-12" + assert format_signed_frames(0) == "0" diff --git a/tests/test_ui_session.py b/tests/test_ui_session.py new file mode 100644 index 0000000..9a05df7 --- /dev/null +++ b/tests/test_ui_session.py @@ -0,0 +1,472 @@ +"""UiSession: discovery correlation, selection, persistence and view state.""" + +import asyncio +from fractions import Fraction +from pathlib import Path +from uuid import uuid4 + +from fake_ui import FakeBridge + +from quickreplay.app.state import ApplicationState +from quickreplay.application.events import ( + ApplicationError, + InputsChanged, + RecordingStarted, +) +from quickreplay.application.models import ApplicationSnapshot +from quickreplay.configuration.errors import ConfigurationWriteError +from quickreplay.configuration.models import QuickReplayConfig, RecordingConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.input.models import ( + AudioStreamInfo, + NdiInputConfig, + NdiInputDescriptor, + StreamInfo, + VideoStreamInfo, +) +from quickreplay.recording.models import RecordingMetrics +from quickreplay.replay.errors import MpvProcessExitedError +from quickreplay.replay.models import ReplayAsset, SetPoint +from quickreplay.ui.session import UiSession + +FPS = Fraction(60, 1) + + +def _stream_info() -> StreamInfo: + return StreamInfo(VideoStreamInfo(1920, 1080, FPS, "UYVY"), AudioStreamInfo(48000, 2)) + + +def _metrics() -> RecordingMetrics: + return RecordingMetrics( + captured_video_frames=100, + recorded_video_frames=100, + captured_audio_samples=0, + recorded_audio_samples=0, + video_queue_drops=0, + audio_queue_drops=0, + buffer_duration_ns=30_000_000_000, + segment_count=15, + input_fps=60.0, + recording_fps=60.0, + ) + + +class _FailingStore(ConfigurationStore): + def save(self, config: QuickReplayConfig) -> None: + raise ConfigurationWriteError("disk full") + + +class _BlockingReplayBridge(FakeBridge): + def __init__(self) -> None: + super().__init__() + self.entered = asyncio.Event() + self.release = asyncio.Event() + + async def step_forward(self) -> None: + self.entered.set() + await self.release.wait() + await super().step_forward() + + +def _session( + tmp_path: Path, + *, + config: QuickReplayConfig | None = None, + store: ConfigurationStore | None = None, + bridge: FakeBridge | None = None, +) -> tuple[UiSession, FakeBridge, ConfigurationStore]: + active_bridge = bridge or FakeBridge() + active_store = store or ConfigurationStore(tmp_path / "config.json") + return ( + UiSession(active_bridge, active_store, config or QuickReplayConfig()), + active_bridge, + active_store, + ) + + +async def _discover(session: UiSession, bridge: FakeBridge, inputs: tuple) -> None: + bridge.events = [InputsChanged(request_id=bridge.next_discovery_id, inputs=inputs)] + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.IDLE) + await session.poll() + + +def test_start_discovers_inputs(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + + asyncio.run(session.start()) + + assert bridge.started + assert bridge.discovery_requests == ["ndi"] + + +def test_discovery_resolves_and_selects_first_input(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("OBS"),))) + + state = session.view_state() + assert state.input_options[0].label == "OBS" + assert state.selected_key is not None + assert state.controls.start_enabled + assert not state.discovering + + +def test_stale_discovery_is_ignored(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + + bridge.events = [InputsChanged(request_id=uuid4(), inputs=(NdiInputDescriptor("Old"),))] + asyncio.run(session.poll()) + + assert session.view_state().input_options == () + assert session.view_state().discovering # still waiting for the current request + + +def test_saved_ndi_is_restored(tmp_path: Path) -> None: + config = QuickReplayConfig(input=NdiInputConfig("Studio")) + session, bridge, _ = _session(tmp_path, config=config) + asyncio.run(session.start()) + asyncio.run( + _discover( + session, + bridge, + (NdiInputDescriptor("Other"), NdiInputDescriptor("Studio")), + ) + ) + + state = session.view_state() + assert state.selected_key == "ndi:Studio" + assert state.controls.start_enabled + + +def test_unavailable_saved_input_disables_start(tmp_path: Path) -> None: + config = QuickReplayConfig(input=NdiInputConfig("Missing")) + session, bridge, _ = _session(tmp_path, config=config) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("Other"),))) + + state = session.view_state() + assert state.selected_key is None + assert not state.controls.start_enabled + assert state.status_message == "Configured input is not currently available" + + +def test_ndi_config_from_selection(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("OBS"),))) + + assert session.build_input_config() == NdiInputConfig("OBS") + + +def test_successful_start_persists_input(tmp_path: Path) -> None: + session, bridge, store = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("OBS"),))) + + asyncio.run(session.start_recording()) + assert bridge.recording_configs == [NdiInputConfig("OBS")] + + bridge.events = [RecordingStarted(stream_info=_stream_info())] + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.RECORDING, stream_info=_stream_info() + ) + asyncio.run(session.poll()) + + assert store.load().input == NdiInputConfig("OBS") + + +def test_new_start_clears_session_error_and_replay_transients(tmp_path: Path) -> None: + session, bridge, _store = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("OBS"),))) + session.note_error("previous recording failed") + session._replay_position_ns = 123 + session._replay_paused = True + session._frame_navigation_active = True + session._set_point = SetPoint(123) + session._time_difference_ns = 4 + session._frame_difference = 2 + + asyncio.run(session.start_recording()) + + state = session.view_state() + assert state.error_message is None + assert state.selected_key is not None + assert session._replay_position_ns is None + assert session._replay_paused is None + assert session._frame_navigation_active is False + assert session._set_point is None + assert session._time_difference_ns is None + assert session._frame_difference is None + + +def test_failed_start_does_not_persist(tmp_path: Path) -> None: + session, bridge, store = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("OBS"),))) + + asyncio.run(session.start_recording()) + # The worker reports an error instead of RecordingStarted. + bridge.events = [ApplicationError(message="input open failed", source="worker")] + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.ERROR, error_message="input open failed" + ) + asyncio.run(session.poll()) + + assert not store.path.exists() + + +def test_config_save_failure_is_non_fatal(tmp_path: Path) -> None: + store = _FailingStore(tmp_path / "config.json") + session, bridge, _ = _session(tmp_path, store=store) + asyncio.run(session.start()) + asyncio.run(_discover(session, bridge, (NdiInputDescriptor("OBS"),))) + + asyncio.run(session.start_recording()) + bridge.events = [RecordingStarted(stream_info=_stream_info())] + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.RECORDING, stream_info=_stream_info() + ) + asyncio.run(session.poll()) + + state = session.view_state() + assert state.state == ApplicationState.RECORDING + assert state.status_message is not None + assert "could not be saved" in state.status_message + + +def test_view_state_formats_stream_and_metrics(tmp_path: Path) -> None: + config = QuickReplayConfig(recording=RecordingConfig(buffer_duration_seconds=120)) + session, bridge, _ = _session(tmp_path, config=config) + asyncio.run(session.start()) + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.RECORDING, + stream_info=_stream_info(), + metrics=_metrics(), + ) + asyncio.run(session.poll()) + + state = session.view_state() + assert state.stream_text == "1920 × 1080 | 60 fps | UYVY" + assert state.audio_text == "Audio: 48 kHz / Stereo" + assert state.metrics is not None + assert state.metrics.buffer == "30.0 / 120 s" + assert state.controls.replay_enabled + + +def test_view_state_without_metrics(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.RECORDING) + asyncio.run(session.poll()) + + state = session.view_state() + assert state.metrics is None + assert state.stream_text == "—" + + +def test_shutdown_closes_bridge(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + + asyncio.run(session.shutdown()) + + assert bridge.shutdown_called + assert bridge.closed + + +def _asset(duration_ns: int = 12_000_000_000, fps: Fraction = FPS) -> ReplayAsset: + return ReplayAsset(Path("replay.mkv"), duration_ns, fps) + + +async def _enter_replay(session, bridge, *, duration_ns: int = 12_000_000_000) -> None: + bridge.snapshot_value = ApplicationSnapshot( + state=ApplicationState.REPLAY, replay_asset=_asset(duration_ns) + ) + await session.poll() + + +def test_replay_entry_populates_view(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + bridge.position_value = 3_250_000_000 + bridge.paused_value = True + + asyncio.run(_enter_replay(session, bridge)) + + view = session.view_state().replay + assert view is not None + assert view.position_ns == 3_250_000_000 + assert view.duration_ns == 12_000_000_000 + assert view.paused is True + assert view.position_text == "00:03.250" + assert view.duration_text == "00:12.000" + assert view.set_point_text == "—" + assert view.time_difference_text == "—" + assert view.frame_difference_text == "—" + assert view.has_set_point is False + + +def test_replay_exit_clears_state(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + bridge.set_point_value = 2_000_000_000 + asyncio.run(session.set_replay_point()) + assert session.view_state().replay is not None + + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.RESUMING) + asyncio.run(session.poll()) + assert session.view_state().replay is None + + # A new replay must not carry over the previous set point. + asyncio.run(_enter_replay(session, bridge)) + view = session.view_state().replay + assert view is not None + assert view.has_set_point is False + assert view.set_point_text == "—" + + +def test_toggle_play_uses_core_pause_state(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + + bridge.paused_value = True + asyncio.run(session.toggle_play_pause()) + assert bridge.play_calls == 1 + assert bridge.pause_calls == 0 + + bridge.paused_value = False + asyncio.run(session.toggle_play_pause()) + assert bridge.pause_calls == 1 + + +def test_replay_action_pending_blocks_only_overlapping_action(tmp_path: Path) -> None: + async def scenario() -> None: + bridge = _BlockingReplayBridge() + session, _, _ = _session(tmp_path, bridge=bridge) + first = asyncio.create_task(session.step_forward()) + await bridge.entered.wait() + + await session.step_forward() + assert bridge.step_forward_calls == 0 + + bridge.release.set() + await first + await session.step_forward() + assert bridge.step_forward_calls == 2 + + asyncio.run(scenario()) + + +def test_set_point_uses_bridge_value_and_shows_differences(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + bridge.position_value = 3_250_000_000 + bridge.set_point_value = 2_500_000_000 + bridge.time_difference_value = 750_000_000 + bridge.frame_difference_value = 45 + + asyncio.run(session.set_replay_point()) + + view = session.view_state().replay + assert view is not None + assert view.has_set_point is True + assert view.set_point_text == "00:02.500" + assert view.time_difference_text == "+00:00.750" + assert view.frame_difference_text == "+45" + assert bridge.set_point_calls == 1 + assert bridge.time_difference_points == [SetPoint(2_500_000_000)] + assert bridge.frame_difference_points == [SetPoint(2_500_000_000)] + + +def test_differences_are_not_queried_without_set_point(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + + assert bridge.time_difference_points == [] + assert bridge.frame_difference_points == [] + + +def test_non_replay_poll_does_not_query_replay_api(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.RECORDING) + + asyncio.run(session.poll()) + + assert bridge.position_calls == 0 + assert bridge.is_paused_calls == 0 + + +def test_replay_status_refreshes_during_replay(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + bridge.set_point_value = 2_000_000_000 + asyncio.run(session.set_replay_point()) + bridge.position_value = 2_050_000_000 + bridge.time_difference_value = 50_000_000 + bridge.frame_difference_value = 3 + + asyncio.run(session.poll()) + + view = session.view_state().replay + assert view is not None + assert view.position_ns == 2_050_000_000 + assert view.time_difference_text == "+00:00.050" + assert view.frame_difference_text == "+3" + + +def test_negative_frame_difference_is_signed(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + bridge.set_point_value = 2_000_000_000 + bridge.frame_difference_value = -12 + bridge.time_difference_value = -750_000_000 + + asyncio.run(session.set_replay_point()) + + view = session.view_state().replay + assert view is not None + assert view.frame_difference_text == "-12" + assert view.time_difference_text == "-00:00.750" + + +def test_mpv_exit_during_status_refresh_is_not_an_error(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + + bridge.position_error = MpvProcessExitedError("mpv exited") + asyncio.run(session.poll()) + assert session.view_state().error_message is None + + bridge.position_error = None + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.RESUMING) + asyncio.run(session.poll()) + assert session.view_state().replay is None + + +def test_transient_replay_error_is_reported(tmp_path: Path) -> None: + session, bridge, _ = _session(tmp_path) + asyncio.run(session.start()) + asyncio.run(_enter_replay(session, bridge)) + + bridge.position_error = RuntimeError("seek failed") + asyncio.run(session.poll()) + + assert "Replay control failed" in (session.view_state().error_message or "") + # The application state machine is unchanged. + assert session.view_state().state == ApplicationState.REPLAY + + bridge.position_error = None + bridge.snapshot_value = ApplicationSnapshot(state=ApplicationState.RESUMING) + asyncio.run(session.poll()) + + assert session.view_state().error_message is None diff --git a/tests/test_ui_settings.py b/tests/test_ui_settings.py new file mode 100644 index 0000000..a41d09d --- /dev/null +++ b/tests/test_ui_settings.py @@ -0,0 +1,93 @@ +"""Settings draft validation and UiSession persistence behavior.""" + +import asyncio +from pathlib import Path + +import pytest +from fake_ui import FakeBridge + +from quickreplay.configuration.errors import ConfigurationWriteError +from quickreplay.configuration.models import QuickReplayConfig +from quickreplay.configuration.store import ConfigurationStore +from quickreplay.input.models import NdiInputConfig +from quickreplay.ui.session import UiSession +from quickreplay.ui.settings import ( + RESTART_REQUIRED_MESSAGE, + SETTINGS_SAVED_MESSAGE, + SettingsDraft, + apply_message, + build_settings_config, + draft_from_config, + restart_required, +) + + +class _FailingStore(ConfigurationStore): + def save(self, config: QuickReplayConfig) -> None: + raise ConfigurationWriteError("disk full") + + +def test_draft_uses_persisted_runtime_settings() -> None: + config = QuickReplayConfig(input=NdiInputConfig("Studio")) + draft = draft_from_config(config) + assert draft.buffer_duration_seconds == "120" + assert draft.mpv_executable == "mpv" + + +def test_apply_config_preserves_input_selection() -> None: + config = QuickReplayConfig(input=NdiInputConfig("Studio")) + result = build_settings_config(SettingsDraft("60", "mpv.exe"), config) + assert result.errors == () + assert result.config is not None + assert result.config.input == NdiInputConfig("Studio") + assert result.config.recording.buffer_duration_seconds == 60 + assert result.config.replay.mpv_executable == "mpv.exe" + + +@pytest.mark.parametrize( + ("draft", "field"), + [ + (SettingsDraft("0", "mpv"), "buffer_duration_seconds"), + (SettingsDraft("abc", "mpv"), "buffer_duration_seconds"), + (SettingsDraft("60", ""), "mpv_executable"), + ], +) +def test_invalid_draft_returns_field_errors(draft: SettingsDraft, field: str) -> None: + result = build_settings_config(draft, QuickReplayConfig()) + assert result.config is None + assert field in {error.field for error in result.errors} + + +def test_restart_required_only_tracks_runtime_settings() -> None: + current = QuickReplayConfig(input=NdiInputConfig("A")) + other_input = QuickReplayConfig(input=NdiInputConfig("B")) + candidate = build_settings_config(SettingsDraft("120", "mpv"), other_input).config + assert candidate is not None + assert not restart_required(current, candidate) + changed = build_settings_config(SettingsDraft("60", "mpv"), current).config + assert changed is not None + assert restart_required(current, changed) + + +def test_apply_message_reflects_restart_requirement() -> None: + assert apply_message(restart=False) == SETTINGS_SAVED_MESSAGE + assert apply_message(restart=True) == RESTART_REQUIRED_MESSAGE + + +def test_session_apply_persists_settings_without_changing_input(tmp_path: Path) -> None: + initial = QuickReplayConfig(input=NdiInputConfig("Studio")) + store = ConfigurationStore(tmp_path / "config.json") + session = UiSession(FakeBridge(), store, initial) + result = asyncio.run(session.apply_settings(SettingsDraft("60", "mpv.exe"))) + assert result.ok and result.restart_required + assert session.config.input == NdiInputConfig("Studio") + assert store.load() == session.config + + +def test_failed_save_does_not_replace_session_config(tmp_path: Path) -> None: + initial = QuickReplayConfig(input=NdiInputConfig("Studio")) + session = UiSession(FakeBridge(), _FailingStore(tmp_path / "config.json"), initial) + result = asyncio.run(session.apply_settings(SettingsDraft("60", "mpv.exe"))) + assert not result.ok + assert "Could not save settings" in result.message + assert session.config == initial diff --git a/tests/test_ui_slider.py b/tests/test_ui_slider.py new file mode 100644 index 0000000..d04d88a --- /dev/null +++ b/tests/test_ui_slider.py @@ -0,0 +1,28 @@ +"""Seek-bar conversion and drag logic (pure, no Flet widgets).""" + +from quickreplay.ui.main_view import SeekDrag, slider_seconds_to_ns + + +def test_slider_seconds_to_ns() -> None: + assert slider_seconds_to_ns(0) == 0 + assert slider_seconds_to_ns(0.001) == 1_000_000 + assert slider_seconds_to_ns(1.25) == 1_250_000_000 + assert slider_seconds_to_ns(3.5) == 3_500_000_000 + + +def test_seek_drag_lifecycle() -> None: + drag = SeekDrag() + assert not drag.active + + drag.start(1.0) + assert drag.active + assert drag.preview_ns == 1_000_000_000 + + drag.update_preview(2.5) + assert drag.active # preview updates do not end the drag + assert drag.preview_ns == 2_500_000_000 + + target = drag.end(3.25) + assert target == 3_250_000_000 + assert drag.preview_ns == 3_250_000_000 + assert not drag.active diff --git a/tests/test_uyvy_converter.py b/tests/test_uyvy_converter.py new file mode 100644 index 0000000..dd16562 --- /dev/null +++ b/tests/test_uyvy_converter.py @@ -0,0 +1,67 @@ +"""UYVY support in the recording FrameConverter.""" + +from fractions import Fraction + +import numpy as np +import pytest + +from quickreplay.input.models import VideoFrame +from quickreplay.recording.errors import SegmentFormatError +from quickreplay.recording.frame_converter import FrameConverter + + +def _uyvy_frame(width: int, height: int, value: int = 128) -> VideoFrame: + data = np.full((height, width * 2), value, dtype=np.uint8) + return VideoFrame(0, width, height, Fraction(60, 1), "UYVY", data) + + +def test_uyvy_converts_to_yuv420p() -> None: + frame = _uyvy_frame(160, 90, value=128) + + av_frame = FrameConverter().to_av_video(frame) + + assert av_frame.format.name == "yuv420p" + assert av_frame.width == 160 + assert av_frame.height == 90 + + +def test_uyvy_odd_width_is_supported() -> None: + frame = _uyvy_frame(158, 90) + + av_frame = FrameConverter().to_av_video(frame) + + assert av_frame.width == 158 + assert av_frame.format.name == "yuv420p" + + +def test_uyvy_wrong_shape_is_rejected() -> None: + bad = VideoFrame(0, 4, 2, Fraction(60, 1), "UYVY", np.zeros((2, 4), dtype=np.uint8)) + + with pytest.raises(SegmentFormatError): + FrameConverter().to_av_video(bad) + + +def test_existing_pixel_formats_still_work() -> None: + converter = FrameConverter() + rgb = VideoFrame(0, 4, 2, Fraction(60, 1), "RGB24", np.zeros((2, 4, 3), dtype=np.uint8)) + + av_frame = converter.to_av_video(rgb) + + assert av_frame.format.name == "yuv420p" + assert (av_frame.width, av_frame.height) == (4, 2) + + +def test_bgra_converts_to_yuv420p() -> None: + frame = VideoFrame( + 0, + 4, + 2, + Fraction(60, 1), + "BGRA", + np.zeros((2, 4, 4), dtype=np.uint8), + ) + + av_frame = FrameConverter().to_av_video(frame) + + assert av_frame.format.name == "yuv420p" + assert (av_frame.width, av_frame.height) == (4, 2) diff --git a/tests/test_worker_errors.py b/tests/test_worker_errors.py new file mode 100644 index 0000000..af39c70 --- /dev/null +++ b/tests/test_worker_errors.py @@ -0,0 +1,81 @@ +"""Component error -> WorkerErrorCode mapping.""" + +import errno + +from quickreplay.input.ndi.errors import ( + NdiCaptureError, + NdiFormatChangeError, + NdiInitializationError, + NdiSourceNotFoundError, + NdiUnsupportedFormatError, +) +from quickreplay.recording.errors import ( + RingStorageError, + SegmentDeleteError, + SegmentEncodingError, + SegmentFormatError, + SegmentMuxError, +) +from quickreplay.recording.models import WorkerErrorCode +from quickreplay.replay.errors import ReplayRemuxError +from quickreplay.worker.errors import ( + PipelineFormatChangeError, + PipelineOrderingError, + PipelineStartupError, + map_worker_error, +) + + +def test_source_not_found() -> None: + assert map_worker_error(NdiSourceNotFoundError("x")) == WorkerErrorCode.INPUT_NOT_FOUND + + +def test_open_failures() -> None: + assert map_worker_error(NdiInitializationError("x")) == WorkerErrorCode.INPUT_OPEN_FAILED + + +def test_disconnect_and_capture() -> None: + assert map_worker_error(NdiCaptureError("x")) == WorkerErrorCode.INPUT_DISCONNECTED + assert map_worker_error(PipelineStartupError("x")) == WorkerErrorCode.INPUT_DISCONNECTED + + +def test_format_errors() -> None: + assert map_worker_error(NdiUnsupportedFormatError("x")) == WorkerErrorCode.UNSUPPORTED_FORMAT + assert map_worker_error(NdiFormatChangeError("x")) == WorkerErrorCode.UNSUPPORTED_FORMAT + assert map_worker_error(SegmentFormatError("x")) == WorkerErrorCode.UNSUPPORTED_FORMAT + assert map_worker_error(PipelineFormatChangeError("x")) == WorkerErrorCode.UNSUPPORTED_FORMAT + + +def test_encode_and_mux() -> None: + assert map_worker_error(SegmentEncodingError("x")) == WorkerErrorCode.ENCODER_FAILED + assert map_worker_error(SegmentMuxError("x")) == WorkerErrorCode.MUXER_FAILED + + +def test_replay_error() -> None: + assert map_worker_error(ReplayRemuxError("x")) == WorkerErrorCode.REPLAY_ASSET_FAILED + + +def test_ring_and_file_io() -> None: + assert map_worker_error(RingStorageError("x")) == WorkerErrorCode.FILE_IO_ERROR + assert map_worker_error(SegmentDeleteError(())) == WorkerErrorCode.FILE_IO_ERROR + assert map_worker_error(OSError("boom")) == WorkerErrorCode.FILE_IO_ERROR + + +def test_ordering_and_unexpected() -> None: + assert map_worker_error(PipelineOrderingError("x")) == WorkerErrorCode.INTERNAL_ERROR + assert map_worker_error(ValueError("x")) == WorkerErrorCode.INTERNAL_ERROR + + +def test_disk_full_wins_over_encoder() -> None: + error = SegmentEncodingError("disk full") + error.__cause__ = OSError(errno.ENOSPC, "no space left on device") + + assert map_worker_error(error) == WorkerErrorCode.DISK_FULL + + +def test_disk_full_through_context_chain() -> None: + error = RingStorageError("delete failed") + context = OSError(errno.ENOSPC, "no space") + error.__context__ = context + + assert map_worker_error(error) == WorkerErrorCode.DISK_FULL diff --git a/tests/test_worker_fs.py b/tests/test_worker_fs.py new file mode 100644 index 0000000..4eb67f7 --- /dev/null +++ b/tests/test_worker_fs.py @@ -0,0 +1,85 @@ +"""Bounded, transient-only retry for recording-session directory cleanup.""" + +import types +from pathlib import Path + +import pytest + +from quickreplay.worker import fs + + +class _TransientOSError(OSError): + def __init__(self, winerror: int) -> None: + super().__init__("transient filesystem error") + self.winerror = winerror + + +def _windows(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(fs, "os", types.SimpleNamespace(name="nt")) + monkeypatch.setattr(fs.time, "sleep", lambda _seconds: None) + + +def test_missing_path_is_a_noop() -> None: + fs.remove_tree(Path("does-not-exist-12345")) + + +def test_retries_transient_windows_errors(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + calls = {"count": 0} + + def fake_rmtree(path: Path, **kwargs) -> None: + calls["count"] += 1 + if calls["count"] < 3: + raise _TransientOSError(32) + + monkeypatch.setattr(fs.shutil, "rmtree", fake_rmtree) + _windows(monkeypatch) + + fs.remove_tree(tmp_path) + + assert calls["count"] == 3 + + +def test_gives_up_after_bounded_attempts(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + calls = {"count": 0} + + def fake_rmtree(path: Path, **kwargs) -> None: + calls["count"] += 1 + raise _TransientOSError(145) + + monkeypatch.setattr(fs.shutil, "rmtree", fake_rmtree) + _windows(monkeypatch) + + with pytest.raises(OSError): + fs.remove_tree(tmp_path, attempts=2) + assert calls["count"] == 2 + + +def test_non_transient_error_is_not_retried( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + calls = {"count": 0} + + def fake_rmtree(path: Path, **kwargs) -> None: + calls["count"] += 1 + raise _TransientOSError(1) + + monkeypatch.setattr(fs.shutil, "rmtree", fake_rmtree) + _windows(monkeypatch) + + with pytest.raises(OSError): + fs.remove_tree(tmp_path) + assert calls["count"] == 1 + + +def test_non_windows_deletes_once(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + calls = {"count": 0} + + def fake_rmtree(path: Path, **kwargs) -> None: + calls["count"] += 1 + + monkeypatch.setattr(fs.shutil, "rmtree", fake_rmtree) + monkeypatch.setattr(fs, "os", types.SimpleNamespace(name="posix")) + + fs.remove_tree(tmp_path) + + assert calls["count"] == 1 diff --git a/tests/test_worker_inputs.py b/tests/test_worker_inputs.py new file mode 100644 index 0000000..8962308 --- /dev/null +++ b/tests/test_worker_inputs.py @@ -0,0 +1,15 @@ +"""Worker input factory and discovery contracts.""" + +from quickreplay.input.models import NdiInputConfig +from quickreplay.input.ndi.source import NdiInputSource +from quickreplay.worker.inputs import create_input_source, input_supports_audio, open_input_source + + +def test_open_input_source_contract_matches_config() -> None: + config = NdiInputConfig("PC (OBS)") + source = open_input_source(config) + + assert isinstance(create_input_source(config), NdiInputSource) + assert isinstance(source.source, NdiInputSource) + assert source.supports_audio is True + assert input_supports_audio(config) is True diff --git a/tests/test_worker_pipeline.py b/tests/test_worker_pipeline.py new file mode 100644 index 0000000..9b03b41 --- /dev/null +++ b/tests/test_worker_pipeline.py @@ -0,0 +1,369 @@ +"""RecordingPipeline: bootstrap, A/V ordering, hold-back and failures.""" + +import threading +import time +from collections.abc import Callable +from fractions import Fraction +from pathlib import Path + +import pytest +from fake_worker_input import ( + FakeInputSource, + audio_frame, + audio_info, + build_script, + video_frame, + video_info, +) + +from quickreplay.input.models import NdiInputConfig +from quickreplay.recording.errors import SegmentMuxError +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction +from quickreplay.worker.errors import ( + PipelineFormatChangeError, + PipelineOrderingError, + PipelineStartupError, +) +from quickreplay.worker.fs import remove_tree +from quickreplay.worker.inputs import InputSourceHandle +from quickreplay.worker.pipeline import RecordingPipeline +from quickreplay.worker.settings import RecorderWorkerSettings + +FPS = Fraction(60, 1) + + +def _pipeline( + tmp_path: Path, + source: FakeInputSource, + *, + supports_audio: bool, + **overrides: int, +) -> RecordingPipeline: + options: dict[str, int] = {"video_queue_capacity": 4096, "audio_queue_capacity": 4096} + options.update(overrides) + settings = RecorderWorkerSettings(working_directory=tmp_path, **options) + handle = InputSourceHandle(source=source, supports_audio=supports_audio) + return RecordingPipeline(settings, input_factory=lambda _config: handle) + + +def _wait_until(predicate: Callable[[], bool], *, timeout: float = 5.0) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.01) + raise AssertionError("condition was not met in time") + + +def test_first_video_is_epoch_and_nothing_is_dropped(tmp_path: Path) -> None: + script, video_frames, _ = build_script( + duration_ns=1_000_000_000, fps=FPS, base_ns=5_000_000_000 + ) + source = FakeInputSource(script, video_stream=video_info(FPS)) + pipeline = _pipeline(tmp_path, source, supports_audio=False) + pipeline.start(NdiInputConfig("fake")) + try: + session = pipeline.session + assert session is not None + assert session.epoch_ns == 5_000_000_000 + _wait_until(lambda: pipeline.metrics().recorded_video_frames >= video_frames) + finally: + pipeline.stop() + assert pipeline.poll_fatal() is None + ring = pipeline.take_ring() + assert ring is not None + assert sum(segment.video_frames for segment in ring.segments) == video_frames + + +def test_delayed_audio_within_holdback_records(tmp_path: Path) -> None: + script, video_frames, audio_samples = build_script( + duration_ns=2_000_000_000, + fps=FPS, + sample_rate=48000, + channels=2, + audio_delay_ns=200_000_000, + ) + source = FakeInputSource(script, video_stream=video_info(FPS), audio_stream=audio_info()) + pipeline = _pipeline(tmp_path, source, supports_audio=True) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.metrics().captured_audio_samples >= audio_samples, timeout=5.0) + pipeline.stop() + finally: + pipeline.abort() + assert pipeline.poll_fatal() is None + metrics = pipeline.metrics() + assert metrics.recorded_video_frames == video_frames + assert metrics.recorded_audio_samples == audio_samples + + +def test_late_frame_beyond_holdback_is_an_ordering_error(tmp_path: Path) -> None: + items: list[tuple[int, int, object]] = [ + (0, 1, audio_frame(0)), + (0, 0, video_frame(0, fps=FPS)), + (20_000_000, 1, audio_frame(20_000_000)), + ] + index = 1 + while True: + offset = round_fraction(Fraction(index * NANOSECONDS_PER_SECOND, 1) / FPS) + if offset > 1_000_000_000: + break + items.append((offset, 0, video_frame(offset, fps=FPS))) + index += 1 + # This audio is delivered late and rewinds the audio stream. + items.append((1_500_000_000, 1, audio_frame(10_000_000))) + items.sort(key=lambda entry: (entry[0], entry[1])) + source = FakeInputSource( + [item for _key, _kind, item in items], + video_stream=video_info(FPS), + audio_stream=audio_info(), + ) + pipeline = _pipeline(tmp_path, source, supports_audio=True) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.poll_fatal() is not None, timeout=5.0) + fatal = pipeline.poll_fatal() + finally: + pipeline.abort() + assert isinstance(fatal, PipelineOrderingError) + + +def test_audio_after_video_only_session_is_a_format_change(tmp_path: Path) -> None: + script: list[object] = [video_frame(index * 16_666_667, fps=FPS) for index in range(4)] + script.extend([None] * 80) + script.extend([lambda: time.sleep(0.12), audio_frame(1_600_000_000)]) + source = FakeInputSource(script, video_stream=video_info(FPS), audio_stream=audio_info()) + pipeline = _pipeline(tmp_path, source, supports_audio=True, stream_probe_window_ns=50_000_000) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.poll_fatal() is not None, timeout=5.0) + fatal = pipeline.poll_fatal() + finally: + pipeline.abort() + assert isinstance(fatal, PipelineFormatChangeError) + + +def test_video_only_input_has_no_audio_holdback(tmp_path: Path) -> None: + script, video_frames, _ = build_script(duration_ns=1_000_000_000, fps=FPS) + source = FakeInputSource(script, video_stream=video_info(FPS)) + pipeline = _pipeline( + tmp_path, source, supports_audio=False, av_reorder_holdback_ns=5_000_000_000 + ) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.metrics().recorded_video_frames > 0, timeout=3.0) + finally: + pipeline.stop() + assert pipeline.poll_fatal() is None + assert pipeline.metrics().recorded_video_frames == video_frames + + +def test_capture_failure_becomes_fatal(tmp_path: Path) -> None: + source = FakeInputSource( + [video_frame(0, fps=FPS), ValueError("capture exploded")], + video_stream=video_info(FPS), + ) + pipeline = _pipeline(tmp_path, source, supports_audio=False) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.poll_fatal() is not None, timeout=5.0) + fatal = pipeline.poll_fatal() + finally: + pipeline.abort() + assert isinstance(fatal, ValueError) + + +def test_startup_timeout_without_video(tmp_path: Path) -> None: + source = FakeInputSource([], video_stream=video_info(FPS)) + pipeline = _pipeline( + tmp_path, source, supports_audio=False, stream_start_timeout_ns=200_000_000 + ) + + with pytest.raises(PipelineStartupError): + pipeline.start(NdiInputConfig("fake")) + + +def test_first_video_timeout_starts_after_source_open(tmp_path: Path) -> None: + class SlowOpenSource(FakeInputSource): + def open(self) -> None: + time.sleep(0.12) + super().open() + + source = SlowOpenSource([video_frame(0, fps=FPS)], video_stream=video_info(FPS)) + pipeline = _pipeline( + tmp_path, + source, + supports_audio=False, + stream_start_timeout_ns=50_000_000, + ) + + info = pipeline.start(NdiInputConfig("fake")) + + try: + assert info.audio is None + assert source.open_count == 1 + finally: + pipeline.stop() + + +def test_audio_probe_uses_control_time_not_media_timestamp_delta(tmp_path: Path) -> None: + timestamps = (0, 200_000_000, 400_000_000, 600_000_000) + script: list[object] = [video_frame(timestamp, fps=FPS) for timestamp in timestamps] + script.append(audio_frame(600_000_000)) + source = FakeInputSource( + script, + video_stream=video_info(FPS), + audio_stream=audio_info(), + ) + pipeline = _pipeline(tmp_path, source, supports_audio=True) + + info = pipeline.start(NdiInputConfig("fake")) + + try: + assert info.audio == audio_info() + _wait_until(lambda: pipeline.metrics().captured_audio_samples > 0) + assert pipeline.poll_fatal() is None + finally: + pipeline.stop() + + +def test_pre_epoch_audio_is_dropped(tmp_path: Path) -> None: + epoch = 1_000_000_000 + items = [ + audio_frame(0), # before the first video -> dropped + video_frame(epoch, fps=FPS), + video_frame(epoch + 16_000_000, fps=FPS), + audio_frame(epoch), # at the epoch -> kept + ] + source = FakeInputSource(items, video_stream=video_info(FPS), audio_stream=audio_info()) + pipeline = _pipeline(tmp_path, source, supports_audio=True) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.metrics().captured_audio_samples >= 1024, timeout=5.0) + pipeline.stop() + finally: + pipeline.abort() + assert pipeline.poll_fatal() is None + assert pipeline.metrics().captured_audio_samples == 1024 + + +class _FakeWriter: + """Test writer that can block or fail during finalize.""" + + def __init__(self, segment_id: int, directory: Path, *, gate, entered, error) -> None: + self.segment_id = segment_id + self._directory = Path(directory) + self._gate = gate + self._entered = entered + self._error = error + + def write_video(self, frame, pts: int) -> None: + return None + + def write_audio(self, data, pts: int) -> None: + return None + + def finalize(self) -> Path: + if self._entered is not None: + self._entered.set() + if self._gate is not None: + self._gate.wait(timeout=5) + if self._error is not None: + raise self._error + path = self._directory / f"segment_{self.segment_id:06d}.mkv" + path.write_bytes(b"segment") + return path + + def abort(self) -> None: + return None + + +class _WriterFactory: + def __init__(self, *, gate=None, entered=None, error=None) -> None: + self._gate = gate + self._entered = entered + self._error = error + + def __call__(self, segment_id: int, directory: Path, stream_info) -> _FakeWriter: + return _FakeWriter( + segment_id, directory, gate=self._gate, entered=self._entered, error=self._error + ) + + +def _pipeline_with_writer( + tmp_path: Path, source: FakeInputSource, writer_factory: _WriterFactory +) -> RecordingPipeline: + settings = RecorderWorkerSettings( + working_directory=tmp_path, + segment_duration_ns=10_000_000_000, + video_queue_capacity=4096, + audio_queue_capacity=4096, + ) + handle = InputSourceHandle(source=source, supports_audio=False) + return RecordingPipeline( + settings, + input_factory=lambda _config: handle, + writer_factory=writer_factory, + ) + + +def test_stop_waits_for_writer_finalize(tmp_path: Path) -> None: + gate = threading.Event() + entered = threading.Event() + script, _frames, _ = build_script(duration_ns=500_000_000, fps=FPS) + source = FakeInputSource(script, video_stream=video_info(FPS)) + pipeline = _pipeline_with_writer(tmp_path, source, _WriterFactory(gate=gate, entered=entered)) + pipeline.start(NdiInputConfig("fake")) + try: + _wait_until(lambda: pipeline.metrics().recorded_video_frames > 0) + errors: list[BaseException] = [] + + def do_stop() -> None: + try: + pipeline.stop() + except BaseException as exc: # noqa: BLE001 - captured for assertion + errors.append(exc) + + stopper = threading.Thread(target=do_stop) + stopper.start() + assert entered.wait(timeout=5) # finalize has started + assert stopper.is_alive() # stop() waits for finalization + gate.set() + stopper.join(timeout=5) + assert not stopper.is_alive() + assert errors == [] + finally: + gate.set() + pipeline.abort() + + +def test_stop_surfaces_writer_finalize_failure(tmp_path: Path) -> None: + script, _frames, _ = build_script(duration_ns=500_000_000, fps=FPS) + source = FakeInputSource(script, video_stream=video_info(FPS)) + pipeline = _pipeline_with_writer( + tmp_path, source, _WriterFactory(error=SegmentMuxError("boom")) + ) + pipeline.start(NdiInputConfig("fake")) + _wait_until(lambda: pipeline.metrics().recorded_video_frames > 0) + + with pytest.raises(SegmentMuxError): + pipeline.stop() + + assert isinstance(pipeline.poll_fatal(), SegmentMuxError) + + +def test_stop_leaves_no_temp_files_and_is_removable(tmp_path: Path) -> None: + script, video_frames, _ = build_script(duration_ns=1_000_000_000, fps=FPS) + source = FakeInputSource(script, video_stream=video_info(FPS)) + pipeline = _pipeline(tmp_path, source, supports_audio=False) + pipeline.start(NdiInputConfig("fake")) + _wait_until(lambda: pipeline.metrics().recorded_video_frames >= video_frames) + pipeline.stop() + + session = pipeline.session + assert session is not None + assert pipeline.poll_fatal() is None + assert list(session.directory.glob("*.tmp.mkv")) == [] + assert list(session.directory.glob("*.mkv")) + remove_tree(session.directory) # immediate delete must succeed + assert not session.directory.exists() diff --git a/tests/test_worker_process.py b/tests/test_worker_process.py new file mode 100644 index 0000000..cf6ad53 --- /dev/null +++ b/tests/test_worker_process.py @@ -0,0 +1,141 @@ +"""Spawn process integration for the recorder worker.""" + +import pickle +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from quickreplay.recording.commands import Shutdown +from quickreplay.recording.events import WorkerStateChanged +from quickreplay.recording.models import WorkerState +from quickreplay.worker import process +from quickreplay.worker.process import ( + RecorderWorkerProcess, + spawn_context, + worker_process_main, +) +from quickreplay.worker.settings import RecorderWorkerSettings + + +def test_worker_process_main_is_a_module_level_function() -> None: + restored = pickle.loads(pickle.dumps(worker_process_main)) + assert restored is worker_process_main + + +def test_worker_process_owns_ndi_runtime_until_runtime_returns(monkeypatch, tmp_path: Path) -> None: + calls = [] + + class FakeBackend: + def initialize(self) -> None: + calls.append("ndi.initialize") + + def shutdown(self) -> None: + calls.append("ndi.shutdown") + + class FakeRuntime: + def __init__(self, *_args, **_kwargs) -> None: + pass + + def run(self) -> None: + calls.append("runtime.run") + + monkeypatch.setattr(process, "PyNdiBackend", FakeBackend) + monkeypatch.setattr(process, "RecorderWorkerRuntime", FakeRuntime) + + worker_process_main( + object(), + SimpleNamespace(put=lambda _event: None), + RecorderWorkerSettings(working_directory=tmp_path), + ) + + assert calls == ["ndi.initialize", "runtime.run", "ndi.shutdown"] + + +def test_worker_process_releases_ndi_runtime_when_runtime_raises( + monkeypatch, tmp_path: Path +) -> None: + calls = [] + + class FakeBackend: + def initialize(self) -> None: + calls.append("ndi.initialize") + + def shutdown(self) -> None: + calls.append("ndi.shutdown") + + class FakeRuntime: + def __init__(self, *_args, **_kwargs) -> None: + pass + + def run(self) -> None: + calls.append("runtime.run") + raise RuntimeError("worker failed") + + monkeypatch.setattr(process, "PyNdiBackend", FakeBackend) + monkeypatch.setattr(process, "RecorderWorkerRuntime", FakeRuntime) + + with pytest.raises(RuntimeError, match="worker failed"): + worker_process_main( + object(), + SimpleNamespace(put=lambda _event: None), + RecorderWorkerSettings(working_directory=tmp_path), + ) + + assert calls == ["ndi.initialize", "runtime.run", "ndi.shutdown"] + + +def test_worker_process_does_not_shutdown_if_ndi_initialization_fails( + monkeypatch, tmp_path: Path +) -> None: + calls = [] + + class FakeBackend: + def initialize(self) -> None: + calls.append("ndi.initialize") + raise RuntimeError("NDI initialization failed") + + def shutdown(self) -> None: + calls.append("ndi.shutdown") + + class FakeRuntime: + def __init__(self, *_args, **_kwargs) -> None: + calls.append("runtime.create") + + monkeypatch.setattr(process, "PyNdiBackend", FakeBackend) + monkeypatch.setattr(process, "RecorderWorkerRuntime", FakeRuntime) + + with pytest.raises(RuntimeError, match="NDI initialization failed"): + worker_process_main( + object(), + SimpleNamespace(put=lambda _event: None), + RecorderWorkerSettings(working_directory=tmp_path), + ) + + assert calls == ["ndi.initialize"] + + +def test_spawn_context_is_spawn() -> None: + assert spawn_context().get_start_method() == "spawn" + + +def test_spawn_worker_starts_idle_and_shuts_down(tmp_path: Path) -> None: + settings = RecorderWorkerSettings(working_directory=tmp_path) + worker = RecorderWorkerProcess(settings) + worker.start() + try: + first = worker.get_event(timeout=30) + assert isinstance(first, WorkerStateChanged) + assert first.state == WorkerState.IDLE + + worker.send(Shutdown()) + shutdown = worker.get_event(timeout=30) + assert isinstance(shutdown, WorkerStateChanged) + assert shutdown.state == WorkerState.SHUTTING_DOWN + + worker.join(timeout=30) + assert not worker.is_alive() + assert worker.exitcode == 0 + finally: + worker.terminate() + worker.close() diff --git a/tests/test_worker_protocol.py b/tests/test_worker_protocol.py new file mode 100644 index 0000000..0132de1 --- /dev/null +++ b/tests/test_worker_protocol.py @@ -0,0 +1,116 @@ +"""Tests for the worker command / event protocol (picklable value objects).""" + +import pickle +from fractions import Fraction +from pathlib import Path +from uuid import UUID, uuid4 + +import pytest + +from quickreplay.input.models import ( + AudioStreamInfo, + NdiInputConfig, + NdiInputDescriptor, + StreamInfo, + VideoStreamInfo, +) +from quickreplay.recording.commands import ( + ChangeInput, + DiscoverInputs, + PrepareReplay, + ResumeRecording, + Shutdown, + StartRecording, + WorkerCommand, +) +from quickreplay.recording.events import ( + InputsDiscovered, + RecordingMetricsUpdated, + ReplayPrepared, + StreamStarted, + WorkerError, + WorkerEvent, + WorkerStateChanged, +) +from quickreplay.recording.models import ( + RecordingMetrics, + WorkerErrorCode, + WorkerState, +) +from quickreplay.replay.models import ReplayAsset + + +def _stream_info() -> StreamInfo: + return StreamInfo( + video=VideoStreamInfo(1920, 1080, Fraction(60000, 1001), "UYVY"), + audio=AudioStreamInfo(48000, 2), + ) + + +def _metrics() -> RecordingMetrics: + return RecordingMetrics( + captured_video_frames=1800, + recorded_video_frames=1799, + captured_audio_samples=1_440_000, + recorded_audio_samples=1_439_000, + video_queue_drops=0, + audio_queue_drops=0, + buffer_duration_ns=30_000_000_000, + segment_count=15, + input_fps=59.94, + recording_fps=60.0, + ) + + +def _commands() -> list[WorkerCommand]: + request_id = uuid4() + return [ + StartRecording(request_id=request_id, input_config=NdiInputConfig("PC-A (OBS)")), + PrepareReplay(request_id=request_id), + ResumeRecording(request_id=request_id), + ChangeInput(request_id=request_id, input_config=NdiInputConfig("PC-B (OBS)")), + DiscoverInputs(request_id=request_id), + Shutdown(), + ] + + +def _events() -> list[WorkerEvent]: + request_id = uuid4() + return [ + WorkerStateChanged(state=WorkerState.RECORDING), + InputsDiscovered( + request_id=request_id, + inputs=(NdiInputDescriptor("PC-A (OBS)"),), + ), + StreamStarted(stream_info=_stream_info()), + RecordingMetricsUpdated(metrics=_metrics()), + ReplayPrepared( + request_id=request_id, + asset=ReplayAsset(Path("replay.mkv"), 30_000_000_000, Fraction(60, 1)), + ), + WorkerError( + code=WorkerErrorCode.ENCODER_FAILED, message="encoder failed", request_id=request_id + ), + WorkerError(code=WorkerErrorCode.INTERNAL_ERROR, message="no request"), + ] + + +@pytest.mark.parametrize("command", _commands()) +def test_command_pickle_round_trip(command: WorkerCommand) -> None: + restored = pickle.loads(pickle.dumps(command)) + assert restored == command + assert type(restored) is type(command) + + +@pytest.mark.parametrize("event", _events()) +def test_event_pickle_round_trip(event: WorkerEvent) -> None: + restored = pickle.loads(pickle.dumps(event)) + assert restored == event + assert type(restored) is type(event) + + +def test_pickled_request_id_is_a_uuid() -> None: + request_id = uuid4() + restored = pickle.loads(pickle.dumps(PrepareReplay(request_id))) + assert isinstance(restored.request_id, UUID) + assert restored.request_id == request_id diff --git a/tests/test_worker_queues.py b/tests/test_worker_queues.py new file mode 100644 index 0000000..95c74a0 --- /dev/null +++ b/tests/test_worker_queues.py @@ -0,0 +1,100 @@ +"""FrameQueues: drop-oldest, hold-back gating and cross-stream ordering.""" + +from fractions import Fraction + +import numpy as np + +from quickreplay.input.models import AudioFrame, VideoFrame +from quickreplay.worker.frame_queues import FrameQueues + +FPS = Fraction(60, 1) + + +def _video(timestamp_ns: int) -> VideoFrame: + return VideoFrame(timestamp_ns, 4, 2, FPS, "BGR24", np.zeros((2, 4, 3), dtype=np.uint8)) + + +def _audio(timestamp_ns: int, samples: int = 10) -> AudioFrame: + return AudioFrame(timestamp_ns, 48000, 2, samples, np.zeros((2, samples), dtype=np.float32)) + + +def test_video_drop_oldest_keeps_newest() -> None: + queues = FrameQueues(video_capacity=2, audio_capacity=2) + + queues.put_video(_video(1)) + queues.put_video(_video(2)) + queues.put_video(_video(3)) + + assert queues.drop_counts() == (1, 0) + queues.begin_drain() + first = queues.take_next(holdback_ns=0, expect_audio=True) + second = queues.take_next(holdback_ns=0, expect_audio=True) + assert first is not None and first.timestamp_ns == 2 + assert second is not None and second.timestamp_ns == 3 + assert queues.take_next(holdback_ns=0, expect_audio=True) is None + + +def test_audio_drop_oldest_keeps_newest() -> None: + queues = FrameQueues(video_capacity=2, audio_capacity=2) + + queues.put_audio(_audio(1)) + queues.put_audio(_audio(2)) + queues.put_audio(_audio(3)) + + assert queues.drop_counts() == (0, 1) + queues.begin_drain() + first = queues.take_next(holdback_ns=0, expect_audio=True) + assert first is not None and first.timestamp_ns == 2 + + +def test_holdback_gates_until_newest_moves() -> None: + queues = FrameQueues(video_capacity=8, audio_capacity=8) + queues.put_video(_video(0)) + queues.put_video(_video(100)) + + assert queues.take_next(holdback_ns=150, expect_audio=True) is None + + queues.put_video(_video(200)) + first = queues.take_next(holdback_ns=150, expect_audio=True) + assert first is not None and first.timestamp_ns == 0 + + +def test_video_only_has_no_holdback() -> None: + queues = FrameQueues(video_capacity=4, audio_capacity=4) + queues.put_video(_video(0)) + + first = queues.take_next(holdback_ns=1_000_000_000, expect_audio=False) + + assert first is not None and first.timestamp_ns == 0 + + +def test_merge_picks_oldest_across_streams() -> None: + queues = FrameQueues(video_capacity=8, audio_capacity=8) + queues.put_video(_video(20)) + queues.put_audio(_audio(10)) + queues.begin_drain() + + first = queues.take_next(holdback_ns=0, expect_audio=True) + second = queues.take_next(holdback_ns=0, expect_audio=True) + assert first is not None and first.timestamp_ns == 10 + assert second is not None and second.timestamp_ns == 20 + + +def test_begin_drain_releases_holdback() -> None: + queues = FrameQueues(video_capacity=4, audio_capacity=4) + queues.put_video(_video(0)) + assert queues.take_next(holdback_ns=1_000, expect_audio=True) is None + + queues.begin_drain() + + assert queues.draining + item = queues.take_next(holdback_ns=1_000, expect_audio=True) + assert item is not None and item.timestamp_ns == 0 + + +def test_capacities_must_be_positive() -> None: + try: + FrameQueues(video_capacity=0, audio_capacity=4) + except ValueError: + return + raise AssertionError("expected ValueError") diff --git a/tests/test_worker_runtime.py b/tests/test_worker_runtime.py new file mode 100644 index 0000000..ba8e4cd --- /dev/null +++ b/tests/test_worker_runtime.py @@ -0,0 +1,399 @@ +"""RecorderWorkerRuntime: state machine, replay lifecycle and error handling.""" + +import pickle +from fractions import Fraction +from pathlib import Path +from uuid import UUID, uuid4 + +from fake_worker_input import ( + FakeInputSource, + ScriptedInputFactory, + WorkerHarness, + video_frame, + video_info, +) + +from quickreplay.input.models import ( + NdiInputConfig, + NdiInputDescriptor, + StreamInfo, +) +from quickreplay.recording.commands import ( + ChangeInput, + DiscoverInputs, + PrepareReplay, + ResumeRecording, + Shutdown, + StartRecording, + StopSession, +) +from quickreplay.recording.events import ( + InputsDiscovered, + RecordingMetricsUpdated, + ReplayPrepared, + SessionStopped, + StreamStarted, + WorkerError, +) +from quickreplay.recording.models import WorkerErrorCode, WorkerState +from quickreplay.replay.asset_builder import ReplayAssetBuilder +from quickreplay.replay.errors import ReplayRemuxError +from quickreplay.worker.inputs import InputSourceHandle +from quickreplay.worker.settings import RecorderWorkerSettings + +FPS = Fraction(60, 1) + + +def _settings(tmp_path: Path, **overrides: int) -> RecorderWorkerSettings: + defaults: dict[str, int] = { + "metrics_interval_ns": 20_000_000, + "stream_start_timeout_ns": 2_000_000_000, + "video_queue_capacity": 4096, + "audio_queue_capacity": 4096, + } + defaults.update(overrides) + return RecorderWorkerSettings(working_directory=tmp_path, **defaults) + + +def _start(harness: WorkerHarness) -> UUID: + harness.start() + harness.wait_state(WorkerState.IDLE) + request_id = uuid4() + harness.send(StartRecording(request_id, NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + return request_id + + +def _wait_captured(harness: WorkerHarness, factory: ScriptedInputFactory) -> None: + harness.wait_event( + RecordingMetricsUpdated, + predicate=lambda event: ( + event.metrics.captured_video_frames >= factory.video_frames + and event.metrics.captured_audio_samples >= factory.audio_samples + ), + timeout=10.0, + description="all frames captured", + ) + + +def test_stream_started_request_id_protocol() -> None: + info = StreamInfo(video=video_info(FPS), audio=None) + assert StreamStarted(info).request_id is None + request_id = uuid4() + restored = pickle.loads(pickle.dumps(StreamStarted(info, request_id))) + assert restored.request_id == request_id + + +def test_start_recording(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + harness = WorkerHarness(_settings(tmp_path), input_factory=factory) + try: + harness.start() + harness.wait_state(WorkerState.IDLE) + request_id = uuid4() + harness.send(StartRecording(request_id, NdiInputConfig("fake"))) + harness.wait_state(WorkerState.STARTING) + harness.wait_state(WorkerState.RECORDING) + started = harness.wait_event(StreamStarted) + assert started.request_id == request_id + assert started.stream_info.audio is not None + assert factory.calls == 1 + finally: + harness.shutdown() + + +def test_metrics_are_emitted(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + harness = WorkerHarness(_settings(tmp_path), input_factory=factory) + try: + _start(harness) + metrics = harness.wait_event( + RecordingMetricsUpdated, + predicate=lambda event: event.metrics.captured_video_frames > 0, + timeout=5.0, + ) + assert metrics.metrics.input_fps >= 0 + assert metrics.metrics.recording_fps >= 0 + finally: + harness.shutdown() + + +def test_prepare_replay_builds_and_cleans_up(tmp_path: Path, probe) -> None: + factory = ScriptedInputFactory(duration_ns=2_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness(settings, input_factory=factory) + try: + _start(harness) + _wait_captured(harness, factory) + request_id = uuid4() + harness.send(PrepareReplay(request_id)) + harness.wait_state(WorkerState.FREEZING) + harness.wait_state(WorkerState.FROZEN) + prepared = harness.wait_event(ReplayPrepared) + + assert prepared.request_id == request_id + assert prepared.asset.path.exists() + facts = probe(prepared.asset.path) + assert facts.decoded_video_frames == factory.video_frames + assert facts.audio_samples == factory.audio_samples + assert list(settings.buffer_root.iterdir()) == [] + finally: + harness.shutdown() + + +def test_resume_starts_a_new_session(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness(settings, input_factory=factory) + try: + _start(harness) + _wait_captured(harness, factory) + harness.send(PrepareReplay(uuid4())) + prepared = harness.wait_event(ReplayPrepared) + replay_path = prepared.asset.path + assert replay_path.exists() + + request_id = uuid4() + harness.send(ResumeRecording(request_id)) + harness.wait_state(WorkerState.STARTING) + harness.wait_state(WorkerState.RECORDING) + started = harness.wait_event( + StreamStarted, predicate=lambda event: event.request_id == request_id + ) + + assert factory.calls == 2 + assert factory.sources[0] is not factory.sources[1] + assert factory.sources[0].close_count >= 1 + assert not replay_path.exists() + assert started.request_id == request_id + directories = [path for path in settings.buffer_root.iterdir() if path.is_dir()] + assert len(directories) == 1 + finally: + harness.shutdown() + + +def test_stop_session_cleans_recording_and_allows_restart(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness(settings, input_factory=factory) + try: + first_start_id = _start(harness) + _wait_captured(harness, factory) + first_pipeline = harness.runtime._pipeline + assert first_pipeline is not None + first_session = first_pipeline.session + assert first_session is not None + first_session_id = first_session.id + first_epoch_ns = first_session.epoch_ns + request_id = uuid4() + harness.send(StopSession(request_id)) + harness.wait_state(WorkerState.IDLE) + stopped = harness.wait_event(SessionStopped) + assert stopped.request_id == request_id + assert list(settings.buffer_root.iterdir()) == [] + assert harness.runtime._config is None + assert harness.runtime._pipeline is None + assert factory.sources[0].close_count >= 1 + + second_start_id = uuid4() + assert second_start_id != first_start_id + harness.send(StartRecording(second_start_id, NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + restarted = harness.wait_event( + StreamStarted, predicate=lambda event: event.request_id == second_start_id + ) + second_pipeline = harness.runtime._pipeline + assert second_pipeline is not None + assert second_pipeline is not first_pipeline + second_session = second_pipeline.session + assert second_session is not None + assert second_session.id != first_session_id + assert second_session.epoch_ns != first_epoch_ns + assert restarted.request_id == second_start_id + assert factory.calls == 2 + assert factory.sources[0] is not factory.sources[1] + assert factory.sources[1].close_count == 0 + assert first_pipeline._metrics is not second_pipeline._metrics + finally: + harness.shutdown() + + +def test_stop_session_cleans_frozen_replay(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness(settings, input_factory=factory) + try: + _start(harness) + _wait_captured(harness, factory) + harness.send(PrepareReplay(uuid4())) + prepared = harness.wait_event(ReplayPrepared) + assert prepared.asset.path.exists() + + request_id = uuid4() + harness.send(StopSession(request_id)) + harness.wait_state(WorkerState.IDLE) + stopped = harness.wait_event(SessionStopped) + assert stopped.request_id == request_id + assert not prepared.asset.path.exists() + + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + finally: + harness.shutdown() + + +def test_change_input_starts_a_new_session(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + harness = WorkerHarness(_settings(tmp_path), input_factory=factory) + try: + _start(harness) + _wait_captured(harness, factory) + request_id = uuid4() + harness.send(ChangeInput(request_id, NdiInputConfig("cam"))) + harness.wait_state(WorkerState.STOPPING) + harness.wait_state(WorkerState.RECORDING) + started = harness.wait_event( + StreamStarted, predicate=lambda event: event.request_id == request_id + ) + assert factory.calls == 2 + assert started.request_id == request_id + assert factory.sources[0].close_count >= 1 + # The previous session was fully cleaned up: only the new session + # directory remains and no writer temporary file is left behind. + settings = _settings(tmp_path) + directories = [entry for entry in settings.buffer_root.iterdir() if entry.is_dir()] + assert len(directories) == 1 + assert list(settings.buffer_root.rglob("*.tmp.mkv")) == [] + finally: + harness.shutdown() + + +def test_discover_inputs(tmp_path: Path) -> None: + descriptor = NdiInputDescriptor("PC (OBS)") + harness = WorkerHarness( + _settings(tmp_path), + input_factory=ScriptedInputFactory(), + discovery=lambda **_kwargs: (descriptor,), + ) + try: + harness.start() + harness.wait_state(WorkerState.IDLE) + request_id = uuid4() + harness.send(DiscoverInputs(request_id)) + event = harness.wait_event(InputsDiscovered) + assert event.request_id == request_id + assert event.inputs == (descriptor,) + finally: + harness.shutdown() + + +def test_invalid_commands_are_rejected(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + harness = WorkerHarness(_settings(tmp_path), input_factory=factory) + try: + harness.start() + harness.wait_state(WorkerState.IDLE) + request_id = uuid4() + harness.send(PrepareReplay(request_id)) + error = harness.wait_event( + WorkerError, predicate=lambda event: event.request_id == request_id + ) + assert error.code == WorkerErrorCode.INTERNAL_ERROR + + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + harness.send(ResumeRecording(uuid4())) + rejected = harness.wait_event( + WorkerError, predicate=lambda event: event.request_id is not None + ) + assert rejected.code == WorkerErrorCode.INTERNAL_ERROR + assert harness.runtime.state == WorkerState.RECORDING + finally: + harness.shutdown() + + +def test_capture_failure_enters_error(tmp_path: Path) -> None: + def factory(_config) -> InputSourceHandle: + source = FakeInputSource( + [video_frame(1_000_000_000, fps=FPS), ValueError("capture exploded")], + video_stream=video_info(FPS), + ) + return InputSourceHandle(source=source, supports_audio=False) + + harness = WorkerHarness(_settings(tmp_path), input_factory=factory) + try: + harness.start() + harness.wait_state(WorkerState.IDLE) + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + error = harness.wait_event(WorkerError, timeout=5.0) + harness.wait_state(WorkerState.ERROR) + assert error.code == WorkerErrorCode.INTERNAL_ERROR + finally: + harness.shutdown() + + +def _failing_remux(segments, tmp_path) -> None: + raise ReplayRemuxError("injected replay failure") + + +def test_replay_failure_enters_error(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness( + settings, + input_factory=factory, + builder_factory=lambda: ReplayAssetBuilder(remux=_failing_remux), + ) + try: + _start(harness) + _wait_captured(harness, factory) + request_id = uuid4() + harness.send(PrepareReplay(request_id)) + error = harness.wait_event(WorkerError, timeout=5.0) + harness.wait_state(WorkerState.ERROR) + assert error.code == WorkerErrorCode.REPLAY_ASSET_FAILED + assert error.request_id == request_id + assert not any(isinstance(event, ReplayPrepared) for event in harness.seen) + assert not (settings.replay_root / str(request_id)).exists() + finally: + harness.shutdown() + + +def test_shutdown_during_recording(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=2_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness(settings, input_factory=factory) + harness.start() + harness.wait_state(WorkerState.IDLE) + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + harness.send(Shutdown()) + harness.wait_state(WorkerState.SHUTTING_DOWN) + harness.join(timeout=10.0) + + assert not harness.thread.is_alive() + assert factory.sources[0].close_count >= 1 + assert list(settings.buffer_root.iterdir()) == [] + assert list(settings.buffer_root.rglob("*.tmp.mkv")) == [] + + +def test_shutdown_after_replay_removes_asset(tmp_path: Path) -> None: + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + settings = _settings(tmp_path) + harness = WorkerHarness(settings, input_factory=factory) + harness.start() + harness.wait_state(WorkerState.IDLE) + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + _wait_captured(harness, factory) + harness.send(PrepareReplay(uuid4())) + prepared = harness.wait_event(ReplayPrepared) + replay_path = prepared.asset.path + + harness.send(Shutdown()) + harness.wait_state(WorkerState.SHUTTING_DOWN) + harness.join(timeout=10.0) + + assert not harness.thread.is_alive() + assert not replay_path.exists() diff --git a/tmp_video/memo.txt b/tmp_video/memo.txt deleted file mode 100644 index db87622..0000000 --- a/tmp_video/memo.txt +++ /dev/null @@ -1 +0,0 @@ -ここにリプレイ用動画が一時保存されます \ No newline at end of file diff --git a/tools/__init__.py b/tools/__init__.py new file mode 100644 index 0000000..984c8a0 --- /dev/null +++ b/tools/__init__.py @@ -0,0 +1 @@ +"""Small release and development helpers.""" diff --git a/tools/package_windows_release.py b/tools/package_windows_release.py new file mode 100644 index 0000000..c811447 --- /dev/null +++ b/tools/package_windows_release.py @@ -0,0 +1,58 @@ +"""Stage the Flet Windows build and create the portable release ZIP.""" + +from __future__ import annotations + +import argparse +import shutil +import tomllib +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + +ROOT = Path(__file__).resolve().parents[1] + + +def read_project_version(pyproject: Path = ROOT / "pyproject.toml") -> str: + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) + return str(data["project"]["version"]) + + +def create_distribution( + *, + build_dir: Path = ROOT / "build" / "windows", + output_dir: Path = ROOT / "dist", +) -> Path: + version = read_project_version() + staging_root = output_dir / "QuickReplay" + archive = output_dir / f"QuickReplay-{version}-windows-x64.zip" + + if not build_dir.is_dir(): + raise FileNotFoundError(f"Flet build output does not exist: {build_dir}") + if output_dir.exists(): + shutil.rmtree(output_dir) + staging_root.mkdir(parents=True) + for item in build_dir.iterdir(): + destination = staging_root / item.name + if item.is_dir(): + shutil.copytree(item, destination) + else: + shutil.copy2(item, destination) + shutil.copy2(ROOT / "LICENSE", staging_root / "LICENSE") + shutil.copy2(ROOT / "LICENSE_ThirdParty.md", staging_root / "LICENSE_ThirdParty.md") + + with ZipFile(archive, "w", compression=ZIP_DEFLATED) as zip_file: + for path in staging_root.rglob("*"): + if path.is_file(): + zip_file.write(path, path.relative_to(output_dir).as_posix()) + return archive + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--build-dir", type=Path, default=ROOT / "build" / "windows") + parser.add_argument("--output-dir", type=Path, default=ROOT / "dist") + args = parser.parse_args() + print(create_distribution(build_dir=args.build_dir, output_dir=args.output_dir)) + + +if __name__ == "__main__": + main() diff --git a/tools/stress_worker_cleanup.py b/tools/stress_worker_cleanup.py new file mode 100644 index 0000000..09c0444 --- /dev/null +++ b/tools/stress_worker_cleanup.py @@ -0,0 +1,136 @@ +"""Windows-local stress test for recording-session cleanup. + +Runs the recorder worker runtime repeatedly through ChangeInput / Shutdown and +reports any iteration that leaves a temporary segment file or an uncleaned +session directory behind. This complements (and does not replace) the pytest +regression tests. + +Usage:: + + uv run python tools/stress_worker_cleanup.py --mode change-input --iterations 100 + uv run python tools/stress_worker_cleanup.py --mode shutdown --iterations 100 + uv run python tools/stress_worker_cleanup.py --mode combined --iterations 100 +""" + +import argparse +import sys +import tempfile +from pathlib import Path +from uuid import uuid4 + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tests")) + +from fake_worker_input import ScriptedInputFactory, WorkerHarness # noqa: E402 + +from quickreplay.input.models import NdiInputConfig # noqa: E402 +from quickreplay.recording.commands import ChangeInput, Shutdown, StartRecording # noqa: E402 +from quickreplay.recording.events import RecordingMetricsUpdated # noqa: E402 +from quickreplay.recording.models import WorkerState # noqa: E402 +from quickreplay.worker.settings import RecorderWorkerSettings # noqa: E402 + + +def _settings(tmp: Path) -> RecorderWorkerSettings: + return RecorderWorkerSettings( + working_directory=tmp, + metrics_interval_ns=20_000_000, + stream_start_timeout_ns=2_000_000_000, + video_queue_capacity=4096, + audio_queue_capacity=4096, + ) + + +def _start(harness: WorkerHarness, factory: ScriptedInputFactory) -> None: + harness.start() + harness.wait_state(WorkerState.IDLE) + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + harness.wait_event( + RecordingMetricsUpdated, + predicate=lambda event: event.metrics.captured_video_frames >= factory.video_frames, + ) + + +def _check_cleanup(tmp: Path, *, expect_session_dirs: int) -> str: + leftover = [str(path.relative_to(tmp)) for path in tmp.rglob("*.tmp.mkv")] + buffer_root = tmp / "buffer" + directories = ( + [entry for entry in buffer_root.iterdir() if entry.is_dir()] if buffer_root.exists() else [] + ) + problems = [] + if leftover: + problems.append(f"tmp files remain: {leftover}") + if len(directories) != expect_session_dirs: + problems.append(f"session dirs={len(directories)} expected={expect_session_dirs}") + return "; ".join(problems) + + +def _change_input(iterations: int) -> int: + failures = 0 + for index in range(iterations): + tmp = Path(tempfile.mkdtemp(prefix="qr_stress_ci_")) + factory = ScriptedInputFactory(duration_ns=1_000_000_000) + harness = WorkerHarness(_settings(tmp), input_factory=factory) + problem = "" + try: + _start(harness, factory) + harness.send(ChangeInput(uuid4(), NdiInputConfig("replacement"))) + harness.wait_state(WorkerState.RECORDING, timeout=5.0) + problem = _check_cleanup(tmp, expect_session_dirs=1) + except AssertionError as exc: + problem = str(exc) + finally: + try: + harness.shutdown() + except Exception: # noqa: BLE001 - best effort + pass + if problem: + failures += 1 + print(f"change-input {index}: FAIL {problem}", flush=True) + return failures + + +def _shutdown(iterations: int) -> int: + failures = 0 + for index in range(iterations): + tmp = Path(tempfile.mkdtemp(prefix="qr_stress_sd_")) + factory = ScriptedInputFactory(duration_ns=2_000_000_000) + harness = WorkerHarness(_settings(tmp), input_factory=factory) + problem = "" + try: + harness.start() + harness.wait_state(WorkerState.IDLE) + harness.send(StartRecording(uuid4(), NdiInputConfig("fake"))) + harness.wait_state(WorkerState.RECORDING) + harness.send(Shutdown()) + harness.wait_state(WorkerState.SHUTTING_DOWN) + harness.join(timeout=10.0) + problem = _check_cleanup(tmp, expect_session_dirs=0) + except AssertionError as exc: + problem = str(exc) + if problem: + failures += 1 + print(f"shutdown {index}: FAIL {problem}", flush=True) + return failures + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "--mode", choices=("change-input", "shutdown", "combined"), default="combined" + ) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + + failures = 0 + if args.mode in ("change-input", "combined"): + failures += _change_input(args.iterations) + if args.mode in ("shutdown", "combined"): + failures += _shutdown(args.iterations) + + total = args.iterations * (2 if args.mode == "combined" else 1) + print(f"iterations={total} failures={failures}") + return 1 if failures else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/verify_replay_controller.py b/tools/verify_replay_controller.py new file mode 100644 index 0000000..da74a53 --- /dev/null +++ b/tools/verify_replay_controller.py @@ -0,0 +1,183 @@ +"""Manual local verification of ReplayController against a real mpv process. + +This is not part of the automated test suite. It builds a replay asset with +the existing recording/remux pipeline and drives it through mpv, printing the +observed playback positions. + +Usage:: + + uv run python tools/verify_replay_controller.py [path/to/mpv[.exe]] +""" + +import sys +import tempfile +import time +from fractions import Fraction +from pathlib import Path +from uuid import uuid4 + +import numpy as np + +from quickreplay.input.models import ( + AudioFrame, + AudioStreamInfo, + StreamInfo, + VideoFrame, + VideoStreamInfo, +) +from quickreplay.recording.models import RecordingSession +from quickreplay.recording.ring_storage import RingStorage +from quickreplay.recording.segment_recorder import SegmentRecorder +from quickreplay.replay.asset_builder import ReplayAssetBuilder +from quickreplay.replay.controller import ReplayController, ReplayControllerSettings +from quickreplay.replay.errors import MpvProcessExitedError +from quickreplay.replay.models import ReplayAsset, ReplaySnapshot +from quickreplay.units import NANOSECONDS_PER_SECOND, round_fraction + +FPS = Fraction(60, 1) +WIDTH, HEIGHT = 320, 180 +SAMPLE_RATE = 48000 +CHANNELS = 2 +DURATION_NS = 6_000_000_000 + + +def build_replay(directory: Path) -> Path: + info = StreamInfo( + video=VideoStreamInfo(WIDTH, HEIGHT, FPS, "BGR24"), + audio=AudioStreamInfo(SAMPLE_RATE, CHANNELS), + ) + recorder = SegmentRecorder() + recorder.start(RecordingSession(uuid4(), info, 0, directory)) + segments = [] + + events: list[tuple[int, int, VideoFrame | AudioFrame]] = [] + index = 0 + while True: + offset = round_fraction(Fraction(index * NANOSECONDS_PER_SECOND, 1) / FPS) + if offset > DURATION_NS: + break + data = np.full((HEIGHT, WIDTH, 3), index % 256, dtype=np.uint8) + events.append((offset, 0, VideoFrame(offset, WIDTH, HEIGHT, FPS, "BGR24", data))) + index += 1 + + total_samples = int(Fraction(DURATION_NS) * SAMPLE_RATE / NANOSECONDS_PER_SECOND) + position = 0 + while position < total_samples: + count = min(1024, total_samples - position) + timestamp = round_fraction(Fraction(position * NANOSECONDS_PER_SECOND, SAMPLE_RATE)) + audio = np.zeros((CHANNELS, count), dtype=np.float32) + events.append((timestamp, 1, AudioFrame(timestamp, SAMPLE_RATE, CHANNELS, count, audio))) + position += count + + events.sort(key=lambda event: (event[0], event[1])) + for _timestamp, _kind, frame in events: + if isinstance(frame, VideoFrame): + segments.extend(recorder.push_video(frame)) + else: + recorder.push_audio(frame) + + last = recorder.finish() + if last is not None: + segments.append(last) + recorder.close() + + ring = RingStorage(buffer_duration_ns=60 * NANOSECONDS_PER_SECOND) + for segment in segments: + ring.add(segment) + with ring.snapshot() as lease: + snapshot = ReplaySnapshot(segments=lease.segments, stream_info=info) + asset = ReplayAssetBuilder().build(snapshot, directory / "replay") + ring.clear() + return asset.path + + +def main() -> int: + executable = sys.argv[1] if len(sys.argv) > 1 else "mpv" + with tempfile.TemporaryDirectory(prefix="qr_controller_") as tmp: + directory = Path(tmp) + asset_path = build_replay(directory) + print(f"replay asset: {asset_path}", flush=True) + + settings = ReplayControllerSettings(mpv_executable=executable) + controller = ReplayController(settings) + ok = True + try: + controller.open(ReplayAsset(asset_path, DURATION_NS, FPS)) + print(f"opened; paused={controller.is_paused()} position={controller.position_ns()}") + + controller.play() + time.sleep(0.6) + moving = controller.position_ns() + controller.pause() + time.sleep(0.3) + stable = controller.position_ns() + print(f"play -> {moving} ns; pause -> {stable} ns") + ok = ok and moving > 0 and abs(stable - moving) < 40_000_000 + + boundary_ns = 2_000_000_000 + controller.seek_absolute_ns(boundary_ns - 50_000_000) + time.sleep(0.3) + forward = [] + for _ in range(5): + controller.step_forward() + time.sleep(0.1) + forward.append(controller.position_ns()) + print("forward steps:", [round(p / 1e6, 1) for p in forward]) + + backward = [] + for _ in range(5): + controller.step_backward() + time.sleep(0.1) + backward.append(controller.position_ns()) + print("backward steps:", [round(p / 1e6, 1) for p in backward]) + + ok = ok and all(b > a for a, b in zip(forward, forward[1:], strict=False)) + ok = ok and all(b < a for a, b in zip(backward, backward[1:], strict=False)) + ok = ok and forward[0] < boundary_ns < forward[-1] + ok = ok and backward[0] > boundary_ns > backward[-1] + + controller.seek_absolute_ns(1_000_000_000) + time.sleep(0.3) + before = controller.position_ns() + controller.seek_frames(20) + time.sleep(0.3) + after = controller.position_ns() + print(f"+20 frames: {before} -> {after} (delta {after - before} ns)") + expected = int(Fraction(20, 1) / FPS * NANOSECONDS_PER_SECOND) + ok = ok and abs((after - before) - expected) < 20_000_000 + + controller.seek_absolute_ns(3_000_000_000) + time.sleep(0.3) + mid = controller.position_ns() + print(f"absolute seek to 3.0s -> {mid} ns") + ok = ok and abs(mid - 3_000_000_000) < 40_000_000 + + point = controller.set_point() + controller.seek_frames(10) + time.sleep(0.2) + print( + f"set point: time diff {controller.time_difference_ns(point)} ns, " + f"frame diff {controller.frame_difference(point)}" + ) + + # Simulate an external window close and confirm detection. + ipc = getattr(controller, "_ipc", None) # noqa: B009 - verification tool + if ipc is not None: + ipc.command("quit", wait=False) + time.sleep(0.5) + try: + controller.play() + except MpvProcessExitedError: + print("unexpected exit detected: MpvProcessExitedError") + else: + print("unexpected exit NOT detected") + ok = False + finally: + controller.close() + + print("RESULT:", "PASS" if ok else "FAIL") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..95b2758 --- /dev/null +++ b/uv.lock @@ -0,0 +1,866 @@ +version = 1 +revision = 3 +requires-python = ">=3.14" + +[[package]] +name = "anyio" +version = "4.15.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, +] + +[[package]] +name = "arrow" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b9/33/032cdc44182491aa708d06a68b62434140d8c50820a087fac7af37703357/arrow-1.4.0.tar.gz", hash = "sha256:ed0cc050e98001b8779e84d461b0098c4ac597e88704a655582b21d116e526d7", size = 152931, upload-time = "2025-10-18T17:46:46.761Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ed/c9/d7977eaacb9df673210491da99e6a247e93df98c715fc43fd136ce1d3d33/arrow-1.4.0-py3-none-any.whl", hash = "sha256:749f0769958ebdc79c173ff0b0670d59051a535fa26e8eba02953dc19eb43205", size = 68797, upload-time = "2025-10-18T17:46:45.663Z" }, +] + +[[package]] +name = "av" +version = "18.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8d/f4/f22114d30d3435e38c6af2b4870f37b864403dca6ae7af747a289ce0a18e/av-18.1.0.tar.gz", hash = "sha256:47bfc286e1bc9de7ab4681fc2b575cd2460a66919d31ffe1bd5aa54fae531a28", size = 4451061, upload-time = "2026-08-12T22:28:18.761Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/d4/d7cdc8bff143c17a6d35924375ae28dd692cacde38700a7d419fde54f44a/av-18.1.0-cp311-abi3-macosx_11_0_x86_64.whl", hash = "sha256:ae75d8bb6467895ed1f8572ededf7ffa49eac07f6e483222f5d7d62a41d12f04", size = 22546147, upload-time = "2026-08-12T22:27:11.851Z" }, + { url = "https://files.pythonhosted.org/packages/3f/c9/37a619297492256b77d5ed906e7d8166c10a26ed251dccf1ae03ab19bff6/av-18.1.0-cp311-abi3-macosx_14_0_arm64.whl", hash = "sha256:b30a4e8d934558e19602b68998a4d9ac9f250fa0dacef216f7e8e40153b13316", size = 18217603, upload-time = "2026-08-12T22:27:14.713Z" }, + { url = "https://files.pythonhosted.org/packages/d9/84/2464ffb64c08c5ce8b522c8e74594714414e3b0575267652c5c51c0574b9/av-18.1.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:6fc837cc51adf80331ac850779cd53b5d4c4460b0ebe9057a02a921c6736f19d", size = 33640142, upload-time = "2026-08-12T22:27:17.835Z" }, + { url = "https://files.pythonhosted.org/packages/27/3a/204dbfc3e08eb4cdc6e6ff57be02150bc44523ebdb50182d10025792ebd9/av-18.1.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:8a032e8d8ebc73dec079364b9b4a6837638a2d106e8472314e685ffbf163e700", size = 35786210, upload-time = "2026-08-12T22:27:20.984Z" }, + { url = "https://files.pythonhosted.org/packages/e1/99/b0d04ec553ff9a7e00455458dfa3a39c8a8f627b273056b4e5fe57d590de/av-18.1.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:3c8b1f8b46f99d52e2d8b0ed5d0cdadf172d24794d46e2077b16e44ed08e26ff", size = 39379798, upload-time = "2026-08-12T22:27:24.432Z" }, + { url = "https://files.pythonhosted.org/packages/56/b1/e00d4feae59160149df6126585e726fdc6300798fd40c5dd324879e81f68/av-18.1.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:ab5ac081bc9eaf54109120d4e56284674fecfbe520d9aa1707c7fa911ec5f4d2", size = 34690321, upload-time = "2026-08-12T22:27:27.769Z" }, + { url = "https://files.pythonhosted.org/packages/dc/94/836fa987e3084d11a21489f11357fb24843ef3aa8faf74ddddfc603d5062/av-18.1.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:191224788d87af06c31784a395bb73f14b72f33d7f4871ace0157de2abdc6276", size = 36859932, upload-time = "2026-08-12T22:27:31.403Z" }, + { url = "https://files.pythonhosted.org/packages/33/b4/76ba21e46704f632004276b85289a1582e95f5eff760436d6149875a1881/av-18.1.0-cp311-abi3-win_amd64.whl", hash = "sha256:ea1480b7a8d5405cb5f382b344731bf125fd2c1c6fae3964f6c48595628387ff", size = 27595679, upload-time = "2026-08-12T22:27:35.177Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ad/a3135884c5753b09773176b97201ae602f67ad14206c395ff838d66bf9b0/av-18.1.0-cp311-abi3-win_arm64.whl", hash = "sha256:5509ec12aaa19fd6601de13cfa6f4cdad450da07982118510592875d970454d6", size = 20257584, upload-time = "2026-08-12T22:27:38.472Z" }, + { url = "https://files.pythonhosted.org/packages/4f/5b/4a756265d7fb164336c8d377bca21c39cfa2c178be23cedee840a69b59c5/av-18.1.0-cp314-cp314t-macosx_11_0_x86_64.whl", hash = "sha256:b36b0bae9e4c62f9487c99481ec15e4e3870fcc868522cd6d18fc2d6bfa04f01", size = 22795654, upload-time = "2026-08-12T22:27:42.016Z" }, + { url = "https://files.pythonhosted.org/packages/d5/cc/1bc841462114a1adf4f7d87456ab78a6972e23271e71865fcd2bbd0e7360/av-18.1.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:025f84494cb23278498f03b0d8117d3e47a1cbc9c44b97eb31875cf02251e46b", size = 18435735, upload-time = "2026-08-12T22:27:45.787Z" }, + { url = "https://files.pythonhosted.org/packages/b8/20/005500ed17a2e62a5e4bb94aa3786942560ec2f55ec1895ebf174c87abef/av-18.1.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:08a9ae288299cfcbf739dba4ad0c53b9b71f45184303dd45947920d022fed695", size = 37090807, upload-time = "2026-08-12T22:27:50.14Z" }, + { url = "https://files.pythonhosted.org/packages/5c/f7/11e7f6d848d3690c31ca4f8578167393e619177f1493ccc93b9400852d4e/av-18.1.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:cf8a17466bef07765dbdecc9e66ed9b25d20b4e14f654fbf35345a58ac45fa0c", size = 38976836, upload-time = "2026-08-12T22:27:54.565Z" }, + { url = "https://files.pythonhosted.org/packages/c3/63/b271473b24e806062d31191e40c6d65545e9cf59f80f044eba56dcbba0f4/av-18.1.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d49a5c542dfdc00f43c6cdb6cc41dac1781ee206fe180b56aa7433dfa816dfae", size = 40896630, upload-time = "2026-08-12T22:27:59.118Z" }, + { url = "https://files.pythonhosted.org/packages/6b/9f/2ab7fa292a947ad3466ed8e655eefa3b82f535d7ea598c297b4471a937c4/av-18.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5548b79e2bf1f59b3e9aedc918a72d9dc45b9adaac10ff9470d5dbdda0002e47", size = 37895673, upload-time = "2026-08-12T22:28:03.98Z" }, + { url = "https://files.pythonhosted.org/packages/e9/d8/04507c57249b399c3e4f23f01d221532f357338b5316fd2858fbd343127d/av-18.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e7ea063f6690193ea335a1d592d6e0274350d45e2ed6af83ee107cb90cbfd84f", size = 39992431, upload-time = "2026-08-12T22:28:08.736Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d6/bc4b95bea9c2353a7e4d62a3fcfad9adcf0f881741c6ce01ee179d539ce3/av-18.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:e4d48b9f12cad009cc72fe4f4099107de5e819c95f82767f4fd01a01481c0661", size = 28497798, upload-time = "2026-08-12T22:28:13.003Z" }, + { url = "https://files.pythonhosted.org/packages/c1/d2/0c277a46f12647c1833f40496e132fb6001e0d19e6144b5ea30896461feb/av-18.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:5cd9085028902c9880622bd37a12fd4b33060f06a52311f6f4867ca9f29a2c3b", size = 21421979, upload-time = "2026-08-12T22:28:16.48Z" }, +] + +[[package]] +name = "binaryornot" +version = "0.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "chardet" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a7/fe/7ebfec74d49f97fc55cd38240c7a7d08134002b1e14be8c3897c0dd5e49b/binaryornot-0.4.4.tar.gz", hash = "sha256:359501dfc9d40632edc9fac890e19542db1a287bbcfa58175b66658392018061", size = 371054, upload-time = "2017-08-03T15:55:25.08Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/7e/f7b6f453e6481d1e233540262ccbfcf89adcd43606f44a028d7f5fae5eb2/binaryornot-0.4.4-py2.py3-none-any.whl", hash = "sha256:b8b71173c917bddcd2c16070412e369c3ed7f0528926f70cac18a6c97fd563e4", size = 9006, upload-time = "2017-08-03T15:55:31.23Z" }, +] + +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + +[[package]] +name = "chardet" +version = "5.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/0d/f7b6ab21ec75897ed80c17d79b15951a719226b9fababf1e40ea74d69079/chardet-5.2.0.tar.gz", hash = "sha256:1b3b6ff479a8c414bc3fa2c0852995695c4a026dcd6d0633b2dd092ca39c1cf7", size = 2069618, upload-time = "2023-08-01T19:23:02.662Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/6f/f5fbc992a329ee4e0f288c1fe0e2ad9485ed064cac731ed2fe47dcc38cbf/chardet-5.2.0-py3-none-any.whl", hash = "sha256:e1cf59446890a00105fe7b7912492ea04b6e6f06d4b742b2c788469e34c82970", size = 199385, upload-time = "2023-08-01T19:23:00.661Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/3f/143b048436775b0f76ac3eec145c019e8173ccc2885c8f20319b996d5e83/charset_normalizer-3.5.1.tar.gz", hash = "sha256:6117b84ea48435e5356dc737f5121485c30920ba43375fa7b434fd753df0eac3", size = 171764, upload-time = "2026-08-15T08:20:44.807Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/29/cd/2b812ce5e888f1ce69a5350281e58aab07ae64a958ecae8912f30865718e/charset_normalizer-3.5.1-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:774d157f112367ff4abd29019f38f023c24e00e56edc7829c20e358a5a913ad8", size = 212318, upload-time = "2026-08-15T08:18:04.403Z" }, + { url = "https://files.pythonhosted.org/packages/9e/4a/a6ee107430768a5334e6d63f31f148a04a1a491ef161a1ac9415a73f2fa8/charset_normalizer-3.5.1-cp314-cp314-android_24_x86_64.whl", hash = "sha256:26422d45fd13551cf564c58932f7d72b4f58b93b0fcf18c35ba6be12b46bb102", size = 224897, upload-time = "2026-08-15T08:18:05.997Z" }, + { url = "https://files.pythonhosted.org/packages/c3/d9/35ae3f64f29d0179c35c3baefe575904df2913dde519129c7f75995a2b1d/charset_normalizer-3.5.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:09a7bba9f739468c8e78c36a75c33768e53cb1959fc638f510454c14683f00d5", size = 194848, upload-time = "2026-08-15T08:18:07.397Z" }, + { url = "https://files.pythonhosted.org/packages/74/76/f2fc7380f056cc273a53af37f50d08ad54b2c59f61078f31432edcf1c2bd/charset_normalizer-3.5.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c9548dc78002099910abaebc0a72ac58b7d30931869e0351c09b507dff4ece3", size = 198163, upload-time = "2026-08-15T08:18:08.989Z" }, + { url = "https://files.pythonhosted.org/packages/e9/40/095ce62fa078483cccc1fa2b36e6bc9580b85422a20ee9f925341c50e44f/charset_normalizer-3.5.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:c428c6c31eb5f4277d7f8eccaf767fbd548ddd5ce3c8b4f4cbbfab3d96b5904c", size = 341823, upload-time = "2026-08-15T08:18:10.458Z" }, + { url = "https://files.pythonhosted.org/packages/f1/5a/0e58b1c04a1596e0256f407274a92d5fb2ee21324409d1fab1da48a65b5b/charset_normalizer-3.5.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2f06b7eae9dbe77fe1d644ca244dad508de8d302870a43f3c559b521270938a0", size = 242458, upload-time = "2026-08-15T08:18:11.989Z" }, + { url = "https://files.pythonhosted.org/packages/22/95/b4618ce912e6db0b1aae89ba788e38e8a7eba0f3025cc66e8c0699f977b2/charset_normalizer-3.5.1-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b7430cf5728e68f6c462254009a6ef4086e1bea43cf2f57aa9c55fb4f50ff96", size = 226717, upload-time = "2026-08-15T08:18:13.401Z" }, + { url = "https://files.pythonhosted.org/packages/8a/76/c681192bbda3d55356db5dadd64381d5202b37c6b598fcda5282e88b5d3d/charset_normalizer-3.5.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ab743e9bc90c1f73552ec33e10e3331315acd2c397b36065b591b0181de533cc", size = 266111, upload-time = "2026-08-15T08:18:14.961Z" }, + { url = "https://files.pythonhosted.org/packages/88/be/55127bfca72c0cff6c022488d140d7c5b04c771e3b72e9bdb4836d54979d/charset_normalizer-3.5.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f6f7deae3feb4edfa2efaf7c574fe88cbf055038a6abdb40188e4fff66d5699f", size = 263128, upload-time = "2026-08-15T08:18:16.515Z" }, + { url = "https://files.pythonhosted.org/packages/e0/91/39c3af510b0aa32bbda03374259200f28430febfd1bf5e511fe765282ce5/charset_normalizer-3.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15f024313246a4ed976c60f440bb8d257815513a681d212ff74fd46f7d715a90", size = 251240, upload-time = "2026-08-15T08:18:18.127Z" }, + { url = "https://files.pythonhosted.org/packages/1c/a5/cbe418bbc6ecdfc3e05a0116002897c4b403a5e838d697e64c78e9f0190d/charset_normalizer-3.5.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:823f82903d189af463d7df250ef1f7f696f3cee08cc8d91deb565e8d425f6506", size = 245282, upload-time = "2026-08-15T08:18:19.625Z" }, + { url = "https://files.pythonhosted.org/packages/cc/a4/689bb42e8e7cd492f3cb64907c6bc00ad247ec9a3628cd3f8eed126e8ae1/charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:01e93745f7f219b703b60ba7afead36cfc4242782be5af484673fc500df12da5", size = 244597, upload-time = "2026-08-15T08:18:21.121Z" }, + { url = "https://files.pythonhosted.org/packages/c1/ce/9962938e179cf9f699d3f1e7b3114b5d7642dee6a893745229f9dd04f274/charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:329fc3ccb63ad22d867d84c2adea759a64079a37ba4a343433b02c7a2816871e", size = 231376, upload-time = "2026-08-15T08:18:22.57Z" }, + { url = "https://files.pythonhosted.org/packages/85/54/46000450ada53bd9eac5429a2c8c54cd2d9b39c0c255f229aea9af0948a5/charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:bb57753e36e4855b8ca375069482250a6246372331a3e4f3407eaebb007443f5", size = 266715, upload-time = "2026-08-15T08:18:24.235Z" }, + { url = "https://files.pythonhosted.org/packages/3d/bb/618749d70f792b44252a777bf89bfb86823b9bbc1ea13fe8ce759b07f38a/charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:fce8cbd4997efeb450bd298b54f755dcdff18d496f7a5ddbb4867c6d7c88fdc3", size = 245848, upload-time = "2026-08-15T08:18:25.726Z" }, + { url = "https://files.pythonhosted.org/packages/7e/3f/ffb64458527c7668031d5eb095d978de561958dc9f5b53f8e488a533e603/charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6c9cdde8becb25a7fde49924511aa2644d6f8081cc8df8e9452724303348d8e3", size = 264521, upload-time = "2026-08-15T08:18:27.193Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ab/74a55fd803916a35ac461daf002708191aac19b546b80dc8cabfedc63d98/charset_normalizer-3.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9ac4444d8d4fd4c4bd08bf451ed3167aa9e7ec6cdb41b648794f1d1103652e36", size = 253054, upload-time = "2026-08-15T08:18:28.568Z" }, + { url = "https://files.pythonhosted.org/packages/a0/2a/6a9034b7d3c60b17499afb482df5878bf9fa20b50cc3887d5ef017a833db/charset_normalizer-3.5.1-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:f03ac127268b43ef4fe9e6ab6794a6794b49485a0cc0c1db79876d2f33f75bc7", size = 140580, upload-time = "2026-08-15T08:18:30.214Z" }, + { url = "https://files.pythonhosted.org/packages/f3/46/1d362e1a00d035d66b9869e1281eee115907f7e390a16a07824ab5737360/charset_normalizer-3.5.1-cp314-cp314-win32.whl", hash = "sha256:1f5883d77fd409a261abb5dc8ccbe335720d798b1de4abb3b1d47ccbbc76b53b", size = 180325, upload-time = "2026-08-15T08:18:31.877Z" }, + { url = "https://files.pythonhosted.org/packages/7a/7c/4938c329b6a9d446f6a59aa2092ff7118f274209b5ed0e26893d1d30a63c/charset_normalizer-3.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:c658c50ac0c98cd755a2dd50b7977d3bca7df401dcc47fbdfa87db53ef7d4e8b", size = 204175, upload-time = "2026-08-15T08:18:33.466Z" }, + { url = "https://files.pythonhosted.org/packages/ac/33/eeb384dbd8dec570661354592f4f2e1b2fcc92585624d146a000caf53841/charset_normalizer-3.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:4bea7f8ebe90bbd7f0e4a2de42ca6924ba23e3e76418c408ff82f1d46fabd687", size = 184123, upload-time = "2026-08-15T08:18:34.913Z" }, + { url = "https://files.pythonhosted.org/packages/1c/6c/c73fa9d5a85f6ab05395de61c5f6984e0a9ff40bb5ff888d46dff02526c6/charset_normalizer-3.5.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:fbc597639158fd7c14d55e808718848319540f51b0e6746e3eefa59723a4a348", size = 381682, upload-time = "2026-08-15T08:18:36.349Z" }, + { url = "https://files.pythonhosted.org/packages/30/c7/63565f860921457feba93bae6c86fb7746deb4cffeed2f375cb845318146/charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e71c909f353863b2b89c83de2ebed71ea6d0df8a6ef65a128193c5e650766bef", size = 240826, upload-time = "2026-08-15T08:18:37.887Z" }, + { url = "https://files.pythonhosted.org/packages/06/ae/7ae8807410dfa33f8e6f1715740adeaafa8a816cc4cb33508f54b1f7c896/charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7ac76cf9afd34929d76eb7fcb63be476a4853d8a96f0dcf2d0db68a0cbdf9885", size = 227861, upload-time = "2026-08-15T08:18:39.315Z" }, + { url = "https://files.pythonhosted.org/packages/e9/a3/887c1642f0da26000b0e0652d91071113c0e72cea33952e225cf589f49a9/charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3a370082ce34d0612f421e15fe011c53bb1feff21a26d06ad4fb244dab5a375", size = 260758, upload-time = "2026-08-15T08:18:40.88Z" }, + { url = "https://files.pythonhosted.org/packages/3e/11/e6f5b9a3d0e55b0ef7505cd3765cdd48f22db89994c947b316f52f801fd8/charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:256dd4d85d9e4dc595e2bc983c980e73f62ddeb3165c58b4c3dfe78c5c8548c1", size = 259950, upload-time = "2026-08-15T08:18:42.351Z" }, + { url = "https://files.pythonhosted.org/packages/1b/ee/e4e10a94d51cd1ee638aa7e00b65399e6b2a4e8376ab6d2eac9f95586671/charset_normalizer-3.5.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:58d4aa13a59c969dbfdf9e6a9560e242cbfd9e8a8f50c2747714df1a423adf65", size = 249329, upload-time = "2026-08-15T08:18:43.914Z" }, + { url = "https://files.pythonhosted.org/packages/c4/25/d5f4198819e6059735a84e8d0bfb72dc33976da67b97adcd3fb5a5e07ec6/charset_normalizer-3.5.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0c6dfb5ca6723eeed15aa8e564a014d69fcb8812f94eef11fe3631e0508199f5", size = 243137, upload-time = "2026-08-15T08:18:45.368Z" }, + { url = "https://files.pythonhosted.org/packages/a5/e9/e925ca7569cf9fb9701fd82503fee73eea5268fdb856bdd64947092d3daa/charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c010f5581d9c612804cc59fcf7b524b707fbcb72828551237ab545bb5c7034af", size = 242820, upload-time = "2026-08-15T08:18:46.842Z" }, + { url = "https://files.pythonhosted.org/packages/34/17/672c251a888ed2aebcdd2fe830ad0104e25ff83c43f5c4f9c15e9fc6853c/charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:52ec005752a56ae79547a05c0139ca2501a0c866390b6115008456b9f0e7cde1", size = 230504, upload-time = "2026-08-15T08:18:48.353Z" }, + { url = "https://files.pythonhosted.org/packages/3f/fc/f6a85abebd42ce4da2f1db0aa56cc6a0df1995e318b3875d14401b8381d1/charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:2bced4061f000f7187254a02ad3433ae17eaf991747ceea2f478422590a5bba9", size = 263087, upload-time = "2026-08-15T08:18:49.859Z" }, + { url = "https://files.pythonhosted.org/packages/98/66/7c42677e739ba66746b297e2046918d793078094dc239e1e72768cffccc6/charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:9eea3ab2597a5e65fe65296e2d6a84570845a6b55532d90333d740d48bbc850a", size = 243269, upload-time = "2026-08-15T08:18:51.601Z" }, + { url = "https://files.pythonhosted.org/packages/de/d8/a50b79237f417af10f8c2a501ce8d1ca87829a22e69117891ca4ba20a69e/charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:496846868fea80e479324862fa877f02411f2fd0f83b79ccee2607aa68b2a032", size = 258766, upload-time = "2026-08-15T08:18:53.23Z" }, + { url = "https://files.pythonhosted.org/packages/2e/1d/0fc91aeaeb3c83b748f532399ce67cf84604b48297405d740000f7a9e786/charset_normalizer-3.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:85d5855daafc240cc045c026d7a15fd198a09b0fc8ff6f5ecbb5297b509cb11e", size = 250814, upload-time = "2026-08-15T08:18:54.768Z" }, + { url = "https://files.pythonhosted.org/packages/ae/10/3d8c777cf9024615295aa1b808324ad5b4a77855869c00824bad74ffaf8a/charset_normalizer-3.5.1-cp314-cp314t-win32.whl", hash = "sha256:58d3e12c88e0950bca850ae1f7c256055c097639c2edb9eb123af9807d8b15e4", size = 191074, upload-time = "2026-08-15T08:18:56.305Z" }, + { url = "https://files.pythonhosted.org/packages/4d/81/ae557d3c44d1a1d688696d60563413a0866a91b7ebc50f20df838be3d8c8/charset_normalizer-3.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:acaf604462bf330b0d07e7a07c1d6e4adac79e5fb13e9c5140590542cafacc00", size = 216476, upload-time = "2026-08-15T08:18:57.889Z" }, + { url = "https://files.pythonhosted.org/packages/27/e9/61c01fb8b804692569c036b3fc50495814502dcf13a60649c6055390b02c/charset_normalizer-3.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:fdb8a068947befafba9952162645dc2fecaeb400e64584829ed5e9b2fbe21a7f", size = 194115, upload-time = "2026-08-15T08:18:59.418Z" }, + { url = "https://files.pythonhosted.org/packages/4a/4e/8544831ef59d8f27ce92c80871380fdacc8076a8a56ed62f82e54f991333/charset_normalizer-3.5.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:9085f87b0e38a2b92b8923059b4e8789fe40d9279712d15dcc670048d77079af", size = 342048, upload-time = "2026-08-15T08:19:01.054Z" }, + { url = "https://files.pythonhosted.org/packages/7f/a6/e3b46852424246065355644f4fb6dbccc0239a42a2eee27ecfc8957f0bcd/charset_normalizer-3.5.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2679de311c7946dde5d3b6f44941844133ff5c7cb86099c0061ab1e8901c20a8", size = 242997, upload-time = "2026-08-15T08:19:02.492Z" }, + { url = "https://files.pythonhosted.org/packages/03/3b/0cc9a26777334ab2f2e3089b948bbf4e4fe72ea70b897715ef6415043ec8/charset_normalizer-3.5.1-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:baf3775a2635e5a11fbd5e4e64ee69c7e86875d224a5c72aca4c141064589a90", size = 237014, upload-time = "2026-08-15T08:19:03.943Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c2/027335f0aa337a2a2e121bac1ad88c4f02ba6053ea0926802784f3db11af/charset_normalizer-3.5.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8ac8c94b6539074e0f40899301273ac8402b9b3e01c7b7ba269ff30340aaaf20", size = 266174, upload-time = "2026-08-15T08:19:05.598Z" }, + { url = "https://files.pythonhosted.org/packages/86/d3/e367787febe4e74769dec0f406f2c3c8d1b955fce5aee1fd0f94e8367a45/charset_normalizer-3.5.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fe532b3c966d1fb794e0698e4589d0444017ae77fc0b31edea13c0e35bcc449", size = 263361, upload-time = "2026-08-15T08:19:07.251Z" }, + { url = "https://files.pythonhosted.org/packages/af/3d/391b193eb9f3e84b02f9314088c386debdc0debee843535aaea2e2c6715d/charset_normalizer-3.5.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5c84bec0ab5ae0c64bfe73a7d2adcb5ce73b467523fc27fd6a28ab2aa6cbe35a", size = 252143, upload-time = "2026-08-15T08:19:08.816Z" }, + { url = "https://files.pythonhosted.org/packages/2e/57/de221f1745a90d418199761967e2776bfe2c275a1194220985e8c1d37833/charset_normalizer-3.5.1-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:854066be00447fa8de2ccbbe893e2ffc4b123ef16d897af794c1e18bd4a714b0", size = 252086, upload-time = "2026-08-15T08:19:10.255Z" }, + { url = "https://files.pythonhosted.org/packages/c8/e3/d119f86a01f9331e8186175f24873b1d74a7ee9e2e4b4d68f9947dae5afd/charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:21b82d8082f6f5e7f456ef0bd16323d08de1266efbfeb476e64b2a91d1471a4e", size = 245231, upload-time = "2026-08-15T08:19:11.807Z" }, + { url = "https://files.pythonhosted.org/packages/26/de/d8e48c135ae480879539cdb179c8d3b50c7879497d75dd899b5763b69cee/charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:838648accb3a7fd9803fd45c87bce8509648eb0c11bc34e216141300977244f2", size = 241546, upload-time = "2026-08-15T08:19:13.416Z" }, + { url = "https://files.pythonhosted.org/packages/67/c4/217755fd1abc50d326c252922cd642002758095a81ff45010337b8b3ef65/charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:195ce897c6153c0700078142cf8efe3e6454ca4cf4357499e4078dfd83396626", size = 267033, upload-time = "2026-08-15T08:19:14.981Z" }, + { url = "https://files.pythonhosted.org/packages/b8/d7/34d8e404e358d2adcc5a228c2134643af00104c8fb0bf525f3688d756f05/charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:978eab16f55b4ab2c2a745be9a0a840bf8f09a7f227d9c76eb30214d078865a5", size = 252045, upload-time = "2026-08-15T08:19:16.618Z" }, + { url = "https://files.pythonhosted.org/packages/5e/fa/40414471acf0aa0692ca77305aa00e434fcd8288f0941c93c30e9a5f8f2f/charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:cc0329df4caaceb950d2f580b5ac716a377f7059624a0bafaeaf8a218c6ed774", size = 264866, upload-time = "2026-08-15T08:19:18.101Z" }, + { url = "https://files.pythonhosted.org/packages/32/90/fcc850bae791abd2e0c041847f13e270aa08692a79f3e00de6d2dce1cb50/charset_normalizer-3.5.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:687c9ca3035544b113bea2055e180af96fb63c0c476e22a9180f51925186e7b7", size = 253932, upload-time = "2026-08-15T08:19:19.734Z" }, + { url = "https://files.pythonhosted.org/packages/af/af/53afe99068b3c10b4cbae592a52ef72a7c92c0188440e83ee3a078fd8f75/charset_normalizer-3.5.1-cp315-cp315-win32.whl", hash = "sha256:706bfd38730a5ac7a365793269a00f4e988178cec121391f4248d84ad8c972e9", size = 180320, upload-time = "2026-08-15T08:19:21.37Z" }, + { url = "https://files.pythonhosted.org/packages/c9/bc/f46a132041b29e4a8779ed712d3df1bf112e94ca8de58b66d7ec2c0cf8b9/charset_normalizer-3.5.1-cp315-cp315-win_amd64.whl", hash = "sha256:92caef967d287a407085d61176fce4012b1dd62daed4eb6d5ceb26d3d2538712", size = 204174, upload-time = "2026-08-15T08:19:23.088Z" }, + { url = "https://files.pythonhosted.org/packages/a1/5d/9ed554480eda8e447b673648628fdc29574d23dbad01fe11837adedd1cae/charset_normalizer-3.5.1-cp315-cp315-win_arm64.whl", hash = "sha256:5fc45d653ea8c9a20479167e11d4a0f8cb2fa3470737ab6f9c827532313187b7", size = 184126, upload-time = "2026-08-15T08:19:24.471Z" }, + { url = "https://files.pythonhosted.org/packages/3b/32/9b8929bf384061ee1fe5d9c27c6f9776d3d824039ad4e14c88ec00c7808e/charset_normalizer-3.5.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:59171c6e45bf07d0d5cab3b0bf81d945035530f6873398b3b531c31184d46663", size = 381441, upload-time = "2026-08-15T08:19:26.038Z" }, + { url = "https://files.pythonhosted.org/packages/96/10/e9aa7923d3ddac652c99a1c5f7be494e737e151566a44abe018daf757f2c/charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9dbdd9205662134957cf0c324f639bdc5031c0ca056e2369e238db75187c0f11", size = 241742, upload-time = "2026-08-15T08:19:27.532Z" }, + { url = "https://files.pythonhosted.org/packages/28/53/a2d249ebddf47b889a100c0bdcb61a2f9dbb8bc24ef325cc062e4f476877/charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e4b018dc5a0eee4676e38fe84a47a427816c590b93b55d9025274ec4d6ffc2dc", size = 235298, upload-time = "2026-08-15T08:19:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/7d/07/469f78af590f7d5cd48e20d8dbfa3d66deeff9ba37768c04d886b5afd45c/charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ced3fdd71aaa83ce593746c2edb42b7a59cb4c19c8b5c407781c72e493aae55a", size = 262500, upload-time = "2026-08-15T08:19:30.955Z" }, + { url = "https://files.pythonhosted.org/packages/55/66/3bb56a47f7dcba014055b1a1d33c6f08bbe9c1e74dba154cfa25f90ae885/charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:19a3dd5aa73cef1c99687c4fc57db016a9c17104ae1185da88ba566a5d3bebe4", size = 258888, upload-time = "2026-08-15T08:19:32.458Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c1/2adc2800903fb013210349313b710a5376856578d9e33e6b9a1d8b36714a/charset_normalizer-3.5.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc5d36d96478aa9c60654bd932525bf32964c62a7281eafdf16d85003a8d6004", size = 250243, upload-time = "2026-08-15T08:19:33.94Z" }, + { url = "https://files.pythonhosted.org/packages/95/b5/a18d0dd1157ab655cc2cb14a545f4a4784bbad70ab3502412e36097502d9/charset_normalizer-3.5.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04368edf83514385ffc3e1cfd4546e595f4f1272dd23ba437a93a9cc3741d47b", size = 249871, upload-time = "2026-08-15T08:19:35.413Z" }, + { url = "https://files.pythonhosted.org/packages/ad/c3/525f508cd1e58d0450ac55ed40ac75bc3a97482c59def5278456a5fbf03c/charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:9b5db6052055d34d41230fb78d7c439c23dc536a9896f6cb039e8dd92cfc1263", size = 243580, upload-time = "2026-08-15T08:19:36.886Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/49a91fe7e97c8140094ca5c64161ab623a70d9f636bf834eace14048acb5/charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:252d099029bcbea642f2a06c4ed5046bdf8b5a8150b64afa5e027e88b106e5ee", size = 239807, upload-time = "2026-08-15T08:19:38.392Z" }, + { url = "https://files.pythonhosted.org/packages/d3/58/56a48c296601274c4689b864a8e2dfb209b81dfcb39472753ce95eea662b/charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:6199d5606e2bbf2b096cf64d03f8b6790c91081d5ac866b8e7bb6422738cc60c", size = 264083, upload-time = "2026-08-15T08:19:39.856Z" }, + { url = "https://files.pythonhosted.org/packages/10/4c/dc48409274a1817ff349711d26c62aa0c597df865d4d69ef79160c859193/charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:77efcff2b23071c349402ac1066667a3d011f62398d81408c9b88ad991747c9e", size = 250317, upload-time = "2026-08-15T08:19:41.53Z" }, + { url = "https://files.pythonhosted.org/packages/81/58/d325912115caec62d6bdd77bbab5e0b7da5d234a9f20affdffcbcb530d0b/charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:a5cbd90ecf0fc62e64726917ad083b73001f0563657a87ec3c0b504e277dc90d", size = 258173, upload-time = "2026-08-15T08:19:43.07Z" }, + { url = "https://files.pythonhosted.org/packages/34/f7/b13b1ccae2c8ec63980d13be1890eb73f8aeabbfce02a24aabc0908788f5/charset_normalizer-3.5.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:4d26f14f041e83dd8edfd61f4cd4fa7285d31798b5bf1f28e70c367ba6c41d61", size = 251960, upload-time = "2026-08-15T08:19:44.587Z" }, + { url = "https://files.pythonhosted.org/packages/1e/25/ed3f9919c5aef8cc818be1f972f565f7610d7b2076b8ebb98839516ffc3c/charset_normalizer-3.5.1-cp315-cp315t-win32.whl", hash = "sha256:ac13b004224fb341e1e25a1ed5e19d32f57cdb2a403e01f003b46f051a550f6f", size = 191186, upload-time = "2026-08-15T08:19:46.293Z" }, + { url = "https://files.pythonhosted.org/packages/69/d5/43c2b3e9d8267092b913eb8b0603f0f71993c395632886bd37a7223f96cf/charset_normalizer-3.5.1-cp315-cp315t-win_amd64.whl", hash = "sha256:35aea775dc2bd5f54cd84a1cd2696cc3207c479cb9cf0bd346f0d343e4300ddb", size = 215947, upload-time = "2026-08-15T08:19:47.853Z" }, + { url = "https://files.pythonhosted.org/packages/a8/76/9aad3e9c8865e5e0efa9a7f6f81c37a67635a985145ecd44528a81e088ee/charset_normalizer-3.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:fb78f6e7fcd8ad785d28cd577168bc1aaee827b25bb8755638f694794ea98f0a", size = 193909, upload-time = "2026-08-15T08:19:49.383Z" }, + { url = "https://files.pythonhosted.org/packages/5b/97/fb4e82231aba271ffd775a1b4993b0defc4e3059f286ae41d9433409fe85/charset_normalizer-3.5.1-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:41876ee62a3dddf48ff1121ad8f0798032aa03f2fd35f21f34a4cab14f18d8d2", size = 331467, upload-time = "2026-08-15T08:19:50.959Z" }, + { url = "https://files.pythonhosted.org/packages/9f/2f/fe3f187327aac18e2d54e9d2b08e15d27bf9b642d9e51c219f130fc34d1a/charset_normalizer-3.5.1-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a6dac12ff6b846103483683f60c5f8fee205121adc58ffd87e90a90a3af69e99", size = 253057, upload-time = "2026-08-15T08:19:52.654Z" }, + { url = "https://files.pythonhosted.org/packages/d7/c7/9e48cee5c161fe24da823b61bf381921d77cb994a0a4de148e95018c1984/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cee5dd7c6fb5dd52a0fe2a740f9bc6e3593f5f8b1788bde49de02086f30182b2", size = 240930, upload-time = "2026-08-15T08:19:54.163Z" }, + { url = "https://files.pythonhosted.org/packages/49/e0/716601f3cc69be7b198951150c75ead1ece33c3c8036ff6ffa46029659a0/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:343fb4f2821043bd87095f7b08a1a181febc8e36ac64212143bbfd0a0e1bc235", size = 230822, upload-time = "2026-08-15T08:19:55.807Z" }, + { url = "https://files.pythonhosted.org/packages/d3/05/71bfc5caa0abcc45aea1f6a4d50ac68e59605ddc7666fe8494f4cd229665/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ae4a097991662cd4fff0ddc74e0fe7874f82e00042fa0ea00855645ed0c79598", size = 260037, upload-time = "2026-08-15T08:19:57.312Z" }, + { url = "https://files.pythonhosted.org/packages/c3/92/de7e32ed05341e7a9c4c877c318418197b7f2d66a3b68d561bf2ac57ca3e/charset_normalizer-3.5.1-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4b599739b93b2cbeded49645ae3c8d1405c29ddfbceac1545c87a3f9580a9e96", size = 255097, upload-time = "2026-08-15T08:19:59.056Z" }, + { url = "https://files.pythonhosted.org/packages/f5/7b/ade0a122600319dfa0b1000ab0f9731c94a817904cf3c5de408c73a4ede7/charset_normalizer-3.5.1-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b39b69b347e5e47a3b5b8cfc005c68c1ba347474e3960236c4944a8ecd174962", size = 250166, upload-time = "2026-08-15T08:20:00.612Z" }, + { url = "https://files.pythonhosted.org/packages/75/9c/019fbb9f4834491a160951349b1a3714439376f66e5f7cf18b4f18f0c7aa/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a2028475ba855475b8b4d3cfeb4994269c967aea8b9892dfba907f4263a863a3", size = 241821, upload-time = "2026-08-15T08:20:02.321Z" }, + { url = "https://files.pythonhosted.org/packages/2b/b8/11d4840bfc99330cc7fbcc2681ee5a044553a6e77655508d8f9b2bff7b34/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:36047af20e17097c3bb9476c2b7655f2f7aa51322c0ba58c07695bedf755a950", size = 232529, upload-time = "2026-08-15T08:20:04.008Z" }, + { url = "https://files.pythonhosted.org/packages/18/96/2b3a21492d9f65171ac75d872f5018260013d00bfa0ff70ec9f179148cbd/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:4c4fb141a727957c93edfe5c32a26ceb6b5f6461d67146e2d39f51e16170bea8", size = 260348, upload-time = "2026-08-15T08:20:05.877Z" }, + { url = "https://files.pythonhosted.org/packages/d6/aa/a69a2028e8bd052476c245460ab19d7de595de084dd968f2d75cd50c3e25/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:2f293479cce755c75f1697e87c409b7ae4c555c7dfecb6e988ad13abba943031", size = 247234, upload-time = "2026-08-15T08:20:07.487Z" }, + { url = "https://files.pythonhosted.org/packages/35/8a/3d130aeabcaf3d2466af76b7b141c08d9e89c9016ab4b7cdd0f7dc2d1c62/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:3588e376b3ea2eea84976f67273d679f229e24c66dce7b82ae45aef04ff6e072", size = 256917, upload-time = "2026-08-15T08:20:09.142Z" }, + { url = "https://files.pythonhosted.org/packages/80/c2/a7379b840292d0c1ab9fbd17d1f3967aa81794dc95bc74be8999d7fedcf7/charset_normalizer-3.5.1-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e199fb99720074809a7720f1c0b4d919eea8b87e88713e0f8f602f7bef543d9d", size = 254846, upload-time = "2026-08-15T08:20:10.727Z" }, + { url = "https://files.pythonhosted.org/packages/01/65/d43b714731bb2f40d4053dfa00ecfc1c5a301f8e3316c5db3a09af59fe94/charset_normalizer-3.5.1-cp37-abi3-win32.whl", hash = "sha256:dd732602a7009217f658d5863d12d79d373a4de0eebc111094bcdd3bb8e0a6cc", size = 174216, upload-time = "2026-08-15T08:20:12.334Z" }, + { url = "https://files.pythonhosted.org/packages/35/4f/b911ed898b26a09789eba9c9200c999aff6c61b4bafaf4838e56d1a1e1a3/charset_normalizer-3.5.1-cp37-abi3-win_amd64.whl", hash = "sha256:70055ff39b97c99e7ae40ea3e393fb62aa2e44dbd9b29f8d14f42fb0025c3959", size = 199764, upload-time = "2026-08-15T08:20:13.908Z" }, + { url = "https://files.pythonhosted.org/packages/f0/a7/920baf467bfd9bf689f3b318340f37aee4572a71f162bd8db51da55ba4fa/charset_normalizer-3.5.1-cp37-abi3-win_arm64.whl", hash = "sha256:87e4f41d375c0b9be2fb5251aee4b8a689169e134535aed81bf085c3b647451e", size = 287318, upload-time = "2026-08-15T08:20:15.551Z" }, + { url = "https://files.pythonhosted.org/packages/cc/61/d01fc49b8dea277640b55a9e15960dbca9fdc8c9fde18e572d39c59f4019/charset_normalizer-3.5.1-py3-none-any.whl", hash = "sha256:6df0ec430f9a831772c23ca5a224cba36517a58a84bb32c32bb59a9fa67c47f6", size = 68658, upload-time = "2026-08-15T08:20:43.306Z" }, +] + +[[package]] +name = "click" +version = "8.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c7/0e/7fa0ef50764b67090eca4114772a2abf8b6148198475e54c660b97caeee6/click-8.5.0.tar.gz", hash = "sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34", size = 382235, upload-time = "2026-08-26T13:33:14.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/50/6c0d534c5f134586a8e1ba4e330569e32f057e33372ae556463212fb4cd3/click-8.5.0-py3-none-any.whl", hash = "sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360", size = 125251, upload-time = "2026-08-26T13:33:12.928Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "cookiecutter" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "arrow" }, + { name = "binaryornot" }, + { name = "click" }, + { name = "jinja2" }, + { name = "python-slugify" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "rich" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/92/03/f4c96d8fd4f5e8af0210bf896eb63927f35d3014a8e8f3bf9d2c43ad3332/cookiecutter-2.7.1.tar.gz", hash = "sha256:ca7bb7bc8c6ff441fbf53921b5537668000e38d56e28d763a1b73975c66c6138", size = 142854, upload-time = "2026-03-04T04:06:02.786Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/a9/8c855c14b401dc67d20739345295af5afce5e930a69600ab20f6cfa50b5c/cookiecutter-2.7.1-py3-none-any.whl", hash = "sha256:cee50defc1eaa7ad0071ee9b9893b746c1b3201b66bf4d3686d0f127c8ed6cf9", size = 41317, upload-time = "2026-03-04T04:06:01.221Z" }, +] + +[[package]] +name = "flet" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "httpx", marker = "sys_platform != 'emscripten'" }, + { name = "msgpack" }, + { name = "oauthlib", marker = "sys_platform != 'emscripten'" }, + { name = "repath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/36/5d/bd3f4b41f7aa16d7e6802a28a2b31878a94c3e91c67d866b02c7f94b702d/flet-1.0.0.tar.gz", hash = "sha256:7d867d4832b03b380864d751dfec6a43ec8391b3db9f7f9d0ab93219a6ce2281", size = 560856, upload-time = "2026-09-14T23:00:41.599Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/6a/80aee6450ec44d11fbfcdd2b539bfcf6516442e561cb82dc0af0c1543c5e/flet-1.0.0-py3-none-any.whl", hash = "sha256:7e61fffc7f2ee70de1d0729ee39177b838897f10258fb92d534e4a0ef8564f48", size = 631615, upload-time = "2026-09-14T23:00:39.906Z" }, +] + +[[package]] +name = "flet-cli" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "binaryornot" }, + { name = "chardet" }, + { name = "cookiecutter" }, + { name = "flet" }, + { name = "flet-platform-assets" }, + { name = "packaging" }, + { name = "qrcode" }, + { name = "rich" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/32/32e6241e859c3262ee34141b22ae9bc727915dfda6a7f686d5e6ae35c766/flet_cli-1.0.0.tar.gz", hash = "sha256:96155821b16ab7cc8cea3c243307f7294dc76b1d9b6477f37f3b474f885345d6", size = 163754, upload-time = "2026-09-14T23:00:46.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/fb/c965ba665d56aa968c97616a7bbf35e089951b9bfac768e164326415b8a2/flet_cli-1.0.0-py3-none-any.whl", hash = "sha256:d23c1a9c7d67e9838f3d34dd2c942a852d455ba7c7f6e9b5357ead30d486929f", size = 139643, upload-time = "2026-09-14T23:00:45.034Z" }, +] + +[[package]] +name = "flet-desktop" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flet" }, + { name = "rich" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/11/03/a8b3566a9c83fc99433e56838dd7d8da9ea24a9c86024ac420d4e9c3918e/flet_desktop-1.0.0.tar.gz", hash = "sha256:fb193450501e35079ea525cc159efc349dc1383cb4837ae39317f3d25d3ddc56", size = 12716, upload-time = "2026-09-14T23:00:49.676Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/f8/76493acd53179cc58338d6338ec34059cbbb69e16fe7bb3a14b9e4837932/flet_desktop-1.0.0-py3-none-any.whl", hash = "sha256:be5d7de55bb917740b5d659c9f8c11aa958782b53a0cf1bd5a33ded18cfce26e", size = 13145, upload-time = "2026-09-14T23:00:48.776Z" }, +] + +[[package]] +name = "flet-platform-assets" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pillow" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/4b/24173bc95d2224b8103bb7739cec2bdbfadd4c56dda8517a5676c9683be3/flet_platform_assets-1.0.0.tar.gz", hash = "sha256:d4d3931dec8c279310e35a18f19eb824cda810bb689b6cf4ce5fe07e9fb47d04", size = 35625, upload-time = "2026-09-14T23:00:53.553Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/c8/b8a39b25d11c9a4f1add2e795e99613867cb04c022e6cceb6a2da93748d1/flet_platform_assets-1.0.0-py3-none-any.whl", hash = "sha256:de06ce4861addb03adc56162641fff0d080199eeee997fb9e02f7612120cec91", size = 25561, upload-time = "2026-09-14T23:00:52.429Z" }, +] + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "markdown-it-py" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/ff/7841249c247aa650a76b9ee4bbaeae59370dc8bfd2f6c01f3630c35eb134/markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49", size = 82454, upload-time = "2026-05-07T12:08:28.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/81/4da04ced5a082363ecfa159c010d200ecbd959ae410c10c0264a38cac0f5/markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a", size = 91687, upload-time = "2026-05-07T12:08:27.182Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/99/7690b6d4034fffd95959cbe0c02de8deb3098cc577c67bb6a24fe5d7caa7/markupsafe-3.0.3.tar.gz", hash = "sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698", size = 80313, upload-time = "2025-09-27T18:37:40.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/8a/8e42d4838cd89b7dde187011e97fe6c3af66d8c044997d2183fbd6d31352/markupsafe-3.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe", size = 11619, upload-time = "2025-09-27T18:37:06.342Z" }, + { url = "https://files.pythonhosted.org/packages/b5/64/7660f8a4a8e53c924d0fa05dc3a55c9cee10bbd82b11c5afb27d44b096ce/markupsafe-3.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026", size = 12029, upload-time = "2025-09-27T18:37:07.213Z" }, + { url = "https://files.pythonhosted.org/packages/da/ef/e648bfd021127bef5fa12e1720ffed0c6cbb8310c8d9bea7266337ff06de/markupsafe-3.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737", size = 24408, upload-time = "2025-09-27T18:37:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/41/3c/a36c2450754618e62008bf7435ccb0f88053e07592e6028a34776213d877/markupsafe-3.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97", size = 23005, upload-time = "2025-09-27T18:37:10.58Z" }, + { url = "https://files.pythonhosted.org/packages/bc/20/b7fdf89a8456b099837cd1dc21974632a02a999ec9bf7ca3e490aacd98e7/markupsafe-3.0.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d", size = 22048, upload-time = "2025-09-27T18:37:11.547Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a7/591f592afdc734f47db08a75793a55d7fbcc6902a723ae4cfbab61010cc5/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda", size = 23821, upload-time = "2025-09-27T18:37:12.48Z" }, + { url = "https://files.pythonhosted.org/packages/7d/33/45b24e4f44195b26521bc6f1a82197118f74df348556594bd2262bda1038/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf", size = 21606, upload-time = "2025-09-27T18:37:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/ff/0e/53dfaca23a69fbfbbf17a4b64072090e70717344c52eaaaa9c5ddff1e5f0/markupsafe-3.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe", size = 23043, upload-time = "2025-09-27T18:37:14.408Z" }, + { url = "https://files.pythonhosted.org/packages/46/11/f333a06fc16236d5238bfe74daccbca41459dcd8d1fa952e8fbd5dccfb70/markupsafe-3.0.3-cp314-cp314-win32.whl", hash = "sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9", size = 14747, upload-time = "2025-09-27T18:37:15.36Z" }, + { url = "https://files.pythonhosted.org/packages/28/52/182836104b33b444e400b14f797212f720cbc9ed6ba34c800639d154e821/markupsafe-3.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581", size = 15341, upload-time = "2025-09-27T18:37:16.496Z" }, + { url = "https://files.pythonhosted.org/packages/6f/18/acf23e91bd94fd7b3031558b1f013adfa21a8e407a3fdb32745538730382/markupsafe-3.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4", size = 14073, upload-time = "2025-09-27T18:37:17.476Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f0/57689aa4076e1b43b15fdfa646b04653969d50cf30c32a102762be2485da/markupsafe-3.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab", size = 11661, upload-time = "2025-09-27T18:37:18.453Z" }, + { url = "https://files.pythonhosted.org/packages/89/c3/2e67a7ca217c6912985ec766c6393b636fb0c2344443ff9d91404dc4c79f/markupsafe-3.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175", size = 12069, upload-time = "2025-09-27T18:37:19.332Z" }, + { url = "https://files.pythonhosted.org/packages/f0/00/be561dce4e6ca66b15276e184ce4b8aec61fe83662cce2f7d72bd3249d28/markupsafe-3.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634", size = 25670, upload-time = "2025-09-27T18:37:20.245Z" }, + { url = "https://files.pythonhosted.org/packages/50/09/c419f6f5a92e5fadde27efd190eca90f05e1261b10dbd8cbcb39cd8ea1dc/markupsafe-3.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50", size = 23598, upload-time = "2025-09-27T18:37:21.177Z" }, + { url = "https://files.pythonhosted.org/packages/22/44/a0681611106e0b2921b3033fc19bc53323e0b50bc70cffdd19f7d679bb66/markupsafe-3.0.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e", size = 23261, upload-time = "2025-09-27T18:37:22.167Z" }, + { url = "https://files.pythonhosted.org/packages/5f/57/1b0b3f100259dc9fffe780cfb60d4be71375510e435efec3d116b6436d43/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5", size = 24835, upload-time = "2025-09-27T18:37:23.296Z" }, + { url = "https://files.pythonhosted.org/packages/26/6a/4bf6d0c97c4920f1597cc14dd720705eca0bf7c787aebc6bb4d1bead5388/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523", size = 22733, upload-time = "2025-09-27T18:37:24.237Z" }, + { url = "https://files.pythonhosted.org/packages/14/c7/ca723101509b518797fedc2fdf79ba57f886b4aca8a7d31857ba3ee8281f/markupsafe-3.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc", size = 23672, upload-time = "2025-09-27T18:37:25.271Z" }, + { url = "https://files.pythonhosted.org/packages/fb/df/5bd7a48c256faecd1d36edc13133e51397e41b73bb77e1a69deab746ebac/markupsafe-3.0.3-cp314-cp314t-win32.whl", hash = "sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d", size = 14819, upload-time = "2025-09-27T18:37:26.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/8a/0402ba61a2f16038b48b39bccca271134be00c5c9f0f623208399333c448/markupsafe-3.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9", size = 15426, upload-time = "2025-09-27T18:37:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + +[[package]] +name = "msgpack" +version = "1.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/44/ea2100ec54d30c46ee9dba10a3bfb79b655e96c6df237238a3234c75869b/msgpack-1.2.2.tar.gz", hash = "sha256:9eb0b0e602064527a045ea28c4f174ed69383587e29cebe28947e3b84106eb2a", size = 187025, upload-time = "2026-08-27T10:03:47.793Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/50/3e92c403346652cabd08cb8faceef847bae917ea3b3c81b64a5b6d09ed41/msgpack-1.2.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:e497ee34e8a3342bbde51b27c22d8db05a651df3361dd3daef5b3ab0d66f3e04", size = 84315, upload-time = "2026-08-27T10:02:41.181Z" }, + { url = "https://files.pythonhosted.org/packages/b6/dc/8efe6dd96a12ab043930cb4cffb40b6e7f061491d6ec7a3d2b75ef1fda42/msgpack-1.2.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:0dd9173c5ebaf5ecc5ca86e7ae1db92934e1d57b856f3dd90698941431f4fd77", size = 84634, upload-time = "2026-08-27T10:02:42.621Z" }, + { url = "https://files.pythonhosted.org/packages/1b/89/996573095bf7b038c04dd65ddbc4f1a4d381b0f7a44ff9186f3c7b8325c2/msgpack-1.2.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8dc4487097571f7311188c3eca2a3e86cd1f1db4c37c7a017bcc3fd38486cbfe", size = 404194, upload-time = "2026-08-27T10:02:44.096Z" }, + { url = "https://files.pythonhosted.org/packages/b6/4e/46f5a5d949dbd054dab60cb15aac7ac6ae6774c134532893414689bf2f53/msgpack-1.2.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:73b0e05c32c3cfc3cd84994908e57430c0ebc6813abf905d3f18ff115d54df3f", size = 412343, upload-time = "2026-08-27T10:02:45.747Z" }, + { url = "https://files.pythonhosted.org/packages/da/e8/739a94197358a313307e6e9e7d8d22ef66add39222de911a44161aa96920/msgpack-1.2.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa1120c653b76d8eafa50423b5eba06b5c9737f8692c74fa3afe03e84b8978ea", size = 372620, upload-time = "2026-08-27T10:02:47.578Z" }, + { url = "https://files.pythonhosted.org/packages/03/d4/09b92e1fcdccea9466bfae45455367ac52362ae445d96a602e51b7a8df73/msgpack-1.2.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ccfd880988f8438d1c91c77d7edc58e70f4d2012e999167bc154c64c6f06ea6b", size = 394603, upload-time = "2026-08-27T10:02:49.172Z" }, + { url = "https://files.pythonhosted.org/packages/47/db/d11bd6f258a60703dcdc7a3772818ad0c2f602ee4c2acfb24088c6c3ebc3/msgpack-1.2.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:6195257a107bf25872ef84aab7295078271eea3ac6413f0506b631f6c9586ed5", size = 372666, upload-time = "2026-08-27T10:02:50.886Z" }, + { url = "https://files.pythonhosted.org/packages/71/cf/fbbbac0c6e5fbb9d51abc23e3b5fe8620f5c01e0588797cf664a623bb9e1/msgpack-1.2.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b8dd6c71d20c28d2d0eb0c51e7cccf3584afde3b1364f6629596186c9025bd54", size = 410889, upload-time = "2026-08-27T10:02:52.51Z" }, + { url = "https://files.pythonhosted.org/packages/94/60/8366558da954095e04e7fbc351f9387d87a682feaee9a235ceda966f794b/msgpack-1.2.2-cp314-cp314-win32.whl", hash = "sha256:d242f3c4ccf55b056e6cf901720dccde58f1df117898f2bbf3bcd6e38ec7c248", size = 66774, upload-time = "2026-08-27T10:02:53.984Z" }, + { url = "https://files.pythonhosted.org/packages/4b/3d/1ce873c8057c65e4fbb076ffe1c99c9ae39d90a00a2540d7b06c652a292f/msgpack-1.2.2-cp314-cp314-win_amd64.whl", hash = "sha256:1510f24612d4b983dff6935d9273e02c320cfd525727fbcb58836a75f589fdbc", size = 73424, upload-time = "2026-08-27T10:02:55.277Z" }, + { url = "https://files.pythonhosted.org/packages/d5/55/e36f2a33e38657f33850d74e0bf256838a0d45802c298cc501a32bffcc08/msgpack-1.2.2-cp314-cp314-win_arm64.whl", hash = "sha256:7826f16edc763e768404f55605ef85dfcf5857e729c1ed29e0d7c180be4fe6d8", size = 67657, upload-time = "2026-08-27T10:02:56.493Z" }, + { url = "https://files.pythonhosted.org/packages/64/58/7e764b957bae80ae281a9cb28761068c8bae8d5c6ac0873e43cc69d176c7/msgpack-1.2.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:f466049b8e1ec0854287bbe9a074316826fe0e08dcf707245f98b1ae49e92650", size = 86594, upload-time = "2026-08-27T10:02:57.796Z" }, + { url = "https://files.pythonhosted.org/packages/ae/f0/250f5985b6ee533e60d357571a808aaae03c54118294dc3db7158e27feb1/msgpack-1.2.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1f6b6f8deb07d49090e1808c6ef9cb7d23ca17bef3aa6ed3e5e03df16606e60c", size = 87374, upload-time = "2026-08-27T10:02:59.256Z" }, + { url = "https://files.pythonhosted.org/packages/bd/2c/126ec8f187877c5f688631c543d1d3a3d75b2e66b83fb9de3ed7c13a39b6/msgpack-1.2.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b542ffc0a5c531eedc40419f291f1bd659aa8d4223408a5b51c88a2796083fd3", size = 428157, upload-time = "2026-08-27T10:03:00.9Z" }, + { url = "https://files.pythonhosted.org/packages/95/21/d2d81d50aaedb14147d01f22094185794db3ad8a8791b60afacba0627c89/msgpack-1.2.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7d095df2627e5dd59ac7b0c5ad627a671c76e6020171e03cbe4621a61f0562c3", size = 426669, upload-time = "2026-08-27T10:03:02.457Z" }, + { url = "https://files.pythonhosted.org/packages/c6/fc/f7d484ee5b572719608e7ffad569bea22ff11309a96ca2fae85eec94226b/msgpack-1.2.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ffdd2f4950daf7815490f23087963e3420175b9609520b7ff5df64d351159c22", size = 380625, upload-time = "2026-08-27T10:03:04.244Z" }, + { url = "https://files.pythonhosted.org/packages/0a/c4/b924cbd5516676f4e612329f18602a833bd055ffbe27f808eeba0f01bfea/msgpack-1.2.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:652d1bf13d01bac8fd569def0fe76745e55bcda01e30aa6332d5947ea3788839", size = 411328, upload-time = "2026-08-27T10:03:05.869Z" }, + { url = "https://files.pythonhosted.org/packages/27/9d/0c1d9683a951a80f270c3b7dac1022c18b9307617344dd44d904135d5e12/msgpack-1.2.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:9bf452ff4d4981f25a18e9476e002bcc9263e7928024aa4d7148e25f7be3f929", size = 377892, upload-time = "2026-08-27T10:03:07.37Z" }, + { url = "https://files.pythonhosted.org/packages/06/bb/bf22338cdd22e0b40c8f28468cea5f3d9c320244c095d8303364bc012c41/msgpack-1.2.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:55faa6f8395e23b848c535ad5dcb96b3462f37f5e7f4ac500d500434f7345da7", size = 419426, upload-time = "2026-08-27T10:03:09Z" }, + { url = "https://files.pythonhosted.org/packages/7d/42/6d02c19a01abd8d7ce817c321d2ee6af1a8e24d584dca619d1b6576a83bf/msgpack-1.2.2-cp314-cp314t-win32.whl", hash = "sha256:419a45c67a5c04213172a14b1864657e014665b77d7081b107a51707923dd39e", size = 71810, upload-time = "2026-08-27T10:03:10.498Z" }, + { url = "https://files.pythonhosted.org/packages/af/df/fda3a204415dab0a8c0db5461ef7205416ea52bd8581c5cafd361be07f3b/msgpack-1.2.2-cp314-cp314t-win_amd64.whl", hash = "sha256:935b1cfad9b908b0fa845010f4271df4c2f04e1cd26e3f18acd61a45f93c9e36", size = 78919, upload-time = "2026-08-27T10:03:12.016Z" }, + { url = "https://files.pythonhosted.org/packages/63/d4/4b4b0ef25a86deca91feaf7252ca885ba4f2ada40461379120122a04fe96/msgpack-1.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:11e8c421e117d1c36728b423d0402555cccbf0c6f53e288f0e75b6b12100d70f", size = 71925, upload-time = "2026-08-27T10:03:13.332Z" }, + { url = "https://files.pythonhosted.org/packages/3b/92/4b44bc8f3243ef8cf9cb5368c17a299d45b9df858f6dfdd98a0482dbbb37/msgpack-1.2.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:e1b99ad34613d5f8477fa5cf99bc4eaeaf27965588007c102370cd9a78fe9de5", size = 84293, upload-time = "2026-08-27T10:03:14.718Z" }, + { url = "https://files.pythonhosted.org/packages/80/05/c992bb65744665a41b5bf531fc0e1619bae0901f57738228ded90023c151/msgpack-1.2.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:0fbc1bed8a535389b41882cfae66376e248cd1680eaa94fd83193c73e1d24986", size = 84490, upload-time = "2026-08-27T10:03:16.12Z" }, + { url = "https://files.pythonhosted.org/packages/d7/bf/7f53b9e6709a4df7f9b9b81dc65f9dfaa32caf65bee94986ec2cb8fa07f1/msgpack-1.2.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:06d95f61de7afe4f4ff908a6feebfcb070d0582ac87c9cf3cedf8551cf634516", size = 405332, upload-time = "2026-08-27T10:03:17.692Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5a/305c4dca14b50d0b51fb88ef04ec125b8f0be3e2ce730dcc62dbaa651cc5/msgpack-1.2.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b5c696ae7cd7166b3657261adb855b461ff31f07823fdbae9de8bf80adfccc21", size = 416798, upload-time = "2026-08-27T10:03:19.389Z" }, + { url = "https://files.pythonhosted.org/packages/7a/df/a645102b4cdfd9a94201cac4e900e9c1429fc16d86aa311c06eef82528c9/msgpack-1.2.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0708afbf6a9587f0bfe479a9825c141d14d91e2f6a5c8103cf28bc96f4edb5d9", size = 377312, upload-time = "2026-08-27T10:03:20.928Z" }, + { url = "https://files.pythonhosted.org/packages/f4/26/c56d8d086d3fb1077bb48092b158b5ea2eee08b279e10c191275f13bc980/msgpack-1.2.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:226a62ffe99fe54c5c61d910ec64c3449b7766c3280bd286bf6c94838dde239a", size = 395182, upload-time = "2026-08-27T10:03:22.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/b5/3d46ba367a565e536d8d2a61eebcee71b1dc803da3ce74a22313b573d6fa/msgpack-1.2.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:9fd7f32e2f0fb334e7ecc5adb5cf0458785bd3a9d9d86f950e1715f101cebce5", size = 377945, upload-time = "2026-08-27T10:03:24.151Z" }, + { url = "https://files.pythonhosted.org/packages/a5/2c/d5d2df273ed5306357da25b69400fd8d7a53c4d87d8976604b677484d61c/msgpack-1.2.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:9db1ba1c1e6a84245a9dd866265b56b8a1e9461549cc72ed296d8cbfbd32961b", size = 413341, upload-time = "2026-08-27T10:03:25.85Z" }, + { url = "https://files.pythonhosted.org/packages/1b/fb/32613bced3cad47b40b1b73dd04d687121349d83f748efc2575929121903/msgpack-1.2.2-cp315-cp315-win32.whl", hash = "sha256:e2eb7ea0ac3911a7aac9d8aaa36d40f216d99455b3274cd3fac38181bcd910cf", size = 66730, upload-time = "2026-08-27T10:03:27.294Z" }, + { url = "https://files.pythonhosted.org/packages/74/56/d86171f7251015e9312e5a7f9fdd4cf89752fc2114b88fed453d2a040c66/msgpack-1.2.2-cp315-cp315-win_amd64.whl", hash = "sha256:9352e6cdb510a7b1a5d3ccaccec730e82e50cf3484a3af7bdaab19e23b9589ff", size = 73477, upload-time = "2026-08-27T10:03:28.615Z" }, + { url = "https://files.pythonhosted.org/packages/13/1a/56b90f6defef61700b86baca3637c15f62ac0f9b21ab0f16613ab9d1f101/msgpack-1.2.2-cp315-cp315-win_arm64.whl", hash = "sha256:29cc2d5291711a52956a79a51f41c732329df39ad727c886bd8f0b5b9237a808", size = 67660, upload-time = "2026-08-27T10:03:29.895Z" }, + { url = "https://files.pythonhosted.org/packages/cd/20/12751ca0d8ec874701b54c392c2b19f51af8dd1de40a92a10e356f0aaf58/msgpack-1.2.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:d886baa46b2532135e7320067e6a44edb09ba5883a6096b0f9c044533984b8a8", size = 86462, upload-time = "2026-08-27T10:03:31.348Z" }, + { url = "https://files.pythonhosted.org/packages/91/4c/cf6d12a3d709fe5f9771dd917c35e6ebcd55597a5b792287382fde056c95/msgpack-1.2.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53679573c75cce5f82359e0bd4e6a97809a6b9a9b7a48fd1ba592f4a82cddc84", size = 87412, upload-time = "2026-08-27T10:03:32.74Z" }, + { url = "https://files.pythonhosted.org/packages/ca/0d/0aac5752d1708dcb458f8754db34a4999514db3df2d2b798b9381293f638/msgpack-1.2.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d3c247d457ae9079974c7ce3c665396754a6d2baff7eaa51332212a8a5a3f13b", size = 422057, upload-time = "2026-08-27T10:03:34.124Z" }, + { url = "https://files.pythonhosted.org/packages/81/30/70f281a3685b04aaf235a5237da11b978a02a865a5a479186205177ad676/msgpack-1.2.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:352ed831042549cca8be23780e1fe7c9177e65ff02bf183509c4b4d33f671782", size = 422696, upload-time = "2026-08-27T10:03:35.862Z" }, + { url = "https://files.pythonhosted.org/packages/8a/6d/f76e8425efb0aa38988cd778ae290bfa120491d80d26872d88bb52fedb3f/msgpack-1.2.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f80361592c13d7226b4379c8941529b63fe1a9d0e05d2de8f3306b70e522b53f", size = 376495, upload-time = "2026-08-27T10:03:37.339Z" }, + { url = "https://files.pythonhosted.org/packages/95/77/0809aa9b52b2868f7d01862dc14073708f0440421a65197b48453480034c/msgpack-1.2.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:68df2947921d449f6dcfeafd86cb2cdde13327a8b447534bbe4ee5aaf32a5695", size = 404683, upload-time = "2026-08-27T10:03:38.87Z" }, + { url = "https://files.pythonhosted.org/packages/02/d2/4e5ac915ba120172d210ef00165c5e6276c8a65db3a4a5cf36e946b83e23/msgpack-1.2.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:51dd39d23cfdea0400ed3ff2d29d1e83bd951d3aea79dc89be5b701a09edfe23", size = 375087, upload-time = "2026-08-27T10:03:40.486Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e3/8051d53e5495c87c6cf27eb42fb680361017037f87f322bdaf525f71e4a2/msgpack-1.2.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b13b59e66f107cca1ba708dd5307179870ca1b15b19fcee7ccf722e5308d9212", size = 414421, upload-time = "2026-08-27T10:03:42.308Z" }, + { url = "https://files.pythonhosted.org/packages/ba/4e/13783aa7c17414d7186c72c49bc718366f75e49f0ea58d4f81cb63ac3187/msgpack-1.2.2-cp315-cp315t-win32.whl", hash = "sha256:8c6321a414f8b4a8dc43976b2fa8349156434ca9adedd9a187b796f7e1d3d3fc", size = 71790, upload-time = "2026-08-27T10:03:43.715Z" }, + { url = "https://files.pythonhosted.org/packages/5e/9d/1d02994c7ae2603c98100984428ff0f67443572133bc18eca6058f732c1b/msgpack-1.2.2-cp315-cp315t-win_amd64.whl", hash = "sha256:6f53285f20d592ed309ee19e509cc4c77a3bda1db02ad67e8a0949bb227a5a6d", size = 78766, upload-time = "2026-08-27T10:03:45.036Z" }, + { url = "https://files.pythonhosted.org/packages/60/54/89ed16e6f966a050dc78b0e94a545025211b07ce9f4bdfe07dff70c03fc2/msgpack-1.2.2-cp315-cp315t-win_arm64.whl", hash = "sha256:a378e12ccc06d76efde115caf4073b7e5ff3cc18291d1341f9e65fb882e3f754", size = 71819, upload-time = "2026-08-27T10:03:46.375Z" }, +] + +[[package]] +name = "ndi-python" +version = "6.3.2.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/c2/af784f75a3b500b0b63cae6b598258c03c32e75c7cba22e9a7b53e027525/ndi_python-6.3.2.4-cp314-cp314-macosx_13_0_arm64.whl", hash = "sha256:f512fffde3ab0be5ff02ea1e6f1aa22020bbdb25d58d9fc7c551d1c362364555", size = 4868751, upload-time = "2026-09-07T11:36:19.436Z" }, + { url = "https://files.pythonhosted.org/packages/e5/2f/9fdaa3b51c297c52138031916093baef96855c868a0656ededb14a00138b/ndi_python-6.3.2.4-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6c933207fd34a145cb8326287af3947095c9bd6f82a615f208ae72de773d20a7", size = 5731079, upload-time = "2026-09-07T11:36:21.761Z" }, + { url = "https://files.pythonhosted.org/packages/30/37/9493a4ac846edb31e00fd4f237947f96621e0b44f9e1a4edcd481e0751de/ndi_python-6.3.2.4-cp314-cp314-manylinux_2_26_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:cb022fceae8c6001fe9c5f7b9bee9ee134420d30667152f06cd4d8d6b003856d", size = 5662574, upload-time = "2026-09-07T11:36:23.745Z" }, + { url = "https://files.pythonhosted.org/packages/8a/14/53a6ffa6fa1966b8e93d61dcc8893c4111dc163e185c0bf74b008685fb50/ndi_python-6.3.2.4-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:69e3d0ef9c1f60a64584214997dc0bac432c65256805e68a9f7842301b930c82", size = 10401289, upload-time = "2026-09-07T11:36:26.286Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ed/90c175c94a8a32750ad4aadc3254bdea0c54caf85007fc47d1ab76251f40/ndi_python-6.3.2.4-cp314-cp314-win_amd64.whl", hash = "sha256:e9654efddc936247c5e1abbb09ed39e719206e49bd33a09aa019a3cc8b4deef6", size = 4779158, upload-time = "2026-09-07T11:36:28.814Z" }, +] + +[[package]] +name = "numpy" +version = "2.5.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/13/01/11703282db468b85f6f7b8c7f22d058de5970d5c7e60a3a8aaa313c3de36/numpy-2.5.3.tar.gz", hash = "sha256:df2d5874ff183595a4ba404edd04f6bd9b5505c1d7708573f6a6c17489a67563", size = 20791231, upload-time = "2026-09-06T16:27:47.073Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/70/78/cf416f15dc29375a229d9dfebf8db6e313f291580b39fa1a568b6052bb07/numpy-2.5.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:350ba9783ce969cf9f7ce6e6a9a58e1a6e2a19ca025b7ee448c4db727706212a", size = 16998686, upload-time = "2026-09-06T16:25:33.171Z" }, + { url = "https://files.pythonhosted.org/packages/9e/59/abcc2d8def4fd60eec7d87f92d27c13448ffd9ab14339bcc63a0d7a2fdea/numpy-2.5.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:012e66aca395d795496446e52aeeb5866312a5d4d3f27da270e5a0b43f70dc5c", size = 12013862, upload-time = "2026-09-06T16:25:36.748Z" }, + { url = "https://files.pythonhosted.org/packages/94/75/4640d2d6e4b64a049e48425a82728a41ef4adb61332d2cba68055774878b/numpy-2.5.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:adc1ada2662f8a5f960b8a10d9986897e7499ef07e06d4cfe7197f8cce923c07", size = 5449793, upload-time = "2026-09-06T16:25:39.476Z" }, + { url = "https://files.pythonhosted.org/packages/96/cd/625b57ae33d4ca560f32cc0b47b4a5922146d9beb998ddf773900d440a73/numpy-2.5.3-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:54a115e5a73b8fc44f0cebef486365a1894b5c9760685d4558b72b7c3eb846e0", size = 6785176, upload-time = "2026-09-06T16:25:42.069Z" }, + { url = "https://files.pythonhosted.org/packages/9c/72/12918652e7912ef9751e8694c88820fcd1908e0618cb23f5f3caa6004b7b/numpy-2.5.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be5a8381859b6da607c84f4f7d6847725f1cf1853ef8a2c9e115b7d58bef47dc", size = 15703377, upload-time = "2026-09-06T16:25:45.135Z" }, + { url = "https://files.pythonhosted.org/packages/45/8f/9beacf79ca7c650688ad0baa80931adb988fe6e6e5d5903c23cc3dbd70eb/numpy-2.5.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b0521d0f4aebb6e06189451025fa17a913287b13c03d5fe05c017333b654ea5b", size = 16711928, upload-time = "2026-09-06T16:25:48.461Z" }, + { url = "https://files.pythonhosted.org/packages/09/8d/41d0a56e1ac4c87495c897a211b1368691b7237aadabec8b3b8f3a74d48f/numpy-2.5.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:9deb49575e5b0b94ed72c8a64ec4d033381adc27e9060ae842971f697ba96104", size = 17059507, upload-time = "2026-09-06T16:25:51.873Z" }, + { url = "https://files.pythonhosted.org/packages/08/1e/0dfbc5cc251d54e2af790f254d24ec38637fa97ec7d5d11de7ffed787098/numpy-2.5.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b00eefbcf0f292945c4b4dec2ae845389ef5bcdcd596e6e4328051db5b5ba694", size = 18471002, upload-time = "2026-09-06T16:25:55.233Z" }, + { url = "https://files.pythonhosted.org/packages/b5/2c/dfa40f6991f8185c8c30ffd023dfcbb11888e823cfab9557b920f3bb7bed/numpy-2.5.3-cp314-cp314-win32.whl", hash = "sha256:c2381f82999704f818e2c987a865050e285ec3621262c66d40f5a96c8f899f8e", size = 6180485, upload-time = "2026-09-06T16:25:58.157Z" }, + { url = "https://files.pythonhosted.org/packages/a4/73/d2c08231e4fde7e415501fd02c715d96e98599b2d8384445933944152984/numpy-2.5.3-cp314-cp314-win_amd64.whl", hash = "sha256:2c25dfa72943e4336ddb6b0ee4277b47a0c85bede0807530ec68103bf58e2c10", size = 12698179, upload-time = "2026-09-06T16:26:00.789Z" }, + { url = "https://files.pythonhosted.org/packages/5c/e9/dcdcc9b95cf5f49815055573aee1b11cfbf5299f38a180e437ded050810f/numpy-2.5.3-cp314-cp314-win_arm64.whl", hash = "sha256:15aa985ac73a8db02db7663381aa109510449d3819d37206caed27b33a65a8a6", size = 10769383, upload-time = "2026-09-06T16:26:04.011Z" }, + { url = "https://files.pythonhosted.org/packages/49/c4/af8bc08a7ef4e1529a7c0cf24969accce316b783999802089a581ec99272/numpy-2.5.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ac7bb1c52d445bd4f8f7f97fefe6abc3a084dc4d63df50d79b17fa2b78e89297", size = 12132668, upload-time = "2026-09-06T16:26:07.138Z" }, + { url = "https://files.pythonhosted.org/packages/c5/ae/0f15eb56d4ec5e13c1f7ff04ff407f997d1acbadb45d3e1f2e2645a8f43c/numpy-2.5.3-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:e6ab667ba76450084eb64013762c438ea76d9d29cc676dcd6c2e9892ba37f841", size = 5568580, upload-time = "2026-09-06T16:26:09.828Z" }, + { url = "https://files.pythonhosted.org/packages/23/fb/c72a8f25d4b6e96c354e7ab45ace3b27dc11e5d6a13b6c7d0cd6b08bf112/numpy-2.5.3-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:f7fabeb6cea87d65f3b926de33d03fb016cfdc29314c90974383b5582ae72891", size = 6882634, upload-time = "2026-09-06T16:26:12.524Z" }, + { url = "https://files.pythonhosted.org/packages/07/a9/968c90ed2ab15060c338e8137f1215b5a60756ae07328e0a60d1c6734df4/numpy-2.5.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1fb6f8fb9ff0b3a69f52c66ce397b0246583e9f28616231b0e32ca49259a5fa6", size = 15748923, upload-time = "2026-09-06T16:26:15.092Z" }, + { url = "https://files.pythonhosted.org/packages/59/08/9df04103947b95e3b6b1f2ed1a70521f325647a31b82da6a2aae3a485508/numpy-2.5.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93e1f5447e2b1e479d7bd74701e84746b86450cff1fc368b132d195e2b8f8211", size = 16746748, upload-time = "2026-09-06T16:26:18.43Z" }, + { url = "https://files.pythonhosted.org/packages/41/a0/14c8d5fe5b53a334aabb653deb391c0fef49558f491880ea300ed6785224/numpy-2.5.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c00abe94c1a69d75d827dcf1c025b25c8a45d230b3bcd77a9020883a1b047653", size = 17111561, upload-time = "2026-09-06T16:26:22.113Z" }, + { url = "https://files.pythonhosted.org/packages/c4/a6/d7e96e42f01522e154c32489640f16dfc4f6181d165d05fc3bec8c2c4999/numpy-2.5.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:536f963710a4e63934d80ac0dc4f478804a83e9a84b6828018f25d09953ada33", size = 18513945, upload-time = "2026-09-06T16:26:25.401Z" }, + { url = "https://files.pythonhosted.org/packages/25/39/3453afb7119d0449ef11c886874120ff180e2c337760e0e2d88f70f1a945/numpy-2.5.3-cp314-cp314t-win32.whl", hash = "sha256:4c8a6d2ebce6305fd82fbefca827775437147052a976ee7c94b36a0c1b52ac6c", size = 6335421, upload-time = "2026-09-06T16:26:28.175Z" }, + { url = "https://files.pythonhosted.org/packages/99/01/22815d2b19a1a746b1d45205cffebb3fe511a18acb75fba6c88491fc9894/numpy-2.5.3-cp314-cp314t-win_amd64.whl", hash = "sha256:9a37475425b431b4d060f23b4f52cd2f3aef6bc7c654bd760adf0040eec9d435", size = 12896420, upload-time = "2026-09-06T16:26:31.265Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ee/a7cbba67eeaff038dc29ca8b98a88396c8b0cc9c89d4924f4a27a5c9150b/numpy-2.5.3-cp314-cp314t-win_arm64.whl", hash = "sha256:2d8240cb4c16fd831074aa2b2cf9fc54664d826341d61c372245b96a74a49a9a", size = 10857177, upload-time = "2026-09-06T16:26:34.167Z" }, + { url = "https://files.pythonhosted.org/packages/45/56/78194492883ff5eec90423fe56a3a44b154da047d88a6307f629713c584f/numpy-2.5.3-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a6391fafaba97500887132cd582abc6e19452b1ac775a47caa7b24490e152058", size = 16996531, upload-time = "2026-09-06T16:26:37.287Z" }, + { url = "https://files.pythonhosted.org/packages/11/39/dd55c0af90bbab564b09ae3b0aa60ec5c02b900fa4f1ba23440525c8b32d/numpy-2.5.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:09d5a423c71ad5feb5625844ad58050e35df43871004b52ac9c0ad44a56775be", size = 12012569, upload-time = "2026-09-06T16:26:40.707Z" }, + { url = "https://files.pythonhosted.org/packages/b6/51/04f67d32e4862b281b1cb84ceeaed3421189a84fb6fb51a391cd6d5009f7/numpy-2.5.3-cp315-cp315-macosx_14_0_arm64.whl", hash = "sha256:f9579f383d1bf9df80081e72760e84960a7fd4f88cf0c9e535a8597c9bb646f5", size = 5448498, upload-time = "2026-09-06T16:26:43.435Z" }, + { url = "https://files.pythonhosted.org/packages/a3/c9/25b4dc0dd1344ec26c7319e84fd4e9809d2b5628f4e12decd618036e5178/numpy-2.5.3-cp315-cp315-macosx_14_0_x86_64.whl", hash = "sha256:86bff898a431c0fb71f7610b75726e75a54d47b37edc9d537f48de63bb3c0b90", size = 6783026, upload-time = "2026-09-06T16:26:46.374Z" }, + { url = "https://files.pythonhosted.org/packages/fc/c7/29285be1e5232a6e7ee3268a33c85843f5a8ee93350c6465cddd66ebbf76/numpy-2.5.3-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1f3ed25271581281f2fccb1adcedfcde4c07362eec69189b50baf6f90e3ae159", size = 15697322, upload-time = "2026-09-06T16:26:49.415Z" }, + { url = "https://files.pythonhosted.org/packages/55/49/bbad5335fb4996a16881f853ff3e0ba582f01720e55c89b1c06b8fc42a90/numpy-2.5.3-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffdc76bfcae6b255dff75202c5e7feaf95b40246bc0a17944facc1fecf9f79ab", size = 16708995, upload-time = "2026-09-06T16:26:53.127Z" }, + { url = "https://files.pythonhosted.org/packages/ef/e9/1df35483760b04a65ea44669f89dc64f30e5aca098b48ceb8b1310b0e0fe/numpy-2.5.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:116f96cadd935c6122e9228d676fe7ede19e741f5c8bb1c3cddbe0c51ccebea2", size = 17052508, upload-time = "2026-09-06T16:26:56.464Z" }, + { url = "https://files.pythonhosted.org/packages/b8/99/66e54da8265cc8be8a7382bf96edce17aaa2837d6f484432025932a3caa5/numpy-2.5.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:09ffa5d903faeaa5c4dd05009cf81c8bab9f2cb37c548b8d39b65b4cfa7c97f7", size = 18468224, upload-time = "2026-09-06T16:26:59.966Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/b5e90a91c115168d793dfd2ad9c69c438c2fe7a13a437e770bc5b078e732/numpy-2.5.3-cp315-cp315-win32.whl", hash = "sha256:e01c918ac3d48e18a927cf7b14a26a3e29ff2bdf2eacb976da0aecd6a43ed034", size = 6179919, upload-time = "2026-09-06T16:27:03.166Z" }, + { url = "https://files.pythonhosted.org/packages/37/ea/780748fd3985109075514ef8fc64cd25f943e40dde13a6d59141eb268fc8/numpy-2.5.3-cp315-cp315-win_amd64.whl", hash = "sha256:e931e4f499e0dc7ef29d269a8e5b35dd722e5d14be07df6240166ea7c6532fae", size = 12697656, upload-time = "2026-09-06T16:27:06.153Z" }, + { url = "https://files.pythonhosted.org/packages/b3/16/407be69a2a87c8cab64d95975a8977a426a29e138f07e276ec258f0fe4e5/numpy-2.5.3-cp315-cp315-win_arm64.whl", hash = "sha256:26e15e4aecd8617dfbaecb37d223e365d7b39411fba20454be2670a96aa74cb5", size = 10767601, upload-time = "2026-09-06T16:27:09.297Z" }, + { url = "https://files.pythonhosted.org/packages/44/bf/a97ffb01e41d50a32a9177aef942a4d0e389a3daf451d04e5f38ef6afb87/numpy-2.5.3-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:6cef4bb1706dfec49243c05d921eefb4e190d41e2528b30d8035ea1f36b4c24a", size = 17090092, upload-time = "2026-09-06T16:27:12.907Z" }, + { url = "https://files.pythonhosted.org/packages/d1/24/136c02f2c2af9a067a84d0c3aa10c99012c0476fa5066732fa4a4202557d/numpy-2.5.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:d1c89973648c85069c5046ad460f7b8a00218b29a2e42359ac8cc63e9ab94832", size = 12129429, upload-time = "2026-09-06T16:27:16.089Z" }, + { url = "https://files.pythonhosted.org/packages/fe/6c/b47582d6597789bf946d5efbeb6b9e56fd8bcbd5efc6fbf51dbe1ea31eb3/numpy-2.5.3-cp315-cp315t-macosx_14_0_arm64.whl", hash = "sha256:214045a5bf00113a146ab9ee9730c44501af6723cdf1f6830932f7b5ef2e7af0", size = 5565452, upload-time = "2026-09-06T16:27:19.868Z" }, + { url = "https://files.pythonhosted.org/packages/be/b4/ef3cc6da73774202d4deae16bb321fd8298a4e0561e3539f8c4be237d916/numpy-2.5.3-cp315-cp315t-macosx_14_0_x86_64.whl", hash = "sha256:8617bbfae4486cf99c9f899966699428d19da931d06ca94ad3da986c76e15997", size = 6876736, upload-time = "2026-09-06T16:27:22.232Z" }, + { url = "https://files.pythonhosted.org/packages/9e/24/e3813329498596cb842703dcacac1741612ed9fb9c4e6a3e0c7e2ebbc597/numpy-2.5.3-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:595d020938c84e320bcf40ad71089e108eac0d377cd018e14a8c094f39e98d85", size = 15745777, upload-time = "2026-09-06T16:27:25.181Z" }, + { url = "https://files.pythonhosted.org/packages/4a/9e/4e7a07fd0776dc2210cdacf2010be8665194d094defc10c419d7dea794cc/numpy-2.5.3-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f24021b9f22bc6301c37b196974a92c1c18dccedb6fef3dd252e95f2d6adbe4", size = 16746949, upload-time = "2026-09-06T16:27:28.576Z" }, + { url = "https://files.pythonhosted.org/packages/91/db/01674c0e20335057813a00c2ebd546ed25bff9ed7914f9bced00f8c55d94/numpy-2.5.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:71b39d9f935b6ec0f8753e3e2afb51e3efba6f2e05b68b32a40754d24bcd4a3c", size = 17108994, upload-time = "2026-09-06T16:27:31.946Z" }, + { url = "https://files.pythonhosted.org/packages/45/7a/584c5e71f8d378e57cac0b033891ed65c683ef90573ba4854e8c28203db0/numpy-2.5.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:6b05c171afb3aa07adbd20abc00aea86fe375beb0fdb9ef780ec5b7f63bab1c0", size = 18512266, upload-time = "2026-09-06T16:27:35.196Z" }, + { url = "https://files.pythonhosted.org/packages/a1/d2/4e1014173aa3c55e6a756e0e567290743a6ab33a288460374d7ef6bcd239/numpy-2.5.3-cp315-cp315t-win32.whl", hash = "sha256:f54660b0eb6b0b9f36e7fe1cdfdff472028dd0d14acd9b9b65098efbad059469", size = 6330292, upload-time = "2026-09-06T16:27:38.149Z" }, + { url = "https://files.pythonhosted.org/packages/6c/b0/ff5658a58199b7bcaad87bf260eef6713d9d42cca4e028f935b4fc5fbac6/numpy-2.5.3-cp315-cp315t-win_amd64.whl", hash = "sha256:1aad64d99730d013cfc6debafed22783b4fc5a7f4b8bc744d2d8cf7dcc880551", size = 12884918, upload-time = "2026-09-06T16:27:40.965Z" }, + { url = "https://files.pythonhosted.org/packages/fb/0b/b12a2df5d1b774bd9007a6fdff9381145b6223d37f11afc9c37ab0efd9a1/numpy-2.5.3-cp315-cp315t-win_arm64.whl", hash = "sha256:befa1ae5bd6030b3f512b43ff3fa5290bbed6b84411a44244b14adf835f5b89d", size = 10850807, upload-time = "2026-09-06T16:27:43.868Z" }, +] + +[[package]] +name = "oauthlib" +version = "3.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0b/5f/19930f824ffeb0ad4372da4812c50edbd1434f678c90c2733e1188edfc63/oauthlib-3.3.1.tar.gz", hash = "sha256:0f0f8aa759826a193cf66c12ea1af1637f87b9b4622d46e866952bb022e538c9", size = 185918, upload-time = "2025-06-19T22:48:08.269Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/9c/92789c596b8df838baa98fa71844d84283302f7604ed565dafe5a6b5041a/oauthlib-3.3.1-py3-none-any.whl", hash = "sha256:88119c938d2b8fb88561af5f6ee0eec8cc8d552b7bb1f712743136eb7523b7a1", size = 160065, upload-time = "2025-06-19T22:48:06.508Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pillow" +version = "12.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/01/001f65b68192f0228cc1dbbc8d2530ab5d58b61037ba0587f946fea607cd/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:9cf95fe4d0f84c82d282745d9bb08ad9f926efa00be4697e767b814ce40d4330", size = 4161736, upload-time = "2026-07-01T11:54:51.156Z" }, + { url = "https://files.pythonhosted.org/packages/1a/d2/0219746d0fd16fc8a84498e79452375be3797d3ce4044596ce565164b84f/pillow-12.3.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:8728f216dcdb6e6d555cf971cb34076139ad74b31fc2c14da4fafc741c5f6217", size = 4255435, upload-time = "2026-07-01T11:54:53.414Z" }, + { url = "https://files.pythonhosted.org/packages/c8/02/8d0bc62ef0302318c46ff2a512822d2610e81c7aa46c9b3abe6cbaca5ad0/pillow-12.3.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:a45650e8ce7fafffd731db8550230db6b0d306d181a90b67d3e6bca2f1990930", size = 3696262, upload-time = "2026-07-01T11:54:55.739Z" }, + { url = "https://files.pythonhosted.org/packages/85/e2/73c77d218410b14f5f2d565e8a998d5317b7b9c75368d29985139f7a46f0/pillow-12.3.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:ba54cfebe86920a559a7c4d6b9050791c20513650a1952ebe3368c7dc70306f8", size = 5350344, upload-time = "2026-07-01T11:54:57.657Z" }, + { url = "https://files.pythonhosted.org/packages/c7/da/32c752228ae345f489e3a42499d817b6c3996da7e8a3bc7a04fc806b243b/pillow-12.3.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e158cb00350dc278f3b91551101aa7d12415a66ebf2c91d8d5ac14e56ddd3ad0", size = 4780131, upload-time = "2026-07-01T11:54:59.713Z" }, + { url = "https://files.pythonhosted.org/packages/b1/9d/8b2c807dbef61a5197c047afe99823787eb66f63daf9fb2432f91d6f0462/pillow-12.3.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e9aeb04d6aef139de265b29683e119b638208f88cf73cdd1658aa07221165321", size = 6263757, upload-time = "2026-07-01T11:55:01.778Z" }, + { url = "https://files.pythonhosted.org/packages/5c/44/c85361f65dbe00eea8576ee467c768d25129989efb76e94f205e9ca9bb46/pillow-12.3.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:251bf95b67017e27b13d82f5b326234ca62d70f9cf4c2b9032de2358a3b12c7b", size = 6936962, upload-time = "2026-07-01T11:55:03.93Z" }, + { url = "https://files.pythonhosted.org/packages/18/7e/e483414b35800b86b6f08dbbc7803fb5cd52c4d6f897f47d53ea2c7e6f65/pillow-12.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fe3cca2e4e8a592be0f269a1ca4835c25199d9f3ce815c8491048f785b0a0198", size = 6339171, upload-time = "2026-07-01T11:55:05.989Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f4/68c491844841ede6bed70189546b3ee9731cf9f2cbad396faff5e1ccba45/pillow-12.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:23aceaa007d6172b02c277f0cd359c79492bbb14f7072b4ede9fbcaf20648130", size = 7048116, upload-time = "2026-07-01T11:55:08.131Z" }, + { url = "https://files.pythonhosted.org/packages/a3/34/77f3f793fed8efc7d243f21b33c5a3f0d1c97ee70346d3db855587e155ff/pillow-12.3.0-cp314-cp314-win32.whl", hash = "sha256:af8d94b0db561cf68b88a267c5c44b49e134f525d0dc2cb7ed413a66bc23559a", size = 6467209, upload-time = "2026-07-01T11:55:10.408Z" }, + { url = "https://files.pythonhosted.org/packages/f1/e0/492879f69d94f91f60fc8cd05ba03650e9520afebb2fb7aa12777d7c7f38/pillow-12.3.0-cp314-cp314-win_amd64.whl", hash = "sha256:fdafc9cce40277e0f7a0feabce0ee50dd2fa1800f3b38015e51296b5e814048d", size = 7237707, upload-time = "2026-07-01T11:55:12.745Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ac/6b11f2875f1c2ac040d84e1bbf9cf22a88038f901ca1037898b280b38365/pillow-12.3.0-cp314-cp314-win_arm64.whl", hash = "sha256:e91206ee562682b51b98ef4b26a6ef48fd84e15fd4c4bc5ec768eb641d206838", size = 2565995, upload-time = "2026-07-01T11:55:14.736Z" }, + { url = "https://files.pythonhosted.org/packages/52/69/c2208e56af9bfc1913afb24020297a691eb1d4ef688474c8a04913f65e04/pillow-12.3.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:164b31cd1a0490ab6efae01aa5df49da7061be0af1b30e035b6e9a1bfe34ee6e", size = 5352503, upload-time = "2026-07-01T11:55:17.076Z" }, + { url = "https://files.pythonhosted.org/packages/07/70/e5686d753e898a45d778ff1718dba8516ead6ab6b95d85fc8c4b70650cf2/pillow-12.3.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5afb51d599ea772b8365ae807ae557f18bccfe46ab261fd1c2a9ed700fc6eb17", size = 4782956, upload-time = "2026-07-01T11:55:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/d5/37/25c6692f06927ee973ff18c8d9ee98ad0b4d84ee67a09610c2dd1447958e/pillow-12.3.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3edce1d53195db527e0191f84b71d02022de0540bf43a16ed734ed7537b07385", size = 6322855, upload-time = "2026-07-01T11:55:21.613Z" }, + { url = "https://files.pythonhosted.org/packages/cc/91/420637fcb8f1bc11029e403b4538e6694744428d8246118e45719f944556/pillow-12.3.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf16ba1b4d0b6b7c8e534936632270cf70eb00dbe09005bc345b2677b726855c", size = 6989642, upload-time = "2026-07-01T11:55:24.006Z" }, + { url = "https://files.pythonhosted.org/packages/10/08/b94d7811281ccf0d143a1cf768d1c49e1e54af63e7b708ab2ee3eb87face/pillow-12.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:24870b09b224f7ae3c39ed07d10e819d06f8720bc551847b1d623832b5b0e28d", size = 6391281, upload-time = "2026-07-01T11:55:26.252Z" }, + { url = "https://files.pythonhosted.org/packages/d2/87/24233f785f55474dc02ce3e739c5528a77e3a862e9333d1dd7a25cc31f70/pillow-12.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:30f2aa603c41533cc25c05acd0da21636e84a315768feb631c937177db558931", size = 7096716, upload-time = "2026-07-01T11:55:28.318Z" }, + { url = "https://files.pythonhosted.org/packages/23/26/fcb2f6e37175b04f53570b59937867e2b80ee1685e744023153028fc14f9/pillow-12.3.0-cp314-cp314t-win32.whl", hash = "sha256:4b0a7fe987b14c31ebda6083f74f22b561fd3739bc0ac51e019622e3d72668c7", size = 6474125, upload-time = "2026-07-01T11:55:30.956Z" }, + { url = "https://files.pythonhosted.org/packages/90/de/3634abee5f1c9e13c56787b7d5517b0ba8d6de51700b95578cf338349c9f/pillow-12.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:962864dc93511324d51ddbb5b9f8731bf71675b93ca612a07441896f4688fb8c", size = 7242939, upload-time = "2026-07-01T11:55:34.044Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2a/fd13f8eb24de5714a6eb444a3d67e2842c6c576e159a43793adf23051351/pillow-12.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0740a512dc522224c77d9aa5a8d70d8b7d73fb91f2c21125d8d025d3b8990e45", size = 2567506, upload-time = "2026-07-01T11:55:35.988Z" }, + { url = "https://files.pythonhosted.org/packages/5d/dc/8fdce34ec725a33c81c6ba122b904d6b9024e50ea9ac7bede62fab54506c/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0feb2e9d6ad6c9e3c06effe9d00f3f1e618a6643273576b016f591e9315a7139", size = 4162063, upload-time = "2026-07-01T11:55:37.941Z" }, + { url = "https://files.pythonhosted.org/packages/76/66/2044b9a63d3b84ff048228dfcb7cd9bf0df983e8470971bf7d4c57b693de/pillow-12.3.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9e881fca225083806662a5c43d627d215f258ff43c890f831966c7d7ba9c7402", size = 4255549, upload-time = "2026-07-01T11:55:40.022Z" }, + { url = "https://files.pythonhosted.org/packages/52/7e/1f67e6f4ece6b582ee4b539decbcc9f848dc245a93ed8cd7338bafef72f1/pillow-12.3.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:4998562bf62a445225f22e07c896bb04b35b1b1f2eb6d760584c9c51d7a5f78c", size = 3696331, upload-time = "2026-07-01T11:55:41.98Z" }, + { url = "https://files.pythonhosted.org/packages/12/40/d306fc2c8e4d45d7f175c77edca7063be7b86fe7fe6e68f4353bf71d808c/pillow-12.3.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:dc624f6bc473dacdf7ef7eb8678d0d08edf15cd94fad6ae5c7d6cc67a4e4902f", size = 5350370, upload-time = "2026-07-01T11:55:44.028Z" }, + { url = "https://files.pythonhosted.org/packages/dd/44/668fb1437e8ce420f62d6106eb66e44a5971602a4d794615bdf79315d82d/pillow-12.3.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:71d6097b330eea8fd15097780c8e89cb1a8ce7838669f48c5bacd6f663dd4701", size = 4780147, upload-time = "2026-07-01T11:55:46.073Z" }, + { url = "https://files.pythonhosted.org/packages/0c/08/93fa2e70e30a2d81547e481b6ee2bb9522117221fb1e0ce4b5df70967677/pillow-12.3.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ce87c5ab450a9dd970b52e5aca5fe63ed432d18a2eaddd1979a00a1ba24ace", size = 6273659, upload-time = "2026-07-01T11:55:48.264Z" }, + { url = "https://files.pythonhosted.org/packages/f8/6d/043e96ff814fc31a33077e4cba86082167db520c93632afdf2042febbb0c/pillow-12.3.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6b02afb9b97f65fbca5f31db6a2a3ba21aa93030225f150fa3f249717e938fb4", size = 6947439, upload-time = "2026-07-01T11:55:50.503Z" }, + { url = "https://files.pythonhosted.org/packages/af/92/ba71d2ee2ac0edf3fa33bd9d5ee9ee080da70b1766f3ca3934f9938ddac9/pillow-12.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:1182d52bc2d5e5d7d0949503aa7e36d12f42205dc287e4883f407b1988820d39", size = 6353577, upload-time = "2026-07-01T11:55:52.697Z" }, + { url = "https://files.pythonhosted.org/packages/0f/ce/e63064e2122923ff687c8ad792d0d736a7b3920a56a46982e81a7fdd25d6/pillow-12.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e795b7eb908249c4e43c7c99fac7c2c75dab0c43566e37db472a355f63693d71", size = 7060394, upload-time = "2026-07-01T11:55:55.149Z" }, + { url = "https://files.pythonhosted.org/packages/54/76/a09cc3ccc8d773a7283d34c38bec1708f9e3cc932093cbc4c5e71ac4060b/pillow-12.3.0-cp315-cp315-win32.whl", hash = "sha256:57b3d78c95ba9059768b10e28b813002261d3f3dfc55cc48b0c988f625175827", size = 6467375, upload-time = "2026-07-01T11:55:57.769Z" }, + { url = "https://files.pythonhosted.org/packages/3e/03/1846c49ba3b1d5550392a4bbd06d6fb4578e1cd91a803198b5c90f5f7d53/pillow-12.3.0-cp315-cp315-win_amd64.whl", hash = "sha256:fa4ecea169a355be7a3ade2c783e2ed12f0e40d2c5621cda8b3297faf7fbb9f5", size = 7237048, upload-time = "2026-07-01T11:55:59.975Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bb/89f35dcc79610423f9f195504d7def7f0d1416a711541b42867e25fe3412/pillow-12.3.0-cp315-cp315-win_arm64.whl", hash = "sha256:877c3f311ff35410f690861c4409e7ccbf0cd2f878e50628a28e5a0bb689e658", size = 2566006, upload-time = "2026-07-01T11:56:02.143Z" }, + { url = "https://files.pythonhosted.org/packages/30/88/707027ba09942dfa2c28759b5c222d769290a41c6d20ea60ec250801941f/pillow-12.3.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:e9871b1ffbfa9656b60aeee92ed5136a5742696006fa322b29ea3d8da0ecc9cf", size = 5352509, upload-time = "2026-07-01T11:56:04.2Z" }, + { url = "https://files.pythonhosted.org/packages/b0/6d/00352fa25332c2569cd387851f568cc5a4b75a9adbfb37ac4fbce4c02eec/pillow-12.3.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:53aa02d20d10c3d814d536aa4e5ac9b84ca0ff5a88377963b085ad6822f93e64", size = 4783167, upload-time = "2026-07-01T11:56:06.631Z" }, + { url = "https://files.pythonhosted.org/packages/13/4f/9e049dfa21af7c22427275720e2490267ba8138120add5c4c574deb69782/pillow-12.3.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:446c34dcc4324b084a53b705127dc15717b22c5e140ae0a3c38349d4efec071e", size = 6329237, upload-time = "2026-07-01T11:56:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/36/16/cf6eeaae8d0fce8dd390a33437cf68c5d5bd73834a2bc6e2f14efda0ab45/pillow-12.3.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cf1845d02ad822a369a49f2bb9345b1614744267682e7a03527dc3bf6eea1777", size = 6997047, upload-time = "2026-07-01T11:56:11.379Z" }, + { url = "https://files.pythonhosted.org/packages/1e/69/dbf769bdd55f48bf5733cac28edc6364ffaa072ec9ba336266e4fe66be55/pillow-12.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:186941b6aef820ad110fb01fb06eb925374dc3a21b17e37ec9a53b250c6fe2d1", size = 6400440, upload-time = "2026-07-01T11:56:13.908Z" }, + { url = "https://files.pythonhosted.org/packages/a0/e1/ffc9cfc2eea0d178da8018e18e959301ad9d6bc9f3edb7181e748a474b97/pillow-12.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:f13c32a3abd6079a66d9526e18dad9b6d280384d49d7c54040cd57b6424041d9", size = 7105895, upload-time = "2026-07-01T11:56:16.575Z" }, + { url = "https://files.pythonhosted.org/packages/18/f0/a5595c1e8c3ae44b9828cb2f0fa8155e5095ef04d6327b8f61cf44a3df85/pillow-12.3.0-cp315-cp315t-win32.whl", hash = "sha256:1657923d2d45afb66526e5b933e5b3052e6bdea196c90d3abb2424e18c77dae8", size = 6474384, upload-time = "2026-07-01T11:56:18.855Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/62bcd9f844984c5938d3b05264a61d797a29d3e0812341a8204af70bbdee/pillow-12.3.0-cp315-cp315t-win_amd64.whl", hash = "sha256:8cd2f7bdda092d99c9fc2fb7391354f306d01443d22785d0cbfafa2e2c8bb418", size = 7243537, upload-time = "2026-07-01T11:56:21.214Z" }, + { url = "https://files.pythonhosted.org/packages/3d/68/1f3066acedf37673694a7141381d8f811ae97f30d34413d236abe7d489f1/pillow-12.3.0-cp315-cp315t-win_arm64.whl", hash = "sha256:06ff022112bc9cbf83b60f8e028d94ad87b60621706487e65f673de61610ab59", size = 2567491, upload-time = "2026-07-01T11:56:23.506Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + +[[package]] +name = "python-slugify" +version = "9.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "text-unidecode" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d8/ca/5740963aa82f2c9dd025d71f1b6cce2159545f9e60dcb86a447d1cf92252/python_slugify-9.1.0.tar.gz", hash = "sha256:3f02e8a0639c61e37eca5a783aae09112796d15d331ee3d5372241b61ee05f1c", size = 63567, upload-time = "2026-09-18T22:30:42.72Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/f1/e450f6f6eb1217a6dc5f015589a21566839297920304961a7c2230477837/python_slugify-9.1.0-py3-none-any.whl", hash = "sha256:ab2d1d0e7ad5fa46b3756f0f3fcfb37d6d5baa006ccd1f22c2481a6ab53b8c12", size = 15641, upload-time = "2026-09-18T22:30:41.612Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814, upload-time = "2025-09-25T21:32:35.712Z" }, + { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809, upload-time = "2025-09-25T21:32:36.789Z" }, + { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454, upload-time = "2025-09-25T21:32:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355, upload-time = "2025-09-25T21:32:39.178Z" }, + { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175, upload-time = "2025-09-25T21:32:40.865Z" }, + { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228, upload-time = "2025-09-25T21:32:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194, upload-time = "2025-09-25T21:32:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429, upload-time = "2025-09-25T21:32:57.844Z" }, + { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912, upload-time = "2025-09-25T21:32:59.247Z" }, + { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108, upload-time = "2025-09-25T21:32:44.377Z" }, + { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641, upload-time = "2025-09-25T21:32:45.407Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901, upload-time = "2025-09-25T21:32:48.83Z" }, + { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132, upload-time = "2025-09-25T21:32:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261, upload-time = "2025-09-25T21:32:51.808Z" }, + { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272, upload-time = "2025-09-25T21:32:52.941Z" }, + { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923, upload-time = "2025-09-25T21:32:54.537Z" }, + { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062, upload-time = "2025-09-25T21:32:55.767Z" }, + { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, +] + +[[package]] +name = "qrcode" +version = "8.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8f/b2/7fc2931bfae0af02d5f53b174e9cf701adbb35f39d69c2af63d4a39f81a9/qrcode-8.2.tar.gz", hash = "sha256:35c3f2a4172b33136ab9f6b3ef1c00260dd2f66f858f24d88418a015f446506c", size = 43317, upload-time = "2025-05-01T15:44:24.726Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/b8/d2d6d731733f51684bbf76bf34dab3b70a9148e8f2cef2bb544fccec681a/qrcode-8.2-py3-none-any.whl", hash = "sha256:16e64e0716c14960108e85d853062c9e8bba5ca8252c0b4d0231b9df4060ff4f", size = 45986, upload-time = "2025-05-01T15:44:22.781Z" }, +] + +[[package]] +name = "quickreplay" +version = "2.0.0" +source = { editable = "." } +dependencies = [ + { name = "av" }, + { name = "flet" }, + { name = "ndi-python" }, + { name = "numpy" }, +] + +[package.dev-dependencies] +dev = [ + { name = "flet-cli" }, + { name = "flet-desktop" }, + { name = "pytest" }, + { name = "ruff" }, + { name = "ty" }, +] + +[package.metadata] +requires-dist = [ + { name = "av", specifier = ">=18.1.0" }, + { name = "flet", specifier = "==1.0.0" }, + { name = "ndi-python", specifier = "==6.3.2.4" }, + { name = "numpy", specifier = ">=2.5.3" }, +] + +[package.metadata.requires-dev] +dev = [ + { name = "flet-cli", specifier = "==1.0.0" }, + { name = "flet-desktop", specifier = "==1.0.0" }, + { name = "pytest", specifier = ">=8.0" }, + { name = "ruff", specifier = ">=0.9" }, + { name = "ty", specifier = ">=0.0.1a0" }, +] + +[[package]] +name = "repath" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/65/e1/824989291d0f01886074fdf9504ba54598f5665bc4dd373b589b87e76608/repath-0.9.0.tar.gz", hash = "sha256:8292139bac6a0e43fd9d70605d4e8daeb25d46672e484ed31a24c7ce0aef0fb7", size = 5492, upload-time = "2019-10-08T00:25:22.3Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/ed/92e9b8a3ffc562f21df14ef2538f54e911df29730e1f0d79130a4edc86e7/repath-0.9.0-py3-none-any.whl", hash = "sha256:ee079d6c91faeb843274d22d8f786094ee01316ecfe293a1eb6546312bb6a318", size = 4738, upload-time = "2019-10-08T00:25:20.842Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rich" +version = "15.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/8f/0722ca900cc807c13a6a0c696dacf35430f72e0ec571c4275d2371fca3e9/rich-15.0.0.tar.gz", hash = "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36", size = 230680, upload-time = "2026-04-12T08:24:00.75Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/78/449cb84790bd5cc3823b2652ee405a4558856e5c4195aee3a16bf7b3eb5d/ruff-0.16.8.tar.gz", hash = "sha256:9247bf92b5f04d825c8639a4fe423ec2e4222acd9222e58412b0dab7e442798b", size = 4938814, upload-time = "2026-09-16T15:54:46.688Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ac/25/6071aabc530e9be7e2c195e8fe3f7aea2735405b6cf447212832d7811831/ruff-0.16.8-py3-none-linux_armv6l.whl", hash = "sha256:6ffbd6d87383c1edf5f6fa890f10200950240d7c1a16052a19a09d3a2307dd38", size = 10048966, upload-time = "2026-09-16T15:53:57.605Z" }, + { url = "https://files.pythonhosted.org/packages/54/98/07f90ecbc74dd5fb5764f11f2bc774d6a7cffef92d2ff5f5b4e9e23c754e/ruff-0.16.8-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:42ed6b878ed61e3acca92f2730a17acff39286944ea82398544696366a6f925e", size = 10165498, upload-time = "2026-09-16T15:54:01.14Z" }, + { url = "https://files.pythonhosted.org/packages/fe/1f/e6a712e3b47cad4a40600134105ed193cb773f618a42eb7ba323cb812cc0/ruff-0.16.8-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ea781c7f2afba8c6a505ea0fb3f994020249e0c450635f5381286fea6b46170", size = 9830004, upload-time = "2026-09-16T15:54:03.998Z" }, + { url = "https://files.pythonhosted.org/packages/23/f2/311a08776d75d81c7676e20b6b020ae63cbe881fcdc7a8dd64e6e18bdd93/ruff-0.16.8-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8efeae3bbe414a5efefda11a792dfb51ef90ac48d50c4830de2f644caf3e8659", size = 9986558, upload-time = "2026-09-16T15:54:06.804Z" }, + { url = "https://files.pythonhosted.org/packages/f3/ed/37b6cb3d3ba8c73e68ae3eb1d502383beb5aa05a582bb7bb3a922f929f54/ruff-0.16.8-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a79b795469fef7fc6e908b218eed2eb17332afd85031db6480dc864560e69b2", size = 9877332, upload-time = "2026-09-16T15:54:09.552Z" }, + { url = "https://files.pythonhosted.org/packages/22/cc/40873a8f36ad084cc540d55fcca7077264d5b13b24659e9180c176fb2b08/ruff-0.16.8-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3fdc5563cdc50555e6fba39322850860e9267c1b3d12c26a74729d8604c3c812", size = 10507125, upload-time = "2026-09-16T15:54:12.152Z" }, + { url = "https://files.pythonhosted.org/packages/c3/e4/fc91a642b78ccbab6b9477720f3644ae7a10a9bcce69a934679cd64f62bc/ruff-0.16.8-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:34508983c70665578dab88f5223d8e6228307e1135398ca8bfc8b7e9501e282b", size = 11336694, upload-time = "2026-09-16T15:54:15.489Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/bbd2a9a600a4e73dc3e7548a249c8d1671273464b55822c6fae50f602dff/ruff-0.16.8-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:644bb578569e0ffc575741232bd385dacdd6fbe123f1a729e7a225f54aa3957f", size = 10774448, upload-time = "2026-09-16T15:54:18.16Z" }, + { url = "https://files.pythonhosted.org/packages/1a/41/d83af9879a7b6e8bf5fe16b1da0b134049d2f5d3afac12defb0897cb84bd/ruff-0.16.8-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15e7d226246961db9235098333caa13063906d3851136b84c2900b82f5daa1df", size = 10323796, upload-time = "2026-09-16T15:54:20.743Z" }, + { url = "https://files.pythonhosted.org/packages/f5/2c/cefd07bfe914b84943ea769ade8d607bd22750b965d3228eefd7cebd15d0/ruff-0.16.8-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:a2bf6bc3e9ebdd4449abc6f06cf64b98051a2c61cf94d2fe9596518c881f1a1e", size = 10514115, upload-time = "2026-09-16T15:54:23.497Z" }, + { url = "https://files.pythonhosted.org/packages/f3/9d/76a2e26c79a23be6e6e3664c57bec9e9fc8de155cfb9e4b67ea91b64f9d7/ruff-0.16.8-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:6ca111ba0849539165e9e59d2b442542f3c1e8060ebbdea82494f1ffbccb1e1f", size = 10072582, upload-time = "2026-09-16T15:54:26.185Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d4/f42edddb39668af1a559ceafa3823aedd65633a48dc9768e775485faa2c1/ruff-0.16.8-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:359a1e5b495448ee1e91018064382ebc86f90e8aac2fed222c7d0e4e8df85fd2", size = 9879644, upload-time = "2026-09-16T15:54:29.278Z" }, + { url = "https://files.pythonhosted.org/packages/f8/d4/913e3195d95e0378786c6656945c865f534a3560e29139da4882aff630d1/ruff-0.16.8-py3-none-musllinux_1_2_i686.whl", hash = "sha256:59e8f5681349474110b24d62e93cfda6593f5fa3473446ca3705200cac1a08b9", size = 10231569, upload-time = "2026-09-16T15:54:32.036Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c4/8aa6ea0bdcedbd1bf87397e2fc4ed8406448ea5842f8660bc6e5f163039d/ruff-0.16.8-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:efa3e7a16d1baaa79957888dfdf8be9ef2e44db81cb032af06d76632ab59e773", size = 10663666, upload-time = "2026-09-16T15:54:34.838Z" }, + { url = "https://files.pythonhosted.org/packages/3d/02/7f10ef4700bc223c30a3fdd10631a29830c45524b810a3c7ed947af64591/ruff-0.16.8-py3-none-win32.whl", hash = "sha256:55793ba85c69921e89be061426d91a78652d6e50317c962240922747a4eb713f", size = 10093472, upload-time = "2026-09-16T15:54:37.47Z" }, + { url = "https://files.pythonhosted.org/packages/1e/5d/a509c07d714b6da88f2c518b4637cf6f1d46b074be8f0f1e5fb9ff5126fe/ruff-0.16.8-py3-none-win_amd64.whl", hash = "sha256:a6b85621fd3c81e31fc5f5add09c9c078b430db3595ca632efafdec9e64ebfaa", size = 10586899, upload-time = "2026-09-16T15:54:40.488Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a0/50787329e4f20bf9dc9f6230015d46ec69c51a97ace5bc202dae4755365d/ruff-0.16.8-py3-none-win_arm64.whl", hash = "sha256:d075e820af612102ce217f07cc93e69f9490b10ec13ea85fa87bd03d996cef8a", size = 10386316, upload-time = "2026-09-16T15:54:43.332Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "text-unidecode" +version = "1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ab/e2/e9a00f0ccb71718418230718b3d900e71a5d16e701a3dae079a21e9cd8f8/text-unidecode-1.3.tar.gz", hash = "sha256:bad6603bb14d279193107714b288be206cac565dfa49aa5b105294dd5c4aab93", size = 76885, upload-time = "2019-08-30T21:36:45.405Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a6/a5/c0b6468d3824fe3fde30dbb5e1f687b291608f9473681bbf7dabbf5a87d7/text_unidecode-1.3-py2.py3-none-any.whl", hash = "sha256:1311f10e8b895935241623731c2ba64f4c455287888b18189350b67134a822e8", size = 78154, upload-time = "2019-08-30T21:37:03.543Z" }, +] + +[[package]] +name = "ty" +version = "0.0.82" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/df/b9f35d0b8860f1bbfcb852fbef363301b5ca4b5590cadc6f2a810646d579/ty-0.0.82.tar.gz", hash = "sha256:586e3bf784cece42113929bb64b4761bed5c2127ae6cea294bb82da670066356", size = 7325958, upload-time = "2026-09-17T19:42:12.243Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/0e/259760638b7b1a875743f1f3975253392932ff74397c8e174df7bfb143c3/ty-0.0.82-py3-none-linux_armv6l.whl", hash = "sha256:be58e089e317e1ada7a655216828e76d369386dc958f7a3b3d455ab6dc7f02b6", size = 13833734, upload-time = "2026-09-17T19:41:35.134Z" }, + { url = "https://files.pythonhosted.org/packages/70/f6/c8a1f70989cf44cf2cada5527e268b4216015a7f28f1d8817e4ef1e84a52/ty-0.0.82-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:c080ba9a816cfbb3e34c0d3a0071829c602d14bb992bc799d885d4b30008b4ab", size = 13449689, upload-time = "2026-09-17T19:41:37.65Z" }, + { url = "https://files.pythonhosted.org/packages/d5/eb/31fc4bdecb2ff0053443d4ec1e6719a3f3171636ad6da7a8a642c879a4f4/ty-0.0.82-py3-none-macosx_11_0_arm64.whl", hash = "sha256:4f08bd5b751c3b2c46eabe8aee890e7fa54e3bcd97ffa4b8338b0a2508d928c2", size = 13410140, upload-time = "2026-09-17T19:41:40.024Z" }, + { url = "https://files.pythonhosted.org/packages/e7/14/e2af8c64004cd891691915b1522f105a5d601dd8d76a635fec112911f251/ty-0.0.82-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f5ef0401743c2eeac8039ef9ff1bc5dd612bd17ed0259b9b0794e19696548a6", size = 13435552, upload-time = "2026-09-17T19:41:42.084Z" }, + { url = "https://files.pythonhosted.org/packages/52/92/b9519a7854189aa8da4309ecb9c6ff5ab8ac91a433e201322b15c98f9388/ty-0.0.82-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c899643f2a4c1782c06a4bf4959909d1aa2d9d2cac7c1ac3de3161dfcb6909f8", size = 13601427, upload-time = "2026-09-17T19:41:44.242Z" }, + { url = "https://files.pythonhosted.org/packages/ce/be/0c7a39e277a25bca21bbd2dcf640eb4d80cf98f318ef611092cda1222399/ty-0.0.82-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b7aa6e4e157c6e0b770c327a5d966371b2a7bc7ad4f22d662ac068623cba00eb", size = 14457370, upload-time = "2026-09-17T19:41:46.405Z" }, + { url = "https://files.pythonhosted.org/packages/6f/33/86ff8f1e15c71096838eb0fdfe0f5b578dc717575de6cba591d96baf3b06/ty-0.0.82-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:28c141ab481748f1b889eb572e803172ea452af621e514c30a2f30884753b020", size = 14888674, upload-time = "2026-09-17T19:41:48.6Z" }, + { url = "https://files.pythonhosted.org/packages/0a/d2/a1c6315907afd080b4e98d2972441b4803a70c9663a8c7a7f6fd554c7361/ty-0.0.82-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:16fff2729fbaa3998ba1cab536dc7d176aef28927b09200588e50982394c56df", size = 14670369, upload-time = "2026-09-17T19:41:50.963Z" }, + { url = "https://files.pythonhosted.org/packages/ae/cd/956ceae4dbe0b116ebc9ecb75dcbe9a0294c50146f76c4c59004e6eb2d77/ty-0.0.82-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c2024a33209b37525ffa85a29036985e9ef53a013c0ff321231bd8b23987cf71", size = 14107030, upload-time = "2026-09-17T19:41:53.343Z" }, + { url = "https://files.pythonhosted.org/packages/b7/f8/6025627cec4d6370fb34a2c5cdcf36d89dd4e4ac75b023bda68231e17dfc/ty-0.0.82-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:14a0ae8591e08aca5911b545d100e51c9b796350a85b2b36d82219820552d662", size = 14485892, upload-time = "2026-09-17T19:41:55.745Z" }, + { url = "https://files.pythonhosted.org/packages/3a/b6/016f9b36096a9ccd0492ee000380bd75fb51dc4ec7bfef4d6d93f6b3ec2e/ty-0.0.82-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:2964202b09108c72232760119c2680cefc33191c428b09e6f620b6c0ab9c6b0f", size = 13383907, upload-time = "2026-09-17T19:41:57.937Z" }, + { url = "https://files.pythonhosted.org/packages/b4/19/1ccc2429399d6ef3d98180340c7abc6793bd90c5039ad41a9003cb8de6df/ty-0.0.82-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:f4ed8fc714e35dc11ef4209832e73ad461cf29c9161099eb6c2c541c6b9a3e0e", size = 13617005, upload-time = "2026-09-17T19:42:00.018Z" }, + { url = "https://files.pythonhosted.org/packages/d7/9d/a4a487db72e78413bba2ee9cd49f79b8f461be93e7f6c4dd790febae1cd7/ty-0.0.82-py3-none-musllinux_1_2_i686.whl", hash = "sha256:32a3fe7b1a50f20679fe76c85c0087280419365d900300898a7b95cbcfe510fc", size = 13906545, upload-time = "2026-09-17T19:42:01.942Z" }, + { url = "https://files.pythonhosted.org/packages/0c/4e/a58d530c0f5abe7b846e2d05af9e3f1fb44a1b620ae0abe3892cd3f9596c/ty-0.0.82-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f751044ae63ea9e73ce2eae4c23a839efa4a04d6487d6ea411a590fbe43360b6", size = 14248518, upload-time = "2026-09-17T19:42:04.164Z" }, + { url = "https://files.pythonhosted.org/packages/a6/db/5505229835171d19adcaaeec3a15e0b533b578d24de1329db5da9306c4c6/ty-0.0.82-py3-none-win32.whl", hash = "sha256:0eb66c5ce58434a48d2cae2780d25285c7ca19e07a0d38b1fe39d1a0f75d6fa3", size = 13059890, upload-time = "2026-09-17T19:42:06.161Z" }, + { url = "https://files.pythonhosted.org/packages/13/22/faa427b65baf39915f52a6fa079ece4253e831f3364c567bf91bc1eef65a/ty-0.0.82-py3-none-win_amd64.whl", hash = "sha256:1e4a6c1ca2dc1a6929517d73a47cd626989bb8bd67811425fbe022d06eb2bf73", size = 14003730, upload-time = "2026-09-17T19:42:08.268Z" }, + { url = "https://files.pythonhosted.org/packages/8b/fc/3b95100993d28acb2f3bcf3a49846985f5b2aafab6562627d018f6d23788/ty-0.0.82-py3-none-win_arm64.whl", hash = "sha256:a6f0e8a1f961518746edbccc5986945c01a56a917ebe37117aa028a038d54ae3", size = 13567713, upload-time = "2026-09-17T19:42:10.248Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/31/3d74fa778a63b98b7374323befcc0be5ab3bd94afd4096a0124e7379152c/tzdata-2026.4.tar.gz", hash = "sha256:f1b8bd365d8d210c55353f4d7f8d6d8561c0ba50d704b700d195a9424bba0d79", size = 199350, upload-time = "2026-09-12T12:56:03.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/bc/8737e8d54cf51106118039b83f485a4783112fab49ea9d044b234978a46e/tzdata-2026.4-py2.py3-none-any.whl", hash = "sha256:c2169a8b0a7a5e9674da5a135ccdfb2b3e671b333ed9fed17b41f73c34476e81", size = 347494, upload-time = "2026-09-12T12:56:01.67Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "watchdog" +version = "6.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/db/7d/7f3d619e951c88ed75c6037b246ddcf2d322812ee8ea189be89511721d54/watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282", size = 131220, upload-time = "2024-11-01T14:07:13.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/c7/ca4bf3e518cb57a686b2feb4f55a1892fd9a3dd13f470fca14e00f80ea36/watchdog-6.0.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:7607498efa04a3542ae3e05e64da8202e58159aa1fa4acddf7678d34a35d4f13", size = 79079, upload-time = "2024-11-01T14:06:59.472Z" }, + { url = "https://files.pythonhosted.org/packages/5c/51/d46dc9332f9a647593c947b4b88e2381c8dfc0942d15b8edc0310fa4abb1/watchdog-6.0.0-py3-none-manylinux2014_armv7l.whl", hash = "sha256:9041567ee8953024c83343288ccc458fd0a2d811d6a0fd68c4c22609e3490379", size = 79078, upload-time = "2024-11-01T14:07:01.431Z" }, + { url = "https://files.pythonhosted.org/packages/d4/57/04edbf5e169cd318d5f07b4766fee38e825d64b6913ca157ca32d1a42267/watchdog-6.0.0-py3-none-manylinux2014_i686.whl", hash = "sha256:82dc3e3143c7e38ec49d61af98d6558288c415eac98486a5c581726e0737c00e", size = 79076, upload-time = "2024-11-01T14:07:02.568Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/da8422b300e13cb187d2203f20b9253e91058aaf7db65b74142013478e66/watchdog-6.0.0-py3-none-manylinux2014_ppc64.whl", hash = "sha256:212ac9b8bf1161dc91bd09c048048a95ca3a4c4f5e5d4a7d1b1a7d5752a7f96f", size = 79077, upload-time = "2024-11-01T14:07:03.893Z" }, + { url = "https://files.pythonhosted.org/packages/2c/3b/b8964e04ae1a025c44ba8e4291f86e97fac443bca31de8bd98d3263d2fcf/watchdog-6.0.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:e3df4cbb9a450c6d49318f6d14f4bbc80d763fa587ba46ec86f99f9e6876bb26", size = 79078, upload-time = "2024-11-01T14:07:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/62/ae/a696eb424bedff7407801c257d4b1afda455fe40821a2be430e173660e81/watchdog-6.0.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:2cce7cfc2008eb51feb6aab51251fd79b85d9894e98ba847408f662b3395ca3c", size = 79077, upload-time = "2024-11-01T14:07:06.376Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e8/dbf020b4d98251a9860752a094d09a65e1b436ad181faf929983f697048f/watchdog-6.0.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:20ffe5b202af80ab4266dcd3e91aae72bf2da48c0d33bdb15c66658e685e94e2", size = 79078, upload-time = "2024-11-01T14:07:07.547Z" }, + { url = "https://files.pythonhosted.org/packages/07/f6/d0e5b343768e8bcb4cda79f0f2f55051bf26177ecd5651f84c07567461cf/watchdog-6.0.0-py3-none-win32.whl", hash = "sha256:07df1fdd701c5d4c8e55ef6cf55b8f0120fe1aef7ef39a1c6fc6bc2e606d517a", size = 79065, upload-time = "2024-11-01T14:07:09.525Z" }, + { url = "https://files.pythonhosted.org/packages/db/d9/c495884c6e548fce18a8f40568ff120bc3a4b7b99813081c8ac0c936fa64/watchdog-6.0.0-py3-none-win_amd64.whl", hash = "sha256:cbafb470cf848d93b5d013e2ecb245d4aa1c8fd0504e863ccefa32445359d680", size = 79070, upload-time = "2024-11-01T14:07:10.686Z" }, + { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, +]