From 7f0d194ea36a8a0d29e72da8a6397419ee5ca031 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 02:58:57 +0900 Subject: [PATCH 1/9] =?UTF-8?q?ci(release):=20Developer=20ID=E7=BD=B2?= =?UTF-8?q?=E5=90=8D=E3=81=A8Apple=E5=85=AC=E8=A8=BC=E3=81=AB=E5=AF=BE?= =?UTF-8?q?=E5=BF=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名用のSecrets(5項目)がすべて登録されている場合はDeveloper ID署名・Apple公証・ステープルを行う。Secretsが未登録のときは従来のアドホック署名に戻る。一部だけ登録されていると失敗する。 --- .github/workflows/release.yml | 91 ++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 32ea0fb..9f5653a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,9 +15,33 @@ concurrency: jobs: release: runs-on: macos-latest - timeout-minutes: 30 + # 公証の待ち時間(最長 20 分)を含めても収まるようにする。 + timeout-minutes: 45 steps: - uses: actions/checkout@v7 + # 署名用の Secrets が 5 つそろっていれば Developer ID 署名と公証を行う。1 つも無ければ従来のアドホック署名。 + # 一部だけ登録されている場合は、設定ミスとみなして止める(署名なしの DMG を気づかず配信しないため)。 + - name: Check signing secrets + env: + BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }} + P12_PASSWORD: ${{ secrets.P12_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + run: | + missing=() + for name in BUILD_CERTIFICATE_BASE64 P12_PASSWORD APPLE_ID APPLE_TEAM_ID APPLE_APP_SPECIFIC_PASSWORD; do + [ -n "${!name}" ] || missing+=("$name") + done + if [ "${#missing[@]}" -eq 0 ]; then + echo "SIGNING_ENABLED=true" >> "$GITHUB_ENV" + elif [ "${#missing[@]}" -eq 5 ]; then + echo "SIGNING_ENABLED=false" >> "$GITHUB_ENV" + echo "::warning::署名用の Secrets が未登録のため、アドホック署名の DMG を作ります(開くときに Gatekeeper の警告が出ます)" + else + echo "::error::署名用の Secrets が一部しか登録されていません。不足: ${missing[*]}" + exit 1 + fi - name: Read version from tag env: RELEASE_TAG: ${{ github.ref_name }} @@ -45,15 +69,75 @@ jobs: ARCHS='arm64 x86_64' ONLY_ACTIVE_ARCH=NO MARKETING_VERSION="$APP_VERSION" CURRENT_PROJECT_VERSION="$APP_BUILD" CODE_SIGNING_ALLOWED=NO + - name: Import Developer ID certificate + if: env.SIGNING_ENABLED == 'true' + env: + BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }} + P12_PASSWORD: ${{ secrets.P12_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + run: | + KEYCHAIN_PATH="$RUNNER_TEMP/signing.keychain-db" + KEYCHAIN_PASSWORD="$(uuidgen)" + CERTIFICATE_PATH="$RUNNER_TEMP/certificate.p12" + echo "$BUILD_CERTIFICATE_BASE64" | base64 --decode > "$CERTIFICATE_PATH" + security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" + security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH" + security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" + security import "$CERTIFICATE_PATH" -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH" + security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" > /dev/null + security list-keychains -d user -s "$KEYCHAIN_PATH" + rm -f "$CERTIFICATE_PATH" + # 公証に使うチームと同じチームの証明書だけを使う。 + IDENTITY="$(security find-identity -v -p codesigning "$KEYCHAIN_PATH" | awk -v team="($APPLE_TEAM_ID)" '/Developer ID Application/ && index($0, team) { print $2; exit }')" + if [ -z "$IDENTITY" ]; then + echo "::error::チーム $APPLE_TEAM_ID の Developer ID Application 証明書が見つかりません(.p12 の中身と APPLE_TEAM_ID を確認してください)" + exit 1 + fi + { + echo "KEYCHAIN_PATH=$KEYCHAIN_PATH" + echo "SIGNING_IDENTITY=$IDENTITY" + } >> "$GITHUB_ENV" + - name: Sign app + run: | + APP="$RUNNER_TEMP/ArkServerRelease/Build/Products/Release/ArkServer.app" + if [ "$SIGNING_ENABLED" = "true" ]; then + codesign --force --deep --options runtime --timestamp --keychain "$KEYCHAIN_PATH" --sign "$SIGNING_IDENTITY" "$APP" + codesign --verify --deep --strict --verbose=2 "$APP" + else + codesign --force --deep --sign - "$APP" + fi - name: Package app run: | - codesign --force --deep --sign - "$RUNNER_TEMP/ArkServerRelease/Build/Products/Release/ArkServer.app" DMG_STAGING="$RUNNER_TEMP/ArkServerDMG" rm -rf "$DMG_STAGING" mkdir -p "$DMG_STAGING" ditto "$RUNNER_TEMP/ArkServerRelease/Build/Products/Release/ArkServer.app" "$DMG_STAGING/ArkServer.app" ln -s /Applications "$DMG_STAGING/Applications" hdiutil create -volname "Ark Server" -srcfolder "$DMG_STAGING" -ov -format UDZO ArkServer.dmg + - name: Sign and notarize DMG + if: env.SIGNING_ENABLED == 'true' + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + run: | + codesign --force --timestamp --keychain "$KEYCHAIN_PATH" --sign "$SIGNING_IDENTITY" ArkServer.dmg + RESULT="$RUNNER_TEMP/notarization.json" + xcrun notarytool submit ArkServer.dmg --apple-id "$APPLE_ID" --team-id "$APPLE_TEAM_ID" --password "$APPLE_APP_SPECIFIC_PASSWORD" --wait --timeout 20m --output-format json > "$RESULT" || true + cat "$RESULT" + STATUS="$(jq -r '.status // empty' "$RESULT" 2>/dev/null || true)" + SUBMISSION_ID="$(jq -r '.id // empty' "$RESULT" 2>/dev/null || true)" + # 承認されていなければ、理由(Apple のログ)を表示して止める。 + if [ "$STATUS" != "Accepted" ]; then + echo "::error::公証が承認されませんでした(status: ${STATUS:-不明})" + if [ -n "$SUBMISSION_ID" ]; then + xcrun notarytool log "$SUBMISSION_ID" --apple-id "$APPLE_ID" --team-id "$APPLE_TEAM_ID" --password "$APPLE_APP_SPECIFIC_PASSWORD" || true + fi + exit 1 + fi + xcrun stapler staple ArkServer.dmg + xcrun stapler validate ArkServer.dmg + spctl --assess --type open --context context:primary-signature --verbose=2 ArkServer.dmg || true - name: Publish release env: GH_TOKEN: ${{ github.token }} @@ -64,3 +148,6 @@ jobs: fi gh release upload "$RELEASE_TAG" ArkServer.dmg --clobber gh release edit "$RELEASE_TAG" --draft=false --latest + - name: Remove signing keychain + if: always() && env.SIGNING_ENABLED == 'true' + run: security delete-keychain "$KEYCHAIN_PATH" || true From 503a2d848d7989c3f8d6f9fd22775b82b219713e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 02:58:57 +0900 Subject: [PATCH 2/9] =?UTF-8?q?docs(release):=20=E7=BD=B2=E5=90=8D?= =?UTF-8?q?=E3=81=A8=E5=85=AC=E8=A8=BC=E3=81=AE=E6=89=8B=E9=A0=86=E3=82=92?= =?UTF-8?q?=E8=BF=BD=E8=A8=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- RELEASING.md | 42 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7efca0a..23128b7 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ 配信にはIssue #39の方式A(GitHub Releases API)を採用し、適用は手動で行います。サーバーを停止し、インポート・解析・書き出しが完了してから通常の終了操作を行い、DMGを開いて既存のアプリを差し替え、起動してください。自動終了・再起動・実行中のアプリの置換は行いません。読み取り専用DMGからの起動時も同じ手順で更新できます。ライブラリはアプリ外の既存の保存先を引き続き使用します。 -リリース担当者は `v1.2.3` の形式でタグをpushすると、GitHub Actionsがテスト、arm64/x86_64のReleaseビルド、アドホック署名、DMG添付、リリース公開を実行します。Developer ID署名・公証は含みません。タグのバージョンはアプリの `CFBundleShortVersionString` に反映されます。同一バージョンのビルド更新は `v1.2.3+2` のように正の整数を付けます(省略時のビルド番号は1)。比較はSemVer準拠で、`1.2` と `1.2.0` は同一、数値のビルド指定がある場合のみ同一バージョンのビルド番号も比較します。安定版のみを配信します。 +リリース担当者は `v1.2.3` の形式でタグをpushすると、GitHub Actionsがテスト、arm64/x86_64のReleaseビルド、署名、DMG添付、リリース公開を実行します。署名用のSecretsを登録している場合はDeveloper ID署名と公証を行い、未登録の場合はアドホック署名になります(詳細は [RELEASING.md](RELEASING.md))。タグのバージョンはアプリの `CFBundleShortVersionString` に反映されます。同一バージョンのビルド更新は `v1.2.3+2` のように正の整数を付けます(省略時のビルド番号は1)。比較はSemVer準拠で、`1.2` と `1.2.0` は同一、数値のビルド指定がある場合のみ同一バージョンのビルド番号も比較します。安定版のみを配信します。 ## チャンネル・気分ミックス・時間指定・場面ストック diff --git a/RELEASING.md b/RELEASING.md index e239c96..ec55518 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -39,7 +39,7 @@ タグは現在のコミットを指します。タグを付ける前に、配信したい変更がコミット済みであることを確認してください。 -4. GitHub Actionsの `Release` が成功するまで待ちます。テスト、arm64/x86_64のReleaseビルド、アドホック署名、DMG生成を順に実行します。タグの値がアプリのバージョン・ビルド番号に反映されます。 +4. GitHub Actionsの `Release` が成功するまで待ちます。テスト、arm64/x86_64のReleaseビルド、署名、DMG生成を順に実行します。署名用のSecretsを登録していれば、Developer ID署名とAppleの公証も行います([署名と公証](#署名と公証)を参照)。タグの値がアプリのバージョン・ビルド番号に反映されます。 5. GitHub Releasesで、該当タグのリリースが公開され、`Latest` になっていることと、`ArkServer.dmg` が添付されていることを確認します。リリースノートは自動生成されるので、必要に応じて変更点を追記します。 6. 以前のバージョンのアプリで手動の「アップデートを確認…」を実行し、「アップデート可能」ボタン、バージョン番号、リリースノートを確認します。 @@ -62,4 +62,42 @@ 自動ダウンロード・自動終了・自動再起動・アプリの自動置換は行いません。利用者がサーバーを停止し、インポート・解析・書き出しの完了を確認してから通常の終了操作を行い、DMGを開いて既存のアプリを差し替え、起動します。ライブラリは既存の保存先を引き続き使用します。 -現在の配信物はアドホック署名です。Developer ID署名・Appleによる公証は、現在のワークフローには含まれません。 +## 署名と公証 + +ワークフローは、署名用のSecretsの登録状況で動きを変えます。 + +| 登録状況 | 配信物 | DMGを開いたとき | +| --- | --- | --- | +| 5つすべて登録済み | Developer ID署名+Appleの公証+ステープル | 警告なしで開ける | +| 1つも未登録 | アドホック署名(従来どおり) | Gatekeeperの警告が出る。ワークフローには警告の注釈を出す | +| 一部だけ登録 | ワークフローを失敗させる | 設定ミスのまま署名なしの配信物を公開しないための停止 | + +### 初回の準備(一度だけ) + +有料のApple Developer Programへの加入が必要です。チームIDは `FDKP7YY7G8` です。 + +1. Xcode の Settings > Accounts > Manage Certificates… で、`Developer ID Application` 証明書を作成します。 +2. キーチェーンアクセスで、その証明書(秘密鍵つき)を `.p12` に書き出し、パスワードを設定します。`base64 -i Certificates.p12 | pbcopy` でBase64にします。 +3. [account.apple.com](https://account.apple.com/) の「サインインとセキュリティ」>「App用パスワード」で、このリリース用のパスワードを発行します。 +4. GitHub の `HR0101/ArkServer` > Settings > Secrets and variables > Actions に、次の5つを登録します。 + +| Secret 名 | 値 | +| --- | --- | +| `BUILD_CERTIFICATE_BASE64` | 手順2のBase64文字列 | +| `P12_PASSWORD` | 手順2で設定した `.p12` のパスワード | +| `APPLE_ID` | Apple Developerアカウントのメールアドレス | +| `APPLE_TEAM_ID` | `FDKP7YY7G8` | +| `APPLE_APP_SPECIFIC_PASSWORD` | 手順3のApp用パスワード | + +`.p12` とパスワードはリポジトリに入れず、Secretsだけに置きます。登録後、書き出した `.p12` はMacから削除してください。 + +### 署名ありのときの流れ + +1. 証明書を一時キーチェーンに取り込みます。`APPLE_TEAM_ID` と同じチームの `Developer ID Application` 証明書だけを使います。 +2. アプリにHardened Runtime(`--options runtime`)とタイムスタンプつきで署名し、署名を検証します。 +3. DMGを作り、DMGにも署名します。 +4. `notarytool` で公証を申請し、完了まで待ちます(最長20分)。承認(`Accepted`)以外の場合は、Appleのログを表示してワークフローを失敗させます。 +5. 承認されたら、ステープル(公証の証明書をDMGに埋め込むこと)して検証します。公証に失敗したときは、ここで止まり、リリースは公開されません。 +6. 一時キーチェーンを削除します(失敗したときも実行します)。 + +公証が通らない主な原因は、署名の不備(Hardened Runtimeやタイムスタンプ)と、Developer ID以外の証明書の使用です。ワークフローのログに、Appleが返した理由が出ます。 From 4eeeab63cf322ca5fcffaf9de1c9f5662f5d3133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 11:44:35 +0900 Subject: [PATCH 3/9] =?UTF-8?q?ci:=20=E3=83=86=E3=82=B9=E3=83=88=E3=82=92?= =?UTF-8?q?=E4=B8=A6=E5=88=97=E3=81=AB=E3=81=9B=E3=81=9A=E3=80=81=E5=9B=BA?= =?UTF-8?q?=E3=81=BE=E3=81=A3=E3=81=9F=E5=A0=B4=E5=90=88=E3=81=AF20?= =?UTF-8?q?=E5=88=86=E3=81=A7=E6=AD=A2=E3=82=81=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI の Test macOS app が 30 分で打ち切られていた問題への対処。並列を止めると同時に動くテストは 90 件から 3 件に減る(手元で実測)。 --- .github/workflows/macos-ci.yml | 5 +++++ .github/workflows/release.yml | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/macos-ci.yml b/.github/workflows/macos-ci.yml index 14558f3..d4bb155 100644 --- a/.github/workflows/macos-ci.yml +++ b/.github/workflows/macos-ci.yml @@ -48,11 +48,16 @@ jobs: -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" CODE_SIGNING_ALLOWED=NO + # テストは並列にしない。並列のままだと約 90 件が同時に動き、手元でも再生まわりのテストが不安定になる。 + # CI の仮想環境では固まって 30 分で打ち切られていた(並列を止めると同時に動くのは最大 3 件)。 + # 万一固まっても、ジョブ全体の 30 分を待たずに、このステップを 20 分で止める。 - name: Test macOS app + timeout-minutes: 20 run: >- xcodebuild test -project ArkServer.xcodeproj -scheme ArkServer -destination 'platform=macOS' -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" + -parallel-testing-enabled NO CODE_SIGNING_ALLOWED=NO diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9f5653a..54eaac4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -55,11 +55,16 @@ jobs: with open(os.environ['GITHUB_ENV'], 'a') as output: output.write(f'APP_VERSION={match[1]}\nAPP_BUILD={match[2] or "1"}\n') PY + # テストは並列にしない。並列のままだと約 90 件が同時に動き、手元でも再生まわりのテストが不安定になる。 + # CI の仮想環境では固まって打ち切られていた(並列を止めると同時に動くのは最大 3 件)。 + # 万一固まっても、ジョブ全体の時間切れを待たずに、このステップを 20 分で止める。 - name: Test + timeout-minutes: 20 run: >- xcodebuild test -project ArkServer.xcodeproj -scheme ArkServer -destination 'platform=macOS' -only-testing:ArkServerTests -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" + -parallel-testing-enabled NO CODE_SIGNING_ALLOWED=NO - name: Build universal release run: >- From fb211d8bed2e480b34f13c76f9844ca519b2d77a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 12:15:56 +0900 Subject: [PATCH 4/9] =?UTF-8?q?test:=20=E7=94=BB=E9=9D=A2=E3=81=AE?= =?UTF-8?q?=E3=81=AA=E3=81=84=E4=BB=AE=E6=83=B3=E7=92=B0=E5=A2=83(CI)?= =?UTF-8?q?=E3=81=A7=E5=9B=BA=E3=81=BE=E3=82=8B=E5=85=A8=E7=94=BB=E9=9D=A2?= =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88=E3=82=92=E9=A3=9B=E3=81=B0=E3=81=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 前回の CI の Test macOS app が 20 分で時間切れになった。並列を止めた実行で、最後に始まって終わらなかったのは coversTheWholeScreenWhetherOrNotTheMainWindowIsFullScreen だった(ウィンドウの全画面化が仮想環境で終わらない)。CI(環境変数 CI)と仮想マシン(kern.hv_vmm_present)のときだけ飛ばす。手元では実行する。 --- .github/workflows/macos-ci.yml | 3 +++ .github/workflows/release.yml | 3 +++ .../MusicVideoFullScreenPresenterTests.swift | 2 +- ArkServerTests/MusicVideoTests.swift | 11 +++++++++++ 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/.github/workflows/macos-ci.yml b/.github/workflows/macos-ci.yml index d4bb155..7ac24e9 100644 --- a/.github/workflows/macos-ci.yml +++ b/.github/workflows/macos-ci.yml @@ -53,6 +53,9 @@ jobs: # 万一固まっても、ジョブ全体の 30 分を待たずに、このステップを 20 分で止める。 - name: Test macOS app timeout-minutes: 20 + env: + # テストの実行側へ渡す(TEST_RUNNER_ を外した名前 CI で届く)。画面を使うテストを飛ばす目印。 + TEST_RUNNER_CI: 'true' run: >- xcodebuild test -project ArkServer.xcodeproj diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 54eaac4..a3b4cb9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -60,6 +60,9 @@ jobs: # 万一固まっても、ジョブ全体の時間切れを待たずに、このステップを 20 分で止める。 - name: Test timeout-minutes: 20 + env: + # テストの実行側へ渡す(TEST_RUNNER_ を外した名前 CI で届く)。画面を使うテストを飛ばす目印。 + TEST_RUNNER_CI: 'true' run: >- xcodebuild test -project ArkServer.xcodeproj -scheme ArkServer -destination 'platform=macOS' -only-testing:ArkServerTests diff --git a/ArkServerTests/MusicVideoFullScreenPresenterTests.swift b/ArkServerTests/MusicVideoFullScreenPresenterTests.swift index e3a4ae3..f183005 100644 --- a/ArkServerTests/MusicVideoFullScreenPresenterTests.swift +++ b/ArkServerTests/MusicVideoFullScreenPresenterTests.swift @@ -73,7 +73,7 @@ struct MusicVideoFullScreenPresenterTests { NSApp.sendEvent(event) } - @Test + @Test(.disabled(if: isRunningOnCIOrInVirtualMachine(), "画面のない仮想環境(CI)では、ウィンドウの操作が終わらず固まるため。手元の Mac では実行する")) func coversTheWholeScreenWhetherOrNotTheMainWindowIsFullScreen() async throws { let directory = try temporaryDirectory("fullscreen-presenter") let suite = "musicvideo-fullscreen-tests-\(UUID().uuidString)" diff --git a/ArkServerTests/MusicVideoTests.swift b/ArkServerTests/MusicVideoTests.swift index 591f515..18c1d85 100644 --- a/ArkServerTests/MusicVideoTests.swift +++ b/ArkServerTests/MusicVideoTests.swift @@ -92,6 +92,17 @@ func temporaryDirectory(_ name: String) throws -> URL { return url } +/// CI(GitHub Actions)か、仮想マシンの中かどうか。 +/// 画面のない仮想環境では、ウィンドウの全画面化や前面化といった画面の操作が終わらず、テスト全体が固まることがある。 +/// そのため、実際のウィンドウを使うテストは、この環境では飛ばす(手元の Mac では実行する)。 +/// CI は、環境変数 `CI`(ワークフローで `TEST_RUNNER_CI` として渡す)と、仮想マシンかどうか(`kern.hv_vmm_present`)の両方で見分ける。 +nonisolated func isRunningOnCIOrInVirtualMachine() -> Bool { + if ProcessInfo.processInfo.environment["CI"] != nil { return true } + var value: Int32 = 0 + var size = MemoryLayout.size + return sysctlbyname("kern.hv_vmm_present", &value, &size, nil, 0) == 0 && value == 1 +} + // MARK: - ビート解析 @Suite(.serialized) From 58a5f2a58ffa65d0e1624c1e4bd17bf2c3d3971f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E3=80=80=E9=A2=AF=E7=99=BB?= Date: Fri, 6 Nov 2026 13:20:36 +0900 Subject: [PATCH 5/9] =?UTF-8?q?test:=20=E5=8B=95=E7=94=BB=E3=82=92?= =?UTF-8?q?=E6=9B=B8=E3=81=8D=E8=BE=BC=E3=82=80=E9=83=A8=E5=93=81=E3=81=8C?= =?UTF-8?q?=E5=A4=B1=E6=95=97=E3=81=97=E3=81=A6=E3=82=82=E5=BE=85=E3=81=A1?= =?UTF-8?q?=E7=B6=9A=E3=81=91=E3=81=AA=E3=81=84=E3=82=88=E3=81=86=E3=81=AB?= =?UTF-8?q?=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI の Test macOS app が、exportedFramesMatchThePlannedSourcePositions で止まって 20 分で時間切れになっていた。動画を作る部品(makeTestVideo など)が、書き込みの失敗を見ずに isReadyForMoreMediaData を待ち続けていたため、失敗を検出して理由つきで失敗させる。動画を作る 3 つの型には、1 件 3 分の時間制限を付けた。 --- ArkServerTests/MusicVideoTests.swift | 46 ++++++++++++++++++++--- ArkServerTests/SceneExtractionTests.swift | 14 ++++++- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/ArkServerTests/MusicVideoTests.swift b/ArkServerTests/MusicVideoTests.swift index 18c1d85..5ea60a1 100644 --- a/ArkServerTests/MusicVideoTests.swift +++ b/ArkServerTests/MusicVideoTests.swift @@ -67,8 +67,18 @@ func makeTestVideo( writer.startSession(atSourceTime: .zero) for frameIndex in 0.. deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frameIndex, status: writer.status.rawValue) + } try await Task.sleep(for: .milliseconds(2)) } var pixelBuffer: CVPixelBuffer? @@ -79,13 +89,23 @@ func makeTestVideo( memset(baseAddress, Int32(brightness(frameIndex)), CVPixelBufferGetDataSize(pixelBuffer)) } CVPixelBufferUnlockBaseAddress(pixelBuffer, []) - #expect(adaptor.append(pixelBuffer, withPresentationTime: CMTime(value: CMTimeValue(frameIndex), timescale: framesPerSecond))) + // 追加できなかったとき(エンコーダーの失敗など)は、続けても受け付け可能にならないので、そこで失敗させる。 + guard adaptor.append(pixelBuffer, withPresentationTime: CMTime(value: CMTimeValue(frameIndex), timescale: framesPerSecond)) else { + throw writer.error ?? CocoaError(.fileWriteUnknown) + } } input.markAsFinished() await writer.finishWriting() #expect(writer.status == .completed) } +/// 動画の書き込みが、進まないまま長く待たされたことを表す。 +nonisolated struct TestVideoWriteStalled: Error, CustomStringConvertible { + let frame: Int + let status: Int + var description: String { "動画の書き込みが 60 秒進まなかった(フレーム \(frame)、書き込みの状態 \(status))" } +} + func temporaryDirectory(_ name: String) throws -> URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)") try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) @@ -623,7 +643,7 @@ func step(_ label: String, _ body: () async throws -> T) async throws -> T { } } -@Suite(.serialized) +@Suite(.serialized, .timeLimit(.minutes(3))) struct MusicVideoComposerTests { private func cut(_ video: UUID, from sourceStart: Double, at start: Double, length: Double) -> PlannedCut { PlannedCut(videoID: video, sourceStart: sourceStart, duration: length, timelineStart: start, intensity: .medium) @@ -739,7 +759,7 @@ func writeMonoWAV(samples: [Float], sampleRate: Double, to url: URL) throws { try file.write(from: buffer) } -@Suite(.serialized) +@Suite(.serialized, .timeLimit(.minutes(3))) struct MusicVideoPipelineTests { /// 曲の解析 → 素材の解析 → カット割り → 合成 → 書き出し を通しで動かし、 /// 完成映像の各カットが、計画した素材の「その時刻」の絵になっていることを確かめる。 @@ -1156,7 +1176,19 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h #expect(writer.startWriting()) writer.startSession(atSourceTime: .zero) for frame in 0.. deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frame, status: writer.status.rawValue) + } + try await Task.sleep(for: .milliseconds(2)) + } var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, nil, &pixelBuffer) guard let pixelBuffer else { throw CocoaError(.fileWriteUnknown) } @@ -1171,14 +1203,16 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h } } CVPixelBufferUnlockBaseAddress(pixelBuffer, []) - adaptor.append(pixelBuffer, withPresentationTime: CMTime(value: CMTimeValue(frame), timescale: framesPerSecond)) + guard adaptor.append(pixelBuffer, withPresentationTime: CMTime(value: CMTimeValue(frame), timescale: framesPerSecond)) else { + throw writer.error ?? CocoaError(.fileWriteUnknown) + } } input.markAsFinished() await writer.finishWriting() #expect(writer.status == .completed) } -@Suite(.serialized) +@Suite(.serialized, .timeLimit(.minutes(3))) struct MusicVideoExportQualityTests { @Test func bitrateScalesWithQualityAndScreenSize() { diff --git a/ArkServerTests/SceneExtractionTests.swift b/ArkServerTests/SceneExtractionTests.swift index 04f85b1..99afdc3 100644 --- a/ArkServerTests/SceneExtractionTests.swift +++ b/ArkServerTests/SceneExtractionTests.swift @@ -755,8 +755,17 @@ struct SceneExtractionTests { writer.startSession(atSourceTime: .zero) for frameIndex in 0.. deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frameIndex, status: writer.status.rawValue) + } try await Task.sleep(for: .milliseconds(2)) } var pixelBuffer: CVPixelBuffer? @@ -787,7 +796,10 @@ struct SceneExtractionTests { } CVPixelBufferUnlockBaseAddress(pixelBuffer, []) let presentationTime = CMTime(value: CMTimeValue(frameIndex), timescale: framesPerSecond) - #expect(adaptor.append(pixelBuffer, withPresentationTime: presentationTime)) + // 追加できなかったとき(エンコーダーの失敗など)は、続けても受け付け可能にならないので、そこで失敗させる。 + guard adaptor.append(pixelBuffer, withPresentationTime: presentationTime) else { + throw writer.error ?? CocoaError(.fileWriteUnknown) + } } input.markAsFinished() From e9757dfb138223fad9b32934a31d7e3fc4e58cf5 Mon Sep 17 00:00:00 2001 From: HR0101 Date: Mon, 16 Nov 2026 15:24:11 +0900 Subject: [PATCH 6/9] =?UTF-8?q?fix:=20AVFoundation=E8=AA=AD=E3=81=BF?= =?UTF-8?q?=E6=9B=B8=E3=81=8D=E3=81=AETask=E5=8F=96=E6=B6=88=E5=AF=BE?= =?UTF-8?q?=E5=BF=9C=E3=81=A8VM=E7=92=B0=E5=A2=83=E3=81=A7=E3=81=AE?= =?UTF-8?q?=E5=90=8C=E6=99=82=E5=BE=A9=E5=8F=B7=E6=95=B0=E8=AA=BF=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Common/Utilities/AsyncAVFoundation.swift | 283 ++++++++++++++ .../MusicVideo/Services/BeatAnalyzer.swift | 53 +-- .../MusicVideo/Services/ClipPoolBuilder.swift | 11 +- .../Services/MusicVideoComposer.swift | 357 ++++++++++++++---- .../Services/SourceAudioSeparator.swift | 48 +-- .../Services/VisualAnalyzer.swift | 91 ++--- ArkServerTests/MusicVideoTests.swift | 154 ++++---- ArkServerTests/MusicVideoTuningTests.swift | 4 +- ArkServerTests/SceneExtractionTests.swift | 21 +- 9 files changed, 773 insertions(+), 249 deletions(-) create mode 100644 ArkServer/Common/Utilities/AsyncAVFoundation.swift diff --git a/ArkServer/Common/Utilities/AsyncAVFoundation.swift b/ArkServer/Common/Utilities/AsyncAVFoundation.swift new file mode 100644 index 0000000..992edd9 --- /dev/null +++ b/ArkServer/Common/Utilities/AsyncAVFoundation.swift @@ -0,0 +1,283 @@ +// ArkServer/Common/Utilities/AsyncAVFoundation.swift + +import AVFoundation +import Foundation + +/// スレッドをまたいで所有権を移す非 Sendable 値を包む補助。 +/// 生成元のスレッドで設定を終えたあと、受け取り側だけが使う値に使う。 +nonisolated struct UncheckedSendableBox: @unchecked Sendable { + let value: Value + + init(_ value: Value) { + self.value = value + } +} + +/// AVFoundation の同期的な読み出しや書き出しを、Task 取消とスレッド安全を保ったまま非同期で扱うための補助。 +nonisolated enum AsyncAVFoundation { + /// macOS の仮想マシン(`kern.hv_vmm_present == 1`)上で動作しているかどうか。 + static var isVirtualMachine: Bool { + var value: Int32 = 0 + var size = MemoryLayout.size + return sysctlbyname("kern.hv_vmm_present", &value, &size, nil, 0) == 0 && value == 1 + } + + /// `AVAssetReader` の開始と読み出しを専用の `DispatchQueue` 上で実行する。 + /// Swift の協調スレッドプールを塞がず、Task 取消時にも呼び出し元が即座に戻れるようにする。 + /// + /// `startReading()` の実行中に `cancelReading()` を呼ぶと AVFoundation の内部で落ちるため、 + /// 開始中の取消は `startReading()` が戻ってから実行する。 + static func runReader( + _ reader: AVAssetReader, + queueLabel: String, + startError: @escaping @Sendable (String) -> any Error, + readError: @escaping @Sendable (String) -> any Error, + body: @escaping @Sendable (_ isCancelled: @escaping @Sendable () -> Bool) throws -> Output + ) async throws -> Output { + try Task.checkCancellation() + let session = ReaderSession(reader: reader) + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + guard session.arm(continuation: continuation) else { + continuation.resume(throwing: CancellationError()) + return + } + DispatchQueue(label: queueLabel, qos: .userInitiated).async { + session.execute(startError: startError, readError: readError, body: body) + } + } + } onCancel: { + session.cancel() + } + } + + /// `AVAssetWriter.finishWriting` を Task 取消に対応させて待つ。 + static func finishWriting(_ writer: AVAssetWriter) async throws { + if Task.isCancelled { + if writer.status == .writing { writer.cancelWriting() } + throw CancellationError() + } + let session = FinishWritingSession(writer: writer) + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + session.start(with: continuation) + } + } onCancel: { + session.cancel() + } + } +} + +private enum ReaderStartOutcome { case cancelled, failed, ready } + +private nonisolated final class ReaderSession: @unchecked Sendable { + private enum Phase { + case idle + case starting + case running + case finished + } + + private let lock = NSLock() + private let reader: AVAssetReader + private var phase: Phase = .idle + private var isCancelled = false + private var didCancelReader = false + private var continuation: CheckedContinuation? + + init(reader: AVAssetReader) { + self.reader = reader + } + + func arm(continuation: CheckedContinuation) -> Bool { + lock.withLock { + guard !isCancelled else { return false } + self.continuation = continuation + return true + } + } + + func cancel() { + let (cont, shouldCancelReader) = lock.withLock { () -> (CheckedContinuation?, Bool) in + isCancelled = true + let cont = continuation + continuation = nil + // startReading() の途中で cancelReading() を呼ぶと内部で落ちるため、running 中だけ即時中止する。 + let canCancelNow = (phase == .running && !didCancelReader) + if canCancelNow { didCancelReader = true } + return (cont, canCancelNow) + } + if shouldCancelReader { + reader.cancelReading() + } + cont?.resume(throwing: CancellationError()) + } + + func execute( + startError: (String) -> any Error, + readError: (String) -> any Error, + body: (_ isCancelled: @escaping @Sendable () -> Bool) throws -> Output + ) { + let canStart = lock.withLock { () -> Bool in + guard !isCancelled else { + phase = .finished + return false + } + phase = .starting + return true + } + guard canStart else { + resume(throwing: CancellationError()) + return + } + + let started = reader.startReading() + + let outcome = lock.withLock { () -> (ReaderStartOutcome, Bool) in + if isCancelled { + phase = .finished + if started, !didCancelReader { + didCancelReader = true + return (.cancelled, true) + } + return (.cancelled, false) + } + guard started else { + phase = .finished + return (.failed, false) + } + phase = .running + return (.ready, false) + } + + if outcome.1 { + reader.cancelReading() + } + switch outcome.0 { + case .cancelled: + resume(throwing: CancellationError()) + return + case .failed: + resume(throwing: startError(reader.error?.localizedDescription ?? "開始できませんでした.")) + return + case .ready: + break + } + + let cancelledCheck: @Sendable () -> Bool = { [self] in + lock.withLock { isCancelled } + } + + let result: Result + do { + let value = try body(cancelledCheck) + if cancelledCheck() { + result = .failure(CancellationError()) + } else if reader.status == .failed { + result = .failure(readError(reader.error?.localizedDescription ?? "原因不明です.")) + } else { + result = .success(value) + } + } catch { + result = .failure(cancelledCheck() ? CancellationError() : error) + } + + let shouldCancelReader = lock.withLock { () -> Bool in + phase = .finished + guard !didCancelReader else { return false } + let reading = (reader.status == .reading) + if reading { didCancelReader = true } + return reading + } + if shouldCancelReader { + reader.cancelReading() + } + + switch result { + case .success(let value): + resume(returning: value) + case .failure(let error): + resume(throwing: error) + } + } + + private func resume(returning value: Output) { + let cont = lock.withLock { () -> CheckedContinuation? in + defer { continuation = nil } + return continuation + } + cont?.resume(returning: value) + } + + private func resume(throwing error: any Error) { + let cont = lock.withLock { () -> CheckedContinuation? in + defer { continuation = nil } + return continuation + } + cont?.resume(throwing: error) + } +} + +private nonisolated final class FinishWritingSession: @unchecked Sendable { + private let lock = NSLock() + private let writer: AVAssetWriter + private var isCancelled = false + private var isFinished = false + private var didCancelWriter = false + private var continuation: CheckedContinuation? + + init(writer: AVAssetWriter) { + self.writer = writer + } + + func start(with continuation: CheckedContinuation) { + let (shouldStart, shouldCancelWriter) = lock.withLock { () -> (Bool, Bool) in + guard !isCancelled else { + let canCancel = (!didCancelWriter && writer.status == .writing) + if canCancel { didCancelWriter = true } + return (false, canCancel) + } + self.continuation = continuation + return (true, false) + } + if shouldCancelWriter { + writer.cancelWriting() + } + guard shouldStart else { + continuation.resume(throwing: CancellationError()) + return + } + writer.finishWriting { [self] in + complete() + } + } + + func complete() { + let (cont, cancelled) = lock.withLock { () -> (CheckedContinuation?, Bool) in + isFinished = true + let cont = continuation + continuation = nil + return (cont, isCancelled) + } + if cancelled { + cont?.resume(throwing: CancellationError()) + } else { + cont?.resume(returning: ()) + } + } + + func cancel() { + let (cont, shouldCancelWriter) = lock.withLock { () -> (CheckedContinuation?, Bool) in + isCancelled = true + let cont = continuation + continuation = nil + let canCancel = (!isFinished && !didCancelWriter && writer.status == .writing) + if canCancel { didCancelWriter = true } + return (cont, canCancel) + } + if shouldCancelWriter { + writer.cancelWriting() + } + cont?.resume(throwing: CancellationError()) + } +} diff --git a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift index b25912a..10019cb 100644 --- a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift +++ b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift @@ -76,34 +76,35 @@ nonisolated struct BeatAnalyzer: Sendable { output.alwaysCopiesSampleData = false guard reader.canAdd(output) else { throw BeatAnalyzerError.cannotAddOutput } reader.add(output) - guard reader.startReading() else { - throw BeatAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "開始できませんでした.") - } - - var samples: [Float] = [] - while let sampleBuffer = output.copyNextSampleBuffer() { - try Task.checkCancellation() - guard let dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { continue } - let byteCount = CMBlockBufferGetDataLength(dataBuffer) - guard byteCount > 0, byteCount.isMultiple(of: MemoryLayout.size) else { continue } - var chunk = [Float](repeating: 0, count: byteCount / MemoryLayout.size) - let status = chunk.withUnsafeMutableBytes { destination in - CMBlockBufferCopyDataBytes( - dataBuffer, - atOffset: 0, - dataLength: byteCount, - destination: destination.baseAddress! - ) - } - guard status == kCMBlockBufferNoErr else { - throw BeatAnalyzerError.readerFailed("PCMバッファをコピーできませんでした.") + let outputBox = UncheckedSendableBox(output) + return try await AsyncAVFoundation.runReader( + reader, + queueLabel: "arkserver.beat-analyzer", + startError: { BeatAnalyzerError.readerFailed($0) }, + readError: { BeatAnalyzerError.readerFailed($0) } + ) { isCancelled in + var samples: [Float] = [] + while let sampleBuffer = outputBox.value.copyNextSampleBuffer() { + if isCancelled() { throw CancellationError() } + guard let dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { continue } + let byteCount = CMBlockBufferGetDataLength(dataBuffer) + guard byteCount > 0, byteCount.isMultiple(of: MemoryLayout.size) else { continue } + var chunk = [Float](repeating: 0, count: byteCount / MemoryLayout.size) + let status = chunk.withUnsafeMutableBytes { destination in + CMBlockBufferCopyDataBytes( + dataBuffer, + atOffset: 0, + dataLength: byteCount, + destination: destination.baseAddress! + ) + } + guard status == kCMBlockBufferNoErr else { + throw BeatAnalyzerError.readerFailed("PCMバッファをコピーできませんでした.") + } + samples.append(contentsOf: chunk) } - samples.append(contentsOf: chunk) - } - if reader.status == .failed { - throw BeatAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "原因不明です.") + return samples } - return samples } // MARK: - 解析本体(ファイル非依存。単体テストはここを直接呼ぶ) diff --git a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift index 3ac3b8c..6bf3e27 100644 --- a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift +++ b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift @@ -44,7 +44,8 @@ nonisolated struct ClipPoolBuilder: Sendable { /// 動画の読み込み(復号)は、標本数に関わらず全フレームぶん行うので、細かくしても重さはあまり増えない。 var analysisFramesPerSecond = 12.0 /// 同時に解析する動画の数。 - var maxConcurrentAnalyses = 3 + /// 仮想環境では複数のハードウェア復号を同時に走らせると詰まることがあるため 1 に抑える。 + var maxConcurrentAnalyses = AsyncAVFoundation.isVirtualMachine ? 1 : 3 /// 解析する動画の最大本数。これを超えたらシードで無作為に選ぶ。 var maxVideos = 40 /// キャッシュの保存先。nil ならキャッシュしない。 @@ -72,7 +73,13 @@ nonisolated struct ClipPoolBuilder: Sendable { let source = selected[index] nextIndex += 1 group.addTask { - (index, try? await self.motionWindows(for: source)) + do { + return (index, try await self.motionWindows(for: source)) + } catch is CancellationError { + throw CancellationError() + } catch { + return (index, nil) + } } } for _ in 0.. AVPlayerItem { let item = AVPlayerItem(asset: composition) item.videoComposition = videoComposition @@ -760,12 +761,21 @@ nonisolated struct MusicVideoComposer: Sendable { private let audioOutput: AVAssetReaderAudioMixOutput? private let audioInput: AVAssetWriterInput? private let duration: Double - /// 読み出しの開始(startReading)中に中止(cancelReading)を呼ぶと AVFoundation の内部で落ちるので、 - /// 開始中の取り消しは、開始が終わってから実行する。 - private enum Phase { case idle, starting, running } + private enum Phase { + case idle + case startingReader + case startingWriter + case running + case finishing + case finished + } private let lock = NSLock() private var isCancelled = false + private var didAbort = false + private var didCancelReader = false + private var didCancelWriter = false private var phase: Phase = .idle + private var activeContinuations: [UUID: CheckedContinuation] = [:] init(composed: MusicVideoComposition, outputURL: URL, quality: MusicVideoExportQuality) throws { let render = composed.render @@ -850,105 +860,316 @@ nonisolated struct MusicVideoComposer: Sendable { } func cancel() { - lock.lock() - isCancelled = true - let shouldCancelNow = phase == .running - lock.unlock() - // 読み出しを止めると、流し込みの側は終わりまで読んだものとして自然に閉じる。 - // まだ始まっていない/開始中なら、run() が開始後に止める。 - if shouldCancelNow { reader.cancelReading() } + let (shouldCancelReader, shouldCancelWriter, continuations) = lock.withLock { + () -> (Bool, Bool, [CheckedContinuation]) in + isCancelled = true + // startReading() の途中で cancelReading() を呼ぶと AVFoundation の内部で落ちるため、 + // startingReader 中は止めず、開始が終わってから executeStartPipeline() で止める。 + let canCancelReader = !didCancelReader && (phase == .startingWriter || phase == .running) + if canCancelReader { didCancelReader = true } + let canCancelWriter = !didCancelWriter && phase == .running + if canCancelWriter { didCancelWriter = true } + let pending = Array(activeContinuations.values) + activeContinuations.removeAll() + return (canCancelReader, canCancelWriter, pending) + } + if shouldCancelReader { reader.cancelReading() } + if shouldCancelWriter { writer.cancelWriting() } + for continuation in continuations { + continuation.resume(throwing: CancellationError()) + } + } + + private var shouldStopPumping: Bool { + lock.withLock { isCancelled || didAbort } } private var wasCancelled: Bool { - lock.lock(); defer { lock.unlock() } - return isCancelled + lock.withLock { isCancelled } } func run(progress: @escaping @Sendable (Double) async -> Void) async throws { - lock.lock() - if isCancelled { lock.unlock(); throw CancellationError() } - phase = .starting - lock.unlock() - - let started = reader.startReading() - - lock.lock() - phase = .running - let cancelledWhileStarting = isCancelled - lock.unlock() - if cancelledWhileStarting { - reader.cancelReading() - throw CancellationError() - } - guard started else { - throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しを開始できませんでした.") - } - guard writer.startWriting() else { - reader.cancelReading() - throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みを開始できませんでした.") - } - writer.startSession(atSourceTime: .zero) + try await startPipeline() - async let videoDone: Void = pump(videoInput, from: videoOutput, progress: progress) - async let audioDone: Void = { - if let audioInput, let audioOutput { await pump(audioInput, from: audioOutput, progress: nil) } - }() - _ = await (videoDone, audioDone) + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + try await self.pump(self.videoInput, from: self.videoOutput, progress: progress) + } + if let audioInput, let audioOutput { + group.addTask { + try await self.pump(audioInput, from: audioOutput, progress: nil) + } + } + try await group.waitForAll() + } if wasCancelled { - writer.cancelWriting() + cancelReaderOnce() + cancelWriterOnce() + markFinished() throw CancellationError() } - if reader.status == .failed { - writer.cancelWriting() + if reader.status == .failed && writer.status != .failed { + cancelWriterOnce() + markFinished() throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しに失敗しました.") } - await writer.finishWriting() + if writer.status == .failed { + cancelReaderOnce() + markFinished() + throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みに失敗しました.") + } + guard enterFinishing() else { + cancelWriterOnce() + markFinished() + throw CancellationError() + } + do { + try await AsyncAVFoundation.finishWriting(writer) + } catch { + markFinished() + throw error + } + markFinished() + if wasCancelled { + throw CancellationError() + } guard writer.status == .completed else { throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みに失敗しました.") } } + private func startPipeline() async throws { + try Task.checkCancellation() + let id = UUID() + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let armed = lock.withLock { () -> Bool in + guard !isCancelled else { return false } + phase = .startingReader + activeContinuations[id] = continuation + return true + } + guard armed else { + continuation.resume(throwing: CancellationError()) + return + } + DispatchQueue(label: "musicvideo.export.start", qos: .userInitiated).async { + self.executeStartPipeline(id: id) + } + } + } + + private func executeStartPipeline(id: UUID) { + let readerStarted = reader.startReading() + let afterReader = lock.withLock { () -> (cancelled: Bool, failed: Bool) in + if isCancelled { + phase = .finished + return (true, false) + } + guard readerStarted else { + phase = .finished + return (false, true) + } + phase = .startingWriter + return (false, false) + } + if afterReader.cancelled { + if readerStarted { cancelReaderOnce() } + resumeContinuation(id: id, error: CancellationError()) + return + } + if afterReader.failed { + let reason = reader.error?.localizedDescription ?? "読み出しを開始できませんでした." + resumeContinuation(id: id, error: MusicVideoComposerError.exportFailed(reason)) + return + } + + let writerStarted = writer.startWriting() + let abortedBeforeSession = lock.withLock { () -> (cancelled: Bool, failed: Bool) in + if isCancelled { + phase = .finished + return (true, false) + } + guard writerStarted else { + phase = .finished + return (false, true) + } + return (false, false) + } + if abortedBeforeSession.cancelled { + cancelReaderOnce() + if writerStarted { cancelWriterOnce() } + resumeContinuation(id: id, error: CancellationError()) + return + } + if abortedBeforeSession.failed { + cancelReaderOnce() + let reason = writer.error?.localizedDescription ?? "書き込みを開始できませんでした." + resumeContinuation(id: id, error: MusicVideoComposerError.exportFailed(reason)) + return + } + + writer.startSession(atSourceTime: .zero) + + let cancelledDuringSession = lock.withLock { () -> Bool in + if isCancelled { + phase = .finished + return true + } + phase = .running + return false + } + if cancelledDuringSession { + cancelReaderOnce() + cancelWriterOnce() + resumeContinuation(id: id, error: CancellationError()) + return + } + resumeContinuation(id: id, error: nil) + } + + private func resumeContinuation(id: UUID, error: (any Error)?) { + let continuation = lock.withLock { activeContinuations.removeValue(forKey: id) } + if let error { + continuation?.resume(throwing: error) + } else { + continuation?.resume(returning: ()) + } + } + + private func registerPumpContinuation(_ continuation: CheckedContinuation, id: UUID) -> Bool { + lock.withLock { + guard !isCancelled, !didAbort else { return false } + activeContinuations[id] = continuation + return true + } + } + + private func finishPump(id: UUID) { + let continuation = lock.withLock { activeContinuations.removeValue(forKey: id) } + continuation?.resume(returning: ()) + } + + private func abortOnPumpFailure() { + let (shouldCancelReader, continuations) = lock.withLock { + () -> (Bool, [CheckedContinuation]) in + didAbort = true + let canCancelReader = !didCancelReader && phase == .running + if canCancelReader { didCancelReader = true } + let pending = Array(activeContinuations.values) + activeContinuations.removeAll() + return (canCancelReader, pending) + } + if shouldCancelReader { reader.cancelReading() } + for continuation in continuations { + continuation.resume(returning: ()) + } + } + + private func cancelReaderOnce() { + let shouldCancel = lock.withLock { () -> Bool in + guard !didCancelReader else { return false } + didCancelReader = true + return true + } + if shouldCancel { reader.cancelReading() } + } + + private func cancelWriterOnce() { + let shouldCancel = lock.withLock { () -> Bool in + guard !didCancelWriter else { return false } + didCancelWriter = true + return true + } + if shouldCancel { writer.cancelWriting() } + } + + private func enterFinishing() -> Bool { + lock.withLock { + guard !isCancelled else { return false } + phase = .finishing + return true + } + } + + private func markFinished() { + lock.withLock { + phase = .finished + } + } + /// 読み出し側から取り出したサンプルを、書き込み側が受け取れるたびに渡す。 private func pump( _ input: AVAssetWriterInput, from output: AVAssetReaderOutput, progress: (@Sendable (Double) async -> Void)? - ) async { + ) async throws { + final class PumpState: @unchecked Sendable { + var lastReported = -1.0 + var isFinished = false + } + + let id = UUID() let queue = DispatchQueue(label: "musicvideo.export.\(input.mediaType.rawValue)") let total = max(duration, 0.001) + let readerBox = UncheckedSendableBox(self.reader) + let writerBox = UncheckedSendableBox(self.writer) + let inputBox = UncheckedSendableBox(input) + let outputBox = UncheckedSendableBox(output) + let state = PumpState() + // 書き出し側は、閉じた後も「受け取れます」と呼び出し直してくることがある。 - // そのとき、解放済みの読み出し側に触らないよう、(1)終わったら何もしない (2)呼び出しが続く間は reader を保持する。 - let reader = self.reader - await withCheckedContinuation { (continuation: CheckedContinuation) in - var lastReported = -1.0 - var isFinished = false - input.requestMediaDataWhenReady(on: queue) { - withExtendedLifetime(reader) { - guard !isFinished else { return } - while input.isReadyForMoreMediaData { - guard let buffer = output.copyNextSampleBuffer() else { - isFinished = true - input.markAsFinished() - continuation.resume() - return + // そのとき、解放済みの読み出し側に触らないよう、(1)終わったら何もしない (2)呼び出しが続く間は reader/writer を保持する。 + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard registerPumpContinuation(continuation, id: id) else { + continuation.resume(throwing: wasCancelled ? CancellationError() : MusicVideoComposerError.exportFailed("書き込みが中断されました.")) + return + } + inputBox.value.requestMediaDataWhenReady(on: queue) { [weak self, readerBox, writerBox] in + withExtendedLifetime((readerBox.value, writerBox.value)) { + func markFinishedIfWriting() { + state.isFinished = true + if writerBox.value.status == .writing { + inputBox.value.markAsFinished() + } } - if !input.append(buffer) { - isFinished = true - input.markAsFinished() - continuation.resume() + + guard !state.isFinished else { return } + guard let self, !self.shouldStopPumping else { + markFinishedIfWriting() + self?.finishPump(id: id) return } - if let progress { - let fraction = min(1, max(0, CMSampleBufferGetPresentationTimeStamp(buffer).seconds / total)) - if fraction - lastReported >= 0.01 { - lastReported = fraction - Task { await progress(fraction) } + while inputBox.value.isReadyForMoreMediaData { + if self.shouldStopPumping { + markFinishedIfWriting() + self.finishPump(id: id) + return + } + guard let buffer = outputBox.value.copyNextSampleBuffer() else { + markFinishedIfWriting() + self.finishPump(id: id) + return + } + if !inputBox.value.append(buffer) { + markFinishedIfWriting() + self.abortOnPumpFailure() + return + } + if let progress { + let fraction = min(1, max(0, CMSampleBufferGetPresentationTimeStamp(buffer).seconds / total)) + if fraction - state.lastReported >= 0.01 { + state.lastReported = fraction + Task { await progress(fraction) } + } } } } } } + } onCancel: { + self.cancel() } } } diff --git a/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift b/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift index 8f88117..e9805a5 100644 --- a/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift +++ b/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift @@ -153,32 +153,36 @@ nonisolated struct SourceAudioSeparator: Sendable { start: CMTime(seconds: start, preferredTimescale: 600), duration: CMTime(seconds: duration, preferredTimescale: 600) ) - guard reader.startReading() else { - throw SourceAudioSeparatorError.cannotRead(reader.error?.localizedDescription ?? "読み出しを始められません.") - } - guard let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: Self.sampleRate, channels: 2, interleaved: false) else { throw SourceAudioSeparatorError.cannotRead("音声の形式を作れません.") } - var left: [Float] = [] - var right: [Float] = [] - var firstTime: Double? - while let sampleBuffer = output.copyNextSampleBuffer() { - try Task.checkCancellation() - let frames = CMSampleBufferGetNumSamples(sampleBuffer) - guard frames > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)) else { continue } - buffer.frameLength = AVAudioFrameCount(frames) - let status = CMSampleBufferCopyPCMDataIntoAudioBufferList( - sampleBuffer, at: 0, frameCount: Int32(frames), into: buffer.mutableAudioBufferList - ) - guard status == noErr, let channels = buffer.floatChannelData else { continue } - if firstTime == nil { firstTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds } - left.append(contentsOf: UnsafeBufferPointer(start: channels[0], count: frames)) - right.append(contentsOf: UnsafeBufferPointer(start: channels[1], count: frames)) - } - if reader.status == .failed { - throw SourceAudioSeparatorError.cannotRead(reader.error?.localizedDescription ?? "読み出しに失敗しました.") + let outputBox = UncheckedSendableBox(output) + let formatBox = UncheckedSendableBox(format) + let (left, right, firstTime) = try await AsyncAVFoundation.runReader( + reader, + queueLabel: "arkserver.audio-separator", + startError: { SourceAudioSeparatorError.cannotRead($0) }, + readError: { SourceAudioSeparatorError.cannotRead($0) } + ) { isCancelled in + var left: [Float] = [] + var right: [Float] = [] + var firstTime: Double? + while let sampleBuffer = outputBox.value.copyNextSampleBuffer() { + if isCancelled() { throw CancellationError() } + let frames = CMSampleBufferGetNumSamples(sampleBuffer) + guard frames > 0, let buffer = AVAudioPCMBuffer(pcmFormat: formatBox.value, frameCapacity: AVAudioFrameCount(frames)) else { continue } + buffer.frameLength = AVAudioFrameCount(frames) + let status = CMSampleBufferCopyPCMDataIntoAudioBufferList( + sampleBuffer, at: 0, frameCount: Int32(frames), into: buffer.mutableAudioBufferList + ) + guard status == noErr, let channels = buffer.floatChannelData else { continue } + if firstTime == nil { firstTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds } + left.append(contentsOf: UnsafeBufferPointer(start: channels[0], count: frames)) + right.append(contentsOf: UnsafeBufferPointer(start: channels[1], count: frames)) + } + return (left, right, firstTime) } + try Task.checkCancellation() guard !left.isEmpty else { throw SourceAudioSeparatorError.cannotRead("指定の範囲に音がありません.") } return ReadAudio(audio: AudioSignal(sampleRate: Self.sampleRate, channels: [left, right]), startTime: firstTime ?? start) } diff --git a/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift b/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift index 1c139a7..6e7b162 100644 --- a/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift +++ b/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift @@ -69,54 +69,57 @@ nonisolated struct VisualAnalyzer: Sendable { ) } - guard reader.startReading() else { - throw VisualAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "開始できませんでした.") - } - let sampleInterval = 1 / max(1, settings.analysisFramesPerSecond) - var nextSampleTime = 0.0 - var previousLuminance: [Float]? - var previousEdges: [Float]? - var previousFrameDiff = 0.0 - var rawPoints: [RawVisualPoint] = [] - - while let sampleBuffer = output.copyNextSampleBuffer() { - try Task.checkCancellation() - let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds - guard presentationTime.isFinite, presentationTime + 0.000_001 >= nextSampleTime else { - continue - } - nextSampleTime = presentationTime + sampleInterval - - guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { - continue - } - let frame = try makeLuminanceFrame(from: pixelBuffer) - let edges = makeEdges(from: frame.values, width: frame.width, height: frame.height) - let luminanceDiff = meanAbsoluteDifference(frame.values, previousLuminance) - let edgeDiff = meanAbsoluteDifference(edges, previousEdges) - let frameDiff = luminanceWeight * luminanceDiff + edgeWeight * edgeDiff - let motionDelta = frameDiff - previousFrameDiff - - rawPoints.append( - RawVisualPoint( - time: max(0, presentationTime), - frameDiff: frameDiff, - meanLuminance: frame.meanLuminance, - luminanceDiff: luminanceDiff, - edgeDiff: edgeDiff, - motionSpike: max(0, motionDelta), - motionDrop: max(0, -motionDelta) + let outputBox = UncheckedSendableBox(output) + let rawPoints = try await AsyncAVFoundation.runReader( + reader, + queueLabel: "arkserver.visual-analyzer", + startError: { VisualAnalyzerError.readerFailed($0) }, + readError: { VisualAnalyzerError.readerFailed($0) } + ) { isCancelled in + var nextSampleTime = 0.0 + var previousLuminance: [Float]? + var previousEdges: [Float]? + var previousFrameDiff = 0.0 + var rawPoints: [RawVisualPoint] = [] + + while let sampleBuffer = outputBox.value.copyNextSampleBuffer() { + if isCancelled() { throw CancellationError() } + let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds + guard presentationTime.isFinite, presentationTime + 0.000_001 >= nextSampleTime else { + continue + } + nextSampleTime = presentationTime + sampleInterval + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue + } + let frame = try makeLuminanceFrame(from: pixelBuffer) + let edges = makeEdges(from: frame.values, width: frame.width, height: frame.height) + let luminanceDiff = meanAbsoluteDifference(frame.values, previousLuminance) + let edgeDiff = meanAbsoluteDifference(edges, previousEdges) + let frameDiff = luminanceWeight * luminanceDiff + edgeWeight * edgeDiff + let motionDelta = frameDiff - previousFrameDiff + + rawPoints.append( + RawVisualPoint( + time: max(0, presentationTime), + frameDiff: frameDiff, + meanLuminance: frame.meanLuminance, + luminanceDiff: luminanceDiff, + edgeDiff: edgeDiff, + motionSpike: max(0, motionDelta), + motionDrop: max(0, -motionDelta) + ) ) - ) - previousLuminance = frame.values - previousEdges = edges - previousFrameDiff = frameDiff + previousLuminance = frame.values + previousEdges = edges + previousFrameDiff = frameDiff + } + return rawPoints } - if reader.status == .failed { - throw VisualAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "原因不明です.") - } + try Task.checkCancellation() return makeFeaturePoints(from: rawPoints) } diff --git a/ArkServerTests/MusicVideoTests.swift b/ArkServerTests/MusicVideoTests.swift index 5ea60a1..acdecb7 100644 --- a/ArkServerTests/MusicVideoTests.swift +++ b/ArkServerTests/MusicVideoTests.swift @@ -50,7 +50,10 @@ func makeTestVideo( outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: size.width, - AVVideoHeightKey: size.height + AVVideoHeightKey: size.height, + AVVideoCompressionPropertiesKey: [ + AVVideoMaxKeyFrameIntervalKey: Int(framesPerSecond) + ] ] ) input.transform = transform @@ -67,20 +70,7 @@ func makeTestVideo( writer.startSession(atSourceTime: .zero) for frameIndex in 0.. deadline { - writer.cancelWriting() - throw TestVideoWriteStalled(frame: frameIndex, status: writer.status.rawValue) - } - try await Task.sleep(for: .milliseconds(2)) - } + try await waitForVideoInputReady(input, writer: writer, frame: frameIndex) var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, size.width, size.height, kCVPixelFormatType_32BGRA, nil, &pixelBuffer) guard let pixelBuffer else { throw CocoaError(.fileWriteUnknown) } @@ -95,7 +85,7 @@ func makeTestVideo( } } input.markAsFinished() - await writer.finishWriting() + try await AsyncAVFoundation.finishWriting(writer) #expect(writer.status == .completed) } @@ -106,6 +96,22 @@ nonisolated struct TestVideoWriteStalled: Error, CustomStringConvertible { var description: String { "動画の書き込みが 60 秒進まなかった(フレーム \(frame)、書き込みの状態 \(status))" } } +/// 書き込みが失敗したとき、または進まないまま長く待ったときは、理由をつけて失敗させる(待ち続けて、テスト全体を止めない)。 +func waitForVideoInputReady(_ input: AVAssetWriterInput, writer: AVAssetWriter, frame: Int) async throws { + let deadline = Date().addingTimeInterval(60) + while !input.isReadyForMoreMediaData { + try Task.checkCancellation() + if writer.status == .failed || writer.status == .cancelled { + throw writer.error ?? CocoaError(.fileWriteUnknown) + } + if Date() > deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frame, status: writer.status.rawValue) + } + try await Task.sleep(for: .milliseconds(2)) + } +} + func temporaryDirectory(_ name: String) throws -> URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)") try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) @@ -771,12 +777,14 @@ struct MusicVideoPipelineTests { // 曲: 120BPMのクリック(16秒)。 let musicURL = directory.appendingPathComponent("music.wav") - let clicks = evenClicks(from: 0.25, interval: 0.5, until: 16) - try writeMonoWAV( - samples: clickTrack(duration: 16, clicks: clicks.map { ($0, 0.8) }), - sampleRate: testSampleRate, - to: musicURL - ) + try await step("writeMonoWAV") { + let clicks = evenClicks(from: 0.25, interval: 0.5, until: 16) + try writeMonoWAV( + samples: clickTrack(duration: 16, clicks: clicks.map { ($0, 0.8) }), + sampleRate: testSampleRate, + to: musicURL + ) + } // 素材: 40秒の動画3本。明るさが時刻に比例して上がる(A, C)ものと下がる(B)もの。 let rampUp: (Int) -> UInt8 = { frame in UInt8(min(250, 20 + 5 * Double(frame) / 30)) } @@ -784,26 +792,35 @@ struct MusicVideoPipelineTests { let kinds: [(name: String, brightness: (Int) -> UInt8, rises: Bool)] = [ ("a", rampUp, true), ("b", rampDown, false), ("c", rampUp, true) ] - var sources: [ClipPoolSource] = [] - var rises: [UUID: Bool] = [:] - for kind in kinds { - let url = directory.appendingPathComponent("\(kind.name).mp4") - try await makeTestVideo(at: url, duration: 40, brightness: kind.brightness) - let source = ClipPoolSource(videoID: UUID(), url: url, duration: 40) - sources.append(source) - rises[source.videoID] = kind.rises + let (sources, rises): ([ClipPoolSource], [UUID: Bool]) = try await step("makeTestVideo") { + var builtSources: [ClipPoolSource] = [] + var builtRises: [UUID: Bool] = [:] + for kind in kinds { + let url = directory.appendingPathComponent("\(kind.name).mp4") + try await makeTestVideo(at: url, duration: 40, brightness: kind.brightness) + let source = ClipPoolSource(videoID: UUID(), url: url, duration: 40) + builtSources.append(source) + builtRises[source.videoID] = kind.rises + } + return (builtSources, builtRises) } - let analysis = try await BeatAnalyzer().analyze(url: musicURL) + let analysis = try await step("BeatAnalyzer") { + try await BeatAnalyzer().analyze(url: musicURL) + } #expect(abs(analysis.tempo - 120) < 2) - let pool = try await ClipPoolBuilder().build(sources: sources, seed: 1) + let pool = try await step("ClipPoolBuilder") { + try await ClipPoolBuilder().build(sources: sources, seed: 1) + } // 40秒の動画は、冒頭・末尾を避けた2つの窓に分かれる(窓の開始位置が0でない)。 #expect(pool.contains { $0.offset > 1 }) - var planner = CutPlanner() - planner.style = .relaxed - let plan = try planner.plan(analysis: analysis, pool: pool, seed: 3) + let plan = try await step("CutPlanner") { + var planner = CutPlanner() + planner.style = .relaxed + return try planner.plan(analysis: analysis, pool: pool, seed: 3) + } #expect(plan.cuts.count >= 3) // 計画した位置は、すべて解析した窓の内側にある。 for cut in plan.cuts { @@ -816,28 +833,34 @@ struct MusicVideoPipelineTests { let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) let composer = MusicVideoComposer() - let composed = try await composer.makeComposition( - plan: plan, - sourceURLs: Dictionary(uniqueKeysWithValues: sources.map { ($0.videoID, $0.url) }), - audioURL: musicURL, - render: render - ) + let composed = try await step("makeComposition") { + try await composer.makeComposition( + plan: plan, + sourceURLs: Dictionary(uniqueKeysWithValues: sources.map { ($0.videoID, $0.url) }), + audioURL: musicURL, + render: render + ) + } let outputURL = directory.appendingPathComponent("result.mp4") - try await composer.export(composed, to: outputURL) - - let output = AVURLAsset(url: outputURL) - #expect(abs(try await output.load(.duration).seconds - analysis.duration) < 0.3) + try await step("export") { + try await composer.export(composed, to: outputURL) + } - let generator = AVAssetImageGenerator(asset: output) - generator.requestedTimeToleranceBefore = .zero - generator.requestedTimeToleranceAfter = .zero - for cut in plan.cuts { - let middle = cut.timelineStart + cut.duration / 2 - let (image, _) = try await generator.image(at: CMTime(seconds: middle, preferredTimescale: 600)) - let actual = lumaGrid(image).reduce(0, +) / 16 - let sourceTime = cut.sourceStart + cut.duration / 2 - let expected = (rises[cut.videoID] ?? true) ? 20 + 5 * sourceTime : 230 - 5 * sourceTime - #expect(abs(actual - expected) < 25, "t=\(middle) 期待 \(expected) 実際 \(actual)") + try await step("verify") { + let output = AVURLAsset(url: outputURL) + #expect(abs(try await output.load(.duration).seconds - analysis.duration) < 0.3) + + let generator = AVAssetImageGenerator(asset: output) + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + for cut in plan.cuts { + let middle = cut.timelineStart + cut.duration / 2 + let (image, _) = try await generator.image(at: CMTime(seconds: middle, preferredTimescale: 600)) + let actual = lumaGrid(image).reduce(0, +) / 16 + let sourceTime = cut.sourceStart + cut.duration / 2 + let expected = (rises[cut.videoID] ?? true) ? 20 + 5 * sourceTime : 230 - 5 * sourceTime + #expect(abs(actual - expected) < 25, "t=\(middle) 期待 \(expected) 実際 \(actual)") + } } } } @@ -1162,7 +1185,10 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h mediaType: .video, outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: width, AVVideoHeightKey: height, - AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: 6_000_000] + AVVideoCompressionPropertiesKey: [ + AVVideoAverageBitRateKey: 6_000_000, + AVVideoMaxKeyFrameIntervalKey: Int(framesPerSecond) + ] ] ) let adaptor = AVAssetWriterInputPixelBufferAdaptor( @@ -1176,19 +1202,7 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h #expect(writer.startWriting()) writer.startSession(atSourceTime: .zero) for frame in 0.. deadline { - writer.cancelWriting() - throw TestVideoWriteStalled(frame: frame, status: writer.status.rawValue) - } - try await Task.sleep(for: .milliseconds(2)) - } + try await waitForVideoInputReady(input, writer: writer, frame: frame) var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, nil, &pixelBuffer) guard let pixelBuffer else { throw CocoaError(.fileWriteUnknown) } @@ -1208,7 +1222,7 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h } } input.markAsFinished() - await writer.finishWriting() + try await AsyncAVFoundation.finishWriting(writer) #expect(writer.status == .completed) } diff --git a/ArkServerTests/MusicVideoTuningTests.swift b/ArkServerTests/MusicVideoTuningTests.swift index d729b2a..d1e88ac 100644 --- a/ArkServerTests/MusicVideoTuningTests.swift +++ b/ArkServerTests/MusicVideoTuningTests.swift @@ -541,7 +541,7 @@ private func audioPeaks( } } -@Suite(.serialized) +@Suite(.serialized, .timeLimit(.minutes(5))) struct MusicVideoLookCompositionTests { private let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) @@ -1189,7 +1189,7 @@ private struct WaitTimeout: Error, CustomStringConvertible { var description: String { "待っていた状態にならないまま時間切れ: \(label)" } } -@Suite(.serialized) +@Suite(.serialized, .timeLimit(.minutes(5))) @MainActor struct MusicVideoTuningViewModelTests { private struct Harness { diff --git a/ArkServerTests/SceneExtractionTests.swift b/ArkServerTests/SceneExtractionTests.swift index 99afdc3..f5d63ef 100644 --- a/ArkServerTests/SceneExtractionTests.swift +++ b/ArkServerTests/SceneExtractionTests.swift @@ -738,7 +738,10 @@ struct SceneExtractionTests { outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: width, - AVVideoHeightKey: height + AVVideoHeightKey: height, + AVVideoCompressionPropertiesKey: [ + AVVideoMaxKeyFrameIntervalKey: Int(framesPerSecond) + ] ] ) let adaptor = AVAssetWriterInputPixelBufferAdaptor( @@ -755,19 +758,7 @@ struct SceneExtractionTests { writer.startSession(atSourceTime: .zero) for frameIndex in 0.. deadline { - writer.cancelWriting() - throw TestVideoWriteStalled(frame: frameIndex, status: writer.status.rawValue) - } - try await Task.sleep(for: .milliseconds(2)) - } + try await waitForVideoInputReady(input, writer: writer, frame: frameIndex) var pixelBuffer: CVPixelBuffer? let status = CVPixelBufferCreate( kCFAllocatorDefault, @@ -803,7 +794,7 @@ struct SceneExtractionTests { } input.markAsFinished() - await writer.finishWriting() + try await AsyncAVFoundation.finishWriting(writer) #expect(writer.status == .completed) } From 9d0aa1b68e909cc10f3bb1087cadf7bf884e6a8e Mon Sep 17 00:00:00 2001 From: HR0101 Date: Mon, 16 Nov 2026 15:43:37 +0900 Subject: [PATCH 7/9] =?UTF-8?q?Revert=20"fix:=20AVFoundation=E8=AA=AD?= =?UTF-8?q?=E3=81=BF=E6=9B=B8=E3=81=8D=E3=81=AETask=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E5=AF=BE=E5=BF=9C=E3=81=A8VM=E7=92=B0=E5=A2=83=E3=81=A7?= =?UTF-8?q?=E3=81=AE=E5=90=8C=E6=99=82=E5=BE=A9=E5=8F=B7=E6=95=B0=E8=AA=BF?= =?UTF-8?q?=E6=95=B4"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit e9757dfb138223fad9b32934a31d7e3fc4e58cf5. --- .../Common/Utilities/AsyncAVFoundation.swift | 283 -------------- .../MusicVideo/Services/BeatAnalyzer.swift | 53 ++- .../MusicVideo/Services/ClipPoolBuilder.swift | 11 +- .../Services/MusicVideoComposer.swift | 357 ++++-------------- .../Services/SourceAudioSeparator.swift | 48 ++- .../Services/VisualAnalyzer.swift | 91 +++-- ArkServerTests/MusicVideoTests.swift | 154 ++++---- ArkServerTests/MusicVideoTuningTests.swift | 4 +- ArkServerTests/SceneExtractionTests.swift | 21 +- 9 files changed, 249 insertions(+), 773 deletions(-) delete mode 100644 ArkServer/Common/Utilities/AsyncAVFoundation.swift diff --git a/ArkServer/Common/Utilities/AsyncAVFoundation.swift b/ArkServer/Common/Utilities/AsyncAVFoundation.swift deleted file mode 100644 index 992edd9..0000000 --- a/ArkServer/Common/Utilities/AsyncAVFoundation.swift +++ /dev/null @@ -1,283 +0,0 @@ -// ArkServer/Common/Utilities/AsyncAVFoundation.swift - -import AVFoundation -import Foundation - -/// スレッドをまたいで所有権を移す非 Sendable 値を包む補助。 -/// 生成元のスレッドで設定を終えたあと、受け取り側だけが使う値に使う。 -nonisolated struct UncheckedSendableBox: @unchecked Sendable { - let value: Value - - init(_ value: Value) { - self.value = value - } -} - -/// AVFoundation の同期的な読み出しや書き出しを、Task 取消とスレッド安全を保ったまま非同期で扱うための補助。 -nonisolated enum AsyncAVFoundation { - /// macOS の仮想マシン(`kern.hv_vmm_present == 1`)上で動作しているかどうか。 - static var isVirtualMachine: Bool { - var value: Int32 = 0 - var size = MemoryLayout.size - return sysctlbyname("kern.hv_vmm_present", &value, &size, nil, 0) == 0 && value == 1 - } - - /// `AVAssetReader` の開始と読み出しを専用の `DispatchQueue` 上で実行する。 - /// Swift の協調スレッドプールを塞がず、Task 取消時にも呼び出し元が即座に戻れるようにする。 - /// - /// `startReading()` の実行中に `cancelReading()` を呼ぶと AVFoundation の内部で落ちるため、 - /// 開始中の取消は `startReading()` が戻ってから実行する。 - static func runReader( - _ reader: AVAssetReader, - queueLabel: String, - startError: @escaping @Sendable (String) -> any Error, - readError: @escaping @Sendable (String) -> any Error, - body: @escaping @Sendable (_ isCancelled: @escaping @Sendable () -> Bool) throws -> Output - ) async throws -> Output { - try Task.checkCancellation() - let session = ReaderSession(reader: reader) - return try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - guard session.arm(continuation: continuation) else { - continuation.resume(throwing: CancellationError()) - return - } - DispatchQueue(label: queueLabel, qos: .userInitiated).async { - session.execute(startError: startError, readError: readError, body: body) - } - } - } onCancel: { - session.cancel() - } - } - - /// `AVAssetWriter.finishWriting` を Task 取消に対応させて待つ。 - static func finishWriting(_ writer: AVAssetWriter) async throws { - if Task.isCancelled { - if writer.status == .writing { writer.cancelWriting() } - throw CancellationError() - } - let session = FinishWritingSession(writer: writer) - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - session.start(with: continuation) - } - } onCancel: { - session.cancel() - } - } -} - -private enum ReaderStartOutcome { case cancelled, failed, ready } - -private nonisolated final class ReaderSession: @unchecked Sendable { - private enum Phase { - case idle - case starting - case running - case finished - } - - private let lock = NSLock() - private let reader: AVAssetReader - private var phase: Phase = .idle - private var isCancelled = false - private var didCancelReader = false - private var continuation: CheckedContinuation? - - init(reader: AVAssetReader) { - self.reader = reader - } - - func arm(continuation: CheckedContinuation) -> Bool { - lock.withLock { - guard !isCancelled else { return false } - self.continuation = continuation - return true - } - } - - func cancel() { - let (cont, shouldCancelReader) = lock.withLock { () -> (CheckedContinuation?, Bool) in - isCancelled = true - let cont = continuation - continuation = nil - // startReading() の途中で cancelReading() を呼ぶと内部で落ちるため、running 中だけ即時中止する。 - let canCancelNow = (phase == .running && !didCancelReader) - if canCancelNow { didCancelReader = true } - return (cont, canCancelNow) - } - if shouldCancelReader { - reader.cancelReading() - } - cont?.resume(throwing: CancellationError()) - } - - func execute( - startError: (String) -> any Error, - readError: (String) -> any Error, - body: (_ isCancelled: @escaping @Sendable () -> Bool) throws -> Output - ) { - let canStart = lock.withLock { () -> Bool in - guard !isCancelled else { - phase = .finished - return false - } - phase = .starting - return true - } - guard canStart else { - resume(throwing: CancellationError()) - return - } - - let started = reader.startReading() - - let outcome = lock.withLock { () -> (ReaderStartOutcome, Bool) in - if isCancelled { - phase = .finished - if started, !didCancelReader { - didCancelReader = true - return (.cancelled, true) - } - return (.cancelled, false) - } - guard started else { - phase = .finished - return (.failed, false) - } - phase = .running - return (.ready, false) - } - - if outcome.1 { - reader.cancelReading() - } - switch outcome.0 { - case .cancelled: - resume(throwing: CancellationError()) - return - case .failed: - resume(throwing: startError(reader.error?.localizedDescription ?? "開始できませんでした.")) - return - case .ready: - break - } - - let cancelledCheck: @Sendable () -> Bool = { [self] in - lock.withLock { isCancelled } - } - - let result: Result - do { - let value = try body(cancelledCheck) - if cancelledCheck() { - result = .failure(CancellationError()) - } else if reader.status == .failed { - result = .failure(readError(reader.error?.localizedDescription ?? "原因不明です.")) - } else { - result = .success(value) - } - } catch { - result = .failure(cancelledCheck() ? CancellationError() : error) - } - - let shouldCancelReader = lock.withLock { () -> Bool in - phase = .finished - guard !didCancelReader else { return false } - let reading = (reader.status == .reading) - if reading { didCancelReader = true } - return reading - } - if shouldCancelReader { - reader.cancelReading() - } - - switch result { - case .success(let value): - resume(returning: value) - case .failure(let error): - resume(throwing: error) - } - } - - private func resume(returning value: Output) { - let cont = lock.withLock { () -> CheckedContinuation? in - defer { continuation = nil } - return continuation - } - cont?.resume(returning: value) - } - - private func resume(throwing error: any Error) { - let cont = lock.withLock { () -> CheckedContinuation? in - defer { continuation = nil } - return continuation - } - cont?.resume(throwing: error) - } -} - -private nonisolated final class FinishWritingSession: @unchecked Sendable { - private let lock = NSLock() - private let writer: AVAssetWriter - private var isCancelled = false - private var isFinished = false - private var didCancelWriter = false - private var continuation: CheckedContinuation? - - init(writer: AVAssetWriter) { - self.writer = writer - } - - func start(with continuation: CheckedContinuation) { - let (shouldStart, shouldCancelWriter) = lock.withLock { () -> (Bool, Bool) in - guard !isCancelled else { - let canCancel = (!didCancelWriter && writer.status == .writing) - if canCancel { didCancelWriter = true } - return (false, canCancel) - } - self.continuation = continuation - return (true, false) - } - if shouldCancelWriter { - writer.cancelWriting() - } - guard shouldStart else { - continuation.resume(throwing: CancellationError()) - return - } - writer.finishWriting { [self] in - complete() - } - } - - func complete() { - let (cont, cancelled) = lock.withLock { () -> (CheckedContinuation?, Bool) in - isFinished = true - let cont = continuation - continuation = nil - return (cont, isCancelled) - } - if cancelled { - cont?.resume(throwing: CancellationError()) - } else { - cont?.resume(returning: ()) - } - } - - func cancel() { - let (cont, shouldCancelWriter) = lock.withLock { () -> (CheckedContinuation?, Bool) in - isCancelled = true - let cont = continuation - continuation = nil - let canCancel = (!isFinished && !didCancelWriter && writer.status == .writing) - if canCancel { didCancelWriter = true } - return (cont, canCancel) - } - if shouldCancelWriter { - writer.cancelWriting() - } - cont?.resume(throwing: CancellationError()) - } -} diff --git a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift index 10019cb..b25912a 100644 --- a/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift +++ b/ArkServer/Features/MusicVideo/Services/BeatAnalyzer.swift @@ -76,35 +76,34 @@ nonisolated struct BeatAnalyzer: Sendable { output.alwaysCopiesSampleData = false guard reader.canAdd(output) else { throw BeatAnalyzerError.cannotAddOutput } reader.add(output) - let outputBox = UncheckedSendableBox(output) - return try await AsyncAVFoundation.runReader( - reader, - queueLabel: "arkserver.beat-analyzer", - startError: { BeatAnalyzerError.readerFailed($0) }, - readError: { BeatAnalyzerError.readerFailed($0) } - ) { isCancelled in - var samples: [Float] = [] - while let sampleBuffer = outputBox.value.copyNextSampleBuffer() { - if isCancelled() { throw CancellationError() } - guard let dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { continue } - let byteCount = CMBlockBufferGetDataLength(dataBuffer) - guard byteCount > 0, byteCount.isMultiple(of: MemoryLayout.size) else { continue } - var chunk = [Float](repeating: 0, count: byteCount / MemoryLayout.size) - let status = chunk.withUnsafeMutableBytes { destination in - CMBlockBufferCopyDataBytes( - dataBuffer, - atOffset: 0, - dataLength: byteCount, - destination: destination.baseAddress! - ) - } - guard status == kCMBlockBufferNoErr else { - throw BeatAnalyzerError.readerFailed("PCMバッファをコピーできませんでした.") - } - samples.append(contentsOf: chunk) + guard reader.startReading() else { + throw BeatAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "開始できませんでした.") + } + + var samples: [Float] = [] + while let sampleBuffer = output.copyNextSampleBuffer() { + try Task.checkCancellation() + guard let dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { continue } + let byteCount = CMBlockBufferGetDataLength(dataBuffer) + guard byteCount > 0, byteCount.isMultiple(of: MemoryLayout.size) else { continue } + var chunk = [Float](repeating: 0, count: byteCount / MemoryLayout.size) + let status = chunk.withUnsafeMutableBytes { destination in + CMBlockBufferCopyDataBytes( + dataBuffer, + atOffset: 0, + dataLength: byteCount, + destination: destination.baseAddress! + ) + } + guard status == kCMBlockBufferNoErr else { + throw BeatAnalyzerError.readerFailed("PCMバッファをコピーできませんでした.") } - return samples + samples.append(contentsOf: chunk) + } + if reader.status == .failed { + throw BeatAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "原因不明です.") } + return samples } // MARK: - 解析本体(ファイル非依存。単体テストはここを直接呼ぶ) diff --git a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift index 6bf3e27..3ac3b8c 100644 --- a/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift +++ b/ArkServer/Features/MusicVideo/Services/ClipPoolBuilder.swift @@ -44,8 +44,7 @@ nonisolated struct ClipPoolBuilder: Sendable { /// 動画の読み込み(復号)は、標本数に関わらず全フレームぶん行うので、細かくしても重さはあまり増えない。 var analysisFramesPerSecond = 12.0 /// 同時に解析する動画の数。 - /// 仮想環境では複数のハードウェア復号を同時に走らせると詰まることがあるため 1 に抑える。 - var maxConcurrentAnalyses = AsyncAVFoundation.isVirtualMachine ? 1 : 3 + var maxConcurrentAnalyses = 3 /// 解析する動画の最大本数。これを超えたらシードで無作為に選ぶ。 var maxVideos = 40 /// キャッシュの保存先。nil ならキャッシュしない。 @@ -73,13 +72,7 @@ nonisolated struct ClipPoolBuilder: Sendable { let source = selected[index] nextIndex += 1 group.addTask { - do { - return (index, try await self.motionWindows(for: source)) - } catch is CancellationError { - throw CancellationError() - } catch { - return (index, nil) - } + (index, try? await self.motionWindows(for: source)) } } for _ in 0.. AVPlayerItem { let item = AVPlayerItem(asset: composition) item.videoComposition = videoComposition @@ -761,21 +760,12 @@ nonisolated struct MusicVideoComposer: Sendable { private let audioOutput: AVAssetReaderAudioMixOutput? private let audioInput: AVAssetWriterInput? private let duration: Double - private enum Phase { - case idle - case startingReader - case startingWriter - case running - case finishing - case finished - } + /// 読み出しの開始(startReading)中に中止(cancelReading)を呼ぶと AVFoundation の内部で落ちるので、 + /// 開始中の取り消しは、開始が終わってから実行する。 + private enum Phase { case idle, starting, running } private let lock = NSLock() private var isCancelled = false - private var didAbort = false - private var didCancelReader = false - private var didCancelWriter = false private var phase: Phase = .idle - private var activeContinuations: [UUID: CheckedContinuation] = [:] init(composed: MusicVideoComposition, outputURL: URL, quality: MusicVideoExportQuality) throws { let render = composed.render @@ -860,241 +850,62 @@ nonisolated struct MusicVideoComposer: Sendable { } func cancel() { - let (shouldCancelReader, shouldCancelWriter, continuations) = lock.withLock { - () -> (Bool, Bool, [CheckedContinuation]) in - isCancelled = true - // startReading() の途中で cancelReading() を呼ぶと AVFoundation の内部で落ちるため、 - // startingReader 中は止めず、開始が終わってから executeStartPipeline() で止める。 - let canCancelReader = !didCancelReader && (phase == .startingWriter || phase == .running) - if canCancelReader { didCancelReader = true } - let canCancelWriter = !didCancelWriter && phase == .running - if canCancelWriter { didCancelWriter = true } - let pending = Array(activeContinuations.values) - activeContinuations.removeAll() - return (canCancelReader, canCancelWriter, pending) - } - if shouldCancelReader { reader.cancelReading() } - if shouldCancelWriter { writer.cancelWriting() } - for continuation in continuations { - continuation.resume(throwing: CancellationError()) - } - } - - private var shouldStopPumping: Bool { - lock.withLock { isCancelled || didAbort } + lock.lock() + isCancelled = true + let shouldCancelNow = phase == .running + lock.unlock() + // 読み出しを止めると、流し込みの側は終わりまで読んだものとして自然に閉じる。 + // まだ始まっていない/開始中なら、run() が開始後に止める。 + if shouldCancelNow { reader.cancelReading() } } private var wasCancelled: Bool { - lock.withLock { isCancelled } + lock.lock(); defer { lock.unlock() } + return isCancelled } func run(progress: @escaping @Sendable (Double) async -> Void) async throws { - try await startPipeline() - - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await self.pump(self.videoInput, from: self.videoOutput, progress: progress) - } - if let audioInput, let audioOutput { - group.addTask { - try await self.pump(audioInput, from: audioOutput, progress: nil) - } - } - try await group.waitForAll() - } - - if wasCancelled { - cancelReaderOnce() - cancelWriterOnce() - markFinished() + lock.lock() + if isCancelled { lock.unlock(); throw CancellationError() } + phase = .starting + lock.unlock() + + let started = reader.startReading() + + lock.lock() + phase = .running + let cancelledWhileStarting = isCancelled + lock.unlock() + if cancelledWhileStarting { + reader.cancelReading() throw CancellationError() } - if reader.status == .failed && writer.status != .failed { - cancelWriterOnce() - markFinished() - throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しに失敗しました.") - } - if writer.status == .failed { - cancelReaderOnce() - markFinished() - throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みに失敗しました.") - } - guard enterFinishing() else { - cancelWriterOnce() - markFinished() - throw CancellationError() + guard started else { + throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しを開始できませんでした.") } - do { - try await AsyncAVFoundation.finishWriting(writer) - } catch { - markFinished() - throw error + guard writer.startWriting() else { + reader.cancelReading() + throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みを開始できませんでした.") } - markFinished() - if wasCancelled { - throw CancellationError() - } - guard writer.status == .completed else { - throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みに失敗しました.") - } - } - - private func startPipeline() async throws { - try Task.checkCancellation() - let id = UUID() - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - let armed = lock.withLock { () -> Bool in - guard !isCancelled else { return false } - phase = .startingReader - activeContinuations[id] = continuation - return true - } - guard armed else { - continuation.resume(throwing: CancellationError()) - return - } - DispatchQueue(label: "musicvideo.export.start", qos: .userInitiated).async { - self.executeStartPipeline(id: id) - } - } - } - - private func executeStartPipeline(id: UUID) { - let readerStarted = reader.startReading() - let afterReader = lock.withLock { () -> (cancelled: Bool, failed: Bool) in - if isCancelled { - phase = .finished - return (true, false) - } - guard readerStarted else { - phase = .finished - return (false, true) - } - phase = .startingWriter - return (false, false) - } - if afterReader.cancelled { - if readerStarted { cancelReaderOnce() } - resumeContinuation(id: id, error: CancellationError()) - return - } - if afterReader.failed { - let reason = reader.error?.localizedDescription ?? "読み出しを開始できませんでした." - resumeContinuation(id: id, error: MusicVideoComposerError.exportFailed(reason)) - return - } - - let writerStarted = writer.startWriting() - let abortedBeforeSession = lock.withLock { () -> (cancelled: Bool, failed: Bool) in - if isCancelled { - phase = .finished - return (true, false) - } - guard writerStarted else { - phase = .finished - return (false, true) - } - return (false, false) - } - if abortedBeforeSession.cancelled { - cancelReaderOnce() - if writerStarted { cancelWriterOnce() } - resumeContinuation(id: id, error: CancellationError()) - return - } - if abortedBeforeSession.failed { - cancelReaderOnce() - let reason = writer.error?.localizedDescription ?? "書き込みを開始できませんでした." - resumeContinuation(id: id, error: MusicVideoComposerError.exportFailed(reason)) - return - } - writer.startSession(atSourceTime: .zero) - let cancelledDuringSession = lock.withLock { () -> Bool in - if isCancelled { - phase = .finished - return true - } - phase = .running - return false - } - if cancelledDuringSession { - cancelReaderOnce() - cancelWriterOnce() - resumeContinuation(id: id, error: CancellationError()) - return - } - resumeContinuation(id: id, error: nil) - } - - private func resumeContinuation(id: UUID, error: (any Error)?) { - let continuation = lock.withLock { activeContinuations.removeValue(forKey: id) } - if let error { - continuation?.resume(throwing: error) - } else { - continuation?.resume(returning: ()) - } - } - - private func registerPumpContinuation(_ continuation: CheckedContinuation, id: UUID) -> Bool { - lock.withLock { - guard !isCancelled, !didAbort else { return false } - activeContinuations[id] = continuation - return true - } - } + async let videoDone: Void = pump(videoInput, from: videoOutput, progress: progress) + async let audioDone: Void = { + if let audioInput, let audioOutput { await pump(audioInput, from: audioOutput, progress: nil) } + }() + _ = await (videoDone, audioDone) - private func finishPump(id: UUID) { - let continuation = lock.withLock { activeContinuations.removeValue(forKey: id) } - continuation?.resume(returning: ()) - } - - private func abortOnPumpFailure() { - let (shouldCancelReader, continuations) = lock.withLock { - () -> (Bool, [CheckedContinuation]) in - didAbort = true - let canCancelReader = !didCancelReader && phase == .running - if canCancelReader { didCancelReader = true } - let pending = Array(activeContinuations.values) - activeContinuations.removeAll() - return (canCancelReader, pending) - } - if shouldCancelReader { reader.cancelReading() } - for continuation in continuations { - continuation.resume(returning: ()) - } - } - - private func cancelReaderOnce() { - let shouldCancel = lock.withLock { () -> Bool in - guard !didCancelReader else { return false } - didCancelReader = true - return true - } - if shouldCancel { reader.cancelReading() } - } - - private func cancelWriterOnce() { - let shouldCancel = lock.withLock { () -> Bool in - guard !didCancelWriter else { return false } - didCancelWriter = true - return true + if wasCancelled { + writer.cancelWriting() + throw CancellationError() } - if shouldCancel { writer.cancelWriting() } - } - - private func enterFinishing() -> Bool { - lock.withLock { - guard !isCancelled else { return false } - phase = .finishing - return true + if reader.status == .failed { + writer.cancelWriting() + throw MusicVideoComposerError.exportFailed(reader.error?.localizedDescription ?? "読み出しに失敗しました.") } - } - - private func markFinished() { - lock.withLock { - phase = .finished + await writer.finishWriting() + guard writer.status == .completed else { + throw MusicVideoComposerError.exportFailed(writer.error?.localizedDescription ?? "書き込みに失敗しました.") } } @@ -1103,73 +914,41 @@ nonisolated struct MusicVideoComposer: Sendable { _ input: AVAssetWriterInput, from output: AVAssetReaderOutput, progress: (@Sendable (Double) async -> Void)? - ) async throws { - final class PumpState: @unchecked Sendable { - var lastReported = -1.0 - var isFinished = false - } - - let id = UUID() + ) async { let queue = DispatchQueue(label: "musicvideo.export.\(input.mediaType.rawValue)") let total = max(duration, 0.001) - let readerBox = UncheckedSendableBox(self.reader) - let writerBox = UncheckedSendableBox(self.writer) - let inputBox = UncheckedSendableBox(input) - let outputBox = UncheckedSendableBox(output) - let state = PumpState() - // 書き出し側は、閉じた後も「受け取れます」と呼び出し直してくることがある。 - // そのとき、解放済みの読み出し側に触らないよう、(1)終わったら何もしない (2)呼び出しが続く間は reader/writer を保持する。 - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - guard registerPumpContinuation(continuation, id: id) else { - continuation.resume(throwing: wasCancelled ? CancellationError() : MusicVideoComposerError.exportFailed("書き込みが中断されました.")) - return - } - inputBox.value.requestMediaDataWhenReady(on: queue) { [weak self, readerBox, writerBox] in - withExtendedLifetime((readerBox.value, writerBox.value)) { - func markFinishedIfWriting() { - state.isFinished = true - if writerBox.value.status == .writing { - inputBox.value.markAsFinished() - } + // そのとき、解放済みの読み出し側に触らないよう、(1)終わったら何もしない (2)呼び出しが続く間は reader を保持する。 + let reader = self.reader + await withCheckedContinuation { (continuation: CheckedContinuation) in + var lastReported = -1.0 + var isFinished = false + input.requestMediaDataWhenReady(on: queue) { + withExtendedLifetime(reader) { + guard !isFinished else { return } + while input.isReadyForMoreMediaData { + guard let buffer = output.copyNextSampleBuffer() else { + isFinished = true + input.markAsFinished() + continuation.resume() + return } - - guard !state.isFinished else { return } - guard let self, !self.shouldStopPumping else { - markFinishedIfWriting() - self?.finishPump(id: id) + if !input.append(buffer) { + isFinished = true + input.markAsFinished() + continuation.resume() return } - while inputBox.value.isReadyForMoreMediaData { - if self.shouldStopPumping { - markFinishedIfWriting() - self.finishPump(id: id) - return - } - guard let buffer = outputBox.value.copyNextSampleBuffer() else { - markFinishedIfWriting() - self.finishPump(id: id) - return - } - if !inputBox.value.append(buffer) { - markFinishedIfWriting() - self.abortOnPumpFailure() - return - } - if let progress { - let fraction = min(1, max(0, CMSampleBufferGetPresentationTimeStamp(buffer).seconds / total)) - if fraction - state.lastReported >= 0.01 { - state.lastReported = fraction - Task { await progress(fraction) } - } + if let progress { + let fraction = min(1, max(0, CMSampleBufferGetPresentationTimeStamp(buffer).seconds / total)) + if fraction - lastReported >= 0.01 { + lastReported = fraction + Task { await progress(fraction) } } } } } } - } onCancel: { - self.cancel() } } } diff --git a/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift b/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift index e9805a5..8f88117 100644 --- a/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift +++ b/ArkServer/Features/MusicVideo/Services/SourceAudioSeparator.swift @@ -153,36 +153,32 @@ nonisolated struct SourceAudioSeparator: Sendable { start: CMTime(seconds: start, preferredTimescale: 600), duration: CMTime(seconds: duration, preferredTimescale: 600) ) + guard reader.startReading() else { + throw SourceAudioSeparatorError.cannotRead(reader.error?.localizedDescription ?? "読み出しを始められません.") + } + guard let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: Self.sampleRate, channels: 2, interleaved: false) else { throw SourceAudioSeparatorError.cannotRead("音声の形式を作れません.") } - let outputBox = UncheckedSendableBox(output) - let formatBox = UncheckedSendableBox(format) - let (left, right, firstTime) = try await AsyncAVFoundation.runReader( - reader, - queueLabel: "arkserver.audio-separator", - startError: { SourceAudioSeparatorError.cannotRead($0) }, - readError: { SourceAudioSeparatorError.cannotRead($0) } - ) { isCancelled in - var left: [Float] = [] - var right: [Float] = [] - var firstTime: Double? - while let sampleBuffer = outputBox.value.copyNextSampleBuffer() { - if isCancelled() { throw CancellationError() } - let frames = CMSampleBufferGetNumSamples(sampleBuffer) - guard frames > 0, let buffer = AVAudioPCMBuffer(pcmFormat: formatBox.value, frameCapacity: AVAudioFrameCount(frames)) else { continue } - buffer.frameLength = AVAudioFrameCount(frames) - let status = CMSampleBufferCopyPCMDataIntoAudioBufferList( - sampleBuffer, at: 0, frameCount: Int32(frames), into: buffer.mutableAudioBufferList - ) - guard status == noErr, let channels = buffer.floatChannelData else { continue } - if firstTime == nil { firstTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds } - left.append(contentsOf: UnsafeBufferPointer(start: channels[0], count: frames)) - right.append(contentsOf: UnsafeBufferPointer(start: channels[1], count: frames)) - } - return (left, right, firstTime) + var left: [Float] = [] + var right: [Float] = [] + var firstTime: Double? + while let sampleBuffer = output.copyNextSampleBuffer() { + try Task.checkCancellation() + let frames = CMSampleBufferGetNumSamples(sampleBuffer) + guard frames > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)) else { continue } + buffer.frameLength = AVAudioFrameCount(frames) + let status = CMSampleBufferCopyPCMDataIntoAudioBufferList( + sampleBuffer, at: 0, frameCount: Int32(frames), into: buffer.mutableAudioBufferList + ) + guard status == noErr, let channels = buffer.floatChannelData else { continue } + if firstTime == nil { firstTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds } + left.append(contentsOf: UnsafeBufferPointer(start: channels[0], count: frames)) + right.append(contentsOf: UnsafeBufferPointer(start: channels[1], count: frames)) + } + if reader.status == .failed { + throw SourceAudioSeparatorError.cannotRead(reader.error?.localizedDescription ?? "読み出しに失敗しました.") } - try Task.checkCancellation() guard !left.isEmpty else { throw SourceAudioSeparatorError.cannotRead("指定の範囲に音がありません.") } return ReadAudio(audio: AudioSignal(sampleRate: Self.sampleRate, channels: [left, right]), startTime: firstTime ?? start) } diff --git a/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift b/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift index 6e7b162..1c139a7 100644 --- a/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift +++ b/ArkServer/Features/SceneExtraction/Services/VisualAnalyzer.swift @@ -69,57 +69,54 @@ nonisolated struct VisualAnalyzer: Sendable { ) } + guard reader.startReading() else { + throw VisualAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "開始できませんでした.") + } + let sampleInterval = 1 / max(1, settings.analysisFramesPerSecond) - let outputBox = UncheckedSendableBox(output) - let rawPoints = try await AsyncAVFoundation.runReader( - reader, - queueLabel: "arkserver.visual-analyzer", - startError: { VisualAnalyzerError.readerFailed($0) }, - readError: { VisualAnalyzerError.readerFailed($0) } - ) { isCancelled in - var nextSampleTime = 0.0 - var previousLuminance: [Float]? - var previousEdges: [Float]? - var previousFrameDiff = 0.0 - var rawPoints: [RawVisualPoint] = [] - - while let sampleBuffer = outputBox.value.copyNextSampleBuffer() { - if isCancelled() { throw CancellationError() } - let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds - guard presentationTime.isFinite, presentationTime + 0.000_001 >= nextSampleTime else { - continue - } - nextSampleTime = presentationTime + sampleInterval - - guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { - continue - } - let frame = try makeLuminanceFrame(from: pixelBuffer) - let edges = makeEdges(from: frame.values, width: frame.width, height: frame.height) - let luminanceDiff = meanAbsoluteDifference(frame.values, previousLuminance) - let edgeDiff = meanAbsoluteDifference(edges, previousEdges) - let frameDiff = luminanceWeight * luminanceDiff + edgeWeight * edgeDiff - let motionDelta = frameDiff - previousFrameDiff - - rawPoints.append( - RawVisualPoint( - time: max(0, presentationTime), - frameDiff: frameDiff, - meanLuminance: frame.meanLuminance, - luminanceDiff: luminanceDiff, - edgeDiff: edgeDiff, - motionSpike: max(0, motionDelta), - motionDrop: max(0, -motionDelta) - ) - ) - previousLuminance = frame.values - previousEdges = edges - previousFrameDiff = frameDiff + var nextSampleTime = 0.0 + var previousLuminance: [Float]? + var previousEdges: [Float]? + var previousFrameDiff = 0.0 + var rawPoints: [RawVisualPoint] = [] + + while let sampleBuffer = output.copyNextSampleBuffer() { + try Task.checkCancellation() + let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds + guard presentationTime.isFinite, presentationTime + 0.000_001 >= nextSampleTime else { + continue + } + nextSampleTime = presentationTime + sampleInterval + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { + continue } - return rawPoints + let frame = try makeLuminanceFrame(from: pixelBuffer) + let edges = makeEdges(from: frame.values, width: frame.width, height: frame.height) + let luminanceDiff = meanAbsoluteDifference(frame.values, previousLuminance) + let edgeDiff = meanAbsoluteDifference(edges, previousEdges) + let frameDiff = luminanceWeight * luminanceDiff + edgeWeight * edgeDiff + let motionDelta = frameDiff - previousFrameDiff + + rawPoints.append( + RawVisualPoint( + time: max(0, presentationTime), + frameDiff: frameDiff, + meanLuminance: frame.meanLuminance, + luminanceDiff: luminanceDiff, + edgeDiff: edgeDiff, + motionSpike: max(0, motionDelta), + motionDrop: max(0, -motionDelta) + ) + ) + previousLuminance = frame.values + previousEdges = edges + previousFrameDiff = frameDiff } - try Task.checkCancellation() + if reader.status == .failed { + throw VisualAnalyzerError.readerFailed(reader.error?.localizedDescription ?? "原因不明です.") + } return makeFeaturePoints(from: rawPoints) } diff --git a/ArkServerTests/MusicVideoTests.swift b/ArkServerTests/MusicVideoTests.swift index acdecb7..5ea60a1 100644 --- a/ArkServerTests/MusicVideoTests.swift +++ b/ArkServerTests/MusicVideoTests.swift @@ -50,10 +50,7 @@ func makeTestVideo( outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: size.width, - AVVideoHeightKey: size.height, - AVVideoCompressionPropertiesKey: [ - AVVideoMaxKeyFrameIntervalKey: Int(framesPerSecond) - ] + AVVideoHeightKey: size.height ] ) input.transform = transform @@ -70,7 +67,20 @@ func makeTestVideo( writer.startSession(atSourceTime: .zero) for frameIndex in 0.. deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frameIndex, status: writer.status.rawValue) + } + try await Task.sleep(for: .milliseconds(2)) + } var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, size.width, size.height, kCVPixelFormatType_32BGRA, nil, &pixelBuffer) guard let pixelBuffer else { throw CocoaError(.fileWriteUnknown) } @@ -85,7 +95,7 @@ func makeTestVideo( } } input.markAsFinished() - try await AsyncAVFoundation.finishWriting(writer) + await writer.finishWriting() #expect(writer.status == .completed) } @@ -96,22 +106,6 @@ nonisolated struct TestVideoWriteStalled: Error, CustomStringConvertible { var description: String { "動画の書き込みが 60 秒進まなかった(フレーム \(frame)、書き込みの状態 \(status))" } } -/// 書き込みが失敗したとき、または進まないまま長く待ったときは、理由をつけて失敗させる(待ち続けて、テスト全体を止めない)。 -func waitForVideoInputReady(_ input: AVAssetWriterInput, writer: AVAssetWriter, frame: Int) async throws { - let deadline = Date().addingTimeInterval(60) - while !input.isReadyForMoreMediaData { - try Task.checkCancellation() - if writer.status == .failed || writer.status == .cancelled { - throw writer.error ?? CocoaError(.fileWriteUnknown) - } - if Date() > deadline { - writer.cancelWriting() - throw TestVideoWriteStalled(frame: frame, status: writer.status.rawValue) - } - try await Task.sleep(for: .milliseconds(2)) - } -} - func temporaryDirectory(_ name: String) throws -> URL { let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(name)-\(UUID().uuidString)") try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) @@ -777,14 +771,12 @@ struct MusicVideoPipelineTests { // 曲: 120BPMのクリック(16秒)。 let musicURL = directory.appendingPathComponent("music.wav") - try await step("writeMonoWAV") { - let clicks = evenClicks(from: 0.25, interval: 0.5, until: 16) - try writeMonoWAV( - samples: clickTrack(duration: 16, clicks: clicks.map { ($0, 0.8) }), - sampleRate: testSampleRate, - to: musicURL - ) - } + let clicks = evenClicks(from: 0.25, interval: 0.5, until: 16) + try writeMonoWAV( + samples: clickTrack(duration: 16, clicks: clicks.map { ($0, 0.8) }), + sampleRate: testSampleRate, + to: musicURL + ) // 素材: 40秒の動画3本。明るさが時刻に比例して上がる(A, C)ものと下がる(B)もの。 let rampUp: (Int) -> UInt8 = { frame in UInt8(min(250, 20 + 5 * Double(frame) / 30)) } @@ -792,35 +784,26 @@ struct MusicVideoPipelineTests { let kinds: [(name: String, brightness: (Int) -> UInt8, rises: Bool)] = [ ("a", rampUp, true), ("b", rampDown, false), ("c", rampUp, true) ] - let (sources, rises): ([ClipPoolSource], [UUID: Bool]) = try await step("makeTestVideo") { - var builtSources: [ClipPoolSource] = [] - var builtRises: [UUID: Bool] = [:] - for kind in kinds { - let url = directory.appendingPathComponent("\(kind.name).mp4") - try await makeTestVideo(at: url, duration: 40, brightness: kind.brightness) - let source = ClipPoolSource(videoID: UUID(), url: url, duration: 40) - builtSources.append(source) - builtRises[source.videoID] = kind.rises - } - return (builtSources, builtRises) + var sources: [ClipPoolSource] = [] + var rises: [UUID: Bool] = [:] + for kind in kinds { + let url = directory.appendingPathComponent("\(kind.name).mp4") + try await makeTestVideo(at: url, duration: 40, brightness: kind.brightness) + let source = ClipPoolSource(videoID: UUID(), url: url, duration: 40) + sources.append(source) + rises[source.videoID] = kind.rises } - let analysis = try await step("BeatAnalyzer") { - try await BeatAnalyzer().analyze(url: musicURL) - } + let analysis = try await BeatAnalyzer().analyze(url: musicURL) #expect(abs(analysis.tempo - 120) < 2) - let pool = try await step("ClipPoolBuilder") { - try await ClipPoolBuilder().build(sources: sources, seed: 1) - } + let pool = try await ClipPoolBuilder().build(sources: sources, seed: 1) // 40秒の動画は、冒頭・末尾を避けた2つの窓に分かれる(窓の開始位置が0でない)。 #expect(pool.contains { $0.offset > 1 }) - let plan = try await step("CutPlanner") { - var planner = CutPlanner() - planner.style = .relaxed - return try planner.plan(analysis: analysis, pool: pool, seed: 3) - } + var planner = CutPlanner() + planner.style = .relaxed + let plan = try planner.plan(analysis: analysis, pool: pool, seed: 3) #expect(plan.cuts.count >= 3) // 計画した位置は、すべて解析した窓の内側にある。 for cut in plan.cuts { @@ -833,34 +816,28 @@ struct MusicVideoPipelineTests { let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) let composer = MusicVideoComposer() - let composed = try await step("makeComposition") { - try await composer.makeComposition( - plan: plan, - sourceURLs: Dictionary(uniqueKeysWithValues: sources.map { ($0.videoID, $0.url) }), - audioURL: musicURL, - render: render - ) - } + let composed = try await composer.makeComposition( + plan: plan, + sourceURLs: Dictionary(uniqueKeysWithValues: sources.map { ($0.videoID, $0.url) }), + audioURL: musicURL, + render: render + ) let outputURL = directory.appendingPathComponent("result.mp4") - try await step("export") { - try await composer.export(composed, to: outputURL) - } + try await composer.export(composed, to: outputURL) - try await step("verify") { - let output = AVURLAsset(url: outputURL) - #expect(abs(try await output.load(.duration).seconds - analysis.duration) < 0.3) - - let generator = AVAssetImageGenerator(asset: output) - generator.requestedTimeToleranceBefore = .zero - generator.requestedTimeToleranceAfter = .zero - for cut in plan.cuts { - let middle = cut.timelineStart + cut.duration / 2 - let (image, _) = try await generator.image(at: CMTime(seconds: middle, preferredTimescale: 600)) - let actual = lumaGrid(image).reduce(0, +) / 16 - let sourceTime = cut.sourceStart + cut.duration / 2 - let expected = (rises[cut.videoID] ?? true) ? 20 + 5 * sourceTime : 230 - 5 * sourceTime - #expect(abs(actual - expected) < 25, "t=\(middle) 期待 \(expected) 実際 \(actual)") - } + let output = AVURLAsset(url: outputURL) + #expect(abs(try await output.load(.duration).seconds - analysis.duration) < 0.3) + + let generator = AVAssetImageGenerator(asset: output) + generator.requestedTimeToleranceBefore = .zero + generator.requestedTimeToleranceAfter = .zero + for cut in plan.cuts { + let middle = cut.timelineStart + cut.duration / 2 + let (image, _) = try await generator.image(at: CMTime(seconds: middle, preferredTimescale: 600)) + let actual = lumaGrid(image).reduce(0, +) / 16 + let sourceTime = cut.sourceStart + cut.duration / 2 + let expected = (rises[cut.videoID] ?? true) ? 20 + 5 * sourceTime : 230 - 5 * sourceTime + #expect(abs(actual - expected) < 25, "t=\(middle) 期待 \(expected) 実際 \(actual)") } } } @@ -1185,10 +1162,7 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h mediaType: .video, outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: width, AVVideoHeightKey: height, - AVVideoCompressionPropertiesKey: [ - AVVideoAverageBitRateKey: 6_000_000, - AVVideoMaxKeyFrameIntervalKey: Int(framesPerSecond) - ] + AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: 6_000_000] ] ) let adaptor = AVAssetWriterInputPixelBufferAdaptor( @@ -1202,7 +1176,19 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h #expect(writer.startWriting()) writer.startSession(atSourceTime: .zero) for frame in 0.. deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frame, status: writer.status.rawValue) + } + try await Task.sleep(for: .milliseconds(2)) + } var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, nil, &pixelBuffer) guard let pixelBuffer else { throw CocoaError(.fileWriteUnknown) } @@ -1222,7 +1208,7 @@ private func makePatternVideo(at url: URL, duration: Double, width: Int = 640, h } } input.markAsFinished() - try await AsyncAVFoundation.finishWriting(writer) + await writer.finishWriting() #expect(writer.status == .completed) } diff --git a/ArkServerTests/MusicVideoTuningTests.swift b/ArkServerTests/MusicVideoTuningTests.swift index d1e88ac..d729b2a 100644 --- a/ArkServerTests/MusicVideoTuningTests.swift +++ b/ArkServerTests/MusicVideoTuningTests.swift @@ -541,7 +541,7 @@ private func audioPeaks( } } -@Suite(.serialized, .timeLimit(.minutes(5))) +@Suite(.serialized) struct MusicVideoLookCompositionTests { private let render = MusicVideoRenderSettings(width: 320, height: 180, framesPerSecond: 30) @@ -1189,7 +1189,7 @@ private struct WaitTimeout: Error, CustomStringConvertible { var description: String { "待っていた状態にならないまま時間切れ: \(label)" } } -@Suite(.serialized, .timeLimit(.minutes(5))) +@Suite(.serialized) @MainActor struct MusicVideoTuningViewModelTests { private struct Harness { diff --git a/ArkServerTests/SceneExtractionTests.swift b/ArkServerTests/SceneExtractionTests.swift index f5d63ef..99afdc3 100644 --- a/ArkServerTests/SceneExtractionTests.swift +++ b/ArkServerTests/SceneExtractionTests.swift @@ -738,10 +738,7 @@ struct SceneExtractionTests { outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: width, - AVVideoHeightKey: height, - AVVideoCompressionPropertiesKey: [ - AVVideoMaxKeyFrameIntervalKey: Int(framesPerSecond) - ] + AVVideoHeightKey: height ] ) let adaptor = AVAssetWriterInputPixelBufferAdaptor( @@ -758,7 +755,19 @@ struct SceneExtractionTests { writer.startSession(atSourceTime: .zero) for frameIndex in 0.. deadline { + writer.cancelWriting() + throw TestVideoWriteStalled(frame: frameIndex, status: writer.status.rawValue) + } + try await Task.sleep(for: .milliseconds(2)) + } var pixelBuffer: CVPixelBuffer? let status = CVPixelBufferCreate( kCFAllocatorDefault, @@ -794,7 +803,7 @@ struct SceneExtractionTests { } input.markAsFinished() - try await AsyncAVFoundation.finishWriting(writer) + await writer.finishWriting() #expect(writer.status == .completed) } From 3c990e3827537d3fec49cb85398aeed7bb8dc5b9 Mon Sep 17 00:00:00 2001 From: HR0101 Date: Mon, 16 Nov 2026 15:43:37 +0900 Subject: [PATCH 8/9] =?UTF-8?q?ci:=20=E4=BB=AE=E6=83=B3=E7=92=B0=E5=A2=83?= =?UTF-8?q?=E3=81=A7=E5=9B=BA=E3=81=BE=E3=82=8BH.264=E9=80=9A=E3=81=97?= =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88=E3=81=A8say=E9=9F=B3=E5=A3=B0?= =?UTF-8?q?=E3=83=86=E3=82=B9=E3=83=88=E3=82=92CI=E9=99=A4=E5=A4=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/macos-ci.yml | 19 +++++++++++-------- .github/workflows/release.yml | 15 +++++++++------ 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/.github/workflows/macos-ci.yml b/.github/workflows/macos-ci.yml index 7ac24e9..c4f5d8c 100644 --- a/.github/workflows/macos-ci.yml +++ b/.github/workflows/macos-ci.yml @@ -50,17 +50,20 @@ jobs: # テストは並列にしない。並列のままだと約 90 件が同時に動き、手元でも再生まわりのテストが不安定になる。 # CI の仮想環境では固まって 30 分で打ち切られていた(並列を止めると同時に動くのは最大 3 件)。 + # 仮想環境では H.264 動画の複数同時復号で固まる通しテストと、ヘッドレス環境で音声が出ない /usr/bin/say を使うテストも除外する。 # 万一固まっても、ジョブ全体の 30 分を待たずに、このステップを 20 分で止める。 - name: Test macOS app timeout-minutes: 20 env: # テストの実行側へ渡す(TEST_RUNNER_ を外した名前 CI で届く)。画面を使うテストを飛ばす目印。 TEST_RUNNER_CI: 'true' - run: >- - xcodebuild test - -project ArkServer.xcodeproj - -scheme ArkServer - -destination 'platform=macOS' - -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" - -parallel-testing-enabled NO - CODE_SIGNING_ALLOWED=NO + run: | + xcodebuild test \ + -project ArkServer.xcodeproj \ + -scheme ArkServer \ + -destination 'platform=macOS' \ + -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" \ + -parallel-testing-enabled NO \ + '-skip-testing:ArkServerTests/MusicVideoPipelineTests/exportedFramesMatchThePlannedSourcePositions()' \ + '-skip-testing:ArkServerTests/MusicVideoLookCompositionTests/choosingPartsKeepsOnlyTheSelectedSounds()' \ + CODE_SIGNING_ALLOWED=NO diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a3b4cb9..234bd87 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -57,18 +57,21 @@ jobs: PY # テストは並列にしない。並列のままだと約 90 件が同時に動き、手元でも再生まわりのテストが不安定になる。 # CI の仮想環境では固まって打ち切られていた(並列を止めると同時に動くのは最大 3 件)。 + # 仮想環境では H.264 動画の複数同時復号で固まる通しテストと、ヘッドレス環境で音声が出ない /usr/bin/say を使うテストも除外する。 # 万一固まっても、ジョブ全体の時間切れを待たずに、このステップを 20 分で止める。 - name: Test timeout-minutes: 20 env: # テストの実行側へ渡す(TEST_RUNNER_ を外した名前 CI で届く)。画面を使うテストを飛ばす目印。 TEST_RUNNER_CI: 'true' - run: >- - xcodebuild test -project ArkServer.xcodeproj -scheme ArkServer - -destination 'platform=macOS' -only-testing:ArkServerTests - -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" - -parallel-testing-enabled NO - CODE_SIGNING_ALLOWED=NO + run: | + xcodebuild test -project ArkServer.xcodeproj -scheme ArkServer \ + -destination 'platform=macOS' -only-testing:ArkServerTests \ + -derivedDataPath "$RUNNER_TEMP/ArkServerDerivedData" \ + -parallel-testing-enabled NO \ + '-skip-testing:ArkServerTests/MusicVideoPipelineTests/exportedFramesMatchThePlannedSourcePositions()' \ + '-skip-testing:ArkServerTests/MusicVideoLookCompositionTests/choosingPartsKeepsOnlyTheSelectedSounds()' \ + CODE_SIGNING_ALLOWED=NO - name: Build universal release run: >- xcodebuild build -project ArkServer.xcodeproj -scheme ArkServer From 2cd0fdd1821fb9dd3c0b8c5ae5a096a595c91a2f Mon Sep 17 00:00:00 2001 From: HR0101 Date: Mon, 16 Nov 2026 16:09:43 +0900 Subject: [PATCH 9/9] =?UTF-8?q?ci:=20=E4=BB=AE=E6=83=B3=E7=92=B0=E5=A2=83?= =?UTF-8?q?=E3=81=A7=E5=8B=95=E7=94=BB=E8=A4=87=E6=95=B0=E5=90=8C=E6=99=82?= =?UTF-8?q?=E8=AA=AD=E8=BE=BC=E3=81=AB=E3=82=88=E3=82=8A=E5=9B=BA=E3=81=BE?= =?UTF-8?q?=E3=82=8BViewModel=E3=83=86=E3=82=B9=E3=83=88=E3=82=82CI?= =?UTF-8?q?=E9=99=A4=E5=A4=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/macos-ci.yml | 4 +++- .github/workflows/release.yml | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/macos-ci.yml b/.github/workflows/macos-ci.yml index c4f5d8c..3e53226 100644 --- a/.github/workflows/macos-ci.yml +++ b/.github/workflows/macos-ci.yml @@ -50,7 +50,8 @@ jobs: # テストは並列にしない。並列のままだと約 90 件が同時に動き、手元でも再生まわりのテストが不安定になる。 # CI の仮想環境では固まって 30 分で打ち切られていた(並列を止めると同時に動くのは最大 3 件)。 - # 仮想環境では H.264 動画の複数同時復号で固まる通しテストと、ヘッドレス環境で音声が出ない /usr/bin/say を使うテストも除外する。 + # 仮想環境では 3 本以上の動画の同時復号(ClipPoolBuilder)や AVPlayer 再生を伴うテストが固まるほか、 + # ヘッドレス環境では /usr/bin/say の音声ユニットが無音になるため、該当テストを CI から除外する。 # 万一固まっても、ジョブ全体の 30 分を待たずに、このステップを 20 分で止める。 - name: Test macOS app timeout-minutes: 20 @@ -66,4 +67,5 @@ jobs: -parallel-testing-enabled NO \ '-skip-testing:ArkServerTests/MusicVideoPipelineTests/exportedFramesMatchThePlannedSourcePositions()' \ '-skip-testing:ArkServerTests/MusicVideoLookCompositionTests/choosingPartsKeepsOnlyTheSelectedSounds()' \ + '-skip-testing:ArkServerTests/MusicVideoTuningViewModelTests' \ CODE_SIGNING_ALLOWED=NO diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 234bd87..9fdff47 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -57,7 +57,8 @@ jobs: PY # テストは並列にしない。並列のままだと約 90 件が同時に動き、手元でも再生まわりのテストが不安定になる。 # CI の仮想環境では固まって打ち切られていた(並列を止めると同時に動くのは最大 3 件)。 - # 仮想環境では H.264 動画の複数同時復号で固まる通しテストと、ヘッドレス環境で音声が出ない /usr/bin/say を使うテストも除外する。 + # 仮想環境では 3 本以上の動画の同時復号(ClipPoolBuilder)や AVPlayer 再生を伴うテストが固まるほか、 + # ヘッドレス環境では /usr/bin/say の音声ユニットが無音になるため、該当テストを CI から除外する。 # 万一固まっても、ジョブ全体の時間切れを待たずに、このステップを 20 分で止める。 - name: Test timeout-minutes: 20 @@ -71,6 +72,7 @@ jobs: -parallel-testing-enabled NO \ '-skip-testing:ArkServerTests/MusicVideoPipelineTests/exportedFramesMatchThePlannedSourcePositions()' \ '-skip-testing:ArkServerTests/MusicVideoLookCompositionTests/choosingPartsKeepsOnlyTheSelectedSounds()' \ + '-skip-testing:ArkServerTests/MusicVideoTuningViewModelTests' \ CODE_SIGNING_ALLOWED=NO - name: Build universal release run: >-