コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
ae3adfa859
|
||
|
|
38c5ee1f5f
|
||
|
|
ec5e2a4c26
|
||
|
|
74b80d7fff
|
||
|
|
3203298bed
|
||
|
|
b7a293ce31
|
||
|
|
4adab4fe40
|
||
|
|
51ede8461d
|
||
|
|
50c48fd355
|
||
|
|
5b28bc2c1a
|
||
|
|
546dd284e8
|
||
|
|
747660f3c7
|
||
|
|
f63b5987fa
|
||
|
|
335daba4c8
|
||
|
|
856c7267c8
|
||
|
|
bdc0a48624
|
||
|
|
26226fd0cf
|
||
|
|
f1e39b536f
|
||
|
|
2fad3f9f16
|
||
|
|
61ffd6e101
|
||
|
|
ce92db73ba
|
||
|
|
6dcd8784dc
|
||
|
|
474d3609e4
|
||
|
|
fca9781341
|
||
|
|
cc54fa0401
|
||
|
|
b80c51e483
|
||
|
|
17f972985d
|
||
|
|
4b8a957fc0
|
||
|
|
51d4e6203b
|
||
|
|
43f3e4f553
|
||
|
|
c933abe299
|
||
|
|
a83985a1d7
|
||
|
|
6993df9b1b
|
||
|
|
669848bbe2
|
||
|
|
73fb8db3d9
|
||
|
|
c765a51567
|
||
|
|
2eda014f27
|
||
|
|
29dd873044
|
||
|
|
cb98e0f15b
|
||
|
|
1a72c0beaf
|
||
|
|
d1d8983800
|
||
|
|
4873ea55cb
|
||
|
|
63ad5cd5b4
|
||
|
|
1ceb8bf623
|
||
|
|
7f7c348a3f
|
||
|
|
11112773be
|
||
|
|
cba29f45e5
|
||
|
|
364696df88
|
||
|
|
ddc043d16b
|
||
|
|
22eb37b847
|
||
|
|
d1dd0417e8
|
||
|
|
6f620ae985
|
||
|
|
659c52cb3c
|
||
|
|
07baf1350a
|
||
|
|
de4756b8f0
|
||
|
|
0c0bd6d974
|
||
|
|
ff07a2845e
|
||
|
|
d81ea8bfea
|
||
|
|
0f68e04cd8
|
||
|
|
a624667006
|
||
|
|
69c82517d7
|
||
|
|
55528849df
|
||
|
|
18b99b9ebc
|
||
|
|
c86cfc1c27
|
||
|
|
5b5d56a8e6
|
||
|
|
026a9011e6
|
||
|
|
28257ab87a
|
||
|
|
a7a72976d7
|
||
|
|
ce46cd4363
|
||
|
|
c490912d93
|
||
|
|
35812bd031
|
||
|
|
bb42ce6ba1
|
||
|
|
7abed4f2d3
|
||
|
|
4bea601287
|
||
|
|
8f1a3372b9
|
||
|
|
69dd4949f9
|
||
|
|
0950048027
|
||
|
|
b7bf0fd52d
|
||
|
|
3e12fff8ce
|
||
|
|
eee59235dd
|
||
|
|
0cfc1e79b1
|
||
|
|
f7c5e48f60
|
||
|
|
1c57f36966
|
||
|
|
e69820e5b8
|
||
|
|
f1281fc862
|
||
|
|
fd78861351
|
||
|
|
ba1c6a8aab
|
||
|
|
2bcfbf0526
|
||
|
|
789fc7fef1
|
||
|
|
04b4bc2f5a
|
||
|
|
64ff17708c
|
||
|
|
91114b3c84
|
||
|
|
a4a3cc0f07
|
||
|
|
05d05e7528
|
||
|
|
f5fdb0390e
|
||
|
|
b94addb9c7
|
||
|
|
c6a9d4718a
|
||
|
|
e5a1389c95
|
||
|
|
c53ba71bb5 | ||
|
|
aeeb221a0a | ||
|
|
4cfe9a0ff3 | ||
|
|
78fe1fe0e1 |
検索条件に一致するファイルはありません
@@ -0,0 +1,139 @@
|
||||
========================================
|
||||
ProxyForge for YMM4 v2.0.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、編集の間だけ使う解像度の低い
|
||||
動画ファイルを作り、プレビューでは元の動画の代わりにそれを読み込む
|
||||
動画読み込みプラグインです。
|
||||
大きな動画をタイムラインに置くと、YMM4 に付属する ffmpeg で 10 秒分ずつの
|
||||
チャンクに分けてバックグラウンドで生成し、できたチャンクから順に切り替えます。
|
||||
動画出力のときは元の動画を読み込むため、出力した動画の画質は変わりません。
|
||||
生成したファイルは YMM4 のユーザーフォルダーのキャッシュに置き、上限を超えた
|
||||
分は最後に使った日時が古いものから消します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 動作要件
|
||||
--------------------------------------------------------------------------------
|
||||
- OS : Windows 10 バージョン 2004 (ビルド 19041) 以降 / Windows 11 (64bit)
|
||||
- YMM4 : YukkuriMovieMaker4(最新版を推奨)
|
||||
- ランタイム : .NET 10.0
|
||||
ffmpeg は YMM4 に付属するものを使い、別途インストールする必要はありません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 使い方
|
||||
--------------------------------------------------------------------------------
|
||||
- YMM4 の設定画面の「動画読み込み」にある「ProxyForge」を開き、読み込み順が
|
||||
「先頭にありません」と表示されているときは「先頭へ移動」を押してください。
|
||||
先頭にないとプロキシは使われません。
|
||||
|
||||
- 100MB 以上の動画をタイムラインに置くと生成が始まり、進捗のウィンドウが
|
||||
画面の右下に出ます。対象にする最小サイズは設定画面で変えられます。
|
||||
|
||||
- プロキシは、元の動画を YMM4 自身の読み込み処理で 1 フレームずつ描画し、
|
||||
設定の解像度へ縮小してから、YMM4 に付属する ffmpeg で H.264 の mp4 に
|
||||
符号化したものです。既定の解像度は元の動画の表示の大きさの 50% です。
|
||||
|
||||
- 動画全体を 10 秒分ずつのチャンクに分けて作り、プレビューで最後に要求された
|
||||
位置のチャンクから先に生成します。生成が終わったチャンクから順に切り替え、
|
||||
まだ無い区間は元の動画をそのまま読みます。既にあるチャンクは飛ばすため、
|
||||
途中で止まった生成は次回に続きから進みます。
|
||||
|
||||
- ハードウェアエンコーダーを使う設定のときは、h264_nvenc、h264_qsv、
|
||||
h264_amf の中から、ffmpeg で 1 フレームの試し書きに成功した最初のものを
|
||||
使います。使えるものが無いときは、ffmpeg のソフトウェアの H.264
|
||||
エンコーダーを使います。
|
||||
|
||||
- 進捗のウィンドウでは、動画ごとに状態と、チャンクごとの生成の状況を帯で
|
||||
表示します。生成が終わったチャンクはその位置が緑になります。「キャンセル」は
|
||||
待ち行列にある生成をすべて止め、「閉じる」は待ち行列が空になるまで
|
||||
ウィンドウを隠します。
|
||||
|
||||
- 生成したチャンクと索引は user/resources/cache/ProxyForge に置きます。
|
||||
合計の大きさが上限を超えると、最後に使った日時が古い動画のプロキシから
|
||||
消します。既定の上限は 10GB です。設定画面のキャッシュの一覧から、選んだ
|
||||
プロキシの削除とすべての削除ができます。
|
||||
|
||||
- 設定は user/setting/<YMM4 のバージョン>/ProxyForge.ProxyForgeSettings.json
|
||||
に保存します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 注意事項
|
||||
--------------------------------------------------------------------------------
|
||||
- 動画出力: 出力の最中は本プラグインは何も返さず、YMM4 の他の読み込み
|
||||
プラグインが元の動画を開きます。出力の最中かどうかは、YMM4 の「動画出力」と
|
||||
「出力」のウィンドウの表示と終了で判断します。コマンドラインの --encode で
|
||||
起動した YMM4 では常に出力中として扱います。
|
||||
|
||||
- 透明を含む動画はプロキシにしません。フレームの縁 2 ピクセルを除いた範囲に
|
||||
透明なピクセルがある動画は生成を止め、除外として覚えます。除外はキャッシュの
|
||||
「すべて削除」で消えます。
|
||||
|
||||
- 生成が終わっていない区間は元の動画を読むため、生成の最中は再生の位置に
|
||||
よって画質が変わります。
|
||||
|
||||
- プロキシは音声を含みません。音声は YMM4 が元の動画から読みます。
|
||||
|
||||
- 生成中は、元の動画の読み込みと縮小と符号化のために CPU と GPU を使います。
|
||||
|
||||
- 元の動画のパスと大きさと更新日時のどれかが変わると、プロキシを生成し直します。
|
||||
|
||||
- 1.x のキャッシュと設定は引き継ぎません。プラグインのフォルダーに残る 1.x の
|
||||
cache フォルダーと System.IO.Hashing.dll は使わないので、消して構いません。
|
||||
|
||||
- 更新の確認: YMM4 を起動してから初めて動画を開くときに一度だけ GitHub の
|
||||
リリースを確認し、新しいものがあればメッセージで知らせます。
|
||||
|
||||
- 本プラグインを使用する前に、YMM4 プロジェクトファイルのバックアップを
|
||||
作成することを推奨します。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 不具合の報告
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
||||
送信します。同意は求めず、常に送信します。
|
||||
|
||||
送信する情報は次のとおりです。
|
||||
例外 : 型の完全名、メッセージ、スタックトレース
|
||||
発生位置 : モジュール名、関数名、ファイル名、行番号
|
||||
プラグイン : アセンブリ名、バージョン
|
||||
実行環境 : OS の名前とバージョン、.NET のバージョン、
|
||||
CPU のアーキテクチャ、論理プロセッサ数
|
||||
識別子 : YMM4 の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||
|
||||
動画ファイルの中身とプロジェクトの内容は送信しません。継続して個人を追跡
|
||||
する識別子も持ちません。セッション識別子は YMM4 を起動し直すと別の値に
|
||||
なります。メッセージとファイル名に含まれる利用者名などの文字列は、送信の
|
||||
前に置き換えます。送信元の IP アドレスは受信側へ渡す手前で取り除いています。
|
||||
|
||||
送信するのは想定していない例外だけです。本プラグインが例外を握り潰す箇所と、
|
||||
YMM4 へ処理を返す境界の両方で報告します。画面の操作やバックグラウンドの
|
||||
処理で未処理になった例外も報告しますが、本プラグインのコードが関わる例外に
|
||||
限ります。YMM4 本体やほかのプラグインで起きた例外は送信しません。
|
||||
|
||||
次の失敗は送信しません。
|
||||
生成の失敗として利用者へ知らせるもの : ffmpeg が見つからない、動画を
|
||||
開けない、透明を含む動画である、
|
||||
元の動画が変更された
|
||||
更新の確認の通信の失敗 : GitHub へ接続できない
|
||||
キャッシュの読み書きで想定している失敗 : 索引を読めない、ファイルを
|
||||
消せない、チャンクを開けない
|
||||
|
||||
送信できなかった報告は YMM4 のユーザーフォルダーへ退避し、次回の起動時に
|
||||
送り直します。送信も再送も非同期に行うため、起動と生成が遅くなることは
|
||||
ありません。
|
||||
--------------------------------------------------------------------------------
|
||||
■ 免責事項
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインは MIT ライセンスのもとで公開されています。
|
||||
本ソフトウェアは「現状のまま」提供されており、明示・黙示を問わず、
|
||||
商品性、特定目的への適合性、および権利非侵害に関する保証を含む、
|
||||
いかなる種類の保証も行いません。
|
||||
作者は、本プラグインの使用または使用不能に起因するいかなる損害についても、
|
||||
一切の責任を負いません。
|
||||
ご利用は自己責任でお願いします。
|
||||
--------------------------------------------------------------------------------
|
||||
■ サードパーティライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
本プラグインはサードパーティソフトウェアを同梱していません。
|
||||
動画の符号化には YMM4 に付属する ffmpeg を使います。
|
||||
--------------------------------------------------------------------------------
|
||||
■ ライセンス
|
||||
--------------------------------------------------------------------------------
|
||||
MIT License
|
||||
https://github.com/routersys/YMM4-ProxyForge
|
||||
========================================
|
||||
@@ -0,0 +1,345 @@
|
||||
name: リリース
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: ソースコードのチェックアウト
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
fetch-depth: 0
|
||||
|
||||
- name: .NET SDK のセットアップ
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: YMM4 最新リリースの取得と解凍
|
||||
id: ymm4
|
||||
shell: pwsh
|
||||
run: |
|
||||
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases/latest" `
|
||||
-Headers @{ "User-Agent" = "ProxyForge-CI" }
|
||||
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
|
||||
if (-not $asset) {
|
||||
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
|
||||
}
|
||||
Write-Host "ダウンロード対象: $($asset.name)"
|
||||
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile "ymm4.zip"
|
||||
Expand-Archive -Path "ymm4.zip" -DestinationPath "ymm4_extracted" -Force
|
||||
$ymm4Dir = (Get-ChildItem -Path "ymm4_extracted" -Recurse -Filter "YukkuriMovieMaker.dll" |
|
||||
Select-Object -First 1).DirectoryName
|
||||
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
|
||||
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: タグ名からバージョンを取得
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = "${{ github.ref_name }}"
|
||||
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
|
||||
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: バージョン記載の照合
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = "${{ steps.version.outputs.TAG }}"
|
||||
$version = "${{ steps.version.outputs.VERSION }}"
|
||||
$problems = @()
|
||||
|
||||
$csprojPath = "ProxyForge/ProxyForge.csproj"
|
||||
$csproj = Get-Content $csprojPath -Raw
|
||||
if (-not $csproj.Contains("<Version>$version</Version>")) {
|
||||
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
|
||||
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
|
||||
}
|
||||
|
||||
$readmePath = ".github/Plugin_Readme.txt"
|
||||
$readme = Get-Content $readmePath -Raw
|
||||
if (-not $readme.Contains(" ProxyForge for YMM4 $tag")) {
|
||||
$current = if ($readme -match '(?m)^ ProxyForge for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
|
||||
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
|
||||
}
|
||||
|
||||
if ($problems.Count -eq 0) {
|
||||
Write-Host "バージョン記載は $tag と一致しています"
|
||||
exit 0
|
||||
}
|
||||
|
||||
foreach ($problem in $problems) {
|
||||
Write-Host "::error::$problem"
|
||||
}
|
||||
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
|
||||
exit 1
|
||||
|
||||
- name: プロジェクトのビルド
|
||||
shell: pwsh
|
||||
run: |
|
||||
$proj = "ProxyForge/ProxyForge.csproj"
|
||||
dotnet build "$proj" `
|
||||
-c Release `
|
||||
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||
-p:SkipPluginDeploy=true
|
||||
|
||||
- name: パッケージの作成
|
||||
id: package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ steps.version.outputs.TAG }}"
|
||||
$outDir = "ProxyForge/bin/Release/net10.0-windows10.0.19041.0"
|
||||
$stageRoot = "stage/ProxyForge"
|
||||
$pkgName = "ProxyForge_$version.ymme"
|
||||
|
||||
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||
|
||||
$dll = "$outDir/ProxyForge.dll"
|
||||
if (-not (Test-Path $dll)) {
|
||||
Write-Error "ビルド結果に ProxyForge.dll が見つかりませんでした: $dll"
|
||||
exit 1
|
||||
}
|
||||
Copy-Item $dll "$stageRoot/"
|
||||
|
||||
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
|
||||
$src = "$outDir/$lang"
|
||||
if (Test-Path $src) {
|
||||
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
|
||||
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
|
||||
}
|
||||
}
|
||||
|
||||
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||
|
||||
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
|
||||
if (-not $readme.Contains(" ProxyForge for YMM4 $version")) {
|
||||
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
||||
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: 変更履歴の作成
|
||||
id: changelog
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.version.outputs.TAG }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
SERVER_URL: ${{ github.server_url }}
|
||||
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
|
||||
run: |
|
||||
$tag = $env:TAG
|
||||
$repository = $env:REPOSITORY
|
||||
$server = $env:SERVER_URL
|
||||
$code = [char]0x60
|
||||
$fence = [string]::new($code, 3)
|
||||
$unit = [char]0x1f
|
||||
|
||||
$previous = ""
|
||||
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
|
||||
if ($candidates.Count -gt 0) {
|
||||
$previous = $candidates[0]
|
||||
}
|
||||
Write-Host "直前のタグ: $previous"
|
||||
|
||||
$range = if ($previous) { "$previous..$tag" } else { $tag }
|
||||
$log = @(git log "--format=%H%x1f%s%x1f%an%x1f%ad" --date=short $range)
|
||||
|
||||
$commits = @()
|
||||
foreach ($line in $log) {
|
||||
if (-not $line) { continue }
|
||||
$fields = $line -split $unit
|
||||
if ($fields.Count -lt 4) { continue }
|
||||
$commits += [pscustomobject]@{
|
||||
Sha = $fields[0]
|
||||
Subject = $fields[1]
|
||||
Name = $fields[2]
|
||||
Date = $fields[3]
|
||||
Login = ""
|
||||
Avatar = ""
|
||||
}
|
||||
}
|
||||
Write-Host "コミット数: $($commits.Count)"
|
||||
|
||||
$pending = [System.Collections.Generic.HashSet[string]]::new()
|
||||
foreach ($commit in $commits) {
|
||||
[void]$pending.Add($commit.Sha)
|
||||
}
|
||||
|
||||
$accounts = @{}
|
||||
$page = 1
|
||||
while ($pending.Count -gt 0 -and $page -le 20) {
|
||||
$rows = @()
|
||||
try {
|
||||
$rows = @(gh api "repos/$repository/commits?sha=$tag&per_page=100&page=$page" --jq '.[] | [.sha, (.author.login // ""), (.author.avatar_url // "")] | @tsv')
|
||||
}
|
||||
catch {
|
||||
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
|
||||
break
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0 -or $rows.Count -eq 0) { break }
|
||||
|
||||
foreach ($row in $rows) {
|
||||
$fields = $row -split "`t"
|
||||
if ($fields.Count -lt 3) { continue }
|
||||
if ($pending.Remove($fields[0])) {
|
||||
$accounts[$fields[0]] = @{ Login = $fields[1]; Avatar = $fields[2] }
|
||||
}
|
||||
}
|
||||
|
||||
if ($rows.Count -lt 100) { break }
|
||||
$page++
|
||||
}
|
||||
|
||||
foreach ($commit in $commits) {
|
||||
if ($accounts.ContainsKey($commit.Sha)) {
|
||||
$commit.Login = $accounts[$commit.Sha].Login
|
||||
$commit.Avatar = $accounts[$commit.Sha].Avatar
|
||||
}
|
||||
}
|
||||
|
||||
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
|
||||
$base = if ($previous) { $previous } else { $emptyTree }
|
||||
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
|
||||
$changedFiles = 0
|
||||
$insertions = 0
|
||||
$deletions = 0
|
||||
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
|
||||
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
|
||||
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
|
||||
$diffStat = @(git diff --stat $base $tag)
|
||||
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
|
||||
|
||||
$contributors = @($commits |
|
||||
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
|
||||
Sort-Object -Property Count -Descending)
|
||||
|
||||
function Get-Icon($avatar, $login, $size) {
|
||||
if (-not $avatar) { return "" }
|
||||
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
|
||||
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
|
||||
}
|
||||
|
||||
$package = Get-Item $env:PACKAGE
|
||||
$size = [math]::Round($package.Length / 1MB, 2)
|
||||
|
||||
$body = [System.Collections.Generic.List[string]]::new()
|
||||
$body.Add("## 概要")
|
||||
$body.Add("")
|
||||
$body.Add("| 項目 | 内容 |")
|
||||
$body.Add("|---|---|")
|
||||
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
|
||||
$body.Add("| 公開日 | $tagDate |")
|
||||
if ($previous) {
|
||||
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
|
||||
}
|
||||
$body.Add("| コミット数 | $($commits.Count) |")
|
||||
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
|
||||
$body.Add("| 変更されたファイル | $changedFiles |")
|
||||
$body.Add("| 追加された行 | $insertions |")
|
||||
$body.Add("| 削除された行 | $deletions |")
|
||||
|
||||
$body.Add("")
|
||||
$body.Add("## ダウンロード")
|
||||
$body.Add("")
|
||||
$body.Add("| ファイル | サイズ |")
|
||||
$body.Add("|---|---|")
|
||||
$body.Add("| $($package.Name) | $size MB |")
|
||||
|
||||
$body.Add("")
|
||||
$body.Add("## 貢献者")
|
||||
$body.Add("")
|
||||
$body.Add("| 貢献者 | コミット数 |")
|
||||
$body.Add("|---|---|")
|
||||
foreach ($contributor in $contributors) {
|
||||
$first = $contributor.Group[0]
|
||||
if ($first.Login) {
|
||||
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
|
||||
}
|
||||
else {
|
||||
$name = $first.Name
|
||||
}
|
||||
$body.Add("| $name | $($contributor.Count) |")
|
||||
}
|
||||
|
||||
$body.Add("")
|
||||
$body.Add("## 変更履歴")
|
||||
$body.Add("")
|
||||
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
|
||||
$body.Add("|---|---|---|---|")
|
||||
$maximumCommits = 300
|
||||
$listed = 0
|
||||
foreach ($commit in $commits) {
|
||||
if ($listed -ge $maximumCommits) { break }
|
||||
$short = $commit.Sha.Substring(0, 7)
|
||||
$subject = $commit.Subject -replace '\|', '\|'
|
||||
if ($commit.Login) {
|
||||
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
|
||||
}
|
||||
else {
|
||||
$author = $commit.Name
|
||||
}
|
||||
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
|
||||
$listed++
|
||||
}
|
||||
if ($commits.Count -gt $maximumCommits) {
|
||||
$body.Add("")
|
||||
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
|
||||
}
|
||||
|
||||
if ($diffStat.Count -gt 0) {
|
||||
$body.Add("")
|
||||
$body.Add("## 変更されたファイル")
|
||||
$body.Add("")
|
||||
$body.Add("<details>")
|
||||
$body.Add("<summary>差分の統計</summary>")
|
||||
$body.Add("")
|
||||
$body.Add($fence)
|
||||
$maximumStatLines = 200
|
||||
$shown = 0
|
||||
foreach ($line in $diffStat) {
|
||||
if ($shown -ge $maximumStatLines) { break }
|
||||
$body.Add($line)
|
||||
$shown++
|
||||
}
|
||||
if ($diffStat.Count -gt $maximumStatLines) {
|
||||
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
|
||||
}
|
||||
$body.Add($fence)
|
||||
$body.Add("")
|
||||
$body.Add("</details>")
|
||||
}
|
||||
|
||||
if ($previous) {
|
||||
$body.Add("")
|
||||
$body.Add("## 全ての変更")
|
||||
$body.Add("")
|
||||
$body.Add("$server/$repository/compare/$previous...$tag")
|
||||
}
|
||||
|
||||
$path = "release-body.md"
|
||||
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
|
||||
if (-not (Test-Path $path)) {
|
||||
throw "変更履歴を作成できませんでした。"
|
||||
}
|
||||
Write-Host "変更履歴の行数: $($body.Count)"
|
||||
$global:LASTEXITCODE = 0
|
||||
|
||||
- name: GitHub リリースの作成
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
name: ${{ steps.version.outputs.TAG }}
|
||||
body_path: release-body.md
|
||||
files: ${{ steps.package.outputs.PKG_NAME }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
+4
-1
@@ -360,4 +360,7 @@ MigrationBackup/
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
FodyWeavers.xsd
|
||||
|
||||
# YukkuriMovieMaker.Generator
|
||||
*.resx
|
||||
+7
-1
@@ -1,3 +1,9 @@
|
||||
[submodule "YukkuriMovieMaker.Generator"]
|
||||
path = YukkuriMovieMaker.Generator
|
||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator
|
||||
[submodule "YMM4-GitHubUpdateNotifier"]
|
||||
path = YMM4-GitHubUpdateNotifier
|
||||
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier
|
||||
[submodule "YMM4-Telemetry"]
|
||||
path = YMM4-Telemetry
|
||||
url = https://github.com/routersys/YMM4-Telemetry
|
||||
+1
-1
@@ -18,4 +18,4 @@ 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.
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,120 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Views;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Wpf")]
|
||||
public sealed class ChunkCoverageBarTests
|
||||
{
|
||||
static (double Start, double Length)[] SegmentsOf(ProxyChunkCoverage coverage) => [.. ChunkCoverageBar.Segments(coverage)];
|
||||
|
||||
[Fact]
|
||||
public void NothingIsDrawnWithoutChunks()
|
||||
{
|
||||
Assert.Empty(SegmentsOf(ProxyChunkCoverage.Empty));
|
||||
Assert.Empty(SegmentsOf(new ProxyChunkCoverage(4, [], null, 0d)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CoveredChunksAreDrawnAtTheirPositions()
|
||||
{
|
||||
var segments = SegmentsOf(new ProxyChunkCoverage(4, [3, 1], null, 0d));
|
||||
|
||||
Assert.Equal([(0.25d, 0.25d), (0.75d, 0.25d)], segments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AdjacentChunksAreMergedIntoOneSegment()
|
||||
{
|
||||
var segments = SegmentsOf(new ProxyChunkCoverage(5, [0, 1, 2, 4], null, 0d));
|
||||
|
||||
Assert.Equal([(0d, 0.6d), (0.8d, 0.2d)], segments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChunksOutsideTheLayoutAndDuplicatesAreIgnored()
|
||||
{
|
||||
var segments = SegmentsOf(new ProxyChunkCoverage(4, [7, -1, 2, 2], null, 0d));
|
||||
|
||||
Assert.Equal([(0.5d, 0.25d)], segments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheChunkBeingGeneratedIsDrawnPartially()
|
||||
{
|
||||
var segments = SegmentsOf(new ProxyChunkCoverage(4, [0], 2, 0.5d));
|
||||
|
||||
Assert.Equal([(0d, 0.25d), (0.5d, 0.125d)], segments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCurrentChunkIsNotDrawnTwiceOrWhenNothingIsDone()
|
||||
{
|
||||
Assert.Equal([(0.5d, 0.25d)], SegmentsOf(new ProxyChunkCoverage(4, [2], 2, 0.5d)));
|
||||
Assert.Empty(SegmentsOf(new ProxyChunkCoverage(4, [], 2, 0d)));
|
||||
Assert.Empty(SegmentsOf(new ProxyChunkCoverage(4, [], 9, 0.5d)));
|
||||
Assert.Equal([(0.5d, 0.25d)], SegmentsOf(new ProxyChunkCoverage(4, [], 2, 1.5d)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RendersGreenWhereChunksExist()
|
||||
{
|
||||
var pixels = RunSta(() =>
|
||||
{
|
||||
var bar = new ChunkCoverageBar
|
||||
{
|
||||
Coverage = new ProxyChunkCoverage(4, [1], 2, 0.5d),
|
||||
Fill = Brushes.Lime,
|
||||
};
|
||||
bar.Measure(new Size(100d, 10d));
|
||||
bar.Arrange(new Rect(0d, 0d, 100d, 10d));
|
||||
bar.UpdateLayout();
|
||||
var bitmap = new RenderTargetBitmap(100, 10, 96d, 96d, PixelFormats.Pbgra32);
|
||||
bitmap.Render(bar);
|
||||
var buffer = new byte[100 * 10 * 4];
|
||||
bitmap.CopyPixels(buffer, 100 * 4, 0);
|
||||
return buffer;
|
||||
});
|
||||
|
||||
Assert.Equal(0, AlphaAt(pixels, 10));
|
||||
Assert.Equal(255, AlphaAt(pixels, 30));
|
||||
Assert.Equal(255, GreenAt(pixels, 30));
|
||||
Assert.Equal(0, RedAt(pixels, 30));
|
||||
Assert.Equal(255, AlphaAt(pixels, 55));
|
||||
Assert.Equal(0, AlphaAt(pixels, 70));
|
||||
Assert.Equal(0, AlphaAt(pixels, 90));
|
||||
}
|
||||
|
||||
static byte AlphaAt(byte[] pixels, int x) => pixels[5 * 100 * 4 + x * 4 + 3];
|
||||
|
||||
static byte GreenAt(byte[] pixels, int x) => pixels[5 * 100 * 4 + x * 4 + 1];
|
||||
|
||||
static byte RedAt(byte[] pixels, int x) => pixels[5 * 100 * 4 + x * 4 + 2];
|
||||
|
||||
static T RunSta<T>(Func<T> action)
|
||||
{
|
||||
var result = default(T)!;
|
||||
Exception? error = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
result = action();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
error = exception;
|
||||
}
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
|
||||
if (error is not null)
|
||||
throw new InvalidOperationException(error.Message, error);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class DisplayBoundsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(1920f, 1080f, 1920, 1080)]
|
||||
[InlineData(1281f, 721f, 1281, 721)]
|
||||
[InlineData(1280.5f, 720.5f, 1281, 721)]
|
||||
[InlineData(1280.4f, 720.4f, 1280, 720)]
|
||||
public void PixelSizesRoundToTheNearestPixel(float width, float height, int expectedWidth, int expectedHeight)
|
||||
{
|
||||
var bounds = new DisplayBounds(0f, 0f, width, height);
|
||||
|
||||
Assert.Equal(expectedWidth, bounds.PixelWidth);
|
||||
Assert.Equal(expectedHeight, bounds.PixelHeight);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0f, 0f, 1f, 1f, true)]
|
||||
[InlineData(-960f, -540f, 1920f, 1080f, true)]
|
||||
[InlineData(0f, 0f, 16384f, 16384f, true)]
|
||||
[InlineData(0f, 0f, 16385f, 1080f, false)]
|
||||
[InlineData(0f, 0f, 1920f, 16385f, false)]
|
||||
[InlineData(0f, 0f, 0.4f, 1f, false)]
|
||||
[InlineData(0f, 0f, 1f, 0f, false)]
|
||||
[InlineData(0f, 0f, -1920f, 1080f, false)]
|
||||
[InlineData(float.NaN, 0f, 1920f, 1080f, false)]
|
||||
[InlineData(0f, float.PositiveInfinity, 1920f, 1080f, false)]
|
||||
[InlineData(0f, 0f, float.NaN, 1080f, false)]
|
||||
[InlineData(0f, 0f, 1920f, float.NegativeInfinity, false)]
|
||||
public void UsabilityRequiresFiniteBoundsWithinTheSupportedSize(float left, float top, float width, float height, bool expected)
|
||||
=> Assert.Equal(expected, new DisplayBounds(left, top, width, height).IsUsable);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using ProxyForge.Export;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class ExportDetectorTests
|
||||
{
|
||||
const string Configuration = "動画出力";
|
||||
const string Progress = "出力";
|
||||
|
||||
static ExportDetector Create(bool commandLineEncode, Func<ExportPhase?>? resolve = null, List<int>? resolveCalls = null)
|
||||
=> new(
|
||||
commandLineEncode,
|
||||
() => Configuration,
|
||||
() => Progress,
|
||||
() =>
|
||||
{
|
||||
resolveCalls?.Add(1);
|
||||
return resolve is null ? ExportPhase.Idle : resolve();
|
||||
});
|
||||
|
||||
[Theory]
|
||||
[InlineData(new[] { "--encode", @"C:\project.ymmp" }, true)]
|
||||
[InlineData(new[] { "YukkuriMovieMaker.exe", "--ENCODE", @"C:\project.ymmp", "--output", @"C:\out.mp4" }, true)]
|
||||
[InlineData(new[] { "--encode" }, false)]
|
||||
[InlineData(new[] { "--encode", "--output" }, false)]
|
||||
[InlineData(new[] { "--encode", " " }, false)]
|
||||
[InlineData(new[] { @"C:\project.ymmp" }, false)]
|
||||
[InlineData(new string[0], false)]
|
||||
public void TheEncodeOptionIsRecognisedLikeTheHost(string[] arguments, bool expected)
|
||||
=> Assert.Equal(expected, ExportDetector.HasEncodeOption(arguments));
|
||||
|
||||
[Theory]
|
||||
[InlineData(Configuration, ExportWindowRole.Configuration)]
|
||||
[InlineData(Progress, ExportWindowRole.Progress)]
|
||||
[InlineData("", ExportWindowRole.None)]
|
||||
[InlineData(null, ExportWindowRole.None)]
|
||||
[InlineData("出力 ", ExportWindowRole.None)]
|
||||
[InlineData("YukkuriMovieMaker4", ExportWindowRole.None)]
|
||||
public void WindowsAreClassifiedByTheirExactTitle(string? title, ExportWindowRole expected)
|
||||
=> Assert.Equal(expected, Create(false).Classify(title));
|
||||
|
||||
[Fact]
|
||||
public void TheCommandLineEncodeAlwaysExports()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
var detector = Create(true, resolveCalls: calls);
|
||||
|
||||
Assert.True(detector.IsCommandLineEncode);
|
||||
Assert.True(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Resolve());
|
||||
Assert.Empty(calls);
|
||||
Assert.Equal(ExportPhase.Idle, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NothingIsExportingAtFirst()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
var detector = Create(false, resolveCalls: calls);
|
||||
|
||||
Assert.False(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Idle, detector.Resolve());
|
||||
Assert.Empty(calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheProgressWindowMeansExportingUntilItCloses()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
var detector = Create(false, resolveCalls: calls);
|
||||
|
||||
detector.OnWindowOpened(ExportWindowRole.Progress);
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Phase);
|
||||
Assert.True(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Resolve());
|
||||
Assert.Empty(calls);
|
||||
|
||||
detector.OnWindowClosed(ExportWindowRole.Progress);
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, detector.Phase);
|
||||
Assert.False(detector.IsExporting());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConfigurationWindowStartsThePreparation()
|
||||
{
|
||||
var detector = Create(false);
|
||||
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClosingTheConfigurationWindowKeepsThePreparation()
|
||||
{
|
||||
var detector = Create(false);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
detector.OnWindowClosed(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnrelatedWindowChangesNothing()
|
||||
{
|
||||
var detector = Create(false);
|
||||
|
||||
detector.OnWindowOpened(ExportWindowRole.None);
|
||||
detector.OnWindowClosed(ExportWindowRole.None);
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuringThePreparationTheWatchingThreadDecidesThatExportingHasStarted()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
ExportDetector? detector = null;
|
||||
detector = Create(false, () =>
|
||||
{
|
||||
detector!.OnWindowOpened(ExportWindowRole.Progress);
|
||||
return ExportPhase.Exporting;
|
||||
}, calls);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.True(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Phase);
|
||||
Assert.True(detector.IsExporting());
|
||||
Assert.Single(calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AVisibleProgressWindowIsAnExportEvenBeforeItsEventArrives()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
var detector = Create(false, () => ExportPhase.Exporting, calls);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.True(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Preparing, detector.Phase);
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Resolve());
|
||||
Assert.Equal(2, calls.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnExportThatStartsDuringTheResolutionWins()
|
||||
{
|
||||
ExportDetector? detector = null;
|
||||
detector = Create(false, () =>
|
||||
{
|
||||
detector!.OnWindowOpened(ExportWindowRole.Progress);
|
||||
return ExportPhase.Idle;
|
||||
});
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Resolve());
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DuringThePreparationTheWatchingThreadDecidesThatItWasCancelled()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
var detector = Create(false, resolveCalls: calls);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, detector.Resolve());
|
||||
Assert.Equal(ExportPhase.Idle, detector.Phase);
|
||||
Assert.Single(calls);
|
||||
Assert.False(detector.IsExporting());
|
||||
Assert.Single(calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AModalDialogKeepsThePreparationWithoutExporting()
|
||||
{
|
||||
var calls = new List<int>();
|
||||
var detector = Create(false, () => ExportPhase.Preparing, calls);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.False(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Preparing, detector.Phase);
|
||||
Assert.Equal(ExportPhase.Preparing, detector.Resolve());
|
||||
Assert.Equal(2, calls.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnresolvedPreparationIsTreatedAsExporting()
|
||||
{
|
||||
var detector = Create(false, () => null);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.True(detector.IsExporting());
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Resolve());
|
||||
Assert.Equal(ExportPhase.Preparing, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConfigurationWindowDuringAnExportDoesNotDemoteThePhase()
|
||||
{
|
||||
var detector = Create(false);
|
||||
detector.OnWindowOpened(ExportWindowRole.Progress);
|
||||
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, detector.Phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheProgressWindowEndsAPreparationThatWasResolvedTooEarly()
|
||||
{
|
||||
var detector = Create(false);
|
||||
detector.OnWindowOpened(ExportWindowRole.Configuration);
|
||||
Assert.False(detector.IsExporting());
|
||||
|
||||
detector.OnWindowOpened(ExportWindowRole.Progress);
|
||||
|
||||
Assert.True(detector.IsExporting());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Threading;
|
||||
using ProxyForge.Export;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Wpf")]
|
||||
public sealed class ExportWindowWatcherTests
|
||||
{
|
||||
const string Configuration = "動画出力";
|
||||
const string Progress = "出力";
|
||||
const int ChildVisibleStyle = 0x50000000;
|
||||
|
||||
static readonly ExportDetector Detector = new(false, () => Configuration, () => Progress, () => null);
|
||||
|
||||
static T RunSta<T>(Func<T> action)
|
||||
{
|
||||
var result = default(T)!;
|
||||
Exception? error = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
result = action();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
error = exception;
|
||||
}
|
||||
});
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
|
||||
if (error is not null)
|
||||
throw new InvalidOperationException(error.Message, error);
|
||||
return result;
|
||||
}
|
||||
|
||||
static T Watch<T>(Func<T> action)
|
||||
=> RunSta(() =>
|
||||
{
|
||||
var reported = new List<Exception>();
|
||||
ExportWindowWatcher.Attach(Detector, reported.Add);
|
||||
try
|
||||
{
|
||||
Assert.True(ExportWindowWatcher.IsAttached);
|
||||
return action();
|
||||
}
|
||||
finally
|
||||
{
|
||||
ExportWindowWatcher.Detach();
|
||||
Detector.OnWindowClosed(ExportWindowRole.Progress);
|
||||
Assert.Empty(reported);
|
||||
Assert.False(ExportWindowWatcher.IsAttached);
|
||||
}
|
||||
});
|
||||
|
||||
static void Pump()
|
||||
{
|
||||
var frame = new DispatcherFrame();
|
||||
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => frame.Continue = false), DispatcherPriority.ContextIdle);
|
||||
Dispatcher.PushFrame(frame);
|
||||
}
|
||||
|
||||
static void PumpUntil(Func<bool> condition)
|
||||
{
|
||||
while (!condition())
|
||||
Pump();
|
||||
}
|
||||
|
||||
static Window CreateWindow(string title) => new()
|
||||
{
|
||||
Title = title,
|
||||
Width = 120,
|
||||
Height = 80,
|
||||
Left = -10_000,
|
||||
Top = -10_000,
|
||||
ShowInTaskbar = false,
|
||||
ShowActivated = false,
|
||||
WindowStyle = WindowStyle.None,
|
||||
};
|
||||
|
||||
static (ExportPhase AfterShow, ExportPhase AfterClose) Observe(string initialTitle, string? lateTitle)
|
||||
=> Watch(() =>
|
||||
{
|
||||
var window = CreateWindow(initialTitle);
|
||||
window.Show();
|
||||
Pump();
|
||||
if (lateTitle is not null)
|
||||
{
|
||||
window.Title = lateTitle;
|
||||
Pump();
|
||||
}
|
||||
|
||||
var afterShow = Detector.Phase;
|
||||
window.Close();
|
||||
Pump();
|
||||
return (afterShow, Detector.Phase);
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public void AProgressWindowTitledBeforeShowingIsSeenAsExportingUntilItCloses()
|
||||
{
|
||||
var (afterShow, afterClose) = Observe(Progress, null);
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, afterShow);
|
||||
Assert.Equal(ExportPhase.Idle, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AProgressWindowTitledAfterShowingIsStillSeen()
|
||||
{
|
||||
var (afterShow, afterClose) = Observe(string.Empty, Progress);
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, afterShow);
|
||||
Assert.Equal(ExportPhase.Idle, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AConfigurationWindowStartsThePreparationAndClosingKeepsIt()
|
||||
{
|
||||
var (afterShow, afterClose) = Observe(Configuration, null);
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, afterShow);
|
||||
Assert.Equal(ExportPhase.Preparing, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnUnrelatedWindowChangesNothing()
|
||||
{
|
||||
var (afterShow, afterClose) = Observe("Something else", "Still something else");
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, afterShow);
|
||||
Assert.Equal(ExportPhase.Idle, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARetitledProgressWindowStaysAnExportUntilItCloses()
|
||||
{
|
||||
var (afterShow, afterClose) = Observe(Progress, "Something else");
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, afterShow);
|
||||
Assert.Equal(ExportPhase.Idle, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AProgressWindowRetitledAsTheConfigurationStillEndsTheExportWhenClosed()
|
||||
{
|
||||
var (afterShow, afterClose) = Observe(Progress, Configuration);
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, afterShow);
|
||||
Assert.Equal(ExportPhase.Idle, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHiddenWindowIsNotSeenUntilItIsShown()
|
||||
{
|
||||
var (whileHidden, afterShow, afterClose) = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow("Something else");
|
||||
new WindowInteropHelper(window).EnsureHandle();
|
||||
window.Title = Progress;
|
||||
Pump();
|
||||
var whileHidden = Detector.Phase;
|
||||
window.Show();
|
||||
Pump();
|
||||
var afterShow = Detector.Phase;
|
||||
window.Close();
|
||||
Pump();
|
||||
return (whileHidden, afterShow, Detector.Phase);
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, whileHidden);
|
||||
Assert.Equal(ExportPhase.Exporting, afterShow);
|
||||
Assert.Equal(ExportPhase.Idle, afterClose);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHiddenProgressWindowEndsTheExportAndShowingItAgainResumes()
|
||||
{
|
||||
var (afterHide, afterShowAgain) = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow(Progress);
|
||||
window.Show();
|
||||
Pump();
|
||||
window.Hide();
|
||||
Pump();
|
||||
var afterHide = Detector.Phase;
|
||||
window.Show();
|
||||
Pump();
|
||||
var afterShowAgain = Detector.Phase;
|
||||
window.Close();
|
||||
Pump();
|
||||
return (afterHide, afterShowAgain);
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, afterHide);
|
||||
Assert.Equal(ExportPhase.Exporting, afterShowAgain);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AChildWindowWithTheProgressTitleIsIgnored()
|
||||
{
|
||||
var (phase, scanned) = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow("Owner");
|
||||
window.Show();
|
||||
Pump();
|
||||
var parameters = new HwndSourceParameters(Progress)
|
||||
{
|
||||
ParentWindow = new WindowInteropHelper(window).Handle,
|
||||
WindowStyle = ChildVisibleStyle,
|
||||
Width = 10,
|
||||
Height = 10,
|
||||
};
|
||||
using (var child = new HwndSource(parameters))
|
||||
{
|
||||
Pump();
|
||||
var phase = Detector.Phase;
|
||||
var scanned = ExportWindowWatcher.Scan();
|
||||
window.Close();
|
||||
Pump();
|
||||
return (phase, scanned);
|
||||
}
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, phase);
|
||||
Assert.Equal(ExportPhase.Idle, scanned);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WindowsShownOnAnotherThreadAreNotWatched()
|
||||
{
|
||||
var phase = Watch(() =>
|
||||
{
|
||||
var shown = RunSta(() =>
|
||||
{
|
||||
var window = CreateWindow(Progress);
|
||||
window.Show();
|
||||
Pump();
|
||||
window.Close();
|
||||
Pump();
|
||||
return true;
|
||||
});
|
||||
Pump();
|
||||
return shown ? Detector.Phase : ExportPhase.Exporting;
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Idle, phase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheScanReportsAVisibleProgressWindow()
|
||||
{
|
||||
var (visible, hidden) = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow(Progress);
|
||||
window.Show();
|
||||
var visible = ExportWindowWatcher.Scan();
|
||||
window.Hide();
|
||||
var hidden = ExportWindowWatcher.Scan();
|
||||
window.Close();
|
||||
Pump();
|
||||
return (visible, hidden);
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, visible);
|
||||
Assert.Equal(ExportPhase.Idle, hidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheScanReportsAVisibleConfigurationWindowAsPreparing()
|
||||
{
|
||||
var scanned = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow(Configuration);
|
||||
window.Show();
|
||||
var scanned = ExportWindowWatcher.Scan();
|
||||
window.Close();
|
||||
Pump();
|
||||
return scanned;
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, scanned);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheScanPrefersTheProgressWindowOverTheConfigurationWindow()
|
||||
{
|
||||
var scanned = Watch(() =>
|
||||
{
|
||||
var configuration = CreateWindow(Configuration);
|
||||
var progress = CreateWindow(Progress);
|
||||
configuration.Show();
|
||||
progress.Show();
|
||||
var scanned = ExportWindowWatcher.Scan();
|
||||
progress.Close();
|
||||
configuration.Close();
|
||||
Pump();
|
||||
return scanned;
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, scanned);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheScanTreatsAModalDialogAsPreparing()
|
||||
{
|
||||
var (during, after) = Watch(() =>
|
||||
{
|
||||
var owner = CreateWindow("Owner");
|
||||
owner.Show();
|
||||
Pump();
|
||||
var dialog = CreateWindow("Dialog");
|
||||
dialog.Owner = owner;
|
||||
ExportPhase? during = null;
|
||||
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
|
||||
{
|
||||
during = ExportWindowWatcher.Scan();
|
||||
dialog.Close();
|
||||
}), DispatcherPriority.ContextIdle);
|
||||
dialog.ShowDialog();
|
||||
Pump();
|
||||
var after = ExportWindowWatcher.Scan();
|
||||
owner.Close();
|
||||
Pump();
|
||||
return (during, after);
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, during);
|
||||
Assert.Equal(ExportPhase.Idle, after);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheScanTreatsAModalDialogWithoutAnOwnerAsPreparing()
|
||||
{
|
||||
var (during, after) = Watch(() =>
|
||||
{
|
||||
var dialog = CreateWindow("Dialog");
|
||||
ExportPhase? during = null;
|
||||
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
|
||||
{
|
||||
during = ExportWindowWatcher.Scan();
|
||||
dialog.Close();
|
||||
}), DispatcherPriority.ContextIdle);
|
||||
dialog.ShowDialog();
|
||||
Pump();
|
||||
return (during, ExportWindowWatcher.Scan());
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, during);
|
||||
Assert.Equal(ExportPhase.Idle, after);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheScanTreatsADisabledVisibleWindowAsPreparing()
|
||||
{
|
||||
var (disabled, enabled) = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow("Owner");
|
||||
window.Show();
|
||||
Pump();
|
||||
var handle = new WindowInteropHelper(window).Handle;
|
||||
EnableWindow(handle, false);
|
||||
var disabled = ExportWindowWatcher.Scan();
|
||||
EnableWindow(handle, true);
|
||||
var enabled = ExportWindowWatcher.Scan();
|
||||
window.Close();
|
||||
Pump();
|
||||
return (disabled, enabled);
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Preparing, disabled);
|
||||
Assert.Equal(ExportPhase.Idle, enabled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePhaseIsResolvedOnTheWatchingThread()
|
||||
{
|
||||
var (fromAnotherThread, fromTheWatchingThread) = Watch(() =>
|
||||
{
|
||||
var window = CreateWindow(Progress);
|
||||
window.Show();
|
||||
Pump();
|
||||
var resolved = Task.Run(ExportWindowWatcher.ResolvePhase);
|
||||
PumpUntil(() => resolved.IsCompleted);
|
||||
var fromTheWatchingThread = ExportWindowWatcher.ResolvePhase();
|
||||
window.Close();
|
||||
Pump();
|
||||
return (resolved.Result, fromTheWatchingThread);
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, fromAnotherThread);
|
||||
Assert.Equal(ExportPhase.Exporting, fromTheWatchingThread);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAWatcherNothingCanBeResolved()
|
||||
{
|
||||
Assert.Null(ExportWindowWatcher.ResolvePhase());
|
||||
Assert.Null(ExportWindowWatcher.Scan());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AttachingTwiceKeepsTheFirstWatcher()
|
||||
{
|
||||
var phase = Watch(() =>
|
||||
{
|
||||
ExportWindowWatcher.Attach(new ExportDetector(false, () => "x", () => "y", () => null), _ => { });
|
||||
var window = CreateWindow(Progress);
|
||||
window.Show();
|
||||
Pump();
|
||||
var phase = Detector.Phase;
|
||||
window.Close();
|
||||
Pump();
|
||||
return phase;
|
||||
});
|
||||
|
||||
Assert.Equal(ExportPhase.Exporting, phase);
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
static extern bool EnableWindow(nint window, [MarshalAs(UnmanagedType.Bool)] bool enable);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Sources;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class FFmpegArgumentsTests
|
||||
{
|
||||
[Fact]
|
||||
public void WriteEncodeEmitsTheRawVideoPipeline()
|
||||
{
|
||||
var request = new FFmpegEncodeRequest(@"C:\cache\proxy.mp4", 960, 540, new FrameRate(30000, 1001), 544_320, 30, "h264_qsv");
|
||||
|
||||
var arguments = new Collection<string>();
|
||||
FFmpegArguments.WriteEncode(arguments, in request);
|
||||
|
||||
string[] expected =
|
||||
[
|
||||
"-hide_banner",
|
||||
"-loglevel", "error",
|
||||
"-y",
|
||||
"-f", "rawvideo",
|
||||
"-pix_fmt", "bgra",
|
||||
"-s", "960x540",
|
||||
"-r", "30000/1001",
|
||||
"-i", "-",
|
||||
"-an", "-sn", "-dn",
|
||||
"-c:v", "h264_qsv",
|
||||
"-b:v", "544320",
|
||||
"-g", "30",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-colorspace", "bt709",
|
||||
"-color_primaries", "bt709",
|
||||
"-color_trc", "bt709",
|
||||
"-color_range", "tv",
|
||||
"-f", "mp4",
|
||||
@"C:\cache\proxy.mp4",
|
||||
];
|
||||
|
||||
Assert.Equal(expected, arguments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WriteEncodeKeepsStandardInputOpen()
|
||||
{
|
||||
var request = new FFmpegEncodeRequest(@"C:\cache\proxy.mp4", 320, 240, new FrameRate(30, 1), 100_000, 1, "h264");
|
||||
|
||||
var arguments = new Collection<string>();
|
||||
FFmpegArguments.WriteEncode(arguments, in request);
|
||||
|
||||
Assert.DoesNotContain("-nostdin", arguments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WriteEncodePassesTheOutputPathWithoutQuoting()
|
||||
{
|
||||
var request = new FFmpegEncodeRequest(@"C:\cache dir\a b'c,d.mp4", 320, 240, new FrameRate(30, 1), 100_000, 1, "h264");
|
||||
|
||||
var arguments = new Collection<string>();
|
||||
FFmpegArguments.WriteEncode(arguments, in request);
|
||||
|
||||
Assert.Contains(@"C:\cache dir\a b'c,d.mp4", arguments);
|
||||
Assert.DoesNotContain(arguments, argument => argument.Contains('"'));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WriteEncoderProbeEncodesASingleBlackFrameToNothing()
|
||||
{
|
||||
var arguments = new Collection<string>();
|
||||
FFmpegArguments.WriteEncoderProbe(arguments, "h264_nvenc", 960, 540);
|
||||
|
||||
string[] expected =
|
||||
[
|
||||
"-hide_banner",
|
||||
"-nostdin",
|
||||
"-loglevel", "error",
|
||||
"-f", "lavfi",
|
||||
"-i", "color=c=black:s=960x540:r=30",
|
||||
"-frames:v", "1",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-c:v", "h264_nvenc",
|
||||
"-f", "null",
|
||||
"-",
|
||||
];
|
||||
|
||||
Assert.Equal(expected, arguments);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(960, 540, "960x540")]
|
||||
[InlineData(2, 2, "2x2")]
|
||||
[InlineData(3840, 2160, "3840x2160")]
|
||||
public void BuildFrameSizeUsesInvariantNumbers(int width, int height, string expected)
|
||||
=> Assert.Equal(expected, FFmpegArguments.BuildFrameSize(width, height));
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1, "30/1")]
|
||||
[InlineData(30000, 1001, "30000/1001")]
|
||||
[InlineData(24, 1, "24/1")]
|
||||
public void BuildFrameRateEmitsTheRationalForm(int numerator, int denominator, string expected)
|
||||
=> Assert.Equal(expected, FFmpegArguments.BuildFrameRate(new FrameRate(numerator, denominator)));
|
||||
|
||||
[Fact]
|
||||
public void BuildColorSourceMatchesTheLavfiSyntax()
|
||||
=> Assert.Equal("color=c=black:s=1280x720:r=30", FFmpegArguments.BuildColorSource(1280, 720));
|
||||
|
||||
[Fact]
|
||||
public void CalculateVideoBitrateScalesThePixelRate()
|
||||
=> Assert.Equal(544_320L, FFmpegArguments.CalculateVideoBitrate(960, 540, 30d, 50));
|
||||
|
||||
[Fact]
|
||||
public void CalculateVideoBitrateAtFullScaleIsTwiceTheHalfScale()
|
||||
=> Assert.Equal(2L * FFmpegArguments.CalculateVideoBitrate(960, 540, 30d, 50), FFmpegArguments.CalculateVideoBitrate(960, 540, 30d, 100));
|
||||
|
||||
[Fact]
|
||||
public void CalculateVideoBitrateClampsToTheMinimum()
|
||||
=> Assert.Equal(100_000L, FFmpegArguments.CalculateVideoBitrate(2, 2, 1d, 1));
|
||||
|
||||
[Fact]
|
||||
public void CalculateVideoBitrateClampsToTheMaximum()
|
||||
=> Assert.Equal(100_000_000L, FFmpegArguments.CalculateVideoBitrate(7680, 4320, 240d, 200));
|
||||
|
||||
[Theory]
|
||||
[InlineData(0d)]
|
||||
[InlineData(-1d)]
|
||||
[InlineData(double.NaN)]
|
||||
[InlineData(double.PositiveInfinity)]
|
||||
public void CalculateVideoBitrateUsesTheDefaultRateForAnUnknownFrameRate(double frameRate)
|
||||
=> Assert.Equal(
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, FFmpegArguments.DefaultFrameRate, 50),
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, frameRate, 50));
|
||||
|
||||
[Fact]
|
||||
public void CalculateVideoBitrateClampsAnExcessiveFrameRate()
|
||||
=> Assert.Equal(
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, 240d, 50),
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, 100_000d, 50));
|
||||
|
||||
[Fact]
|
||||
public void CalculateVideoBitrateClampsATinyFrameRate()
|
||||
=> Assert.Equal(
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, 1d, 50),
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, 0.001d, 50));
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
public void CalculateVideoBitrateTreatsANonPositiveScaleAsFullScale(int scale)
|
||||
=> Assert.Equal(
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, 30d, 100),
|
||||
FFmpegArguments.CalculateVideoBitrate(960, 540, 30d, scale));
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class FFmpegDiagnosticsTests
|
||||
{
|
||||
[Fact]
|
||||
public void AppendJoinsLinesWithANewline()
|
||||
{
|
||||
var buffer = new FFmpegDiagnosticsBuffer(4096);
|
||||
buffer.Append("first");
|
||||
buffer.Append("second");
|
||||
|
||||
Assert.Equal("first\nsecond", buffer.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AppendSkipsBlankLines()
|
||||
{
|
||||
var buffer = new FFmpegDiagnosticsBuffer(4096);
|
||||
buffer.Append("");
|
||||
buffer.Append(" ");
|
||||
buffer.Append("real");
|
||||
buffer.Append("\t");
|
||||
|
||||
Assert.Equal("real", buffer.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AppendTrimsSurroundingWhitespace()
|
||||
{
|
||||
var buffer = new FFmpegDiagnosticsBuffer(4096);
|
||||
buffer.Append(" padded ");
|
||||
|
||||
Assert.Equal("padded", buffer.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AppendNeverExceedsTheCapacity()
|
||||
{
|
||||
var buffer = new FFmpegDiagnosticsBuffer(16);
|
||||
for (var i = 0; i < 1000; i++)
|
||||
buffer.Append("0123456789");
|
||||
|
||||
Assert.True(buffer.ToString().Length <= 16);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AppendKeepsTheEarliestDiagnosticsWhenTruncating()
|
||||
{
|
||||
var buffer = new FFmpegDiagnosticsBuffer(16);
|
||||
buffer.Append("root cause here");
|
||||
buffer.Append("cascading noise");
|
||||
|
||||
Assert.StartsWith("root cause here", buffer.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AppendCutsALineThatOverflowsTheCapacity()
|
||||
{
|
||||
var buffer = new FFmpegDiagnosticsBuffer(8);
|
||||
buffer.Append("0123456789");
|
||||
|
||||
Assert.Equal("01234567", buffer.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstDiagnosticLineReturnsTheLeadingLine()
|
||||
{
|
||||
var result = new FFmpegProcessResult(1, "Unknown encoder 'h264_nvenc'\nError selecting an encoder");
|
||||
|
||||
Assert.Equal("Unknown encoder 'h264_nvenc'", result.FirstDiagnosticLine(200));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstDiagnosticLineTruncatesToTheRequestedLength()
|
||||
{
|
||||
var result = new FFmpegProcessResult(1, new string('x', 500));
|
||||
|
||||
Assert.Equal(200, result.FirstDiagnosticLine(200).Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstDiagnosticLineOfBlankDiagnosticsIsEmpty()
|
||||
{
|
||||
var result = new FFmpegProcessResult(1, " \n ");
|
||||
|
||||
Assert.Equal(string.Empty, result.FirstDiagnosticLine(200));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, true)]
|
||||
[InlineData(1, false)]
|
||||
[InlineData(-1, false)]
|
||||
public void OnlyAZeroExitCodeSucceeds(int exitCode, bool expected)
|
||||
=> Assert.Equal(expected, new FFmpegProcessResult(exitCode, string.Empty).IsSuccess);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class FFmpegEncoderCandidatesTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("h264_nvenc", FFmpegEncoderCandidates.VendorNvidia)]
|
||||
[InlineData("av1_nvenc", FFmpegEncoderCandidates.VendorNvidia)]
|
||||
[InlineData("h264_amf", FFmpegEncoderCandidates.VendorAmd)]
|
||||
[InlineData("h264_qsv", FFmpegEncoderCandidates.VendorIntel)]
|
||||
[InlineData("h264", 0)]
|
||||
[InlineData("libopenh264", 0)]
|
||||
public void VendorOfMapsTheEncoderSuffixToAVendorId(string encoder, int expected)
|
||||
=> Assert.Equal(expected, FFmpegEncoderCandidates.VendorOf(encoder));
|
||||
|
||||
[Fact]
|
||||
public void TheCandidatesAreNvencQsvAmfInThatOrder()
|
||||
{
|
||||
string[] expected = ["h264_nvenc", "h264_qsv", "h264_amf"];
|
||||
|
||||
Assert.Equal(expected, Candidates());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutADiscreteGpuTheDeclaredOrderIsKept()
|
||||
{
|
||||
string[] expected = ["h264_nvenc", "h264_qsv", "h264_amf"];
|
||||
|
||||
Assert.Equal(expected, Order([]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADiscreteAmdGpuPromotesAmfAboveIntegratedIntel()
|
||||
{
|
||||
string[] expected = ["h264_amf", "h264_nvenc", "h264_qsv"];
|
||||
|
||||
Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorAmd]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADiscreteNvidiaGpuKeepsNvencFirst()
|
||||
{
|
||||
string[] expected = ["h264_nvenc", "h264_qsv", "h264_amf"];
|
||||
|
||||
Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorNvidia]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADiscreteIntelGpuPromotesQsv()
|
||||
{
|
||||
string[] expected = ["h264_qsv", "h264_nvenc", "h264_amf"];
|
||||
|
||||
Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorIntel]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SeveralDiscreteVendorsKeepTheirRelativeOrder()
|
||||
{
|
||||
string[] expected = ["h264_nvenc", "h264_amf", "h264_qsv"];
|
||||
|
||||
Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorAmd, FFmpegEncoderCandidates.VendorNvidia]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOrderIsAPermutationOfTheInput()
|
||||
{
|
||||
var ordered = Order([FFmpegEncoderCandidates.VendorAmd]);
|
||||
|
||||
Assert.Equal(Candidates().Order(), ordered.Order());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATooSmallDestinationIsRejected()
|
||||
{
|
||||
var destination = new string[FFmpegEncoderCandidates.Hardware264.Length - 1];
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() =>
|
||||
FFmpegEncoderCandidates.Order(FFmpegEncoderCandidates.Hardware264, new HashSet<int>(), destination));
|
||||
}
|
||||
|
||||
static string[] Candidates() => FFmpegEncoderCandidates.Hardware264.ToArray();
|
||||
|
||||
static string[] Order(int[] discreteVendors)
|
||||
{
|
||||
var destination = new string[FFmpegEncoderCandidates.Hardware264.Length];
|
||||
FFmpegEncoderCandidates.Order(FFmpegEncoderCandidates.Hardware264, new HashSet<int>(discreteVendors), destination);
|
||||
return destination;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class FFmpegExecutablesTests
|
||||
{
|
||||
[Fact]
|
||||
public void UnavailableReportsNotAvailable()
|
||||
{
|
||||
var executables = FFmpegExecutables.Unavailable;
|
||||
|
||||
Assert.False(executables.IsAvailable);
|
||||
Assert.Equal(string.Empty, executables.FFmpegPath);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", false)]
|
||||
[InlineData(@"C:\ffmpeg.exe", true)]
|
||||
public void IsAvailableRequiresAnExecutablePath(string ffmpegPath, bool expected)
|
||||
=> Assert.Equal(expected, new FFmpegExecutables(ffmpegPath).IsAvailable);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
sealed class FakeEncodeSession(ProxyAnalysis analysis, Func<int, int, string, IProgress<double>?, CancellationToken, Task<long>> encode) : IProxyEncodeSession
|
||||
{
|
||||
public bool IsDisposed { get; private set; }
|
||||
|
||||
public ProxyAnalysis Analysis => analysis;
|
||||
|
||||
public Task<long> EncodeAsync(int firstFrame, int frameCount, string outputPath, IProgress<double>? progress, CancellationToken cancellationToken)
|
||||
=> encode(firstFrame, frameCount, outputPath, progress, cancellationToken);
|
||||
|
||||
public void Dispose() => IsDisposed = true;
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class FrameRateResolverTests
|
||||
{
|
||||
static Func<TimeSpan, int> HostFunction(int numerator, int denominator)
|
||||
=> time => FrameTime.TimeToFrame(time, numerator, denominator);
|
||||
|
||||
static TimeSpan DurationOf(int frameCount, int numerator, int denominator)
|
||||
=> TimeSpan.FromTicks((long)Math.Round((double)frameCount * denominator * TimeSpan.TicksPerSecond / numerator));
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1)]
|
||||
[InlineData(24, 1)]
|
||||
[InlineData(25, 1)]
|
||||
[InlineData(50, 1)]
|
||||
[InlineData(60, 1)]
|
||||
[InlineData(120, 1)]
|
||||
[InlineData(240, 1)]
|
||||
[InlineData(15, 1)]
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(24000, 1001)]
|
||||
[InlineData(30000, 1001)]
|
||||
[InlineData(60000, 1001)]
|
||||
[InlineData(2997, 100)]
|
||||
[InlineData(1000000, 33367)]
|
||||
[InlineData(2, 3)]
|
||||
public void RecoversTheExactRateFromTheHostConversion(int numerator, int denominator)
|
||||
{
|
||||
var function = HostFunction(numerator, denominator);
|
||||
var duration = DurationOf(1000, numerator, denominator);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(function, function(duration), duration);
|
||||
|
||||
Assert.Equal(new FrameRate(numerator, denominator), rate);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(30000, 1001)]
|
||||
[InlineData(60000, 1001)]
|
||||
[InlineData(24000, 1001)]
|
||||
public void RecoversTheExactRateForAVeryShortClip(int numerator, int denominator)
|
||||
{
|
||||
var function = HostFunction(numerator, denominator);
|
||||
var duration = DurationOf(3, numerator, denominator);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(function, function(duration), duration);
|
||||
|
||||
Assert.Equal(new FrameRate(numerator, denominator), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecoversTheExactRateForAThreeHourClip()
|
||||
{
|
||||
var function = HostFunction(30000, 1001);
|
||||
var duration = TimeSpan.FromHours(3);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(function, function(duration), duration);
|
||||
|
||||
Assert.Equal(new FrameRate(30000, 1001), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecoversTheExactRateWhenTheDurationHasAnAudioTail()
|
||||
{
|
||||
var function = HostFunction(30000, 1001);
|
||||
var duration = DurationOf(1000, 30000, 1001) + TimeSpan.FromMilliseconds(300);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(function, function(duration), duration);
|
||||
|
||||
Assert.Equal(new FrameRate(30000, 1001), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecoversTheExactRateWhereTheApproximationFails()
|
||||
{
|
||||
var function = HostFunction(30000, 1001);
|
||||
var duration = DurationOf(1000, 30000, 1001);
|
||||
var frameCount = function(duration);
|
||||
|
||||
Assert.NotEqual(new FrameRate(30000, 1001), FrameRate.Approximate(frameCount, duration));
|
||||
Assert.Equal(new FrameRate(30000, 1001), FrameRateResolver.Resolve(function, frameCount, duration));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FallsBackToTheApproximationWhenTheFunctionClampsAtTheEnd()
|
||||
{
|
||||
var function = HostFunction(30, 1);
|
||||
var duration = TimeSpan.FromSeconds(10);
|
||||
var frameCount = function(duration);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(time => Math.Min(function(time), frameCount), frameCount, duration);
|
||||
|
||||
Assert.Equal(FrameRate.Approximate(frameCount, duration), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FallsBackToTheApproximationWhenTheFunctionThrowsOutsideTheClip()
|
||||
{
|
||||
var function = HostFunction(30, 1);
|
||||
var duration = TimeSpan.FromSeconds(10);
|
||||
var frameCount = function(duration);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(
|
||||
time => time > duration ? throw new ArgumentOutOfRangeException(nameof(time)) : function(time),
|
||||
frameCount,
|
||||
duration);
|
||||
|
||||
Assert.Equal(FrameRate.Approximate(frameCount, duration), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FallsBackToTheApproximationWhenTheFunctionIsConstant()
|
||||
{
|
||||
var duration = TimeSpan.FromSeconds(10);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(_ => 0, 1, duration);
|
||||
|
||||
Assert.Equal(FrameRate.Approximate(1, duration), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FallsBackToTheApproximationWhenTheFunctionDisagreesInsideTheClip()
|
||||
{
|
||||
var function = HostFunction(30000, 1001);
|
||||
var duration = DurationOf(300, 30000, 1001) + TimeSpan.FromMilliseconds(300);
|
||||
var frameCount = function(duration);
|
||||
var disagreement = new TimeSpan(duration.Ticks / 7 * 3);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(
|
||||
time => time == disagreement ? function(time) + 1 : function(time),
|
||||
frameCount,
|
||||
duration);
|
||||
|
||||
Assert.Equal(FrameRate.Approximate(frameCount, duration), rate);
|
||||
Assert.NotEqual(new FrameRate(30000, 1001), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FallsBackToTheApproximationWhenTheFunctionTruncates()
|
||||
{
|
||||
var duration = TimeSpan.FromSeconds(10);
|
||||
Func<TimeSpan, int> function = time => (int)Math.Floor(time.TotalSeconds * 30000d / 1001d);
|
||||
var frameCount = function(duration);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(function, frameCount, duration);
|
||||
|
||||
Assert.Equal(FrameRate.Approximate(frameCount, duration), rate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FallsBackToTheApproximationWhenTheFrameCountContradictsTheFunction()
|
||||
{
|
||||
var function = HostFunction(30, 1);
|
||||
var duration = TimeSpan.FromSeconds(10);
|
||||
|
||||
var rate = FrameRateResolver.Resolve(function, 299, duration);
|
||||
|
||||
Assert.Equal(FrameRate.Approximate(299, duration), rate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class FrameRateTests
|
||||
{
|
||||
[Fact]
|
||||
public void ApproximateReproducesAnIntegerRate()
|
||||
{
|
||||
var rate = FrameRate.Approximate(180, TimeSpan.FromSeconds(6));
|
||||
|
||||
Assert.Equal(30, rate.Numerator);
|
||||
Assert.Equal(1, rate.Denominator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApproximateReproducesTheNtscRateWhenTheDurationIsExact()
|
||||
{
|
||||
var duration = TimeSpan.FromTicks(120L * TimeSpan.TicksPerSecond * 1001L / 30000L);
|
||||
|
||||
var rate = FrameRate.Approximate(120, duration);
|
||||
|
||||
Assert.Equal(30000, rate.Numerator);
|
||||
Assert.Equal(1001, rate.Denominator);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(24, 1)]
|
||||
[InlineData(25, 1)]
|
||||
[InlineData(50, 1)]
|
||||
[InlineData(60, 1)]
|
||||
[InlineData(24000, 1001)]
|
||||
[InlineData(60000, 1001)]
|
||||
public void ApproximateRoundTripsCommonRates(int numerator, int denominator)
|
||||
{
|
||||
const int frameCount = 600;
|
||||
var duration = TimeSpan.FromTicks(frameCount * TimeSpan.TicksPerSecond * denominator / numerator);
|
||||
|
||||
var rate = FrameRate.Approximate(frameCount, duration);
|
||||
|
||||
Assert.Equal(numerator, rate.Numerator);
|
||||
Assert.Equal(denominator, rate.Denominator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApproximateStaysWithinIntegerRangeForLongDurations()
|
||||
{
|
||||
var duration = TimeSpan.FromHours(3);
|
||||
var frameCount = (int)(duration.TotalSeconds * 30);
|
||||
|
||||
var rate = FrameRate.Approximate(frameCount, duration);
|
||||
|
||||
Assert.True(rate.IsValid);
|
||||
Assert.Equal(30d, rate.Value, 9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApproximateApproximatesAnAwkwardDuration()
|
||||
{
|
||||
var rate = FrameRate.Approximate(108_000, TimeSpan.FromTicks(36_000_000_001L));
|
||||
|
||||
Assert.True(rate.IsValid);
|
||||
Assert.InRange(rate.Value, 29.999_999, 30.000_001);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
public void ApproximateRejectsANonPositiveFrameCount(int frameCount)
|
||||
=> Assert.Throws<ArgumentOutOfRangeException>(() => FrameRate.Approximate(frameCount, TimeSpan.FromSeconds(1)));
|
||||
|
||||
[Fact]
|
||||
public void ApproximateRejectsAZeroDuration()
|
||||
=> Assert.Throws<ArgumentOutOfRangeException>(() => FrameRate.Approximate(1, TimeSpan.Zero));
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1, true)]
|
||||
[InlineData(30000, 1001, true)]
|
||||
[InlineData(0, 1, false)]
|
||||
[InlineData(30, 0, false)]
|
||||
[InlineData(-30, 1, false)]
|
||||
[InlineData(30, -1, false)]
|
||||
public void IsValidRequiresPositiveTerms(int numerator, int denominator, bool expected)
|
||||
=> Assert.Equal(expected, new FrameRate(numerator, denominator).IsValid);
|
||||
|
||||
[Fact]
|
||||
public void GetFrameIndexMatchesTheHostConversion()
|
||||
{
|
||||
var rate = new FrameRate(30000, 1001);
|
||||
|
||||
for (var index = 0; index < 500; index++)
|
||||
{
|
||||
var time = TimeSpan.FromTicks(index * 137_913L);
|
||||
Assert.Equal(FrameTime.TimeToFrame(time, 30000, 1001), rate.GetFrameIndex(time));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSampleTimeIsTheMiddleOfEachFrame()
|
||||
{
|
||||
var rate = new FrameRate(30, 1);
|
||||
|
||||
Assert.Equal(TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 60), rate.GetSampleTime(0));
|
||||
Assert.Equal(TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 20), rate.GetSampleTime(1));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1, 180)]
|
||||
[InlineData(30000, 1001, 120)]
|
||||
[InlineData(24000, 1001, 97)]
|
||||
[InlineData(1, 1, 3)]
|
||||
public void GetSampleTimeStaysInsideItsOwnFrame(int numerator, int denominator, int frameCount)
|
||||
{
|
||||
var rate = new FrameRate(numerator, denominator);
|
||||
|
||||
for (var index = 0; index < frameCount; index++)
|
||||
{
|
||||
var sample = rate.GetSampleTime(index);
|
||||
var start = (Int128)index * denominator * TimeSpan.TicksPerSecond / numerator;
|
||||
var end = (Int128)(index + 1) * denominator * TimeSpan.TicksPerSecond / numerator;
|
||||
Assert.True(start <= sample.Ticks && sample.Ticks < end);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSampleTimeIsStrictlyIncreasing()
|
||||
{
|
||||
var rate = new FrameRate(30000, 1001);
|
||||
var previous = TimeSpan.MinValue;
|
||||
|
||||
for (var index = 0; index < 120; index++)
|
||||
{
|
||||
var sample = rate.GetSampleTime(index);
|
||||
Assert.True(sample > previous);
|
||||
previous = sample;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSampleTimeDoesNotOverflowForTheLastFrameOfALongVideo()
|
||||
{
|
||||
var rate = new FrameRate(60000, 1001);
|
||||
|
||||
var sample = rate.GetSampleTime(int.MaxValue - 1);
|
||||
|
||||
Assert.InRange(sample.TotalHours, 9_900d, 10_000d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSampleTimeRejectsANegativeIndex()
|
||||
=> Assert.Throws<ArgumentOutOfRangeException>(() => new FrameRate(30, 1).GetSampleTime(-1));
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1, 0L, 0)]
|
||||
[InlineData(30, 1, 3_500_000L, 10)]
|
||||
[InlineData(30, 1, 3_666_666L, 10)]
|
||||
[InlineData(30, 1, 3_666_667L, 11)]
|
||||
[InlineData(30000, 1001, 100_100_000L, 300)]
|
||||
[InlineData(30000, 1001, 100_099_999L, 299)]
|
||||
[InlineData(30, 1, -1L, 0)]
|
||||
[InlineData(30, 1, long.MaxValue, int.MaxValue)]
|
||||
public void GetContainingFrameFloorsLikeTheHostDecoders(int numerator, int denominator, long ticks, int expected)
|
||||
=> Assert.Equal(expected, new FrameRate(numerator, denominator).GetContainingFrame(new TimeSpan(ticks)));
|
||||
|
||||
[Fact]
|
||||
public void TheContainingFrameDiffersFromTheRoundedIndexInTheUpperHalf()
|
||||
{
|
||||
var rate = new FrameRate(30, 1);
|
||||
var sample = rate.GetSampleTime(10);
|
||||
|
||||
Assert.Equal(10, rate.GetContainingFrame(sample));
|
||||
Assert.Equal(11, rate.GetFrameIndex(sample));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1, 300, 100_000_000L)]
|
||||
[InlineData(30000, 1001, 300, 100_100_000L)]
|
||||
[InlineData(24000, 1001, 1, 417_083L)]
|
||||
[InlineData(60, 1, 0, 0L)]
|
||||
public void GetFrameStartIsTheExactBeginningOfTheFrame(int numerator, int denominator, int frame, long expectedTicks)
|
||||
{
|
||||
var rate = new FrameRate(numerator, denominator);
|
||||
|
||||
var start = rate.GetFrameStart(frame);
|
||||
|
||||
Assert.Equal(expectedTicks, start.Ticks);
|
||||
Assert.Equal(frame, rate.GetContainingFrame(start + TimeSpan.FromTicks(1)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetFrameStartRejectsANegativeIndex()
|
||||
=> Assert.Throws<ArgumentOutOfRangeException>(() => new FrameRate(30, 1).GetFrameStart(-1));
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
using System.IO;
|
||||
using ProxyForge.Cache;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class ProxyCacheTests : IDisposable
|
||||
{
|
||||
readonly string root = Path.Combine(Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
|
||||
public ProxyCacheTests() => Directory.CreateDirectory(root);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
string CacheDirectory => Path.Combine(root, "cache");
|
||||
|
||||
ProxyCache CreateCache() => new(CacheDirectory);
|
||||
|
||||
SourceIdentity CreateSource(string name = "source.mp4", int length = 1000)
|
||||
{
|
||||
var path = Path.Combine(root, name);
|
||||
File.WriteAllBytes(path, new byte[length]);
|
||||
return SourceIdentity.Of(path)!.Value;
|
||||
}
|
||||
|
||||
static ProxyCacheEntry Describe(SourceIdentity source, int scale = 50, int frameCount = 300, int chunkLength = 100) => new()
|
||||
{
|
||||
SourcePath = source.Path,
|
||||
SourceLength = source.Length,
|
||||
SourceWriteTimeTicks = source.WriteTimeTicks,
|
||||
Scale = scale,
|
||||
ProxyWidth = 960,
|
||||
ProxyHeight = 540,
|
||||
DisplayLeft = -960f,
|
||||
DisplayTop = -540f,
|
||||
DisplayWidth = 1920f,
|
||||
DisplayHeight = 1080f,
|
||||
FrameRateNumerator = 30000,
|
||||
FrameRateDenominator = 1001,
|
||||
DurationTicks = TimeSpan.TicksPerSecond * 10,
|
||||
FrameCount = frameCount,
|
||||
ChunkLength = chunkLength,
|
||||
};
|
||||
|
||||
static string WriteChunk(ProxyCache cache, int length = 100)
|
||||
{
|
||||
var path = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(path, new byte[length]);
|
||||
return path;
|
||||
}
|
||||
|
||||
static ProxyCacheEntry Fill(ProxyCache cache, ProxyCacheEntry registered, int chunkLength = 100)
|
||||
{
|
||||
var entry = registered;
|
||||
for (var chunk = 0; chunk < registered.ChunkCount; chunk++)
|
||||
entry = cache.AddChunk(registered.Id, chunk, WriteChunk(cache, chunkLength))!;
|
||||
return entry;
|
||||
}
|
||||
|
||||
ProxyCacheEntry AddComplete(ProxyCache cache, SourceIdentity source, int scale = 50, int chunkLength = 100)
|
||||
=> Fill(cache, cache.Register(Describe(source, scale)), chunkLength);
|
||||
|
||||
[Fact]
|
||||
public void AMissingSourceHasNoIdentity()
|
||||
=> Assert.Null(SourceIdentity.Of(Path.Combine(root, "missing.mp4")));
|
||||
|
||||
[Fact]
|
||||
public void AnInvalidPathHasNoIdentity()
|
||||
=> Assert.Null(SourceIdentity.Of("\0"));
|
||||
|
||||
[Fact]
|
||||
public void TheIdentityIsTheFullPathLengthAndWriteTime()
|
||||
{
|
||||
var path = Path.Combine(root, "source.mp4");
|
||||
File.WriteAllBytes(path, new byte[123]);
|
||||
|
||||
var identity = SourceIdentity.Of(Path.Combine(root, ".", "source.mp4"))!.Value;
|
||||
|
||||
Assert.Equal(path, identity.Path);
|
||||
Assert.Equal(123L, identity.Length);
|
||||
Assert.Equal(File.GetLastWriteTimeUtc(path).Ticks, identity.WriteTimeTicks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IdentitiesAreEqualRegardlessOfThePathCase()
|
||||
{
|
||||
var identity = new SourceIdentity(@"C:\Videos\Source.mp4", 123L, 456L);
|
||||
var upper = identity with { Path = identity.Path.ToUpperInvariant() };
|
||||
|
||||
Assert.Equal(identity, upper);
|
||||
Assert.Equal(identity.GetHashCode(), upper.GetHashCode());
|
||||
Assert.NotEqual(identity, identity with { Length = 124L });
|
||||
Assert.NotEqual(identity, identity with { WriteTimeTicks = 457L });
|
||||
Assert.NotEqual(identity, identity with { Path = @"C:\Videos\Other.mp4" });
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(300, 100, 3)]
|
||||
[InlineData(301, 100, 4)]
|
||||
[InlineData(1, 100, 1)]
|
||||
[InlineData(100, 0, 0)]
|
||||
public void TheChunkCountCoversEveryFrame(int frameCount, int chunkLength, int expected)
|
||||
=> Assert.Equal(expected, new ProxyCacheEntry { FrameCount = frameCount, ChunkLength = chunkLength }.ChunkCount);
|
||||
|
||||
[Fact]
|
||||
public void AnEntryIsCompleteWhenEveryChunkExists()
|
||||
{
|
||||
var entry = new ProxyCacheEntry { FrameCount = 250, ChunkLength = 100, Chunks = [0, 2] };
|
||||
|
||||
Assert.False(entry.IsComplete);
|
||||
Assert.True(entry.HasChunk(2));
|
||||
Assert.False(entry.HasChunk(1));
|
||||
|
||||
entry.Chunks.Add(1);
|
||||
|
||||
Assert.True(entry.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClonesDoNotShareTheChunkList()
|
||||
{
|
||||
var entry = new ProxyCacheEntry { FrameCount = 300, ChunkLength = 100, Chunks = [0] };
|
||||
|
||||
var clone = entry.Clone();
|
||||
clone.Chunks.Add(1);
|
||||
|
||||
Assert.Single(entry.Chunks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEmptyCacheFindsNothing()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
|
||||
Assert.Null(cache.Find(CreateSource(), 50));
|
||||
Assert.Equal(0, cache.Count);
|
||||
Assert.Equal(0L, cache.TotalBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterCreatesAnEmptyEntryWithItsDirectory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
|
||||
var before = DateTime.UtcNow.Ticks;
|
||||
var registered = cache.Register(Describe(source));
|
||||
|
||||
Assert.NotEqual(Guid.Empty, registered.Id);
|
||||
Assert.Empty(registered.Chunks);
|
||||
Assert.Equal(3, registered.ChunkCount);
|
||||
Assert.Equal(0L, registered.FileLength);
|
||||
Assert.InRange(registered.CreatedTicks, before, DateTime.UtcNow.Ticks);
|
||||
Assert.Equal(registered.CreatedTicks, registered.LastUsedTicks);
|
||||
Assert.True(Directory.Exists(cache.GetDirectoryPath(registered)));
|
||||
Assert.Equal(1, cache.Count);
|
||||
Assert.NotNull(cache.Find(source, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterRejectsAnEntryWithoutALayout()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
|
||||
Assert.Throws<ArgumentException>(() => cache.Register(Describe(CreateSource(), chunkLength: 0)));
|
||||
Assert.Throws<ArgumentException>(() => cache.Register(Describe(CreateSource(), frameCount: 0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisteringTheSameLayoutAgainReturnsTheExistingEntry()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var registered = cache.Register(Describe(source));
|
||||
cache.AddChunk(registered.Id, 1, WriteChunk(cache));
|
||||
|
||||
var again = cache.Register(Describe(source));
|
||||
|
||||
Assert.Equal(registered.Id, again.Id);
|
||||
Assert.Equal([1], again.Chunks);
|
||||
Assert.Equal(1, cache.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisteringADifferentLayoutReplacesTheEntry()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var registered = cache.Register(Describe(source));
|
||||
cache.AddChunk(registered.Id, 0, WriteChunk(cache));
|
||||
|
||||
var replaced = cache.Register(Describe(source, chunkLength: 50));
|
||||
|
||||
Assert.NotEqual(registered.Id, replaced.Id);
|
||||
Assert.Empty(replaced.Chunks);
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(registered)));
|
||||
Assert.Equal(1, cache.Count);
|
||||
Assert.Equal(0L, cache.TotalBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChunkMovesTheFileAndFillsTheBookkeeping()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var registered = cache.Register(Describe(CreateSource()));
|
||||
var temporary = WriteChunk(cache, 120);
|
||||
Thread.Sleep(20);
|
||||
|
||||
var updated = cache.AddChunk(registered.Id, 2, temporary)!;
|
||||
|
||||
Assert.Equal([2], updated.Chunks);
|
||||
Assert.Equal(120L, updated.FileLength);
|
||||
Assert.True(updated.LastUsedTicks > registered.LastUsedTicks);
|
||||
Assert.False(File.Exists(temporary));
|
||||
Assert.True(File.Exists(cache.GetChunkPath(updated, 2)));
|
||||
Assert.EndsWith(Path.Combine(registered.Id.ToString("N"), "000002.mp4"), cache.GetChunkPath(updated, 2));
|
||||
Assert.Equal(120L, cache.TotalBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChunksAreKeptSortedAndReplacingOneKeepsTheTotalRight()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var registered = cache.Register(Describe(CreateSource()));
|
||||
cache.AddChunk(registered.Id, 2, WriteChunk(cache, 100));
|
||||
cache.AddChunk(registered.Id, 0, WriteChunk(cache, 100));
|
||||
|
||||
var updated = cache.AddChunk(registered.Id, 2, WriteChunk(cache, 30))!;
|
||||
|
||||
Assert.Equal([0, 2], updated.Chunks);
|
||||
Assert.Equal(130L, updated.FileLength);
|
||||
Assert.Equal(30L, new FileInfo(cache.GetChunkPath(updated, 2)).Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChunkOutsideTheLayoutOrForAnUnknownEntryDiscardsTheFile()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var registered = cache.Register(Describe(CreateSource()));
|
||||
var outside = WriteChunk(cache);
|
||||
var unknown = WriteChunk(cache);
|
||||
|
||||
Assert.Null(cache.AddChunk(registered.Id, 3, outside));
|
||||
Assert.Null(cache.AddChunk(Guid.NewGuid(), 0, unknown));
|
||||
Assert.False(File.Exists(outside));
|
||||
Assert.False(File.Exists(unknown));
|
||||
Assert.Equal(0L, cache.TotalBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChunkRejectsAnEmptyTemporaryPath()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var registered = cache.Register(Describe(CreateSource()));
|
||||
|
||||
Assert.Throws<ArgumentException>(() => cache.AddChunk(registered.Id, 0, string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FillingEveryChunkCompletesTheEntry()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
|
||||
var entry = AddComplete(cache, source);
|
||||
|
||||
Assert.True(entry.IsComplete);
|
||||
Assert.Equal([0, 1, 2], entry.Chunks);
|
||||
Assert.Equal(300L, entry.FileLength);
|
||||
Assert.True(cache.Find(source, 50)!.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ForgetChunkDeletesTheFileAndTheCoverage()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var entry = AddComplete(cache, CreateSource());
|
||||
|
||||
var updated = cache.ForgetChunk(entry.Id, 1)!;
|
||||
|
||||
Assert.Equal([0, 2], updated.Chunks);
|
||||
Assert.Equal(200L, updated.FileLength);
|
||||
Assert.False(File.Exists(cache.GetChunkPath(entry, 1)));
|
||||
Assert.Equal([0, 2], cache.ForgetChunk(entry.Id, 1)!.Chunks);
|
||||
Assert.Null(cache.ForgetChunk(Guid.NewGuid(), 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetReturnsACopyOfTheEntryById()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var entry = AddComplete(cache, CreateSource());
|
||||
|
||||
var got = cache.Get(entry.Id)!;
|
||||
got.Chunks.Clear();
|
||||
|
||||
Assert.Equal(entry.Id, got.Id);
|
||||
Assert.Equal(3, cache.Get(entry.Id)!.Chunks.Count);
|
||||
Assert.Null(cache.Get(Guid.NewGuid()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindReturnsTheEntryForTheSameSourceAndScale()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var added = AddComplete(cache, source);
|
||||
|
||||
var found = cache.Find(source, 50);
|
||||
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal(added.Id, found.Id);
|
||||
Assert.Equal(30000, found.FrameRateNumerator);
|
||||
Assert.Equal(1001, found.FrameRateDenominator);
|
||||
Assert.Equal(100, found.ChunkLength);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindIgnoresTheCaseOfThePath()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
AddComplete(cache, source);
|
||||
|
||||
Assert.NotNull(cache.Find(source with { Path = source.Path.ToUpperInvariant() }, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindDistinguishesTheScale()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
AddComplete(cache, source, 50);
|
||||
|
||||
Assert.Null(cache.Find(source, 25));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AChangedSourceIsNotFound()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
AddComplete(cache, source);
|
||||
|
||||
Assert.Null(cache.Find(source with { Length = source.Length + 1 }, 50));
|
||||
Assert.Null(cache.Find(source with { WriteTimeTicks = source.WriteTimeTicks + 1 }, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindTouchesTheLastUse()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var added = AddComplete(cache, source);
|
||||
Thread.Sleep(20);
|
||||
|
||||
var found = cache.Find(source, 50)!;
|
||||
|
||||
Assert.True(found.LastUsedTicks > added.LastUsedTicks);
|
||||
Assert.Equal(found.LastUsedTicks, cache.Snapshot().Single().LastUsedTicks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindDropsAnEntryWhoseDirectoryVanished()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var added = AddComplete(cache, source);
|
||||
Directory.Delete(cache.GetDirectoryPath(added), true);
|
||||
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
Assert.Equal(0, cache.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DifferentScalesOfTheSameSourceCoexist()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
AddComplete(cache, source, 50);
|
||||
AddComplete(cache, source, 25);
|
||||
|
||||
Assert.Equal(2, cache.Count);
|
||||
Assert.Equal(50, cache.Find(source, 50)!.Scale);
|
||||
Assert.Equal(25, cache.Find(source, 25)!.Scale);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddChunkTrimsTheLeastRecentlyUsedEntriesBeyondTheLimit()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
cache.LimitBytes = 750;
|
||||
var first = AddComplete(cache, CreateSource("a.mp4"));
|
||||
Thread.Sleep(20);
|
||||
var second = AddComplete(cache, CreateSource("b.mp4"));
|
||||
Thread.Sleep(20);
|
||||
cache.Find(first.Source, 50);
|
||||
Thread.Sleep(20);
|
||||
|
||||
var third = AddComplete(cache, CreateSource("c.mp4"));
|
||||
|
||||
Assert.Equal(2, cache.Count);
|
||||
Assert.True(Directory.Exists(cache.GetDirectoryPath(first)));
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(second)));
|
||||
Assert.True(Directory.Exists(cache.GetDirectoryPath(third)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEntryLargerThanTheLimitStaysAlone()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
cache.LimitBytes = 50;
|
||||
AddComplete(cache, CreateSource("a.mp4"));
|
||||
|
||||
var big = AddComplete(cache, CreateSource("b.mp4"));
|
||||
|
||||
Assert.Equal(big.Id, cache.Snapshot().Single().Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimAppliesANewLimit()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
AddComplete(cache, CreateSource("a.mp4"));
|
||||
Thread.Sleep(20);
|
||||
AddComplete(cache, CreateSource("b.mp4"));
|
||||
cache.LimitBytes = 450;
|
||||
|
||||
Assert.Equal(1, cache.Trim());
|
||||
Assert.Equal(1, cache.Count);
|
||||
Assert.Equal(0, cache.Trim());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACacheExactlyAtTheLimitIsNotTrimmed()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
AddComplete(cache, CreateSource("a.mp4"));
|
||||
AddComplete(cache, CreateSource("b.mp4"));
|
||||
cache.LimitBytes = 600;
|
||||
|
||||
Assert.Equal(0, cache.Trim());
|
||||
Assert.Equal(2, cache.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrimSkipsAnEntryThatCannotBeDeleted()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var locked = AddComplete(cache, CreateSource("a.mp4"));
|
||||
Thread.Sleep(20);
|
||||
var second = AddComplete(cache, CreateSource("b.mp4"));
|
||||
cache.LimitBytes = 450;
|
||||
|
||||
using (File.Open(cache.GetChunkPath(locked, 0), FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
{
|
||||
Assert.Equal(1, cache.Trim());
|
||||
}
|
||||
|
||||
Assert.True(Directory.Exists(cache.GetDirectoryPath(locked)));
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(second)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveDeletesTheDirectoryAndTheEntry()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var added = AddComplete(cache, source);
|
||||
|
||||
Assert.True(cache.Remove(added.Id));
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(added)));
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
Assert.False(cache.Remove(added.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveKeepsAnEntryWhoseFileIsLocked()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var added = AddComplete(cache, CreateSource());
|
||||
|
||||
using (File.Open(cache.GetChunkPath(added, 0), FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
{
|
||||
Assert.False(cache.Remove(added.Id));
|
||||
}
|
||||
|
||||
Assert.Equal(1, cache.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClearDeletesEverythingIncludingTheSkips()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var skipped = CreateSource("skipped.mp4");
|
||||
cache.AddSkip(skipped, ProxyCacheSkipReason.Transparent);
|
||||
var first = AddComplete(cache, CreateSource("a.mp4"));
|
||||
var second = AddComplete(cache, CreateSource("b.mp4"));
|
||||
|
||||
Assert.Equal(2, cache.Clear());
|
||||
Assert.Equal(0, cache.Count);
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(first)));
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(second)));
|
||||
Assert.False(cache.IsSkipped(skipped));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASkipIsRememberedForTheSameSourceOnly()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
|
||||
cache.AddSkip(source, ProxyCacheSkipReason.Transparent);
|
||||
|
||||
Assert.True(cache.IsSkipped(source));
|
||||
Assert.True(cache.IsSkipped(source with { Path = source.Path.ToUpperInvariant() }));
|
||||
Assert.False(cache.IsSkipped(source with { Length = source.Length + 1 }));
|
||||
Assert.False(cache.IsSkipped(source with { WriteTimeTicks = source.WriteTimeTicks + 1 }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheIndexSurvivesANewInstance()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var skipped = CreateSource("skipped.mp4");
|
||||
var registered = cache.Register(Describe(source));
|
||||
var added = cache.AddChunk(registered.Id, 1, WriteChunk(cache))!;
|
||||
cache.AddSkip(skipped, ProxyCacheSkipReason.Transparent);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
var found = reloaded.Find(source, 50);
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal(added.Id, found.Id);
|
||||
Assert.Equal([1], found.Chunks);
|
||||
Assert.Equal(added.DisplayLeft, found.DisplayLeft);
|
||||
Assert.Equal(added.DurationTicks, found.DurationTicks);
|
||||
Assert.Equal(added.FrameCount, found.FrameCount);
|
||||
Assert.Equal(added.ChunkLength, found.ChunkLength);
|
||||
Assert.Equal(100L, found.FileLength);
|
||||
Assert.True(reloaded.IsSkipped(skipped));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadingDropsEntriesWhoseDirectoryIsGone()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var added = AddComplete(cache, source);
|
||||
Directory.Delete(cache.GetDirectoryPath(added), true);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
Assert.Equal(0, reloaded.Count);
|
||||
Assert.DoesNotContain(added.Id.ToString("N"), File.ReadAllText(reloaded.IndexPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadingReconcilesTheChunksWithTheFiles()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var added = AddComplete(cache, CreateSource());
|
||||
File.Delete(cache.GetChunkPath(added, 1));
|
||||
var stray = Path.Combine(cache.GetDirectoryPath(added), "000007.mp4");
|
||||
File.WriteAllBytes(stray, new byte[10]);
|
||||
var partial = Path.Combine(cache.GetDirectoryPath(added), "000002.tmp");
|
||||
File.WriteAllBytes(partial, new byte[10]);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
var found = reloaded.Get(added.Id)!;
|
||||
Assert.Equal([0, 2], found.Chunks);
|
||||
Assert.Equal(200L, found.FileLength);
|
||||
Assert.False(File.Exists(stray));
|
||||
Assert.False(File.Exists(partial));
|
||||
Assert.Equal([0, 2], CreateCache().Get(added.Id)!.Chunks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadingDeletesLeftoversAndOrphans()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var added = AddComplete(cache, CreateSource());
|
||||
var leftover = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(leftover, new byte[10]);
|
||||
var orphanFile = Path.Combine(cache.DirectoryPath, Guid.NewGuid().ToString("N") + ".mp4");
|
||||
File.WriteAllBytes(orphanFile, new byte[10]);
|
||||
var orphanDirectory = Path.Combine(cache.DirectoryPath, Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(orphanDirectory);
|
||||
File.WriteAllBytes(Path.Combine(orphanDirectory, "000000.mp4"), new byte[10]);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
Assert.Equal(1, reloaded.Count);
|
||||
Assert.True(File.Exists(cache.GetChunkPath(added, 0)));
|
||||
Assert.False(File.Exists(leftover));
|
||||
Assert.False(File.Exists(orphanFile));
|
||||
Assert.False(Directory.Exists(orphanDirectory));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACorruptIndexIsReplacedAndItsFilesAreDiscarded()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var added = AddComplete(cache, CreateSource());
|
||||
File.WriteAllText(cache.IndexPath, "{ not json");
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
Assert.Equal(0, reloaded.Count);
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(added)));
|
||||
Assert.Contains("\"Entries\"", File.ReadAllText(reloaded.IndexPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnIndexWithBrokenRecordsKeepsTheGoodOnes()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
var added = AddComplete(cache, source);
|
||||
var text = File.ReadAllText(cache.IndexPath);
|
||||
text = text.Replace("\"Entries\": [", "\"Entries\": [ null, { \"Id\": \"00000000000000000000000000000000\" }, { \"Id\": \"" + Guid.NewGuid().ToString("N") + "\", \"SourcePath\": \"\" },");
|
||||
File.WriteAllText(cache.IndexPath, text);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
Assert.Equal(added.Id, reloaded.Snapshot().Single().Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnIndexFromTheSingleFileFormatIsDiscarded()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var added = AddComplete(cache, CreateSource());
|
||||
var text = File.ReadAllText(cache.IndexPath).Replace("\"ChunkLength\": 100", "\"ChunkLength\": 0");
|
||||
File.WriteAllText(cache.IndexPath, text);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
Assert.Equal(0, reloaded.Count);
|
||||
Assert.False(Directory.Exists(cache.GetDirectoryPath(added)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnIndexListingChunksOutsideTheLayoutIsRepaired()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var added = AddComplete(cache, CreateSource());
|
||||
var text = File.ReadAllText(cache.IndexPath).Replace("\"Chunks\": [", "\"Chunks\": [ 7, 0, -1,");
|
||||
File.WriteAllText(cache.IndexPath, text);
|
||||
|
||||
var reloaded = CreateCache();
|
||||
|
||||
Assert.Equal([0, 1, 2], reloaded.Get(added.Id)!.Chunks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotsAreCopies()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var source = CreateSource();
|
||||
AddComplete(cache, source);
|
||||
|
||||
cache.Snapshot()[0].Scale = 99;
|
||||
cache.Snapshot()[0].Chunks.Clear();
|
||||
|
||||
Assert.Equal(50, cache.Snapshot()[0].Scale);
|
||||
Assert.Equal(3, cache.Snapshot()[0].Chunks.Count);
|
||||
Assert.NotNull(cache.Find(source, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TemporaryPathsAreUniqueAndInsideTheCacheDirectory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
|
||||
var first = cache.CreateTemporaryPath();
|
||||
var second = cache.CreateTemporaryPath();
|
||||
|
||||
Assert.NotEqual(first, second);
|
||||
Assert.StartsWith(cache.DirectoryPath, first);
|
||||
Assert.EndsWith(".tmp", first);
|
||||
Assert.True(Directory.Exists(cache.DirectoryPath));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
using System.IO;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class ProxyChunkLoaderTests : IDisposable
|
||||
{
|
||||
readonly string root = Path.Combine(Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
readonly GraphicsDevices devices = new();
|
||||
readonly IGraphicsDevicesAndContext context;
|
||||
readonly ProxyCache cache;
|
||||
readonly ProxyGenerationQueue queue;
|
||||
readonly SourceFocus focus = new();
|
||||
readonly List<TestVideoSource> created = [];
|
||||
readonly TaskCompletionSource gate = new();
|
||||
bool refuse;
|
||||
bool hold;
|
||||
bool transparent;
|
||||
|
||||
public ProxyChunkLoaderTests()
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
context = devices.CreateContext();
|
||||
cache = new ProxyCache(Path.Combine(root, "cache"));
|
||||
queue = new ProxyGenerationQueue(cache, Open, () => new ProxyEncodeOptions(50, 30, 10, false), () => ExportPhase.Idle, focus, _ => { }, TestUiThread.Post)
|
||||
{
|
||||
CompletedRetention = TimeSpan.FromMilliseconds(50),
|
||||
FailedRetention = TimeSpan.FromMilliseconds(50),
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
gate.TrySetResult();
|
||||
context.Dispose();
|
||||
devices.Dispose();
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
Task<IProxyEncodeSession> Open(ProxyEncodeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var analysis = new ProxyAnalysis(new ProxyGeometry(960, 540), new DisplayBounds(-960f, -540f, 1920f, 1080f), new FrameRate(30, 1), TimeSpan.FromSeconds(30), 900);
|
||||
return Task.FromResult<IProxyEncodeSession>(new FakeEncodeSession(analysis, (_, _, output, _, _) =>
|
||||
{
|
||||
if (transparent)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.Transparent, "alpha");
|
||||
|
||||
File.WriteAllBytes(output, new byte[64]);
|
||||
return Task.FromResult(64L);
|
||||
}));
|
||||
}
|
||||
|
||||
IVideoFileSource? Factory(IGraphicsDevicesAndContext target, string path)
|
||||
{
|
||||
if (hold)
|
||||
gate.Task.Wait();
|
||||
if (refuse)
|
||||
return null;
|
||||
|
||||
var source = TestVideoSource.Solid(target, 960, 540, 30, 1, 300);
|
||||
created.Add(source);
|
||||
return source;
|
||||
}
|
||||
|
||||
SourceIdentity CreateSource(string name = "source.mp4")
|
||||
{
|
||||
var path = Path.Combine(root, name);
|
||||
File.WriteAllBytes(path, new byte[100]);
|
||||
return SourceIdentity.Of(path)!.Value;
|
||||
}
|
||||
|
||||
ProxyCacheEntry Register(SourceIdentity source, int scale = 50, params int[] chunks)
|
||||
{
|
||||
var entry = cache.Register(new ProxyCacheEntry
|
||||
{
|
||||
SourcePath = source.Path,
|
||||
SourceLength = source.Length,
|
||||
SourceWriteTimeTicks = source.WriteTimeTicks,
|
||||
Scale = scale,
|
||||
ProxyWidth = 960,
|
||||
ProxyHeight = 540,
|
||||
DisplayLeft = -960f,
|
||||
DisplayTop = -540f,
|
||||
DisplayWidth = 1920f,
|
||||
DisplayHeight = 1080f,
|
||||
FrameRateNumerator = 30,
|
||||
FrameRateDenominator = 1,
|
||||
DurationTicks = TimeSpan.FromSeconds(30).Ticks,
|
||||
FrameCount = 900,
|
||||
ChunkLength = 300,
|
||||
});
|
||||
foreach (var chunk in chunks)
|
||||
{
|
||||
var temporary = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(temporary, new byte[64]);
|
||||
entry = cache.AddChunk(entry.Id, chunk, temporary)!;
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
ProxyChunkLoader CreateLoader(SourceIdentity source, ProxyCacheEntry? entry, int scale = 50)
|
||||
=> new(context, source, scale, entry, cache, queue, Factory);
|
||||
|
||||
static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
for (var attempt = 0; attempt < 500 && !condition(); attempt++)
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
Assert.True(condition());
|
||||
}
|
||||
|
||||
static async Task<IReadOnlyList<KeyValuePair<int, OpenedChunk>>> TakeAsync(ProxyChunkLoader loader)
|
||||
{
|
||||
for (var attempt = 0; attempt < 500; attempt++)
|
||||
{
|
||||
var taken = loader.TakeLoaded();
|
||||
if (taken.Count > 0)
|
||||
return taken;
|
||||
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
throw new TimeoutException("nothing was loaded");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARequestedChunkIsOpenedInTheBackgroundOnce()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0, 1);
|
||||
using var loader = CreateLoader(source, entry);
|
||||
|
||||
loader.Request(1);
|
||||
loader.Request(1);
|
||||
var taken = await TakeAsync(loader);
|
||||
|
||||
var single = Assert.Single(taken);
|
||||
Assert.Equal(1, single.Key);
|
||||
Assert.Same(created.Single(), single.Value.Source);
|
||||
Assert.Empty(loader.TakeLoaded());
|
||||
Assert.False(loader.IsLoading);
|
||||
single.Value.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AChunkThatIsNotInTheEntryIsNotRequested()
|
||||
{
|
||||
var source = CreateSource();
|
||||
using var loader = CreateLoader(source, Register(source, 50, 0));
|
||||
|
||||
loader.Request(1);
|
||||
await Task.Delay(50, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Empty(created);
|
||||
Assert.Empty(loader.TakeLoaded());
|
||||
Assert.False(loader.IsLoading);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAnEntryNothingIsAvailable()
|
||||
{
|
||||
var source = CreateSource();
|
||||
using var loader = CreateLoader(source, null);
|
||||
|
||||
loader.Request(0);
|
||||
|
||||
Assert.Null(loader.Entry);
|
||||
Assert.Null(loader.Open(context, 0));
|
||||
Assert.Empty(created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpenReturnsTheChunkSynchronouslyOnTheGivenContext()
|
||||
{
|
||||
var source = CreateSource();
|
||||
using var loader = CreateLoader(source, Register(source, 50, 0));
|
||||
|
||||
var opened = loader.Open(context, 0);
|
||||
|
||||
Assert.NotNull(opened);
|
||||
Assert.Same(created.Single(), opened.Source);
|
||||
Assert.Null(loader.Open(context, 1));
|
||||
opened.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AChunkThatCannotBeOpenedIsForgotten()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0, 1);
|
||||
using var loader = CreateLoader(source, entry);
|
||||
refuse = true;
|
||||
|
||||
Assert.Null(loader.Open(context, 0));
|
||||
|
||||
Assert.Equal([1], cache.Get(entry.Id)!.Chunks);
|
||||
Assert.Equal([1], loader.Entry!.Chunks);
|
||||
Assert.False(File.Exists(cache.GetChunkPath(entry, 0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ABackgroundFailureIsForgottenAsWell()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0, 1);
|
||||
using var loader = CreateLoader(source, entry);
|
||||
refuse = true;
|
||||
|
||||
loader.Request(1);
|
||||
await WaitUntilAsync(() => !loader.IsLoading);
|
||||
|
||||
Assert.Empty(loader.TakeLoaded());
|
||||
Assert.Equal([0], loader.Entry!.Chunks);
|
||||
Assert.Equal([0], cache.Get(entry.Id)!.Chunks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChunksGeneratedLaterBecomeAvailable()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0);
|
||||
using var loader = CreateLoader(source, entry);
|
||||
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal([0, 1, 2], loader.Entry!.Chunks);
|
||||
loader.Request(2);
|
||||
var taken = await TakeAsync(loader);
|
||||
Assert.Equal(2, Assert.Single(taken).Key);
|
||||
taken[0].Value.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnAnnouncementForAnotherScaleOrFileIsIgnored()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var other = CreateSource("other.mp4");
|
||||
Register(source, 25);
|
||||
Register(other, 50);
|
||||
using var loader = CreateLoader(source, null);
|
||||
|
||||
Assert.True(queue.TryEnqueue(source, 25));
|
||||
Assert.True(queue.TryEnqueue(other, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Null(loader.Entry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADiscardedEntryIsForgotten()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0);
|
||||
using var loader = CreateLoader(source, entry);
|
||||
transparent = true;
|
||||
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Null(loader.Entry);
|
||||
Assert.Null(loader.Open(context, 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisposingDropsLoadedChunksAndIgnoresLateAnnouncements()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0, 1);
|
||||
var loader = CreateLoader(source, entry);
|
||||
loader.Request(0);
|
||||
await WaitUntilAsync(() => !loader.IsLoading);
|
||||
|
||||
loader.Dispose();
|
||||
loader.Dispose();
|
||||
|
||||
Assert.True(created.Single().IsDisposed);
|
||||
Assert.Empty(loader.TakeLoaded());
|
||||
loader.Request(1);
|
||||
Assert.False(loader.IsLoading);
|
||||
Assert.Null(loader.Open(context, 1));
|
||||
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
Assert.Equal([0, 1], loader.Entry!.Chunks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALoadThatFinishesAfterDisposeIsDiscarded()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 50, 0);
|
||||
var loader = CreateLoader(source, entry);
|
||||
hold = true;
|
||||
loader.Request(0);
|
||||
await WaitUntilAsync(() => loader.IsLoading);
|
||||
|
||||
loader.Dispose();
|
||||
gate.SetResult();
|
||||
await WaitUntilAsync(() => !loader.IsLoading);
|
||||
|
||||
Assert.True(created.Single().IsDisposed);
|
||||
Assert.Empty(loader.TakeLoaded());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Sources;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class ProxyEncoderTests
|
||||
{
|
||||
const string SoftwareEncoder = FFmpegArguments.SoftwareVideoEncoder;
|
||||
|
||||
[Fact]
|
||||
public async Task EncodesAProxyAtTheRequestedScale()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(1280, 720, 30, 1, 30);
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(640, 360), result.Analysis.Geometry);
|
||||
Assert.Equal(new FrameRate(30, 1), result.Analysis.FrameRate);
|
||||
Assert.Equal(30, result.Analysis.FrameCount);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1), result.Analysis.Duration);
|
||||
Assert.Equal(new FileInfo(workspace.OutputPath).Length, result.FileLength);
|
||||
Assert.Equal("640", await workspace.ReadStreamEntryAsync("width"));
|
||||
Assert.Equal("360", await workspace.ReadStreamEntryAsync("height"));
|
||||
Assert.Equal("yuv420p", await workspace.ReadStreamEntryAsync("pix_fmt"));
|
||||
Assert.Equal("h264", await workspace.ReadStreamEntryAsync("codec_name"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MeasuresTheBoundsAsDirect2DRasterisesThem()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(1281, 721, 30, 1, 2, centering: TestCentering.Exact);
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new DisplayBounds(-641f, -361f, 1282f, 722f), result.Analysis.Display);
|
||||
Assert.Equal(new ProxyGeometry(640, 360), result.Analysis.Geometry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RendersEveryFrameOfTheSourceOnce()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 45);
|
||||
await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("45", await workspace.ReadStreamEntryAsync("nb_frames"));
|
||||
Assert.Equal(46, workspace.Source!.UpdateCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportsProgressInAscendingSteps()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
var reports = new List<double>();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 250);
|
||||
await workspace.EncodeAllAsync(encoder, workspace.Request(50), new SynchronousProgress(reports.Add), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.InRange(reports.Count, 100, 101);
|
||||
Assert.Equal(1d, reports[^1]);
|
||||
Assert.Equal(reports.OrderBy(x => x), reports);
|
||||
Assert.Equal(reports.Distinct(), reports);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PreservesAnIntegerFrameRate()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 60);
|
||||
await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("30/1", await workspace.ReadStreamEntryAsync("r_frame_rate"));
|
||||
Assert.Equal("60", await workspace.ReadStreamEntryAsync("nb_frames"));
|
||||
Assert.Equal(workspace.Source!.Duration.TotalSeconds, await workspace.ReadDurationSecondsAsync(), 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PreservesTheNtscFrameRateExactly()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30000, 1001, 120);
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new FrameRate(30000, 1001), result.Analysis.FrameRate);
|
||||
Assert.Equal("30000/1001", await workspace.ReadStreamEntryAsync("r_frame_rate"));
|
||||
Assert.Equal("120", await workspace.ReadStreamEntryAsync("nb_frames"));
|
||||
Assert.Equal(workspace.Source!.Duration.TotalSeconds, await workspace.ReadDurationSecondsAsync(), 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PreservesTheSourceColour()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 10, blue: 32, green: 160, red: 200);
|
||||
await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
var (blue, green, red) = await workspace.ReadPixelAsync(320, 180, 160, 90);
|
||||
|
||||
Assert.InRange(blue, 32 - 8, 32 + 8);
|
||||
Assert.InRange(green, 160 - 8, 160 + 8);
|
||||
Assert.InRange(red, 200 - 8, 200 + 8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task KeepsTheLeftAndRightHalvesWhereTheyBelong()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 4, pixelOf: (x, _) => x < 320 ? ((byte)220, (byte)20, (byte)20, byte.MaxValue) : ((byte)20, (byte)20, (byte)220, byte.MaxValue));
|
||||
await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
var left = await workspace.ReadPixelAsync(320, 180, 40, 90);
|
||||
var right = await workspace.ReadPixelAsync(320, 180, 280, 90);
|
||||
|
||||
Assert.True(left.Blue > 180 && left.Red < 60, $"left={left}");
|
||||
Assert.True(right.Red > 180 && right.Blue < 60, $"right={right}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(TestCentering.Floor)]
|
||||
[InlineData(TestCentering.Exact)]
|
||||
public async Task AlignsAnOddSizedSourceSymmetrically(TestCentering centering)
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(641, 361, 30, 1, 2, centering: centering,
|
||||
pixelOf: (x, y) => x == 0 || y == 0 || x == 640 || y == 360 ? ((byte)255, (byte)255, (byte)255, byte.MaxValue) : ((byte)0, (byte)0, (byte)0, byte.MaxValue));
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(320, 180), result.Analysis.Geometry);
|
||||
var leftEdge = await workspace.ReadPixelAsync(320, 180, 0, 90);
|
||||
var rightEdge = await workspace.ReadPixelAsync(320, 180, 319, 90);
|
||||
var topEdge = await workspace.ReadPixelAsync(320, 180, 160, 0);
|
||||
var bottomEdge = await workspace.ReadPixelAsync(320, 180, 160, 179);
|
||||
var centre = await workspace.ReadPixelAsync(320, 180, 160, 90);
|
||||
|
||||
Assert.True(Math.Abs(leftEdge.Green - rightEdge.Green) <= 24, $"left={leftEdge} right={rightEdge} top={topEdge} bottom={bottomEdge} centre={centre}");
|
||||
Assert.True(Math.Abs(topEdge.Green - bottomEdge.Green) <= 24, $"left={leftEdge} right={rightEdge} top={topEdge} bottom={bottomEdge} centre={centre}");
|
||||
Assert.True(leftEdge.Green > 60, $"leftEdge={leftEdge}");
|
||||
Assert.True(centre.Green < 24, $"centre={centre}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APortraitSourceProducesAPortraitProxy()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(1080, 1920, 30, 1, 10);
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(540, 960), result.Analysis.Geometry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATransparentSourceIsRefusedAndLeavesNoFile()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 10,
|
||||
pixelOf: (x, y) => x is >= 300 and < 340 && y is >= 160 and < 200 ? ((byte)0, (byte)0, (byte)0, (byte)0) : ((byte)64, (byte)64, (byte)64, byte.MaxValue));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<ProxyEncodeException>(() => workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken));
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.Transparent, exception.Failure);
|
||||
Assert.False(File.Exists(workspace.OutputPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASoftEdgeIsNotMistakenForTransparency()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(641, 361, 30, 1, 2, centering: TestCentering.Exact);
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(2, result.Analysis.FrameCount);
|
||||
Assert.True(File.Exists(workspace.OutputPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnAlreadyCancelledTokenLeavesNoFile()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
await cancellation.CancelAsync();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 10);
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => workspace.EncodeAllAsync(encoder, workspace.Request(50), null, cancellation.Token));
|
||||
Assert.False(File.Exists(workspace.OutputPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancellationDuringTheEncodeLeavesNoFile()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
var encoder = workspace.CreateEncoder(1920, 1080, 30, 1, 3000);
|
||||
var progress = new SynchronousProgress(fraction =>
|
||||
{
|
||||
if (fraction >= 0.05d)
|
||||
cancellation.Cancel();
|
||||
});
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => workspace.EncodeAllAsync(encoder, workspace.Request(50), progress, cancellation.Token));
|
||||
Assert.False(File.Exists(workspace.OutputPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASourceNobodyCanOpenIsReported()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = new ProxyEncoder(Ymm4TestEnvironment.Executables, static (_, _) => null);
|
||||
|
||||
var exception = await Assert.ThrowsAsync<ProxyEncodeException>(() => workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken));
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.SourceUnavailable, exception.Failure);
|
||||
Assert.False(File.Exists(workspace.OutputPath));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASourceWithoutFramesIsReported()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 0);
|
||||
|
||||
var exception = await Assert.ThrowsAsync<ProxyEncodeException>(() => workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken));
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.NoFrames, exception.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARelativeSourcePathIsRejected()
|
||||
{
|
||||
using var workspace = new Workspace();
|
||||
var encoder = new ProxyEncoder(Ymm4TestEnvironment.Executables, static (_, _) => null);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => encoder.OpenAsync(workspace.Request(50) with { SourcePath = "relative.mp4" }, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnOutputOutsideTheWorkingDirectoryIsRejected()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 10);
|
||||
using var session = await encoder.OpenAsync(workspace.Request(50), TestContext.Current.CancellationToken);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => session.EncodeAsync(0, 10, Path.Combine(Path.GetTempPath(), "escaped.mp4"), null, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1, 5)]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(5, 6)]
|
||||
public async Task AFrameRangeOutsideTheSourceIsRejected(int firstFrame, int frameCount)
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 10);
|
||||
using var session = await encoder.OpenAsync(workspace.Request(50), TestContext.Current.CancellationToken);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => session.EncodeAsync(firstFrame, frameCount, workspace.OutputPath, null, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADisposedSessionRefusesToEncode()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 10);
|
||||
var session = await encoder.OpenAsync(workspace.Request(50), TestContext.Current.CancellationToken);
|
||||
session.Dispose();
|
||||
|
||||
await Assert.ThrowsAsync<ObjectDisposedException>(() => session.EncodeAsync(0, 10, workspace.OutputPath, null, TestContext.Current.CancellationToken));
|
||||
Assert.True(workspace.Source!.IsDisposed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASessionEncodesTheRequestedFrameRangeOnly()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 30,
|
||||
framePixelOf: (frame, _, _) => ((byte)(frame * 8), (byte)(frame * 8), (byte)(frame * 8), byte.MaxValue));
|
||||
using var session = await encoder.OpenAsync(workspace.Request(50), TestContext.Current.CancellationToken);
|
||||
workspace.Source!.RequestedFrames.Clear();
|
||||
|
||||
var length = await session.EncodeAsync(10, 5, workspace.OutputPath, null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new FileInfo(workspace.OutputPath).Length, length);
|
||||
Assert.Equal("5", await workspace.ReadStreamEntryAsync("nb_frames"));
|
||||
Assert.Equal([10, 11, 12, 13, 14], workspace.Source.RequestedFrames);
|
||||
var (blue, _, _) = await workspace.ReadPixelAsync(320, 180, 160, 90);
|
||||
Assert.InRange(blue, 80 - 8, 80 + 8);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASessionEncodesSeveralChunksFromOneSource()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
var encoder = workspace.CreateEncoder(640, 360, 30, 1, 20);
|
||||
using var session = await encoder.OpenAsync(workspace.Request(50), TestContext.Current.CancellationToken);
|
||||
var second = Path.Combine(workspace.Path, "second.mp4");
|
||||
|
||||
await session.EncodeAsync(0, 10, workspace.OutputPath, null, TestContext.Current.CancellationToken);
|
||||
await session.EncodeAsync(10, 10, second, null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("10", await workspace.ReadStreamEntryAsync("nb_frames"));
|
||||
Assert.True(new FileInfo(second).Length > 0);
|
||||
Assert.Equal(21, workspace.Source!.UpdateCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MissingExecutablesAreReported()
|
||||
{
|
||||
using var workspace = new Workspace();
|
||||
var encoder = new ProxyEncoder(FFmpegExecutables.Unavailable, static (_, _) => null);
|
||||
|
||||
var exception = await Assert.ThrowsAsync<ProxyEncodeException>(() => workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken));
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.FFmpegUnavailable, exception.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFullHdSourceOfRealisticLengthEncodes()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = workspace.CreateEncoder(1920, 1080, 30, 1, 300);
|
||||
var result = await workspace.EncodeAllAsync(encoder, workspace.Request(50), null, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(960, 540), result.Analysis.Geometry);
|
||||
Assert.Equal("300", await workspace.ReadStreamEntryAsync("nb_frames"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncKillsTheProcessPromptlyOnCancellation()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(750));
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => FFmpegProcessRunner.RunAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath,
|
||||
static arguments =>
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-nostdin");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("lavfi");
|
||||
arguments.Add("-i");
|
||||
arguments.Add("testsrc2=size=1920x1080:rate=30:duration=600");
|
||||
arguments.Add("-c:v");
|
||||
arguments.Add(SoftwareEncoder);
|
||||
arguments.Add("-f");
|
||||
arguments.Add("null");
|
||||
arguments.Add("-");
|
||||
},
|
||||
workspace.Path,
|
||||
null,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
cancellation.Token));
|
||||
|
||||
stopwatch.Stop();
|
||||
Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(30), $"Cancellation took {stopwatch.Elapsed}.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncCapturesDiagnosticsOfAFailure()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var result = await FFmpegProcessRunner.RunAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath,
|
||||
static arguments =>
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-nostdin");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-i");
|
||||
arguments.Add("nonexistent-input-file.mp4");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("null");
|
||||
arguments.Add("-");
|
||||
},
|
||||
workspace.Path,
|
||||
null,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.NotEqual(string.Empty, result.FirstDiagnosticLine(200));
|
||||
Assert.DoesNotContain('\r', result.Diagnostics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncDecodesNonAsciiDiagnosticsAsUtf8()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var broken = Path.Combine(workspace.Path, "壊れた動画ファイル.mp4");
|
||||
await File.WriteAllTextAsync(broken, "not a video", TestContext.Current.CancellationToken);
|
||||
|
||||
var result = await FFmpegProcessRunner.RunAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath,
|
||||
arguments =>
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-nostdin");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-i");
|
||||
arguments.Add(broken);
|
||||
arguments.Add("-f");
|
||||
arguments.Add("null");
|
||||
arguments.Add("-");
|
||||
},
|
||||
workspace.Path,
|
||||
null,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Contains("壊れた動画ファイル.mp4", result.Diagnostics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncWrapsAnIoFailureOfTheInputWriterWithTheDiagnostics()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var failure = await Assert.ThrowsAsync<InvalidOperationException>(() => RunRawInput(workspace, static (_, _) => throw new IOException("frame source exploded")));
|
||||
|
||||
Assert.IsType<IOException>(failure.InnerException);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncRethrowsOtherFailuresOfTheInputWriterUnchanged()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var failure = await Assert.ThrowsAsync<ProxyEncodeException>(() => RunRawInput(workspace, static (_, _) => throw new ProxyEncodeException(ProxyEncodeFailure.Transparent, "transparent")));
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.Transparent, failure.Failure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncReportsAMissingExecutable()
|
||||
{
|
||||
using var workspace = new Workspace();
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => FFmpegProcessRunner.RunAsync(
|
||||
Path.Combine(workspace.Path, "missing-ffmpeg.exe"),
|
||||
static arguments => arguments.Add("-version"),
|
||||
workspace.Path,
|
||||
null,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsyncWithHardwareDisabledSelectsTheSoftwareEncoder()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = await FFmpegEncoderSelector.ResolveAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath, false, 960, 540, workspace.Path, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(SoftwareEncoder, encoder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAsyncWithHardwareEnabledSelectsAnEncoderThatRuns()
|
||||
{
|
||||
Ymm4TestEnvironment.Require();
|
||||
using var workspace = new Workspace();
|
||||
|
||||
var encoder = await FFmpegEncoderSelector.ResolveAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath, true, 320, 240, workspace.Path, TestContext.Current.CancellationToken);
|
||||
|
||||
string[] permitted = [SoftwareEncoder, .. FFmpegEncoderCandidates.Hardware264.ToArray()];
|
||||
Assert.Contains(encoder, permitted);
|
||||
|
||||
var repeated = await FFmpegEncoderSelector.ResolveAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath, true, 320, 240, workspace.Path, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(encoder, repeated);
|
||||
}
|
||||
|
||||
static Task<FFmpegProcessResult> RunRawInput(Workspace workspace, FFmpegInputWriter writer)
|
||||
=> FFmpegProcessRunner.RunAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath,
|
||||
static arguments =>
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("rawvideo");
|
||||
arguments.Add("-pix_fmt");
|
||||
arguments.Add("bgra");
|
||||
arguments.Add("-s");
|
||||
arguments.Add("32x32");
|
||||
arguments.Add("-r");
|
||||
arguments.Add("30/1");
|
||||
arguments.Add("-i");
|
||||
arguments.Add("-");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("null");
|
||||
arguments.Add("-");
|
||||
},
|
||||
workspace.Path,
|
||||
writer,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
sealed class SynchronousProgress(Action<double> report) : IProgress<double>
|
||||
{
|
||||
public void Report(double value) => report(value);
|
||||
}
|
||||
|
||||
sealed class Workspace : IDisposable
|
||||
{
|
||||
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
|
||||
public string SourcePath => System.IO.Path.Combine(Path, "source.mp4");
|
||||
|
||||
public string OutputPath => System.IO.Path.Combine(Path, "proxy.mp4");
|
||||
|
||||
public TestVideoSource? Source { get; private set; }
|
||||
|
||||
public Workspace() => Directory.CreateDirectory(Path);
|
||||
|
||||
public ProxyEncodeRequest Request(int scale) => new(SourcePath, Path, scale, 50, 30, false);
|
||||
|
||||
public async Task<(ProxyAnalysis Analysis, long FileLength)> EncodeAllAsync(ProxyEncoder encoder, ProxyEncodeRequest request, IProgress<double>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
using var session = await encoder.OpenAsync(request, cancellationToken);
|
||||
var length = await session.EncodeAsync(0, session.Analysis.FrameCount, OutputPath, progress, cancellationToken);
|
||||
return (session.Analysis, length);
|
||||
}
|
||||
|
||||
public ProxyEncoder CreateEncoder(
|
||||
int width,
|
||||
int height,
|
||||
int frameRateNumerator,
|
||||
int frameRateDenominator,
|
||||
int frameCount,
|
||||
byte blue = 64,
|
||||
byte green = 64,
|
||||
byte red = 64,
|
||||
TestCentering centering = TestCentering.Floor,
|
||||
Func<int, int, (byte Blue, byte Green, byte Red, byte Alpha)>? pixelOf = null,
|
||||
Func<int, int, int, (byte Blue, byte Green, byte Red, byte Alpha)>? framePixelOf = null)
|
||||
{
|
||||
var pixel = pixelOf ?? ((_, _) => (blue, green, red, byte.MaxValue));
|
||||
return new ProxyEncoder(Ymm4TestEnvironment.Executables, (devices, _) =>
|
||||
{
|
||||
var source = new TestVideoSource(devices, width, height, frameRateNumerator, frameRateDenominator, frameCount, pixel, centering, framePixelOf);
|
||||
Source = source;
|
||||
return source;
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<string> ReadStreamEntryAsync(string entry)
|
||||
{
|
||||
var values = await ProbeAsync("stream=" + entry);
|
||||
return values.Length > 0 ? values[0] : string.Empty;
|
||||
}
|
||||
|
||||
public async Task<double> ReadDurationSecondsAsync()
|
||||
{
|
||||
var values = await ProbeAsync("format=duration");
|
||||
return values.Length > 0 ? double.Parse(values[0], CultureInfo.InvariantCulture) : 0d;
|
||||
}
|
||||
|
||||
public async Task<(byte Blue, byte Green, byte Red)> ReadPixelAsync(int width, int height, int x, int y)
|
||||
{
|
||||
var rawPath = System.IO.Path.Combine(Path, "frame.raw");
|
||||
await RunFFmpegAsync(arguments =>
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-nostdin");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-y");
|
||||
arguments.Add("-i");
|
||||
arguments.Add(OutputPath);
|
||||
arguments.Add("-frames:v");
|
||||
arguments.Add("1");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("rawvideo");
|
||||
arguments.Add("-pix_fmt");
|
||||
arguments.Add("bgra");
|
||||
arguments.Add(rawPath);
|
||||
});
|
||||
|
||||
var bytes = await File.ReadAllBytesAsync(rawPath, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(width * height * 4, bytes.Length);
|
||||
var offset = (y * width + x) * 4;
|
||||
return (bytes[offset], bytes[offset + 1], bytes[offset + 2]);
|
||||
}
|
||||
|
||||
async Task<string[]> ProbeAsync(string showEntries)
|
||||
{
|
||||
var startInfo = new ProcessStartInfo(Ymm4TestEnvironment.FFprobePath)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardOutput = true,
|
||||
WorkingDirectory = Path,
|
||||
};
|
||||
foreach (var argument in new[] { "-hide_banner", "-loglevel", "error", "-select_streams", "v:0", "-show_entries", showEntries, "-of", "csv=p=0", "-i", OutputPath })
|
||||
startInfo.ArgumentList.Add(argument);
|
||||
|
||||
using var process = Process.Start(startInfo)!;
|
||||
var output = await process.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(0, process.ExitCode);
|
||||
return output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
}
|
||||
|
||||
async Task RunFFmpegAsync(Action<Collection<string>> argumentWriter)
|
||||
{
|
||||
var result = await FFmpegProcessRunner.RunAsync(
|
||||
Ymm4TestEnvironment.FFmpegPath,
|
||||
argumentWriter,
|
||||
Path,
|
||||
null,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess, result.Diagnostics);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(Path))
|
||||
Directory.Delete(Path, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<AssemblyName>ProxyForge.Tests</AssemblyName>
|
||||
<RootNamespace>ProxyForge.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="10.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.10.0" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="xunit.v3" Version="3.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ProxyForge\ProxyForge.csproj" SetConfiguration="Configuration=$(Configuration)">
|
||||
<AdditionalProperties Condition="'$(BuildingSolutionFile)' != 'true'">SkipPluginDeploy=true</AdditionalProperties>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyMetadata Include="Ymm4Directory" Value="$(YMM4DirPath)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Mathematics">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Controls">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Plugin">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,124 @@
|
||||
using ProxyForge.Cache;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class ProxyForgeSettingsTests
|
||||
{
|
||||
[Fact]
|
||||
public void TheDefaultsMatchTheDocumentedBehaviour()
|
||||
{
|
||||
var settings = new ProxyForgeSettings();
|
||||
|
||||
Assert.True(settings.IsEnabled);
|
||||
Assert.True(settings.GeneratesAutomatically);
|
||||
Assert.Equal(50, settings.Scale);
|
||||
Assert.Equal(100, settings.MinimumFileSizeMegabytes);
|
||||
Assert.Equal(50, settings.BitrateScale);
|
||||
Assert.Equal(30, settings.KeyFrameInterval);
|
||||
Assert.Equal(10, settings.ChunkSeconds);
|
||||
Assert.True(settings.UsesHardwareEncoder);
|
||||
Assert.Equal(10, settings.CacheLimitGigabytes);
|
||||
Assert.True(settings.ShowsProgressWindow);
|
||||
Assert.Equal(SettingsCategory.VideoFileSource, settings.Category);
|
||||
Assert.Equal("ProxyForge", settings.Name);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(9, 10)]
|
||||
[InlineData(10, 10)]
|
||||
[InlineData(75, 75)]
|
||||
[InlineData(100, 100)]
|
||||
[InlineData(101, 100)]
|
||||
public void TheScaleIsClamped(int value, int expected)
|
||||
{
|
||||
var settings = new ProxyForgeSettings { Scale = value };
|
||||
|
||||
Assert.Equal(expected, settings.Scale);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(1, 1)]
|
||||
[InlineData(100_000, 100_000)]
|
||||
[InlineData(100_001, 100_000)]
|
||||
public void TheMinimumFileSizeIsClamped(int value, int expected)
|
||||
{
|
||||
var settings = new ProxyForgeSettings { MinimumFileSizeMegabytes = value };
|
||||
|
||||
Assert.Equal(expected, settings.MinimumFileSizeMegabytes);
|
||||
Assert.Equal(expected * 1024L * 1024L, settings.MinimumFileSizeBytes);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(200, 200)]
|
||||
[InlineData(201, 200)]
|
||||
public void TheBitrateScaleIsClamped(int value, int expected)
|
||||
{
|
||||
var settings = new ProxyForgeSettings { BitrateScale = value };
|
||||
|
||||
Assert.Equal(expected, settings.BitrateScale);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(300, 300)]
|
||||
[InlineData(301, 300)]
|
||||
public void TheKeyFrameIntervalIsClamped(int value, int expected)
|
||||
{
|
||||
var settings = new ProxyForgeSettings { KeyFrameInterval = value };
|
||||
|
||||
Assert.Equal(expected, settings.KeyFrameInterval);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(10, 10)]
|
||||
[InlineData(120, 120)]
|
||||
[InlineData(121, 120)]
|
||||
public void TheChunkLengthIsClamped(int value, int expected)
|
||||
{
|
||||
var settings = new ProxyForgeSettings { ChunkSeconds = value };
|
||||
|
||||
Assert.Equal(expected, settings.ChunkSeconds);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(7, 7)]
|
||||
[InlineData(1024, 1024)]
|
||||
[InlineData(1025, 1024)]
|
||||
public void TheCacheLimitIsClamped(int value, int expected)
|
||||
{
|
||||
var settings = new ProxyForgeSettings { CacheLimitGigabytes = value };
|
||||
|
||||
Assert.Equal(expected, settings.CacheLimitGigabytes);
|
||||
Assert.Equal(expected * 1024L * 1024L * 1024L, ProxyCache.Shared.LimitBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAppliesTheCacheLimit()
|
||||
{
|
||||
var settings = new ProxyForgeSettings { CacheLimitGigabytes = 3 };
|
||||
ProxyCache.Shared.LimitBytes = 1;
|
||||
|
||||
settings.Initialize();
|
||||
|
||||
Assert.Equal(3L * 1024L * 1024L * 1024L, ProxyCache.Shared.LimitBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingAValueRaisesPropertyChanged()
|
||||
{
|
||||
var settings = new ProxyForgeSettings();
|
||||
var raised = new List<string?>();
|
||||
settings.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
|
||||
|
||||
settings.Scale = 60;
|
||||
settings.Scale = 60;
|
||||
settings.IsEnabled = false;
|
||||
|
||||
Assert.Equal([nameof(ProxyForgeSettings.Scale), nameof(ProxyForgeSettings.IsEnabled)], raised);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using ProxyForge.Encoding;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class ProxyFrameRendererTests
|
||||
{
|
||||
static (byte Blue, byte Green, byte Red, byte Alpha) Bgra(int blue, int green, int red, int alpha)
|
||||
=> ((byte)blue, (byte)green, (byte)red, (byte)alpha);
|
||||
|
||||
static (byte Blue, byte Green, byte Red, byte Alpha) Pixel(ReadOnlySpan<byte> frame, int width, int x, int y)
|
||||
{
|
||||
var offset = (y * width + x) * 4;
|
||||
return (frame[offset], frame[offset + 1], frame[offset + 2], frame[offset + 3]);
|
||||
}
|
||||
|
||||
static byte[] Render(int width, int height, int scale, TestCentering centering, Func<int, int, (byte Blue, byte Green, byte Red, byte Alpha)> pixelOf, out ProxyGeometry geometry, out DisplayBounds display)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
context.DeviceContext.SetDpi(ProxyFrameRenderer.ReferenceDpi, ProxyFrameRenderer.ReferenceDpi);
|
||||
using var source = new TestVideoSource(context, width, height, 30, 1, 1, pixelOf, centering);
|
||||
source.Update(TimeSpan.Zero);
|
||||
|
||||
display = DisplayBounds.Measure(context.DeviceContext, source.Output);
|
||||
geometry = ProxyGeometryCalculator.Calculate(display.PixelWidth, display.PixelHeight, scale);
|
||||
using var renderer = new ProxyFrameRenderer(context, source.Output, display, geometry);
|
||||
var frame = new byte[renderer.FrameByteCount];
|
||||
renderer.Render(frame);
|
||||
return frame;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASolidSourceIsCopiedExactly()
|
||||
{
|
||||
var frame = Render(64, 48, 100, TestCentering.Floor, (_, _) => Bgra(32, 160, 200, 255), out var geometry, out _);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(64, 48), geometry);
|
||||
for (var y = 0; y < 48; y++)
|
||||
{
|
||||
for (var x = 0; x < 64; x++)
|
||||
Assert.Equal(((byte)32, (byte)160, (byte)200, (byte)255), Pixel(frame, 64, x, y));
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(TestCentering.Floor)]
|
||||
[InlineData(TestCentering.Exact)]
|
||||
public void AFullScaleCopyOfACheckerboardIsPixelExact(TestCentering centering)
|
||||
{
|
||||
var frame = Render(64, 32, 100, centering, (x, y) => (x + y) % 2 == 0 ? Bgra(255, 255, 255, 255) : Bgra(0, 0, 0, 255), out var geometry, out _);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(64, 32), geometry);
|
||||
for (var y = 0; y < 32; y++)
|
||||
{
|
||||
for (var x = 0; x < 64; x++)
|
||||
{
|
||||
var expected = (x + y) % 2 == 0 ? (byte)255 : (byte)0;
|
||||
Assert.Equal((expected, expected, expected, (byte)255), Pixel(frame, 64, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static double Centroid(ReadOnlySpan<byte> frame, int width, int y)
|
||||
{
|
||||
var weighted = 0d;
|
||||
var total = 0d;
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
double value = Pixel(frame, width, x, y).Green;
|
||||
weighted += (x + 0.5d) * value;
|
||||
total += value;
|
||||
}
|
||||
|
||||
return weighted / total;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(100, 640, 360, TestCentering.Floor, 0)]
|
||||
[InlineData(50, 640, 360, TestCentering.Floor, 0)]
|
||||
[InlineData(50, 641, 361, TestCentering.Floor, 0)]
|
||||
[InlineData(50, 641, 361, TestCentering.Exact, 0)]
|
||||
[InlineData(50, 641, 361, TestCentering.Floor, 300)]
|
||||
[InlineData(50, 641, 361, TestCentering.Floor, 617)]
|
||||
[InlineData(25, 641, 361, TestCentering.Floor, 0)]
|
||||
[InlineData(25, 641, 361, TestCentering.Floor, 617)]
|
||||
[InlineData(10, 641, 361, TestCentering.Floor, 0)]
|
||||
[InlineData(10, 641, 361, TestCentering.Exact, 617)]
|
||||
[InlineData(10, 1919, 1079, TestCentering.Exact, 1895)]
|
||||
[InlineData(33, 1919, 1079, TestCentering.Floor, 900)]
|
||||
public void ABandLandsWhereTheBoundsMapIt(int scale, int width, int height, TestCentering centering, int bandStart)
|
||||
{
|
||||
const int bandWidth = 24;
|
||||
var frame = Render(width, height, scale, centering,
|
||||
(x, _) => x >= bandStart && x < bandStart + bandWidth ? Bgra(255, 255, 255, 255) : Bgra(0, 0, 0, 255), out var geometry, out var display);
|
||||
|
||||
var expected = (bandStart + bandWidth / 2d + (centering == TestCentering.Floor ? MathF.Floor(-width / 2f) : -width / 2f) - display.Left) * geometry.Width / display.Width;
|
||||
var centroid = Centroid(frame, geometry.Width, geometry.Height / 2);
|
||||
|
||||
Assert.True(Math.Abs(centroid - expected) <= 0.2d, $"centroid={centroid} expected={expected} display={display} geometry={geometry}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(50, 641, 361, TestCentering.Floor)]
|
||||
[InlineData(50, 641, 361, TestCentering.Exact)]
|
||||
[InlineData(50, 640, 360, TestCentering.Floor)]
|
||||
[InlineData(25, 640, 360, TestCentering.Floor)]
|
||||
[InlineData(10, 1920, 1080, TestCentering.Floor)]
|
||||
public void AScaledBorderIsSymmetric(int scale, int width, int height, TestCentering centering)
|
||||
{
|
||||
var frame = Render(width, height, scale, centering,
|
||||
(x, y) => x == 0 || y == 0 || x == width - 1 || y == height - 1 ? Bgra(255, 255, 255, 255) : Bgra(0, 0, 0, 255), out var geometry, out _);
|
||||
|
||||
var middleY = geometry.Height / 2;
|
||||
var middleX = geometry.Width / 2;
|
||||
var left = Pixel(frame, geometry.Width, 0, middleY).Green;
|
||||
var right = Pixel(frame, geometry.Width, geometry.Width - 1, middleY).Green;
|
||||
var top = Pixel(frame, geometry.Width, middleX, 0).Green;
|
||||
var bottom = Pixel(frame, geometry.Width, middleX, geometry.Height - 1).Green;
|
||||
|
||||
Assert.True(Math.Abs(left - right) <= 4, $"left={left} right={right}");
|
||||
Assert.True(Math.Abs(top - bottom) <= 4, $"top={top} bottom={bottom}");
|
||||
Assert.True(left >= 255 * scale / 100 / 2, $"left={left}");
|
||||
Assert.Equal((byte)0, Pixel(frame, geometry.Width, middleX, middleY).Green);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(100, 1280, 720, 0)]
|
||||
[InlineData(100, 1281, 721, 0)]
|
||||
[InlineData(50, 641, 361, 1)]
|
||||
[InlineData(50, 640, 360, 1)]
|
||||
[InlineData(25, 1920, 1080, 2)]
|
||||
[InlineData(10, 1920, 1080, 3)]
|
||||
[InlineData(50, 100, 31, 0)]
|
||||
[InlineData(50, 31, 100, 0)]
|
||||
public void HalvesUntilTheRemainingScaleIsAtLeastAHalf(int scale, int width, int height, int expectedHalvings)
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = TestVideoSource.Solid(context, width, height, 30, 1, 1);
|
||||
source.Update(TimeSpan.Zero);
|
||||
var display = DisplayBounds.Measure(context.DeviceContext, source.Output);
|
||||
var geometry = ProxyGeometryCalculator.Calculate(display.PixelWidth, display.PixelHeight, scale);
|
||||
using var renderer = new ProxyFrameRenderer(context, source.Output, display, geometry);
|
||||
|
||||
Assert.Equal(expectedHalvings, renderer.HalvingCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheWholeFrameIsOpaqueForAnOpaqueSource()
|
||||
{
|
||||
var frame = Render(641, 361, 50, TestCentering.Exact, (_, _) => Bgra(10, 20, 30, 255), out var geometry, out _);
|
||||
|
||||
Assert.True(FrameAlpha.IsOpaque(frame, geometry.Width, geometry.Height));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATransparentHoleIsDetected()
|
||||
{
|
||||
var frame = Render(640, 360, 50, TestCentering.Floor,
|
||||
(x, y) => x is >= 300 and < 340 && y is >= 160 and < 200 ? Bgra(0, 0, 0, 0) : Bgra(10, 20, 30, 255), out var geometry, out _);
|
||||
|
||||
Assert.False(FrameAlpha.IsOpaque(frame, geometry.Width, geometry.Height));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RenderingAfterDisposeIsRefused()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = TestVideoSource.Solid(context, 16, 16, 30, 1, 1);
|
||||
source.Update(TimeSpan.Zero);
|
||||
var display = DisplayBounds.Measure(context.DeviceContext, source.Output);
|
||||
var renderer = new ProxyFrameRenderer(context, source.Output, display, new ProxyGeometry(16, 16));
|
||||
renderer.Dispose();
|
||||
|
||||
Assert.Throws<ObjectDisposedException>(() => renderer.Render(new byte[renderer.FrameByteCount]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATooSmallBufferIsRefused()
|
||||
{
|
||||
using var devices = new GraphicsDevices();
|
||||
using var context = devices.CreateContext();
|
||||
using var source = TestVideoSource.Solid(context, 16, 16, 30, 1, 1);
|
||||
source.Update(TimeSpan.Zero);
|
||||
var display = DisplayBounds.Measure(context.DeviceContext, source.Output);
|
||||
using var renderer = new ProxyFrameRenderer(context, source.Output, display, new ProxyGeometry(16, 16));
|
||||
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => renderer.Render(new byte[renderer.FrameByteCount - 1]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
using System.IO;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class ProxyGenerationQueueTests : IDisposable
|
||||
{
|
||||
readonly string root = Path.Combine(Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
readonly ProxyCache cache;
|
||||
readonly List<Exception> reported = [];
|
||||
readonly SourceFocus focus = new();
|
||||
ExportPhase phase = ExportPhase.Idle;
|
||||
ProxyEncodeOptions options = new(50, 30, 10, false);
|
||||
|
||||
public ProxyGenerationQueueTests()
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
cache = new ProxyCache(Path.Combine(root, "cache"));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
SourceIdentity CreateSource(string name = "source.mp4")
|
||||
{
|
||||
var path = Path.Combine(root, name);
|
||||
File.WriteAllBytes(path, new byte[100]);
|
||||
return SourceIdentity.Of(path)!.Value;
|
||||
}
|
||||
|
||||
ProxyGenerationQueue CreateQueue(ProxyEncodeSessionFactory open)
|
||||
=> new(cache, open, () => options, () => phase, focus, reported.Add, TestUiThread.Post)
|
||||
{
|
||||
CompletedRetention = TimeSpan.FromMilliseconds(50),
|
||||
CancelledRetention = TimeSpan.FromMilliseconds(50),
|
||||
FailedRetention = TimeSpan.FromMilliseconds(50),
|
||||
};
|
||||
|
||||
ProxyGenerationQueue CreateQueue(Func<int, int, string, IProgress<double>?, CancellationToken, Task<long>> encode, int frameCount = 300, Action<ProxyEncodeRequest>? onOpen = null)
|
||||
=> CreateQueue((request, _) =>
|
||||
{
|
||||
onOpen?.Invoke(request);
|
||||
return Task.FromResult<IProxyEncodeSession>(new FakeEncodeSession(Analysis(frameCount), encode));
|
||||
});
|
||||
|
||||
static ProxyAnalysis Analysis(int frameCount = 300)
|
||||
=> new(new ProxyGeometry(960, 540), new DisplayBounds(-960f, -540f, 1920f, 1080f), new FrameRate(30, 1), TimeSpan.FromTicks(frameCount * TimeSpan.TicksPerSecond / 30), frameCount);
|
||||
|
||||
static Task<long> WriteChunk(string outputPath, int length = 100)
|
||||
{
|
||||
File.WriteAllBytes(outputPath, new byte[length]);
|
||||
return Task.FromResult((long)length);
|
||||
}
|
||||
|
||||
static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
for (var attempt = 0; attempt < 200 && !TestUiThread.Read(condition); attempt++)
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
Assert.True(TestUiThread.Read(condition));
|
||||
}
|
||||
|
||||
static async Task<ProxyGenerationItem> EnqueueAsync(ProxyGenerationQueue queue, SourceIdentity source, int scale)
|
||||
{
|
||||
Assert.True(queue.TryEnqueue(source, scale));
|
||||
await WaitUntilAsync(() => queue.Items.Count == 1);
|
||||
return TestUiThread.Read(() => queue.Items[0]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(30, 1, 10, 300)]
|
||||
[InlineData(30000, 1001, 10, 300)]
|
||||
[InlineData(24, 1, 1, 24)]
|
||||
[InlineData(1, 1000, 10, 1)]
|
||||
public void TheChunkLengthIsTheFrameRateTimesTheSeconds(int numerator, int denominator, int seconds, int expected)
|
||||
=> Assert.Equal(expected, ProxyChunkPlan.LengthFor(new FrameRate(numerator, denominator), seconds));
|
||||
|
||||
[Theory]
|
||||
[InlineData(new int[0], 4, null, 0)]
|
||||
[InlineData(new[] { 0 }, 4, null, 1)]
|
||||
[InlineData(new int[0], 4, 250, 2)]
|
||||
[InlineData(new[] { 2, 3 }, 4, 250, 0)]
|
||||
[InlineData(new[] { 0, 2, 3 }, 4, 250, 1)]
|
||||
[InlineData(new[] { 0, 1, 2, 3 }, 4, 250, null)]
|
||||
[InlineData(new int[0], 4, 100_000, 3)]
|
||||
[InlineData(new int[0], 0, 0, null)]
|
||||
public void TheNextChunkStartsAtTheFocusAndWrapsAround(int[] completed, int chunkCount, int? focusFrame, int? expected)
|
||||
=> Assert.Equal(expected, ProxyChunkPlan.Next(completed, chunkCount, 100, focusFrame));
|
||||
|
||||
[Fact]
|
||||
public async Task AJobEncodesEveryChunkIntoTheCacheAndAnnouncesEachOne()
|
||||
{
|
||||
var source = CreateSource();
|
||||
ProxyEncodeRequest? seen = null;
|
||||
var ranges = new List<(int First, int Count)>();
|
||||
var queue = CreateQueue((first, count, output, progress, _) =>
|
||||
{
|
||||
ranges.Add((first, count));
|
||||
progress?.Report(0.5d);
|
||||
return WriteChunk(output);
|
||||
}, 250, request => seen = request);
|
||||
var announced = new List<(SourceIdentity Source, int Scale, ProxyCacheEntry Entry)>();
|
||||
queue.ChunkCompleted += (announcedSource, scale, entry) => announced.Add((announcedSource, scale, entry.Clone()));
|
||||
options = new ProxyEncodeOptions(80, 15, 4, true);
|
||||
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
Assert.True(queue.IsPending(source, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.NotNull(seen);
|
||||
Assert.Equal(source.Path, seen.Value.SourcePath);
|
||||
Assert.Equal(50, seen.Value.Scale);
|
||||
Assert.Equal(80, seen.Value.BitrateScale);
|
||||
Assert.Equal(15, seen.Value.KeyFrameInterval);
|
||||
Assert.True(seen.Value.UsesHardwareEncoder);
|
||||
Assert.Equal(cache.DirectoryPath, seen.Value.WorkingDirectory);
|
||||
Assert.Equal([(0, 120), (120, 120), (240, 10)], ranges);
|
||||
|
||||
var found = cache.Find(source, 50);
|
||||
Assert.NotNull(found);
|
||||
Assert.Equal(960, found.ProxyWidth);
|
||||
Assert.Equal(30, found.FrameRateNumerator);
|
||||
Assert.Equal(250, found.FrameCount);
|
||||
Assert.Equal(120, found.ChunkLength);
|
||||
Assert.True(found.IsComplete);
|
||||
Assert.Equal(300L, found.FileLength);
|
||||
Assert.Equal(3, announced.Count);
|
||||
Assert.All(announced, item => Assert.Equal((source, 50, found.Id), (item.Source, item.Scale, item.Entry.Id)));
|
||||
Assert.Equal([1, 2, 3], announced.Select(item => item.Entry.Chunks.Count));
|
||||
Assert.Empty(Directory.GetFiles(cache.DirectoryPath, "*.tmp"));
|
||||
Assert.False(queue.IsPending(source, 50));
|
||||
Assert.False(queue.HasFailed(source, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheItemWalksThroughItsStatusesAndCountsChunks()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var started = new TaskCompletionSource();
|
||||
var release = new TaskCompletionSource();
|
||||
var progressed = new List<double>();
|
||||
var covered = new List<ProxyChunkCoverage>();
|
||||
var queue = CreateQueue(async (_, _, output, progress, _) =>
|
||||
{
|
||||
started.TrySetResult();
|
||||
await release.Task;
|
||||
progress?.Report(0.5d);
|
||||
return await WriteChunk(output);
|
||||
});
|
||||
options = new ProxyEncodeOptions(50, 30, 5, false);
|
||||
|
||||
queue.TryEnqueue(source, 50);
|
||||
await started.Task;
|
||||
var item = TestUiThread.Read(() => Assert.Single(queue.Items));
|
||||
Assert.Equal(new ProxyChunkCoverage(2, [], 0, 0d), item.Coverage, CoverageComparer.Instance);
|
||||
item.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(ProxyGenerationItem.Progress))
|
||||
progressed.Add(item.Progress);
|
||||
if (e.PropertyName == nameof(ProxyGenerationItem.Coverage))
|
||||
covered.Add(item.Coverage);
|
||||
};
|
||||
Assert.Equal(source.Path, item.SourcePath);
|
||||
Assert.Equal("source.mp4", item.FileName);
|
||||
Assert.Equal(50, item.Scale);
|
||||
Assert.Equal(ProxyGenerationStatus.Generating, item.Status);
|
||||
Assert.Equal(0d, item.Progress);
|
||||
|
||||
release.SetResult();
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyGenerationStatus.Completed, item.Status);
|
||||
Assert.Equal(1d, item.Progress);
|
||||
Assert.Equal(progressed.OrderBy(value => value), progressed);
|
||||
Assert.Contains(0.25d, progressed);
|
||||
Assert.Contains(0.5d, progressed);
|
||||
Assert.Contains(new ProxyChunkCoverage(2, [], 0, 0.5d), covered, CoverageComparer.Instance);
|
||||
Assert.Contains(new ProxyChunkCoverage(2, [0], 1, 0.5d), covered, CoverageComparer.Instance);
|
||||
Assert.Equal(new ProxyChunkCoverage(2, [0, 1], null, 0d), item.Coverage, CoverageComparer.Instance);
|
||||
await WaitUntilAsync(() => queue.Items.Count == 0);
|
||||
}
|
||||
|
||||
sealed class CoverageComparer : IEqualityComparer<ProxyChunkCoverage>
|
||||
{
|
||||
public static CoverageComparer Instance { get; } = new();
|
||||
|
||||
public bool Equals(ProxyChunkCoverage? x, ProxyChunkCoverage? y)
|
||||
=> x is not null && y is not null && x.ChunkCount == y.ChunkCount && x.Chunks.SequenceEqual(y.Chunks) && x.CurrentChunk == y.CurrentChunk && x.CurrentProgress == y.CurrentProgress;
|
||||
|
||||
public int GetHashCode(ProxyChunkCoverage coverage) => HashCode.Combine(coverage.ChunkCount, coverage.Chunks.Count, coverage.CurrentChunk, coverage.CurrentProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChunksStartAtTheFocusAndFinishTheRest()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var ranges = new List<int>();
|
||||
var queue = CreateQueue((first, _, output, _, _) =>
|
||||
{
|
||||
ranges.Add(first);
|
||||
return WriteChunk(output);
|
||||
}, 1000);
|
||||
focus.Report(source, 650);
|
||||
|
||||
queue.TryEnqueue(source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal([600, 900, 0, 300], ranges);
|
||||
Assert.True(cache.Find(source, 50)!.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AJobResumesAPartialEntryAndSkipsExistingChunks()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var ranges = new List<int>();
|
||||
var queue = CreateQueue((first, _, output, _, _) =>
|
||||
{
|
||||
ranges.Add(first);
|
||||
return WriteChunk(output);
|
||||
}, 1000);
|
||||
var registered = cache.Register(new ProxyCacheEntry
|
||||
{
|
||||
SourcePath = source.Path,
|
||||
SourceLength = source.Length,
|
||||
SourceWriteTimeTicks = source.WriteTimeTicks,
|
||||
Scale = 50,
|
||||
ProxyWidth = 960,
|
||||
ProxyHeight = 540,
|
||||
DisplayLeft = -960f,
|
||||
DisplayTop = -540f,
|
||||
DisplayWidth = 1920f,
|
||||
DisplayHeight = 1080f,
|
||||
FrameRateNumerator = 30,
|
||||
FrameRateDenominator = 1,
|
||||
DurationTicks = 1000 * TimeSpan.TicksPerSecond / 30,
|
||||
FrameCount = 1000,
|
||||
ChunkLength = 300,
|
||||
});
|
||||
var temporary = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(temporary, new byte[10]);
|
||||
cache.AddChunk(registered.Id, 1, temporary);
|
||||
|
||||
queue.TryEnqueue(source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal([0, 600, 900], ranges);
|
||||
var found = cache.Find(source, 50)!;
|
||||
Assert.Equal(registered.Id, found.Id);
|
||||
Assert.True(found.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ACompleteEntryFinishesWithoutEncoding()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var encoded = 0;
|
||||
var queue = CreateQueue((_, _, output, _, _) =>
|
||||
{
|
||||
encoded++;
|
||||
return WriteChunk(output);
|
||||
}, 100);
|
||||
queue.TryEnqueue(source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
Assert.Equal(1, encoded);
|
||||
await WaitUntilAsync(() => queue.Items.Count == 0);
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(1, encoded);
|
||||
Assert.Equal(ProxyGenerationStatus.Completed, item.Status);
|
||||
Assert.Equal(1d, item.Progress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePendingJobIsNotEnqueuedTwice()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var release = new TaskCompletionSource();
|
||||
var queue = CreateQueue(async (_, _, output, _, _) =>
|
||||
{
|
||||
await release.Task;
|
||||
return await WriteChunk(output);
|
||||
});
|
||||
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
Assert.False(queue.TryEnqueue(source, 50));
|
||||
Assert.False(queue.TryEnqueue(source with { Path = source.Path.ToUpperInvariant() }, 50));
|
||||
Assert.True(queue.TryEnqueue(source, 25));
|
||||
|
||||
release.SetResult();
|
||||
await queue.WhenIdleAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OnlyOneJobEncodesAtATime()
|
||||
{
|
||||
var first = CreateSource("a.mp4");
|
||||
var second = CreateSource("b.mp4");
|
||||
var running = 0;
|
||||
var overlap = false;
|
||||
var queue = CreateQueue(async (_, _, output, _, _) =>
|
||||
{
|
||||
if (Interlocked.Increment(ref running) > 1)
|
||||
overlap = true;
|
||||
await Task.Delay(20, CancellationToken.None);
|
||||
Interlocked.Decrement(ref running);
|
||||
return await WriteChunk(output);
|
||||
});
|
||||
|
||||
queue.TryEnqueue(first, 50);
|
||||
queue.TryEnqueue(second, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.False(overlap);
|
||||
Assert.True(cache.Find(first, 50)!.IsComplete);
|
||||
Assert.True(cache.Find(second, 50)!.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AJobWaitsUntilTheExportHasEnded()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var encoded = false;
|
||||
var queue = CreateQueue((_, _, output, _, _) =>
|
||||
{
|
||||
encoded = true;
|
||||
return WriteChunk(output);
|
||||
});
|
||||
phase = ExportPhase.Preparing;
|
||||
|
||||
queue.TryEnqueue(source, 50);
|
||||
await Task.Delay(ProxyGenerationQueue.ExportPollInterval * 3, TestContext.Current.CancellationToken);
|
||||
Assert.False(encoded);
|
||||
Assert.Equal(ProxyGenerationStatus.Waiting, TestUiThread.Read(() => Assert.Single(queue.Items).Status));
|
||||
|
||||
phase = ExportPhase.Idle;
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.True(encoded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnExportThatStartsBetweenChunksPausesTheJob()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var encoded = 0;
|
||||
var queue = CreateQueue((_, _, output, _, _) =>
|
||||
{
|
||||
if (++encoded == 1)
|
||||
phase = ExportPhase.Exporting;
|
||||
return WriteChunk(output);
|
||||
});
|
||||
options = new ProxyEncodeOptions(50, 30, 4, false);
|
||||
|
||||
queue.TryEnqueue(source, 50);
|
||||
await Task.Delay(ProxyGenerationQueue.ExportPollInterval * 3, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1, encoded);
|
||||
|
||||
phase = ExportPhase.Idle;
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(3, encoded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFailedJobIsRememberedUntilForgotten()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _, _, _, _) => throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegFailed, "boom"));
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.True(queue.HasFailed(source, 50));
|
||||
Assert.False(queue.HasFailed(source, 25));
|
||||
Assert.False(queue.TryEnqueue(source, 50));
|
||||
Assert.Equal(ProxyGenerationStatus.Failed, item.Status);
|
||||
Assert.Equal(ProxyEncodeFailure.FFmpegFailed, item.Failure);
|
||||
Assert.Empty(cache.Find(source, 50)!.Chunks);
|
||||
|
||||
queue.ForgetFailures();
|
||||
|
||||
Assert.False(queue.HasFailed(source, 50));
|
||||
await WaitUntilAsync(() => queue.Items.Count == 0);
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFailureToOpenTheSourceIsReportedAsSuch()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _) => throw new ProxyEncodeException(ProxyEncodeFailure.SourceUnavailable, "no plugin"));
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.SourceUnavailable, item.Failure);
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATransparentSourceIsSkippedAndItsChunksAreDiscarded()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var encoded = 0;
|
||||
var queue = CreateQueue((_, _, output, _, _) =>
|
||||
{
|
||||
if (++encoded == 2)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.Transparent, "alpha");
|
||||
return WriteChunk(output);
|
||||
});
|
||||
var discarded = new List<(SourceIdentity Source, int Scale)>();
|
||||
queue.EntryDiscarded += (discardedSource, scale) => discarded.Add((discardedSource, scale));
|
||||
options = new ProxyEncodeOptions(50, 30, 4, false);
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.True(cache.IsSkipped(source));
|
||||
Assert.Equal(ProxyEncodeFailure.Transparent, item.Failure);
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
Assert.Equal(0, cache.Count);
|
||||
Assert.Equal((source, 50), Assert.Single(discarded));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnexpectedExceptionFailsTheJobWithoutAReason()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _, _, _, _) => throw new InvalidOperationException("unexpected"));
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyGenerationStatus.Failed, item.Status);
|
||||
Assert.Null(item.Failure);
|
||||
Assert.True(queue.HasFailed(source, 50));
|
||||
Assert.False(cache.IsSkipped(source));
|
||||
Assert.IsType<InvalidOperationException>(Assert.Single(reported));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelAllStopsARunningJobAndKeepsTheFinishedChunks()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var started = new TaskCompletionSource();
|
||||
var queue = CreateQueue(async (first, _, output, _, token) =>
|
||||
{
|
||||
if (first == 0)
|
||||
return await WriteChunk(output);
|
||||
|
||||
started.TrySetResult();
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, token);
|
||||
return 0L;
|
||||
});
|
||||
options = new ProxyEncodeOptions(50, 30, 4, false);
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await started.Task;
|
||||
queue.CancelAll();
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyGenerationStatus.Cancelled, item.Status);
|
||||
Assert.False(queue.HasFailed(source, 50));
|
||||
Assert.Equal([0], cache.Find(source, 50)!.Chunks);
|
||||
Assert.Empty(Directory.GetFiles(cache.DirectoryPath, "*.tmp"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CancelAllStopsAWaitingJob()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _, output, _, _) => WriteChunk(output));
|
||||
phase = ExportPhase.Exporting;
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await Task.Delay(50, TestContext.Current.CancellationToken);
|
||||
queue.CancelAll();
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyGenerationStatus.Cancelled, item.Status);
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASourceThatChangedDuringTheEncodeIsRejectedAndItsEntryDiscarded()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _, output, _, _) =>
|
||||
{
|
||||
File.WriteAllBytes(source.Path, new byte[200]);
|
||||
return WriteChunk(output);
|
||||
});
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyEncodeFailure.SourceChanged, item.Failure);
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
Assert.Equal(0, cache.Count);
|
||||
Assert.False(cache.IsSkipped(source));
|
||||
Assert.Empty(Directory.GetFiles(cache.DirectoryPath, "*.tmp"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AJobWhoseTemporaryFileVanishedFailsWithoutAReason()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _, _, _, _) => Task.FromResult(0L));
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyGenerationStatus.Failed, item.Status);
|
||||
Assert.True(queue.HasFailed(source, 50));
|
||||
Assert.IsType<FileNotFoundException>(Assert.Single(reported));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AJobWhoseEntryWasRemovedMeanwhileIsCancelled()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((first, _, output, _, _) =>
|
||||
{
|
||||
if (first == 0)
|
||||
cache.Clear();
|
||||
return WriteChunk(output);
|
||||
});
|
||||
|
||||
var item = await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Equal(ProxyGenerationStatus.Cancelled, item.Status);
|
||||
Assert.Null(cache.Find(source, 50));
|
||||
Assert.Empty(Directory.GetFiles(cache.DirectoryPath, "*.tmp"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSessionIsDisposedWhenTheJobEnds()
|
||||
{
|
||||
var source = CreateSource();
|
||||
FakeEncodeSession? session = null;
|
||||
var queue = CreateQueue((_, _) =>
|
||||
{
|
||||
session = new FakeEncodeSession(Analysis(100), (_, _, output, _, _) => WriteChunk(output));
|
||||
return Task.FromResult<IProxyEncodeSession>(session);
|
||||
});
|
||||
|
||||
queue.TryEnqueue(source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.True(session!.IsDisposed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpectedFailuresAreNotReported()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var queue = CreateQueue((_, _, _, _, _) => throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegFailed, "boom"));
|
||||
|
||||
await EnqueueAsync(queue, source, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
|
||||
Assert.Empty(reported);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class ProxyGeometryTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0, 2)]
|
||||
[InlineData(1, 2)]
|
||||
[InlineData(2, 2)]
|
||||
[InlineData(3, 2)]
|
||||
[InlineData(540, 540)]
|
||||
[InlineData(541, 540)]
|
||||
[InlineData(16384, 16384)]
|
||||
public void AlignEvenRoundsDownWithAMinimumOfTwo(int value, int expected)
|
||||
=> Assert.Equal(expected, ProxyGeometryCalculator.AlignEven(value));
|
||||
|
||||
[Fact]
|
||||
public void HalfOfFullHdKeepsTheAspectRatioExactly()
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, 50);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(960, 540), geometry);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(10, 192, 108)]
|
||||
[InlineData(25, 480, 270)]
|
||||
[InlineData(33, 634, 356)]
|
||||
[InlineData(75, 1440, 810)]
|
||||
[InlineData(100, 1920, 1080)]
|
||||
public void FullHdProducesEvenDimensionsAtEveryScale(int scale, int expectedWidth, int expectedHeight)
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, scale);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(expectedWidth, expectedHeight), geometry);
|
||||
Assert.Equal(0, geometry.Width % 2);
|
||||
Assert.Equal(0, geometry.Height % 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APortraitSourceStaysPortrait()
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1080, 1920, 50);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(540, 960), geometry);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(101)]
|
||||
[InlineData(200)]
|
||||
[InlineData(int.MaxValue)]
|
||||
public void AScaleAboveOneHundredNeverExceedsTheSource(int scale)
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, scale);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(1920, 1080), geometry);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(9)]
|
||||
[InlineData(0)]
|
||||
[InlineData(-50)]
|
||||
[InlineData(int.MinValue)]
|
||||
public void AScaleBelowTenIsRaisedToTen(int scale)
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, scale);
|
||||
|
||||
Assert.Equal(ProxyGeometryCalculator.Calculate(1920, 1080, 10), geometry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OddSourceDimensionsAreClampedToTheEvenSource()
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1081, 1081, 100);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(1080, 1080), geometry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HalfOfAnOddDimensionRoundsBeforeAligning()
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(1081, 1919, 50);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(540, 960), geometry);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ATinySourceStaysAtTheMinimumDimensions()
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(10, 10, 10);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(2, 2), geometry);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1080)]
|
||||
[InlineData(1920, 0)]
|
||||
[InlineData(-1, 1080)]
|
||||
[InlineData(16385, 1080)]
|
||||
[InlineData(1920, 16385)]
|
||||
public void AnUnusableSourceSizeIsRejected(int width, int height)
|
||||
=> Assert.Throws<ArgumentOutOfRangeException>(() => ProxyGeometryCalculator.Calculate(width, height, 50));
|
||||
|
||||
[Fact]
|
||||
public void TheLargestSourceIsAccepted()
|
||||
{
|
||||
var geometry = ProxyGeometryCalculator.Calculate(16384, 16384, 100);
|
||||
|
||||
Assert.Equal(new ProxyGeometry(16384, 16384), geometry);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
using System.IO;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class ProxySourceProviderTests : IDisposable
|
||||
{
|
||||
readonly string root = Path.Combine(Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
readonly GraphicsDevices devices = new();
|
||||
readonly IGraphicsDevicesAndContext context;
|
||||
readonly ProxyCache cache;
|
||||
readonly ProxyGenerationQueue queue;
|
||||
readonly SourceFocus focus = new();
|
||||
readonly ProxyForgeSettings settings = new() { MinimumFileSizeMegabytes = 1, Scale = 50 };
|
||||
readonly List<string> opened = [];
|
||||
readonly TaskCompletionSource release = new();
|
||||
bool exporting;
|
||||
bool refuseAll;
|
||||
bool holdOpen;
|
||||
int encoded;
|
||||
|
||||
public ProxySourceProviderTests()
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
context = devices.CreateContext();
|
||||
cache = new ProxyCache(Path.Combine(root, "cache"));
|
||||
queue = CreateQueue(Open);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
release.TrySetResult();
|
||||
queue.CancelAll();
|
||||
context.Dispose();
|
||||
devices.Dispose();
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
ProxyGenerationQueue CreateQueue(ProxyEncodeSessionFactory open)
|
||||
=> new(cache, open, () => new ProxyEncodeOptions(50, 30, 10, false), () => ExportPhase.Idle, focus, _ => { }, TestUiThread.Post)
|
||||
{
|
||||
CompletedRetention = TimeSpan.FromMilliseconds(50),
|
||||
FailedRetention = TimeSpan.FromMilliseconds(50),
|
||||
};
|
||||
|
||||
async Task<IProxyEncodeSession> Open(ProxyEncodeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (holdOpen)
|
||||
await release.Task;
|
||||
|
||||
var analysis = new ProxyAnalysis(new ProxyGeometry(960, 540), new DisplayBounds(-960f, -540f, 1920f, 1080f), new FrameRate(30, 1), TimeSpan.FromSeconds(20), 600);
|
||||
return new FakeEncodeSession(analysis, (_, _, output, _, _) =>
|
||||
{
|
||||
encoded++;
|
||||
File.WriteAllBytes(output, new byte[64]);
|
||||
return Task.FromResult(64L);
|
||||
});
|
||||
}
|
||||
|
||||
IVideoFileSource? Factory(IGraphicsDevicesAndContext target, string path)
|
||||
{
|
||||
opened.Add(path);
|
||||
if (refuseAll)
|
||||
return null;
|
||||
if (path.StartsWith(cache.DirectoryPath, StringComparison.OrdinalIgnoreCase))
|
||||
return TestVideoSource.Solid(target, 960, 540, 30, 1, 300);
|
||||
|
||||
return TestVideoSource.Solid(target, 1920, 1080, 30, 1, 600);
|
||||
}
|
||||
|
||||
ProxySourceProvider CreateProvider(ProxyGenerationQueue? generation = null)
|
||||
=> new(cache, generation ?? queue, focus, () => exporting, () => settings, Factory);
|
||||
|
||||
string CreateFile(string name = "source.mp4", int megabytes = 2)
|
||||
{
|
||||
var path = Path.Combine(root, name);
|
||||
File.WriteAllBytes(path, new byte[megabytes * 1024 * 1024]);
|
||||
return path;
|
||||
}
|
||||
|
||||
static SourceIdentity IdentityOf(string path) => SourceIdentity.Of(path)!.Value;
|
||||
|
||||
ProxyCacheEntry Seed(string path, params int[] chunks)
|
||||
{
|
||||
var identity = IdentityOf(path);
|
||||
var entry = cache.Register(new ProxyCacheEntry
|
||||
{
|
||||
SourcePath = identity.Path,
|
||||
SourceLength = identity.Length,
|
||||
SourceWriteTimeTicks = identity.WriteTimeTicks,
|
||||
Scale = 50,
|
||||
ProxyWidth = 960,
|
||||
ProxyHeight = 540,
|
||||
DisplayLeft = -960f,
|
||||
DisplayTop = -540f,
|
||||
DisplayWidth = 1920f,
|
||||
DisplayHeight = 1080f,
|
||||
FrameRateNumerator = 30,
|
||||
FrameRateDenominator = 1,
|
||||
DurationTicks = TimeSpan.FromSeconds(20).Ticks,
|
||||
FrameCount = 600,
|
||||
ChunkLength = 300,
|
||||
});
|
||||
foreach (var chunk in chunks)
|
||||
{
|
||||
var temporary = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(temporary, new byte[64]);
|
||||
entry = cache.AddChunk(entry.Id, chunk, temporary)!;
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
static async Task UpdateUntilAsync(ProxyVideoSource proxy, TimeSpan time, Func<bool> condition)
|
||||
{
|
||||
for (var attempt = 0; attempt < 500 && !condition(); attempt++)
|
||||
{
|
||||
proxy.Update(time);
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
Assert.True(condition());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DisabledSettingsYieldNothing()
|
||||
{
|
||||
settings.IsEnabled = false;
|
||||
var path = CreateFile();
|
||||
|
||||
Assert.Null(CreateProvider().Create(context, path));
|
||||
Assert.Empty(opened);
|
||||
Assert.False(queue.IsPending(IdentityOf(path), 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NothingIsProxiedWhileExporting()
|
||||
{
|
||||
exporting = true;
|
||||
var path = CreateFile();
|
||||
Seed(path, 0, 1);
|
||||
|
||||
Assert.Null(CreateProvider().Create(context, path));
|
||||
Assert.Empty(opened);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMissingFileYieldsNothing()
|
||||
{
|
||||
Assert.Null(CreateProvider().Create(context, Path.Combine(root, "missing.mp4")));
|
||||
Assert.Empty(opened);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASmallFileYieldsNothing()
|
||||
{
|
||||
settings.MinimumFileSizeMegabytes = 3;
|
||||
var path = CreateFile(megabytes: 2);
|
||||
|
||||
Assert.Null(CreateProvider().Create(context, path));
|
||||
Assert.Empty(opened);
|
||||
Assert.False(queue.IsPending(IdentityOf(path), 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFileExactlyAtTheThresholdIsProxied()
|
||||
{
|
||||
settings.MinimumFileSizeMegabytes = 2;
|
||||
var path = CreateFile(megabytes: 2);
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
Assert.NotNull(source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASkippedFileYieldsNothing()
|
||||
{
|
||||
var path = CreateFile();
|
||||
cache.AddSkip(IdentityOf(path), ProxyCacheSkipReason.Transparent);
|
||||
|
||||
Assert.Null(CreateProvider().Create(context, path));
|
||||
Assert.Empty(opened);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACompleteEntryIsUsedWithoutOpeningTheOriginalOrEncoding()
|
||||
{
|
||||
var path = CreateFile();
|
||||
Seed(path, 0, 1);
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
var proxy = Assert.IsType<ProxyVideoSource>(source);
|
||||
Assert.False(proxy.HasOriginal);
|
||||
Assert.Equal(TimeSpan.FromSeconds(20), proxy.Duration);
|
||||
Assert.Empty(opened);
|
||||
Assert.False(queue.IsPending(IdentityOf(path), 50));
|
||||
|
||||
proxy.Update(TimeSpan.FromSeconds(12));
|
||||
|
||||
Assert.True(proxy.IsProxy);
|
||||
Assert.Equal(1, proxy.ShownChunk);
|
||||
Assert.EndsWith("000001.mp4", Assert.Single(opened));
|
||||
Assert.Equal(0, encoded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APartialEntryIsUsedAndTheRestIsQueued()
|
||||
{
|
||||
var path = CreateFile();
|
||||
Seed(path, 0);
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
var proxy = Assert.IsType<ProxyVideoSource>(source);
|
||||
Assert.False(proxy.HasOriginal);
|
||||
Assert.True(queue.IsPending(IdentityOf(path), 50));
|
||||
await queue.WhenIdleAsync();
|
||||
Assert.Equal(1, encoded);
|
||||
Assert.True(cache.Find(IdentityOf(path), 50)!.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANewFileIsWrappedAroundTheOriginalAndQueued()
|
||||
{
|
||||
var path = CreateFile();
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
var proxy = Assert.IsType<ProxyVideoSource>(source);
|
||||
Assert.True(proxy.HasOriginal);
|
||||
Assert.False(proxy.IsProxy);
|
||||
Assert.Equal(TimeSpan.FromSeconds(20), proxy.Duration);
|
||||
Assert.Equal(path, Assert.Single(opened));
|
||||
await queue.WhenIdleAsync();
|
||||
Assert.Equal(2, encoded);
|
||||
Assert.True(cache.Find(IdentityOf(path), 50)!.IsComplete);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFailedFileYieldsNothingAfterwards()
|
||||
{
|
||||
var path = CreateFile();
|
||||
var failing = CreateQueue((_, _) => throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegFailed, "boom"));
|
||||
failing.TryEnqueue(IdentityOf(path), 50);
|
||||
await failing.WhenIdleAsync();
|
||||
|
||||
Assert.Null(CreateProvider(failing).Create(context, path));
|
||||
Assert.Empty(opened);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFailedFileStillUsesItsFinishedChunks()
|
||||
{
|
||||
var path = CreateFile();
|
||||
Seed(path, 0);
|
||||
var failing = CreateQueue((_, _) => throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegFailed, "boom"));
|
||||
failing.TryEnqueue(IdentityOf(path), 50);
|
||||
await failing.WhenIdleAsync();
|
||||
|
||||
using var source = CreateProvider(failing).Create(context, path);
|
||||
|
||||
var proxy = Assert.IsType<ProxyVideoSource>(source);
|
||||
Assert.False(failing.IsPending(IdentityOf(path), 50));
|
||||
proxy.Update(TimeSpan.Zero);
|
||||
Assert.True(proxy.IsProxy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAutomaticGenerationAnUnknownFileYieldsNothing()
|
||||
{
|
||||
settings.GeneratesAutomatically = false;
|
||||
var path = CreateFile();
|
||||
|
||||
Assert.Null(CreateProvider().Create(context, path));
|
||||
Assert.Empty(opened);
|
||||
Assert.False(queue.IsPending(IdentityOf(path), 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAutomaticGenerationAPartialEntryIsStillUsedButNotQueued()
|
||||
{
|
||||
settings.GeneratesAutomatically = false;
|
||||
var path = CreateFile();
|
||||
Seed(path, 0);
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
Assert.IsType<ProxyVideoSource>(source);
|
||||
Assert.False(queue.IsPending(IdentityOf(path), 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAutomaticGenerationAPendingFileIsStillWrapped()
|
||||
{
|
||||
var path = CreateFile();
|
||||
var identity = IdentityOf(path);
|
||||
holdOpen = true;
|
||||
queue.TryEnqueue(identity, 50);
|
||||
settings.GeneratesAutomatically = false;
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
var proxy = Assert.IsType<ProxyVideoSource>(source);
|
||||
Assert.True(proxy.HasOriginal);
|
||||
Assert.Equal(TimeSpan.FromSeconds(20), proxy.Duration);
|
||||
release.SetResult();
|
||||
await queue.WhenIdleAsync();
|
||||
await UpdateUntilAsync(proxy, TimeSpan.Zero, () => proxy.IsProxy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFileNoPluginCanOpenYieldsNothingAndIsNotQueued()
|
||||
{
|
||||
refuseAll = true;
|
||||
var path = CreateFile();
|
||||
|
||||
Assert.Null(CreateProvider().Create(context, path));
|
||||
Assert.Single(opened);
|
||||
Assert.False(queue.IsPending(IdentityOf(path), 50));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheWrapperSwitchesToTheChunksAsTheyAreGenerated()
|
||||
{
|
||||
var path = CreateFile();
|
||||
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
var proxy = Assert.IsType<ProxyVideoSource>(source);
|
||||
await queue.WhenIdleAsync();
|
||||
await UpdateUntilAsync(proxy, TimeSpan.FromSeconds(1), () => proxy.IsProxy);
|
||||
|
||||
Assert.Equal(0, proxy.ShownChunk);
|
||||
Assert.Equal(TimeSpan.FromSeconds(20), proxy.Duration);
|
||||
Assert.Contains(opened, candidate => candidate.EndsWith("000000.mp4", StringComparison.Ordinal));
|
||||
await UpdateUntilAsync(proxy, TimeSpan.FromSeconds(1), () => !proxy.HasOriginal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheFocusFollowsTheRequestedFrame()
|
||||
{
|
||||
var path = CreateFile();
|
||||
using var source = CreateProvider().Create(context, path);
|
||||
|
||||
source!.Update(TimeSpan.FromSeconds(3));
|
||||
|
||||
Assert.Equal(90, focus.Get(IdentityOf(path)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
[Collection("Direct2D")]
|
||||
public sealed class ProxyVideoSourceTests : IDisposable
|
||||
{
|
||||
const int ChunkLength = 300;
|
||||
|
||||
readonly string root = Path.Combine(Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
readonly GraphicsDevices devices = new();
|
||||
readonly IGraphicsDevicesAndContext context;
|
||||
readonly ProxyCache cache;
|
||||
readonly ProxyGenerationQueue queue;
|
||||
readonly SourceFocus focus = new();
|
||||
readonly List<TestVideoSource> chunkSources = [];
|
||||
readonly List<string> openedPaths = [];
|
||||
int frameCount = 900;
|
||||
bool refuseChunks;
|
||||
bool refuseOriginal;
|
||||
bool transparent;
|
||||
|
||||
public ProxyVideoSourceTests()
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
context = devices.CreateContext();
|
||||
cache = new ProxyCache(Path.Combine(root, "cache"));
|
||||
queue = new ProxyGenerationQueue(cache, Open, () => new ProxyEncodeOptions(50, 30, 10, false), () => ExportPhase.Idle, focus, _ => { }, TestUiThread.Post)
|
||||
{
|
||||
CompletedRetention = TimeSpan.FromMilliseconds(50),
|
||||
FailedRetention = TimeSpan.FromMilliseconds(50),
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
context.Dispose();
|
||||
devices.Dispose();
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
Task<IProxyEncodeSession> Open(ProxyEncodeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var analysis = new ProxyAnalysis(new ProxyGeometry(960, 540), new DisplayBounds(-960f, -540f, 1920f, 1080f), new FrameRate(30, 1), TimeSpan.FromTicks(frameCount * TimeSpan.TicksPerSecond / 30), frameCount);
|
||||
return Task.FromResult<IProxyEncodeSession>(new FakeEncodeSession(analysis, (_, _, output, _, _) =>
|
||||
{
|
||||
if (transparent)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.Transparent, "alpha");
|
||||
|
||||
File.WriteAllBytes(output, new byte[64]);
|
||||
return Task.FromResult(64L);
|
||||
}));
|
||||
}
|
||||
|
||||
SourceIdentity CreateSource()
|
||||
{
|
||||
var path = Path.Combine(root, "source.mp4");
|
||||
File.WriteAllBytes(path, new byte[100]);
|
||||
return SourceIdentity.Of(path)!.Value;
|
||||
}
|
||||
|
||||
ProxyCacheEntry Register(SourceIdentity source, params int[] chunks)
|
||||
{
|
||||
var entry = cache.Register(new ProxyCacheEntry
|
||||
{
|
||||
SourcePath = source.Path,
|
||||
SourceLength = source.Length,
|
||||
SourceWriteTimeTicks = source.WriteTimeTicks,
|
||||
Scale = 50,
|
||||
ProxyWidth = 960,
|
||||
ProxyHeight = 540,
|
||||
DisplayLeft = -960f,
|
||||
DisplayTop = -540f,
|
||||
DisplayWidth = 1920f,
|
||||
DisplayHeight = 1080f,
|
||||
FrameRateNumerator = 30,
|
||||
FrameRateDenominator = 1,
|
||||
DurationTicks = frameCount * TimeSpan.TicksPerSecond / 30,
|
||||
FrameCount = frameCount,
|
||||
ChunkLength = ChunkLength,
|
||||
});
|
||||
foreach (var chunk in chunks)
|
||||
{
|
||||
var temporary = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(temporary, new byte[64]);
|
||||
entry = cache.AddChunk(entry.Id, chunk, temporary)!;
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
IVideoFileSource? Factory(IGraphicsDevicesAndContext target, string path)
|
||||
{
|
||||
openedPaths.Add(path);
|
||||
if (path.StartsWith(cache.DirectoryPath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (refuseChunks)
|
||||
return null;
|
||||
|
||||
var chunk = TestVideoSource.Solid(target, 960, 540, 30, 1, ChunkLength);
|
||||
chunkSources.Add(chunk);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
return refuseOriginal ? null : TestVideoSource.Solid(target, 1920, 1080, 30, 1, frameCount);
|
||||
}
|
||||
|
||||
ProxyVideoSource CreateWrapper(SourceIdentity source, ProxyCacheEntry? entry, TestVideoSource? original)
|
||||
=> new(context, source, original, entry, new ProxyChunkLoader(context, source, 50, entry, cache, queue, Factory), Factory, focus);
|
||||
|
||||
static TimeSpan FrameTimeOf(int frame) => new FrameRate(30, 1).GetSampleTime(frame);
|
||||
|
||||
async Task UpdateUntilAsync(ProxyVideoSource wrapper, TimeSpan time, Func<bool> condition)
|
||||
{
|
||||
for (var attempt = 0; attempt < 500 && !condition(); attempt++)
|
||||
{
|
||||
wrapper.Update(time);
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
Assert.True(condition());
|
||||
}
|
||||
|
||||
async Task GenerateAsync(SourceIdentity source)
|
||||
{
|
||||
Assert.True(queue.TryEnqueue(source, 50));
|
||||
await queue.WhenIdleAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AWrapperNeedsAnOriginalOrAnEntry()
|
||||
{
|
||||
var source = CreateSource();
|
||||
|
||||
Assert.Throws<ArgumentException>(() => CreateWrapper(source, null, null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAnEntryTheOriginalAnswersEverything()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var original = TestVideoSource.Solid(context, 1920, 1080, 30, 1, 60);
|
||||
using var wrapper = CreateWrapper(source, null, original);
|
||||
|
||||
Assert.Equal(TimeSpan.FromSeconds(2), wrapper.Duration);
|
||||
Assert.Equal(original.GetFrameIndex(TimeSpan.FromSeconds(1.5)), wrapper.GetFrameIndex(TimeSpan.FromSeconds(1.5)));
|
||||
Assert.NotNull(wrapper.Output);
|
||||
|
||||
wrapper.Update(TimeSpan.FromSeconds(1));
|
||||
|
||||
Assert.False(wrapper.IsProxy);
|
||||
Assert.Equal(1, original.UpdateCount);
|
||||
Assert.Equal(TimeSpan.FromSeconds(1), original.LastUpdateTime);
|
||||
Assert.Equal(30, focus.Get(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEntryAnswersTheDurationAndTheFrameIndexWithoutTheOriginal()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
|
||||
Assert.Equal(TimeSpan.FromSeconds(30), wrapper.Duration);
|
||||
Assert.Equal(FrameTime.TimeToFrame(TimeSpan.FromSeconds(7), 30, 1), wrapper.GetFrameIndex(TimeSpan.FromSeconds(7)));
|
||||
Assert.False(wrapper.HasOriginal);
|
||||
Assert.Empty(openedPaths);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithoutAnOriginalTheChunkIsOpenedSynchronously()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
|
||||
wrapper.Update(FrameTimeOf(450));
|
||||
|
||||
Assert.True(wrapper.IsProxy);
|
||||
Assert.Equal(1, wrapper.ShownChunk);
|
||||
Assert.False(wrapper.HasOriginal);
|
||||
Assert.EndsWith("000001.mp4", openedPaths[0]);
|
||||
Assert.Equal(FrameTimeOf(150), chunkSources[0].LastUpdateTime);
|
||||
Assert.Equal(450, focus.Get(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFrameInTheUpperHalfOfItsIntervalStaysInItsChunk()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
|
||||
wrapper.Update(FrameTimeOf(299));
|
||||
|
||||
Assert.Equal(0, wrapper.ShownChunk);
|
||||
Assert.Equal(FrameTimeOf(299), chunkSources[0].LastUpdateTime);
|
||||
Assert.Equal(299, focus.Get(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithAnOriginalTheChunkArrivesInTheBackground()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
var original = TestVideoSource.Solid(context, 1920, 1080, 30, 1, frameCount);
|
||||
using var wrapper = CreateWrapper(source, entry, original);
|
||||
|
||||
wrapper.Update(FrameTimeOf(450));
|
||||
Assert.False(wrapper.IsProxy);
|
||||
Assert.Equal(1, original.UpdateCount);
|
||||
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(450), () => wrapper.IsProxy);
|
||||
|
||||
Assert.Equal(1, wrapper.ShownChunk);
|
||||
Assert.Contains(chunkSources, chunk => chunk.LastUpdateTime == FrameTimeOf(150));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheNextChunkIsPrefetchedAndFarChunksAreEvicted()
|
||||
{
|
||||
frameCount = 1500;
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2, 3, 4);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
|
||||
wrapper.Update(FrameTimeOf(0));
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(0), () => wrapper.OpenChunkCount == 2);
|
||||
Assert.Equal(0, wrapper.ShownChunk);
|
||||
|
||||
wrapper.Update(FrameTimeOf(1350));
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(1350), () => wrapper.OpenChunkCount == 1 && chunkSources.Count(chunk => chunk.IsDisposed) == 2);
|
||||
|
||||
Assert.Equal(4, wrapper.ShownChunk);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AMissingChunkFallsBackToTheOriginalUntilItIsGenerated()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0);
|
||||
var original = TestVideoSource.Solid(context, 1920, 1080, 30, 1, frameCount);
|
||||
using var wrapper = CreateWrapper(source, entry, original);
|
||||
|
||||
wrapper.Update(FrameTimeOf(450));
|
||||
Assert.False(wrapper.IsProxy);
|
||||
Assert.Equal(FrameTimeOf(450), original.LastUpdateTime);
|
||||
|
||||
await GenerateAsync(source);
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(450), () => wrapper.IsProxy);
|
||||
|
||||
Assert.Equal(1, wrapper.ShownChunk);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOriginalIsReleasedOnceEveryChunkExists()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1);
|
||||
var original = TestVideoSource.Solid(context, 1920, 1080, 30, 1, frameCount);
|
||||
using var wrapper = CreateWrapper(source, entry, original);
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(0), () => wrapper.IsProxy);
|
||||
Assert.True(wrapper.HasOriginal);
|
||||
|
||||
await GenerateAsync(source);
|
||||
wrapper.Update(FrameTimeOf(0));
|
||||
|
||||
Assert.False(wrapper.HasOriginal);
|
||||
Assert.True(original.IsDisposed);
|
||||
Assert.True(wrapper.IsProxy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADiscardedEntryReturnsToTheOriginal()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
wrapper.Update(FrameTimeOf(0));
|
||||
Assert.True(wrapper.IsProxy);
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(0), () => wrapper.OpenChunkCount == 2);
|
||||
|
||||
transparent = true;
|
||||
await GenerateAsync(source);
|
||||
wrapper.Update(FrameTimeOf(0));
|
||||
|
||||
Assert.False(wrapper.IsProxy);
|
||||
Assert.True(wrapper.HasOriginal);
|
||||
Assert.Equal(0, wrapper.OpenChunkCount);
|
||||
Assert.All(chunkSources, chunk => Assert.True(chunk.IsDisposed));
|
||||
Assert.Equal(TimeSpan.FromSeconds(30), wrapper.Duration);
|
||||
Assert.True(cache.IsSkipped(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AChunkThatCannotBeOpenedIsForgottenAndTheOriginalIsOpened()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
refuseChunks = true;
|
||||
|
||||
wrapper.Update(FrameTimeOf(0));
|
||||
|
||||
Assert.False(wrapper.IsProxy);
|
||||
Assert.True(wrapper.HasOriginal);
|
||||
Assert.DoesNotContain(0, cache.Get(entry.Id)!.Chunks);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WhenNothingCanBeOpenedTheOutputIsEmptyButUsable()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
using var wrapper = CreateWrapper(source, entry, null);
|
||||
refuseChunks = true;
|
||||
refuseOriginal = true;
|
||||
|
||||
wrapper.Update(FrameTimeOf(0));
|
||||
wrapper.Update(FrameTimeOf(1));
|
||||
|
||||
Assert.False(wrapper.IsProxy);
|
||||
Assert.False(wrapper.HasOriginal);
|
||||
Assert.Equal(1, openedPaths.Count(path => path == source.Path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisposingReleasesEverythingAndRefusesUpdates()
|
||||
{
|
||||
var source = CreateSource();
|
||||
var entry = Register(source, 0, 1, 2);
|
||||
var original = TestVideoSource.Solid(context, 1920, 1080, 30, 1, frameCount);
|
||||
var wrapper = CreateWrapper(source, entry, original);
|
||||
await UpdateUntilAsync(wrapper, FrameTimeOf(0), () => wrapper.IsProxy);
|
||||
|
||||
wrapper.Dispose();
|
||||
wrapper.Dispose();
|
||||
|
||||
Assert.True(original.IsDisposed);
|
||||
Assert.All(chunkSources, chunk => Assert.True(chunk.IsDisposed));
|
||||
Assert.Throws<ObjectDisposedException>(() => wrapper.Update(TimeSpan.Zero));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AlignMapsTheProxyRectangleOntoTheDisplayRectangle()
|
||||
{
|
||||
var transform = OpenedChunk.Align(new DisplayBounds(-480f, -270f, 960f, 540f), Layout());
|
||||
|
||||
Assert.Equal(new Vector2(-960f, -540f), Vector2.Transform(new Vector2(-480f, -270f), transform));
|
||||
Assert.Equal(new Vector2(960f, 540f), Vector2.Transform(new Vector2(480f, 270f), transform));
|
||||
Assert.Equal(new Vector2(0f, 0f), Vector2.Transform(new Vector2(0f, 0f), transform));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AlignHandlesAnOffCentreProxyAndUnevenScales()
|
||||
{
|
||||
var transform = OpenedChunk.Align(new DisplayBounds(-160f, -90f, 320f, 180f), Layout(-641f, -361f, 1282f, 722f));
|
||||
|
||||
var topLeft = Vector2.Transform(new Vector2(-160f, -90f), transform);
|
||||
var bottomRight = Vector2.Transform(new Vector2(160f, 90f), transform);
|
||||
Assert.Equal(-641f, topLeft.X, 3);
|
||||
Assert.Equal(-361f, topLeft.Y, 3);
|
||||
Assert.Equal(641f, bottomRight.X, 3);
|
||||
Assert.Equal(361f, bottomRight.Y, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpenReturnsNullWhenNoPluginOpensTheChunk()
|
||||
=> Assert.Null(OpenedChunk.Open(context, "chunk.mp4", Layout(), static (_, _) => null));
|
||||
|
||||
[Fact]
|
||||
public void OpenRejectsAnEntryWithAnInvalidRateBeforeOpeningAnything()
|
||||
{
|
||||
var entry = Layout();
|
||||
entry.FrameRateDenominator = 0;
|
||||
var created = false;
|
||||
|
||||
var opened = OpenedChunk.Open(context, "chunk.mp4", entry, (target, _) =>
|
||||
{
|
||||
created = true;
|
||||
return TestVideoSource.Solid(target, 960, 540, 30, 1, 10);
|
||||
});
|
||||
|
||||
Assert.Null(opened);
|
||||
Assert.False(created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpenRejectsAnEntryWithoutADisplaySize()
|
||||
{
|
||||
var created = false;
|
||||
|
||||
var opened = OpenedChunk.Open(context, "chunk.mp4", Layout(width: 0f), (target, _) =>
|
||||
{
|
||||
created = true;
|
||||
return TestVideoSource.Solid(target, 960, 540, 30, 1, 10);
|
||||
});
|
||||
|
||||
Assert.Null(opened);
|
||||
Assert.False(created);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpenMeasuresTheChunkAndBuildsTheAlignment()
|
||||
{
|
||||
TestVideoSource? created = null;
|
||||
|
||||
var opened = OpenedChunk.Open(context, "chunk.mp4", Layout(), (target, _) => created = TestVideoSource.Solid(target, 960, 540, 30000, 1001, 300));
|
||||
|
||||
Assert.NotNull(opened);
|
||||
Assert.Same(created, opened.Source);
|
||||
Assert.Equal(1, created!.UpdateCount);
|
||||
Assert.Equal(new Vector2(-960f, -540f), Vector2.Transform(new Vector2(-480f, -270f), opened.Transform));
|
||||
Assert.Equal(new Vector2(960f, 540f), Vector2.Transform(new Vector2(480f, 270f), opened.Transform));
|
||||
|
||||
opened.Dispose();
|
||||
|
||||
Assert.True(created.IsDisposed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OpenDisposesTheSourceWhenTheFactoryProductThrows()
|
||||
{
|
||||
var thrown = Assert.Throws<InvalidOperationException>(() => OpenedChunk.Open(context, "chunk.mp4", Layout(), (_, _) => new ThrowingVideoSource()));
|
||||
|
||||
Assert.Equal("update", thrown.Message);
|
||||
Assert.True(ThrowingVideoSource.LastDisposed);
|
||||
}
|
||||
|
||||
static ProxyCacheEntry Layout(float left = -960f, float top = -540f, float width = 1920f, float height = 1080f) => new()
|
||||
{
|
||||
DisplayLeft = left,
|
||||
DisplayTop = top,
|
||||
DisplayWidth = width,
|
||||
DisplayHeight = height,
|
||||
FrameRateNumerator = 30000,
|
||||
FrameRateDenominator = 1001,
|
||||
DurationTicks = TimeSpan.FromSeconds(10).Ticks,
|
||||
FrameCount = 300,
|
||||
ChunkLength = 100,
|
||||
};
|
||||
|
||||
sealed class ThrowingVideoSource : IVideoFileSource
|
||||
{
|
||||
public static bool LastDisposed { get; private set; }
|
||||
|
||||
public TimeSpan Duration => TimeSpan.FromSeconds(1);
|
||||
|
||||
public Vortice.Direct2D1.ID2D1Image Output => throw new InvalidOperationException("output");
|
||||
|
||||
public void Update(TimeSpan time) => throw new InvalidOperationException("update");
|
||||
|
||||
public int GetFrameIndex(TimeSpan time) => 0;
|
||||
|
||||
public void Dispose() => LastDisposed = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
static class TestUiThread
|
||||
{
|
||||
static readonly Lock gate = new();
|
||||
|
||||
public static void Post(Action action)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
action();
|
||||
}
|
||||
|
||||
public static T Read<T>(Func<T> read)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
return read();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Numerics;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public enum TestCentering
|
||||
{
|
||||
Floor,
|
||||
Exact,
|
||||
}
|
||||
|
||||
internal sealed class TestVideoSource : IVideoFileSource
|
||||
{
|
||||
const float ReferenceDpi = 96f;
|
||||
|
||||
readonly ID2D1Bitmap1 bitmap;
|
||||
readonly AffineTransform2D centering;
|
||||
readonly ID2D1Image output;
|
||||
readonly int frameRateNumerator;
|
||||
readonly int frameRateDenominator;
|
||||
readonly int width;
|
||||
readonly int height;
|
||||
readonly Func<int, int, int, (byte Blue, byte Green, byte Red, byte Alpha)>? framePixelOf;
|
||||
int uploadedFrame = -1;
|
||||
|
||||
public int UpdateCount { get; private set; }
|
||||
|
||||
public List<int> RequestedFrames { get; } = [];
|
||||
|
||||
public bool IsDisposed { get; private set; }
|
||||
|
||||
public TimeSpan LastUpdateTime { get; private set; }
|
||||
|
||||
public TimeSpan Duration { get; }
|
||||
|
||||
public ID2D1Image Output => output;
|
||||
|
||||
public TestVideoSource(
|
||||
IGraphicsDevicesAndContext devices,
|
||||
int width,
|
||||
int height,
|
||||
int frameRateNumerator,
|
||||
int frameRateDenominator,
|
||||
int frameCount,
|
||||
Func<int, int, (byte Blue, byte Green, byte Red, byte Alpha)> pixelOf,
|
||||
TestCentering centering = TestCentering.Floor,
|
||||
Func<int, int, int, (byte Blue, byte Green, byte Red, byte Alpha)>? framePixelOf = null)
|
||||
{
|
||||
this.frameRateNumerator = frameRateNumerator;
|
||||
this.frameRateDenominator = frameRateDenominator;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.framePixelOf = framePixelOf;
|
||||
Duration = TimeSpan.FromTicks(frameCount * TimeSpan.TicksPerSecond * frameRateDenominator / frameRateNumerator);
|
||||
|
||||
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
bitmap = devices.DeviceContext.CreateBitmap(
|
||||
new SizeI(width, height), nint.Zero, width * 4,
|
||||
new BitmapProperties1(pixelFormat, ReferenceDpi, ReferenceDpi, BitmapOptions.None));
|
||||
Upload(pixelOf);
|
||||
|
||||
this.centering = new AffineTransform2D(devices.DeviceContext);
|
||||
this.centering.SetInput(0, bitmap, true);
|
||||
this.centering.TransformMatrix = centering == TestCentering.Floor
|
||||
? Matrix3x2.CreateTranslation(MathF.Floor(-width / 2f), MathF.Floor(-height / 2f))
|
||||
: Matrix3x2.CreateTranslation(-width / 2f, -height / 2f);
|
||||
output = this.centering.Output;
|
||||
}
|
||||
|
||||
public static TestVideoSource Solid(
|
||||
IGraphicsDevicesAndContext devices,
|
||||
int width,
|
||||
int height,
|
||||
int frameRateNumerator,
|
||||
int frameRateDenominator,
|
||||
int frameCount,
|
||||
byte blue = 64,
|
||||
byte green = 64,
|
||||
byte red = 64)
|
||||
=> new(devices, width, height, frameRateNumerator, frameRateDenominator, frameCount, (_, _) => (blue, green, red, byte.MaxValue));
|
||||
|
||||
public void Update(TimeSpan time)
|
||||
{
|
||||
UpdateCount++;
|
||||
LastUpdateTime = time;
|
||||
var frame = time <= TimeSpan.Zero ? 0 : (int)((Int128)time.Ticks * frameRateNumerator / ((Int128)frameRateDenominator * TimeSpan.TicksPerSecond));
|
||||
RequestedFrames.Add(frame);
|
||||
if (framePixelOf is null || frame == uploadedFrame)
|
||||
return;
|
||||
|
||||
uploadedFrame = frame;
|
||||
Upload((x, y) => framePixelOf(frame, x, y));
|
||||
}
|
||||
|
||||
void Upload(Func<int, int, (byte Blue, byte Green, byte Red, byte Alpha)> pixelOf)
|
||||
{
|
||||
var stride = width * 4;
|
||||
var pixels = new byte[stride * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (blue, green, red, alpha) = pixelOf(x, y);
|
||||
var offset = y * stride + x * 4;
|
||||
pixels[offset] = Premultiply(blue, alpha);
|
||||
pixels[offset + 1] = Premultiply(green, alpha);
|
||||
pixels[offset + 2] = Premultiply(red, alpha);
|
||||
pixels[offset + 3] = alpha;
|
||||
}
|
||||
}
|
||||
|
||||
bitmap.CopyFromMemory(pixels, stride);
|
||||
}
|
||||
|
||||
public int GetFrameIndex(TimeSpan time) => FrameTime.TimeToFrame(time, frameRateNumerator, frameRateDenominator);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (IsDisposed)
|
||||
return;
|
||||
|
||||
IsDisposed = true;
|
||||
output.Dispose();
|
||||
centering.SetInput(0, null, true);
|
||||
centering.Dispose();
|
||||
bitmap.Dispose();
|
||||
}
|
||||
|
||||
static byte Premultiply(byte value, byte alpha)
|
||||
=> (byte)Math.Round(value * (double)alpha / byte.MaxValue, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class UiThreadTests
|
||||
{
|
||||
[Fact]
|
||||
public void WithoutAnApplicationTheActionRunsInlineOnTheCallingThread()
|
||||
{
|
||||
var threadId = 0;
|
||||
|
||||
UiThread.Post(() => threadId = Environment.CurrentManagedThreadId);
|
||||
|
||||
Assert.Equal(Environment.CurrentManagedThreadId, threadId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
using ProxyForge.ViewModels;
|
||||
using ProxyForge.Views;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
public sealed class ByteTextTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0L, "0 B")]
|
||||
[InlineData(-5L, "0 B")]
|
||||
[InlineData(1L, "1 B")]
|
||||
[InlineData(1023L, "1023 B")]
|
||||
[InlineData(1024L, "1 KB")]
|
||||
[InlineData(1536L, "1.5 KB")]
|
||||
[InlineData(1024L * 1024L, "1 MB")]
|
||||
[InlineData(544_320L, "531.56 KB")]
|
||||
[InlineData(10L * 1024L * 1024L * 1024L, "10 GB")]
|
||||
[InlineData(1024L * 1024L * 1024L * 1024L * 3L, "3 TB")]
|
||||
[InlineData(1024L * 1024L * 1024L * 1024L * 1024L * 2L, "2048 TB")]
|
||||
public void FormatsWithTheLargestFittingUnit(long bytes, string expected)
|
||||
=> Assert.Equal(expected, ByteText.Format(bytes));
|
||||
}
|
||||
|
||||
public sealed class PluginOrderTests
|
||||
{
|
||||
const string Name = "ProxyForge.ProxyForgeVideoFileSourcePlugin";
|
||||
|
||||
[Fact]
|
||||
public void ThePluginNameIsTheFullTypeName()
|
||||
=> Assert.Equal(Name, PluginOrder.PluginName);
|
||||
|
||||
[Fact]
|
||||
public void AnEmptyOrderIsNotFirst()
|
||||
=> Assert.False(PluginOrder.IsFirst([], Name));
|
||||
|
||||
[Fact]
|
||||
public void TheFirstEntryDecides()
|
||||
{
|
||||
Assert.True(PluginOrder.IsFirst([Name, "Other"], Name));
|
||||
Assert.False(PluginOrder.IsFirst(["Other", Name], Name));
|
||||
Assert.False(PluginOrder.IsFirst([Name.ToUpperInvariant()], Name));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveToFrontPutsTheNameFirstAndKeepsTheRest()
|
||||
{
|
||||
var moved = PluginOrder.MoveToFront(["A", Name, "B"], Name);
|
||||
|
||||
Assert.Equal([Name, "A", "B"], moved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveToFrontAddsAMissingName()
|
||||
{
|
||||
var moved = PluginOrder.MoveToFront(["A", "B"], Name);
|
||||
|
||||
Assert.Equal([Name, "A", "B"], moved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveToFrontRemovesDuplicates()
|
||||
{
|
||||
var moved = PluginOrder.MoveToFront([Name, "A", Name], Name);
|
||||
|
||||
Assert.Equal([Name, "A"], moved);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveToFrontLeavesAnOrderThatIsAlreadyRightUnchanged()
|
||||
{
|
||||
ImmutableList<string> order = [Name, "A"];
|
||||
|
||||
Assert.Equal(order, PluginOrder.MoveToFront(order, Name));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ProxyCacheEntryViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public void FormatsTheEntryForDisplay()
|
||||
{
|
||||
var lastUsed = new DateTime(2026, 9, 13, 1, 2, 0, DateTimeKind.Utc);
|
||||
var entry = new ProxyCacheEntry
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
SourcePath = @"C:\videos\clip.mp4",
|
||||
Scale = 50,
|
||||
ProxyWidth = 960,
|
||||
ProxyHeight = 540,
|
||||
FileLength = 1536,
|
||||
FrameCount = 250,
|
||||
ChunkLength = 100,
|
||||
Chunks = [0, 2],
|
||||
LastUsedTicks = lastUsed.Ticks,
|
||||
};
|
||||
|
||||
var viewModel = new ProxyCacheEntryViewModel(entry);
|
||||
|
||||
Assert.Equal(entry.Id, viewModel.Id);
|
||||
Assert.Equal(@"C:\videos\clip.mp4", viewModel.SourcePath);
|
||||
Assert.Equal("clip.mp4", viewModel.FileName);
|
||||
Assert.Equal("960×540", viewModel.Resolution);
|
||||
Assert.Equal("50%", viewModel.Scale);
|
||||
Assert.Equal(1536L, viewModel.Bytes);
|
||||
Assert.Equal("1.5 KB", viewModel.Size);
|
||||
Assert.Equal("2/3", viewModel.Chunks);
|
||||
Assert.Equal(lastUsed.ToLocalTime().ToString("yyyy/MM/dd HH:mm", System.Globalization.CultureInfo.InvariantCulture), viewModel.LastUsed);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class GenerationItemViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public void MirrorsTheItem()
|
||||
{
|
||||
var item = new ProxyGenerationItem(@"C:\videos\clip.mp4", 50);
|
||||
var viewModel = new GenerationItemViewModel(item);
|
||||
var raised = new List<string?>();
|
||||
viewModel.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
|
||||
|
||||
Assert.Equal("clip.mp4", viewModel.FileName);
|
||||
Assert.Equal(@"C:\videos\clip.mp4", viewModel.SourcePath);
|
||||
Assert.True(viewModel.IsWaiting);
|
||||
Assert.Equal(Texts.StatusWaiting, viewModel.StatusText);
|
||||
Assert.Equal(0d, viewModel.Percentage);
|
||||
|
||||
item.Progress = 0.25d;
|
||||
Assert.Equal(25d, viewModel.Percentage);
|
||||
Assert.Contains(nameof(GenerationItemViewModel.Percentage), raised);
|
||||
|
||||
Assert.Same(ProxyChunkCoverage.Empty, viewModel.Coverage);
|
||||
var coverage = new ProxyChunkCoverage(4, [1], 2, 0.5d);
|
||||
item.Coverage = coverage;
|
||||
Assert.Same(coverage, viewModel.Coverage);
|
||||
Assert.Contains(nameof(GenerationItemViewModel.Coverage), raised);
|
||||
|
||||
item.Status = ProxyGenerationStatus.Generating;
|
||||
Assert.False(viewModel.IsWaiting);
|
||||
Assert.Equal(Texts.StatusGenerating, viewModel.StatusText);
|
||||
Assert.Contains(nameof(GenerationItemViewModel.StatusText), raised);
|
||||
Assert.Contains(nameof(GenerationItemViewModel.IsWaiting), raised);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ProxyGenerationStatus.Completed, null)]
|
||||
[InlineData(ProxyGenerationStatus.Cancelled, null)]
|
||||
[InlineData(ProxyGenerationStatus.Failed, null)]
|
||||
[InlineData(ProxyGenerationStatus.Failed, ProxyEncodeFailure.Transparent)]
|
||||
public void DescribesEveryStatus(ProxyGenerationStatus status, ProxyEncodeFailure? failure)
|
||||
{
|
||||
var item = new ProxyGenerationItem(@"C:\videos\clip.mp4", 50) { Failure = failure, Status = status };
|
||||
|
||||
var text = new GenerationItemViewModel(item).StatusText;
|
||||
|
||||
var expected = status switch
|
||||
{
|
||||
ProxyGenerationStatus.Completed => Texts.StatusCompleted,
|
||||
ProxyGenerationStatus.Cancelled => Texts.StatusCancelled,
|
||||
_ => failure is null ? Texts.StatusFailed : string.Concat(Texts.StatusFailed, ": ", Texts.FailureTransparent),
|
||||
};
|
||||
Assert.Equal(expected, text);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ProxyEncodeFailure.FFmpegUnavailable)]
|
||||
[InlineData(ProxyEncodeFailure.SourceUnavailable)]
|
||||
[InlineData(ProxyEncodeFailure.NoFrames)]
|
||||
[InlineData(ProxyEncodeFailure.UnusableSize)]
|
||||
[InlineData(ProxyEncodeFailure.Transparent)]
|
||||
[InlineData(ProxyEncodeFailure.FFmpegFailed)]
|
||||
[InlineData(ProxyEncodeFailure.NoOutput)]
|
||||
[InlineData(ProxyEncodeFailure.SourceChanged)]
|
||||
public void EveryFailureHasALocalisedDescription(ProxyEncodeFailure failure)
|
||||
{
|
||||
var text = GenerationItemViewModel.DescribeFailure(failure);
|
||||
|
||||
Assert.False(string.IsNullOrWhiteSpace(text));
|
||||
Assert.NotEqual(failure.ToString(), text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EveryFailureIsDistinct()
|
||||
{
|
||||
var texts = Enum.GetValues<ProxyEncodeFailure>().Select(GenerationItemViewModel.DescribeFailure).ToArray();
|
||||
|
||||
Assert.Equal(texts.Length, texts.Distinct().Count());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class GenerationProgressViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public void FollowsTheSourceCollection()
|
||||
{
|
||||
var source = new ObservableCollection<ProxyGenerationItem>();
|
||||
var first = new ProxyGenerationItem(@"C:\a.mp4", 50);
|
||||
source.Add(first);
|
||||
var viewModel = new GenerationProgressViewModel(source, () => { });
|
||||
var raised = 0;
|
||||
viewModel.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(GenerationProgressViewModel.HasItems))
|
||||
raised++;
|
||||
};
|
||||
|
||||
Assert.True(viewModel.HasItems);
|
||||
Assert.Same(first, Assert.Single(viewModel.Items).Item);
|
||||
|
||||
var second = new ProxyGenerationItem(@"C:\b.mp4", 50);
|
||||
source.Add(second);
|
||||
Assert.Equal(2, viewModel.Items.Count);
|
||||
Assert.Same(second, viewModel.Items[1].Item);
|
||||
|
||||
source.Remove(first);
|
||||
Assert.Same(second, Assert.Single(viewModel.Items).Item);
|
||||
|
||||
source.Clear();
|
||||
Assert.Empty(viewModel.Items);
|
||||
Assert.False(viewModel.HasItems);
|
||||
Assert.Equal(3, raised);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCancelCommandCancelsEverythingWhileItemsExist()
|
||||
{
|
||||
var source = new ObservableCollection<ProxyGenerationItem>();
|
||||
var cancelled = 0;
|
||||
var viewModel = new GenerationProgressViewModel(source, () => cancelled++);
|
||||
|
||||
Assert.False(viewModel.CancelCommand.CanExecute(null));
|
||||
|
||||
source.Add(new ProxyGenerationItem(@"C:.mp4", 50));
|
||||
Assert.True(viewModel.CancelCommand.CanExecute(null));
|
||||
viewModel.CancelCommand.Execute(null);
|
||||
|
||||
Assert.Equal(1, cancelled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InsertsAtTheSourcePosition()
|
||||
{
|
||||
var source = new ObservableCollection<ProxyGenerationItem> { new(@"C:\a.mp4", 50), new(@"C:\c.mp4", 50) };
|
||||
var viewModel = new GenerationProgressViewModel(source, () => { });
|
||||
|
||||
var inserted = new ProxyGenerationItem(@"C:\b.mp4", 50);
|
||||
source.Insert(1, inserted);
|
||||
|
||||
Assert.Same(inserted, viewModel.Items[1].Item);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class GenerationProgressWindowHostTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(0, true, false, false)]
|
||||
[InlineData(1, true, false, true)]
|
||||
[InlineData(1, false, false, false)]
|
||||
[InlineData(1, true, true, false)]
|
||||
[InlineData(0, false, true, false)]
|
||||
public void TheWindowShowsOnlyForItemsWhenEnabledAndNotHidden(int count, bool enabled, bool hidden, bool expected)
|
||||
=> Assert.Equal(expected, GenerationProgressWindowHost.ShouldShow(count, enabled, hidden));
|
||||
}
|
||||
|
||||
public sealed class ProxyForgeSettingsViewModelTests : IDisposable
|
||||
{
|
||||
readonly string root = Path.Combine(Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N"));
|
||||
readonly ProxyCache cache;
|
||||
readonly ProxyGenerationQueue queue;
|
||||
readonly ProxyForgeSettings settings = new();
|
||||
bool first;
|
||||
bool ffmpeg = true;
|
||||
int moved;
|
||||
|
||||
public ProxyForgeSettingsViewModelTests()
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
cache = new ProxyCache(Path.Combine(root, "cache"));
|
||||
queue = new ProxyGenerationQueue(cache, (_, _) => throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegFailed, "boom"), () => new ProxyEncodeOptions(50, 30, 10, false), () => ExportPhase.Idle, new SourceFocus(), _ => { }, TestUiThread.Post);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(root, true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
ProxyForgeSettingsViewModel Create()
|
||||
=> new(settings, cache, queue, () => first, () => { moved++; first = true; }, () => ffmpeg);
|
||||
|
||||
ProxyCacheEntry Seed(string name, int length)
|
||||
{
|
||||
var path = Path.Combine(root, name);
|
||||
File.WriteAllBytes(path, new byte[10]);
|
||||
var identity = SourceIdentity.Of(path)!.Value;
|
||||
var temporary = cache.CreateTemporaryPath();
|
||||
File.WriteAllBytes(temporary, new byte[length]);
|
||||
var registered = cache.Register(new ProxyCacheEntry
|
||||
{
|
||||
SourcePath = identity.Path,
|
||||
SourceLength = identity.Length,
|
||||
SourceWriteTimeTicks = identity.WriteTimeTicks,
|
||||
Scale = 50,
|
||||
ProxyWidth = 2,
|
||||
ProxyHeight = 2,
|
||||
DisplayWidth = 4f,
|
||||
DisplayHeight = 4f,
|
||||
FrameRateNumerator = 30,
|
||||
FrameRateDenominator = 1,
|
||||
DurationTicks = 1,
|
||||
FrameCount = 2,
|
||||
ChunkLength = 1,
|
||||
});
|
||||
return cache.AddChunk(registered.Id, 0, temporary)!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReportsTheOrderTheFFmpegAndTheCache()
|
||||
{
|
||||
Seed("a.mp4", 100);
|
||||
Seed("b.mp4", 200);
|
||||
|
||||
var viewModel = Create();
|
||||
|
||||
Assert.False(viewModel.IsPluginFirst);
|
||||
Assert.Equal(Texts.PluginOrderNotFirst, viewModel.PluginOrderText);
|
||||
Assert.Equal(Texts.FFmpegAvailable, viewModel.FFmpegText);
|
||||
Assert.Equal(string.Format(Texts.GenerationCountFormat, 0), viewModel.GenerationText);
|
||||
Assert.Equal(2, viewModel.Entries.Count);
|
||||
Assert.Equal(string.Format(Texts.CacheSummaryFormat, 2, "300 B"), viewModel.CacheSummary);
|
||||
Assert.Same(viewModel.Settings, settings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ListsTheMostRecentlyUsedFirst()
|
||||
{
|
||||
var older = Seed("a.mp4", 100);
|
||||
Thread.Sleep(20);
|
||||
var newer = Seed("b.mp4", 100);
|
||||
|
||||
var viewModel = Create();
|
||||
|
||||
Assert.Equal(newer.Id, viewModel.Entries[0].Id);
|
||||
Assert.Equal(older.Id, viewModel.Entries[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MoveToFrontUsesTheHostSettingsAndUpdatesTheText()
|
||||
{
|
||||
var viewModel = Create();
|
||||
Assert.True(viewModel.MoveToFrontCommand.CanExecute(null));
|
||||
|
||||
viewModel.MoveToFrontCommand.Execute(null);
|
||||
|
||||
Assert.Equal(1, moved);
|
||||
Assert.True(viewModel.IsPluginFirst);
|
||||
Assert.Equal(Texts.PluginOrderFirst, viewModel.PluginOrderText);
|
||||
Assert.False(viewModel.MoveToFrontCommand.CanExecute(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMissingFFmpegIsReported()
|
||||
{
|
||||
ffmpeg = false;
|
||||
|
||||
Assert.Equal(Texts.FFmpegUnavailable, Create().FFmpegText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RemoveDeletesTheSelectedEntry()
|
||||
{
|
||||
var kept = Seed("a.mp4", 100);
|
||||
var removed = Seed("b.mp4", 100);
|
||||
var viewModel = Create();
|
||||
Assert.False(viewModel.RemoveEntryCommand.CanExecute(null));
|
||||
viewModel.SelectedEntry = viewModel.Entries.Single(entry => entry.Id == removed.Id);
|
||||
Assert.True(viewModel.RemoveEntryCommand.CanExecute(null));
|
||||
|
||||
viewModel.RemoveEntryCommand.Execute(null);
|
||||
|
||||
Assert.Equal(kept.Id, Assert.Single(viewModel.Entries).Id);
|
||||
Assert.Null(viewModel.SelectedEntry);
|
||||
Assert.Equal(1, cache.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearDeletesEverythingAndForgetsFailures()
|
||||
{
|
||||
Seed("a.mp4", 100);
|
||||
var failedPath = Path.Combine(root, "failed.mp4");
|
||||
File.WriteAllBytes(failedPath, new byte[10]);
|
||||
var failed = SourceIdentity.Of(failedPath)!.Value;
|
||||
queue.TryEnqueue(failed, 50);
|
||||
await queue.WhenIdleAsync();
|
||||
Assert.True(queue.HasFailed(failed, 50));
|
||||
var viewModel = Create();
|
||||
Assert.True(viewModel.ClearCommand.CanExecute(null));
|
||||
|
||||
viewModel.ClearCommand.Execute(null);
|
||||
|
||||
Assert.Empty(viewModel.Entries);
|
||||
Assert.Equal(0, cache.Count);
|
||||
Assert.False(queue.HasFailed(failed, 50));
|
||||
Assert.False(viewModel.ClearCommand.CanExecute(null));
|
||||
Assert.Equal(string.Format(Texts.CacheSummaryFormat, 0, "0 B"), viewModel.CacheSummary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefreshPicksUpExternalChanges()
|
||||
{
|
||||
var viewModel = Create();
|
||||
Assert.Empty(viewModel.Entries);
|
||||
Seed("a.mp4", 100);
|
||||
|
||||
viewModel.RefreshCommand.Execute(null);
|
||||
|
||||
Assert.Single(viewModel.Entries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoweringTheLimitTrimsTheCacheAndRefreshes()
|
||||
{
|
||||
Seed("a.mp4", 100);
|
||||
Thread.Sleep(20);
|
||||
Seed("b.mp4", 100);
|
||||
var viewModel = Create();
|
||||
Assert.Equal(2, viewModel.Entries.Count);
|
||||
cache.LimitBytes = 150;
|
||||
|
||||
settings.CacheLimitGigabytes = settings.CacheLimitGigabytes + 1;
|
||||
|
||||
Assert.Single(viewModel.Entries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheGenerationCountFollowsTheQueue()
|
||||
{
|
||||
var viewModel = Create();
|
||||
|
||||
queue.Items.Add(new ProxyGenerationItem(@"C:\a.mp4", 50));
|
||||
|
||||
Assert.Equal(string.Format(Texts.GenerationCountFormat, 1), viewModel.GenerationText);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
internal static class Ymm4AssemblyResolver
|
||||
{
|
||||
const string MetadataKey = "Ymm4Directory";
|
||||
const string AssemblyExtension = ".dll";
|
||||
const string UserDirectoryName = "user";
|
||||
|
||||
public static string Directory { get; } = ReadDirectory();
|
||||
|
||||
public static bool IsConfigured => Directory.Length != 0 && System.IO.Directory.Exists(Directory);
|
||||
|
||||
[ModuleInitializer]
|
||||
internal static void Initialize()
|
||||
{
|
||||
if (!IsConfigured)
|
||||
return;
|
||||
|
||||
System.IO.Directory.CreateDirectory(Path.Combine(AppContext.BaseDirectory, UserDirectoryName));
|
||||
AppDomain.CurrentDomain.AssemblyResolve += (_, arguments) =>
|
||||
{
|
||||
var name = new AssemblyName(arguments.Name).Name;
|
||||
if (name is null)
|
||||
return null;
|
||||
|
||||
var candidate = Path.Combine(Directory, name + AssemblyExtension);
|
||||
return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null;
|
||||
};
|
||||
}
|
||||
|
||||
static string ReadDirectory() => typeof(Ymm4AssemblyResolver).Assembly
|
||||
.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))
|
||||
?.Value ?? string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.IO;
|
||||
using ProxyForge.Encoding;
|
||||
|
||||
namespace ProxyForge.Tests;
|
||||
|
||||
internal static class Ymm4TestEnvironment
|
||||
{
|
||||
static readonly string BundledFFmpegDirectory = Ymm4AssemblyResolver.IsConfigured
|
||||
? Path.Combine(Ymm4AssemblyResolver.Directory, "resources", "bin", "x64", "ffmpeg")
|
||||
: string.Empty;
|
||||
|
||||
public static bool IsAvailable => BundledFFmpegDirectory.Length != 0 && File.Exists(FFmpegPath) && File.Exists(FFprobePath);
|
||||
|
||||
public static string FFmpegPath => Path.Combine(BundledFFmpegDirectory, "ffmpeg.exe");
|
||||
|
||||
public static string FFprobePath => Path.Combine(BundledFFmpegDirectory, "ffprobe.exe");
|
||||
|
||||
public static FFmpegExecutables Executables => new(FFmpegPath);
|
||||
|
||||
public static void Require()
|
||||
{
|
||||
if (!IsAvailable)
|
||||
Assert.Skip("YMM4 bundled FFmpeg is not available on this machine.");
|
||||
}
|
||||
}
|
||||
+5
-6
@@ -1,10 +1,9 @@
|
||||
<Solution>
|
||||
<Configurations>
|
||||
<Platform Name="Any CPU" />
|
||||
<Platform Name="x64" />
|
||||
</Configurations>
|
||||
<Project Path="ProxyForge/ProxyForge.csproj" />
|
||||
<Project Path="ProxyForge.Tests/ProxyForge.Tests.csproj" />
|
||||
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.csproj" />
|
||||
<Project Path="ProxyForge/ProxyForge.csproj">
|
||||
<Platform Solution="*|x64" Project="x64" />
|
||||
<Project Path="YukkuriMovieMaker.Generator/YukkuriMovieMaker.Generator.Build/YukkuriMovieMaker.Generator.Build.csproj">
|
||||
<BuildType Solution="*|*" Project="Debug" />
|
||||
<Platform Solution="*|*" Project="Any CPU" />
|
||||
</Project>
|
||||
</Solution>
|
||||
@@ -0,0 +1,435 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Cache;
|
||||
|
||||
internal sealed class ProxyCache(string directoryPath)
|
||||
{
|
||||
public const string IndexFileName = "index.json";
|
||||
public const string ChunkExtension = ".mp4";
|
||||
public const string TemporaryExtension = ".tmp";
|
||||
public const long DefaultLimitBytes = 10L * 1024L * 1024L * 1024L;
|
||||
|
||||
static readonly JsonSerializerSettings SerializerSettings = new()
|
||||
{
|
||||
Formatting = Formatting.Indented,
|
||||
Converters = { new StringEnumConverter() },
|
||||
};
|
||||
|
||||
readonly Lock gate = new();
|
||||
ProxyCacheIndex index = new();
|
||||
bool loaded;
|
||||
|
||||
public static ProxyCache Shared { get; } = new(Path.Combine(AppDirectories.UserResourceDirectory, "cache", "ProxyForge"));
|
||||
|
||||
public string DirectoryPath { get; } = directoryPath;
|
||||
|
||||
public string IndexPath => Path.Combine(DirectoryPath, IndexFileName);
|
||||
|
||||
public long LimitBytes { get; set; } = DefaultLimitBytes;
|
||||
|
||||
public long TotalBytes
|
||||
{
|
||||
get
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
return index.Entries.Sum(entry => entry.FileLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
return index.Entries.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string GetDirectoryPath(ProxyCacheEntry entry) => GetDirectoryPath(entry.Id);
|
||||
|
||||
public string GetChunkPath(ProxyCacheEntry entry, int chunk) => GetChunkPath(entry.Id, chunk);
|
||||
|
||||
public string CreateTemporaryPath()
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
Directory.CreateDirectory(DirectoryPath);
|
||||
return Path.Combine(DirectoryPath, Guid.NewGuid().ToString("N") + TemporaryExtension);
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyCacheEntry? Find(SourceIdentity source, int scale)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
var entry = index.Entries.FirstOrDefault(candidate => candidate.Matches(source, scale));
|
||||
if (entry is null)
|
||||
return null;
|
||||
|
||||
if (!Directory.Exists(GetDirectoryPath(entry)))
|
||||
{
|
||||
index.Entries.Remove(entry);
|
||||
Save();
|
||||
return null;
|
||||
}
|
||||
|
||||
entry.LastUsedTicks = DateTime.UtcNow.Ticks;
|
||||
Save();
|
||||
return entry.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyCacheEntry? Get(Guid id)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
return index.Entries.FirstOrDefault(candidate => candidate.Id == id)?.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsSkipped(SourceIdentity source)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
return index.Skips.Exists(skip => skip.Matches(source));
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyCacheEntry Register(ProxyCacheEntry layout)
|
||||
{
|
||||
if (!layout.HasValidLayout)
|
||||
throw new ArgumentException("The entry needs a positive frame count and chunk length.", nameof(layout));
|
||||
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
||||
var existing = index.Entries.FirstOrDefault(candidate => candidate.Matches(layout.Source, layout.Scale));
|
||||
if (existing is not null && existing.HasSameLayout(layout) && Directory.Exists(GetDirectoryPath(existing)))
|
||||
{
|
||||
existing.LastUsedTicks = DateTime.UtcNow.Ticks;
|
||||
Save();
|
||||
return existing.Clone();
|
||||
}
|
||||
|
||||
if (existing is not null && TryDeleteDirectory(GetDirectoryPath(existing)))
|
||||
index.Entries.Remove(existing);
|
||||
|
||||
var entry = layout.Clone();
|
||||
entry.Id = Guid.NewGuid();
|
||||
entry.Chunks = [];
|
||||
entry.FileLength = 0L;
|
||||
var now = DateTime.UtcNow.Ticks;
|
||||
entry.CreatedTicks = now;
|
||||
entry.LastUsedTicks = now;
|
||||
Directory.CreateDirectory(GetDirectoryPath(entry));
|
||||
index.Entries.Add(entry);
|
||||
Save();
|
||||
return entry.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyCacheEntry? AddChunk(Guid id, int chunk, string temporaryPath)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(temporaryPath);
|
||||
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
||||
var entry = index.Entries.FirstOrDefault(candidate => candidate.Id == id);
|
||||
if (entry is null || chunk < 0 || chunk >= entry.ChunkCount)
|
||||
{
|
||||
TryDeleteFile(temporaryPath);
|
||||
return null;
|
||||
}
|
||||
|
||||
var length = new FileInfo(temporaryPath).Length;
|
||||
var path = GetChunkPath(entry, chunk);
|
||||
Directory.CreateDirectory(GetDirectoryPath(entry));
|
||||
if (entry.HasChunk(chunk))
|
||||
entry.FileLength -= FileLengthOf(path);
|
||||
File.Move(temporaryPath, path, true);
|
||||
|
||||
if (!entry.HasChunk(chunk))
|
||||
{
|
||||
entry.Chunks.Add(chunk);
|
||||
entry.Chunks.Sort();
|
||||
}
|
||||
|
||||
entry.FileLength += length;
|
||||
entry.LastUsedTicks = DateTime.UtcNow.Ticks;
|
||||
TrimCore(entry);
|
||||
Save();
|
||||
return entry.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyCacheEntry? ForgetChunk(Guid id, int chunk)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
||||
var entry = index.Entries.FirstOrDefault(candidate => candidate.Id == id);
|
||||
if (entry is null || !entry.HasChunk(chunk))
|
||||
return entry?.Clone();
|
||||
|
||||
var path = GetChunkPath(entry, chunk);
|
||||
entry.FileLength -= FileLengthOf(path);
|
||||
entry.Chunks.Remove(chunk);
|
||||
TryDeleteFile(path);
|
||||
Save();
|
||||
return entry.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
public void AddSkip(SourceIdentity source, ProxyCacheSkipReason reason)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
index.Skips.RemoveAll(skip => skip.Matches(source));
|
||||
index.Skips.Add(new ProxyCacheSkip
|
||||
{
|
||||
SourcePath = source.Path,
|
||||
SourceLength = source.Length,
|
||||
SourceWriteTimeTicks = source.WriteTimeTicks,
|
||||
Reason = reason,
|
||||
});
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
public bool Remove(Guid id)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
var entry = index.Entries.FirstOrDefault(candidate => candidate.Id == id);
|
||||
if (entry is null)
|
||||
return false;
|
||||
if (!TryDeleteDirectory(GetDirectoryPath(entry)))
|
||||
return false;
|
||||
|
||||
index.Entries.Remove(entry);
|
||||
Save();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public int Clear()
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
var removed = 0;
|
||||
foreach (var entry in index.Entries.ToArray())
|
||||
{
|
||||
if (!TryDeleteDirectory(GetDirectoryPath(entry)))
|
||||
continue;
|
||||
|
||||
index.Entries.Remove(entry);
|
||||
removed++;
|
||||
}
|
||||
|
||||
index.Skips.Clear();
|
||||
Save();
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
public int Trim()
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
var removed = TrimCore(null);
|
||||
if (removed > 0)
|
||||
Save();
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<ProxyCacheEntry> Snapshot()
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
EnsureLoaded();
|
||||
return index.Entries.Select(entry => entry.Clone()).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
string GetDirectoryPath(Guid id) => Path.Combine(DirectoryPath, id.ToString("N"));
|
||||
|
||||
string GetChunkPath(Guid id, int chunk) => Path.Combine(GetDirectoryPath(id), chunk.ToString("D6", CultureInfo.InvariantCulture) + ChunkExtension);
|
||||
|
||||
void EnsureLoaded()
|
||||
{
|
||||
if (loaded)
|
||||
return;
|
||||
|
||||
loaded = true;
|
||||
Directory.CreateDirectory(DirectoryPath);
|
||||
var dirty = !TryReadIndex(out index);
|
||||
|
||||
dirty |= index.Entries.RemoveAll(entry => !entry.HasValidLayout || !Directory.Exists(GetDirectoryPath(entry))) > 0;
|
||||
foreach (var entry in index.Entries)
|
||||
dirty |= Reconcile(entry);
|
||||
|
||||
var known = index.Entries.Select(entry => GetDirectoryPath(entry)).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var file in Directory.EnumerateFiles(DirectoryPath))
|
||||
{
|
||||
if (!string.Equals(file, IndexPath, StringComparison.OrdinalIgnoreCase))
|
||||
TryDeleteFile(file);
|
||||
}
|
||||
|
||||
foreach (var directory in Directory.EnumerateDirectories(DirectoryPath))
|
||||
{
|
||||
if (!known.Contains(directory))
|
||||
TryDeleteDirectory(directory);
|
||||
}
|
||||
|
||||
if (dirty)
|
||||
Save();
|
||||
}
|
||||
|
||||
bool Reconcile(ProxyCacheEntry entry)
|
||||
{
|
||||
var directory = GetDirectoryPath(entry);
|
||||
var listed = entry.Chunks.Where(chunk => chunk >= 0 && chunk < entry.ChunkCount).Distinct().ToList();
|
||||
var expected = listed.ToDictionary(chunk => GetChunkPath(entry, chunk), chunk => chunk, StringComparer.OrdinalIgnoreCase);
|
||||
var present = new List<int>();
|
||||
var total = 0L;
|
||||
foreach (var file in Directory.EnumerateFiles(directory))
|
||||
{
|
||||
if (expected.TryGetValue(file, out var chunk))
|
||||
{
|
||||
present.Add(chunk);
|
||||
total += FileLengthOf(file);
|
||||
}
|
||||
else
|
||||
{
|
||||
TryDeleteFile(file);
|
||||
}
|
||||
}
|
||||
|
||||
present.Sort();
|
||||
var changed = !present.SequenceEqual(entry.Chunks) || total != entry.FileLength;
|
||||
entry.Chunks = present;
|
||||
entry.FileLength = total;
|
||||
return changed;
|
||||
}
|
||||
|
||||
bool TryReadIndex(out ProxyCacheIndex read)
|
||||
{
|
||||
read = new ProxyCacheIndex();
|
||||
if (!File.Exists(IndexPath))
|
||||
return true;
|
||||
|
||||
try
|
||||
{
|
||||
var text = File.ReadAllText(IndexPath);
|
||||
var parsed = JsonConvert.DeserializeObject<ProxyCacheIndex>(text, SerializerSettings);
|
||||
if (parsed is null)
|
||||
return false;
|
||||
|
||||
parsed.Entries ??= [];
|
||||
parsed.Skips ??= [];
|
||||
var broken = parsed.Entries.RemoveAll(entry => entry is null || entry.Id == Guid.Empty || string.IsNullOrEmpty(entry.SourcePath))
|
||||
+ parsed.Skips.RemoveAll(skip => skip is null || string.IsNullOrEmpty(skip.SourcePath));
|
||||
foreach (var entry in parsed.Entries)
|
||||
entry.Chunks ??= [];
|
||||
read = parsed;
|
||||
return broken == 0;
|
||||
}
|
||||
catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: キャッシュの索引を読めなかったため作り直します。", exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void Save()
|
||||
{
|
||||
var temporaryPath = IndexPath + TemporaryExtension;
|
||||
try
|
||||
{
|
||||
File.WriteAllText(temporaryPath, JsonConvert.SerializeObject(index, SerializerSettings));
|
||||
File.Move(temporaryPath, IndexPath, true);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: キャッシュの索引を保存できませんでした。", exception);
|
||||
}
|
||||
}
|
||||
|
||||
int TrimCore(ProxyCacheEntry? protectedEntry)
|
||||
{
|
||||
var removed = 0;
|
||||
var total = index.Entries.Sum(entry => entry.FileLength);
|
||||
var candidates = index.Entries.Where(entry => !ReferenceEquals(entry, protectedEntry)).OrderBy(entry => entry.LastUsedTicks).ToList();
|
||||
foreach (var entry in candidates)
|
||||
{
|
||||
if (total <= LimitBytes)
|
||||
break;
|
||||
if (!TryDeleteDirectory(GetDirectoryPath(entry)))
|
||||
continue;
|
||||
|
||||
index.Entries.Remove(entry);
|
||||
total -= entry.FileLength;
|
||||
removed++;
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
static long FileLengthOf(string path)
|
||||
{
|
||||
var file = new FileInfo(path);
|
||||
return file.Exists ? file.Length : 0L;
|
||||
}
|
||||
|
||||
static bool TryDeleteFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Default.Write($"ProxyForge: キャッシュのファイルを削除できませんでした。{path}", exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool TryDeleteDirectory(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(path))
|
||||
Directory.Delete(path, true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Default.Write($"ProxyForge: キャッシュのフォルダーを削除できませんでした。{path}", exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace ProxyForge.Cache;
|
||||
|
||||
internal sealed class ProxyCacheEntry
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public string SourcePath { get; set; } = string.Empty;
|
||||
|
||||
public long SourceLength { get; set; }
|
||||
|
||||
public long SourceWriteTimeTicks { get; set; }
|
||||
|
||||
public int Scale { get; set; }
|
||||
|
||||
public int ProxyWidth { get; set; }
|
||||
|
||||
public int ProxyHeight { get; set; }
|
||||
|
||||
public float DisplayLeft { get; set; }
|
||||
|
||||
public float DisplayTop { get; set; }
|
||||
|
||||
public float DisplayWidth { get; set; }
|
||||
|
||||
public float DisplayHeight { get; set; }
|
||||
|
||||
public int FrameRateNumerator { get; set; }
|
||||
|
||||
public int FrameRateDenominator { get; set; }
|
||||
|
||||
public long DurationTicks { get; set; }
|
||||
|
||||
public int FrameCount { get; set; }
|
||||
|
||||
public int ChunkLength { get; set; }
|
||||
|
||||
public List<int> Chunks { get; set; } = [];
|
||||
|
||||
public long FileLength { get; set; }
|
||||
|
||||
public long CreatedTicks { get; set; }
|
||||
|
||||
public long LastUsedTicks { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public SourceIdentity Source => new(SourcePath, SourceLength, SourceWriteTimeTicks);
|
||||
|
||||
[JsonIgnore]
|
||||
public int ChunkCount => ChunkLength <= 0 ? 0 : (FrameCount + ChunkLength - 1) / ChunkLength;
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsComplete => Chunks.Count >= ChunkCount;
|
||||
|
||||
[JsonIgnore]
|
||||
public bool HasValidLayout => ChunkLength > 0 && FrameCount > 0;
|
||||
|
||||
public bool Matches(SourceIdentity source, int scale) => Scale == scale && Source == source;
|
||||
|
||||
public bool HasChunk(int chunk) => Chunks.Contains(chunk);
|
||||
|
||||
public bool HasSameLayout(ProxyCacheEntry other)
|
||||
=> ProxyWidth == other.ProxyWidth
|
||||
&& ProxyHeight == other.ProxyHeight
|
||||
&& DisplayLeft == other.DisplayLeft
|
||||
&& DisplayTop == other.DisplayTop
|
||||
&& DisplayWidth == other.DisplayWidth
|
||||
&& DisplayHeight == other.DisplayHeight
|
||||
&& FrameRateNumerator == other.FrameRateNumerator
|
||||
&& FrameRateDenominator == other.FrameRateDenominator
|
||||
&& DurationTicks == other.DurationTicks
|
||||
&& FrameCount == other.FrameCount
|
||||
&& ChunkLength == other.ChunkLength;
|
||||
|
||||
public ProxyCacheEntry Clone()
|
||||
{
|
||||
var clone = (ProxyCacheEntry)MemberwiseClone();
|
||||
clone.Chunks = [.. Chunks];
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
|
||||
internal enum ProxyCacheSkipReason
|
||||
{
|
||||
Transparent,
|
||||
}
|
||||
|
||||
internal sealed class ProxyCacheSkip
|
||||
{
|
||||
public string SourcePath { get; set; } = string.Empty;
|
||||
|
||||
public long SourceLength { get; set; }
|
||||
|
||||
public long SourceWriteTimeTicks { get; set; }
|
||||
|
||||
public ProxyCacheSkipReason Reason { get; set; }
|
||||
|
||||
public bool Matches(SourceIdentity source) => new SourceIdentity(SourcePath, SourceLength, SourceWriteTimeTicks) == source;
|
||||
}
|
||||
|
||||
internal sealed class ProxyCacheIndex
|
||||
{
|
||||
public List<ProxyCacheEntry> Entries { get; set; } = [];
|
||||
|
||||
public List<ProxyCacheSkip> Skips { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.IO;
|
||||
|
||||
namespace ProxyForge.Cache;
|
||||
|
||||
internal readonly record struct SourceIdentity(string Path, long Length, long WriteTimeTicks)
|
||||
{
|
||||
public static SourceIdentity? Of(string path)
|
||||
{
|
||||
string fullPath;
|
||||
try
|
||||
{
|
||||
fullPath = System.IO.Path.GetFullPath(path);
|
||||
}
|
||||
catch (Exception exception) when (exception is ArgumentException or PathTooLongException or NotSupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var file = new FileInfo(fullPath);
|
||||
if (!file.Exists)
|
||||
return null;
|
||||
|
||||
return new SourceIdentity(fullPath, file.Length, file.LastWriteTimeUtc.Ticks);
|
||||
}
|
||||
|
||||
public bool Matches(string path, long length, long writeTimeTicks)
|
||||
=> Length == length
|
||||
&& WriteTimeTicks == writeTimeTicks
|
||||
&& string.Equals(Path, path, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public bool Equals(SourceIdentity other) => Matches(other.Path, other.Length, other.WriteTimeTicks);
|
||||
|
||||
public override int GetHashCode() => HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Path), Length, WriteTimeTicks);
|
||||
}
|
||||
@@ -1,614 +0,0 @@
|
||||
using ProxyForge.Interfaces;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Hashing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ProxyForge.Cache;
|
||||
|
||||
internal sealed class VideoCacheDatabase : IVideoCacheDatabase
|
||||
{
|
||||
private const long MagicNumber = 0x0042_4456_5F50_445A;
|
||||
private const int FormatVersion = 1;
|
||||
private const int HeaderSize = 32;
|
||||
private const int HeaderCrcOffset = 16;
|
||||
private const string OldDbFileName = "zerodiskproxy.vdb";
|
||||
private const string DbFileName = "proxyforge.vdb";
|
||||
private const string BackupSuffix = ".bak";
|
||||
private const string TempSuffix = ".tmp";
|
||||
|
||||
private readonly string _dbPath;
|
||||
private readonly string _backupPath;
|
||||
private readonly string _cacheDirectory;
|
||||
private readonly VideoCacheDiskStore _diskStore;
|
||||
private readonly Mutex _mutex;
|
||||
private List<VideoCacheRecord> _records;
|
||||
private int _disposed;
|
||||
|
||||
public string CacheDirectory => _cacheDirectory;
|
||||
|
||||
internal VideoCacheDatabase(string cacheDirectory)
|
||||
{
|
||||
_cacheDirectory = cacheDirectory;
|
||||
Directory.CreateDirectory(_cacheDirectory);
|
||||
_dbPath = Path.Combine(_cacheDirectory, DbFileName);
|
||||
_backupPath = _dbPath + BackupSuffix;
|
||||
|
||||
var oldDbPath = Path.Combine(_cacheDirectory, OldDbFileName);
|
||||
if (File.Exists(oldDbPath) && !File.Exists(_dbPath))
|
||||
{
|
||||
Debug.WriteLine("[VideoCacheDatabase] Starting robust data migration to ProxyForge format.");
|
||||
try
|
||||
{
|
||||
var migrationTempPath = _dbPath + ".migration.tmp";
|
||||
File.Copy(oldDbPath, migrationTempPath, true);
|
||||
|
||||
var oldBackupPath = oldDbPath + BackupSuffix;
|
||||
var migrationBackupTempPath = _backupPath + ".migration.tmp";
|
||||
var hasBackup = File.Exists(oldBackupPath);
|
||||
if (hasBackup)
|
||||
{
|
||||
File.Copy(oldBackupPath, migrationBackupTempPath, true);
|
||||
}
|
||||
|
||||
File.Move(migrationTempPath, _dbPath, true);
|
||||
if (hasBackup)
|
||||
{
|
||||
File.Move(migrationBackupTempPath, _backupPath, true);
|
||||
}
|
||||
|
||||
File.Delete(oldDbPath);
|
||||
if (hasBackup)
|
||||
{
|
||||
File.Delete(oldBackupPath);
|
||||
}
|
||||
var oldTempPath = oldDbPath + TempSuffix;
|
||||
if (File.Exists(oldTempPath))
|
||||
{
|
||||
File.Delete(oldTempPath);
|
||||
}
|
||||
|
||||
Debug.WriteLine("[VideoCacheDatabase] Migration completed successfully. Legacy files removed.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[VideoCacheDatabase] Migration failed: ", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
_diskStore = new VideoCacheDiskStore(_cacheDirectory);
|
||||
|
||||
Span<byte> hashBuf = stackalloc byte[32];
|
||||
VideoCacheRecord.ComputePathHashToSpan(_cacheDirectory.AsSpan(), hashBuf);
|
||||
Span<char> mutexName = stackalloc char[64];
|
||||
"Global\\ZDP_VDB_".AsSpan().CopyTo(mutexName);
|
||||
for (var i = 0; i < 16; i++)
|
||||
hashBuf[i].TryFormat(mutexName[(15 + i * 2)..], out _, "X2");
|
||||
_mutex = new Mutex(false, new string(mutexName[..47]));
|
||||
|
||||
_records = [];
|
||||
LoadDatabase();
|
||||
}
|
||||
|
||||
public bool TryGet(string originalPath, float scale, out VideoCacheLookupResult result)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
|
||||
Span<byte> hashBuf = stackalloc byte[VideoCacheRecord.HashBytes];
|
||||
VideoCacheRecord.ComputePathHashToSpan(originalPath.AsSpan(), hashBuf);
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
for (var i = 0; i < _records.Count; i++)
|
||||
{
|
||||
ref var rec = ref CollectionsMarshal.AsSpan(_records)[i];
|
||||
if (!rec.IsActive)
|
||||
continue;
|
||||
|
||||
if (!rec.MatchesPathAndScale(originalPath.AsSpan(), hashBuf, scale))
|
||||
continue;
|
||||
|
||||
if (!_diskStore.FileExists(rec.Uuid))
|
||||
{
|
||||
rec.Flags = 0;
|
||||
rec.RecomputeCrc32();
|
||||
ScheduleFlush();
|
||||
continue;
|
||||
}
|
||||
|
||||
rec.UpdateLastAccess();
|
||||
result = ToLookupResult(in rec);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
result = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public VideoCacheLookupResult[] GetAll()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
if (_records.Count == 0)
|
||||
return [];
|
||||
|
||||
var count = 0;
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].IsActive)
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count == 0)
|
||||
return [];
|
||||
|
||||
var results = new VideoCacheLookupResult[count];
|
||||
var idx = 0;
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].IsActive)
|
||||
results[idx++] = ToLookupResult(in span[i]);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(string originalPath, float scale, uint proxyWidth, uint proxyHeight,
|
||||
long fileSize, uint fileCrc32, Guid uuid)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
|
||||
Span<byte> hashBuf = stackalloc byte[VideoCacheRecord.HashBytes];
|
||||
VideoCacheRecord.ComputePathHashToSpan(originalPath.AsSpan(), hashBuf);
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].IsActive && span[i].MatchesPathAndScale(originalPath.AsSpan(), hashBuf, scale))
|
||||
{
|
||||
_diskStore.DeleteFile(span[i].Uuid);
|
||||
span[i].Flags = 0;
|
||||
span[i].RecomputeCrc32();
|
||||
}
|
||||
}
|
||||
|
||||
var record = new VideoCacheRecord
|
||||
{
|
||||
Uuid = uuid,
|
||||
PathLength = Math.Min(originalPath.Length, VideoCacheRecord.PathMaxChars),
|
||||
Scale = scale,
|
||||
ProxyWidth = proxyWidth,
|
||||
ProxyHeight = proxyHeight,
|
||||
FileSize = fileSize,
|
||||
CreatedAtTicks = DateTime.UtcNow.Ticks,
|
||||
LastAccessedTicks = DateTime.UtcNow.Ticks,
|
||||
Flags = VideoCacheRecord.FlagActive,
|
||||
FileCrc32 = fileCrc32
|
||||
};
|
||||
|
||||
VideoCacheRecord.ComputePathHash(originalPath.AsSpan(), ref record.PathHash);
|
||||
WritePathToRecord(originalPath, ref record);
|
||||
record.RecomputeCrc32();
|
||||
|
||||
_records.Add(record);
|
||||
}
|
||||
|
||||
FlushToFile();
|
||||
}
|
||||
|
||||
public bool Remove(Guid uuid)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].Uuid == uuid && span[i].IsActive)
|
||||
{
|
||||
_diskStore.DeleteFile(span[i].Uuid);
|
||||
span[i].Flags = 0;
|
||||
span[i].RecomputeCrc32();
|
||||
FlushToFile();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int RemoveByPath(string originalPath)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
|
||||
Span<byte> hashBuf = stackalloc byte[VideoCacheRecord.HashBytes];
|
||||
VideoCacheRecord.ComputePathHashToSpan(originalPath.AsSpan(), hashBuf);
|
||||
var removed = 0;
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (!span[i].IsActive)
|
||||
continue;
|
||||
|
||||
if (!span[i].MatchesPath(originalPath.AsSpan(), hashBuf))
|
||||
continue;
|
||||
|
||||
_diskStore.DeleteFile(span[i].Uuid);
|
||||
span[i].Flags = 0;
|
||||
span[i].RecomputeCrc32();
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
|
||||
if (removed > 0)
|
||||
FlushToFile();
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
public int ClearAll()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
|
||||
int count;
|
||||
lock (_records)
|
||||
{
|
||||
count = 0;
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].IsActive)
|
||||
{
|
||||
_diskStore.DeleteFile(span[i].Uuid);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
_records.Clear();
|
||||
}
|
||||
|
||||
FlushToFile();
|
||||
return count;
|
||||
}
|
||||
|
||||
public void UpdateLastAccess(Guid uuid)
|
||||
{
|
||||
lock (_records)
|
||||
{
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].Uuid == uuid)
|
||||
{
|
||||
span[i].UpdateLastAccess();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string GetCacheFilePath(Guid uuid) =>
|
||||
_diskStore.GetFilePath(uuid);
|
||||
|
||||
internal VideoCacheDiskStore DiskStore => _diskStore;
|
||||
|
||||
private void LoadDatabase()
|
||||
{
|
||||
_mutex.WaitOne();
|
||||
try
|
||||
{
|
||||
if (TryLoadFromFile(_dbPath))
|
||||
return;
|
||||
|
||||
Debug.WriteLine("[VideoCacheDatabase] Primary DB failed, trying backup");
|
||||
if (TryLoadFromFile(_backupPath))
|
||||
{
|
||||
FlushToFileCore();
|
||||
return;
|
||||
}
|
||||
|
||||
Debug.WriteLine("[VideoCacheDatabase] Both DB files failed, rebuilding from disk");
|
||||
RebuildFromDisk();
|
||||
FlushToFileCore();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_mutex.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLoadFromFile(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(
|
||||
path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536,
|
||||
FileOptions.SequentialScan);
|
||||
|
||||
if (fs.Length < HeaderSize)
|
||||
return false;
|
||||
|
||||
Span<byte> headerBuf = stackalloc byte[HeaderSize];
|
||||
if (fs.Read(headerBuf) < HeaderSize)
|
||||
return false;
|
||||
|
||||
var magic = MemoryMarshal.Read<long>(headerBuf);
|
||||
if (magic != MagicNumber)
|
||||
return false;
|
||||
|
||||
var version = MemoryMarshal.Read<int>(headerBuf[8..]);
|
||||
if (version != FormatVersion)
|
||||
return false;
|
||||
|
||||
var headerCrc = MemoryMarshal.Read<uint>(headerBuf[HeaderCrcOffset..]);
|
||||
headerBuf.Slice(HeaderCrcOffset, 4).Clear();
|
||||
var computedHeaderCrc = Crc32.HashToUInt32(headerBuf[..HeaderCrcOffset]);
|
||||
if (headerCrc != computedHeaderCrc)
|
||||
return false;
|
||||
|
||||
var recordCount = MemoryMarshal.Read<int>(headerBuf[12..]);
|
||||
if (recordCount < 0 || recordCount > 100_000)
|
||||
return false;
|
||||
|
||||
var expectedSize = HeaderSize + (long)recordCount * VideoCacheRecord.RecordSize;
|
||||
if (fs.Length < expectedSize)
|
||||
return false;
|
||||
|
||||
var records = new List<VideoCacheRecord>(recordCount);
|
||||
var recordBuf = new byte[VideoCacheRecord.RecordSize];
|
||||
var repairNeeded = false;
|
||||
|
||||
for (var i = 0; i < recordCount; i++)
|
||||
{
|
||||
if (fs.Read(recordBuf) < VideoCacheRecord.RecordSize)
|
||||
break;
|
||||
|
||||
var record = MemoryMarshal.Read<VideoCacheRecord>(recordBuf);
|
||||
|
||||
if (!record.ValidateCrc32())
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[VideoCacheDatabase] Corrupt record at index ", i.ToString()));
|
||||
if (TryRepairRecord(ref record))
|
||||
{
|
||||
repairNeeded = true;
|
||||
records.Add(record);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (record.IsActive && !_diskStore.FileExists(record.Uuid))
|
||||
{
|
||||
record.Flags = 0;
|
||||
record.RecomputeCrc32();
|
||||
repairNeeded = true;
|
||||
}
|
||||
|
||||
records.Add(record);
|
||||
}
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
_records = records;
|
||||
}
|
||||
|
||||
if (repairNeeded)
|
||||
FlushToFileCore();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[VideoCacheDatabase] Load failed: ", ex.Message));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryRepairRecord(ref VideoCacheRecord record)
|
||||
{
|
||||
if (!_diskStore.FileExists(record.Uuid))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var fileSize = _diskStore.GetFileSize(record.Uuid);
|
||||
if (fileSize <= 0)
|
||||
return false;
|
||||
|
||||
record.FileSize = fileSize;
|
||||
record.FileCrc32 = _diskStore.ComputeFileCrc32(record.Uuid);
|
||||
record.Flags = VideoCacheRecord.FlagActive;
|
||||
record.LastAccessedTicks = DateTime.UtcNow.Ticks;
|
||||
record.RecomputeCrc32();
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RebuildFromDisk()
|
||||
{
|
||||
var records = new List<VideoCacheRecord>();
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(_cacheDirectory, "*.mp4"))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
if (!Guid.TryParse(name, out var uuid))
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(file);
|
||||
if (!info.Exists || info.Length == 0)
|
||||
continue;
|
||||
|
||||
var record = new VideoCacheRecord
|
||||
{
|
||||
Uuid = uuid,
|
||||
PathLength = 0,
|
||||
Scale = 0.5f,
|
||||
ProxyWidth = 0,
|
||||
ProxyHeight = 0,
|
||||
FileSize = info.Length,
|
||||
CreatedAtTicks = info.CreationTimeUtc.Ticks,
|
||||
LastAccessedTicks = info.LastAccessTimeUtc.Ticks,
|
||||
Flags = VideoCacheRecord.FlagActive,
|
||||
FileCrc32 = _diskStore.ComputeFileCrc32(uuid)
|
||||
};
|
||||
record.RecomputeCrc32();
|
||||
records.Add(record);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
lock (_records)
|
||||
{
|
||||
_records = records;
|
||||
}
|
||||
}
|
||||
|
||||
private void FlushToFile()
|
||||
{
|
||||
_mutex.WaitOne();
|
||||
try
|
||||
{
|
||||
FlushToFileCore();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_mutex.ReleaseMutex();
|
||||
}
|
||||
}
|
||||
|
||||
private void FlushToFileCore()
|
||||
{
|
||||
List<VideoCacheRecord> snapshot;
|
||||
lock (_records)
|
||||
{
|
||||
snapshot = new List<VideoCacheRecord>(_records.Count);
|
||||
var span = CollectionsMarshal.AsSpan(_records);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
if (span[i].IsActive)
|
||||
snapshot.Add(span[i]);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (File.Exists(_dbPath))
|
||||
{
|
||||
try { File.Copy(_dbPath, _backupPath, true); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
var tempPath = _dbPath + TempSuffix;
|
||||
|
||||
using (var fs = new FileStream(
|
||||
tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536,
|
||||
FileOptions.WriteThrough))
|
||||
{
|
||||
WriteHeader(fs, snapshot.Count);
|
||||
|
||||
var span = CollectionsMarshal.AsSpan(snapshot);
|
||||
for (var i = 0; i < span.Length; i++)
|
||||
{
|
||||
WriteRecord(fs, in span[i]);
|
||||
}
|
||||
|
||||
fs.Flush(true);
|
||||
}
|
||||
|
||||
File.Move(tempPath, _dbPath, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[VideoCacheDatabase] Flush failed: ", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteHeader(FileStream fs, int recordCount)
|
||||
{
|
||||
Span<byte> header = stackalloc byte[HeaderSize];
|
||||
header.Clear();
|
||||
var magic = MagicNumber;
|
||||
var version = FormatVersion;
|
||||
MemoryMarshal.Write(header, in magic);
|
||||
MemoryMarshal.Write(header[8..], in version);
|
||||
MemoryMarshal.Write(header[12..], in recordCount);
|
||||
var crc = Crc32.HashToUInt32(header[..HeaderCrcOffset]);
|
||||
MemoryMarshal.Write(header[HeaderCrcOffset..], in crc);
|
||||
fs.Write(header);
|
||||
}
|
||||
|
||||
private static void WriteRecord(FileStream fs, in VideoCacheRecord record)
|
||||
{
|
||||
ReadOnlySpan<byte> span = MemoryMarshal.CreateReadOnlySpan(
|
||||
ref Unsafe.As<VideoCacheRecord, byte>(ref Unsafe.AsRef(in record)),
|
||||
VideoCacheRecord.RecordSize);
|
||||
fs.Write(span);
|
||||
}
|
||||
|
||||
private void ScheduleFlush()
|
||||
{
|
||||
_ = Task.Run(() =>
|
||||
{
|
||||
try { FlushToFile(); }
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void WritePathToRecord(string path, ref VideoCacheRecord record)
|
||||
{
|
||||
Span<byte> raw = record.PathChars;
|
||||
raw.Clear();
|
||||
var chars = MemoryMarshal.Cast<byte, char>(raw);
|
||||
var len = Math.Min(path.Length, VideoCacheRecord.PathMaxChars);
|
||||
path.AsSpan(0, len).CopyTo(chars);
|
||||
record.PathLength = len;
|
||||
}
|
||||
|
||||
private static VideoCacheLookupResult ToLookupResult(in VideoCacheRecord rec) =>
|
||||
new(rec.Uuid,
|
||||
rec.GetOriginalPath(),
|
||||
rec.GetFileName(),
|
||||
rec.Scale,
|
||||
rec.ProxyWidth,
|
||||
rec.ProxyHeight,
|
||||
rec.FileSize,
|
||||
rec.FileCrc32,
|
||||
new DateTime(rec.CreatedAtTicks, DateTimeKind.Utc),
|
||||
new DateTime(rec.LastAccessedTicks, DateTimeKind.Utc));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
FlushToFile();
|
||||
}
|
||||
catch { }
|
||||
|
||||
_mutex.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
using ProxyForge.Memory;
|
||||
using System.IO;
|
||||
using System.IO.Hashing;
|
||||
|
||||
namespace ProxyForge.Cache;
|
||||
|
||||
internal sealed class VideoCacheDiskStore
|
||||
{
|
||||
private readonly string _cacheDirectory;
|
||||
|
||||
internal VideoCacheDiskStore(string cacheDirectory)
|
||||
{
|
||||
_cacheDirectory = cacheDirectory;
|
||||
Directory.CreateDirectory(_cacheDirectory);
|
||||
}
|
||||
|
||||
internal string GetFilePath(Guid uuid)
|
||||
{
|
||||
Span<char> buf = stackalloc char[36 + 4];
|
||||
uuid.TryFormat(buf, out _, "D");
|
||||
".mp4".AsSpan().CopyTo(buf[36..]);
|
||||
return Path.Combine(_cacheDirectory, new string(buf));
|
||||
}
|
||||
|
||||
internal bool FileExists(Guid uuid) =>
|
||||
File.Exists(GetFilePath(uuid));
|
||||
|
||||
internal long GetFileSize(Guid uuid)
|
||||
{
|
||||
var path = GetFilePath(uuid);
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
return info.Exists ? info.Length : 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
internal void SaveFromEntry(Guid uuid, byte[] data, int length)
|
||||
{
|
||||
var path = GetFilePath(uuid);
|
||||
using var fs = new FileStream(
|
||||
path, FileMode.Create, FileAccess.Write, FileShare.None, 65536,
|
||||
FileOptions.SequentialScan | FileOptions.WriteThrough);
|
||||
fs.Write(data, 0, length);
|
||||
fs.Flush(true);
|
||||
}
|
||||
|
||||
internal void SaveFromStream(Guid uuid, Stream source)
|
||||
{
|
||||
var path = GetFilePath(uuid);
|
||||
var buf = BufferPool.Rent(65536);
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(
|
||||
path, FileMode.Create, FileAccess.Write, FileShare.None, 65536,
|
||||
FileOptions.SequentialScan | FileOptions.WriteThrough);
|
||||
|
||||
int read;
|
||||
while ((read = source.Read(buf, 0, buf.Length)) > 0)
|
||||
fs.Write(buf, 0, read);
|
||||
|
||||
fs.Flush(true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferPool.Return(buf);
|
||||
}
|
||||
}
|
||||
|
||||
internal void CopyFromFile(Guid uuid, string sourcePath)
|
||||
{
|
||||
var destPath = GetFilePath(uuid);
|
||||
var buf = BufferPool.Rent(65536);
|
||||
try
|
||||
{
|
||||
using var src = new FileStream(
|
||||
sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536,
|
||||
FileOptions.SequentialScan);
|
||||
using var dst = new FileStream(
|
||||
destPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536,
|
||||
FileOptions.SequentialScan | FileOptions.WriteThrough);
|
||||
|
||||
int read;
|
||||
while ((read = src.Read(buf, 0, buf.Length)) > 0)
|
||||
dst.Write(buf, 0, read);
|
||||
|
||||
dst.Flush(true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferPool.Return(buf);
|
||||
}
|
||||
}
|
||||
|
||||
internal bool DeleteFile(Guid uuid)
|
||||
{
|
||||
var path = GetFilePath(uuid);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
return false;
|
||||
File.Delete(path);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal uint ComputeFileCrc32(Guid uuid)
|
||||
{
|
||||
var path = GetFilePath(uuid);
|
||||
if (!File.Exists(path))
|
||||
return 0;
|
||||
|
||||
var buf = BufferPool.Rent(65536);
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(
|
||||
path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536,
|
||||
FileOptions.SequentialScan);
|
||||
|
||||
var crc = new Crc32();
|
||||
int read;
|
||||
while ((read = fs.Read(buf, 0, buf.Length)) > 0)
|
||||
crc.Append(buf.AsSpan(0, read));
|
||||
|
||||
Span<byte> hash = stackalloc byte[4];
|
||||
crc.GetHashAndReset(hash);
|
||||
return System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(hash);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferPool.Return(buf);
|
||||
}
|
||||
}
|
||||
|
||||
internal uint ComputeFileCrc32FromPath(string filePath)
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
return 0;
|
||||
|
||||
var buf = BufferPool.Rent(65536);
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(
|
||||
filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536,
|
||||
FileOptions.SequentialScan);
|
||||
|
||||
var crc = new Crc32();
|
||||
int read;
|
||||
while ((read = fs.Read(buf, 0, buf.Length)) > 0)
|
||||
crc.Append(buf.AsSpan(0, read));
|
||||
|
||||
Span<byte> hash = stackalloc byte[4];
|
||||
crc.GetHashAndReset(hash);
|
||||
return System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(hash);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferPool.Return(buf);
|
||||
}
|
||||
}
|
||||
|
||||
internal int CleanupOrphanedFiles(HashSet<Guid> knownUuids)
|
||||
{
|
||||
var removed = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(_cacheDirectory, "*.mp4"))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
if (Guid.TryParse(name, out var uuid) && !knownUuids.Contains(uuid))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
removed++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
using System.IO.Hashing;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace ProxyForge.Cache;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1)]
|
||||
internal struct VideoCacheRecord : IEquatable<VideoCacheRecord>
|
||||
{
|
||||
internal const int PathMaxChars = 260;
|
||||
internal const int PathBufferBytes = PathMaxChars * 2;
|
||||
internal const int HashBytes = 32;
|
||||
internal const int ReservedBytes = 36;
|
||||
internal const int RecordSize = 656;
|
||||
internal const int CrcOffset = 616;
|
||||
|
||||
internal Guid Uuid;
|
||||
internal PathHashBuffer PathHash;
|
||||
internal int PathLength;
|
||||
internal PathCharBuffer PathChars;
|
||||
internal float Scale;
|
||||
internal uint ProxyWidth;
|
||||
internal uint ProxyHeight;
|
||||
internal long FileSize;
|
||||
internal long CreatedAtTicks;
|
||||
internal long LastAccessedTicks;
|
||||
internal int Flags;
|
||||
internal uint FileCrc32;
|
||||
internal uint RecordCrc32;
|
||||
internal ReservedBuffer Reserved;
|
||||
|
||||
[InlineArray(HashBytes)]
|
||||
internal struct PathHashBuffer
|
||||
{
|
||||
private byte _element;
|
||||
}
|
||||
|
||||
[InlineArray(PathBufferBytes)]
|
||||
internal struct PathCharBuffer
|
||||
{
|
||||
private byte _element;
|
||||
}
|
||||
|
||||
[InlineArray(ReservedBytes)]
|
||||
internal struct ReservedBuffer
|
||||
{
|
||||
private byte _element;
|
||||
}
|
||||
|
||||
internal const int FlagActive = 1;
|
||||
|
||||
internal readonly bool IsActive
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => (Flags & FlagActive) != 0;
|
||||
}
|
||||
|
||||
internal static VideoCacheRecord Create(
|
||||
string originalPath, float scale, uint proxyWidth, uint proxyHeight,
|
||||
long fileSize, uint fileCrc32)
|
||||
{
|
||||
var record = new VideoCacheRecord
|
||||
{
|
||||
Uuid = Guid.NewGuid(),
|
||||
PathLength = Math.Min(originalPath.Length, PathMaxChars),
|
||||
Scale = scale,
|
||||
ProxyWidth = proxyWidth,
|
||||
ProxyHeight = proxyHeight,
|
||||
FileSize = fileSize,
|
||||
CreatedAtTicks = DateTime.UtcNow.Ticks,
|
||||
LastAccessedTicks = DateTime.UtcNow.Ticks,
|
||||
Flags = FlagActive,
|
||||
FileCrc32 = fileCrc32
|
||||
};
|
||||
|
||||
ComputePathHash(originalPath, ref record.PathHash);
|
||||
WritePathChars(originalPath, ref record.PathChars, record.PathLength);
|
||||
record.RecordCrc32 = record.ComputeCrc32();
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
internal readonly string GetOriginalPath()
|
||||
{
|
||||
ReadOnlySpan<byte> raw = PathChars;
|
||||
var chars = MemoryMarshal.Cast<byte, char>(raw);
|
||||
return new string(chars[..PathLength]);
|
||||
}
|
||||
|
||||
internal readonly string GetFileName()
|
||||
{
|
||||
ReadOnlySpan<byte> raw = PathChars;
|
||||
var chars = MemoryMarshal.Cast<byte, char>(raw)[..PathLength];
|
||||
var lastSep = chars.LastIndexOfAny('\\', '/');
|
||||
return lastSep >= 0 ? new string(chars[(lastSep + 1)..]) : new string(chars);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal readonly bool MatchesPath(ReadOnlySpan<char> path, ReadOnlySpan<byte> pathHash)
|
||||
{
|
||||
ReadOnlySpan<byte> storedHash = PathHash;
|
||||
if (!storedHash.SequenceEqual(pathHash))
|
||||
return false;
|
||||
|
||||
ReadOnlySpan<byte> raw = PathChars;
|
||||
var storedPath = MemoryMarshal.Cast<byte, char>(raw)[..PathLength];
|
||||
return storedPath.Equals(path, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal readonly bool MatchesPathAndScale(ReadOnlySpan<char> path, ReadOnlySpan<byte> pathHash, float scale)
|
||||
{
|
||||
return Scale == scale && MatchesPath(path, pathHash);
|
||||
}
|
||||
|
||||
internal readonly bool ValidateCrc32()
|
||||
{
|
||||
return RecordCrc32 == ComputeCrc32();
|
||||
}
|
||||
|
||||
internal void RecomputeCrc32()
|
||||
{
|
||||
RecordCrc32 = ComputeCrc32();
|
||||
}
|
||||
|
||||
internal void UpdateLastAccess()
|
||||
{
|
||||
LastAccessedTicks = DateTime.UtcNow.Ticks;
|
||||
RecomputeCrc32();
|
||||
}
|
||||
|
||||
private readonly uint ComputeCrc32()
|
||||
{
|
||||
ReadOnlySpan<byte> span = MemoryMarshal.CreateReadOnlySpan(
|
||||
ref Unsafe.As<VideoCacheRecord, byte>(ref Unsafe.AsRef(in this)),
|
||||
CrcOffset);
|
||||
return Crc32.HashToUInt32(span);
|
||||
}
|
||||
|
||||
internal static void ComputePathHash(ReadOnlySpan<char> path, ref PathHashBuffer hash)
|
||||
{
|
||||
Span<char> upper = stackalloc char[Math.Min(path.Length, PathMaxChars)];
|
||||
path[..upper.Length].ToUpperInvariant(upper);
|
||||
var bytes = MemoryMarshal.AsBytes(upper);
|
||||
Span<byte> dest = hash;
|
||||
SHA256.TryHashData(bytes, dest, out _);
|
||||
}
|
||||
|
||||
internal static void ComputePathHashToSpan(ReadOnlySpan<char> path, Span<byte> dest)
|
||||
{
|
||||
Span<char> upper = stackalloc char[Math.Min(path.Length, PathMaxChars)];
|
||||
path[..upper.Length].ToUpperInvariant(upper);
|
||||
var bytes = MemoryMarshal.AsBytes(upper);
|
||||
SHA256.TryHashData(bytes, dest, out _);
|
||||
}
|
||||
|
||||
private static void WritePathChars(string path, ref PathCharBuffer buffer, int length)
|
||||
{
|
||||
Span<byte> raw = buffer;
|
||||
raw.Clear();
|
||||
var chars = MemoryMarshal.Cast<byte, char>(raw);
|
||||
path.AsSpan(0, length).CopyTo(chars);
|
||||
}
|
||||
|
||||
public readonly bool Equals(VideoCacheRecord other) =>
|
||||
Uuid.Equals(other.Uuid);
|
||||
|
||||
public override readonly bool Equals(object? obj) =>
|
||||
obj is VideoCacheRecord other && Equals(other);
|
||||
|
||||
public override readonly int GetHashCode() => Uuid.GetHashCode();
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace ProxyForge.Core;
|
||||
|
||||
internal readonly record struct EncoderConfig(
|
||||
bool EnableHardwareAcceleration,
|
||||
bool EnableDiskFallback
|
||||
);
|
||||
@@ -1,193 +0,0 @@
|
||||
using ProxyForge.Interfaces;
|
||||
using ProxyForge.Interop;
|
||||
using ProxyForge.Memory;
|
||||
using ProxyForge.Progress;
|
||||
using System.IO;
|
||||
using Windows.Foundation;
|
||||
using Windows.Media.MediaProperties;
|
||||
using Windows.Media.Transcoding;
|
||||
using Windows.Storage;
|
||||
|
||||
namespace ProxyForge.Core;
|
||||
|
||||
internal sealed class MfProxyEncoder : IProxyEncoder
|
||||
{
|
||||
private readonly MemoryBudget _memoryBudget;
|
||||
private readonly string _fallbackDirectory;
|
||||
private readonly EncoderConfig _config;
|
||||
private int _disposed;
|
||||
|
||||
internal MfProxyEncoder(MemoryBudget memoryBudget, string fallbackDirectory, EncoderConfig config)
|
||||
{
|
||||
_memoryBudget = memoryBudget;
|
||||
_fallbackDirectory = fallbackDirectory;
|
||||
_config = config;
|
||||
}
|
||||
|
||||
public async Task<ProxyCacheEntry> EncodeAsync(
|
||||
string inputPath, float scale, float bitrateFactor, int gopSize,
|
||||
ProxyGenerationItem? progressItem, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
ValidateInputPath(inputPath);
|
||||
|
||||
Directory.CreateDirectory(_fallbackDirectory);
|
||||
|
||||
Span<char> fileNameBuf = stackalloc char[40];
|
||||
"zdp_".AsSpan().CopyTo(fileNameBuf);
|
||||
Guid.NewGuid().TryFormat(fileNameBuf[4..], out _, "N");
|
||||
".mp4".AsSpan().CopyTo(fileNameBuf[36..]);
|
||||
var tempFileName = new string(fileNameBuf);
|
||||
|
||||
var tempPath = Path.Combine(_fallbackDirectory, tempFileName);
|
||||
ValidateTempPath(tempPath);
|
||||
|
||||
ProxyCacheEntry? entry = null;
|
||||
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var inputFile = await StorageFile.GetFileFromPathAsync(inputPath);
|
||||
var outputFolder = await StorageFolder.GetFolderFromPathAsync(_fallbackDirectory);
|
||||
var outputFile = await outputFolder.CreateFileAsync(tempFileName, CreationCollisionOption.ReplaceExisting);
|
||||
|
||||
var sourceProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
|
||||
uint origWidth = sourceProfile?.Video?.Width ?? 1920u;
|
||||
uint origHeight = sourceProfile?.Video?.Height ?? 1080u;
|
||||
if (origWidth == 0) origWidth = 1920;
|
||||
if (origHeight == 0) origHeight = 1080;
|
||||
|
||||
double fps = 30.0;
|
||||
if (sourceProfile?.Video?.FrameRate is { Numerator: > 0, Denominator: > 0 } fr)
|
||||
fps = (double)fr.Numerator / fr.Denominator;
|
||||
|
||||
var proxyWidth = AlignTo16((uint)(origWidth * scale));
|
||||
var proxyHeight = AlignTo16((uint)(origHeight * scale));
|
||||
|
||||
var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
|
||||
profile.Video = VideoEncodingProperties.CreateH264();
|
||||
profile.Video.Width = proxyWidth;
|
||||
profile.Video.Height = proxyHeight;
|
||||
profile.Video.Bitrate = Math.Max((uint)(proxyWidth * proxyHeight * fps * 0.07 * bitrateFactor), 100_000u);
|
||||
profile.Video.FrameRate.Numerator = (uint)Math.Max(1, Math.Round(fps));
|
||||
profile.Video.FrameRate.Denominator = 1;
|
||||
profile.Video.Properties[MfGuids.MF_MT_MAX_KEYFRAME_SPACING] = (uint)Math.Max(1, gopSize);
|
||||
profile.Audio = null;
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var transcoder = new MediaTranscoder
|
||||
{
|
||||
HardwareAccelerationEnabled = _config.EnableHardwareAcceleration,
|
||||
VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default
|
||||
};
|
||||
|
||||
var prepResult = await transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, profile);
|
||||
|
||||
if (!prepResult.CanTranscode && _config.EnableHardwareAcceleration)
|
||||
{
|
||||
transcoder.HardwareAccelerationEnabled = false;
|
||||
prepResult = await transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, profile);
|
||||
}
|
||||
|
||||
if (!prepResult.CanTranscode)
|
||||
throw new InvalidOperationException(string.Concat("Transcode failed: ", prepResult.FailureReason.ToString()));
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var transcodeOp = prepResult.TranscodeAsync();
|
||||
|
||||
if (progressItem is not null)
|
||||
{
|
||||
var reporter = new TranscodeProgressReporter(progressItem);
|
||||
transcodeOp.Progress = reporter.Report;
|
||||
}
|
||||
|
||||
using var reg = cancellationToken.Register(
|
||||
static state => ((IAsyncActionWithProgress<double>)state!).Cancel(),
|
||||
transcodeOp);
|
||||
await transcodeOp;
|
||||
|
||||
float effectiveScale = (float)proxyWidth / origWidth;
|
||||
entry = new ProxyCacheEntry(inputPath, effectiveScale, _memoryBudget.RecordDeallocation)
|
||||
{
|
||||
ProxyWidth = proxyWidth,
|
||||
ProxyHeight = proxyHeight
|
||||
};
|
||||
|
||||
CaptureOutputHybrid(tempPath, entry);
|
||||
return entry;
|
||||
}
|
||||
catch
|
||||
{
|
||||
entry?.Dispose();
|
||||
TryDeleteFile(tempPath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void CaptureOutputHybrid(string outputPath, ProxyCacheEntry entry)
|
||||
{
|
||||
var fileSize = new FileInfo(outputPath).Length;
|
||||
entry.SetDiskPath(outputPath, fileSize);
|
||||
}
|
||||
|
||||
internal static uint AlignTo16(uint value)
|
||||
{
|
||||
var aligned = (value + 15u) & ~15u;
|
||||
return aligned < 16u ? 16u : aligned;
|
||||
}
|
||||
|
||||
private static void ValidateInputPath(string inputPath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(inputPath) || !Path.IsPathFullyQualified(inputPath))
|
||||
throw new ArgumentException("Input path must be a fully qualified absolute path.", nameof(inputPath));
|
||||
}
|
||||
|
||||
private void ValidateTempPath(string tempPath)
|
||||
{
|
||||
var fullTemp = Path.GetFullPath(tempPath);
|
||||
var fullDir = Path.GetFullPath(_fallbackDirectory);
|
||||
Span<char> dirWithSep = stackalloc char[fullDir.Length + 1];
|
||||
fullDir.AsSpan().CopyTo(dirWithSep);
|
||||
dirWithSep[fullDir.Length] = Path.DirectorySeparatorChar;
|
||||
if (!fullTemp.AsSpan().StartsWith(dirWithSep, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("Temporary path is outside the designated fallback directory.");
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Interlocked.Exchange(ref _disposed, 1);
|
||||
}
|
||||
|
||||
private sealed class TranscodeProgressReporter(ProxyGenerationItem progressItem)
|
||||
{
|
||||
private readonly Action _dispatchAction = progressItem.ApplyPendingProgress;
|
||||
private long _lastReportedCenti;
|
||||
|
||||
internal void Report(IAsyncActionWithProgress<double> _, double pct)
|
||||
{
|
||||
var p = Math.Min(99.0, pct);
|
||||
var centi = (long)(p * 100);
|
||||
var prev = Volatile.Read(ref _lastReportedCenti);
|
||||
if (centi - prev < 100 && p < 99.0)
|
||||
return;
|
||||
Volatile.Write(ref _lastReportedCenti, centi);
|
||||
progressItem.SetPendingProgress(p);
|
||||
System.Windows.Application.Current?.Dispatcher.BeginInvoke(
|
||||
System.Windows.Threading.DispatcherPriority.Background,
|
||||
_dispatchAction);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
using ProxyForge.Interfaces;
|
||||
using ProxyForge.Memory;
|
||||
|
||||
namespace ProxyForge.Core;
|
||||
|
||||
internal sealed class MfProxyEncoderFactory(
|
||||
MemoryBudget memoryBudget,
|
||||
string fallbackDirectory,
|
||||
Func<EncoderConfig> configProvider) : IProxyEncoderFactory
|
||||
{
|
||||
public IProxyEncoder Create() =>
|
||||
new MfProxyEncoder(memoryBudget, fallbackDirectory, configProvider());
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
using ProxyForge.Memory;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace ProxyForge.Core;
|
||||
|
||||
internal sealed class ProxyCacheEntry : IDisposable
|
||||
{
|
||||
private byte[]? _memoryData;
|
||||
private int _memoryDataLength;
|
||||
private string? _diskPath;
|
||||
private readonly Action<long>? _onMemoryReleased;
|
||||
private long _cachedSize;
|
||||
private long _trackedMemoryBytes;
|
||||
private long _lastAccessedTicks = DateTime.UtcNow.Ticks;
|
||||
private readonly object _diskWriteLock = new();
|
||||
private int _disposed;
|
||||
private int _streamCount;
|
||||
private int _releaseMemoryWhenPossible;
|
||||
private int _persistentDiskEntry;
|
||||
|
||||
internal string OriginalPath { get; }
|
||||
internal float Scale { get; }
|
||||
internal uint ProxyWidth { get; init; }
|
||||
internal uint ProxyHeight { get; init; }
|
||||
|
||||
internal bool IsInMemory =>
|
||||
Volatile.Read(ref _memoryData) is not null &&
|
||||
Volatile.Read(ref _diskPath) is null;
|
||||
|
||||
internal bool IsValid =>
|
||||
Volatile.Read(ref _disposed) == 0 &&
|
||||
(Volatile.Read(ref _memoryData) is not null || Volatile.Read(ref _diskPath) is not null);
|
||||
|
||||
internal long DataSize => Interlocked.Read(ref _cachedSize);
|
||||
internal DateTime CreatedAt { get; } = DateTime.UtcNow;
|
||||
internal DateTime LastAccessedAt => new(Interlocked.Read(ref _lastAccessedTicks));
|
||||
|
||||
internal ProxyCacheEntry(string originalPath, float scale, Action<long>? onMemoryReleased = null)
|
||||
{
|
||||
OriginalPath = originalPath;
|
||||
Scale = scale;
|
||||
_onMemoryReleased = onMemoryReleased;
|
||||
}
|
||||
|
||||
internal void SetMemoryData(byte[] pooledBuffer, int length)
|
||||
{
|
||||
Interlocked.Exchange(ref _trackedMemoryBytes, length);
|
||||
Interlocked.Exchange(ref _cachedSize, (long)length);
|
||||
Volatile.Write(ref _memoryDataLength, length);
|
||||
Volatile.Write(ref _diskPath, null);
|
||||
Volatile.Write(ref _releaseMemoryWhenPossible, 0);
|
||||
Volatile.Write(ref _memoryData, pooledBuffer);
|
||||
UpdateLastAccess();
|
||||
}
|
||||
|
||||
internal void SetDiskPath(string path, long size)
|
||||
{
|
||||
Interlocked.Exchange(ref _cachedSize, size);
|
||||
Volatile.Write(ref _diskPath, path);
|
||||
Volatile.Write(ref _releaseMemoryWhenPossible, 1);
|
||||
TryReturnBuffer();
|
||||
UpdateLastAccess();
|
||||
}
|
||||
|
||||
internal void MarkPersistent() =>
|
||||
Volatile.Write(ref _persistentDiskEntry, 1);
|
||||
|
||||
internal string? GetCurrentDiskPath() =>
|
||||
Volatile.Read(ref _diskPath);
|
||||
|
||||
internal void ReplaceDiskPath(string newPath)
|
||||
{
|
||||
Volatile.Write(ref _diskPath, newPath);
|
||||
MarkPersistent();
|
||||
}
|
||||
|
||||
internal Stream OpenReadStream()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
UpdateLastAccess();
|
||||
|
||||
while (true)
|
||||
{
|
||||
var mem = Volatile.Read(ref _memoryData);
|
||||
if (mem is null)
|
||||
break;
|
||||
|
||||
Interlocked.Increment(ref _streamCount);
|
||||
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
{
|
||||
OnStreamClosed();
|
||||
throw new ObjectDisposedException(nameof(ProxyCacheEntry));
|
||||
}
|
||||
|
||||
if (!ReferenceEquals(mem, Volatile.Read(ref _memoryData)))
|
||||
{
|
||||
OnStreamClosed();
|
||||
continue;
|
||||
}
|
||||
|
||||
var len = Volatile.Read(ref _memoryDataLength);
|
||||
return new PooledMemoryStream(mem, len, this);
|
||||
}
|
||||
|
||||
var disk = Volatile.Read(ref _diskPath);
|
||||
if (disk is not null && File.Exists(disk))
|
||||
return new FileStream(disk, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan);
|
||||
|
||||
throw new InvalidOperationException("Proxy data unavailable");
|
||||
}
|
||||
|
||||
internal string GetOrCreateTempFilePath(string tempDirectory)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
UpdateLastAccess();
|
||||
|
||||
var disk = Volatile.Read(ref _diskPath);
|
||||
if (disk is not null && File.Exists(disk))
|
||||
return disk;
|
||||
|
||||
lock (_diskWriteLock)
|
||||
{
|
||||
disk = Volatile.Read(ref _diskPath);
|
||||
if (disk is not null && File.Exists(disk))
|
||||
return disk;
|
||||
|
||||
var mem = Volatile.Read(ref _memoryData);
|
||||
if (mem is null)
|
||||
throw new InvalidOperationException("Proxy data unavailable");
|
||||
|
||||
Directory.CreateDirectory(tempDirectory);
|
||||
|
||||
Span<char> nameBuf = stackalloc char[45];
|
||||
"zdp_read_".AsSpan().CopyTo(nameBuf);
|
||||
Guid.NewGuid().TryFormat(nameBuf[9..], out _, "N");
|
||||
".mp4".AsSpan().CopyTo(nameBuf[41..]);
|
||||
var tempPath = Path.Combine(tempDirectory, new string(nameBuf));
|
||||
|
||||
using var fs = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536);
|
||||
fs.Write(mem, 0, Volatile.Read(ref _memoryDataLength));
|
||||
|
||||
Volatile.Write(ref _diskPath, tempPath);
|
||||
Volatile.Write(ref _releaseMemoryWhenPossible, 1);
|
||||
TryReturnBuffer();
|
||||
return tempPath;
|
||||
}
|
||||
}
|
||||
|
||||
internal CacheEntrySnapshot CreateSnapshot() =>
|
||||
new(OriginalPath,
|
||||
Path.GetFileName(OriginalPath),
|
||||
Scale,
|
||||
ProxyWidth,
|
||||
ProxyHeight,
|
||||
IsInMemory,
|
||||
DataSize,
|
||||
CreatedAt,
|
||||
LastAccessedAt);
|
||||
|
||||
private void OnStreamClosed()
|
||||
{
|
||||
if (Interlocked.Decrement(ref _streamCount) == 0)
|
||||
TryReturnBuffer();
|
||||
}
|
||||
|
||||
private void TryReturnBuffer()
|
||||
{
|
||||
if (Volatile.Read(ref _streamCount) != 0)
|
||||
return;
|
||||
|
||||
if (Volatile.Read(ref _disposed) == 0 && Volatile.Read(ref _releaseMemoryWhenPossible) == 0)
|
||||
return;
|
||||
|
||||
var buf = Interlocked.Exchange(ref _memoryData, null);
|
||||
if (buf is null)
|
||||
return;
|
||||
|
||||
Volatile.Write(ref _memoryDataLength, 0);
|
||||
BufferPool.Return(buf);
|
||||
|
||||
var released = Interlocked.Exchange(ref _trackedMemoryBytes, 0);
|
||||
if (released > 0)
|
||||
_onMemoryReleased?.Invoke(released);
|
||||
}
|
||||
|
||||
private void UpdateLastAccess() =>
|
||||
Interlocked.Exchange(ref _lastAccessedTicks, DateTime.UtcNow.Ticks);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
TryReturnBuffer();
|
||||
|
||||
var disk = Interlocked.Exchange(ref _diskPath, null);
|
||||
if (disk is null || Volatile.Read(ref _persistentDiskEntry) != 0)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
if (File.Exists(disk))
|
||||
File.Delete(disk);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyCacheEntry] Delete failed: ", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PooledMemoryStream(byte[] buffer, int length, ProxyCacheEntry owner) : Stream
|
||||
{
|
||||
private int _position;
|
||||
private int _streamDisposed;
|
||||
|
||||
public override bool CanRead => Volatile.Read(ref _streamDisposed) == 0;
|
||||
public override bool CanSeek => Volatile.Read(ref _streamDisposed) == 0;
|
||||
public override bool CanWrite => false;
|
||||
public override long Length => length;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => Volatile.Read(ref _position);
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(value, length);
|
||||
Volatile.Write(ref _position, (int)value);
|
||||
}
|
||||
}
|
||||
|
||||
public override int Read(byte[] destination, int offset, int count)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(offset);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(count);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(offset + count, destination.Length);
|
||||
return ReadCore(destination.AsSpan(offset, count));
|
||||
}
|
||||
|
||||
public override int Read(Span<byte> destination) => ReadCore(destination);
|
||||
|
||||
private int ReadCore(Span<byte> destination)
|
||||
{
|
||||
var pos = Volatile.Read(ref _position);
|
||||
var available = length - pos;
|
||||
if (available <= 0)
|
||||
return 0;
|
||||
var toRead = Math.Min(destination.Length, available);
|
||||
buffer.AsSpan(pos, toRead).CopyTo(destination);
|
||||
Volatile.Write(ref _position, pos + toRead);
|
||||
return toRead;
|
||||
}
|
||||
|
||||
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return ValueTask.FromCanceled<int>(cancellationToken);
|
||||
return ValueTask.FromResult(ReadCore(destination.Span));
|
||||
}
|
||||
|
||||
public override Task<int> ReadAsync(byte[] destination, int offset, int count, CancellationToken cancellationToken)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return Task.FromCanceled<int>(cancellationToken);
|
||||
return Task.FromResult(Read(destination, offset, count));
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
var newPos = origin switch
|
||||
{
|
||||
SeekOrigin.Begin => offset,
|
||||
SeekOrigin.Current => Volatile.Read(ref _position) + offset,
|
||||
SeekOrigin.End => length + offset,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(origin))
|
||||
};
|
||||
var clamped = (int)Math.Clamp(newPos, 0L, (long)length);
|
||||
Volatile.Write(ref _position, clamped);
|
||||
return clamped;
|
||||
}
|
||||
|
||||
public override void Flush() { }
|
||||
|
||||
public override void SetLength(long value) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
public override void Write(byte[] destination, int offset, int count) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _streamDisposed, 1) == 0 && disposing)
|
||||
owner.OnStreamClosed();
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal readonly record struct CacheEntrySnapshot(
|
||||
string OriginalPath,
|
||||
string FileName,
|
||||
float Scale,
|
||||
uint ProxyWidth,
|
||||
uint ProxyHeight,
|
||||
bool IsInMemory,
|
||||
long DataSize,
|
||||
DateTime CreatedAt,
|
||||
DateTime LastAccessedAt
|
||||
);
|
||||
@@ -1,333 +0,0 @@
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Interfaces;
|
||||
using ProxyForge.Localization;
|
||||
using ProxyForge.Progress;
|
||||
using ProxyForge.Settings;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
|
||||
namespace ProxyForge.Core;
|
||||
|
||||
internal sealed class ProxyCacheManager : IDisposable
|
||||
{
|
||||
private readonly record struct CacheKey(string Path, float Scale) : IEquatable<CacheKey>
|
||||
{
|
||||
public bool Equals(CacheKey other) =>
|
||||
Scale == other.Scale &&
|
||||
string.Equals(Path, other.Path, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public override int GetHashCode() =>
|
||||
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Path), Scale);
|
||||
}
|
||||
|
||||
private readonly ConcurrentDictionary<CacheKey, ProxyCacheEntry> _cache = new();
|
||||
private readonly ConcurrentDictionary<CacheKey, CancellationTokenSource> _pendingGenerations = new();
|
||||
private readonly IProxyEncoderFactory _encoderFactory;
|
||||
private readonly VideoCacheDatabase? _videoCache;
|
||||
private readonly string _tmpDirectory;
|
||||
private int _disposed;
|
||||
|
||||
internal ObservableCollection<ProxyGenerationItem> ActiveGenerations { get; } = [];
|
||||
internal event Action<string, ProxyCacheEntry>? ProxyCompleted;
|
||||
|
||||
internal ProxyCacheManager(IProxyEncoderFactory encoderFactory, VideoCacheDatabase? videoCache = null, string tmpDirectory = "")
|
||||
{
|
||||
_encoderFactory = encoderFactory;
|
||||
_videoCache = videoCache;
|
||||
_tmpDirectory = tmpDirectory;
|
||||
}
|
||||
|
||||
private static CacheKey MakeKey(string path, float scale) =>
|
||||
new(GetFullPath(path), scale);
|
||||
|
||||
private static string GetFullPath(string path)
|
||||
{
|
||||
try { return Path.GetFullPath(path); }
|
||||
catch { return path; }
|
||||
}
|
||||
|
||||
internal ProxyCacheEntry? TryGetProxy(string originalPath, float scale)
|
||||
{
|
||||
var key = MakeKey(originalPath, scale);
|
||||
if (_cache.TryGetValue(key, out var entry) && entry.IsValid)
|
||||
return entry;
|
||||
|
||||
if (_videoCache is not null &&
|
||||
ProxyForgeSettings.Default.EnableVideoCache &&
|
||||
_videoCache.TryGet(originalPath, scale, out var dbResult))
|
||||
{
|
||||
var cachePath = _videoCache.GetCacheFilePath(dbResult.Uuid);
|
||||
if (File.Exists(cachePath))
|
||||
{
|
||||
var diskEntry = new ProxyCacheEntry(originalPath, scale)
|
||||
{
|
||||
ProxyWidth = dbResult.ProxyWidth,
|
||||
ProxyHeight = dbResult.ProxyHeight
|
||||
};
|
||||
diskEntry.SetDiskPath(cachePath, dbResult.FileSize);
|
||||
diskEntry.MarkPersistent();
|
||||
var stored = _cache.GetOrAdd(key, diskEntry);
|
||||
if (!ReferenceEquals(stored, diskEntry))
|
||||
diskEntry.Dispose();
|
||||
_videoCache.UpdateLastAccess(dbResult.Uuid);
|
||||
return stored.IsValid ? stored : null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
internal bool ProxyExists(string originalPath, float scale)
|
||||
{
|
||||
var key = MakeKey(originalPath, scale);
|
||||
if (_cache.TryGetValue(key, out var entry) && entry.IsValid)
|
||||
return true;
|
||||
|
||||
if (_videoCache is not null &&
|
||||
ProxyForgeSettings.Default.EnableVideoCache &&
|
||||
_videoCache.TryGet(originalPath, scale, out _))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
internal void StartProxyGeneration(string originalPath, float scale, ProxyForgeSettings settings)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
return;
|
||||
|
||||
var key = MakeKey(originalPath, scale);
|
||||
|
||||
if (_cache.TryGetValue(key, out var existing) && existing.IsValid)
|
||||
return;
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
if (!_pendingGenerations.TryAdd(key, cts))
|
||||
{
|
||||
cts.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
_ = Task.Run(() => RunGenerationAsync(key, originalPath, scale, settings, cts), CancellationToken.None);
|
||||
}
|
||||
|
||||
private async Task RunGenerationAsync(CacheKey key, string originalPath, float scale, ProxyForgeSettings settings, CancellationTokenSource cts)
|
||||
{
|
||||
var progressItem = new ProxyGenerationItem(originalPath);
|
||||
DispatchInvoke(() => ActiveGenerations.Add(progressItem));
|
||||
|
||||
var delayMs = 2000;
|
||||
|
||||
try
|
||||
{
|
||||
using var encoder = _encoderFactory.Create();
|
||||
var entry = await encoder.EncodeAsync(
|
||||
originalPath, scale, settings.BitrateFactor / 100f, settings.GopSize,
|
||||
progressItem, cts.Token).ConfigureAwait(false);
|
||||
|
||||
var stored = _cache.GetOrAdd(key, entry);
|
||||
if (!ReferenceEquals(stored, entry))
|
||||
entry.Dispose();
|
||||
|
||||
if (_videoCache is not null && ProxyForgeSettings.Default.EnableVideoCache)
|
||||
PersistToVideoCache(originalPath, scale, stored);
|
||||
|
||||
var isInMem = stored.IsInMemory;
|
||||
DispatchInvoke(() =>
|
||||
{
|
||||
progressItem.Progress = 100;
|
||||
progressItem.IsCompleted = true;
|
||||
progressItem.StatusMessage = Translate.ProxyGenerationStatusCompleted;
|
||||
progressItem.IsInMemory = isInMem;
|
||||
});
|
||||
|
||||
ProxyCompleted?.Invoke(originalPath, stored);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
delayMs = 3000;
|
||||
DispatchInvoke(() =>
|
||||
{
|
||||
progressItem.StatusMessage = Translate.ProxyGenerationStatusCanceled;
|
||||
progressItem.IsFailed = true;
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
delayMs = 8000;
|
||||
var msg = ex.Message;
|
||||
Debug.WriteLine(string.Concat("[ProxyForge] Proxy generation failed for ", originalPath, ": ", ex));
|
||||
DispatchInvoke(() =>
|
||||
{
|
||||
progressItem.StatusMessage = string.Concat(Translate.ProxyGenerationStatusFailedPrefix, msg);
|
||||
progressItem.IsFailed = true;
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pendingGenerations.TryRemove(key, out _);
|
||||
cts.Dispose();
|
||||
}
|
||||
|
||||
await Task.Delay(delayMs, CancellationToken.None).ConfigureAwait(false);
|
||||
DispatchInvoke(() => ActiveGenerations.Remove(progressItem));
|
||||
}
|
||||
|
||||
private static void DispatchInvoke(Action action)
|
||||
{
|
||||
var app = Application.Current;
|
||||
if (app is null)
|
||||
return;
|
||||
|
||||
if (app.Dispatcher.CheckAccess())
|
||||
action();
|
||||
else
|
||||
app.Dispatcher.Invoke(action);
|
||||
}
|
||||
|
||||
internal void RemoveProxy(string originalPath, float scale)
|
||||
{
|
||||
var key = MakeKey(originalPath, scale);
|
||||
if (_cache.TryRemove(key, out var entry))
|
||||
entry.Dispose();
|
||||
|
||||
_videoCache?.RemoveByPath(originalPath);
|
||||
}
|
||||
|
||||
internal (int count, long totalSize) ClearAll()
|
||||
{
|
||||
foreach (var kvp in _pendingGenerations)
|
||||
{
|
||||
if (_pendingGenerations.TryRemove(kvp.Key, out var removed))
|
||||
{
|
||||
try { removed.Cancel(); removed.Dispose(); }
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
long totalSize = 0;
|
||||
var count = 0;
|
||||
foreach (var kvp in _cache)
|
||||
{
|
||||
if (_cache.TryRemove(kvp.Key, out var removed))
|
||||
{
|
||||
totalSize += removed.DataSize;
|
||||
removed.Dispose();
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return (count, totalSize);
|
||||
}
|
||||
|
||||
internal CacheEntrySnapshot[] GetAllSnapshots()
|
||||
{
|
||||
var resultList = new List<CacheEntrySnapshot>();
|
||||
|
||||
foreach (var entry in _cache.Values)
|
||||
{
|
||||
if (entry.IsValid)
|
||||
resultList.Add(entry.CreateSnapshot());
|
||||
}
|
||||
|
||||
if (_videoCache is not null && ProxyForgeSettings.Default.EnableVideoCache)
|
||||
{
|
||||
var dbEntries = _videoCache.GetAll();
|
||||
foreach (var db in dbEntries)
|
||||
{
|
||||
var alreadyInMemory = false;
|
||||
foreach (var existing in resultList)
|
||||
{
|
||||
if (string.Equals(existing.OriginalPath, db.OriginalPath, StringComparison.OrdinalIgnoreCase) &&
|
||||
existing.Scale == db.Scale)
|
||||
{
|
||||
alreadyInMemory = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!alreadyInMemory)
|
||||
{
|
||||
resultList.Add(new CacheEntrySnapshot(
|
||||
db.OriginalPath, db.FileName, db.Scale,
|
||||
db.ProxyWidth, db.ProxyHeight,
|
||||
false, db.FileSize, db.CreatedAt, db.LastAccessedAt));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resultList.Count > 0 ? [.. resultList] : [];
|
||||
}
|
||||
|
||||
internal (int entryCount, long memSize, long diskSize, int memCount, int diskCount) GetCacheInfo()
|
||||
{
|
||||
long ms = 0, ds = 0;
|
||||
int mc = 0, dc = 0;
|
||||
foreach (var e in _cache.Values)
|
||||
{
|
||||
if (!e.IsValid)
|
||||
continue;
|
||||
|
||||
if (e.IsInMemory)
|
||||
{
|
||||
ms += e.DataSize;
|
||||
mc++;
|
||||
}
|
||||
else
|
||||
{
|
||||
ds += e.DataSize;
|
||||
dc++;
|
||||
}
|
||||
}
|
||||
return (_cache.Count, ms, ds, mc, dc);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
ClearAll();
|
||||
}
|
||||
|
||||
private void PersistToVideoCache(string originalPath, float scale, ProxyCacheEntry entry)
|
||||
{
|
||||
if (_videoCache is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var uuid = Guid.NewGuid();
|
||||
var diskStore = _videoCache.DiskStore;
|
||||
var destPath = diskStore.GetFilePath(uuid);
|
||||
|
||||
var tmpPath = entry.GetCurrentDiskPath();
|
||||
if (tmpPath is not null && File.Exists(tmpPath) && IsTmpFile(tmpPath))
|
||||
{
|
||||
File.Move(tmpPath, destPath, true);
|
||||
entry.ReplaceDiskPath(destPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
using var stream = entry.OpenReadStream();
|
||||
diskStore.SaveFromStream(uuid, stream);
|
||||
}
|
||||
|
||||
var fileCrc = diskStore.ComputeFileCrc32FromPath(destPath);
|
||||
var fileSize = new FileInfo(destPath).Length;
|
||||
|
||||
_videoCache.Add(originalPath, scale, entry.ProxyWidth, entry.ProxyHeight,
|
||||
fileSize, fileCrc, uuid);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyCacheManager] PersistToVideoCache failed: ", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsTmpFile(string path) =>
|
||||
!string.IsNullOrEmpty(_tmpDirectory) &&
|
||||
path.StartsWith(_tmpDirectory, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
using ProxyForge.Interfaces;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using YukkuriMovieMaker.Resources.Localization;
|
||||
|
||||
namespace ProxyForge.Detection;
|
||||
|
||||
internal sealed partial class ExportDetector : IExportDetector
|
||||
{
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial uint GetWindowThreadProcessId(nint hWnd, out uint lpdwProcessId);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int GetWindowText(nint hWnd, char[] lpString, int nMaxCount);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EnumWindows(EnumWindowsProc enumProc, nint lParam);
|
||||
|
||||
private delegate bool EnumWindowsProc(nint hWnd, nint lParam);
|
||||
|
||||
[ThreadStatic]
|
||||
private static bool t_found;
|
||||
[ThreadStatic]
|
||||
private static uint t_processId;
|
||||
[ThreadStatic]
|
||||
private static char[]? t_titleBuffer;
|
||||
|
||||
private const int WindowTitleBufferSize = 512;
|
||||
private const long CacheIntervalMs = 2000L;
|
||||
private const long StateUnknown = 0L;
|
||||
private const long StateFalse = 1L;
|
||||
private const long StateTrue = 2L;
|
||||
|
||||
private static readonly EnumWindowsProc s_enumWindowsCallback = EnumWindowsCallback;
|
||||
|
||||
private long _packed;
|
||||
|
||||
public bool IsExporting()
|
||||
{
|
||||
var nowMs = Environment.TickCount64;
|
||||
var packed = Interlocked.Read(ref _packed);
|
||||
var state = packed & 3L;
|
||||
|
||||
if (state != StateUnknown && (nowMs - (packed >> 2)) < CacheIntervalMs)
|
||||
return state == StateTrue;
|
||||
|
||||
var result = CheckExportWindow();
|
||||
Interlocked.Exchange(ref _packed, (nowMs << 2) | (result ? StateTrue : StateFalse));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool CheckExportWindow()
|
||||
{
|
||||
Debug.Assert(
|
||||
SynchronizationContext.Current is null || !Thread.CurrentThread.IsThreadPoolThread,
|
||||
"CheckExportWindow relies on ThreadStatic fields and must not be called from async continuations on thread pool threads.");
|
||||
|
||||
try
|
||||
{
|
||||
t_processId = (uint)Environment.ProcessId;
|
||||
t_found = false;
|
||||
EnumWindows(s_enumWindowsCallback, nint.Zero);
|
||||
return t_found;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool EnumWindowsCallback(nint hWnd, nint _)
|
||||
{
|
||||
GetWindowThreadProcessId(hWnd, out var pid);
|
||||
if (pid != t_processId)
|
||||
return true;
|
||||
|
||||
t_titleBuffer ??= new char[WindowTitleBufferSize];
|
||||
var len = GetWindowText(hWnd, t_titleBuffer, t_titleBuffer.Length);
|
||||
if (len <= 0)
|
||||
return true;
|
||||
|
||||
var title = t_titleBuffer.AsSpan(0, len);
|
||||
if (title.SequenceEqual(Texts.OutputProgressWindowTitle.AsSpan()) ||
|
||||
title.SequenceEqual(Texts.VideoExportWindowTitle.AsSpan()))
|
||||
{
|
||||
t_found = true;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Reset() => Interlocked.Exchange(ref _packed, 0L);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<YMM4DirPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\</YMM4DirPath>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,21 @@
|
||||
using Vortice.Direct2D1;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal readonly record struct DisplayBounds(float Left, float Top, float Width, float Height)
|
||||
{
|
||||
public int PixelWidth => (int)Math.Round(Width, MidpointRounding.AwayFromZero);
|
||||
|
||||
public int PixelHeight => (int)Math.Round(Height, MidpointRounding.AwayFromZero);
|
||||
|
||||
public bool IsUsable =>
|
||||
float.IsFinite(Left) && float.IsFinite(Top) && float.IsFinite(Width) && float.IsFinite(Height)
|
||||
&& PixelWidth >= 1 && PixelHeight >= 1
|
||||
&& PixelWidth <= ProxyGeometryCalculator.MaximumDimension && PixelHeight <= ProxyGeometryCalculator.MaximumDimension;
|
||||
|
||||
public static DisplayBounds Measure(ID2D1DeviceContext context, ID2D1Image image)
|
||||
{
|
||||
var bounds = context.GetImageLocalBounds(image);
|
||||
return new DisplayBounds(bounds.Left, bounds.Top, bounds.Right - bounds.Left, bounds.Bottom - bounds.Top);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using ProxyForge.Sources;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal readonly record struct FFmpegEncodeRequest(
|
||||
string OutputPath,
|
||||
int Width,
|
||||
int Height,
|
||||
FrameRate FrameRate,
|
||||
long BitrateBitsPerSecond,
|
||||
int KeyFrameInterval,
|
||||
string VideoEncoder);
|
||||
|
||||
internal static class FFmpegArguments
|
||||
{
|
||||
public const string SoftwareVideoEncoder = "h264";
|
||||
public const string InputPixelFormat = "bgra";
|
||||
public const string OutputPixelFormat = "yuv420p";
|
||||
public const string ColorSpace = "bt709";
|
||||
public const double DefaultFrameRate = 30d;
|
||||
|
||||
const double BitratePerPixelPerSecond = 0.07;
|
||||
const long MinimumBitrate = 100_000L;
|
||||
const long MaximumBitrate = 100_000_000L;
|
||||
const double MinimumFrameRate = 1d;
|
||||
const double MaximumFrameRate = 240d;
|
||||
|
||||
public static void WriteEncode(Collection<string> arguments, in FFmpegEncodeRequest request)
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-y");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("rawvideo");
|
||||
arguments.Add("-pix_fmt");
|
||||
arguments.Add(InputPixelFormat);
|
||||
arguments.Add("-s");
|
||||
arguments.Add(BuildFrameSize(request.Width, request.Height));
|
||||
arguments.Add("-r");
|
||||
arguments.Add(BuildFrameRate(request.FrameRate));
|
||||
arguments.Add("-i");
|
||||
arguments.Add("-");
|
||||
arguments.Add("-an");
|
||||
arguments.Add("-sn");
|
||||
arguments.Add("-dn");
|
||||
arguments.Add("-c:v");
|
||||
arguments.Add(request.VideoEncoder);
|
||||
arguments.Add("-b:v");
|
||||
arguments.Add(request.BitrateBitsPerSecond.ToString(CultureInfo.InvariantCulture));
|
||||
arguments.Add("-g");
|
||||
arguments.Add(request.KeyFrameInterval.ToString(CultureInfo.InvariantCulture));
|
||||
arguments.Add("-pix_fmt");
|
||||
arguments.Add(OutputPixelFormat);
|
||||
arguments.Add("-colorspace");
|
||||
arguments.Add(ColorSpace);
|
||||
arguments.Add("-color_primaries");
|
||||
arguments.Add(ColorSpace);
|
||||
arguments.Add("-color_trc");
|
||||
arguments.Add(ColorSpace);
|
||||
arguments.Add("-color_range");
|
||||
arguments.Add("tv");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("mp4");
|
||||
arguments.Add(request.OutputPath);
|
||||
}
|
||||
|
||||
public static void WriteEncoderProbe(Collection<string> arguments, string encoder, int width, int height)
|
||||
{
|
||||
arguments.Add("-hide_banner");
|
||||
arguments.Add("-nostdin");
|
||||
arguments.Add("-loglevel");
|
||||
arguments.Add("error");
|
||||
arguments.Add("-f");
|
||||
arguments.Add("lavfi");
|
||||
arguments.Add("-i");
|
||||
arguments.Add(BuildColorSource(width, height));
|
||||
arguments.Add("-frames:v");
|
||||
arguments.Add("1");
|
||||
arguments.Add("-pix_fmt");
|
||||
arguments.Add(OutputPixelFormat);
|
||||
arguments.Add("-c:v");
|
||||
arguments.Add(encoder);
|
||||
arguments.Add("-f");
|
||||
arguments.Add("null");
|
||||
arguments.Add("-");
|
||||
}
|
||||
|
||||
public static string BuildFrameSize(int width, int height)
|
||||
=> string.Create(CultureInfo.InvariantCulture, $"{width}x{height}");
|
||||
|
||||
public static string BuildFrameRate(FrameRate frameRate)
|
||||
=> string.Create(CultureInfo.InvariantCulture, $"{frameRate.Numerator}/{frameRate.Denominator}");
|
||||
|
||||
public static string BuildColorSource(int width, int height)
|
||||
=> string.Create(CultureInfo.InvariantCulture, $"color=c=black:s={width}x{height}:r=30");
|
||||
|
||||
public static long CalculateVideoBitrate(int width, int height, double frameRate, int bitrateScale)
|
||||
{
|
||||
var rate = double.IsFinite(frameRate) && frameRate > 0d
|
||||
? Math.Clamp(frameRate, MinimumFrameRate, MaximumFrameRate)
|
||||
: DefaultFrameRate;
|
||||
var scale = bitrateScale > 0 ? bitrateScale / 100d : 1d;
|
||||
var bitrate = (double)width * height * rate * BitratePerPixelPerSecond * scale;
|
||||
|
||||
if (!double.IsFinite(bitrate))
|
||||
return MaximumBitrate;
|
||||
|
||||
return (long)Math.Clamp(bitrate, MinimumBitrate, MaximumBitrate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using Vortice.DXGI;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal static class FFmpegEncoderCandidates
|
||||
{
|
||||
public const int VendorNvidia = 0x10DE;
|
||||
public const int VendorAmd = 0x1002;
|
||||
public const int VendorIntel = 0x8086;
|
||||
|
||||
static readonly string[] Hardware = ["h264_nvenc", "h264_qsv", "h264_amf"];
|
||||
|
||||
public static ReadOnlySpan<string> Hardware264 => Hardware;
|
||||
|
||||
public static int VendorOf(string encoder)
|
||||
{
|
||||
if (encoder.Contains("nvenc", StringComparison.Ordinal))
|
||||
return VendorNvidia;
|
||||
if (encoder.Contains("amf", StringComparison.Ordinal))
|
||||
return VendorAmd;
|
||||
if (encoder.Contains("qsv", StringComparison.Ordinal))
|
||||
return VendorIntel;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static void Order(ReadOnlySpan<string> candidates, IReadOnlySet<int> discreteVendors, Span<string> destination)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(destination.Length, candidates.Length);
|
||||
|
||||
var index = 0;
|
||||
for (var i = 0; i < candidates.Length; i++)
|
||||
{
|
||||
if (discreteVendors.Contains(VendorOf(candidates[i])))
|
||||
destination[index++] = candidates[i];
|
||||
}
|
||||
|
||||
for (var i = 0; i < candidates.Length; i++)
|
||||
{
|
||||
if (!discreteVendors.Contains(VendorOf(candidates[i])))
|
||||
destination[index++] = candidates[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class FFmpegEncoderSelector
|
||||
{
|
||||
const int ProbeTimeoutMilliseconds = 15_000;
|
||||
const long DiscreteVideoMemoryThreshold = 512L * 1024L * 1024L;
|
||||
|
||||
static readonly ConcurrentDictionary<long, string> ResolvedEncoders = new();
|
||||
|
||||
static readonly Lazy<IReadOnlySet<int>> DiscreteGpuVendors =
|
||||
new(DetectDiscreteGpuVendors, LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
|
||||
public static async Task<string> ResolveAsync(
|
||||
string ffmpegPath,
|
||||
bool hardwareEncoderEnabled,
|
||||
int width,
|
||||
int height,
|
||||
string workingDirectory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!hardwareEncoderEnabled)
|
||||
return FFmpegArguments.SoftwareVideoEncoder;
|
||||
|
||||
var key = ((long)width << 32) | (uint)height;
|
||||
if (ResolvedEncoders.TryGetValue(key, out var cached))
|
||||
return cached;
|
||||
|
||||
var candidates = FFmpegEncoderCandidates.Hardware264;
|
||||
var ordered = new string[candidates.Length];
|
||||
FFmpegEncoderCandidates.Order(candidates, DiscreteGpuVendors.Value, ordered);
|
||||
|
||||
foreach (var candidate in ordered)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (!await ProbeEncoderAsync(ffmpegPath, candidate, width, height, workingDirectory, cancellationToken).ConfigureAwait(false))
|
||||
continue;
|
||||
|
||||
Log.Default.Write($"ProxyForge: ハードウェアエンコーダー '{candidate}' を使用します。({width}x{height})");
|
||||
ResolvedEncoders[key] = candidate;
|
||||
return candidate;
|
||||
}
|
||||
|
||||
Log.Default.Write($"ProxyForge: 使えるハードウェアエンコーダーが見つからず、ソフトウェアエンコードを使用します。({width}x{height})");
|
||||
ResolvedEncoders[key] = FFmpegArguments.SoftwareVideoEncoder;
|
||||
return FFmpegArguments.SoftwareVideoEncoder;
|
||||
}
|
||||
|
||||
static async Task<bool> ProbeEncoderAsync(
|
||||
string ffmpegPath,
|
||||
string encoder,
|
||||
int width,
|
||||
int height,
|
||||
string workingDirectory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(ProbeTimeoutMilliseconds);
|
||||
|
||||
try
|
||||
{
|
||||
var result = await FFmpegProcessRunner.RunAsync(
|
||||
ffmpegPath,
|
||||
arguments => FFmpegArguments.WriteEncoderProbe(arguments, encoder, width, height),
|
||||
workingDirectory,
|
||||
null,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
timeout.Token).ConfigureAwait(false);
|
||||
|
||||
return result.IsSuccess;
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (InvalidOperationException exception)
|
||||
{
|
||||
Log.Default.Write($"ProxyForge: エンコーダー '{encoder}' の確認に失敗しました。", exception);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static IReadOnlySet<int> DetectDiscreteGpuVendors()
|
||||
{
|
||||
var vendors = new HashSet<int>();
|
||||
|
||||
try
|
||||
{
|
||||
using var factory = DXGI.CreateDXGIFactory1<IDXGIFactory1>();
|
||||
|
||||
var index = 0;
|
||||
while (factory.EnumAdapters1(index, out var adapter).Success)
|
||||
{
|
||||
using (adapter)
|
||||
{
|
||||
var description = adapter.Description1;
|
||||
if ((description.Flags & AdapterFlags.Software) == 0 &&
|
||||
(long)description.DedicatedVideoMemory >= DiscreteVideoMemoryThreshold)
|
||||
vendors.Add(description.VendorId);
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
catch (Exception exception) when (exception is SharpGen.Runtime.SharpGenException or DllNotFoundException or EntryPointNotFoundException)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: アダプターの列挙に失敗しました。", exception);
|
||||
}
|
||||
|
||||
return vendors;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
using System.Buffers;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal delegate Task FFmpegInputWriter(Stream destination, CancellationToken cancellationToken);
|
||||
|
||||
internal readonly record struct FFmpegProcessResult(int ExitCode, string Diagnostics)
|
||||
{
|
||||
public bool IsSuccess => ExitCode == 0;
|
||||
|
||||
public string FirstDiagnosticLine(int maximumLength)
|
||||
{
|
||||
var text = Diagnostics.AsSpan().Trim();
|
||||
if (text.IsEmpty)
|
||||
return string.Empty;
|
||||
|
||||
var index = text.IndexOf('\n');
|
||||
var line = index < 0 ? text : text[..index];
|
||||
return new string(line.Length > maximumLength ? line[..maximumLength] : line);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class FFmpegDiagnosticsBuffer(int capacity)
|
||||
{
|
||||
readonly StringBuilder builder = new();
|
||||
|
||||
public void Append(ReadOnlySpan<char> line)
|
||||
{
|
||||
var trimmed = line.Trim();
|
||||
if (trimmed.IsEmpty || builder.Length >= capacity)
|
||||
return;
|
||||
|
||||
if (builder.Length != 0)
|
||||
builder.Append('\n');
|
||||
|
||||
var remaining = capacity - builder.Length;
|
||||
builder.Append(trimmed.Length > remaining ? trimmed[..remaining] : trimmed);
|
||||
}
|
||||
|
||||
public override string ToString() => builder.ToString();
|
||||
}
|
||||
|
||||
internal static class FFmpegProcessRunner
|
||||
{
|
||||
const int LineBufferLength = 4096;
|
||||
const int DiagnosticsCapacity = 4096;
|
||||
|
||||
static readonly UTF8Encoding PipeEncoding = new(encoderShouldEmitUTF8Identifier: false);
|
||||
|
||||
public static async Task<FFmpegProcessResult> RunAsync(
|
||||
string executablePath,
|
||||
Action<Collection<string>> argumentWriter,
|
||||
string workingDirectory,
|
||||
FFmpegInputWriter? standardInputWriter,
|
||||
ProcessPriorityClass priority,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var startInfo = new ProcessStartInfo(executablePath)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardInput = standardInputWriter is not null,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
StandardOutputEncoding = PipeEncoding,
|
||||
StandardErrorEncoding = PipeEncoding,
|
||||
WorkingDirectory = workingDirectory,
|
||||
};
|
||||
argumentWriter(startInfo.ArgumentList);
|
||||
|
||||
var diagnostics = new FFmpegDiagnosticsBuffer(DiagnosticsCapacity);
|
||||
|
||||
using var process = new Process { StartInfo = startInfo };
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
}
|
||||
catch (Win32Exception exception)
|
||||
{
|
||||
throw new InvalidOperationException(string.Concat("Failed to start the FFmpeg process: ", executablePath), exception);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
process.PriorityClass = priority;
|
||||
}
|
||||
catch (Exception exception) when (exception is InvalidOperationException or Win32Exception)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: ffmpeg の優先度を設定できませんでした。", exception);
|
||||
}
|
||||
|
||||
var standardOutputTask = DrainAsync(process.StandardOutput);
|
||||
var standardErrorTask = PumpLinesAsync(process.StandardError, diagnostics);
|
||||
|
||||
var registration = cancellationToken.CanBeCanceled
|
||||
? cancellationToken.Register(static state => TryKill((Process)state!), process)
|
||||
: default;
|
||||
|
||||
Exception? inputFailure = null;
|
||||
|
||||
try
|
||||
{
|
||||
if (standardInputWriter is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await WriteStandardInputAsync(process, standardInputWriter, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
inputFailure = exception;
|
||||
}
|
||||
}
|
||||
|
||||
await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
await standardOutputTask.ConfigureAwait(false);
|
||||
await standardErrorTask.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await registration.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (inputFailure is IOException)
|
||||
throw new InvalidOperationException(string.Concat("Failed to send frames to FFmpeg. ", diagnostics.ToString()), inputFailure);
|
||||
if (inputFailure is not null)
|
||||
ExceptionDispatchInfo.Throw(inputFailure);
|
||||
|
||||
return new FFmpegProcessResult(process.ExitCode, diagnostics.ToString());
|
||||
}
|
||||
|
||||
static async Task WriteStandardInputAsync(Process process, FFmpegInputWriter writer, CancellationToken cancellationToken)
|
||||
{
|
||||
var destination = process.StandardInput.BaseStream;
|
||||
try
|
||||
{
|
||||
await writer(destination, cancellationToken).ConfigureAwait(false);
|
||||
await destination.FlushAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
destination.Close();
|
||||
}
|
||||
catch (IOException exception)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: ffmpeg の標準入力を閉じられませんでした。", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void TryKill(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!process.HasExited)
|
||||
process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch (Exception exception) when (exception is InvalidOperationException or Win32Exception)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: ffmpeg を停止できませんでした。", exception);
|
||||
}
|
||||
}
|
||||
|
||||
static async Task DrainAsync(TextReader reader)
|
||||
{
|
||||
var buffer = ArrayPool<char>.Shared.Rent(LineBufferLength);
|
||||
try
|
||||
{
|
||||
while (await reader.ReadAsync(buffer).ConfigureAwait(false) > 0)
|
||||
{
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<char>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
static async Task PumpLinesAsync(TextReader reader, FFmpegDiagnosticsBuffer diagnostics)
|
||||
{
|
||||
var buffer = ArrayPool<char>.Shared.Rent(LineBufferLength);
|
||||
try
|
||||
{
|
||||
var length = 0;
|
||||
while (true)
|
||||
{
|
||||
var read = await reader.ReadAsync(buffer.AsMemory(length)).ConfigureAwait(false);
|
||||
if (read == 0)
|
||||
break;
|
||||
|
||||
length += read;
|
||||
var consumed = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var pending = buffer.AsSpan(consumed, length - consumed);
|
||||
var index = pending.IndexOf('\n');
|
||||
if (index < 0)
|
||||
break;
|
||||
|
||||
diagnostics.Append(pending[..index]);
|
||||
consumed += index + 1;
|
||||
}
|
||||
|
||||
if (consumed > 0)
|
||||
{
|
||||
buffer.AsSpan(consumed, length - consumed).CopyTo(buffer);
|
||||
length -= consumed;
|
||||
}
|
||||
else if (length == buffer.Length)
|
||||
{
|
||||
diagnostics.Append(buffer.AsSpan(0, length));
|
||||
length = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (length > 0)
|
||||
diagnostics.Append(buffer.AsSpan(0, length));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<char>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource.FFmpeg;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal readonly record struct FFmpegExecutables(string FFmpegPath)
|
||||
{
|
||||
public static FFmpegExecutables Unavailable => new(string.Empty);
|
||||
|
||||
public bool IsAvailable => FFmpegPath.Length != 0;
|
||||
}
|
||||
|
||||
internal static class FFmpegRuntime
|
||||
{
|
||||
static readonly Lazy<FFmpegExecutables> Resolved = new(Resolve, LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
|
||||
public static FFmpegExecutables Executables => Resolved.Value;
|
||||
|
||||
static FFmpegExecutables Resolve()
|
||||
{
|
||||
string path;
|
||||
try
|
||||
{
|
||||
path = GetFFmpegExePath();
|
||||
}
|
||||
catch (Exception exception) when (exception is TypeLoadException or MissingMemberException or FileNotFoundException)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: YMM4 の ffmpeg の場所を取得できませんでした。", exception);
|
||||
return FFmpegExecutables.Unavailable;
|
||||
}
|
||||
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Log.Default.Write($"ProxyForge: ffmpeg.exe が見つかりません。{path}");
|
||||
return FFmpegExecutables.Unavailable;
|
||||
}
|
||||
|
||||
return new FFmpegExecutables(path);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static string GetFFmpegExePath() => FFmpegResourceLocator.GetFFmpegExePath();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal static class FrameAlpha
|
||||
{
|
||||
public const int BytesPerPixel = 4;
|
||||
public const int EdgeMargin = 2;
|
||||
public const byte Opaque = byte.MaxValue;
|
||||
|
||||
public static bool IsOpaque(ReadOnlySpan<byte> frame, int width, int height)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(width, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(height, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(frame.Length, checked(width * height * BytesPerPixel));
|
||||
|
||||
var stride = width * BytesPerPixel;
|
||||
var top = Math.Min(EdgeMargin, height);
|
||||
var bottom = Math.Max(top, height - EdgeMargin);
|
||||
var left = Math.Min(EdgeMargin, width);
|
||||
var right = Math.Max(left, width - EdgeMargin);
|
||||
|
||||
for (var y = top; y < bottom; y++)
|
||||
{
|
||||
var row = frame.Slice(y * stride, stride);
|
||||
for (var x = left; x < right; x++)
|
||||
{
|
||||
if (row[x * BytesPerPixel + 3] != Opaque)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal sealed record ProxyChunkCoverage(int ChunkCount, IReadOnlyList<int> Chunks, int? CurrentChunk, double CurrentProgress)
|
||||
{
|
||||
public static ProxyChunkCoverage Empty { get; } = new(0, [], null, 0d);
|
||||
|
||||
public bool Contains(int chunk) => Chunks.Contains(chunk);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using ProxyForge.Sources;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal static class ProxyChunkPlan
|
||||
{
|
||||
public static int LengthFor(FrameRate frameRate, int seconds)
|
||||
=> Math.Max(1, (int)Math.Round(frameRate.Value * seconds, MidpointRounding.AwayFromZero));
|
||||
|
||||
public static int? Next(IReadOnlyCollection<int> completed, int chunkCount, int chunkLength, int? focusFrame)
|
||||
{
|
||||
if (chunkCount <= 0)
|
||||
return null;
|
||||
|
||||
var start = focusFrame is { } frame && frame > 0 ? Math.Min(frame / chunkLength, chunkCount - 1) : 0;
|
||||
for (var chunk = start; chunk < chunkCount; chunk++)
|
||||
{
|
||||
if (!completed.Contains(chunk))
|
||||
return chunk;
|
||||
}
|
||||
|
||||
for (var chunk = 0; chunk < start; chunk++)
|
||||
{
|
||||
if (!completed.Contains(chunk))
|
||||
return chunk;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
public enum ProxyEncodeFailure
|
||||
{
|
||||
FFmpegUnavailable,
|
||||
SourceUnavailable,
|
||||
NoFrames,
|
||||
UnusableSize,
|
||||
Transparent,
|
||||
FFmpegFailed,
|
||||
NoOutput,
|
||||
SourceChanged,
|
||||
}
|
||||
|
||||
internal sealed class ProxyEncodeException(ProxyEncodeFailure failure, string message) : Exception(message)
|
||||
{
|
||||
public ProxyEncodeFailure Failure { get; } = failure;
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
using System.Buffers;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal readonly record struct ProxyEncodeRequest(
|
||||
string SourcePath,
|
||||
string WorkingDirectory,
|
||||
int Scale,
|
||||
int BitrateScale,
|
||||
int KeyFrameInterval,
|
||||
bool UsesHardwareEncoder);
|
||||
|
||||
internal sealed record ProxyAnalysis(
|
||||
ProxyGeometry Geometry,
|
||||
DisplayBounds Display,
|
||||
FrameRate FrameRate,
|
||||
TimeSpan Duration,
|
||||
int FrameCount);
|
||||
|
||||
internal interface IProxyEncodeSession : IDisposable
|
||||
{
|
||||
ProxyAnalysis Analysis { get; }
|
||||
|
||||
Task<long> EncodeAsync(int firstFrame, int frameCount, string outputPath, IProgress<double>? progress, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
internal delegate Task<IProxyEncodeSession> ProxyEncodeSessionFactory(ProxyEncodeRequest request, CancellationToken cancellationToken);
|
||||
|
||||
internal sealed class ProxyEncoder(FFmpegExecutables executables, VideoSourceFactory sourceFactory)
|
||||
{
|
||||
const int DiagnosticExcerptLength = 200;
|
||||
|
||||
public async Task<IProxyEncodeSession> OpenAsync(ProxyEncodeRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.SourcePath) || !Path.IsPathFullyQualified(request.SourcePath))
|
||||
throw new ArgumentException("The source path must be fully qualified.", nameof(request));
|
||||
|
||||
if (!executables.IsAvailable)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegUnavailable, "The FFmpeg executable bundled with YukkuriMovieMaker could not be located.");
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Directory.CreateDirectory(request.WorkingDirectory);
|
||||
|
||||
GraphicsDevices? devices = null;
|
||||
IGraphicsDevicesAndContext? context = null;
|
||||
IVideoFileSource? source = null;
|
||||
ProxyFrameRenderer? renderer = null;
|
||||
|
||||
try
|
||||
{
|
||||
devices = new GraphicsDevices();
|
||||
context = devices.CreateContext();
|
||||
context.DeviceContext.SetDpi(ProxyFrameRenderer.ReferenceDpi, ProxyFrameRenderer.ReferenceDpi);
|
||||
|
||||
source = sourceFactory(context, request.SourcePath)
|
||||
?? throw new ProxyEncodeException(ProxyEncodeFailure.SourceUnavailable, "No video file source plugin was able to open the input file.");
|
||||
|
||||
var duration = source.Duration;
|
||||
if (duration <= TimeSpan.Zero)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.NoFrames, "The video source reported a zero duration.");
|
||||
|
||||
var frameCount = source.GetFrameIndex(duration);
|
||||
if (frameCount <= 0)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.NoFrames, "The video source reported no frames.");
|
||||
|
||||
var frameRate = FrameRateResolver.Resolve(source.GetFrameIndex, frameCount, duration);
|
||||
|
||||
source.Update(frameRate.GetSampleTime(0));
|
||||
var display = DisplayBounds.Measure(context.DeviceContext, source.Output);
|
||||
if (!display.IsUsable)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.UnusableSize, "The video source reported an unusable image size.");
|
||||
|
||||
var geometry = ProxyGeometryCalculator.Calculate(display.PixelWidth, display.PixelHeight, request.Scale);
|
||||
renderer = new ProxyFrameRenderer(context, source.Output, display, geometry);
|
||||
|
||||
var videoEncoder = await FFmpegEncoderSelector.ResolveAsync(
|
||||
executables.FFmpegPath,
|
||||
request.UsesHardwareEncoder,
|
||||
geometry.Width,
|
||||
geometry.Height,
|
||||
request.WorkingDirectory,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var analysis = new ProxyAnalysis(geometry, display, frameRate, duration, frameCount);
|
||||
var session = new Session(executables, request, analysis, videoEncoder, devices, context, source, renderer);
|
||||
devices = null;
|
||||
context = null;
|
||||
source = null;
|
||||
renderer = null;
|
||||
return session;
|
||||
}
|
||||
finally
|
||||
{
|
||||
renderer?.Dispose();
|
||||
source?.Dispose();
|
||||
context?.Dispose();
|
||||
devices?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Default.Write($"ProxyForge: 途中まで書き出したファイルを削除できませんでした。{path}", exception);
|
||||
}
|
||||
}
|
||||
|
||||
sealed class Session(
|
||||
FFmpegExecutables executables,
|
||||
ProxyEncodeRequest request,
|
||||
ProxyAnalysis analysis,
|
||||
string videoEncoder,
|
||||
GraphicsDevices devices,
|
||||
IGraphicsDevicesAndContext context,
|
||||
IVideoFileSource source,
|
||||
ProxyFrameRenderer renderer) : IProxyEncodeSession
|
||||
{
|
||||
bool disposed;
|
||||
|
||||
public ProxyAnalysis Analysis => analysis;
|
||||
|
||||
public async Task<long> EncodeAsync(int firstFrame, int frameCount, string outputPath, IProgress<double>? progress, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(firstFrame);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameCount);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(firstFrame + frameCount, analysis.FrameCount);
|
||||
|
||||
var directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(request.WorkingDirectory)) + Path.DirectorySeparatorChar;
|
||||
if (!Path.GetFullPath(outputPath).StartsWith(directory, StringComparison.OrdinalIgnoreCase))
|
||||
throw new ArgumentException("The output path must be inside the working directory.", nameof(outputPath));
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var geometry = analysis.Geometry;
|
||||
var frameRate = analysis.FrameRate;
|
||||
var encodeRequest = new FFmpegEncodeRequest(
|
||||
outputPath,
|
||||
geometry.Width,
|
||||
geometry.Height,
|
||||
frameRate,
|
||||
FFmpegArguments.CalculateVideoBitrate(geometry.Width, geometry.Height, frameRate.Value, request.BitrateScale),
|
||||
Math.Max(1, request.KeyFrameInterval),
|
||||
videoEncoder);
|
||||
|
||||
var pump = new FramePump(source, renderer, frameRate, firstFrame, frameCount, geometry, progress);
|
||||
|
||||
try
|
||||
{
|
||||
var result = await FFmpegProcessRunner.RunAsync(
|
||||
executables.FFmpegPath,
|
||||
arguments => FFmpegArguments.WriteEncode(arguments, in encodeRequest),
|
||||
request.WorkingDirectory,
|
||||
pump.WriteAsync,
|
||||
ProcessPriorityClass.BelowNormal,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
{
|
||||
Log.Default.Write(string.Concat("ProxyForge: ffmpeg が失敗しました。", Environment.NewLine, result.Diagnostics));
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.FFmpegFailed, string.Concat(
|
||||
"ffmpeg exited with code ",
|
||||
result.ExitCode.ToString(CultureInfo.InvariantCulture),
|
||||
": ",
|
||||
result.FirstDiagnosticLine(DiagnosticExcerptLength)));
|
||||
}
|
||||
|
||||
var output = new FileInfo(outputPath);
|
||||
if (!output.Exists || output.Length == 0)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.NoOutput, "ffmpeg completed without producing a proxy file.");
|
||||
|
||||
return output.Length;
|
||||
}
|
||||
catch
|
||||
{
|
||||
TryDelete(outputPath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
return;
|
||||
|
||||
disposed = true;
|
||||
renderer.Dispose();
|
||||
source.Dispose();
|
||||
context.Dispose();
|
||||
devices.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
sealed class FramePump(
|
||||
IVideoFileSource source,
|
||||
ProxyFrameRenderer renderer,
|
||||
FrameRate frameRate,
|
||||
int firstFrame,
|
||||
int frameCount,
|
||||
ProxyGeometry geometry,
|
||||
IProgress<double>? progress)
|
||||
{
|
||||
const int ProgressSteps = 100;
|
||||
|
||||
int reportedStep = -1;
|
||||
|
||||
public Task WriteAsync(Stream destination, CancellationToken cancellationToken)
|
||||
=> Task.Factory.StartNew(
|
||||
() => Write(destination, cancellationToken),
|
||||
cancellationToken,
|
||||
TaskCreationOptions.LongRunning,
|
||||
TaskScheduler.Default);
|
||||
|
||||
void Write(Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
|
||||
|
||||
var frameBytes = renderer.FrameByteCount;
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(frameBytes);
|
||||
try
|
||||
{
|
||||
var frame = buffer.AsSpan(0, frameBytes);
|
||||
for (var index = 0; index < frameCount; index++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
source.Update(frameRate.GetSampleTime(firstFrame + index));
|
||||
renderer.Render(frame);
|
||||
if (!FrameAlpha.IsOpaque(frame, geometry.Width, geometry.Height))
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.Transparent, "The video contains transparent pixels.");
|
||||
|
||||
destination.Write(frame);
|
||||
Report(index + 1);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
void Report(int completedFrames)
|
||||
{
|
||||
if (progress is null)
|
||||
return;
|
||||
|
||||
var step = (int)((long)completedFrames * ProgressSteps / frameCount);
|
||||
if (step == reportedStep)
|
||||
return;
|
||||
|
||||
reportedStep = step;
|
||||
progress.Report((double)completedFrames / frameCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using System.Numerics;
|
||||
using Vortice.DCommon;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using Vortice.DXGI;
|
||||
using Vortice.Mathematics;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal sealed class ProxyFrameRenderer : IDisposable
|
||||
{
|
||||
public const float ReferenceDpi = 96f;
|
||||
|
||||
readonly ID2D1DeviceContext6 context;
|
||||
readonly ID2D1Bitmap1 target;
|
||||
readonly ID2D1Bitmap1 readback;
|
||||
readonly List<ID2D1Effect> chain = [];
|
||||
readonly List<ID2D1Image> outputs = [];
|
||||
readonly int width;
|
||||
readonly int height;
|
||||
readonly int stride;
|
||||
bool disposed;
|
||||
|
||||
public int FrameByteCount => stride * height;
|
||||
|
||||
public int HalvingCount { get; }
|
||||
|
||||
public ProxyFrameRenderer(IGraphicsDevicesAndContext devices, ID2D1Image source, DisplayBounds display, ProxyGeometry geometry)
|
||||
{
|
||||
context = devices.DeviceContext;
|
||||
width = geometry.Width;
|
||||
height = geometry.Height;
|
||||
stride = width * FrameAlpha.BytesPerPixel;
|
||||
|
||||
var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied);
|
||||
var size = new SizeI(width, height);
|
||||
|
||||
target = context.CreateBitmap(size, nint.Zero, stride,
|
||||
new BitmapProperties1(pixelFormat, ReferenceDpi, ReferenceDpi, BitmapOptions.Target));
|
||||
readback = context.CreateBitmap(size, nint.Zero, stride,
|
||||
new BitmapProperties1(pixelFormat, ReferenceDpi, ReferenceDpi,
|
||||
BitmapOptions.CpuRead | BitmapOptions.CannotDraw));
|
||||
|
||||
var align = new AffineTransform2D(context)
|
||||
{
|
||||
InterPolationMode = AffineTransform2DInterpolationMode.Linear,
|
||||
BorderMode = BorderMode.Hard,
|
||||
TransformMatrix = Matrix3x2.CreateTranslation(-display.Left, -display.Top),
|
||||
};
|
||||
var extend = new Border(context)
|
||||
{
|
||||
EdgeModeX = BorderEdgeMode.Clamp,
|
||||
EdgeModeY = BorderEdgeMode.Clamp,
|
||||
};
|
||||
var image = Append(extend, Append(align, source));
|
||||
|
||||
var contentWidth = (double)display.Width;
|
||||
var contentHeight = (double)display.Height;
|
||||
while (contentWidth >= 2d * width && contentHeight >= 2d * height)
|
||||
{
|
||||
var halve = new Scale(context)
|
||||
{
|
||||
Value = new Vector2(0.5f, 0.5f),
|
||||
CenterPoint = Vector2.Zero,
|
||||
InterpolationMode = ScaleInterpolationMode.Linear,
|
||||
BorderMode = BorderMode.Hard,
|
||||
};
|
||||
image = Append(halve, image);
|
||||
contentWidth /= 2d;
|
||||
contentHeight /= 2d;
|
||||
HalvingCount++;
|
||||
}
|
||||
|
||||
var fit = new AffineTransform2D(context)
|
||||
{
|
||||
InterPolationMode = AffineTransform2DInterpolationMode.Cubic,
|
||||
BorderMode = BorderMode.Hard,
|
||||
TransformMatrix = Matrix3x2.CreateScale((float)(width / contentWidth), (float)(height / contentHeight)),
|
||||
};
|
||||
Append(fit, image);
|
||||
}
|
||||
|
||||
ID2D1Image Append(ID2D1Effect effect, ID2D1Image input)
|
||||
{
|
||||
effect.SetInput(0, input, true);
|
||||
chain.Add(effect);
|
||||
var output = effect.Output;
|
||||
outputs.Add(output);
|
||||
return output;
|
||||
}
|
||||
|
||||
public void Render(Span<byte> destination)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(destination.Length, FrameByteCount);
|
||||
|
||||
context.Target = target;
|
||||
context.BeginDraw();
|
||||
context.Clear(new Color4(0f, 0f, 0f, 0f));
|
||||
context.DrawImage(outputs[^1], InterpolationMode.Linear, CompositeMode.SourceOver);
|
||||
context.EndDraw();
|
||||
context.Target = null;
|
||||
|
||||
readback.CopyFromBitmap(target);
|
||||
|
||||
var mapped = readback.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
var scanline = (byte*)mapped.Bits;
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
new ReadOnlySpan<byte>(scanline + (long)y * mapped.Pitch, stride)
|
||||
.CopyTo(destination.Slice(y * stride, stride));
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
readback.Unmap();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
return;
|
||||
|
||||
disposed = true;
|
||||
for (var index = chain.Count - 1; index >= 0; index--)
|
||||
{
|
||||
outputs[index].Dispose();
|
||||
chain[index].SetInput(0, null, true);
|
||||
chain[index].Dispose();
|
||||
}
|
||||
|
||||
readback.Dispose();
|
||||
target.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.IO;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
public enum ProxyGenerationStatus
|
||||
{
|
||||
Waiting,
|
||||
Generating,
|
||||
Completed,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
internal sealed class ProxyGenerationItem(string sourcePath, int scale) : Bindable
|
||||
{
|
||||
double progress;
|
||||
ProxyChunkCoverage coverage = ProxyChunkCoverage.Empty;
|
||||
ProxyGenerationStatus status;
|
||||
ProxyEncodeFailure? failure;
|
||||
|
||||
public string SourcePath { get; } = sourcePath;
|
||||
|
||||
public string FileName { get; } = Path.GetFileName(sourcePath);
|
||||
|
||||
public int Scale { get; } = scale;
|
||||
|
||||
public double Progress
|
||||
{
|
||||
get => progress;
|
||||
set => Set(ref progress, value);
|
||||
}
|
||||
|
||||
public ProxyChunkCoverage Coverage
|
||||
{
|
||||
get => coverage;
|
||||
set => Set(ref coverage, value);
|
||||
}
|
||||
|
||||
public ProxyGenerationStatus Status
|
||||
{
|
||||
get => status;
|
||||
set => Set(ref status, value);
|
||||
}
|
||||
|
||||
public ProxyEncodeFailure? Failure
|
||||
{
|
||||
get => failure;
|
||||
set => Set(ref failure, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal readonly record struct ProxyEncodeOptions(int BitrateScale, int KeyFrameInterval, int ChunkSeconds, bool UsesHardwareEncoder);
|
||||
|
||||
internal sealed class ProxyGenerationQueue(
|
||||
ProxyCache cache,
|
||||
ProxyEncodeSessionFactory open,
|
||||
Func<ProxyEncodeOptions> options,
|
||||
Func<ExportPhase> exportPhase,
|
||||
SourceFocus focus,
|
||||
Action<Exception> reportUnexpected,
|
||||
Action<Action> onUi)
|
||||
{
|
||||
public static readonly TimeSpan ExportPollInterval = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
readonly record struct Key(SourceIdentity Source, int Scale);
|
||||
|
||||
sealed class ChunkProgress(ProxyGenerationItem item, ProxyCacheEntry entry, int chunk, Action<Action> onUi) : IProgress<double>
|
||||
{
|
||||
public void Report(double value)
|
||||
{
|
||||
var fraction = Math.Clamp(value, 0d, 1d);
|
||||
onUi(() =>
|
||||
{
|
||||
item.Progress = (entry.Chunks.Count + fraction) / entry.ChunkCount;
|
||||
item.Coverage = new ProxyChunkCoverage(entry.ChunkCount, entry.Chunks, chunk, fraction);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
readonly Lock gate = new();
|
||||
readonly Dictionary<Key, (CancellationTokenSource Cancellation, Task Task)> pending = [];
|
||||
readonly HashSet<Key> failures = [];
|
||||
readonly SemaphoreSlim slot = new(1, 1);
|
||||
|
||||
public static ProxyGenerationQueue Shared { get; } = new(
|
||||
ProxyCache.Shared,
|
||||
(request, cancellationToken) => new ProxyEncoder(FFmpegRuntime.Executables, VideoSourceLoader.Load).OpenAsync(request, cancellationToken),
|
||||
() => new ProxyEncodeOptions(ProxyForgeSettings.Default.BitrateScale, ProxyForgeSettings.Default.KeyFrameInterval, ProxyForgeSettings.Default.ChunkSeconds, ProxyForgeSettings.Default.UsesHardwareEncoder),
|
||||
ExportDetector.Shared.Resolve,
|
||||
SourceFocus.Shared,
|
||||
ProxyForgeTelemetry.Report,
|
||||
UiThread.Post);
|
||||
|
||||
public ObservableCollection<ProxyGenerationItem> Items { get; } = [];
|
||||
|
||||
public TimeSpan CompletedRetention { get; set; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
public TimeSpan CancelledRetention { get; set; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
public TimeSpan FailedRetention { get; set; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
public event Action<SourceIdentity, int, ProxyCacheEntry>? ChunkCompleted;
|
||||
|
||||
public event Action<SourceIdentity, int>? EntryDiscarded;
|
||||
|
||||
public bool IsPending(SourceIdentity source, int scale)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
return pending.ContainsKey(new Key(source, scale));
|
||||
}
|
||||
|
||||
public bool HasFailed(SourceIdentity source, int scale)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
return failures.Contains(new Key(source, scale));
|
||||
}
|
||||
|
||||
public bool TryEnqueue(SourceIdentity source, int scale)
|
||||
{
|
||||
var key = new Key(source, scale);
|
||||
var item = new ProxyGenerationItem(source.Path, scale);
|
||||
var cancellation = new CancellationTokenSource();
|
||||
|
||||
using (gate.EnterScope())
|
||||
{
|
||||
if (pending.ContainsKey(key) || failures.Contains(key))
|
||||
{
|
||||
cancellation.Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
var task = Task.Run(() => RunAsync(key, item, cancellation));
|
||||
pending[key] = (cancellation, task);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public Task WhenIdleAsync()
|
||||
{
|
||||
Task[] tasks;
|
||||
using (gate.EnterScope())
|
||||
tasks = pending.Values.Select(job => job.Task).ToArray();
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
public void ForgetFailures()
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
failures.Clear();
|
||||
}
|
||||
|
||||
public void CancelAll()
|
||||
{
|
||||
(CancellationTokenSource Cancellation, Task Task)[] jobs;
|
||||
using (gate.EnterScope())
|
||||
jobs = pending.Values.ToArray();
|
||||
|
||||
foreach (var job in jobs)
|
||||
{
|
||||
try
|
||||
{
|
||||
job.Cancellation.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async Task RunAsync(Key key, ProxyGenerationItem item, CancellationTokenSource cancellation)
|
||||
{
|
||||
var token = cancellation.Token;
|
||||
var retention = CompletedRetention;
|
||||
onUi(() => Items.Add(item));
|
||||
|
||||
try
|
||||
{
|
||||
await slot.WaitAsync(token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await WaitForExportToEndAsync(token).ConfigureAwait(false);
|
||||
onUi(() => item.Status = ProxyGenerationStatus.Generating);
|
||||
await GenerateAsync(key, item, token).ConfigureAwait(false);
|
||||
onUi(() =>
|
||||
{
|
||||
item.Progress = 1d;
|
||||
item.Status = ProxyGenerationStatus.Completed;
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
slot.Release();
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
retention = CancelledRetention;
|
||||
onUi(() => item.Status = ProxyGenerationStatus.Cancelled);
|
||||
}
|
||||
catch (ProxyEncodeException exception)
|
||||
{
|
||||
retention = FailedRetention;
|
||||
RememberFailure(key, exception);
|
||||
Log.Default.Write($"ProxyForge: プロキシを生成できませんでした。{key.Source.Path}", exception);
|
||||
onUi(() =>
|
||||
{
|
||||
item.Failure = exception.Failure;
|
||||
item.Status = ProxyGenerationStatus.Failed;
|
||||
});
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
retention = FailedRetention;
|
||||
RememberFailure(key, null);
|
||||
Log.Default.Write($"ProxyForge: プロキシの生成で想定していない例外が起きました。{key.Source.Path}", exception);
|
||||
reportUnexpected(exception);
|
||||
onUi(() => item.Status = ProxyGenerationStatus.Failed);
|
||||
}
|
||||
finally
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
pending.Remove(key);
|
||||
cancellation.Dispose();
|
||||
}
|
||||
|
||||
await Task.Delay(retention, CancellationToken.None).ConfigureAwait(false);
|
||||
onUi(() => Items.Remove(item));
|
||||
}
|
||||
|
||||
async Task WaitForExportToEndAsync(CancellationToken token)
|
||||
{
|
||||
while (exportPhase() != ExportPhase.Idle)
|
||||
await Task.Delay(ExportPollInterval, token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
async Task GenerateAsync(Key key, ProxyGenerationItem item, CancellationToken token)
|
||||
{
|
||||
var current = options();
|
||||
var request = new ProxyEncodeRequest(
|
||||
key.Source.Path,
|
||||
cache.DirectoryPath,
|
||||
key.Scale,
|
||||
current.BitrateScale,
|
||||
current.KeyFrameInterval,
|
||||
current.UsesHardwareEncoder);
|
||||
|
||||
using var session = await open(request, token).ConfigureAwait(false);
|
||||
var analysis = session.Analysis;
|
||||
var entry = cache.Register(Describe(key, analysis, ProxyChunkPlan.LengthFor(analysis.FrameRate, current.ChunkSeconds)));
|
||||
var chunkCount = entry.ChunkCount;
|
||||
Publish(item, entry, null);
|
||||
|
||||
while (ProxyChunkPlan.Next(entry.Chunks, chunkCount, entry.ChunkLength, focus.Get(key.Source)) is { } chunk)
|
||||
{
|
||||
await WaitForExportToEndAsync(token).ConfigureAwait(false);
|
||||
|
||||
var firstFrame = chunk * entry.ChunkLength;
|
||||
var frameCount = Math.Min(entry.ChunkLength, analysis.FrameCount - firstFrame);
|
||||
var temporaryPath = cache.CreateTemporaryPath();
|
||||
ProxyCacheEntry? updated;
|
||||
try
|
||||
{
|
||||
Publish(item, entry, chunk);
|
||||
await session.EncodeAsync(firstFrame, frameCount, temporaryPath, new ChunkProgress(item, entry, chunk, onUi), token).ConfigureAwait(false);
|
||||
if (SourceIdentity.Of(key.Source.Path) != key.Source)
|
||||
throw new ProxyEncodeException(ProxyEncodeFailure.SourceChanged, "The source file changed while the proxy was being generated.");
|
||||
|
||||
updated = cache.AddChunk(entry.Id, chunk, temporaryPath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
TryDelete(temporaryPath);
|
||||
throw;
|
||||
}
|
||||
|
||||
if (updated is null)
|
||||
throw new OperationCanceledException();
|
||||
|
||||
entry = updated;
|
||||
Publish(item, entry, null);
|
||||
ChunkCompleted?.Invoke(key.Source, key.Scale, entry);
|
||||
}
|
||||
}
|
||||
|
||||
void Publish(ProxyGenerationItem item, ProxyCacheEntry entry, int? chunk)
|
||||
=> onUi(() =>
|
||||
{
|
||||
item.Progress = (double)entry.Chunks.Count / entry.ChunkCount;
|
||||
item.Coverage = new ProxyChunkCoverage(entry.ChunkCount, entry.Chunks, chunk, 0d);
|
||||
});
|
||||
|
||||
static ProxyCacheEntry Describe(Key key, ProxyAnalysis analysis, int chunkLength) => new()
|
||||
{
|
||||
SourcePath = key.Source.Path,
|
||||
SourceLength = key.Source.Length,
|
||||
SourceWriteTimeTicks = key.Source.WriteTimeTicks,
|
||||
Scale = key.Scale,
|
||||
ProxyWidth = analysis.Geometry.Width,
|
||||
ProxyHeight = analysis.Geometry.Height,
|
||||
DisplayLeft = analysis.Display.Left,
|
||||
DisplayTop = analysis.Display.Top,
|
||||
DisplayWidth = analysis.Display.Width,
|
||||
DisplayHeight = analysis.Display.Height,
|
||||
FrameRateNumerator = analysis.FrameRate.Numerator,
|
||||
FrameRateDenominator = analysis.FrameRate.Denominator,
|
||||
DurationTicks = analysis.Duration.Ticks,
|
||||
FrameCount = analysis.FrameCount,
|
||||
ChunkLength = chunkLength,
|
||||
};
|
||||
|
||||
void RememberFailure(Key key, ProxyEncodeException? exception)
|
||||
{
|
||||
using (gate.EnterScope())
|
||||
failures.Add(key);
|
||||
|
||||
if (exception?.Failure is not (ProxyEncodeFailure.Transparent or ProxyEncodeFailure.SourceChanged))
|
||||
return;
|
||||
|
||||
if (exception.Failure == ProxyEncodeFailure.Transparent)
|
||||
cache.AddSkip(key.Source, ProxyCacheSkipReason.Transparent);
|
||||
|
||||
var entry = cache.Find(key.Source, key.Scale);
|
||||
if (entry is not null && cache.Remove(entry.Id))
|
||||
EntryDiscarded?.Invoke(key.Source, key.Scale);
|
||||
}
|
||||
|
||||
static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Default.Write($"ProxyForge: 途中まで書き出したファイルを削除できませんでした。{path}", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace ProxyForge.Encoding;
|
||||
|
||||
internal readonly record struct ProxyGeometry(int Width, int Height);
|
||||
|
||||
internal static class ProxyGeometryCalculator
|
||||
{
|
||||
public const int MinimumDimension = 2;
|
||||
public const int MaximumDimension = 16384;
|
||||
public const int MinimumScale = 10;
|
||||
public const int MaximumScale = 100;
|
||||
|
||||
public static int AlignEven(int value)
|
||||
{
|
||||
var aligned = value & ~1;
|
||||
return aligned < MinimumDimension ? MinimumDimension : aligned;
|
||||
}
|
||||
|
||||
public static ProxyGeometry Calculate(int displayWidth, int displayHeight, int scale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(displayWidth, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(displayHeight, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(displayWidth, MaximumDimension);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(displayHeight, MaximumDimension);
|
||||
|
||||
var clamped = Math.Clamp(scale, MinimumScale, MaximumScale);
|
||||
return new ProxyGeometry(
|
||||
ScaleDimension(displayWidth, clamped),
|
||||
ScaleDimension(displayHeight, clamped));
|
||||
}
|
||||
|
||||
static int ScaleDimension(int dimension, int scale)
|
||||
=> AlignEven((int)Math.Round(dimension * (double)scale / MaximumScale, MidpointRounding.AwayFromZero));
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using HostTexts = YukkuriMovieMaker.Resources.Localization.Texts;
|
||||
|
||||
namespace ProxyForge.Export;
|
||||
|
||||
public enum ExportPhase
|
||||
{
|
||||
Idle,
|
||||
Preparing,
|
||||
Exporting,
|
||||
}
|
||||
|
||||
public enum ExportWindowRole
|
||||
{
|
||||
None,
|
||||
Configuration,
|
||||
Progress,
|
||||
}
|
||||
|
||||
internal sealed class ExportDetector(
|
||||
bool commandLineEncode,
|
||||
Func<string> configurationTitle,
|
||||
Func<string> progressTitle,
|
||||
Func<ExportPhase?> resolvePhase)
|
||||
{
|
||||
public const string EncodeOption = "--encode";
|
||||
|
||||
int phase;
|
||||
|
||||
public static ExportDetector Shared { get; } = new(
|
||||
HasEncodeOption(Environment.GetCommandLineArgs()),
|
||||
() => HostTexts.VideoExportWindowTitle,
|
||||
() => HostTexts.OutputProgressWindowTitle,
|
||||
ExportWindowWatcher.ResolvePhase);
|
||||
|
||||
public bool IsCommandLineEncode => commandLineEncode;
|
||||
|
||||
public ExportPhase Phase => (ExportPhase)Volatile.Read(ref phase);
|
||||
|
||||
public static bool HasEncodeOption(string[] arguments)
|
||||
{
|
||||
var index = Array.FindIndex(arguments, argument => string.Equals(argument, EncodeOption, StringComparison.OrdinalIgnoreCase));
|
||||
if (index < 0 || index + 1 >= arguments.Length)
|
||||
return false;
|
||||
|
||||
var input = arguments[index + 1];
|
||||
return !string.IsNullOrWhiteSpace(input) && !input.StartsWith("--", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public ExportWindowRole Classify(ReadOnlySpan<char> title)
|
||||
{
|
||||
if (title.IsEmpty)
|
||||
return ExportWindowRole.None;
|
||||
if (title.SequenceEqual(progressTitle()))
|
||||
return ExportWindowRole.Progress;
|
||||
if (title.SequenceEqual(configurationTitle()))
|
||||
return ExportWindowRole.Configuration;
|
||||
return ExportWindowRole.None;
|
||||
}
|
||||
|
||||
public void OnWindowOpened(ExportWindowRole role)
|
||||
{
|
||||
switch (role)
|
||||
{
|
||||
case ExportWindowRole.Configuration:
|
||||
Interlocked.CompareExchange(ref phase, (int)ExportPhase.Preparing, (int)ExportPhase.Idle);
|
||||
break;
|
||||
case ExportWindowRole.Progress:
|
||||
Interlocked.Exchange(ref phase, (int)ExportPhase.Exporting);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnWindowClosed(ExportWindowRole role)
|
||||
{
|
||||
if (role == ExportWindowRole.Progress)
|
||||
Interlocked.Exchange(ref phase, (int)ExportPhase.Idle);
|
||||
}
|
||||
|
||||
public bool IsExporting() => Resolve() == ExportPhase.Exporting;
|
||||
|
||||
public ExportPhase Resolve()
|
||||
{
|
||||
if (commandLineEncode)
|
||||
return ExportPhase.Exporting;
|
||||
|
||||
var current = Phase;
|
||||
if (current != ExportPhase.Preparing)
|
||||
return current;
|
||||
|
||||
switch (resolvePhase())
|
||||
{
|
||||
case ExportPhase.Idle:
|
||||
var previous = (ExportPhase)Interlocked.CompareExchange(ref phase, (int)ExportPhase.Idle, (int)ExportPhase.Preparing);
|
||||
return previous == ExportPhase.Preparing ? ExportPhase.Idle : previous;
|
||||
case ExportPhase.Preparing:
|
||||
return ExportPhase.Preparing;
|
||||
default:
|
||||
return ExportPhase.Exporting;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Threading;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Export;
|
||||
|
||||
internal static unsafe partial class ExportWindowWatcher
|
||||
{
|
||||
const uint EventObjectDestroy = 0x8001;
|
||||
const uint EventObjectShow = 0x8002;
|
||||
const uint EventObjectHide = 0x8003;
|
||||
const uint EventObjectNameChange = 0x800C;
|
||||
const uint OutOfContext = 0;
|
||||
const uint AncestorParent = 1;
|
||||
const int TitleCapacity = 256;
|
||||
static readonly TimeSpan ResolveTimeout = TimeSpan.FromSeconds(3);
|
||||
|
||||
static readonly Dictionary<nint, ExportWindowRole> windows = [];
|
||||
static ExportDetector? detector;
|
||||
static Action<Exception>? reportUnexpected;
|
||||
static Dispatcher? dispatcher;
|
||||
static nint visibilityHook;
|
||||
static nint nameHook;
|
||||
static uint threadId;
|
||||
static ExportPhase scanned;
|
||||
|
||||
public static bool IsAttached => visibilityHook != 0;
|
||||
|
||||
public static void Attach(ExportDetector detector, Action<Exception> reportUnexpected)
|
||||
{
|
||||
if (IsAttached)
|
||||
return;
|
||||
|
||||
ExportWindowWatcher.detector = detector;
|
||||
ExportWindowWatcher.reportUnexpected = reportUnexpected;
|
||||
threadId = GetCurrentThreadId();
|
||||
var process = (uint)Environment.ProcessId;
|
||||
visibilityHook = SetWinEventHook(EventObjectDestroy, EventObjectHide, 0, &OnWinEvent, process, threadId, OutOfContext);
|
||||
nameHook = SetWinEventHook(EventObjectNameChange, EventObjectNameChange, 0, &OnWinEvent, process, threadId, OutOfContext);
|
||||
if (visibilityHook == 0 || nameHook == 0)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: 出力ウィンドウの監視を開始できませんでした。");
|
||||
Detach();
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref dispatcher, Dispatcher.CurrentDispatcher);
|
||||
}
|
||||
|
||||
public static void Detach()
|
||||
{
|
||||
Volatile.Write(ref dispatcher, null);
|
||||
if (visibilityHook != 0)
|
||||
UnhookWinEvent(visibilityHook);
|
||||
if (nameHook != 0)
|
||||
UnhookWinEvent(nameHook);
|
||||
|
||||
visibilityHook = 0;
|
||||
nameHook = 0;
|
||||
windows.Clear();
|
||||
detector = null;
|
||||
reportUnexpected = null;
|
||||
}
|
||||
|
||||
public static ExportPhase? ResolvePhase()
|
||||
{
|
||||
var target = Volatile.Read(ref dispatcher);
|
||||
if (target is null || target.HasShutdownStarted)
|
||||
return null;
|
||||
if (target.CheckAccess())
|
||||
return Scan();
|
||||
|
||||
try
|
||||
{
|
||||
var operation = target.InvokeAsync(Scan, DispatcherPriority.ContextIdle);
|
||||
if (operation.Task.Wait(ResolveTimeout))
|
||||
return operation.Result;
|
||||
|
||||
operation.Abort();
|
||||
return null;
|
||||
}
|
||||
catch (Exception exception) when (exception is TaskCanceledException or AggregateException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static ExportPhase? Scan()
|
||||
{
|
||||
if (detector is null)
|
||||
return null;
|
||||
|
||||
scanned = ComponentDispatcher.IsThreadModal ? ExportPhase.Preparing : ExportPhase.Idle;
|
||||
EnumThreadWindows(threadId, &OnWindowEnumerated, 0);
|
||||
return scanned;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
|
||||
static void OnWinEvent(nint hook, uint eventType, nint window, int objectId, int childId, uint eventThread, uint eventTime)
|
||||
{
|
||||
if (objectId != 0 || childId != 0 || window == 0 || detector is not { } current)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Handle(current, eventType, window);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Report(exception);
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
|
||||
static int OnWindowEnumerated(nint window, nint parameter)
|
||||
{
|
||||
if (detector is not { } current)
|
||||
return 0;
|
||||
|
||||
try
|
||||
{
|
||||
return Inspect(current, window) ? 1 : 0;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Report(exception);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void Handle(ExportDetector current, uint eventType, nint window)
|
||||
{
|
||||
switch (eventType)
|
||||
{
|
||||
case EventObjectShow:
|
||||
case EventObjectNameChange:
|
||||
if (!windows.ContainsKey(window) && IsWindowVisible(window) && GetAncestor(window, AncestorParent) == GetDesktopWindow())
|
||||
Track(current, window);
|
||||
break;
|
||||
case EventObjectHide:
|
||||
case EventObjectDestroy:
|
||||
if (windows.Remove(window, out var role))
|
||||
current.OnWindowClosed(role);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void Track(ExportDetector current, nint window)
|
||||
{
|
||||
Span<char> title = stackalloc char[TitleCapacity];
|
||||
var role = current.Classify(ReadTitle(window, title));
|
||||
if (role == ExportWindowRole.None)
|
||||
return;
|
||||
|
||||
windows[window] = role;
|
||||
current.OnWindowOpened(role);
|
||||
}
|
||||
|
||||
static bool Inspect(ExportDetector current, nint window)
|
||||
{
|
||||
if (!IsWindowVisible(window))
|
||||
return true;
|
||||
|
||||
Span<char> title = stackalloc char[TitleCapacity];
|
||||
switch (current.Classify(ReadTitle(window, title)))
|
||||
{
|
||||
case ExportWindowRole.Progress:
|
||||
scanned = ExportPhase.Exporting;
|
||||
return false;
|
||||
case ExportWindowRole.Configuration:
|
||||
scanned = ExportPhase.Preparing;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!IsWindowEnabled(window))
|
||||
scanned = ExportPhase.Preparing;
|
||||
return true;
|
||||
}
|
||||
|
||||
static ReadOnlySpan<char> ReadTitle(nint window, Span<char> buffer)
|
||||
{
|
||||
fixed (char* pointer = buffer)
|
||||
{
|
||||
var length = GetWindowText(window, pointer, buffer.Length);
|
||||
return buffer[..Math.Max(length, 0)];
|
||||
}
|
||||
}
|
||||
|
||||
static void Report(Exception exception)
|
||||
{
|
||||
Log.Default.Write("ProxyForge: 出力ウィンドウの監視で想定していない例外が起きました。", exception);
|
||||
reportUnexpected?.Invoke(exception);
|
||||
}
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint SetWinEventHook(uint eventMin, uint eventMax, nint module, delegate* unmanaged[Stdcall]<nint, uint, nint, int, int, uint, uint, void> procedure, uint processId, uint threadId, uint flags);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool UnhookWinEvent(nint hook);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool EnumThreadWindows(uint threadId, delegate* unmanaged[Stdcall]<nint, nint, int> callback, nint parameter);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool IsWindowVisible(nint window);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool IsWindowEnabled(nint window);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint GetAncestor(nint window, uint flags);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
private static partial nint GetDesktopWindow();
|
||||
|
||||
[LibraryImport("user32.dll", EntryPoint = "GetWindowTextW")]
|
||||
private static partial int GetWindowText(nint window, char* buffer, int capacity);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial uint GetCurrentThreadId();
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace ProxyForge.Interfaces;
|
||||
|
||||
internal interface IDialogService
|
||||
{
|
||||
void ShowInformation(string message, string title);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace ProxyForge.Interfaces;
|
||||
|
||||
internal interface IExportDetector
|
||||
{
|
||||
bool IsExporting();
|
||||
void Reset();
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
using ProxyForge.Core;
|
||||
using ProxyForge.Progress;
|
||||
|
||||
namespace ProxyForge.Interfaces;
|
||||
|
||||
internal interface IProxyEncoder : IDisposable
|
||||
{
|
||||
Task<ProxyCacheEntry> EncodeAsync(
|
||||
string inputPath, float scale, float bitrateFactor, int gopSize,
|
||||
ProxyGenerationItem? progressItem, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace ProxyForge.Interfaces;
|
||||
|
||||
internal interface IProxyEncoderFactory
|
||||
{
|
||||
IProxyEncoder Create();
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
namespace ProxyForge.Interfaces;
|
||||
|
||||
internal interface IVideoCacheDatabase : IDisposable
|
||||
{
|
||||
bool TryGet(string originalPath, float scale, out VideoCacheLookupResult result);
|
||||
VideoCacheLookupResult[] GetAll();
|
||||
void Add(string originalPath, float scale, uint proxyWidth, uint proxyHeight,
|
||||
long fileSize, uint fileCrc32, Guid uuid);
|
||||
bool Remove(Guid uuid);
|
||||
int RemoveByPath(string originalPath);
|
||||
int ClearAll();
|
||||
void UpdateLastAccess(Guid uuid);
|
||||
string GetCacheFilePath(Guid uuid);
|
||||
string CacheDirectory { get; }
|
||||
}
|
||||
|
||||
internal readonly record struct VideoCacheLookupResult(
|
||||
Guid Uuid,
|
||||
string OriginalPath,
|
||||
string FileName,
|
||||
float Scale,
|
||||
uint ProxyWidth,
|
||||
uint ProxyHeight,
|
||||
long FileSize,
|
||||
uint FileCrc32,
|
||||
DateTime CreatedAt,
|
||||
DateTime LastAccessedAt
|
||||
);
|
||||
@@ -1,8 +0,0 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace ProxyForge.Interfaces;
|
||||
|
||||
internal interface IWindowThemeService
|
||||
{
|
||||
void Bind(Window window);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ProxyForge.Interop;
|
||||
|
||||
internal static class HResultExtensions
|
||||
{
|
||||
internal const int S_OK = 0;
|
||||
internal const int S_FALSE = 1;
|
||||
internal const int MF_E_NO_MORE_TYPES = unchecked((int)0xC00D36B9);
|
||||
internal const int MF_E_TRANSFORM_NEED_MORE_INPUT = unchecked((int)0xC00D6D72);
|
||||
internal const int E_FAIL = unchecked((int)0x80004005);
|
||||
internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E);
|
||||
internal const int E_NOTIMPL = unchecked((int)0x80004001);
|
||||
|
||||
internal static void ThrowOnFailure(int hr, string? context = null)
|
||||
{
|
||||
if (hr >= 0)
|
||||
return;
|
||||
|
||||
var message = context is not null
|
||||
? string.Concat("[ZeroDiskProxy] ", context, ": HRESULT 0x", hr.ToString("X8"))
|
||||
: string.Concat("[ZeroDiskProxy] HRESULT 0x", hr.ToString("X8"));
|
||||
|
||||
throw hr switch
|
||||
{
|
||||
E_OUTOFMEMORY => new OutOfMemoryException(message),
|
||||
E_NOTIMPL => new NotImplementedException(message),
|
||||
_ => Marshal.GetExceptionForHR(hr) ?? new COMException(message, hr),
|
||||
};
|
||||
}
|
||||
|
||||
internal static bool Succeeded(int hr) => hr >= 0;
|
||||
internal static bool Failed(int hr) => hr < 0;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
namespace ProxyForge.Interop;
|
||||
|
||||
internal static class MfAttributeKeys
|
||||
{
|
||||
internal static readonly Guid MF_MT_MAJOR_TYPE = new("48eba18e-f8c9-4687-bf11-0a74c9f96a8f");
|
||||
internal static readonly Guid MF_MT_SUBTYPE = new("f7e34c9a-42e8-4714-b74b-cb29d72c35e5");
|
||||
internal static readonly Guid MF_MT_FRAME_SIZE = new("1652c33d-d6b2-4012-b834-72030849a37d");
|
||||
internal static readonly Guid MF_MT_FRAME_RATE = new("c459a2e8-3d2c-4e44-b132-fee5156c7bb0");
|
||||
internal static readonly Guid MF_MT_AVG_BITRATE = new("20332624-fb0d-4d9e-bd0d-cbf6786c102e");
|
||||
internal static readonly Guid MF_MT_INTERLACE_MODE = new("e2724bb8-e676-4806-b4b2-a8d6efb44ccd");
|
||||
internal static readonly Guid MF_MT_DEFAULT_STRIDE = new("644b4e48-1e02-4516-b0eb-c01ca9d49ac5");
|
||||
internal static readonly Guid MF_MT_MPEG2_PROFILE = new("ad76a80b-2d5c-4e0b-b375-64e520137036");
|
||||
internal static readonly Guid MF_MT_MPEG2_LEVEL = new("96f66574-11c5-4015-8666-bff516436da7");
|
||||
|
||||
internal static readonly Guid MFMediaType_Video = new("73646976-0000-0010-8000-00aa00389b71");
|
||||
internal static readonly Guid MFMediaType_Audio = new("73647561-0000-0010-8000-00aa00389b71");
|
||||
internal static readonly Guid MFVideoFormat_H264 = new("34363248-0000-0010-8000-00aa00389b71");
|
||||
internal static readonly Guid MFVideoFormat_NV12 = new("3231564e-0000-0010-8000-00aa00389b71");
|
||||
internal static readonly Guid MFVideoFormat_RGB32 = new("00000016-0000-0010-8000-00aa00389b71");
|
||||
|
||||
internal static readonly Guid MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS = new("a634a91c-822b-41b9-a494-4de4643612b0");
|
||||
internal static readonly Guid MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING = new("f81da2c0-b537-4672-a8b2-a681b17307a3");
|
||||
internal static readonly Guid MF_SINK_WRITER_DISABLE_THROTTLING = new("08b845d8-2b74-4afe-9d53-be16d2d5ae4f");
|
||||
internal static readonly Guid MF_LOW_LATENCY = new("9c27891a-ed7a-40e1-88e8-b22727a024ee");
|
||||
|
||||
internal static readonly Guid MF_PD_DURATION = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a");
|
||||
internal static readonly Guid MF_SOURCE_READER_MEDIASOURCE_CHARACTERISTICS = new("6d23f5c8-c5d7-4a9b-9971-5d11f8bca880");
|
||||
}
|
||||
@@ -1,392 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ProxyForge.Interop;
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")]
|
||||
internal interface IMFSourceReader
|
||||
{
|
||||
[PreserveSig]
|
||||
int GetStreamSelection(uint dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] out bool pfSelected);
|
||||
|
||||
[PreserveSig]
|
||||
int SetStreamSelection(uint dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] bool fSelected);
|
||||
|
||||
[PreserveSig]
|
||||
int GetNativeMediaType(uint dwStreamIndex, uint dwMediaTypeIndex, out IMFMediaType ppMediaType);
|
||||
|
||||
[PreserveSig]
|
||||
int GetCurrentMediaType(uint dwStreamIndex, out IMFMediaType ppMediaType);
|
||||
|
||||
[PreserveSig]
|
||||
int SetCurrentMediaType(uint dwStreamIndex, nint pdwReserved, IMFMediaType pMediaType);
|
||||
|
||||
[PreserveSig]
|
||||
int SetCurrentPosition(in Guid guidTimeFormat, in PropVariant varPosition);
|
||||
|
||||
[PreserveSig]
|
||||
int ReadSample(
|
||||
uint dwStreamIndex, uint dwControlFlags,
|
||||
out uint pdwActualStreamIndex, out uint pdwStreamFlags,
|
||||
out long pllTimestamp, out IMFSample? ppSample);
|
||||
|
||||
[PreserveSig]
|
||||
int Flush(uint dwStreamIndex);
|
||||
|
||||
[PreserveSig]
|
||||
int GetServiceForStream(uint dwStreamIndex, in Guid guidService, in Guid riid, out nint ppvObject);
|
||||
|
||||
[PreserveSig]
|
||||
int GetPresentationAttribute(uint dwStreamIndex, in Guid guidAttribute, nint pvarAttribute);
|
||||
}
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("3137f1cd-fe5e-4805-a5d8-fb477448cb3d")]
|
||||
internal interface IMFSinkWriter
|
||||
{
|
||||
[PreserveSig]
|
||||
int AddStream(IMFMediaType pTargetMediaType, out uint pdwStreamIndex);
|
||||
|
||||
[PreserveSig]
|
||||
int SetInputMediaType(uint dwStreamIndex, IMFMediaType pInputMediaType, IMFAttributes? pEncodingParameters);
|
||||
|
||||
[PreserveSig]
|
||||
int BeginWriting();
|
||||
|
||||
[PreserveSig]
|
||||
int WriteSample(uint dwStreamIndex, IMFSample pSample);
|
||||
|
||||
[PreserveSig]
|
||||
int SendStreamTick(uint dwStreamIndex, long llTimestamp);
|
||||
|
||||
[PreserveSig]
|
||||
int PlaceSampleMarker(uint dwStreamIndex, nint pvContext);
|
||||
|
||||
[PreserveSig]
|
||||
int NotifyEndOfSegment(uint dwStreamIndex);
|
||||
|
||||
[PreserveSig]
|
||||
int Flush(uint dwStreamIndex);
|
||||
|
||||
[PreserveSig]
|
||||
int Finalize_();
|
||||
|
||||
[PreserveSig]
|
||||
int GetServiceForStream(uint dwStreamIndex, in Guid guidService, in Guid riid, out nint ppvObject);
|
||||
|
||||
[PreserveSig]
|
||||
int GetStatistics(uint dwStreamIndex, out MF_SINK_WRITER_STATISTICS pStats);
|
||||
}
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("44ae0fa8-ea31-4109-8d2e-4cae4997c555")]
|
||||
internal interface IMFMediaType : IMFAttributes
|
||||
{
|
||||
[PreserveSig]
|
||||
new int GetItem(in Guid guidKey, nint pValue);
|
||||
[PreserveSig]
|
||||
new int GetItemType(in Guid guidKey, out uint pType);
|
||||
[PreserveSig]
|
||||
new int CompareItem(in Guid guidKey, nint Value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);
|
||||
[PreserveSig]
|
||||
new int Compare(IMFAttributes pTheirs, uint MatchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);
|
||||
[PreserveSig]
|
||||
new int GetUINT32(in Guid guidKey, out uint punValue);
|
||||
[PreserveSig]
|
||||
new int GetUINT64(in Guid guidKey, out ulong punValue);
|
||||
[PreserveSig]
|
||||
new int GetDouble(in Guid guidKey, out double pfValue);
|
||||
[PreserveSig]
|
||||
new int GetGUID(in Guid guidKey, out Guid pguidValue);
|
||||
[PreserveSig]
|
||||
new int GetStringLength(in Guid guidKey, out uint pcchLength);
|
||||
[PreserveSig]
|
||||
new int GetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string pwszValue, uint cchBufSize, nint pcchLength);
|
||||
[PreserveSig]
|
||||
new int GetAllocatedString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out uint pcchLength);
|
||||
[PreserveSig]
|
||||
new int GetBlobSize(in Guid guidKey, out uint pcbBlobSize);
|
||||
[PreserveSig]
|
||||
new int GetBlob(in Guid guidKey, nint pBuf, uint cbBufSize, nint pcbBlobSize);
|
||||
[PreserveSig]
|
||||
new int GetAllocatedBlob(in Guid guidKey, out nint ppBuf, out uint pcbSize);
|
||||
[PreserveSig]
|
||||
new int GetUnknown(in Guid guidKey, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
|
||||
[PreserveSig]
|
||||
new int SetItem(in Guid guidKey, nint Value);
|
||||
[PreserveSig]
|
||||
new int DeleteItem(in Guid guidKey);
|
||||
[PreserveSig]
|
||||
new int DeleteAllItems();
|
||||
[PreserveSig]
|
||||
new int SetUINT32(in Guid guidKey, uint unValue);
|
||||
[PreserveSig]
|
||||
new int SetUINT64(in Guid guidKey, ulong unValue);
|
||||
[PreserveSig]
|
||||
new int SetDouble(in Guid guidKey, double fValue);
|
||||
[PreserveSig]
|
||||
new int SetGUID(in Guid guidKey, in Guid guidValue);
|
||||
[PreserveSig]
|
||||
new int SetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] string wszValue);
|
||||
[PreserveSig]
|
||||
new int SetBlob(in Guid guidKey, nint pBuf, uint cbBufSize);
|
||||
[PreserveSig]
|
||||
new int SetUnknown(in Guid guidKey, [MarshalAs(UnmanagedType.IUnknown)] object pUnknown);
|
||||
[PreserveSig]
|
||||
new int LockStore();
|
||||
[PreserveSig]
|
||||
new int UnlockStore();
|
||||
[PreserveSig]
|
||||
new int GetCount(out uint pcItems);
|
||||
[PreserveSig]
|
||||
new int GetItemByIndex(uint unIndex, out Guid pguidKey, nint pValue);
|
||||
[PreserveSig]
|
||||
new int CopyAllItems(IMFAttributes pDest);
|
||||
|
||||
[PreserveSig]
|
||||
int GetMajorType(out Guid pguidMajorType);
|
||||
[PreserveSig]
|
||||
int IsCompressedFormat([MarshalAs(UnmanagedType.Bool)] out bool pfCompressed);
|
||||
[PreserveSig]
|
||||
int IsEqual(IMFMediaType pIMediaType, out uint pdwFlags);
|
||||
[PreserveSig]
|
||||
int GetRepresentation(Guid guidRepresentation, out nint ppvRepresentation);
|
||||
[PreserveSig]
|
||||
int FreeRepresentation(Guid guidRepresentation, nint pvRepresentation);
|
||||
}
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("2cd2d921-c447-44a7-a13c-4adabfc247e3")]
|
||||
internal interface IMFAttributes
|
||||
{
|
||||
[PreserveSig]
|
||||
int GetItem(in Guid guidKey, nint pValue);
|
||||
[PreserveSig]
|
||||
int GetItemType(in Guid guidKey, out uint pType);
|
||||
[PreserveSig]
|
||||
int CompareItem(in Guid guidKey, nint Value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);
|
||||
[PreserveSig]
|
||||
int Compare(IMFAttributes pTheirs, uint MatchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);
|
||||
[PreserveSig]
|
||||
int GetUINT32(in Guid guidKey, out uint punValue);
|
||||
[PreserveSig]
|
||||
int GetUINT64(in Guid guidKey, out ulong punValue);
|
||||
[PreserveSig]
|
||||
int GetDouble(in Guid guidKey, out double pfValue);
|
||||
[PreserveSig]
|
||||
int GetGUID(in Guid guidKey, out Guid pguidValue);
|
||||
[PreserveSig]
|
||||
int GetStringLength(in Guid guidKey, out uint pcchLength);
|
||||
[PreserveSig]
|
||||
int GetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string pwszValue, uint cchBufSize, nint pcchLength);
|
||||
[PreserveSig]
|
||||
int GetAllocatedString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out uint pcchLength);
|
||||
[PreserveSig]
|
||||
int GetBlobSize(in Guid guidKey, out uint pcbBlobSize);
|
||||
[PreserveSig]
|
||||
int GetBlob(in Guid guidKey, nint pBuf, uint cbBufSize, nint pcbBlobSize);
|
||||
[PreserveSig]
|
||||
int GetAllocatedBlob(in Guid guidKey, out nint ppBuf, out uint pcbSize);
|
||||
[PreserveSig]
|
||||
int GetUnknown(in Guid guidKey, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
|
||||
[PreserveSig]
|
||||
int SetItem(in Guid guidKey, nint Value);
|
||||
[PreserveSig]
|
||||
int DeleteItem(in Guid guidKey);
|
||||
[PreserveSig]
|
||||
int DeleteAllItems();
|
||||
[PreserveSig]
|
||||
int SetUINT32(in Guid guidKey, uint unValue);
|
||||
[PreserveSig]
|
||||
int SetUINT64(in Guid guidKey, ulong unValue);
|
||||
[PreserveSig]
|
||||
int SetDouble(in Guid guidKey, double fValue);
|
||||
[PreserveSig]
|
||||
int SetGUID(in Guid guidKey, in Guid guidValue);
|
||||
[PreserveSig]
|
||||
int SetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] string wszValue);
|
||||
[PreserveSig]
|
||||
int SetBlob(in Guid guidKey, nint pBuf, uint cbBufSize);
|
||||
[PreserveSig]
|
||||
int SetUnknown(in Guid guidKey, [MarshalAs(UnmanagedType.IUnknown)] object pUnknown);
|
||||
[PreserveSig]
|
||||
int LockStore();
|
||||
[PreserveSig]
|
||||
int UnlockStore();
|
||||
[PreserveSig]
|
||||
int GetCount(out uint pcItems);
|
||||
[PreserveSig]
|
||||
int GetItemByIndex(uint unIndex, out Guid pguidKey, nint pValue);
|
||||
[PreserveSig]
|
||||
int CopyAllItems(IMFAttributes pDest);
|
||||
}
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("c40a00f2-b93a-4d80-ae8c-5a1c634f58e4")]
|
||||
internal interface IMFSample : IMFAttributes
|
||||
{
|
||||
[PreserveSig]
|
||||
new int GetItem(in Guid guidKey, nint pValue);
|
||||
[PreserveSig]
|
||||
new int GetItemType(in Guid guidKey, out uint pType);
|
||||
[PreserveSig]
|
||||
new int CompareItem(in Guid guidKey, nint Value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);
|
||||
[PreserveSig]
|
||||
new int Compare(IMFAttributes pTheirs, uint MatchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult);
|
||||
[PreserveSig]
|
||||
new int GetUINT32(in Guid guidKey, out uint punValue);
|
||||
[PreserveSig]
|
||||
new int GetUINT64(in Guid guidKey, out ulong punValue);
|
||||
[PreserveSig]
|
||||
new int GetDouble(in Guid guidKey, out double pfValue);
|
||||
[PreserveSig]
|
||||
new int GetGUID(in Guid guidKey, out Guid pguidValue);
|
||||
[PreserveSig]
|
||||
new int GetStringLength(in Guid guidKey, out uint pcchLength);
|
||||
[PreserveSig]
|
||||
new int GetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string pwszValue, uint cchBufSize, nint pcchLength);
|
||||
[PreserveSig]
|
||||
new int GetAllocatedString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out uint pcchLength);
|
||||
[PreserveSig]
|
||||
new int GetBlobSize(in Guid guidKey, out uint pcbBlobSize);
|
||||
[PreserveSig]
|
||||
new int GetBlob(in Guid guidKey, nint pBuf, uint cbBufSize, nint pcbBlobSize);
|
||||
[PreserveSig]
|
||||
new int GetAllocatedBlob(in Guid guidKey, out nint ppBuf, out uint pcbSize);
|
||||
[PreserveSig]
|
||||
new int GetUnknown(in Guid guidKey, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
|
||||
[PreserveSig]
|
||||
new int SetItem(in Guid guidKey, nint Value);
|
||||
[PreserveSig]
|
||||
new int DeleteItem(in Guid guidKey);
|
||||
[PreserveSig]
|
||||
new int DeleteAllItems();
|
||||
[PreserveSig]
|
||||
new int SetUINT32(in Guid guidKey, uint unValue);
|
||||
[PreserveSig]
|
||||
new int SetUINT64(in Guid guidKey, ulong unValue);
|
||||
[PreserveSig]
|
||||
new int SetDouble(in Guid guidKey, double fValue);
|
||||
[PreserveSig]
|
||||
new int SetGUID(in Guid guidKey, in Guid guidValue);
|
||||
[PreserveSig]
|
||||
new int SetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] string wszValue);
|
||||
[PreserveSig]
|
||||
new int SetBlob(in Guid guidKey, nint pBuf, uint cbBufSize);
|
||||
[PreserveSig]
|
||||
new int SetUnknown(in Guid guidKey, [MarshalAs(UnmanagedType.IUnknown)] object pUnknown);
|
||||
[PreserveSig]
|
||||
new int LockStore();
|
||||
[PreserveSig]
|
||||
new int UnlockStore();
|
||||
[PreserveSig]
|
||||
new int GetCount(out uint pcItems);
|
||||
[PreserveSig]
|
||||
new int GetItemByIndex(uint unIndex, out Guid pguidKey, nint pValue);
|
||||
[PreserveSig]
|
||||
new int CopyAllItems(IMFAttributes pDest);
|
||||
|
||||
[PreserveSig]
|
||||
int GetSampleFlags(out uint pdwSampleFlags);
|
||||
[PreserveSig]
|
||||
int SetSampleFlags(uint dwSampleFlags);
|
||||
[PreserveSig]
|
||||
int GetSampleTime(out long phnsSampleTime);
|
||||
[PreserveSig]
|
||||
int SetSampleTime(long hnsSampleTime);
|
||||
[PreserveSig]
|
||||
int GetSampleDuration(out long phnsSampleDuration);
|
||||
[PreserveSig]
|
||||
int SetSampleDuration(long hnsSampleDuration);
|
||||
[PreserveSig]
|
||||
int GetBufferCount(out uint pdwBufferCount);
|
||||
[PreserveSig]
|
||||
int GetBufferByIndex(uint dwIndex, out IMFMediaBuffer ppBuffer);
|
||||
[PreserveSig]
|
||||
int ConvertToContiguousBuffer(out IMFMediaBuffer ppBuffer);
|
||||
[PreserveSig]
|
||||
int AddBuffer(IMFMediaBuffer pBuffer);
|
||||
[PreserveSig]
|
||||
int RemoveBufferByIndex(uint dwIndex);
|
||||
[PreserveSig]
|
||||
int RemoveAllBuffers();
|
||||
[PreserveSig]
|
||||
int GetTotalLength(out uint pcbTotalLength);
|
||||
[PreserveSig]
|
||||
int CopyToBuffer(IMFMediaBuffer pBuffer);
|
||||
}
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("045FA593-8799-42b8-BC8D-8968C6453507")]
|
||||
internal interface IMFMediaBuffer
|
||||
{
|
||||
[PreserveSig]
|
||||
int Lock(out nint ppbBuffer, out int pcbMaxLength, out int pcbCurrentLength);
|
||||
[PreserveSig]
|
||||
int Unlock();
|
||||
[PreserveSig]
|
||||
int GetCurrentLength(out int pcbCurrentLength);
|
||||
[PreserveSig]
|
||||
int SetCurrentLength(int cbCurrentLength);
|
||||
[PreserveSig]
|
||||
int GetMaxLength(out int pcbMaxLength);
|
||||
}
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("7DC9D5F9-9ED9-44ec-9BBF-0600BB589FBF")]
|
||||
internal interface IMF2DBuffer
|
||||
{
|
||||
[PreserveSig]
|
||||
int Lock2D(out nint ppbScanline0, out int plPitch);
|
||||
[PreserveSig]
|
||||
int Unlock2D();
|
||||
[PreserveSig]
|
||||
int GetScanline0AndPitch(out nint pbScanline0, out int plPitch);
|
||||
[PreserveSig]
|
||||
int IsContiguousFormat([MarshalAs(UnmanagedType.Bool)] out bool pfIsContiguous);
|
||||
[PreserveSig]
|
||||
int GetContiguousLength(out int pcbLength);
|
||||
[PreserveSig]
|
||||
int ContiguousCopyTo(nint pbDestBuffer, int cbDestBuffer);
|
||||
[PreserveSig]
|
||||
int ContiguousCopyFrom(nint pbSrcBuffer, int cbSrcBuffer);
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct MF_SINK_WRITER_STATISTICS
|
||||
{
|
||||
public uint cb;
|
||||
public long llLastTimestampReceived;
|
||||
public long llLastTimestampEncoded;
|
||||
public long llLastTimestampProcessed;
|
||||
public long llLastStreamTickReceived;
|
||||
public long llLastSinkSampleRequest;
|
||||
public ulong qwNumSamplesReceived;
|
||||
public ulong qwNumSamplesEncoded;
|
||||
public ulong qwNumSamplesProcessed;
|
||||
public ulong qwNumStreamTicksReceived;
|
||||
public uint dwByteCountQueued;
|
||||
public ulong qwByteCountProcessed;
|
||||
public uint dwNumOutstandingSinkSampleRequests;
|
||||
public uint dwAverageSampleRateReceived;
|
||||
public uint dwAverageSampleRateEncoded;
|
||||
public uint dwAverageSampleRateProcessed;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Explicit, Size = 24)]
|
||||
internal struct PropVariant : IDisposable
|
||||
{
|
||||
[FieldOffset(0)] internal ushort vt;
|
||||
[FieldOffset(8)] internal long hVal;
|
||||
|
||||
internal static PropVariant FromInt64(long value) => new() { vt = 20, hVal = value };
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (vt != 0)
|
||||
PropVariantClear(ref this);
|
||||
}
|
||||
|
||||
[DllImport("ole32.dll")]
|
||||
private static extern int PropVariantClear(ref PropVariant pvar);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace ProxyForge.Interop;
|
||||
|
||||
internal static class MfGuids
|
||||
{
|
||||
internal static readonly Guid MF_MT_MAX_KEYFRAME_SPACING = new("c16eb52b-73a1-476f-8d62-839d6a020652");
|
||||
internal static readonly Guid CLSID_CColorConvertDMO = new("98230571-0087-4204-b020-3282538e57d3");
|
||||
internal static readonly Guid IID_IMFTransform = new("bf94c121-5b05-4e6f-8000-ba598961414d");
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ProxyForge.Interop;
|
||||
|
||||
internal static partial class MfNativeMethods
|
||||
{
|
||||
[LibraryImport("mfplat.dll")]
|
||||
internal static partial int MFStartup(uint version, uint dwFlags);
|
||||
|
||||
[LibraryImport("mfplat.dll")]
|
||||
internal static partial int MFShutdown();
|
||||
|
||||
[DllImport("mfplat.dll")]
|
||||
internal static extern int MFCreateMediaType(out IMFMediaType ppMFType);
|
||||
|
||||
[DllImport("mfplat.dll")]
|
||||
internal static extern int MFCreateMemoryBuffer(int cbMaxLength, out IMFMediaBuffer ppBuffer);
|
||||
|
||||
[DllImport("mfplat.dll")]
|
||||
internal static extern int MFCreateSample(out IMFSample ppIMFSample);
|
||||
|
||||
[DllImport("mfplat.dll")]
|
||||
internal static extern int MFCreateAttributes(out IMFAttributes ppMFAttributes, uint cInitialSize);
|
||||
|
||||
[DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern int MFCreateSourceReaderFromURL(
|
||||
string pwszURL, IMFAttributes? pAttributes, out IMFSourceReader ppSourceReader);
|
||||
|
||||
[DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern int MFCreateSinkWriterFromURL(
|
||||
string pwszOutputURL, nint pByteStream, IMFAttributes? pAttributes, out IMFSinkWriter ppSinkWriter);
|
||||
|
||||
[DllImport("ole32.dll")]
|
||||
internal static extern int PropVariantClear(nint pvar);
|
||||
|
||||
[DllImport("ole32.dll")]
|
||||
internal static extern int CoCreateInstance(
|
||||
in Guid rclsid, nint pUnkOuter, uint dwClsContext, in Guid riid, out nint ppv);
|
||||
|
||||
[DllImport("ole32.dll")]
|
||||
internal static extern int CreateStreamOnHGlobal(
|
||||
nint hGlobal,
|
||||
[MarshalAs(UnmanagedType.Bool)] bool fDeleteOnRelease,
|
||||
out nint ppstm);
|
||||
|
||||
[DllImport("mfplat.dll")]
|
||||
internal static extern int MFCreateMFByteStreamOnStream(nint pStream, out nint ppByteStream);
|
||||
|
||||
internal const uint MF_VERSION = 0x00020070;
|
||||
internal const uint MF_SOURCE_READER_FIRST_VIDEO_STREAM = 0xFFFFFFFC;
|
||||
internal const uint MF_SOURCE_READER_FIRST_AUDIO_STREAM = 0xFFFFFFFD;
|
||||
internal const uint MF_SOURCE_READER_MEDIASOURCE = 0xFFFFFFFF;
|
||||
internal const uint MF_SOURCE_READERF_ENDOFSTREAM = 0x00000001;
|
||||
internal const uint MF_SOURCE_READERF_ERROR = 0x00000002;
|
||||
|
||||
internal static ulong PackSize(uint width, uint height) => ((ulong)width << 32) | height;
|
||||
internal static ulong PackRatio(uint numerator, uint denominator) => ((ulong)numerator << 32) | denominator;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ProxyForge.Interop;
|
||||
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
[Guid("bf94c121-5b05-4e6f-8000-ba598961414d")]
|
||||
internal interface IMFTransform
|
||||
{
|
||||
[PreserveSig]
|
||||
int GetStreamLimits(out uint pdwInputMinimum, out uint pdwInputMaximum, out uint pdwOutputMinimum, out uint pdwOutputMaximum);
|
||||
|
||||
[PreserveSig]
|
||||
int GetStreamCount(out uint pcInputStreams, out uint pcOutputStreams);
|
||||
|
||||
[PreserveSig]
|
||||
int GetStreamIDs(uint dwInputIDArraySize, [Out] uint[] pdwInputIDs, uint dwOutputIDArraySize, [Out] uint[] pdwOutputIDs);
|
||||
|
||||
[PreserveSig]
|
||||
int GetInputStreamInfo(uint dwInputStreamID, out MFT_INPUT_STREAM_INFO pStreamInfo);
|
||||
|
||||
[PreserveSig]
|
||||
int GetOutputStreamInfo(uint dwOutputStreamID, out MFT_OUTPUT_STREAM_INFO pStreamInfo);
|
||||
|
||||
[PreserveSig]
|
||||
int GetAttributes(out IMFAttributes pAttributes);
|
||||
|
||||
[PreserveSig]
|
||||
int GetInputStreamAttributes(uint dwInputStreamID, out IMFAttributes pAttributes);
|
||||
|
||||
[PreserveSig]
|
||||
int GetOutputStreamAttributes(uint dwOutputStreamID, out IMFAttributes pAttributes);
|
||||
|
||||
[PreserveSig]
|
||||
int DeleteInputStream(uint dwStreamID);
|
||||
|
||||
[PreserveSig]
|
||||
int AddInputStreams(uint cStreams, [In] uint[] adwStreamIDs);
|
||||
|
||||
[PreserveSig]
|
||||
int GetInputAvailableType(uint dwInputStreamID, uint dwTypeIndex, out IMFMediaType ppType);
|
||||
|
||||
[PreserveSig]
|
||||
int GetOutputAvailableType(uint dwOutputStreamID, uint dwTypeIndex, out IMFMediaType ppType);
|
||||
|
||||
[PreserveSig]
|
||||
int SetInputType(uint dwInputStreamID, IMFMediaType? pType, uint dwFlags);
|
||||
|
||||
[PreserveSig]
|
||||
int SetOutputType(uint dwOutputStreamID, IMFMediaType? pType, uint dwFlags);
|
||||
|
||||
[PreserveSig]
|
||||
int GetInputCurrentType(uint dwInputStreamID, out IMFMediaType ppType);
|
||||
|
||||
[PreserveSig]
|
||||
int GetOutputCurrentType(uint dwOutputStreamID, out IMFMediaType ppType);
|
||||
|
||||
[PreserveSig]
|
||||
int GetInputStatus(uint dwInputStreamID, out uint pdwFlags);
|
||||
|
||||
[PreserveSig]
|
||||
int GetOutputStatus(out uint pdwFlags);
|
||||
|
||||
[PreserveSig]
|
||||
int SetOutputBounds(long hnsLowerBound, long hnsUpperBound);
|
||||
|
||||
[PreserveSig]
|
||||
int ProcessEvent(uint dwInputStreamID, nint pEvent);
|
||||
|
||||
[PreserveSig]
|
||||
int ProcessMessage(uint eMessage, nint ulParam);
|
||||
|
||||
[PreserveSig]
|
||||
int ProcessInput(uint dwInputStreamID, IMFSample pSample, uint dwFlags);
|
||||
|
||||
[PreserveSig]
|
||||
int ProcessOutput(uint dwFlags, uint cOutputBufferCount, ref MFT_OUTPUT_DATA_BUFFER pOutputSamples, out uint pdwStatus);
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct MFT_INPUT_STREAM_INFO
|
||||
{
|
||||
public long hnsMaxLatency;
|
||||
public uint dwFlags;
|
||||
public uint cbSize;
|
||||
public uint cbMaxLookahead;
|
||||
public uint cbAlignment;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct MFT_OUTPUT_STREAM_INFO
|
||||
{
|
||||
public uint dwFlags;
|
||||
public uint cbSize;
|
||||
public uint cbAlignment;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct MFT_OUTPUT_DATA_BUFFER
|
||||
{
|
||||
public uint dwStreamID;
|
||||
[MarshalAs(UnmanagedType.Interface)]
|
||||
public IMFSample? pSample;
|
||||
public uint dwStatus;
|
||||
[MarshalAs(UnmanagedType.Interface)]
|
||||
public object? pEvents;
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>ar-sa</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>إعدادات ProxyForge</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>الذاكرة</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>القرص</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>جارٍ الإنشاء...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>مكتمل</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>تم الإلغاء</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>فشل:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>جارٍ التحميل...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>لا توجد ذاكرة تخزين مؤقت للحذف.</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>تم حذف {0} عنصرًا ({1}).</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>لم تتم تهيئة المكوّن الإضافي</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>عدد عناصر التخزين المؤقت: {0}</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>الذاكرة: {0} عنصر ({1}) القرص: {2} عنصر ({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>مخصّص: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - جارٍ إنشاء الوكيل</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>جارٍ إنشاء فيديو وكيل...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>لا توجد عناصر وكيل قيد الإنشاء.</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>تسريع التحرير باستخدام فيديوهات وكيلة قائمة على الذاكرة</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>الإعدادات الأساسية</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>اضبط السلوك الأساسي لفيديوهات الوكيل</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>استخدام الوكيل</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>استخدم فيديو وكيل منخفض الدقة في الذاكرة أثناء التحرير.&#10;يتم التبديل تلقائيًا إلى الأصل عند التصدير.</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>مقياس الدقة</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>معامل مقياس الدقة لفيديو الوكيل</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>الحد الأدنى لحجم الملف</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>إنشاء وكيل فقط للفيديوهات الأكبر من هذا الحجم</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>إعدادات الجودة</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>اضبط التوازن بين جودة الترميز والأداء</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>معامل معدل البت</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>القيمة الأعلى تعطي جودة أفضل لكنها تستهلك ذاكرة أكبر</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>حجم GOP</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>الفاصل بين الإطارات المفتاحية</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>إعدادات الذاكرة</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>التحكم في استخدام الذاكرة والرجوع إلى القرص</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>الذاكرة المحجوزة</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>يتم الرجوع إلى القرص عند انخفاض الذاكرة عن هذه القيمة</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>أقصى ذاكرة للتخزين المؤقت</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>الرجوع إلى القرص</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>أنشئ ملفات مؤقتة على القرص عند عدم كفاية الذاكرة</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>إعدادات الأتمتة</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>إنشاء تلقائي</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>مسح التخزين المؤقت عند الإنهاء</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>الإعدادات المتقدمة</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>تمكين الإعدادات المتقدمة</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>تسريع العتاد</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>إدارة التخزين المؤقت</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>تحديث المعلومات</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>مسح التخزين المؤقت</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>قائمة التخزين المؤقت</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>لا توجد ذاكرة تخزين مؤقت.</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>ذاكرة الفيديو المؤقتة</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>حفظ فيديوهات الوكيل على القرص لتقليل وقت البدء</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>تمكين ذاكرة الفيديو المؤقتة</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>حفظ فيديوهات الوكيل على القرص وتحميلها تلقائيًا.&#10;يلغي إعادة الإنشاء.</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>التخزين المؤقت الدائم: {0} عناصر ({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>قائمة التخزين المؤقت الدائم</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>لا يوجد تخزين مؤقت دائم.</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>مسح التخزين المؤقت الدائم</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>دائم</value></data>
|
||||
</root>
|
||||
@@ -1,9 +0,0 @@
|
||||
using YukkuriMovieMaker.Generator;
|
||||
|
||||
namespace ProxyForge.Localization;
|
||||
|
||||
[AutoGenLocalizer]
|
||||
partial class Translate
|
||||
{
|
||||
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
Key,comment,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id,
|
||||
"AppName",Application name,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,
|
||||
"SettingsName",Settings page name,ProxyForge 設定,ProxyForge Settings,ProxyForge 设置,ProxyForge 設定,ProxyForge 설정,Configuración de ProxyForge,إعدادات ProxyForge,Pengaturan ProxyForge,
|
||||
"StorageMemory",Storage type memory,メモリ,Memory,内存,記憶體,메모리,Memoria,الذاكرة,Memori,
|
||||
"StorageDisk",Storage type disk,ディスク,Disk,磁盘,磁碟,디스크,Disco,القرص,Disk,
|
||||
"ProxyGenerationStatusGenerating",Proxy generation generating status,生成中...,Generating...,正在生成...,正在產生...,생성 중...,Generando...,جارٍ الإنشاء...,Sedang membuat...,
|
||||
"ProxyGenerationStatusCompleted",Proxy generation completed status,完了,Completed,完成,完成,완료,Completado,مكتمل,Selesai,
|
||||
"ProxyGenerationStatusCanceled",Proxy generation canceled status,キャンセル,Canceled,已取消,已取消,취소됨,Cancelado,تم الإلغاء,Dibatalkan,
|
||||
"ProxyGenerationStatusFailedPrefix",Proxy generation failed prefix,失敗: ,Failed: ,失败: ,失敗: ,실패: ,Error: ,فشل: ,Gagal: ,
|
||||
"CacheSummaryLoading",Cache summary loading text,読み込み中...,Loading...,加载中...,載入中...,불러오는 중...,Cargando...,جارٍ التحميل...,Memuat...,
|
||||
"CacheNoEntriesToDelete",No cache entries to delete message,削除するキャッシュがありません。,There is no cache to delete.,没有可删除的缓存。,沒有可刪除的快取。,삭제할 캐시가 없습니다.,No hay caché para eliminar.,لا توجد ذاكرة تخزين مؤقت للحذف.,Tidak ada cache untuk dihapus.,
|
||||
"CacheDeleteSummaryFormat",Cache delete result summary format,{0} 件 ({1}) を削除しました。,Deleted {0} items ({1}).,已删除 {0} 项({1})。,已刪除 {0} 項({1})。,{0}개 항목({1})을 삭제했습니다.,Se eliminaron {0} elementos ({1}).,تم حذف {0} عنصرًا ({1}).,{0} item ({1}) telah dihapus.,
|
||||
"CacheSummaryPluginNotInitialized",Plugin not initialized cache summary,プラグイン未初期化,Plugin not initialized,插件未初始化,外掛未初始化,플러그인이 초기화되지 않음,Plugin no inicializado,لم تتم تهيئة المكوّن الإضافي,Plugin belum diinisialisasi,
|
||||
"CacheSummaryCountFormat",Cache entry count summary format,キャッシュ数: {0} 件,Cache count: {0} items,缓存数: {0} 项,快取數: {0} 項,캐시 수: {0}개,Conteo de caché: {0} elementos,عدد عناصر التخزين المؤقت: {0},Jumlah cache: {0} item,
|
||||
"CacheUsageMemoryAndDiskFormat",Memory and disk usage summary format,メモリ: {0} 件 ({1}) ディスク: {2} 件 ({3}),Memory: {0} items ({1}) Disk: {2} items ({3}),内存: {0} 项({1}) 磁盘: {2} 项({3}),記憶體: {0} 項({1}) 磁碟: {2} 項({3}),메모리: {0}개({1}) 디스크: {2}개({3}),Memoria: {0} elementos ({1}) Disco: {2} elementos ({3}),الذاكرة: {0} عنصر ({1}) القرص: {2} عنصر ({3}),Memori: {0} item ({1}) Disk: {2} item ({3}),
|
||||
"CacheUsageAllocatedFormat",Allocated memory suffix format, 割当済: {0}, Allocated: {0}, 已分配: {0}, 已配置: {0}, 할당됨: {0}, Asignado: {0}, مخصّص: {0}, Dialokasikan: {0},
|
||||
"GenerationPopupWindowTitle",Generation popup window title,ProxyForge - プロキシ生成中,ProxyForge - Generating Proxy,ProxyForge - 正在生成代理,ProxyForge - 正在產生代理,ProxyForge - 프록시 생성 중,ProxyForge - Generando proxy,ProxyForge - جارٍ إنشاء الوكيل,ProxyForge - Sedang Membuat Proksi,
|
||||
"GenerationPopupHeader",Generation popup header text,プロキシ動画を生成しています...,Generating proxy video...,正在生成代理视频...,正在產生代理影片...,프록시 영상을 생성하는 중...,Generando video proxy...,جارٍ إنشاء فيديو وكيل...,Sedang membuat video proksi...,
|
||||
"GenerationPopupNoActiveItems",No active generation items message,生成中のプロキシはありません,There are no proxies being generated.,当前没有正在生成的代理。,目前沒有正在產生的代理。,생성 중인 프록시가 없습니다.,No hay proxies en generación.,لا توجد عناصر وكيل قيد الإنشاء.,Tidak ada proksi yang sedang dibuat.,
|
||||
"SettingsCardDescription",Settings card description,メモリベースのプロキシ動画で編集を高速化,Speed up editing with memory-based proxy videos,通过基于内存的代理视频加速编辑,透過記憶體式代理影片加速編輯,메모리 기반 프록시 영상으로 편집 속도 향상,Acelera la edición con videos proxy basados en memoria,تسريع التحرير باستخدام فيديوهات وكيلة قائمة على الذاكرة,Tingkatkan kecepatan edit dengan video proksi berbasis memori,
|
||||
"SectionBasicSettingsHeader",Basic settings section header,基本設定,Basic Settings,基本设置,基本設定,기본 설정,Configuración básica,الإعدادات الأساسية,Pengaturan Dasar,
|
||||
"SectionBasicSettingsDescription",Basic settings section description,プロキシ動画の基本的な動作を設定します,Configure the basic behavior of proxy videos,设置代理视频的基本行为,設定代理影片的基本行為,프록시 영상의 기본 동작을 설정합니다,Configura el comportamiento básico de los videos proxy,اضبط السلوك الأساسي لفيديوهات الوكيل,Atur perilaku dasar video proksi,
|
||||
"SettingUseProxyLabel",Use proxy setting label,プロキシを使用する,Use proxy,使用代理,使用代理,프록시 사용,Usar proxy,استخدام الوكيل,Gunakan proksi,
|
||||
"SettingUseProxyTooltip",Use proxy setting tooltip,編集中にメモリ上の低解像度プロキシ動画を使用します。 出力時は自動でオリジナルに切り替わります。,Use low-resolution proxy video in memory while editing. Automatically switches to original on export.,编辑时使用内存中的低分辨率代理视频。 导出时自动切换为原始视频。,編輯時使用記憶體中的低解析度代理影片。 輸出時會自動切換為原始影片。,편집 중에는 메모리의 저해상도 프록시 영상을 사용합니다. 내보낼 때는 원본으로 자동 전환됩니다.,Usa video proxy de baja resolución en memoria durante la edición. Al exportar cambia automáticamente al original.,استخدم فيديو وكيل منخفض الدقة في الذاكرة أثناء التحرير. يتم التبديل تلقائيًا إلى الأصل عند التصدير.,Gunakan video proksi resolusi rendah di memori saat mengedit. Akan otomatis beralih ke video asli saat ekspor.,
|
||||
"SettingResolutionScaleLabel",Resolution scale setting label,解像度スケール,Resolution Scale,分辨率缩放,解析度縮放,해상도 배율,Escala de resolución,مقياس الدقة,Skala Resolusi,
|
||||
"SettingResolutionScaleTooltip",Resolution scale setting tooltip,プロキシ動画の解像度倍率,Resolution scale factor for proxy video,代理视频的分辨率倍率,代理影片的解析度倍率,프록시 영상의 해상도 배율,Factor de escala de resolución para video proxy,معامل مقياس الدقة لفيديو الوكيل,Faktor skala resolusi untuk video proksi,
|
||||
"SettingMinFileSizeLabel",Minimum file size setting label,最小ファイルサイズ,Minimum File Size,最小文件大小,最小檔案大小,최소 파일 크기,Tamaño mínimo de archivo,الحد الأدنى لحجم الملف,Ukuran File Minimum,
|
||||
"SettingMinFileSizeTooltip",Minimum file size setting tooltip,このサイズ以上の動画のみプロキシを生成します,Generate proxy only for videos larger than this size,仅为大于此大小的视频生成代理,僅為大於此大小的影片產生代理,이 크기 이상의 영상만 프록시를 생성합니다,Solo genera proxy para videos mayores que este tamaño,إنشاء وكيل فقط للفيديوهات الأكبر من هذا الحجم,Buat proksi hanya untuk video yang lebih besar dari ukuran ini,
|
||||
"SectionQualitySettingsHeader",Quality settings section header,品質設定,Quality Settings,质量设置,品質設定,품질 설정,Configuración de calidad,إعدادات الجودة,Pengaturan Kualitas,
|
||||
"SectionQualitySettingsDescription",Quality settings section description,エンコード品質とパフォーマンスのバランスを調整します,Adjust the balance between encoding quality and performance,调整编码质量与性能之间的平衡,調整編碼品質與效能之間的平衡,인코딩 품질과 성능의 균형을 조정합니다,Ajusta el equilibrio entre calidad de codificación y rendimiento,اضبط التوازن بين جودة الترميز والأداء,Sesuaikan keseimbangan antara kualitas encoding dan performa,
|
||||
"SettingBitrateFactorLabel",Bitrate factor setting label,ビットレート係数,Bitrate Factor,比特率系数,位元率係數,비트레이트 계수,Factor de bitrate,معامل معدل البت,Faktor Bitrate,
|
||||
"SettingBitrateFactorTooltip",Bitrate factor setting tooltip,高いほど高品質ですがメモリ使用量が増えます,Higher value gives better quality but uses more memory,值越高画质越好但内存占用越大,值越高畫質越好但記憶體用量越大,값이 높을수록 품질은 좋아지지만 메모리 사용량이 늘어납니다,Un valor más alto mejora la calidad pero aumenta el uso de memoria,القيمة الأعلى تعطي جودة أفضل لكنها تستهلك ذاكرة أكبر,Nilai lebih tinggi memberi kualitas lebih baik tetapi memakai lebih banyak memori,
|
||||
"SettingGopSizeLabel",GOP size setting label,GOPサイズ,GOP Size,GOP 大小,GOP 大小,GOP 크기,Tamaño GOP,حجم GOP,Ukuran GOP,
|
||||
"SettingGopSizeTooltip",GOP size setting tooltip,キーフレーム間隔,Keyframe interval,关键帧间隔,關鍵影格間隔,키프레임 간격,Intervalo de fotogramas clave,الفاصل بين الإطارات المفتاحية,Interval keyframe,
|
||||
"SectionMemorySettingsHeader",Memory settings section header,メモリ設定,Memory Settings,内存设置,記憶體設定,메모리 설정,Configuración de memoria,إعدادات الذاكرة,Pengaturan Memori,
|
||||
"SectionMemorySettingsDescription",Memory settings section description,メモリ使用量とディスクフォールバックを制御します,Control memory usage and disk fallback,控制内存使用量和磁盘回退,控制記憶體使用量與磁碟回退,메모리 사용량과 디스크 폴백을 제어합니다,Controla el uso de memoria y el respaldo en disco,التحكم في استخدام الذاكرة والرجوع إلى القرص,Kendalikan penggunaan memori dan fallback ke disk,
|
||||
"SettingMemoryReserveLabel",Memory reserve setting label,メモリ予約量,Memory Reserve,内存预留量,記憶體保留量,메모리 예약량,Reserva de memoria,الذاكرة المحجوزة,Cadangan Memori,
|
||||
"SettingMemoryReserveTooltip",Memory reserve setting tooltip,これを下回るとディスクにフォールバックします,Falls back to disk when memory goes below this value,内存低于该值时回退到磁盘,記憶體低於此值時回退到磁碟,메모리가 이 값보다 낮아지면 디스크로 폴백합니다,Cambia a disco cuando la memoria cae por debajo de este valor,يتم الرجوع إلى القرص عند انخفاض الذاكرة عن هذه القيمة,Akan fallback ke disk saat memori turun di bawah nilai ini,
|
||||
"SettingMaxCacheMemoryLabel",Max cache memory setting label,最大キャッシュメモリ,Max Cache Memory,最大缓存内存,最大快取記憶體,최대 캐시 메모리,Máxima memoria de caché,أقصى ذاكرة للتخزين المؤقت,Maksimum Memori Cache,
|
||||
"SettingDiskFallbackLabel",Disk fallback setting label,ディスクフォールバック,Disk Fallback,磁盘回退,磁碟回退,디스크 폴백,Respaldo en disco,الرجوع إلى القرص,Fallback Disk,
|
||||
"SettingDiskFallbackTooltip",Disk fallback setting tooltip,メモリ不足時にディスクに一時ファイルを作成します,Create temporary files on disk when memory is insufficient,内存不足时在磁盘创建临时文件,記憶體不足時在磁碟建立暫存檔,메모리가 부족할 때 디스크에 임시 파일을 생성합니다,Crea archivos temporales en disco cuando no hay suficiente memoria,أنشئ ملفات مؤقتة على القرص عند عدم كفاية الذاكرة,Buat file sementara di disk saat memori tidak cukup,
|
||||
"SectionAutomationSettingsHeader",Automation settings section header,自動化設定,Automation Settings,自动化设置,自動化設定,자동화 설정,Configuración de automatización,إعدادات الأتمتة,Pengaturan Otomatisasi,
|
||||
"SettingAutoGenerateLabel",Auto generate setting label,自動生成,Auto Generate,自动生成,自動產生,자동 생성,Generación automática,إنشاء تلقائي,Buat Otomatis,
|
||||
"SettingClearCacheOnExitLabel",Clear cache on exit setting label,終了時にキャッシュクリア,Clear Cache on Exit,退出时清除缓存,結束時清除快取,종료 시 캐시 지우기,Borrar caché al salir,مسح التخزين المؤقت عند الإنهاء,Hapus Cache saat Keluar,
|
||||
"SectionAdvancedSettingsHeader",Advanced settings section header,詳細設定,Advanced Settings,高级设置,進階設定,고급 설정,Configuración avanzada,الإعدادات المتقدمة,Pengaturan Lanjutan,
|
||||
"SettingEnableAdvancedLabel",Enable advanced settings label,詳細設定を有効にする,Enable Advanced Settings,启用高级设置,啟用進階設定,고급 설정 활성화,Habilitar configuración avanzada,تمكين الإعدادات المتقدمة,Aktifkan Pengaturan Lanjutan,
|
||||
"SettingHardwareAccelerationLabel",Hardware acceleration setting label,ハードウェアアクセラレーション,Hardware Acceleration,硬件加速,硬體加速,하드웨어 가속,Aceleración por hardware,تسريع العتاد,Akselerasi Perangkat Keras,
|
||||
"SectionCacheManagementHeader",Cache management section header,キャッシュ管理,Cache Management,缓存管理,快取管理,캐시 관리,Gestión de caché,إدارة التخزين المؤقت,Manajemen Cache,
|
||||
"ButtonRefreshInfo",Refresh info button label,情報を更新,Refresh Info,刷新信息,更新資訊,정보 새로고침,Actualizar información,تحديث المعلومات,Perbarui Info,
|
||||
"ButtonClearCache",Clear cache button label,キャッシュをクリア,Clear Cache,清除缓存,清除快取,캐시 지우기,Borrar caché,مسح التخزين المؤقت,Hapus Cache,
|
||||
"CacheListHeader",Cache list header,キャッシュ一覧,Cache List,缓存列表,快取清單,캐시 목록,Lista de caché,قائمة التخزين المؤقت,Daftar Cache,
|
||||
"CacheListEmpty",Empty cache list message,キャッシュはありません,There is no cache.,没有缓存。,沒有快取。,캐시가 없습니다.,No hay caché.,لا توجد ذاكرة تخزين مؤقت.,Tidak ada cache.,
|
||||
"SectionVideoCacheHeader",Video cache section header,映像キャッシュ,Video Cache,视频缓存,影片快取,영상 캐시,Caché de video,ذاكرة الفيديو المؤقتة,Cache Video,
|
||||
"SectionVideoCacheDescription",Video cache section description,プロキシ動画をディスクに永続保存し起動時間を短縮します,Persist proxy videos to disk to reduce startup time,将代理视频持久保存到磁盘以缩短启动时间,將代理影片永久保存到磁碟以縮短啟動時間,프록시 영상을 디스크에 영구 저장하여 시작 시간을 단축합니다,Guarda videos proxy en disco para reducir el tiempo de inicio,حفظ فيديوهات الوكيل على القرص لتقليل وقت البدء,Simpan video proksi ke disk untuk mengurangi waktu startup,
|
||||
"SettingEnableVideoCacheLabel",Enable video cache label,映像キャッシュを有効にする,Enable Video Cache,启用视频缓存,啟用影片快取,영상 캐시 활성화,Habilitar caché de video,تمكين ذاكرة الفيديو المؤقتة,Aktifkan Cache Video,
|
||||
"SettingEnableVideoCacheTooltip",Enable video cache tooltip,プロキシ動画をディスクに保存し次回起動時に自動ロードします。 生成の手間を省きます。,Save proxy videos to disk and auto-load on next startup. Eliminates regeneration overhead.,将代理视频保存到磁盘并在下次启动时自动加载。 免去重新生成。,將代理影片儲存到磁碟並在下次啟動時自動載入。 免去重新產生。,프록시 영상을 디스크에 저장하고 다음 시작 시 자동 로드합니다. 재생성을 생략합니다.,Guarda videos proxy en disco y los carga automáticamente. Elimina la regeneración.,حفظ فيديوهات الوكيل على القرص وتحميلها تلقائيًا. يلغي إعادة الإنشاء.,Simpan video proksi ke disk dan muat otomatis saat startup berikutnya. Menghilangkan regenerasi.,
|
||||
"VideoCacheSummaryFormat",Video cache summary format,永続キャッシュ: {0} 件 ({1}),Persistent cache: {0} items ({1}),持久缓存: {0} 项({1}),永久快取: {0} 項({1}),영구 캐시: {0}개({1}),Caché persistente: {0} elementos ({1}),التخزين المؤقت الدائم: {0} عناصر ({1}),Cache persisten: {0} item ({1}),
|
||||
"VideoCacheListHeader",Video cache list header,永続キャッシュ一覧,Persistent Cache List,持久缓存列表,永久快取清單,영구 캐시 목록,Lista de caché persistente,قائمة التخزين المؤقت الدائم,Daftar Cache Persisten,
|
||||
"VideoCacheListEmpty",Video cache list empty message,永続キャッシュはありません,No persistent cache entries.,没有持久缓存。,沒有永久快取。,영구 캐시가 없습니다.,No hay caché persistente.,لا يوجد تخزين مؤقت دائم.,Tidak ada cache persisten.,
|
||||
"ButtonClearVideoCache",Clear video cache button label,永続キャッシュをクリア,Clear Persistent Cache,清除持久缓存,清除永久快取,영구 캐시 지우기,Borrar caché persistente,مسح التخزين المؤقت الدائم,Hapus Cache Persisten,
|
||||
"StoragePersistent",Storage type persistent,永続,Persistent,持久,永久,영구,Persistente,دائم,Persisten,
|
||||
|
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>en-us</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>ProxyForge Settings</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>Memory</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>Disk</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>Generating...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>Completed</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>Canceled</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>Failed:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>Loading...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>There is no cache to delete.</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>Deleted {0} items ({1}).</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>Plugin not initialized</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>Cache count: {0} items</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>Memory: {0} items ({1}) Disk: {2} items ({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>Allocated: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - Generating Proxy</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>Generating proxy video...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>There are no proxies being generated.</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>Speed up editing with memory-based proxy videos</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>Basic Settings</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>Configure the basic behavior of proxy videos</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>Use proxy</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>Use low-resolution proxy video in memory while editing.&#10;Automatically switches to original on export.</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>Resolution Scale</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>Resolution scale factor for proxy video</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>Minimum File Size</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>Generate proxy only for videos larger than this size</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>Quality Settings</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>Adjust the balance between encoding quality and performance</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>Bitrate Factor</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>Higher value gives better quality but uses more memory</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>GOP Size</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>Keyframe interval</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>Memory Settings</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>Control memory usage and disk fallback</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>Memory Reserve</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>Falls back to disk when memory goes below this value</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>Max Cache Memory</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>Disk Fallback</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>Create temporary files on disk when memory is insufficient</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>Automation Settings</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>Auto Generate</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>Clear Cache on Exit</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>Advanced Settings</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>Enable Advanced Settings</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>Hardware Acceleration</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>Cache Management</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>Refresh Info</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>Clear Cache</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>Cache List</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>There is no cache.</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>Video Cache</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>Persist proxy videos to disk to reduce startup time</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>Enable Video Cache</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>Save proxy videos to disk and auto-load on next startup.&#10;Eliminates regeneration overhead.</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>Persistent cache: {0} items ({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>Persistent Cache List</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>No persistent cache entries.</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>Clear Persistent Cache</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>Persistent</value></data>
|
||||
</root>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>es-es</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>Configuración de ProxyForge</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>Memoria</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>Disco</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>Generando...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>Completado</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>Cancelado</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>Error:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>Cargando...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>No hay caché para eliminar.</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>Se eliminaron {0} elementos ({1}).</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>Plugin no inicializado</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>Conteo de caché: {0} elementos</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>Memoria: {0} elementos ({1}) Disco: {2} elementos ({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>Asignado: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - Generando proxy</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>Generando video proxy...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>No hay proxies en generación.</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>Acelera la edición con videos proxy basados en memoria</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>Configuración básica</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>Configura el comportamiento básico de los videos proxy</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>Usar proxy</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>Usa video proxy de baja resolución en memoria durante la edición.&#10;Al exportar cambia automáticamente al original.</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>Escala de resolución</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>Factor de escala de resolución para video proxy</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>Tamaño mínimo de archivo</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>Solo genera proxy para videos mayores que este tamaño</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>Configuración de calidad</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>Ajusta el equilibrio entre calidad de codificación y rendimiento</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>Factor de bitrate</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>Un valor más alto mejora la calidad pero aumenta el uso de memoria</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>Tamaño GOP</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>Intervalo de fotogramas clave</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>Configuración de memoria</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>Controla el uso de memoria y el respaldo en disco</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>Reserva de memoria</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>Cambia a disco cuando la memoria cae por debajo de este valor</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>Máxima memoria de caché</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>Respaldo en disco</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>Crea archivos temporales en disco cuando no hay suficiente memoria</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>Configuración de automatización</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>Generación automática</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>Borrar caché al salir</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>Configuración avanzada</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>Habilitar configuración avanzada</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>Aceleración por hardware</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>Gestión de caché</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>Actualizar información</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>Borrar caché</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>Lista de caché</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>No hay caché.</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>Caché de video</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>Guarda videos proxy en disco para reducir el tiempo de inicio</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>Habilitar caché de video</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>Guarda videos proxy en disco y los carga automáticamente.&#10;Elimina la regeneración.</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>Caché persistente: {0} elementos ({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>Lista de caché persistente</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>No hay caché persistente.</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>Borrar caché persistente</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>Persistente</value></data>
|
||||
</root>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>id-id</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>Pengaturan ProxyForge</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>Memori</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>Disk</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>Sedang membuat...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>Selesai</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>Dibatalkan</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>Gagal:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>Memuat...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>Tidak ada cache untuk dihapus.</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>{0} item ({1}) telah dihapus.</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>Plugin belum diinisialisasi</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>Jumlah cache: {0} item</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>Memori: {0} item ({1}) Disk: {2} item ({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>Dialokasikan: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - Sedang Membuat Proksi</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>Sedang membuat video proksi...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>Tidak ada proksi yang sedang dibuat.</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>Tingkatkan kecepatan edit dengan video proksi berbasis memori</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>Pengaturan Dasar</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>Atur perilaku dasar video proksi</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>Gunakan proksi</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>Gunakan video proksi resolusi rendah di memori saat mengedit.&#10;Akan otomatis beralih ke video asli saat ekspor.</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>Skala Resolusi</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>Faktor skala resolusi untuk video proksi</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>Ukuran File Minimum</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>Buat proksi hanya untuk video yang lebih besar dari ukuran ini</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>Pengaturan Kualitas</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>Sesuaikan keseimbangan antara kualitas encoding dan performa</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>Faktor Bitrate</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>Nilai lebih tinggi memberi kualitas lebih baik tetapi memakai lebih banyak memori</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>Ukuran GOP</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>Interval keyframe</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>Pengaturan Memori</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>Kendalikan penggunaan memori dan fallback ke disk</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>Cadangan Memori</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>Akan fallback ke disk saat memori turun di bawah nilai ini</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>Maksimum Memori Cache</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>Fallback Disk</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>Buat file sementara di disk saat memori tidak cukup</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>Pengaturan Otomatisasi</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>Buat Otomatis</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>Hapus Cache saat Keluar</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>Pengaturan Lanjutan</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>Aktifkan Pengaturan Lanjutan</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>Akselerasi Perangkat Keras</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>Manajemen Cache</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>Perbarui Info</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>Hapus Cache</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>Daftar Cache</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>Tidak ada cache.</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>Cache Video</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>Simpan video proksi ke disk untuk mengurangi waktu startup</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>Aktifkan Cache Video</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>Simpan video proksi ke disk dan muat otomatis saat startup berikutnya.&#10;Menghilangkan regenerasi.</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>Cache persisten: {0} item ({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>Daftar Cache Persisten</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>Tidak ada cache persisten.</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>Hapus Cache Persisten</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>Persisten</value></data>
|
||||
</root>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>ko-kr</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>ProxyForge 설정</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>메모리</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>디스크</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>생성 중...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>완료</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>취소됨</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>실패:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>불러오는 중...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>삭제할 캐시가 없습니다.</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>{0}개 항목({1})을 삭제했습니다.</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>플러그인이 초기화되지 않음</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>캐시 수: {0}개</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>메모리: {0}개({1}) 디스크: {2}개({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>할당됨: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - 프록시 생성 중</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>프록시 영상을 생성하는 중...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>생성 중인 프록시가 없습니다.</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>메모리 기반 프록시 영상으로 편집 속도 향상</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>기본 설정</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>프록시 영상의 기본 동작을 설정합니다</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>프록시 사용</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>편집 중에는 메모리의 저해상도 프록시 영상을 사용합니다.&#10;내보낼 때는 원본으로 자동 전환됩니다.</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>해상도 배율</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>프록시 영상의 해상도 배율</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>최소 파일 크기</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>이 크기 이상의 영상만 프록시를 생성합니다</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>품질 설정</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>인코딩 품질과 성능의 균형을 조정합니다</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>비트레이트 계수</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>값이 높을수록 품질은 좋아지지만 메모리 사용량이 늘어납니다</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>GOP 크기</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>키프레임 간격</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>메모리 설정</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>메모리 사용량과 디스크 폴백을 제어합니다</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>메모리 예약량</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>메모리가 이 값보다 낮아지면 디스크로 폴백합니다</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>최대 캐시 메모리</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>디스크 폴백</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>메모리가 부족할 때 디스크에 임시 파일을 생성합니다</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>자동화 설정</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>자동 생성</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>종료 시 캐시 지우기</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>고급 설정</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>고급 설정 활성화</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>하드웨어 가속</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>캐시 관리</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>정보 새로고침</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>캐시 지우기</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>캐시 목록</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>캐시가 없습니다.</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>영상 캐시</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>프록시 영상을 디스크에 영구 저장하여 시작 시간을 단축합니다</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>영상 캐시 활성화</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>프록시 영상을 디스크에 저장하고 다음 시작 시 자동 로드합니다.&#10;재생성을 생략합니다.</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>영구 캐시: {0}개({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>영구 캐시 목록</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>영구 캐시가 없습니다.</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>영구 캐시 지우기</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>영구</value></data>
|
||||
</root>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>ja-jp</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>ProxyForge 設定</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>メモリ</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>ディスク</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>生成中...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>完了</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>キャンセル</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>失敗:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>読み込み中...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>削除するキャッシュがありません。</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>{0} 件 ({1}) を削除しました。</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>プラグイン未初期化</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>キャッシュ数: {0} 件</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>メモリ: {0} 件 ({1}) ディスク: {2} 件 ({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>割当済: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - プロキシ生成中</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>プロキシ動画を生成しています...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>生成中のプロキシはありません</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>メモリベースのプロキシ動画で編集を高速化</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>基本設定</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>プロキシ動画の基本的な動作を設定します</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>プロキシを使用する</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>編集中にメモリ上の低解像度プロキシ動画を使用します。&#10;出力時は自動でオリジナルに切り替わります。</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>解像度スケール</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>プロキシ動画の解像度倍率</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>最小ファイルサイズ</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>このサイズ以上の動画のみプロキシを生成します</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>品質設定</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>エンコード品質とパフォーマンスのバランスを調整します</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>ビットレート係数</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>高いほど高品質ですがメモリ使用量が増えます</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>GOPサイズ</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>キーフレーム間隔</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>メモリ設定</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>メモリ使用量とディスクフォールバックを制御します</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>メモリ予約量</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>これを下回るとディスクにフォールバックします</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>最大キャッシュメモリ</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>ディスクフォールバック</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>メモリ不足時にディスクに一時ファイルを作成します</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>自動化設定</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>自動生成</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>終了時にキャッシュクリア</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>詳細設定</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>詳細設定を有効にする</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>ハードウェアアクセラレーション</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>キャッシュ管理</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>情報を更新</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>キャッシュをクリア</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>キャッシュ一覧</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>キャッシュはありません</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>映像キャッシュ</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>プロキシ動画をディスクに永続保存し起動時間を短縮します</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>映像キャッシュを有効にする</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>プロキシ動画をディスクに保存し次回起動時に自動ロードします。&#10;生成の手間を省きます。</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>永続キャッシュ: {0} 件 ({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>永続キャッシュ一覧</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>永続キャッシュはありません</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>永続キャッシュをクリア</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>永続</value></data>
|
||||
</root>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>zh-cn</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>ProxyForge 设置</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>内存</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>磁盘</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>正在生成...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>完成</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>已取消</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>失败:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>加载中...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>没有可删除的缓存。</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>已删除 {0} 项({1})。</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>插件未初始化</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>缓存数: {0} 项</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>内存: {0} 项({1}) 磁盘: {2} 项({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>已分配: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - 正在生成代理</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>正在生成代理视频...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>当前没有正在生成的代理。</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>通过基于内存的代理视频加速编辑</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>基本设置</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>设置代理视频的基本行为</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>使用代理</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>编辑时使用内存中的低分辨率代理视频。&#10;导出时自动切换为原始视频。</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>分辨率缩放</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>代理视频的分辨率倍率</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>最小文件大小</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>仅为大于此大小的视频生成代理</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>质量设置</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>调整编码质量与性能之间的平衡</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>比特率系数</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>值越高画质越好但内存占用越大</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>GOP 大小</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>关键帧间隔</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>内存设置</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>控制内存使用量和磁盘回退</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>内存预留量</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>内存低于该值时回退到磁盘</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>最大缓存内存</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>磁盘回退</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>内存不足时在磁盘创建临时文件</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>自动化设置</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>自动生成</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>退出时清除缓存</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>高级设置</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>启用高级设置</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>硬件加速</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>缓存管理</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>刷新信息</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>清除缓存</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>缓存列表</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>没有缓存。</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>视频缓存</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>将代理视频持久保存到磁盘以缩短启动时间</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>启用视频缓存</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>将代理视频保存到磁盘并在下次启动时自动加载。&#10;免去重新生成。</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>持久缓存: {0} 项({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>持久缓存列表</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>没有持久缓存。</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>清除持久缓存</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>持久</value></data>
|
||||
</root>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="CurrentCulture" xml:space="preserve"><value>zh-tw</value></data>
|
||||
<data name="AppName" xml:space="preserve"><value>ProxyForge</value></data>
|
||||
<data name="SettingsName" xml:space="preserve"><value>ProxyForge 設定</value></data>
|
||||
<data name="StorageMemory" xml:space="preserve"><value>記憶體</value></data>
|
||||
<data name="StorageDisk" xml:space="preserve"><value>磁碟</value></data>
|
||||
<data name="ProxyGenerationStatusGenerating" xml:space="preserve"><value>正在產生...</value></data>
|
||||
<data name="ProxyGenerationStatusCompleted" xml:space="preserve"><value>完成</value></data>
|
||||
<data name="ProxyGenerationStatusCanceled" xml:space="preserve"><value>已取消</value></data>
|
||||
<data name="ProxyGenerationStatusFailedPrefix" xml:space="preserve"><value>失敗:</value></data>
|
||||
<data name="CacheSummaryLoading" xml:space="preserve"><value>載入中...</value></data>
|
||||
<data name="CacheNoEntriesToDelete" xml:space="preserve"><value>沒有可刪除的快取。</value></data>
|
||||
<data name="CacheDeleteSummaryFormat" xml:space="preserve"><value>已刪除 {0} 項({1})。</value></data>
|
||||
<data name="CacheSummaryPluginNotInitialized" xml:space="preserve"><value>外掛未初始化</value></data>
|
||||
<data name="CacheSummaryCountFormat" xml:space="preserve"><value>快取數: {0} 項</value></data>
|
||||
<data name="CacheUsageMemoryAndDiskFormat" xml:space="preserve"><value>記憶體: {0} 項({1}) 磁碟: {2} 項({3})</value></data>
|
||||
<data name="CacheUsageAllocatedFormat" xml:space="preserve"><value>已配置: {0}</value></data>
|
||||
<data name="GenerationPopupWindowTitle" xml:space="preserve"><value>ProxyForge - 正在產生代理</value></data>
|
||||
<data name="GenerationPopupHeader" xml:space="preserve"><value>正在產生代理影片...</value></data>
|
||||
<data name="GenerationPopupNoActiveItems" xml:space="preserve"><value>目前沒有正在產生的代理。</value></data>
|
||||
<data name="SettingsCardDescription" xml:space="preserve"><value>透過記憶體式代理影片加速編輯</value></data>
|
||||
<data name="SectionBasicSettingsHeader" xml:space="preserve"><value>基本設定</value></data>
|
||||
<data name="SectionBasicSettingsDescription" xml:space="preserve"><value>設定代理影片的基本行為</value></data>
|
||||
<data name="SettingUseProxyLabel" xml:space="preserve"><value>使用代理</value></data>
|
||||
<data name="SettingUseProxyTooltip" xml:space="preserve"><value>編輯時使用記憶體中的低解析度代理影片。&#10;輸出時會自動切換為原始影片。</value></data>
|
||||
<data name="SettingResolutionScaleLabel" xml:space="preserve"><value>解析度縮放</value></data>
|
||||
<data name="SettingResolutionScaleTooltip" xml:space="preserve"><value>代理影片的解析度倍率</value></data>
|
||||
<data name="SettingMinFileSizeLabel" xml:space="preserve"><value>最小檔案大小</value></data>
|
||||
<data name="SettingMinFileSizeTooltip" xml:space="preserve"><value>僅為大於此大小的影片產生代理</value></data>
|
||||
<data name="SectionQualitySettingsHeader" xml:space="preserve"><value>品質設定</value></data>
|
||||
<data name="SectionQualitySettingsDescription" xml:space="preserve"><value>調整編碼品質與效能之間的平衡</value></data>
|
||||
<data name="SettingBitrateFactorLabel" xml:space="preserve"><value>位元率係數</value></data>
|
||||
<data name="SettingBitrateFactorTooltip" xml:space="preserve"><value>值越高畫質越好但記憶體用量越大</value></data>
|
||||
<data name="SettingGopSizeLabel" xml:space="preserve"><value>GOP 大小</value></data>
|
||||
<data name="SettingGopSizeTooltip" xml:space="preserve"><value>關鍵影格間隔</value></data>
|
||||
<data name="SectionMemorySettingsHeader" xml:space="preserve"><value>記憶體設定</value></data>
|
||||
<data name="SectionMemorySettingsDescription" xml:space="preserve"><value>控制記憶體使用量與磁碟回退</value></data>
|
||||
<data name="SettingMemoryReserveLabel" xml:space="preserve"><value>記憶體保留量</value></data>
|
||||
<data name="SettingMemoryReserveTooltip" xml:space="preserve"><value>記憶體低於此值時回退到磁碟</value></data>
|
||||
<data name="SettingMaxCacheMemoryLabel" xml:space="preserve"><value>最大快取記憶體</value></data>
|
||||
<data name="SettingDiskFallbackLabel" xml:space="preserve"><value>磁碟回退</value></data>
|
||||
<data name="SettingDiskFallbackTooltip" xml:space="preserve"><value>記憶體不足時在磁碟建立暫存檔</value></data>
|
||||
<data name="SectionAutomationSettingsHeader" xml:space="preserve"><value>自動化設定</value></data>
|
||||
<data name="SettingAutoGenerateLabel" xml:space="preserve"><value>自動產生</value></data>
|
||||
<data name="SettingClearCacheOnExitLabel" xml:space="preserve"><value>結束時清除快取</value></data>
|
||||
<data name="SectionAdvancedSettingsHeader" xml:space="preserve"><value>進階設定</value></data>
|
||||
<data name="SettingEnableAdvancedLabel" xml:space="preserve"><value>啟用進階設定</value></data>
|
||||
<data name="SettingHardwareAccelerationLabel" xml:space="preserve"><value>硬體加速</value></data>
|
||||
<data name="SectionCacheManagementHeader" xml:space="preserve"><value>快取管理</value></data>
|
||||
<data name="ButtonRefreshInfo" xml:space="preserve"><value>更新資訊</value></data>
|
||||
<data name="ButtonClearCache" xml:space="preserve"><value>清除快取</value></data>
|
||||
<data name="CacheListHeader" xml:space="preserve"><value>快取清單</value></data>
|
||||
<data name="CacheListEmpty" xml:space="preserve"><value>沒有快取。</value></data>
|
||||
<data name="SectionVideoCacheHeader" xml:space="preserve"><value>影片快取</value></data>
|
||||
<data name="SectionVideoCacheDescription" xml:space="preserve"><value>將代理影片永久保存到磁碟以縮短啟動時間</value></data>
|
||||
<data name="SettingEnableVideoCacheLabel" xml:space="preserve"><value>啟用影片快取</value></data>
|
||||
<data name="SettingEnableVideoCacheTooltip" xml:space="preserve"><value>將代理影片儲存到磁碟並在下次啟動時自動載入。&#10;免去重新產生。</value></data>
|
||||
<data name="VideoCacheSummaryFormat" xml:space="preserve"><value>永久快取: {0} 項({1})</value></data>
|
||||
<data name="VideoCacheListHeader" xml:space="preserve"><value>永久快取清單</value></data>
|
||||
<data name="VideoCacheListEmpty" xml:space="preserve"><value>沒有永久快取。</value></data>
|
||||
<data name="ButtonClearVideoCache" xml:space="preserve"><value>清除永久快取</value></data>
|
||||
<data name="StoragePersistent" xml:space="preserve"><value>永久</value></data>
|
||||
</root>
|
||||
@@ -1,38 +0,0 @@
|
||||
using System.Buffers;
|
||||
|
||||
namespace ProxyForge.Memory;
|
||||
|
||||
internal static class BufferPool
|
||||
{
|
||||
private const int MaxPoolableSize = 1024 * 1024;
|
||||
internal static byte[] Rent(int minimumLength) => ArrayPool<byte>.Shared.Rent(minimumLength);
|
||||
|
||||
internal static void Return(byte[] buffer, bool clearArray = false)
|
||||
{
|
||||
if (buffer.Length <= MaxPoolableSize)
|
||||
ArrayPool<byte>.Shared.Return(buffer, clearArray);
|
||||
}
|
||||
}
|
||||
|
||||
internal struct PooledBuffer : IDisposable
|
||||
{
|
||||
private byte[]? _buffer;
|
||||
private readonly int _length;
|
||||
|
||||
internal PooledBuffer(int length)
|
||||
{
|
||||
_length = length;
|
||||
_buffer = BufferPool.Rent(length);
|
||||
}
|
||||
|
||||
internal readonly byte[] Array => _buffer ?? throw new ObjectDisposedException(nameof(PooledBuffer));
|
||||
internal readonly int Length => _length;
|
||||
internal readonly Span<byte> Span => _buffer is not null ? _buffer.AsSpan(0, _length) : throw new ObjectDisposedException(nameof(PooledBuffer));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
var buf = Interlocked.Exchange(ref _buffer, null);
|
||||
if (buf is not null)
|
||||
BufferPool.Return(buf);
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace ProxyForge.Memory;
|
||||
|
||||
internal sealed class FallbackStream : Stream
|
||||
{
|
||||
private Stream _inner;
|
||||
private readonly MemoryBudget _budget;
|
||||
private readonly string _fallbackDir;
|
||||
private string? _fallbackPath;
|
||||
private volatile bool _isFallenBack;
|
||||
private int _disposed;
|
||||
private readonly object _switchLock = new();
|
||||
|
||||
internal bool IsFallenBack => _isFallenBack;
|
||||
|
||||
internal FallbackStream(MemoryBudget budget, string fallbackDirectory, int initialCapacity = 4096)
|
||||
{
|
||||
_budget = budget;
|
||||
_fallbackDir = fallbackDirectory;
|
||||
_inner = new MemoryStream(initialCapacity);
|
||||
}
|
||||
|
||||
public override bool CanRead => _inner.CanRead;
|
||||
public override bool CanSeek => _inner.CanSeek;
|
||||
public override bool CanWrite => Volatile.Read(ref _disposed) == 0 && _inner.CanWrite;
|
||||
public override long Length => _inner.Length;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => _inner.Position;
|
||||
set => _inner.Position = value;
|
||||
}
|
||||
|
||||
public override void Flush() => _inner.Flush();
|
||||
public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count);
|
||||
public override int Read(Span<byte> buffer) => _inner.Read(buffer);
|
||||
public override long Seek(long offset, SeekOrigin origin) => _inner.Seek(offset, origin);
|
||||
public override void SetLength(long value) => _inner.SetLength(value);
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (_isFallenBack)
|
||||
{
|
||||
_inner.Write(buffer, offset, count);
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_switchLock)
|
||||
{
|
||||
if (!_isFallenBack && !_budget.CanAllocateInMemory(_inner.Position + count))
|
||||
SwitchToDiskCore();
|
||||
_inner.Write(buffer, offset, count);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
if (_isFallenBack)
|
||||
{
|
||||
_inner.Write(buffer);
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_switchLock)
|
||||
{
|
||||
if (!_isFallenBack && !_budget.CanAllocateInMemory(_inner.Position + buffer.Length))
|
||||
SwitchToDiskCore();
|
||||
_inner.Write(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return ValueTask.FromCanceled(cancellationToken);
|
||||
|
||||
Write(buffer.Span);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
internal byte[] ToArray()
|
||||
{
|
||||
lock (_switchLock)
|
||||
{
|
||||
if (_inner is MemoryStream ms)
|
||||
return ms.ToArray();
|
||||
|
||||
var pos = _inner.Position;
|
||||
_inner.Position = 0;
|
||||
var result = new byte[_inner.Length];
|
||||
int totalRead = 0;
|
||||
while (totalRead < result.Length)
|
||||
{
|
||||
int read = _inner.Read(result, totalRead, result.Length - totalRead);
|
||||
if (read == 0)
|
||||
break;
|
||||
totalRead += read;
|
||||
}
|
||||
_inner.Position = pos;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
internal string? TransferDiskOwnership()
|
||||
{
|
||||
lock (_switchLock)
|
||||
{
|
||||
if (!_isFallenBack || _fallbackPath is null)
|
||||
return null;
|
||||
|
||||
var path = _fallbackPath;
|
||||
_fallbackPath = null;
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
private void SwitchToDiskCore()
|
||||
{
|
||||
if (_isFallenBack)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_fallbackDir);
|
||||
|
||||
Span<char> nameBuf = stackalloc char[40];
|
||||
"zdp_".AsSpan().CopyTo(nameBuf);
|
||||
Guid.NewGuid().TryFormat(nameBuf[4..], out _, "N");
|
||||
".tmp".AsSpan().CopyTo(nameBuf[36..]);
|
||||
var path = Path.Combine(_fallbackDir, new string(nameBuf));
|
||||
|
||||
var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 65536);
|
||||
|
||||
var oldStream = _inner;
|
||||
var position = oldStream.Position;
|
||||
oldStream.Position = 0;
|
||||
oldStream.CopyTo(fileStream);
|
||||
fileStream.Position = position;
|
||||
|
||||
var memLength = oldStream.Length;
|
||||
_inner = fileStream;
|
||||
_fallbackPath = path;
|
||||
_isFallenBack = true;
|
||||
|
||||
oldStream.Dispose();
|
||||
_budget.RecordDeallocation(memLength);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[FallbackStream] Disk fallback failed: ", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
lock (_switchLock)
|
||||
{
|
||||
var length = _inner.Length;
|
||||
_inner.Dispose();
|
||||
|
||||
if (!_isFallenBack)
|
||||
_budget.RecordDeallocation(length);
|
||||
|
||||
if (_fallbackPath is not null)
|
||||
{
|
||||
try { File.Delete(_fallbackPath); }
|
||||
catch { }
|
||||
_fallbackPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ProxyForge.Memory;
|
||||
|
||||
internal sealed class MemoryBudget(long reserveMb, long maxCacheMb)
|
||||
{
|
||||
private readonly long _reserveBytes = reserveMb * 1024L * 1024L;
|
||||
private readonly long _maxCacheBytes = maxCacheMb * 1024L * 1024L;
|
||||
private long _allocatedBytes;
|
||||
|
||||
private long _memoryCachePacked;
|
||||
private const long MemoryCacheIntervalMs = 100L;
|
||||
|
||||
internal long AllocatedBytes => Volatile.Read(ref _allocatedBytes);
|
||||
|
||||
internal bool CanAllocateInMemory(long requestedBytes)
|
||||
{
|
||||
if (requestedBytes <= 0)
|
||||
return true;
|
||||
|
||||
var limit = Math.Min(GetCachedAvailablePhysicalMemory() - _reserveBytes, _maxCacheBytes);
|
||||
if (limit <= 0)
|
||||
return false;
|
||||
|
||||
var allocated = Volatile.Read(ref _allocatedBytes);
|
||||
return allocated >= 0 && requestedBytes <= limit - allocated;
|
||||
}
|
||||
|
||||
internal bool TryAllocate(long requestedBytes)
|
||||
{
|
||||
if (requestedBytes <= 0)
|
||||
return true;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var available = GetCachedAvailablePhysicalMemory();
|
||||
var current = Volatile.Read(ref _allocatedBytes);
|
||||
if (current < 0)
|
||||
return false;
|
||||
|
||||
var limit = Math.Min(available - _reserveBytes, _maxCacheBytes);
|
||||
if (limit <= 0)
|
||||
return false;
|
||||
|
||||
var next = current + requestedBytes;
|
||||
if (next < 0 || next > limit)
|
||||
return false;
|
||||
|
||||
if (Interlocked.CompareExchange(ref _allocatedBytes, next, current) == current)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal void RecordAllocation(long bytes)
|
||||
{
|
||||
if (bytes > 0)
|
||||
Interlocked.Add(ref _allocatedBytes, bytes);
|
||||
}
|
||||
|
||||
internal void RecordDeallocation(long bytes)
|
||||
{
|
||||
if (bytes > 0)
|
||||
Interlocked.Add(ref _allocatedBytes, -bytes);
|
||||
}
|
||||
|
||||
internal static long EstimateProxySize(long originalFileSize, float scale)
|
||||
=> (long)(originalFileSize * scale * scale * 0.3);
|
||||
|
||||
private static uint WrapSafeElapsedMs(uint nowMs, uint cachedMs) =>
|
||||
unchecked(nowMs - cachedMs);
|
||||
|
||||
private long GetCachedAvailablePhysicalMemory()
|
||||
{
|
||||
var nowMs = (uint)Environment.TickCount64;
|
||||
var packed = Interlocked.Read(ref _memoryCachePacked);
|
||||
var cachedMs = (uint)(packed >> 32);
|
||||
|
||||
if (WrapSafeElapsedMs(nowMs, cachedMs) < (uint)MemoryCacheIntervalMs)
|
||||
{
|
||||
var memKb = (uint)packed;
|
||||
if (memKb > 0)
|
||||
return (long)memKb * 1024L;
|
||||
}
|
||||
|
||||
var fresh = GetAvailablePhysicalMemory();
|
||||
var freshKbCapped = (uint)Math.Min(fresh >> 10, (long)uint.MaxValue);
|
||||
Interlocked.Exchange(ref _memoryCachePacked, ((long)nowMs << 32) | freshKbCapped);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MEMORYSTATUSEX
|
||||
{
|
||||
public uint dwLength;
|
||||
public uint dwMemoryLoad;
|
||||
public ulong ullTotalPhys;
|
||||
public ulong ullAvailPhys;
|
||||
public ulong ullTotalPageFile;
|
||||
public ulong ullAvailPageFile;
|
||||
public ulong ullTotalVirtual;
|
||||
public ulong ullAvailVirtual;
|
||||
public ulong ullAvailExtendedVirtual;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
|
||||
|
||||
private static long GetAvailablePhysicalMemory()
|
||||
{
|
||||
var status = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };
|
||||
return GlobalMemoryStatusEx(ref status) ? (long)status.ullAvailPhys : 2L * 1024 * 1024 * 1024;
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Core;
|
||||
using ProxyForge.Detection;
|
||||
using ProxyForge.Interfaces;
|
||||
using ProxyForge.Memory;
|
||||
using ProxyForge.Services;
|
||||
using ProxyForge.Settings;
|
||||
using ProxyForge.Streaming;
|
||||
using ProxyForge.ViewModels;
|
||||
using ProxyForge.Views;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Plugin;
|
||||
|
||||
internal sealed class PluginHost : IDisposable
|
||||
{
|
||||
private static PluginHost? _instance;
|
||||
private static readonly object Lock = new();
|
||||
private int _disposed;
|
||||
private GenerationPopupView? _popupView;
|
||||
|
||||
internal static PluginHost? Instance => _instance;
|
||||
internal MemoryBudget Budget { get; }
|
||||
internal ProxyCacheManager CacheManager { get; }
|
||||
internal IExportDetector ExportDetector { get; }
|
||||
internal ChunkAllocator ChunkAllocator { get; }
|
||||
internal string FallbackDirectory { get; }
|
||||
internal string TmpDirectory { get; }
|
||||
internal VideoCacheDatabase? VideoCache { get; }
|
||||
|
||||
private PluginHost(
|
||||
MemoryBudget budget,
|
||||
IProxyEncoderFactory encoderFactory,
|
||||
IExportDetector exportDetector,
|
||||
ChunkAllocator chunkAllocator,
|
||||
string fallbackDirectory,
|
||||
string tmpDirectory,
|
||||
VideoCacheDatabase? videoCache)
|
||||
{
|
||||
Budget = budget;
|
||||
ExportDetector = exportDetector;
|
||||
ChunkAllocator = chunkAllocator;
|
||||
FallbackDirectory = fallbackDirectory;
|
||||
TmpDirectory = tmpDirectory;
|
||||
VideoCache = videoCache;
|
||||
CacheManager = new ProxyCacheManager(encoderFactory, videoCache, tmpDirectory);
|
||||
|
||||
CacheManager.ActiveGenerations.CollectionChanged += OnGenerationsChanged;
|
||||
}
|
||||
|
||||
private static PluginHost CreateDefault()
|
||||
{
|
||||
var settings = ProxyForgeSettings.Default;
|
||||
var budget = new MemoryBudget(settings.MemoryReserveMb, settings.MaxCacheMemoryMb);
|
||||
var pluginDir = Path.GetDirectoryName(typeof(PluginHost).Assembly.Location) ?? AppDirectories.TemporaryDirectory;
|
||||
var cacheDir = Path.Combine(pluginDir, "cache");
|
||||
var tmpDirectory = Path.Combine(cacheDir, "tmp");
|
||||
var chunkAllocator = new ChunkAllocator(65536);
|
||||
|
||||
MfSession.AddRef();
|
||||
WindowThemeRegistry.Register(new WindowThemeService());
|
||||
|
||||
IProxyEncoderFactory encoderFactory = new MfProxyEncoderFactory(
|
||||
budget,
|
||||
tmpDirectory,
|
||||
static () => new EncoderConfig(
|
||||
ProxyForgeSettings.Default.EnableHardwareAcceleration,
|
||||
ProxyForgeSettings.Default.EnableDiskFallback));
|
||||
|
||||
VideoCacheDatabase? videoCache = null;
|
||||
if (settings.EnableVideoCache)
|
||||
{
|
||||
try
|
||||
{
|
||||
videoCache = new VideoCacheDatabase(cacheDir);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
IExportDetector exportDetector = new ExportDetector();
|
||||
return new PluginHost(budget, encoderFactory, exportDetector, chunkAllocator, tmpDirectory, tmpDirectory, videoCache);
|
||||
}
|
||||
|
||||
internal static PluginHost EnsureInitialized()
|
||||
{
|
||||
if (_instance is not null)
|
||||
return _instance;
|
||||
|
||||
lock (Lock)
|
||||
{
|
||||
_instance ??= CreateDefault();
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
|
||||
internal static void TearDown()
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
if (_instance is null)
|
||||
return;
|
||||
|
||||
_instance.Dispose();
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnGenerationsChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
Application.Current?.Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (CacheManager.ActiveGenerations.Count > 0)
|
||||
EnsurePopupVisible();
|
||||
else
|
||||
_popupView?.Hide();
|
||||
});
|
||||
}
|
||||
|
||||
private void EnsurePopupVisible()
|
||||
{
|
||||
if (_popupView is null)
|
||||
{
|
||||
var vm = new GenerationPopupViewModel(CacheManager.ActiveGenerations);
|
||||
_popupView = new GenerationPopupView(vm);
|
||||
WindowThemeRegistry.Bind(_popupView);
|
||||
|
||||
var mainWindow = Application.Current?.MainWindow;
|
||||
if (mainWindow is { IsLoaded: true })
|
||||
{
|
||||
try
|
||||
{
|
||||
_popupView.Owner = mainWindow;
|
||||
}
|
||||
catch
|
||||
{
|
||||
var helper = new WindowInteropHelper(_popupView);
|
||||
var mainHelper = new WindowInteropHelper(mainWindow);
|
||||
if (mainHelper.Handle != nint.Zero)
|
||||
helper.Owner = mainHelper.Handle;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!_popupView.IsVisible)
|
||||
_popupView.Show();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
CacheManager.ActiveGenerations.CollectionChanged -= OnGenerationsChanged;
|
||||
|
||||
Application.Current?.Dispatcher.Invoke(() =>
|
||||
{
|
||||
_popupView?.ForceClose();
|
||||
_popupView = null;
|
||||
});
|
||||
|
||||
CacheManager.Dispose();
|
||||
VideoCache?.Dispose();
|
||||
ChunkAllocator.Dispose();
|
||||
CleanupTmpDirectory();
|
||||
|
||||
MfSession.Release();
|
||||
}
|
||||
|
||||
private void CleanupTmpDirectory()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(TmpDirectory))
|
||||
return;
|
||||
|
||||
foreach (var file in Directory.GetFiles(TmpDirectory))
|
||||
{
|
||||
try { File.Delete(file); }
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
using ProxyForge.Core;
|
||||
using ProxyForge.Settings;
|
||||
using ProxyForge.Streaming;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Plugin;
|
||||
|
||||
internal sealed class ProxyForgePlugin : IVideoFileSourcePlugin
|
||||
{
|
||||
public string Name => "ProxyForge";
|
||||
|
||||
public ProxyForgePlugin()
|
||||
{
|
||||
PluginHost.EnsureInitialized();
|
||||
if (Application.Current is not null)
|
||||
Application.Current.Exit += OnApplicationExit;
|
||||
}
|
||||
|
||||
public IVideoFileSource? CreateVideoFileSource(IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreateCore(devices, filePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyForge] CreateCore failed for ", filePath, ": ", ex.Message));
|
||||
return FallbackLoad(devices, filePath);
|
||||
}
|
||||
}
|
||||
|
||||
private static IVideoFileSource? CreateCore(IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
var host = PluginHost.Instance;
|
||||
if (host is null)
|
||||
return null;
|
||||
|
||||
var settings = ProxyForgeSettings.Default;
|
||||
if (!settings.UseProxy && !settings.AutoGenerate)
|
||||
return null;
|
||||
|
||||
if (host.ExportDetector.IsExporting())
|
||||
return WrapFromOther(devices, filePath);
|
||||
|
||||
if (!IsLargeEnough(filePath, settings.MinFileSizeForProxy))
|
||||
return null;
|
||||
|
||||
var proxyScale = settings.Scale / 100f;
|
||||
|
||||
if (settings.UseProxy)
|
||||
{
|
||||
var cached = host.CacheManager.TryGetProxy(filePath, proxyScale);
|
||||
if (cached is { IsValid: true })
|
||||
return LoadFromCache(devices, cached, host.FallbackDirectory);
|
||||
|
||||
var initialSource = CreateLightweightSource(devices, filePath)
|
||||
?? WrapFromOther(devices, filePath);
|
||||
if (initialSource is null)
|
||||
return null;
|
||||
|
||||
var generationStarted = 0;
|
||||
return new ProxyForgeVideoSource(initialSource, devices,
|
||||
() =>
|
||||
{
|
||||
if (Interlocked.Exchange(ref generationStarted, 1) == 0)
|
||||
host.CacheManager.StartProxyGeneration(filePath, proxyScale, settings);
|
||||
return TryLoadProxy(devices, filePath, proxyScale, host);
|
||||
});
|
||||
}
|
||||
|
||||
if (settings.AutoGenerate)
|
||||
{
|
||||
if (!host.CacheManager.ProxyExists(filePath, proxyScale))
|
||||
host.CacheManager.StartProxyGeneration(filePath, proxyScale, settings);
|
||||
|
||||
return WrapFromOther(devices, filePath);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static IVideoFileSource? CreateLightweightSource(
|
||||
IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
return LightweightVideoFileSource.TryCreate(filePath, devices);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyForge] LightweightSource failed for ", filePath, ": ", ex.Message));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static IVideoFileSource? LoadFromCache(
|
||||
IGraphicsDevicesAndContext devices, ProxyCacheEntry entry, string fallbackDir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tempPath = entry.GetOrCreateTempFilePath(fallbackDir);
|
||||
|
||||
var source = LoadRaw(devices, tempPath);
|
||||
if (source is null)
|
||||
return null;
|
||||
|
||||
return entry.Scale < 0.99f
|
||||
? new ProxyForgeVideoSourceWithScale(source, devices, entry.Scale)
|
||||
: new ProxyForgeVideoSource(source, devices);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyForge] LoadFromCache failed: ", ex.Message));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static IVideoFileSource? WrapFromOther(IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
var source = LoadRaw(devices, filePath);
|
||||
return source is not null ? new ProxyForgeVideoSource(source, devices) : null;
|
||||
}
|
||||
|
||||
private static IVideoFileSource? LoadRaw(IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
foreach (var plugin in PluginLoader.VideoFileSourcePlugins)
|
||||
{
|
||||
if (plugin is ProxyForgePlugin)
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
var s = plugin.CreateVideoFileSource(devices, filePath);
|
||||
if (s is not null)
|
||||
return s;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyForge] Plugin ", plugin.Name, " failed for ", filePath, ": ", ex.Message));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static IVideoFileSource? FallbackLoad(IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var lightSource = CreateLightweightSource(devices, filePath);
|
||||
if (lightSource is not null)
|
||||
return lightSource;
|
||||
|
||||
return WrapFromOther(devices, filePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(string.Concat("[ProxyForge] FallbackLoad failed for ", filePath, ": ", ex.Message));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static IVideoFileSource? TryLoadProxy(
|
||||
IGraphicsDevicesAndContext devices, string filePath, float proxyScale, PluginHost host)
|
||||
{
|
||||
var cached = host.CacheManager.TryGetProxy(filePath, proxyScale);
|
||||
if (cached is null || !cached.IsValid)
|
||||
return null;
|
||||
|
||||
var source = LoadFromCache(devices, cached, host.FallbackDirectory);
|
||||
if (source is null)
|
||||
host.CacheManager.RemoveProxy(filePath, proxyScale);
|
||||
|
||||
return source;
|
||||
}
|
||||
|
||||
private static bool IsLargeEnough(string filePath, int minSizeMb)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(filePath);
|
||||
return info.Exists && info.Length >= (long)minSizeMb * 1048576L;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnApplicationExit(object? sender, ExitEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (ProxyForgeSettings.Default.ClearCacheOnExit)
|
||||
PluginHost.Instance?.CacheManager.ClearAll();
|
||||
|
||||
PluginHost.TearDown();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Plugin;
|
||||
|
||||
internal sealed class ProxyForgeVideoSource : IVideoFileSource
|
||||
{
|
||||
private IVideoFileSource _inner;
|
||||
private Func<IVideoFileSource?>? _tryUpgradeSource;
|
||||
private readonly AffineTransform2D _switchEffect;
|
||||
private readonly ID2D1Image _output;
|
||||
private List<IVideoFileSource>? _retiredSources;
|
||||
private readonly object _gate = new();
|
||||
private volatile bool _upgraded;
|
||||
private volatile IVideoFileSource? _pendingUpgrade;
|
||||
private int _upgradeFetching;
|
||||
private long _nextUpgradeAttemptTicks;
|
||||
private int _disposed;
|
||||
|
||||
public TimeSpan Duration
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
return _inner.Duration;
|
||||
}
|
||||
}
|
||||
|
||||
public ID2D1Image Output => _output;
|
||||
|
||||
internal ProxyForgeVideoSource(IVideoFileSource inner, IGraphicsDevicesAndContext devices)
|
||||
{
|
||||
_inner = inner;
|
||||
_switchEffect = new AffineTransform2D(devices.DeviceContext);
|
||||
_switchEffect.SetInput(0, inner.Output, true);
|
||||
_switchEffect.TransformMatrix = Matrix3x2.Identity;
|
||||
_output = _switchEffect.Output;
|
||||
}
|
||||
|
||||
internal ProxyForgeVideoSource(IVideoFileSource inner, IGraphicsDevicesAndContext devices, Func<IVideoFileSource?> tryUpgradeSource)
|
||||
{
|
||||
_inner = inner;
|
||||
_switchEffect = new AffineTransform2D(devices.DeviceContext);
|
||||
_switchEffect.SetInput(0, inner.Output, true);
|
||||
_switchEffect.TransformMatrix = Matrix3x2.Identity;
|
||||
_output = _switchEffect.Output;
|
||||
_tryUpgradeSource = tryUpgradeSource;
|
||||
}
|
||||
|
||||
public void Update(TimeSpan time)
|
||||
{
|
||||
if (!_upgraded && _tryUpgradeSource is not null)
|
||||
TryApplyUpgrade();
|
||||
|
||||
if (_upgraded)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) == 0)
|
||||
_inner.Update(time);
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) == 0)
|
||||
_inner.Update(time);
|
||||
}
|
||||
}
|
||||
|
||||
private void TryApplyUpgrade()
|
||||
{
|
||||
var pending = _pendingUpgrade;
|
||||
if (pending is not null)
|
||||
{
|
||||
_pendingUpgrade = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_upgraded && Volatile.Read(ref _disposed) == 0)
|
||||
{
|
||||
var old = _inner;
|
||||
_inner = pending;
|
||||
_switchEffect.SetInput(0, pending.Output, true);
|
||||
_upgraded = true;
|
||||
_tryUpgradeSource = null;
|
||||
_retiredSources = null;
|
||||
old.Dispose();
|
||||
ThreadPool.QueueUserWorkItem(static _ => ForceMemoryReclaim());
|
||||
}
|
||||
else
|
||||
{
|
||||
pending.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var now = Stopwatch.GetTimestamp();
|
||||
if (now >= Volatile.Read(ref _nextUpgradeAttemptTicks) &&
|
||||
Interlocked.Exchange(ref _upgradeFetching, 1) == 0)
|
||||
{
|
||||
Volatile.Write(ref _nextUpgradeAttemptTicks, now + Stopwatch.Frequency / 2);
|
||||
ThreadPool.UnsafeQueueUserWorkItem(static s => s.FetchUpgradeAsync(), this, preferLocal: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void FetchUpgradeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var upgraded = _tryUpgradeSource!();
|
||||
if (upgraded is not null)
|
||||
_pendingUpgrade = upgraded;
|
||||
}
|
||||
catch { }
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _upgradeFetching, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public int GetFrameIndex(TimeSpan time)
|
||||
{
|
||||
lock (_gate)
|
||||
return _inner.GetFrameIndex(time);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
_output.Dispose();
|
||||
_switchEffect.SetInput(0, null, true);
|
||||
_switchEffect.Dispose();
|
||||
_inner.Dispose();
|
||||
|
||||
if (_retiredSources is { } retired)
|
||||
{
|
||||
foreach (var source in retired)
|
||||
source.Dispose();
|
||||
retired.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
var orphan = _pendingUpgrade;
|
||||
if (orphan is not null)
|
||||
{
|
||||
_pendingUpgrade = null;
|
||||
orphan.Dispose();
|
||||
}
|
||||
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
private static void ForceMemoryReclaim()
|
||||
{
|
||||
try
|
||||
{
|
||||
GC.Collect(2, GCCollectionMode.Aggressive, true, true);
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect(2, GCCollectionMode.Forced, true, true);
|
||||
GC.WaitForPendingFinalizers();
|
||||
GC.Collect(1, GCCollectionMode.Forced, true);
|
||||
|
||||
try
|
||||
{
|
||||
EmptyWorkingSet(GetCurrentProcess());
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
[DllImport("kernel32")]
|
||||
private static extern nint GetCurrentProcess();
|
||||
|
||||
[DllImport("psapi")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool EmptyWorkingSet(nint hProcess);
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
using System.Numerics;
|
||||
using Vortice.Direct2D1;
|
||||
using Vortice.Direct2D1.Effects;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge.Plugin;
|
||||
|
||||
internal sealed class ProxyForgeVideoSourceWithScale : IVideoFileSource
|
||||
{
|
||||
private readonly IVideoFileSource _inner;
|
||||
private readonly AffineTransform2D _scaleEffect;
|
||||
private readonly ID2D1Image _output;
|
||||
private int _disposed;
|
||||
|
||||
public TimeSpan Duration => _inner.Duration;
|
||||
public ID2D1Image Output => _output;
|
||||
|
||||
internal ProxyForgeVideoSourceWithScale(IVideoFileSource inner, IGraphicsDevicesAndContext devices, float proxyScale)
|
||||
{
|
||||
_inner = inner;
|
||||
_scaleEffect = new AffineTransform2D(devices.DeviceContext);
|
||||
_scaleEffect.SetInput(0, inner.Output, true);
|
||||
_scaleEffect.TransformMatrix = Matrix3x2.CreateScale(1f / proxyScale);
|
||||
_output = _scaleEffect.Output;
|
||||
}
|
||||
|
||||
public void Update(TimeSpan time) => _inner.Update(time);
|
||||
public int GetFrameIndex(TimeSpan time) => _inner.GetFrameIndex(time);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return;
|
||||
|
||||
_output.Dispose();
|
||||
_scaleEffect.SetInput(0, null, true);
|
||||
_scaleEffect.Dispose();
|
||||
_inner.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Collections.Immutable;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
|
||||
namespace ProxyForge;
|
||||
|
||||
internal static class PluginOrder
|
||||
{
|
||||
public static string PluginName { get; } = typeof(ProxyForgeVideoFileSourcePlugin).FullName ?? nameof(ProxyForgeVideoFileSourcePlugin);
|
||||
|
||||
public static bool IsFirst(ImmutableList<string> order, string name)
|
||||
=> order.Count > 0 && string.Equals(order[0], name, StringComparison.Ordinal);
|
||||
|
||||
public static ImmutableList<string> MoveToFront(ImmutableList<string> order, string name)
|
||||
=> order.RemoveAll(entry => string.Equals(entry, name, StringComparison.Ordinal)).Insert(0, name);
|
||||
|
||||
public static bool IsPluginFirst()
|
||||
=> IsFirst(PluginLoaderSettings.Default.VideoFileSourcePlugins, PluginName);
|
||||
|
||||
public static void MovePluginToFront()
|
||||
=> PluginLoaderSettings.Default.VideoFileSourcePlugins = MoveToFront(PluginLoaderSettings.Default.VideoFileSourcePlugins, PluginName);
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
using ProxyForge.Localization;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace ProxyForge.Progress;
|
||||
|
||||
public sealed class ProxyGenerationItem : Bindable
|
||||
{
|
||||
public string FileName { get; }
|
||||
public string OriginalPath { get; }
|
||||
public DateTime StartedAt { get; } = DateTime.Now;
|
||||
|
||||
private long _pendingProgressBits;
|
||||
|
||||
private double _progress;
|
||||
public double Progress
|
||||
{
|
||||
get => _progress;
|
||||
set
|
||||
{
|
||||
if (Set(ref _progress, value))
|
||||
{
|
||||
OnPropertyChanged(nameof(ProgressText));
|
||||
OnPropertyChanged(nameof(ElapsedText));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string ProgressText => string.Create(null, stackalloc char[16], $"{Progress:F1}%");
|
||||
|
||||
public string ElapsedText
|
||||
{
|
||||
get
|
||||
{
|
||||
var elapsed = DateTime.Now - StartedAt;
|
||||
return elapsed.TotalMinutes >= 1
|
||||
? string.Create(null, stackalloc char[16], $"{(int)elapsed.TotalMinutes}m{elapsed.Seconds}s")
|
||||
: string.Create(null, stackalloc char[8], $"{elapsed.Seconds}s");
|
||||
}
|
||||
}
|
||||
|
||||
private bool _isCompleted;
|
||||
public bool IsCompleted
|
||||
{
|
||||
get => _isCompleted;
|
||||
set => Set(ref _isCompleted, value);
|
||||
}
|
||||
|
||||
private bool _isFailed;
|
||||
public bool IsFailed
|
||||
{
|
||||
get => _isFailed;
|
||||
set => Set(ref _isFailed, value);
|
||||
}
|
||||
|
||||
private string _statusMessage = Translate.ProxyGenerationStatusGenerating;
|
||||
public string StatusMessage
|
||||
{
|
||||
get => _statusMessage;
|
||||
set => Set(ref _statusMessage, value);
|
||||
}
|
||||
|
||||
private bool _isInMemory = true;
|
||||
public bool IsInMemory
|
||||
{
|
||||
get => _isInMemory;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isInMemory, value))
|
||||
OnPropertyChanged(nameof(StorageText));
|
||||
}
|
||||
}
|
||||
|
||||
public string StorageText => _isInMemory ? Translate.StorageMemory : Translate.StorageDisk;
|
||||
|
||||
internal ProxyGenerationItem(string originalPath)
|
||||
{
|
||||
OriginalPath = originalPath;
|
||||
FileName = System.IO.Path.GetFileName(originalPath);
|
||||
}
|
||||
|
||||
internal void SetPendingProgress(double value) =>
|
||||
Interlocked.Exchange(ref _pendingProgressBits, BitConverter.DoubleToInt64Bits(value));
|
||||
|
||||
internal void ApplyPendingProgress() =>
|
||||
Progress = BitConverter.Int64BitsToDouble(Interlocked.Read(ref _pendingProgressBits));
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"profiles": {
|
||||
"ZeroDiskProxy": {
|
||||
"commandName": "Project"
|
||||
},
|
||||
"YMM4": {
|
||||
"commandName": "Executable",
|
||||
"executablePath": "C:\\Program Files\\YukkuriMovieMaker_v4_Lite_Dev\\YukkuriMovieMaker.exe"
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-54
@@ -1,67 +1,43 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Version>1.0.1</Version>
|
||||
<Version>2.0.0</Version>
|
||||
<Platforms>AnyCPU;x64;x64</Platforms>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="bin\**" />
|
||||
<EmbeddedResource Remove="bin\**" />
|
||||
<None Remove="bin\**" />
|
||||
<Page Remove="bin\**" />
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||
<_Parameter1>ProxyForge.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="AvalonDock">
|
||||
<HintPath>$(YMM4DirPath)AvalonDock.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="NAudio">
|
||||
<HintPath>$(YMM4DirPath)NAudio.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="NAudio.Core">
|
||||
<HintPath>$(YMM4DirPath)NAudio.Core.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="NAudio.Midi">
|
||||
<HintPath>$(YMM4DirPath)NAudio.Midi.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="NCalc.Core">
|
||||
<HintPath>$(YMM4DirPath)NCalc.Core.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json">
|
||||
<HintPath>$(YMM4DirPath)Newtonsoft.Json.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime.COM">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct2D1">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct2D1.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.Direct3D11">
|
||||
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.D3DCompiler.dll">
|
||||
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DXGI.dll">
|
||||
<Reference Include="Vortice.DXGI">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
@@ -69,10 +45,6 @@
|
||||
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="YukkuriMovieMaker.Controls">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Controls.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
@@ -81,31 +53,27 @@
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpGen.Runtime.COM">
|
||||
<HintPath>$(YMM4DirPath)SharpGen.Runtime.COM.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
<Reference Include="Vortice.DirectX">
|
||||
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
|
||||
<Reference Include="YukkuriMovieMaker.Plugin.FileSource.FFmpeg">
|
||||
<HintPath>$(YMM4DirPath)YukkuriMovieMaker.Plugin.FileSource.FFmpeg.dll</HintPath>
|
||||
<Private>false</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\YMM4-GitHubUpdateNotifier\GitHubUpdateNotifier\*.cs" LinkBase="GitHubUpdateNotifier" />
|
||||
</ItemGroup>
|
||||
|
||||
<Import Project="..\YMM4-Telemetry\Telemetry.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
|
||||
<AdditionalFiles Include="**/*.csv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AdditionalFiles Remove="bin\**" />
|
||||
</ItemGroup>
|
||||
<Import Project="..\YukkuriMovieMaker.Generator\YukkuriMovieMaker.Generator.targets" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.IO.Hashing" Version="10.0.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(SkipPluginDeploy)' != 'true'">
|
||||
<Exec Command="mkdir "$(YMM4DirPath)user\plugin\$(ProjectName)" > NUL 2>&1
copy "$(TargetPath)" "$(YMM4DirPath)user\plugin\$(ProjectName)\"" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Windows;
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Export;
|
||||
using ProxyForge.Sources;
|
||||
using ProxyForge.Views;
|
||||
|
||||
namespace ProxyForge;
|
||||
|
||||
internal static class ProxyForgeHost
|
||||
{
|
||||
static int started;
|
||||
|
||||
public static ProxySourceProvider Provider { get; } = new(
|
||||
ProxyCache.Shared,
|
||||
ProxyGenerationQueue.Shared,
|
||||
SourceFocus.Shared,
|
||||
ExportDetector.Shared.IsExporting,
|
||||
() => ProxyForgeSettings.Default,
|
||||
VideoSourceLoader.Load);
|
||||
|
||||
public static void EnsureStartedOnce()
|
||||
{
|
||||
if (Interlocked.Exchange(ref started, 1) != 0)
|
||||
return;
|
||||
|
||||
ProxyForgeTelemetry.EnsureStartedOnce();
|
||||
if (ExportDetector.Shared.IsCommandLineEncode)
|
||||
return;
|
||||
|
||||
ProxyForgeUpdateNotifier.EnsureCheckedOnce();
|
||||
var application = Application.Current;
|
||||
if (application is null)
|
||||
return;
|
||||
|
||||
application.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
ExportWindowWatcher.Attach(ExportDetector.Shared, ProxyForgeTelemetry.Report);
|
||||
GenerationProgressWindowHost.Attach(ProxyGenerationQueue.Shared, ProxyForgeSettings.Default);
|
||||
application.Exit += OnExit;
|
||||
});
|
||||
}
|
||||
|
||||
static void OnExit(object sender, ExitEventArgs e)
|
||||
{
|
||||
ProxyGenerationQueue.Shared.CancelAll();
|
||||
GenerationProgressWindowHost.Shutdown();
|
||||
ExportWindowWatcher.Detach();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using ProxyForge.Cache;
|
||||
using ProxyForge.Encoding;
|
||||
using ProxyForge.Views;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
|
||||
namespace ProxyForge;
|
||||
|
||||
internal sealed class ProxyForgeSettings : SettingsBase<ProxyForgeSettings>
|
||||
{
|
||||
public const int MinimumScale = ProxyGeometryCalculator.MinimumScale;
|
||||
public const int MaximumScale = ProxyGeometryCalculator.MaximumScale;
|
||||
public const int MinimumFileSizeMegabytesLowerBound = 1;
|
||||
public const int MinimumFileSizeMegabytesUpperBound = 100_000;
|
||||
public const int MinimumBitrateScale = 1;
|
||||
public const int MaximumBitrateScale = 200;
|
||||
public const int MinimumKeyFrameInterval = 1;
|
||||
public const int MaximumKeyFrameInterval = 300;
|
||||
public const int MinimumChunkSeconds = 1;
|
||||
public const int MaximumChunkSeconds = 120;
|
||||
public const int MinimumCacheLimitGigabytes = 1;
|
||||
public const int MaximumCacheLimitGigabytes = 1024;
|
||||
const long BytesPerMegabyte = 1024L * 1024L;
|
||||
const long BytesPerGigabyte = 1024L * 1024L * 1024L;
|
||||
|
||||
bool isEnabled = true;
|
||||
bool generatesAutomatically = true;
|
||||
int scale = 50;
|
||||
int minimumFileSizeMegabytes = 100;
|
||||
int bitrateScale = 50;
|
||||
int keyFrameInterval = 30;
|
||||
int chunkSeconds = 10;
|
||||
bool usesHardwareEncoder = true;
|
||||
int cacheLimitGigabytes = 10;
|
||||
bool showsProgressWindow = true;
|
||||
|
||||
public override SettingsCategory Category => SettingsCategory.VideoFileSource;
|
||||
|
||||
public override string Name => Texts.ProxyForge;
|
||||
|
||||
public override bool HasSettingView => true;
|
||||
|
||||
public override object? SettingView => new ProxyForgeSettingsView();
|
||||
|
||||
public bool IsEnabled
|
||||
{
|
||||
get => isEnabled;
|
||||
set => Set(ref isEnabled, value);
|
||||
}
|
||||
|
||||
public bool GeneratesAutomatically
|
||||
{
|
||||
get => generatesAutomatically;
|
||||
set => Set(ref generatesAutomatically, value);
|
||||
}
|
||||
|
||||
public int Scale
|
||||
{
|
||||
get => scale;
|
||||
set => Set(ref scale, Math.Clamp(value, MinimumScale, MaximumScale));
|
||||
}
|
||||
|
||||
public int MinimumFileSizeMegabytes
|
||||
{
|
||||
get => minimumFileSizeMegabytes;
|
||||
set => Set(ref minimumFileSizeMegabytes, Math.Clamp(value, MinimumFileSizeMegabytesLowerBound, MinimumFileSizeMegabytesUpperBound));
|
||||
}
|
||||
|
||||
public int BitrateScale
|
||||
{
|
||||
get => bitrateScale;
|
||||
set => Set(ref bitrateScale, Math.Clamp(value, MinimumBitrateScale, MaximumBitrateScale));
|
||||
}
|
||||
|
||||
public int KeyFrameInterval
|
||||
{
|
||||
get => keyFrameInterval;
|
||||
set => Set(ref keyFrameInterval, Math.Clamp(value, MinimumKeyFrameInterval, MaximumKeyFrameInterval));
|
||||
}
|
||||
|
||||
public int ChunkSeconds
|
||||
{
|
||||
get => chunkSeconds;
|
||||
set => Set(ref chunkSeconds, Math.Clamp(value, MinimumChunkSeconds, MaximumChunkSeconds));
|
||||
}
|
||||
|
||||
public bool UsesHardwareEncoder
|
||||
{
|
||||
get => usesHardwareEncoder;
|
||||
set => Set(ref usesHardwareEncoder, value);
|
||||
}
|
||||
|
||||
public int CacheLimitGigabytes
|
||||
{
|
||||
get => cacheLimitGigabytes;
|
||||
set
|
||||
{
|
||||
if (Set(ref cacheLimitGigabytes, Math.Clamp(value, MinimumCacheLimitGigabytes, MaximumCacheLimitGigabytes)))
|
||||
ApplyCacheLimit();
|
||||
}
|
||||
}
|
||||
|
||||
public bool ShowsProgressWindow
|
||||
{
|
||||
get => showsProgressWindow;
|
||||
set => Set(ref showsProgressWindow, value);
|
||||
}
|
||||
|
||||
public long MinimumFileSizeBytes => minimumFileSizeMegabytes * BytesPerMegabyte;
|
||||
|
||||
public override void Initialize() => ApplyCacheLimit();
|
||||
|
||||
void ApplyCacheLimit() => ProxyCache.Shared.LimitBytes = cacheLimitGigabytes * BytesPerGigabyte;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Telemetry;
|
||||
|
||||
namespace ProxyForge;
|
||||
|
||||
internal static class ProxyForgeTelemetry
|
||||
{
|
||||
private const int MaxChainLength = 5;
|
||||
private const int MaxFrames = 100;
|
||||
|
||||
private static readonly Assembly Own = typeof(ProxyForgeTelemetry).Assembly;
|
||||
private static int _started;
|
||||
|
||||
public static void EnsureStartedOnce()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) != 0)
|
||||
return;
|
||||
|
||||
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
|
||||
|
||||
var application = Application.Current;
|
||||
if (application is not null)
|
||||
application.DispatcherUnhandledException += OnDispatcherUnhandledException;
|
||||
|
||||
TelemetryReporter.Start();
|
||||
}
|
||||
|
||||
public static void Report(Exception exception) => TelemetryReporter.Report(exception);
|
||||
|
||||
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
||||
=> ReportOwn(e.ExceptionObject as Exception);
|
||||
|
||||
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
||||
=> ReportOwn(e.Exception);
|
||||
|
||||
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
=> ReportOwn(e.Exception);
|
||||
|
||||
private static void ReportOwn(Exception? exception)
|
||||
{
|
||||
if (exception is not null && IsOwn(exception))
|
||||
TelemetryReporter.Report(exception);
|
||||
}
|
||||
|
||||
private static bool IsOwn(Exception exception)
|
||||
{
|
||||
var current = exception;
|
||||
for (var depth = 0; current is not null && depth < MaxChainLength; depth++)
|
||||
{
|
||||
if (HasOwnFrame(current))
|
||||
return true;
|
||||
|
||||
current = current is AggregateException aggregate && aggregate.InnerExceptions.Count > 0
|
||||
? aggregate.InnerExceptions[0]
|
||||
: current.InnerException;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool HasOwnFrame(Exception exception)
|
||||
{
|
||||
StackFrame[]? frames;
|
||||
|
||||
try
|
||||
{
|
||||
frames = new StackTrace(exception, false).GetFrames();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (frames is null)
|
||||
return false;
|
||||
|
||||
for (var index = 0; index < Math.Min(frames.Length, MaxFrames); index++)
|
||||
{
|
||||
MethodBase? method;
|
||||
|
||||
try
|
||||
{
|
||||
method = frames[index].GetMethod();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (method?.DeclaringType is { } declaringType && ReferenceEquals(declaringType.Assembly, Own))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Windows;
|
||||
using GitHubUpdateNotifier;
|
||||
using YukkuriMovieMaker.Plugin.Update;
|
||||
using Notifier = GitHubUpdateNotifier.GitHubUpdateNotifier;
|
||||
|
||||
namespace ProxyForge;
|
||||
|
||||
internal static class ProxyForgeUpdateNotifier
|
||||
{
|
||||
private const string Owner = "routersys";
|
||||
private const string Repository = "YMM4-ProxyForge";
|
||||
private static int _started;
|
||||
|
||||
public static void EnsureCheckedOnce()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _started, 1) != 0)
|
||||
return;
|
||||
_ = RunAsync();
|
||||
}
|
||||
|
||||
private static async Task RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var options = new UpdateNotifierOptions
|
||||
{
|
||||
CurrentVersion = PluginVersion.FromAssemblyInformationalVersion(typeof(ProxyForgeUpdateNotifier)),
|
||||
IncludePrerelease = false,
|
||||
MessageFormatter = FormatMessage,
|
||||
NotificationHandler = ShowNotificationAsync,
|
||||
};
|
||||
await new Notifier(Owner, Repository, options).NotifyAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (exception is not UpdateCheckException)
|
||||
ProxyForgeTelemetry.Report(exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static string FormatMessage(UpdateInfo update)
|
||||
=> string.Format(Texts.UpdateAvailableMessage, update.TagName) + Environment.NewLine + update.ReleaseUrl;
|
||||
|
||||
private static Task ShowNotificationAsync(UpdateNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
var application = Application.Current;
|
||||
if (application is null)
|
||||
return Task.CompletedTask;
|
||||
return application.Dispatcher.InvokeAsync(() =>
|
||||
MessageBox.Show(notification.Message, Texts.ProxyForge, MessageBoxButton.OK, MessageBoxImage.Information)).Task;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
|
||||
namespace ProxyForge;
|
||||
|
||||
[PluginDetails(AuthorName = "routersys")]
|
||||
internal sealed class ProxyForgeVideoFileSourcePlugin : IVideoFileSourcePlugin
|
||||
{
|
||||
public string Name => Texts.ProxyForge;
|
||||
|
||||
public IVideoFileSource? CreateVideoFileSource(IGraphicsDevicesAndContext devices, string filePath)
|
||||
{
|
||||
ProxyForgeHost.EnsureStartedOnce();
|
||||
return ProxyForgeHost.Provider.Create(devices, filePath);
|
||||
}
|
||||
}
|
||||
145ファイル中100ファイルを読み込みました。 変更されたファイルが多すぎるため、それ以降のファイルは表示していません。
さらに表示
新しいイシューから参照
ユーザーをブロックする