Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
chore(integration): take only main's CI and packaging, not its code
Etienne Lescot8b50969b3bfe
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 625966ab3..319a9473b 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -1,406 +1,437 @@-name: Build Electron App--on:- push:- tags:- - "v*"- workflow_dispatch:- inputs:- arch:- description: "macOS architecture to build"- required: true- default: "both"- type: choice- options:- - arm64- - x64- - both- release_tag:- description: "Optional release tag to create or update, e.g. v1.5.0"- required: false- type: string--permissions:- contents: write--concurrency:- group: build-${{ github.ref_name }}-${{ github.event.inputs.release_tag || 'artifacts' }}- cancel-in-progress: false--jobs:- build-windows:- name: Windows installer- runs-on: windows-latest- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: ./.github/actions/setup-- - name: Cache caption assets- uses: actions/cache@v4- with:- path: caption-assets- key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}-- # ponytail: STT is handled by the bundled whisper-stt-server (whisper.cpp- # with native DTW token timestamps). No separate VAD model is fetched- # here. See docs/engineering/stt-spec.md for the full architecture.-- - name: Build Windows app- run: npm run build:win -- --publish never-- - name: Upload Windows installer- uses: actions/upload-artifact@v4- with:- name: openscreen-windows- path: release/**/Openscreen.Setup.*.exe- if-no-files-found: error- retention-days: 30-- build-macos:- name: macOS ${{ matrix.arch }} DMG- runs-on: macos-latest- strategy:- fail-fast: false- matrix:- arch: ${{ fromJSON((github.event_name == 'workflow_dispatch' && github.event.inputs.arch != 'both') && format('["{0}"]', github.event.inputs.arch) || '["arm64", "x64"]') }}- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: ./.github/actions/setup-- - name: Setup Python- uses: actions/setup-python@v5- with:- python-version: "3.11"-- - name: Ensure sharp prebuilt- run: npm rebuild sharp- env:- npm_config_build_from_source: "false"-- - name: Cache caption assets- uses: actions/cache@v4- with:- path: caption-assets- key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}-- # ponytail: STT is handled by the bundled whisper-stt-server (see the- # build-windows comment); no VAD model is fetched here.- - name: Resolve macOS signing- id: signing- env:- MAC_CERTIFICATE_P12: ${{ secrets.MAC_CERTIFICATE_P12 }}- MAC_CERTIFICATE_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}- MAC_CSC_NAME: ${{ secrets.MAC_CSC_NAME }}- APPLE_ID: ${{ secrets.APPLE_ID }}- APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}- APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}- run: |- if [[ -n "$MAC_CERTIFICATE_P12" && -n "$MAC_CERTIFICATE_PASSWORD" && -n "$MAC_CSC_NAME" && -n "$APPLE_ID" && -n "$APPLE_TEAM_ID" && -n "$APPLE_APP_SPECIFIC_PASSWORD" ]]; then- echo "enabled=true" >> "$GITHUB_OUTPUT"- else- echo "enabled=false" >> "$GITHUB_OUTPUT"- fi-- - name: Import code signing certificate- if: steps.signing.outputs.enabled == 'true'- env:- MAC_CERTIFICATE_P12: ${{ secrets.MAC_CERTIFICATE_P12 }}- MAC_CERTIFICATE_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}- run: |- KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain-db"- KEYCHAIN_PASSWORD="$(openssl rand -base64 32)"-- security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"- security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"- security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"-- echo "$MAC_CERTIFICATE_P12" | base64 --decode > "$RUNNER_TEMP/certificate.p12"- security import "$RUNNER_TEMP/certificate.p12" \- -k "$KEYCHAIN_PATH" \- -P "$MAC_CERTIFICATE_PASSWORD" \- -T /usr/bin/codesign \- -T /usr/bin/security-- security set-key-partition-list -S apple-tool:,apple: -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"- security list-keychains -d user -s "$KEYCHAIN_PATH" $(security list-keychains -d user | tr -d '"')- security find-identity -v -p codesigning "$KEYCHAIN_PATH"- rm -f "$RUNNER_TEMP/certificate.p12"-- - name: Build Vite + Electron- run: npx tsc && npx vite build-- - name: Build native macOS helpers- run: npm run build:native:mac- env:- OPENSCREEN_MAC_HELPER_ARCHS: ${{ matrix.arch }}-- - name: Package .app bundle- run: npx electron-builder --mac --${{ matrix.arch }} --dir --publish never- env:- CSC_NAME: ${{ secrets.MAC_CSC_NAME }}- CSC_IDENTITY_AUTO_DISCOVERY: ${{ steps.signing.outputs.enabled == 'true' && 'true' || 'false' }}-- - name: Get version- id: version- run: |- VERSION="$(node -e "console.log(require('./package.json').version)")"- echo "version=$VERSION" >> "$GITHUB_OUTPUT"-- - name: Find .app bundle- id: find_app- run: |- VERSION="${{ steps.version.outputs.version }}"- APP_BUNDLE="$(find "release/${VERSION}" -maxdepth 4 -name "*.app" -type d | head -n1)"- if [[ -z "$APP_BUNDLE" ]]; then- echo "::error::No .app bundle found in release/${VERSION}/"- find "release/${VERSION}" -maxdepth 4 -print || true- exit 1- fi- echo "app_bundle=$APP_BUNDLE" >> "$GITHUB_OUTPUT"-- - name: Verify .app code signature- if: steps.signing.outputs.enabled == 'true'- run: codesign --verify --deep --strict "${{ steps.find_app.outputs.app_bundle }}"-- - name: Create DMG- id: dmg- run: |- VERSION="${{ steps.version.outputs.version }}"- ARCH="${{ matrix.arch }}"- DMG_NAME="Openscreen-Mac-${ARCH}-${VERSION}.dmg"- RELEASE_DIR="release/${VERSION}"- DMG_OUTPUT="${RELEASE_DIR}/${DMG_NAME}"- STAGING="${RELEASE_DIR}/dmg-staging"-- rm -rf "$STAGING"- rm -f "$DMG_OUTPUT"- mkdir -p "$STAGING"- cp -R "${{ steps.find_app.outputs.app_bundle }}" "$STAGING/"- ln -s /Applications "$STAGING/Applications"-- hdiutil create \- -srcfolder "$STAGING" \- -volname "Openscreen" \- -fs HFS+ \- -fsargs "-c c=64,a=16,e=16" \- -format UDBZ \- "$DMG_OUTPUT"-- rm -rf "$STAGING"- echo "dmg_path=$DMG_OUTPUT" >> "$GITHUB_OUTPUT"-- - name: Sign DMG- if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')- run: |- codesign --force \- --sign "${{ secrets.MAC_CSC_NAME }}" \- --timestamp \- "${{ steps.dmg.outputs.dmg_path }}"-- - name: Notarize DMG- if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')- run: |- xcrun notarytool submit "${{ steps.dmg.outputs.dmg_path }}" \- --apple-id "${{ secrets.APPLE_ID }}" \- --team-id "${{ secrets.APPLE_TEAM_ID }}" \- --password "${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}" \- --wait- timeout-minutes: 15-- - name: Staple notarization ticket- if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')- run: xcrun stapler staple "${{ steps.dmg.outputs.dmg_path }}"-- - name: Validate stapled DMG- if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')- run: |- xcrun stapler validate "${{ steps.dmg.outputs.dmg_path }}"- spctl -a -vv -t install "${{ steps.dmg.outputs.dmg_path }}"-- - name: Upload macOS DMG- uses: actions/upload-artifact@v4- with:- name: openscreen-mac-${{ matrix.arch }}- path: ${{ steps.dmg.outputs.dmg_path }}- if-no-files-found: error- retention-days: 30-- - name: Cleanup keychain- if: always() && steps.signing.outputs.enabled == 'true'- run: security delete-keychain "$RUNNER_TEMP/build.keychain-db" || true-- build-linux:- name: Linux packages- runs-on: ubuntu-latest- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: ./.github/actions/setup-- - name: Install pacman build dependencies- run: sudo apt-get update && sudo apt-get install -y libarchive-tools-- - name: Cache caption assets- uses: actions/cache@v4- with:- path: caption-assets- key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}-- # ponytail: no VAD fetch here either (see build-windows comment).- - name: Build Linux app- run: npm run build:linux -- --publish never-- - name: Upload Linux packages- uses: actions/upload-artifact@v4- with:- name: openscreen-linux- path: |- release/**/*.AppImage- release/**/*.zsync- release/**/*.deb- release/**/*.pacman- if-no-files-found: error- retention-days: 30-- publish-release:- name: Publish GitHub release- runs-on: ubuntu-latest- needs:- - build-windows- - build-macos- - build-linux- if: ${{ (github.event_name == 'push' && github.ref_type == 'tag') || (github.event_name == 'workflow_dispatch' && github.event.inputs.release_tag != '') }}- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Resolve release tag- id: release- env:- INPUT_TAG: ${{ github.event.inputs.release_tag }}- run: |- if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then- TAG="${GITHUB_REF_NAME}"- else- TAG="${INPUT_TAG}"- fi-- if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-(rc|beta|alpha)\.[0-9]+)?$ ]]; then- echo "::error::Release tag must look like v1.5.0 or v1.5.0-rc.1; got '${TAG}'"- exit 1- fi-- VERSION="${TAG#v}"- # For an RC tag (e.g. v1.5.0-rc.1) package.json is at the pre-release version- # (1.5.0-rc.1), not the stable version (1.5.0). Compare against the full tag version.- PACKAGE_VERSION="$(node -p 'require("./package.json").version')"- if [[ "$PACKAGE_VERSION" != "$VERSION" ]]; then- echo "::error::package.json version ${PACKAGE_VERSION} does not match ${VERSION} from tag ${TAG}"- exit 1- fi-- if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-(rc|beta|alpha)\.[0-9]+$ ]]; then- PRERELEASE_FLAG="--prerelease"- IS_PRERELEASE="true"- else- PRERELEASE_FLAG=""- IS_PRERELEASE="false"- fi-- # Compute the previous stable tag for auto-generated release notes. We don't use- # GitHub's "most recent prior release by date" because the fork carries re-published- # upstream releases whose published_at is more recent than the fork's own first release.- # For SemVer X.Y.Z: previous is vX.Y.(Z-1) if Z>0, else vX.(Y-1).0, else v(X-1).0.0.- STABLE_VERSION="${VERSION%%-*}"- IFS='.' read -r PX PY PZ <<< "$STABLE_VERSION"- if (( PZ > 0 )); then- NOTES_START_TAG="v${PX}.${PY}.$((PZ - 1))"- elif (( PY > 0 )); then- NOTES_START_TAG="v${PX}.$((PY - 1)).0"- else- NOTES_START_TAG="v$((PX - 1)).0.0"- fi- echo "Computed notes_start_tag=${NOTES_START_TAG} for tag=${TAG}"-- echo "tag=$TAG" >> "$GITHUB_OUTPUT"- echo "version=$VERSION" >> "$GITHUB_OUTPUT"- echo "stable_version=$STABLE_VERSION" >> "$GITHUB_OUTPUT"- echo "is_prerelease=$IS_PRERELEASE" >> "$GITHUB_OUTPUT"- echo "prerelease_flag=$PRERELEASE_FLAG" >> "$GITHUB_OUTPUT"- echo "notes_start_tag=$NOTES_START_TAG" >> "$GITHUB_OUTPUT"-- - name: Download Windows installer- uses: actions/download-artifact@v4- with:- name: openscreen-windows- path: artifacts/windows-- - name: Download macOS arm64 DMG- continue-on-error: true- uses: actions/download-artifact@v4- with:- name: openscreen-mac-arm64- path: artifacts/mac-arm64-- - name: Download macOS x64 DMG- continue-on-error: true- uses: actions/download-artifact@v4- with:- name: openscreen-mac-x64- path: artifacts/mac-x64-- - name: Download Linux packages- uses: actions/download-artifact@v4- with:- name: openscreen-linux- path: artifacts/linux-- - name: Publish release assets- env:- GH_TOKEN: ${{ secrets.OPENSCREEN_RELEASE_TOKEN }}- TAG: ${{ steps.release.outputs.tag }}- PRERELEASE_FLAG: ${{ steps.release.outputs.prerelease_flag }}- NOTES_START_TAG: ${{ steps.release.outputs.notes_start_tag }}- run: |- mapfile -t FILES < <(find artifacts -type f | sort)- if [[ "${#FILES[@]}" -eq 0 ]]; then- echo "::error::No installer artifacts were downloaded"- exit 1- fi-- if gh release view "$TAG" >/dev/null 2>&1; then- gh release upload "$TAG" "${FILES[@]}" --clobber- else- # --notes-start-tag controls which previous tag GitHub compares against- # when auto-generating the release notes. Default behaviour (most recent- # prior release by date) doesn't work for this fork because the v1.4.0- # release in the fork was re-published after v1.5.0, which makes GitHub- # pick v1.4.0 as the "previous" for any v1.5.x release.- # shellcheck disable=SC2086- gh release create "$TAG" "${FILES[@]}" \- --target "$GITHUB_SHA" \- --title "$TAG" \- --generate-notes \- --notes-start-tag "$NOTES_START_TAG" \- $PRERELEASE_FLAG- fi-- if [[ -n "$PRERELEASE_FLAG" ]]; then- gh release edit "$TAG" \- --draft=false \- --latest=false \- --title "$TAG"- else- gh release edit "$TAG" \- --draft=false \- --latest \- --title "$TAG"- fi+name: Build Electron App++on:+ push:+ tags:+ - "v*"+ workflow_dispatch:+ inputs:+ arch:+ description: "macOS architecture to build"+ required: true+ default: "both"+ type: choice+ options:+ - arm64+ - x64+ - both+ release_tag:+ description: "Optional release tag to create or update, e.g. v1.5.0"+ required: false+ type: string++permissions:+ contents: write++concurrency:+ group: build-${{ github.ref_name }}-${{ github.event.inputs.release_tag || 'artifacts' }}+ cancel-in-progress: false++jobs:+ build-windows:+ name: Windows installer+ runs-on: windows-latest+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: ./.github/actions/setup++ - name: Cache caption assets+ uses: actions/cache@v4+ with:+ path: caption-assets+ key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}++ # ponytail: STT is handled by the bundled whisper-stt-server (whisper.cpp+ # with native DTW token timestamps). No separate VAD model is fetched+ # here. See docs/engineering/stt-spec.md for the full architecture.++ - name: Build Windows app+ run: npm run build:win -- --publish never++ - name: Upload Windows installer+ uses: actions/upload-artifact@v4+ with:+ name: openscreen-windows+ path: release/**/Openscreen.Setup.*.exe+ if-no-files-found: error+ retention-days: 30++ build-windows-store:+ name: Windows Store package+ runs-on: windows-latest+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: ./.github/actions/setup++ - name: Cache caption assets+ uses: actions/cache@v4+ with:+ path: caption-assets+ key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}++ # ponytail: STT is handled by the bundled whisper-stt-server (whisper.cpp+ # with native DTW token timestamps). No separate VAD model is fetched+ # here. See docs/engineering/stt-spec.md for the full architecture.++ - name: Build Windows Store package+ run: npm run build:win:store -- --publish never++ - name: Upload Windows Store package+ uses: actions/upload-artifact@v4+ with:+ name: openscreen-windows-store+ path: release/**/Openscreen.Setup.*.appx+ if-no-files-found: error+ retention-days: 30++ build-macos:+ name: macOS ${{ matrix.arch }} DMG+ runs-on: macos-latest+ strategy:+ fail-fast: false+ matrix:+ arch: ${{ fromJSON((github.event_name == 'workflow_dispatch' && github.event.inputs.arch != 'both') && format('["{0}"]', github.event.inputs.arch) || '["arm64", "x64"]') }}+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: ./.github/actions/setup++ - name: Setup Python+ uses: actions/setup-python@v5+ with:+ python-version: "3.11"++ - name: Ensure sharp prebuilt+ run: npm rebuild sharp+ env:+ npm_config_build_from_source: "false"++ - name: Cache caption assets+ uses: actions/cache@v4+ with:+ path: caption-assets+ key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}++ # ponytail: STT is handled by the bundled whisper-stt-server (see the+ # build-windows comment); no VAD model is fetched here.+ - name: Resolve macOS signing+ id: signing+ env:+ MAC_CERTIFICATE_P12: ${{ secrets.MAC_CERTIFICATE_P12 }}+ MAC_CERTIFICATE_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}+ MAC_CSC_NAME: ${{ secrets.MAC_CSC_NAME }}+ APPLE_ID: ${{ secrets.APPLE_ID }}+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}+ run: |+ if [[ -n "$MAC_CERTIFICATE_P12" && -n "$MAC_CERTIFICATE_PASSWORD" && -n "$MAC_CSC_NAME" && -n "$APPLE_ID" && -n "$APPLE_TEAM_ID" && -n "$APPLE_APP_SPECIFIC_PASSWORD" ]]; then+ echo "enabled=true" >> "$GITHUB_OUTPUT"+ else+ echo "enabled=false" >> "$GITHUB_OUTPUT"+ fi++ - name: Import code signing certificate+ if: steps.signing.outputs.enabled == 'true'+ env:+ MAC_CERTIFICATE_P12: ${{ secrets.MAC_CERTIFICATE_P12 }}+ MAC_CERTIFICATE_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}+ run: |+ KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain-db"+ KEYCHAIN_PASSWORD="$(openssl rand -base64 32)"++ security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"+ security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"+ security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"++ echo "$MAC_CERTIFICATE_P12" | base64 --decode > "$RUNNER_TEMP/certificate.p12"+ security import "$RUNNER_TEMP/certificate.p12" \+ -k "$KEYCHAIN_PATH" \+ -P "$MAC_CERTIFICATE_PASSWORD" \+ -T /usr/bin/codesign \+ -T /usr/bin/security++ security set-key-partition-list -S apple-tool:,apple: -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"+ security list-keychains -d user -s "$KEYCHAIN_PATH" $(security list-keychains -d user | tr -d '"')+ security find-identity -v -p codesigning "$KEYCHAIN_PATH"+ rm -f "$RUNNER_TEMP/certificate.p12"++ - name: Build Vite + Electron+ run: npx tsc && npx vite build++ - name: Build native macOS helpers+ run: npm run build:native:mac+ env:+ OPENSCREEN_MAC_HELPER_ARCHS: ${{ matrix.arch }}++ - name: Package .app bundle+ run: npx electron-builder --mac --${{ matrix.arch }} --dir --publish never+ env:+ CSC_NAME: ${{ secrets.MAC_CSC_NAME }}+ CSC_IDENTITY_AUTO_DISCOVERY: ${{ steps.signing.outputs.enabled == 'true' && 'true' || 'false' }}++ - name: Get version+ id: version+ run: |+ VERSION="$(node -e "console.log(require('./package.json').version)")"+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"++ - name: Find .app bundle+ id: find_app+ run: |+ VERSION="${{ steps.version.outputs.version }}"+ APP_BUNDLE="$(find "release/${VERSION}" -maxdepth 4 -name "*.app" -type d | head -n1)"+ if [[ -z "$APP_BUNDLE" ]]; then+ echo "::error::No .app bundle found in release/${VERSION}/"+ find "release/${VERSION}" -maxdepth 4 -print || true+ exit 1+ fi+ echo "app_bundle=$APP_BUNDLE" >> "$GITHUB_OUTPUT"++ - name: Verify .app code signature+ if: steps.signing.outputs.enabled == 'true'+ run: codesign --verify --deep --strict "${{ steps.find_app.outputs.app_bundle }}"++ - name: Create DMG+ id: dmg+ run: |+ VERSION="${{ steps.version.outputs.version }}"+ ARCH="${{ matrix.arch }}"+ DMG_NAME="Openscreen-Mac-${ARCH}-${VERSION}.dmg"+ RELEASE_DIR="release/${VERSION}"+ DMG_OUTPUT="${RELEASE_DIR}/${DMG_NAME}"+ STAGING="${RELEASE_DIR}/dmg-staging"++ rm -rf "$STAGING"+ rm -f "$DMG_OUTPUT"+ mkdir -p "$STAGING"+ cp -R "${{ steps.find_app.outputs.app_bundle }}" "$STAGING/"+ ln -s /Applications "$STAGING/Applications"++ hdiutil create \+ -srcfolder "$STAGING" \+ -volname "Openscreen" \+ -fs HFS+ \+ -fsargs "-c c=64,a=16,e=16" \+ -format UDBZ \+ "$DMG_OUTPUT"++ rm -rf "$STAGING"+ echo "dmg_path=$DMG_OUTPUT" >> "$GITHUB_OUTPUT"++ - name: Sign DMG+ if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')+ run: |+ codesign --force \+ --sign "${{ secrets.MAC_CSC_NAME }}" \+ --timestamp \+ "${{ steps.dmg.outputs.dmg_path }}"++ - name: Notarize DMG+ if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')+ run: |+ xcrun notarytool submit "${{ steps.dmg.outputs.dmg_path }}" \+ --apple-id "${{ secrets.APPLE_ID }}" \+ --team-id "${{ secrets.APPLE_TEAM_ID }}" \+ --password "${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}" \+ --wait+ timeout-minutes: 15++ - name: Staple notarization ticket+ if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')+ run: xcrun stapler staple "${{ steps.dmg.outputs.dmg_path }}"++ - name: Validate stapled DMG+ if: steps.signing.outputs.enabled == 'true' && !contains(github.ref_name, '-')+ run: |+ xcrun stapler validate "${{ steps.dmg.outputs.dmg_path }}"+ spctl -a -vv -t install "${{ steps.dmg.outputs.dmg_path }}"++ - name: Upload macOS DMG+ uses: actions/upload-artifact@v4+ with:+ name: openscreen-mac-${{ matrix.arch }}+ path: ${{ steps.dmg.outputs.dmg_path }}+ if-no-files-found: error+ retention-days: 30++ - name: Cleanup keychain+ if: always() && steps.signing.outputs.enabled == 'true'+ run: security delete-keychain "$RUNNER_TEMP/build.keychain-db" || true++ build-linux:+ name: Linux packages+ runs-on: ubuntu-latest+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: ./.github/actions/setup++ - name: Install pacman build dependencies+ run: sudo apt-get update && sudo apt-get install -y libarchive-tools++ - name: Cache caption assets+ uses: actions/cache@v4+ with:+ path: caption-assets+ key: caption-assets-${{ runner.os }}-${{ hashFiles('scripts/fetch-caption-model.mjs') }}++ # ponytail: no VAD fetch here either (see build-windows comment).+ - name: Build Linux app+ run: npm run build:linux -- --publish never++ - name: Upload Linux packages+ uses: actions/upload-artifact@v4+ with:+ name: openscreen-linux+ path: |+ release/**/*.AppImage+ release/**/*.zsync+ release/**/*.deb+ release/**/*.pacman+ if-no-files-found: error+ retention-days: 30++ publish-release:+ name: Publish GitHub release+ runs-on: ubuntu-latest+ needs:+ - build-windows+ - build-macos+ - build-linux+ if: ${{ (github.event_name == 'push' && github.ref_type == 'tag') || (github.event_name == 'workflow_dispatch' && github.event.inputs.release_tag != '') }}+ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Resolve release tag+ id: release+ env:+ INPUT_TAG: ${{ github.event.inputs.release_tag }}+ run: |+ if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then+ TAG="${GITHUB_REF_NAME}"+ else+ TAG="${INPUT_TAG}"+ fi++ if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-(rc|beta|alpha)\.[0-9]+)?$ ]]; then+ echo "::error::Release tag must look like v1.5.0 or v1.5.0-rc.1; got '${TAG}'"+ exit 1+ fi++ VERSION="${TAG#v}"+ # For an RC tag (e.g. v1.5.0-rc.1) package.json is at the pre-release version+ # (1.5.0-rc.1), not the stable version (1.5.0). Compare against the full tag version.+ PACKAGE_VERSION="$(node -p 'require("./package.json").version')"+ if [[ "$PACKAGE_VERSION" != "$VERSION" ]]; then+ echo "::error::package.json version ${PACKAGE_VERSION} does not match ${VERSION} from tag ${TAG}"+ exit 1+ fi++ if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-(rc|beta|alpha)\.[0-9]+$ ]]; then+ PRERELEASE_FLAG="--prerelease"+ IS_PRERELEASE="true"+ else+ PRERELEASE_FLAG=""+ IS_PRERELEASE="false"+ fi++ # Compute the previous stable tag for auto-generated release notes. We don't use+ # GitHub's "most recent prior release by date" because the fork carries re-published+ # upstream releases whose published_at is more recent than the fork's own first release.+ # For SemVer X.Y.Z: previous is vX.Y.(Z-1) if Z>0, else vX.(Y-1).0, else v(X-1).0.0.+ STABLE_VERSION="${VERSION%%-*}"+ IFS='.' read -r PX PY PZ <<< "$STABLE_VERSION"+ if (( PZ > 0 )); then+ NOTES_START_TAG="v${PX}.${PY}.$((PZ - 1))"+ elif (( PY > 0 )); then+ NOTES_START_TAG="v${PX}.$((PY - 1)).0"+ else+ NOTES_START_TAG="v$((PX - 1)).0.0"+ fi+ echo "Computed notes_start_tag=${NOTES_START_TAG} for tag=${TAG}"++ echo "tag=$TAG" >> "$GITHUB_OUTPUT"+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"+ echo "stable_version=$STABLE_VERSION" >> "$GITHUB_OUTPUT"+ echo "is_prerelease=$IS_PRERELEASE" >> "$GITHUB_OUTPUT"+ echo "prerelease_flag=$PRERELEASE_FLAG" >> "$GITHUB_OUTPUT"+ echo "notes_start_tag=$NOTES_START_TAG" >> "$GITHUB_OUTPUT"++ - name: Download Windows installer+ uses: actions/download-artifact@v4+ with:+ name: openscreen-windows+ path: artifacts/windows++ - name: Download macOS arm64 DMG+ continue-on-error: true+ uses: actions/download-artifact@v4+ with:+ name: openscreen-mac-arm64+ path: artifacts/mac-arm64++ - name: Download macOS x64 DMG+ continue-on-error: true+ uses: actions/download-artifact@v4+ with:+ name: openscreen-mac-x64+ path: artifacts/mac-x64++ - name: Download Linux packages+ uses: actions/download-artifact@v4+ with:+ name: openscreen-linux+ path: artifacts/linux++ - name: Publish release assets+ env:+ GH_TOKEN: ${{ secrets.OPENSCREEN_RELEASE_TOKEN }}+ TAG: ${{ steps.release.outputs.tag }}+ PRERELEASE_FLAG: ${{ steps.release.outputs.prerelease_flag }}+ NOTES_START_TAG: ${{ steps.release.outputs.notes_start_tag }}+ run: |+ mapfile -t FILES < <(find artifacts -type f | sort)+ if [[ "${#FILES[@]}" -eq 0 ]]; then+ echo "::error::No installer artifacts were downloaded"+ exit 1+ fi++ if gh release view "$TAG" >/dev/null 2>&1; then+ gh release upload "$TAG" "${FILES[@]}" --clobber+ else+ # --notes-start-tag controls which previous tag GitHub compares against+ # when auto-generating the release notes. Default behaviour (most recent+ # prior release by date) doesn't work for this fork because the v1.4.0+ # release in the fork was re-published after v1.5.0, which makes GitHub+ # pick v1.4.0 as the "previous" for any v1.5.x release.+ # shellcheck disable=SC2086+ gh release create "$TAG" "${FILES[@]}" \+ --target "$GITHUB_SHA" \+ --title "$TAG" \+ --generate-notes \+ --notes-start-tag "$NOTES_START_TAG" \+ $PRERELEASE_FLAG+ fi++ if [[ -n "$PRERELEASE_FLAG" ]]; then+ gh release edit "$TAG" \+ --draft=false \+ --latest=false \+ --title "$TAG"+ else+ gh release edit "$TAG" \+ --draft=false \+ --latest \+ --title "$TAG"+ fidiff --git a/.gitignore b/.gitignoreindex ea760a81b..ccc431231 100644--- a/.gitignore+++ b/.gitignore@@ -1,106 +1,107 @@-# Logs-logs-*.log-npm-debug.log*-yarn-debug.log*-yarn-error.log*-pnpm-debug.log*-lerna-debug.log*--node_modules-dist-dist-electron-dist-ssr-*.local-.env--# Native helper build outputs-/electron/native/wgc-capture/build/-/electron/native/compositor-view/build/-/electron/native/screencapturekit/build/-/electron/native/screencapturekit/.build/-/electron/native/screencapturekit/.swiftpm/-/electron/native/bin/--# Native macOS generated files-DerivedData/-*.xcuserstate-xcuserdata/--# Editor directories and files-.vscode/*-.zed/-!.vscode/extensions.json-.idea-.DS_Store-*.suo-*.ntvs*-*.njsproj-*.sln-*.sw?-release/**-*.kiro/-.claude/-.worktrees/-# npx electron-builder --mac --win--# Playwright-test-results-playwright-report/---# Vitest browser mode screenshots-__screenshots__/--# shell files-/shell.sh-# Nix-result-result-*-.direnv/--#kilocode-.kilo/--#others--**/*.import--# Auto-caption model + ORT wasm — regenerated at build by scripts/fetch-caption-model.mjs-/caption-assets/--# Native STT artifacts — whisper-stt-server binaries + ggml backend sidecars.-/electron/native/bin/-/electron/native/models/--# Build cache for the native STT server (FetchContent clones + CMake build).-/.cache/--# Vite's dependency cache, moved out of node_modules so concurrent dev servers-# (main checkout + worktrees, which share node_modules via a junction) stop-# re-optimising into each other's cache. See `cacheDir` in vite.config.ts.-/.vite-cache/--# whisper.cpp DTW POC (tools/stt-eval/whispercpp-dtw-poc) — vendored engine-# clone, downloaded GGML models, and generated build/results artifacts.-# See docs/engineering/stt-whispercpp-dtw-poc-plan.md.-/tools/stt-eval/whispercpp-dtw-poc/whisper.cpp/-/tools/stt-eval/whispercpp-dtw-poc/build-cpu/-/tools/stt-eval/whispercpp-dtw-poc/build-vulkan/-/tools/stt-eval/whispercpp-dtw-poc/build-cuda/-/tools/stt-eval/whispercpp-dtw-poc/build-harness/-/tools/stt-eval/whispercpp-dtw-poc/fixtures/*.wav-/tools/stt-eval/whispercpp-dtw-poc/results/--opencode.json-opencode.json--# Frames dumped by `npm run bench:export -- --dumpFrame=N`, for eyes only.-bench-frame-*.png--# POC inputs (real recordings) and outputs — big, and not source.-poc/media/-poc/out/--# cc-delegate worker worktrees/branches + scratch test artifacts.-.cc-delegate/+# Logs+logs+*.log+npm-debug.log*+yarn-debug.log*+yarn-error.log*+pnpm-debug.log*+lerna-debug.log*++node_modules+dist+dist-electron+dist-ssr+*.local+.env++# Native helper build outputs+/electron/native/wgc-capture/build/+/electron/native/compositor-view/build/+/electron/native/screencapturekit/build/+/electron/native/screencapturekit/.build/+/electron/native/screencapturekit/.swiftpm/+/electron/native/bin/++# Native macOS generated files+DerivedData/+*.xcuserstate+xcuserdata/++# Editor directories and files+.vscode/*+.zed/+!.vscode/extensions.json+.idea+.DS_Store+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?+release/**+*.kiro/+.claude/+.worktrees/+# npx electron-builder --mac --win++# Playwright+test-results+playwright-report/+++# Vitest browser mode screenshots+__screenshots__/+.vitest-attachments/++# shell files+/shell.sh+# Nix+result+result-*+.direnv/++#kilocode+.kilo/++#others++**/*.import++# Auto-caption model + ORT wasm — regenerated at build by scripts/fetch-caption-model.mjs+/caption-assets/++# Native STT artifacts — whisper-stt-server binaries + ggml backend sidecars.+/electron/native/bin/+/electron/native/models/++# Build cache for the native STT server (FetchContent clones + CMake build).+/.cache/++# Vite's dependency cache, moved out of node_modules so concurrent dev servers+# (main checkout + worktrees, which share node_modules via a junction) stop+# re-optimising into each other's cache. See `cacheDir` in vite.config.ts.+/.vite-cache/++# whisper.cpp DTW POC (tools/stt-eval/whispercpp-dtw-poc) — vendored engine+# clone, downloaded GGML models, and generated build/results artifacts.+# See docs/engineering/stt-whispercpp-dtw-poc-plan.md.+/tools/stt-eval/whispercpp-dtw-poc/whisper.cpp/+/tools/stt-eval/whispercpp-dtw-poc/build-cpu/+/tools/stt-eval/whispercpp-dtw-poc/build-vulkan/+/tools/stt-eval/whispercpp-dtw-poc/build-cuda/+/tools/stt-eval/whispercpp-dtw-poc/build-harness/+/tools/stt-eval/whispercpp-dtw-poc/fixtures/*.wav+/tools/stt-eval/whispercpp-dtw-poc/results/++opencode.json+opencode.json++# Frames dumped by `npm run bench:export -- --dumpFrame=N`, for eyes only.+bench-frame-*.png++# POC inputs (real recordings) and outputs — big, and not source.+poc/media/+poc/out/++# cc-delegate worker worktrees/branches + scratch test artifacts.+.cc-delegate/diff --git a/package.json b/package.jsonindex c2268af36..c6cd9761a 100644--- a/package.json+++ b/package.json@@ -31,6 +31,7 @@"build:native:win": "node scripts/build-windows-wgc-helper.mjs","build:native:compositor": "node scripts/build-windows-compositor-addon.mjs","build:win": "npm run build:native:win && npm run build:native:compositor && npm run fetch:ffmpeg && tsc && vite build && electron-builder --win --config.npmRebuild=false",+ "build:win:store": "npm run build:native:win && npm run build:native:compositor && npm run fetch:ffmpeg && tsc && vite build && electron-builder --win appx --config.npmRebuild=false","build:linux": "tsc && vite build && electron-builder --linux AppImage deb pacman --config.npmRebuild=false","build:whisper-binaries": "bash scripts/build-whisper-stt.sh","test": "vitest --run",diff --git a/src/components/video-editor/types.test.ts b/src/components/video-editor/types.test.tsdeleted file mode 100644index bd9738744..000000000--- a/src/components/video-editor/types.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { describe, expect, it } from "vitest";-import { createTextAnnotationRegion, resolveTextAnnotationContent } from "./types";--// Regression coverage for #127: a freshly created text annotation must start with-// truly empty content so the properties panel's placeholder shows and typing-// replaces rather than appends to baked-in text.-describe("createTextAnnotationRegion", () => {- it("starts with empty content, not a baked-in placeholder string", () => {- const region = createTextAnnotationRegion({- id: "annotation-1",- startMs: 1000,- endMs: 2000,- zIndex: 1,- });-- expect(region.content).toBe("");- expect(region.type).toBe("text");- });-});--describe("resolveTextAnnotationContent", () => {- it("falls back to empty content when no prior text was stored", () => {- expect(resolveTextAnnotationContent(undefined)).toBe("");- });-- it("preserves existing text content when converting an existing region to text", () => {- expect(resolveTextAnnotationContent("hello world")).toBe("hello world");- });-});diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.tsindex cabf28800..9fc45ab0d 100644--- a/src/components/video-editor/types.ts+++ b/src/components/video-editor/types.ts@@ -345,37 +345,6 @@ export const DEFAULT_ANNOTATION_STYLE: AnnotationTextStyle = {textAnimation: "none",};-/**- * A freshly created text annotation starts with no content: the properties panel's- * textarea has a real `placeholder` attribute for the empty-state hint, so the- * actual value must be empty for it to show and for typing to replace rather than- * append to baked-in text (see #127).- */-export function createTextAnnotationRegion(params: {- id: string;- startMs: number;- endMs: number;- zIndex: number;-}): AnnotationRegion {- return {- id: params.id,- startMs: params.startMs,- endMs: params.endMs,- type: "text",- content: "",- position: { ...DEFAULT_ANNOTATION_POSITION },- size: { ...DEFAULT_ANNOTATION_SIZE },- style: { ...DEFAULT_ANNOTATION_STYLE },- zIndex: params.zIndex,- };-}--/** Resolves the content for a region whose type is being switched to "text" -- same- * empty-by-default rule as a freshly created one when no prior text was stored. */-export function resolveTextAnnotationContent(existingTextContent?: string): string {- return existingTextContent || "";-}-export const DEFAULT_FIGURE_DATA: FigureData = {arrowDirection: "right",color: "#34B27B",diff --git a/src/components/video-editor/videoPlayback/rafCoalescer.test.ts b/src/components/video-editor/videoPlayback/rafCoalescer.test.tsdeleted file mode 100644index 6f896081a..000000000--- a/src/components/video-editor/videoPlayback/rafCoalescer.test.ts+++ /dev/null@@ -1,97 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { createRafCoalescer } from "./rafCoalescer";--describe("createRafCoalescer", () => {- let rafCallbacks: FrameRequestCallback[];- let nextRafId: number;-- beforeEach(() => {- rafCallbacks = [];- nextRafId = 1;- vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {- rafCallbacks.push(cb);- return nextRafId++;- });- vi.stubGlobal("cancelAnimationFrame", (id: number) => {- // Mark the callback as a no-op instead of removing it, to mirror the- // browser's index-stable semantics.- const index = id - 1;- if (rafCallbacks[index]) {- rafCallbacks[index] = () => {- // Cancelled: no-op.- };- }- });- });-- afterEach(() => {- vi.unstubAllGlobals();- });-- function flushOneFrame(timeMs = 0) {- const callbacks = rafCallbacks;- rafCallbacks = [];- for (const cb of callbacks) cb(timeMs);- }-- it("does not call flush until an animation frame runs", () => {- const flush = vi.fn();- const coalescer = createRafCoalescer<number>(flush);-- coalescer.schedule(1);-- expect(flush).not.toHaveBeenCalled();- });-- it("collapses multiple schedule calls within the same frame into a single flush", () => {- const flush = vi.fn();- const coalescer = createRafCoalescer<number>(flush);-- coalescer.schedule(1);- coalescer.schedule(2);- coalescer.schedule(3);-- flushOneFrame();-- expect(flush).toHaveBeenCalledTimes(1);- expect(flush).toHaveBeenCalledWith(3);- });-- it("schedules a fresh frame for values reported after the previous frame flushed", () => {- const flush = vi.fn();- const coalescer = createRafCoalescer<number>(flush);-- coalescer.schedule(1);- flushOneFrame();- coalescer.schedule(2);- flushOneFrame();-- expect(flush).toHaveBeenCalledTimes(2);- expect(flush).toHaveBeenNthCalledWith(1, 1);- expect(flush).toHaveBeenNthCalledWith(2, 2);- });-- it("cancel() prevents a pending flush from firing", () => {- const flush = vi.fn();- const coalescer = createRafCoalescer<number>(flush);-- coalescer.schedule(1);- coalescer.cancel();- flushOneFrame();-- expect(flush).not.toHaveBeenCalled();- });-- it("a schedule() call after cancel() still flushes on the next frame", () => {- const flush = vi.fn();- const coalescer = createRafCoalescer<number>(flush);-- coalescer.schedule(1);- coalescer.cancel();- coalescer.schedule(2);- flushOneFrame();-- expect(flush).toHaveBeenCalledTimes(1);- expect(flush).toHaveBeenCalledWith(2);- });-});diff --git a/src/components/video-editor/videoPlayback/rafCoalescer.ts b/src/components/video-editor/videoPlayback/rafCoalescer.tsdeleted file mode 100644index be0b2f1a9..000000000--- a/src/components/video-editor/videoPlayback/rafCoalescer.ts+++ /dev/null@@ -1,41 +0,0 @@-/**- * Coalesces rapid-fire calls into at most one flush per animation frame.- *- * Used so a ref-backed value can be updated synchronously on every call (cheap),- * while an expensive side effect — e.g. a React state commit — is deferred to- * once per frame. Without this, a burst of calls within the same frame (many- * `seeking` events fired while dragging the timeline playhead) would otherwise- * force one state commit per call, saturating the main thread and making both- * the drag and the playhead's own rendering feel laggy.- */-export function createRafCoalescer<T>(flush: (value: T) => void) {- let pendingValue: T | undefined;- let hasPending = false;- let rafId: number | null = null;-- const schedule = (value: T) => {- pendingValue = value;- hasPending = true;- if (rafId !== null) return;- rafId = requestAnimationFrame(() => {- rafId = null;- if (hasPending) {- hasPending = false;- const valueToFlush = pendingValue as T;- pendingValue = undefined;- flush(valueToFlush);- }- });- };-- const cancel = () => {- if (rafId !== null) {- cancelAnimationFrame(rafId);- rafId = null;- }- hasPending = false;- pendingValue = undefined;- };-- return { schedule, cancel };-}diff --git a/src/components/video-editor/videoPlayback/zoomRegionUtils.test.ts b/src/components/video-editor/videoPlayback/zoomRegionUtils.test.tsdeleted file mode 100644index d5d58cbf4..000000000--- a/src/components/video-editor/videoPlayback/zoomRegionUtils.test.ts+++ /dev/null@@ -1,59 +0,0 @@-import { describe, expect, it } from "vitest";-import type { CursorTelemetryPoint, ZoomRegion } from "../types";-import { DEFAULT_ZOOM_DEPTH, ZOOM_DEPTH_SCALES } from "../types";-import { findDominantRegion } from "./zoomRegionUtils";--/**- * Regression coverage for issue #72: an auto-placed zoom region must pan to follow- * the cursor for its whole span, not freeze at the focus point captured when the- * region was created/suggested.- */-describe("findDominantRegion — auto-zoom cursor following", () => {- const baseRegion: ZoomRegion = {- id: "zoom-1",- startMs: 0,- endMs: 4000,- depth: DEFAULT_ZOOM_DEPTH,- customScale: ZOOM_DEPTH_SCALES[DEFAULT_ZOOM_DEPTH],- // The static focus captured at suggestion time (e.g. the dwell centroid) — should- // be ignored in favor of the live cursor position once focusMode is "auto". Kept- // within the depth-3 focus bounds (~0.28-0.72) so clamping doesn't distort assertions.- focus: { cx: 0.35, cy: 0.5 },- focusMode: "auto",- source: "auto",- };-- // Cursor sweeps steadily from the left edge to the right edge across the region.- const movingTelemetry: CursorTelemetryPoint[] = [- { timeMs: 0, cx: 0.1, cy: 0.5 },- { timeMs: 2000, cx: 0.5, cy: 0.5 },- { timeMs: 4000, cx: 0.9, cy: 0.5 },- ];-- it("tracks the cursor across the region instead of freezing at the initial focus", () => {- const early = findDominantRegion([baseRegion], 200, { cursorTelemetry: movingTelemetry });- const mid = findDominantRegion([baseRegion], 2000, { cursorTelemetry: movingTelemetry });- const late = findDominantRegion([baseRegion], 3800, { cursorTelemetry: movingTelemetry });-- expect(early.region).not.toBeNull();- expect(mid.region).not.toBeNull();- expect(late.region).not.toBeNull();-- // The focus must move meaningfully between samples (cursor-following), not stay pinned.- expect(mid.region?.focus.cx).toBeGreaterThan(early.region?.focus.cx ?? 0);- expect(late.region?.focus.cx).toBeGreaterThan(mid.region?.focus.cx ?? 0);-- // And it must not equal the static creation-time focus baked into the region.- expect(mid.region?.focus.cx).not.toBeCloseTo(baseRegion.focus.cx, 2);- });-- it("stays frozen at the static focus when focusMode is not auto (manual regions unaffected)", () => {- const manualRegion: ZoomRegion = { ...baseRegion, focusMode: "manual", source: "manual" };-- const early = findDominantRegion([manualRegion], 200, { cursorTelemetry: movingTelemetry });- const late = findDominantRegion([manualRegion], 3800, { cursorTelemetry: movingTelemetry });-- expect(early.region?.focus.cx).toBeCloseTo(manualRegion.focus.cx, 5);- expect(late.region?.focus.cx).toBeCloseTo(manualRegion.focus.cx, 5);- });-});diff --git a/src/lib/exporter/audioEncoder.test.ts b/src/lib/exporter/audioEncoder.test.tsindex e7c7fb9f0..0fb3708c5 100644--- a/src/lib/exporter/audioEncoder.test.ts+++ b/src/lib/exporter/audioEncoder.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { AudioProcessor, downmixPlanarChannelsForExport, mixPlanarSources } from "./audioEncoder";+import { AudioProcessor, downmixPlanarChannelsForExport } from "./audioEncoder";describe("AudioProcessor.selectSupportedExportCodec", () => {afterEach(() => {@@ -70,110 +70,3 @@ describe("downmixPlanarChannelsForExport", () => {expect(Array.from(stereo)).toEqual([0.25, -0.5, 0.25, -0.5]);});});--describe("mixPlanarSources", () => {- it("sums overlapping stereo sources sample-aligned", () => {- const system = {- planes: [new Float32Array([0.1, 0.2, 0.3]), new Float32Array([0.1, 0.2, 0.3])],- startFrame: 0,- };- const mic = {- planes: [new Float32Array([0.2, 0.2, 0.2]), new Float32Array([0.4, 0.4, 0.4])],- startFrame: 0,- };-- const mixed = mixPlanarSources([system, mic], 2, 3);-- expect(mixed).toHaveLength(2);- expect(Array.from(mixed[0])).toEqual([- expect.closeTo(0.3, 5),- expect.closeTo(0.4, 5),- expect.closeTo(0.5, 5),- ]);- expect(Array.from(mixed[1])).toEqual([- expect.closeTo(0.5, 5),- expect.closeTo(0.6, 5),- expect.closeTo(0.7, 5),- ]);- });-- it("recovers a track when the other is silent (the #108 case)", () => {- // System audio captured silence; the microphone track holds the real signal.- const silentSystem = {- planes: [new Float32Array([0, 0, 0]), new Float32Array([0, 0, 0])],- startFrame: 0,- };- const mic = {- planes: [new Float32Array([0.5, -0.5, 0.25]), new Float32Array([0.5, -0.5, 0.25])],- startFrame: 0,- };-- const mixed = mixPlanarSources([silentSystem, mic], 2, 3);-- expect(Array.from(mixed[0])).toEqual([- expect.closeTo(0.5, 5),- expect.closeTo(-0.5, 5),- expect.closeTo(0.25, 5),- ]);- });-- it("aligns each source at its startFrame offset", () => {- const early = { planes: [new Float32Array([1, 1])], startFrame: 0 };- // Mic packets often start slightly after the video (source start_time > 0).- const late = { planes: [new Float32Array([0.5, 0.5])], startFrame: 2 };-- const mixed = mixPlanarSources([early, late], 1, 4);-- expect(Array.from(mixed[0])).toEqual([- expect.closeTo(1, 5),- expect.closeTo(1, 5),- expect.closeTo(0.5, 5),- expect.closeTo(0.5, 5),- ]);- });-- it("discards samples before frame zero from a negative startFrame (AAC preroll)", () => {- // AAC preroll gives the first decoded frame a negative timestamp, so the source's- // startFrame is signed. The preroll samples (timeline < 0) must be dropped while- // the real timestamp-zero sample keeps its true offset.- const withPreroll = {- planes: [new Float32Array([0.9, 0.5, 0.5])],- startFrame: -2,- };-- const mixed = mixPlanarSources([withPreroll], 1, 2);-- // Frames -2 and -1 (0.9, 0.5) are discarded; frame 0 keeps the real sample.- expect(Array.from(mixed[0])).toEqual([expect.closeTo(0.5, 5), expect.closeTo(0, 5)]);- });-- it("upmixes a mono source to stereo before mixing", () => {- const mono = { planes: [new Float32Array([0.3, 0.3])], startFrame: 0 };- const stereo = {- planes: [new Float32Array([0.1, 0.1]), new Float32Array([0.2, 0.2])],- startFrame: 0,- };-- const mixed = mixPlanarSources([mono, stereo], 2, 2);-- expect(Array.from(mixed[0])).toEqual([expect.closeTo(0.4, 5), expect.closeTo(0.4, 5)]);- expect(Array.from(mixed[1])).toEqual([expect.closeTo(0.5, 5), expect.closeTo(0.5, 5)]);- });-- it("clamps the summed signal to [-1, 1] to avoid overflow", () => {- const a = { planes: [new Float32Array([0.8, -0.8])], startFrame: 0 };- const b = { planes: [new Float32Array([0.8, -0.8])], startFrame: 0 };-- const mixed = mixPlanarSources([a, b], 1, 2);-- expect(Array.from(mixed[0])).toEqual([1, -1]);- });-- it("ignores samples that fall beyond the mixed length", () => {- const source = { planes: [new Float32Array([0.5, 0.5, 0.5])], startFrame: 1 };-- const mixed = mixPlanarSources([source], 1, 2);-- expect(Array.from(mixed[0])).toEqual([expect.closeTo(0, 5), expect.closeTo(0.5, 5)]);- });-});diff --git a/src/lib/exporter/audioEncoder.ts b/src/lib/exporter/audioEncoder.tsindex f3ffc7d65..506f21c17 100644--- a/src/lib/exporter/audioEncoder.ts+++ b/src/lib/exporter/audioEncoder.ts@@ -1,4 +1,4 @@-import { AVMediaType, type WebAVStream, WebDemuxer } from "web-demuxer";+import { WebDemuxer } from "web-demuxer";import {MAX_NATIVE_PLAYBACK_RATE,type SpeedRegion,@@ -133,71 +133,6 @@ function getStereoDownmixWeights(sourceChannels: number) {};}-/** One decoded audio source to be mixed: its per-channel PCM and where it starts on the timeline. */-export interface PlanarAudioSource {- /** Per-channel planar samples (`channels[c][frame]`). */- planes: Float32Array[];- /** Timeline sample offset of this source's first sample (from the stream's start_time). */- startFrame: number;-}--/**- * Mixes several decoded audio sources into a single planar buffer.- *- * Native macOS recordings write system audio and the microphone as two separate- * tracks in the same file. The exporter historically decoded only the one track- * FFmpeg's `av_find_best_stream` selects — which, when both tracks are marked- * default, is the first (system) track. If nothing was playing that track is- * silent, so the mic was dropped from the export (issue #108). Mixing every audio- * source together mirrors the browser recorder, which already blends system + mic- * into one track before encoding.- *- * Each source is first downmixed to `targetChannels`, then summed sample-aligned at- * its `startFrame`. The result is hard-clamped to [-1, 1] so a loud overlap can't wrap- * or overflow the encoder. Hard clipping (rather than a 1/N gain pre-sum or soft-knee- * limiter) can add harmonic distortion when two sources are simultaneously near unity —- * an acceptable trade-off for a screen recorder, where keeping both tracks at full level- * matters more than headroom. Sources of differing lengths and offsets are supported;- * samples past `totalFrames` are dropped.- */-export function mixPlanarSources(- sources: PlanarAudioSource[],- targetChannels: number,- totalFrames: number,-): Float32Array[] {- const mixed = Array.from({ length: targetChannels }, () => new Float32Array(totalFrames));-- for (const source of sources) {- const frameCount = source.planes[0]?.length ?? 0;- if (frameCount === 0) continue;-- // Reuse the export downmix so mono→stereo, surround→stereo, etc. match the- // single-track path exactly. Output is planar-concatenated: [ch0…, ch1…].- const downmixed = downmixPlanarChannelsForExport(source.planes, targetChannels);-- for (let channel = 0; channel < targetChannels; channel++) {- const target = mixed[channel];- const base = channel * frameCount;- for (let frame = 0; frame < frameCount; frame++) {- const outFrame = source.startFrame + frame;- if (outFrame < 0) continue;- if (outFrame >= totalFrames) break;- target[outFrame] += downmixed[base + frame];- }- }- }-- for (const channel of mixed) {- for (let frame = 0; frame < channel.length; frame++) {- const sample = channel[frame];- if (sample > 1) channel[frame] = 1;- else if (sample < -1) channel[frame] = -1;- }- }-- return mixed;-}-export function downmixPlanarChannelsForExport(sourcePlanes: Float32Array[],targetChannels: number,@@ -291,277 +226,6 @@ export class AudioProcessor {);}- /** All audio streams in the source, in container order. Empty on failure. */- private static async listAudioStreams(demuxer: WebDemuxer): Promise<WebAVStream[]> {- try {- const info = await demuxer.getMediaInfo();- return info.streams.filter((s) => s.codec_type_string === "audio");- } catch {- return [];- }- }-- /**- * Fully decodes one specific audio stream to contiguous planar PCM. Unlike- * `demuxer.read("audio")`/`getDecoderConfig("audio")` — which resolve to the- * single stream `av_find_best_stream` picks — this targets a stream by its- * container index, so each track of a multi-track recording can be decoded- * independently and then mixed. Returns null when the stream can't be decoded.- */- private async decodeAudioStreamToPlanes(- demuxer: WebDemuxer,- stream: WebAVStream,- readEndSec: number | undefined,- ): Promise<(PlanarAudioSource & { sampleRate: number; numberOfChannels: number }) | null> {- const config: AudioDecoderConfig = {- codec: stream.codec_string || "",- sampleRate: stream.sample_rate,- numberOfChannels: stream.channels,- description: stream.extradata && stream.extradata.length > 0 ? stream.extradata : undefined,- };- if (!config.codec || !config.sampleRate || !config.numberOfChannels) return null;-- const support = await AudioDecoder.isConfigSupported(config);- if (!support.supported) {- console.warn(- `[AudioProcessor] Audio codec not supported for stream ${stream.index}:`,- config.codec,- );- return null;- }-- const decoded: AudioData[] = [];- const decoder = new AudioDecoder({- output: (data: AudioData) => decoded.push(data),- error: (e: DOMException) => console.error("[AudioProcessor] Decode error:", e),- });- decoder.configure(config);-- const safeReadEnd =- typeof readEndSec === "number" && Number.isFinite(readEndSec) ? Math.max(0, readEndSec) : 0;- const packetStream = demuxer.readAVPacket(- 0,- safeReadEnd,- AVMediaType.AVMEDIA_TYPE_AUDIO,- stream.index,- );- const reader = packetStream.getReader();- try {- while (!this.cancelled) {- const { done, value: packet } = await reader.read();- if (done || !packet) break;- decoder.decode(- new EncodedAudioChunk({- type: packet.keyframe === 1 ? "key" : "delta",- timestamp: Math.round(packet.timestamp * 1_000_000),- duration: Math.round(packet.duration * 1_000_000),- data: packet.data,- }),- );- while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- }- } finally {- try {- await reader.cancel();- } catch {- /* reader already closed */- }- }-- if (decoder.state === "configured") {- if (!this.cancelled) await decoder.flush();- decoder.close();- }-- if (this.cancelled || decoded.length === 0) {- for (const d of decoded) d.close();- return null;- }-- // Decode order is normally monotonic; sort defensively so timeline placement- // stays correct even if the decoder emits out of order.- decoded.sort((a, b) => a.timestamp - b.timestamp);- const sampleRate = decoded[0].sampleRate;- const numberOfChannels = decoded[0].numberOfChannels;- // Absolute timeline position of this stream's first sample (mic tracks often- // start slightly after the video, e.g. start_time ~0.17s), so mixing keeps- // every track locked to the same source-time origin the video uses. Kept signed:- // AAC preroll carries a negative timestamp, and clamping it to zero would land the- // preroll and the real timestamp-zero frame on the same offset. mixPlanarSources()- // discards frames before zero, so the signed origin stays correct.- const startFrame = Math.round((decoded[0].timestamp / 1_000_000) * sampleRate);-- let totalFrames = 0;- for (const d of decoded) {- const frameOffset =- Math.round((d.timestamp / 1_000_000) * sampleRate) - startFrame + d.numberOfFrames;- if (frameOffset > totalFrames) totalFrames = frameOffset;- }-- const planes = Array.from({ length: numberOfChannels }, () => new Float32Array(totalFrames));- for (const d of decoded) {- const at = Math.max(0, Math.round((d.timestamp / 1_000_000) * sampleRate) - startFrame);- const room = totalFrames - at;- if (room > 0) {- const take = Math.min(d.numberOfFrames, room);- for (let c = 0; c < numberOfChannels; c++) {- const temp = new Float32Array(d.numberOfFrames);- d.copyTo(temp, { format: "f32-planar", planeIndex: c });- planes[c].set(temp.subarray(0, take), at);- }- }- d.close();- }-- return { planes, startFrame, sampleRate, numberOfChannels };- }-- /**- * Decodes every audio stream and mixes them into one planar timeline (see- * {@link mixPlanarSources}). Returns null when there is at most one audio stream- * (callers keep the existing single-stream fast path) or when the streams can't- * be mixed (e.g. mismatched sample rates — never the case for native captures,- * which are all 48 kHz).- */- private async decodeMixedAudioPlanes(- demuxer: WebDemuxer,- streams: WebAVStream[],- readEndSec: number | undefined,- outputChannels: number,- ): Promise<{ planes: Float32Array[]; sampleRate: number; numberOfChannels: number } | null> {- if (streams.length < 2) return null;-- const sources: Array<PlanarAudioSource & { sampleRate: number }> = [];- for (const stream of streams) {- if (this.cancelled) return null;- const decoded = await this.decodeAudioStreamToPlanes(demuxer, stream, readEndSec);- if (decoded) sources.push(decoded);- }-- if (sources.length === 0) return null;- // If only one of several streams decoded, keep it rather than falling back to the- // demuxer's best stream — that fallback can re-select the stream that just failed- // to decode and export silence. mixPlanarSources() handles a single source fine.-- const sampleRate = sources[0].sampleRate;- if (sources.some((s) => s.sampleRate !== sampleRate)) {- console.warn(- `[AudioProcessor] Audio streams differ in sample rate; skipping mix (rates: ${sources- .map((s) => s.sampleRate)- .join(", ")}Hz)`,- );- return null;- }-- const channels = Math.min(2, Math.max(1, outputChannels || 2));- let totalFrames = 0;- for (const s of sources) {- const end = s.startFrame + (s.planes[0]?.length ?? 0);- if (end > totalFrames) totalFrames = end;- }- if (totalFrames === 0) return null;-- const planes = mixPlanarSources(- sources.map((s) => ({ planes: s.planes, startFrame: s.startFrame })),- channels,- totalFrames,- );- console.log(- `[AudioProcessor] Mixed ${sources.length} audio tracks (${totalFrames} frames @ ${sampleRate}Hz)`,- );- return { planes, sampleRate, numberOfChannels: channels };- }-- /**- * Encodes a pre-mixed planar timeline into the muxer, applying the same trim- * skipping + timestamp remap the single-stream trim-only path uses. Blocks are a- * single AAC frame wide so trim boundaries land at the same granularity.- */- private async encodeMixedPlanarTimeline(- mixed: { planes: Float32Array[]; sampleRate: number; numberOfChannels: number },- muxer: VideoMuxer,- sortedTrims: TrimRegion[],- exportCodec: ExportAudioCodec,- ): Promise<void> {- const { planes, sampleRate } = mixed;- const totalFrames = planes[0]?.length ?? 0;- if (totalFrames === 0) return;-- const outputSampleRate = exportCodec.sampleRate || sampleRate;- const outputChannels = exportCodec.numberOfChannels || mixed.numberOfChannels;-- const encodeConfig: AudioEncoderConfig = {- codec: exportCodec.encoderCodec,- sampleRate: outputSampleRate,- numberOfChannels: outputChannels,- bitrate: AUDIO_BITRATE,- };- const encodeSupport = await AudioEncoder.isConfigSupported(encodeConfig);- if (!encodeSupport.supported) {- console.warn(`[AudioProcessor] ${exportCodec.label} encoding not supported, skipping audio`);- return;- }-- const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];- const encoder = new AudioEncoder({- output: (chunk: EncodedAudioChunk, meta?: EncodedAudioChunkMetadata) => {- encodedChunks.push({ chunk, meta });- },- error: (e: DOMException) => console.error("[AudioProcessor] Encode error:", e),- });- encoder.configure(encodeConfig);-- // One AAC frame per block so trim skipping matches the packet granularity of- // the single-stream path.- const BLOCK_FRAMES = 1024;- for (let start = 0; start < totalFrames && !this.cancelled; start += BLOCK_FRAMES) {- const count = Math.min(BLOCK_FRAMES, totalFrames - start);- const timestampMs = (start / sampleRate) * 1000;- if (this.isInTrimRegion(timestampMs, sortedTrims)) continue;-- const trimOffsetMs = this.computeTrimOffset(timestampMs, sortedTrims);- const adjustedTimestampUs = Math.max(- 0,- Math.round((start / sampleRate - trimOffsetMs / 1000) * 1_000_000),- );-- const buffer = new Float32Array(count * outputChannels);- for (let c = 0; c < outputChannels; c++) {- const srcPlane = planes[Math.min(c, planes.length - 1)];- buffer.set(srcPlane.subarray(start, start + count), c * count);- }-- const audioData = new AudioData({- format: "f32-planar",- sampleRate: outputSampleRate,- numberOfFrames: count,- numberOfChannels: outputChannels,- timestamp: adjustedTimestampUs,- data: buffer.buffer as ArrayBuffer,- });- encoder.encode(audioData);- audioData.close();-- while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- }-- if (encoder.state === "configured") {- await encoder.flush();- encoder.close();- }-- for (const { chunk, meta } of encodedChunks) {- if (this.cancelled) break;- await muxer.addAudioChunk(chunk, meta);- }-- console.log(`[AudioProcessor] Encoded mixed audio timeline: ${encodedChunks.length} chunks`);- }-/*** Two modes: no speed regions uses the fast WebCodecs trim-only pipeline; speed* regions use the pitch-preserving rendered timeline pipeline.@@ -590,12 +254,7 @@ export class AudioProcessor {if (sortedSpeedRegions.length > 0) {const segments = buildSpeedSegments(validatedDurationSec, sortedTrims, sortedSpeedRegions);- // The real-time capture path plays the file through an <audio> element,- // which decodes only one audio track — so multi-track recordings must take- // the offline WebCodecs path, the only one that can decode every track and- // mix them. (Losing the mic entirely is worse than WSOLA vs real-time.)- const audioStreams = await AudioProcessor.listAudioStreams(demuxer);- if (maxTimelineSpeed(segments) > MAX_NATIVE_PLAYBACK_RATE || audioStreams.length > 1) {+ if (maxTimelineSpeed(segments) > MAX_NATIVE_PLAYBACK_RATE) {await this.renderOfflineTimelineAudio(demuxer,muxer,@@ -634,27 +293,6 @@ export class AudioProcessor {readEndSec?: number,exportCodec?: ExportAudioCodec,): Promise<void> {- // Multi-track recordings (native macOS writes system audio + mic as separate- // tracks) must be mixed — reading only the best stream drops the other track,- // which is how the mic went missing in issue #108. Single-track sources keep- // the original fast path below.- const audioStreams = await AudioProcessor.listAudioStreams(demuxer);- if (audioStreams.length > 1 && exportCodec) {- const mixed = await this.decodeMixedAudioPlanes(- demuxer,- audioStreams,- readEndSec,- exportCodec.numberOfChannels,- );- if (this.cancelled) return;- if (mixed) {- await this.encodeMixedPlanarTimeline(mixed, muxer, sortedTrims, exportCodec);- return;- }- // Mixing unavailable (e.g. only one stream decoded); fall through to the- // single-stream path rather than exporting silence.- }-let audioConfig: AudioDecoderConfig;try {audioConfig = await demuxer.getDecoderConfig("audio");@@ -1010,42 +648,22 @@ export class AudioProcessor {exportCodec: ExportAudioCodec,targetFrameRate: number,): Promise<void> {- // Multi-track sources are decoded and mixed up front, then fed through the same- // segment/WSOLA machinery as a single pre-mixed stream. Single-track sources- // stream through the decoder as before.- const audioStreams = await AudioProcessor.listAudioStreams(demuxer);- const lastSegmentEndSec = segments.length > 0 ? segments[segments.length - 1].endSec : 0;- const mixReadEndSec = lastSegmentEndSec + 0.5;- const mixed =- audioStreams.length > 1- ? await this.decodeMixedAudioPlanes(- demuxer,- audioStreams,- mixReadEndSec,- exportCodec.numberOfChannels,- )- : null;- if (this.cancelled) return;-- let audioConfig: AudioDecoderConfig | null = null;- if (!mixed) {- try {- audioConfig = await demuxer.getDecoderConfig("audio");- } catch {- console.warn("[AudioProcessor] No audio track found, skipping");- return;- }+ let audioConfig: AudioDecoderConfig;+ try {+ audioConfig = await demuxer.getDecoderConfig("audio");+ } catch {+ console.warn("[AudioProcessor] No audio track found, skipping");+ return;+ }- const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);- if (!codecCheck.supported) {- console.warn("[AudioProcessor] Audio codec not supported:", audioConfig.codec);- return;- }+ const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);+ if (!codecCheck.supported) {+ console.warn("[AudioProcessor] Audio codec not supported:", audioConfig.codec);+ return;}- const sampleRate = mixed?.sampleRate || audioConfig?.sampleRate || 48000;- const outputChannels =- exportCodec.numberOfChannels || mixed?.numberOfChannels || audioConfig?.numberOfChannels || 2;+ const sampleRate = audioConfig.sampleRate || 48000;+ const outputChannels = exportCodec.numberOfChannels || audioConfig.numberOfChannels || 2;const outputSampleRate = exportCodec.sampleRate || sampleRate;const encodeConfig: AudioEncoderConfig = {@@ -1194,104 +812,89 @@ export class AudioProcessor {}};- if (mixed) {- // Pre-mixed timeline (multi-track): route it through the same segment/WSOLA- // machinery in source order, in fixed-size chunks. The mixed buffer starts- // at source-time 0 so a chunk's start index is its absolute source sample.- const total = mixed.planes[0]?.length ?? 0;- const CHUNK_FRAMES = 4096;- for (let start = 0; start < total && !this.cancelled; start += CHUNK_FRAMES) {- const count = Math.min(CHUNK_FRAMES, total - start);- const chunkPlanes = mixed.planes.map((p) => p.subarray(start, start + count));- routeFrame(chunkPlanes, start, count);+ // Streaming decode: frames arrive in source order via the decoder callback.+ const pending: AudioData[] = [];+ const decoder = new AudioDecoder({+ output: (data: AudioData) => pending.push(data),+ error: (e: DOMException) => console.error("[AudioProcessor] Decode error:", e),+ });+ decoder.configure(audioConfig);++ const drainPending = async () => {+ while (pending.length > 0) {+ if (this.cancelled) {+ for (const d of pending) d.close();+ pending.length = 0;+ return;+ }+ const data = pending.shift();+ if (!data) continue;+ const frameCount = data.numberOfFrames;+ const sourceChannels = data.numberOfChannels;+ const srcPlanes: Float32Array[] = [];+ for (let c = 0; c < sourceChannels; c++) {+ const plane = new Float32Array(frameCount);+ data.copyTo(plane, { format: "f32-planar", planeIndex: c });+ srcPlanes.push(plane);+ }+ // Raw source timestamps — the same origin the video decoder uses+ // (streamingDecoder), so audio and video stay in one coordinate system.+ // Frames before the first segment start (e.g. negative-timestamp codec+ // preroll, or a leading trim) are correctly discarded by routeFrame.+ const frameStartSample = Math.round((data.timestamp / 1_000_000) * sampleRate);+ data.close();++ // Match source channels through untouched; otherwise downmix (to 1 or 2).+ let planes: Float32Array[];+ if (outputChannels === sourceChannels) {+ planes = srcPlanes;+ } else {+ const downmixed = downmixPlanarChannelsForExport(srcPlanes, outputChannels);+ planes = [];+ for (let c = 0; c < outputChannels; c++) {+ planes.push(downmixed.subarray(c * frameCount, (c + 1) * frameCount));+ }+ }++ routeFrame(planes, frameStartSample, frameCount);flushOutput(false);+while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {await new Promise((resolve) => setTimeout(resolve, 1));}}- } else if (audioConfig) {- // Streaming decode: frames arrive in source order via the decoder callback.- const pending: AudioData[] = [];- const decoder = new AudioDecoder({- output: (data: AudioData) => pending.push(data),- error: (e: DOMException) => console.error("[AudioProcessor] Decode error:", e),- });- decoder.configure(audioConfig);-- const drainPending = async () => {- while (pending.length > 0) {- if (this.cancelled) {- for (const d of pending) d.close();- pending.length = 0;- return;- }- const data = pending.shift();- if (!data) continue;- const frameCount = data.numberOfFrames;- const sourceChannels = data.numberOfChannels;- const srcPlanes: Float32Array[] = [];- for (let c = 0; c < sourceChannels; c++) {- const plane = new Float32Array(frameCount);- data.copyTo(plane, { format: "f32-planar", planeIndex: c });- srcPlanes.push(plane);- }- // Raw source timestamps — the same origin the video decoder uses- // (streamingDecoder), so audio and video stay in one coordinate system.- // Frames before the first segment start (e.g. negative-timestamp codec- // preroll, or a leading trim) are correctly discarded by routeFrame.- const frameStartSample = Math.round((data.timestamp / 1_000_000) * sampleRate);- data.close();-- // Match source channels through untouched; otherwise downmix (to 1 or 2).- let planes: Float32Array[];- if (outputChannels === sourceChannels) {- planes = srcPlanes;- } else {- const downmixed = downmixPlanarChannelsForExport(srcPlanes, outputChannels);- planes = [];- for (let c = 0; c < outputChannels; c++) {- planes.push(downmixed.subarray(c * frameCount, (c + 1) * frameCount));- }- }-- routeFrame(planes, frameStartSample, frameCount);- flushOutput(false);+ };- while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }+ // Read past the last segment's source end (mirrors streamingDecoder's +0.5s+ // window so both paths read the same distance past the boundary).+ const lastSegmentEndSec = segments.length > 0 ? segments[segments.length - 1].endSec : 0;+ const readEndSec = lastSegmentEndSec + 0.5;+ const reader = demuxer.read("audio", 0, readEndSec).getReader();+ try {+ while (!this.cancelled) {+ const { done, value: chunk } = await reader.read();+ if (done || !chunk) break;+ decoder.decode(chunk);+ while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {+ await new Promise((resolve) => setTimeout(resolve, 1));}- };-- // Read past the last segment's source end (mirrors streamingDecoder's +0.5s- // window so both paths read the same distance past the boundary).- const reader = demuxer.read("audio", 0, mixReadEndSec).getReader();+ await drainPending();+ }+ } finally {try {- while (!this.cancelled) {- const { done, value: chunk } = await reader.read();- if (done || !chunk) break;- decoder.decode(chunk);- while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- await drainPending();- }- } finally {- try {- await reader.cancel();- } catch {- /* reader already closed */- }+ await reader.cancel();+ } catch {+ /* reader already closed */}+ }- if (decoder.state === "configured") {- if (!this.cancelled) {- await decoder.flush();- }- decoder.close();+ if (decoder.state === "configured") {+ if (!this.cancelled) {+ await decoder.flush();}- await drainPending();+ decoder.close();}+ await drainPending();if (this.cancelled) {if (encoder.state === "configured") encoder.close();diff --git a/src/lib/exporter/audioMixExport.browser.test.ts b/src/lib/exporter/audioMixExport.browser.test.tsdeleted file mode 100644index e4ca8d224..000000000--- a/src/lib/exporter/audioMixExport.browser.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import { describe, expect, it } from "vitest";-import dualAudioUrl from "../../../tests/fixtures/sample-dual-audio.mp4?url";-import { VideoExporter } from "./videoExporter";--/**- * Regression test for issue #108: native macOS recordings write system audio and- * the microphone as two separate tracks. FFmpeg's `av_find_best_stream` (used by- * web-demuxer) resolves the bare "audio" selector to the first track, so when the- * system-audio track is silent the exporter dropped the mic and produced silence.- *- * The fixture mirrors that layout: track 0 is silent, track 1 is a 440 Hz tone.- * A correct export mixes both, so the output must carry the tone.- */-async function measureAudioRms(blob: Blob): Promise<{ rms: number; hasAudio: boolean }> {- const bytes = await blob.arrayBuffer();- const audioContext = new AudioContext();- try {- const audioBuffer = await audioContext.decodeAudioData(bytes.slice(0));- if (audioBuffer.numberOfChannels === 0 || audioBuffer.length === 0) {- return { rms: 0, hasAudio: false };- }- let sumSquares = 0;- let sampleCount = 0;- for (let channel = 0; channel < audioBuffer.numberOfChannels; channel++) {- const data = audioBuffer.getChannelData(channel);- for (let i = 0; i < data.length; i++) {- sumSquares += data[i] * data[i];- sampleCount++;- }- }- return { rms: Math.sqrt(sumSquares / sampleCount), hasAudio: true };- } finally {- await audioContext.close();- }-}--describe("Multi-track audio export (real browser)", () => {- it("mixes both audio tracks so a silent first track can't drop the mic (#108)", async () => {- const exporter = new VideoExporter({- videoUrl: dualAudioUrl,- width: 320,- height: 180,- frameRate: 15,- bitrate: 1_000_000,- wallpaper: "#1a1a2e",- zoomRegions: [],- showShadow: false,- shadowIntensity: 0,- showBlur: false,- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- });-- const result = await exporter.export();- expect(result.success, result.error).toBe(true);- expect(result.blob).toBeInstanceOf(Blob);-- const { rms, hasAudio } = await measureAudioRms(result.blob!);- expect(hasAudio).toBe(true);- // Silence (the first track alone) sits near 0; the mixed-in 440 Hz tone lifts- // RMS to ~0.08. Threshold sits below the tone's real level but well above the- // noise floor, so a near-silent fallback (the old #108 bug) still fails.- expect(rms).toBeGreaterThan(0.05);- });-- it("mixes both audio tracks through the speed-region (offline) path too", async () => {- const exporter = new VideoExporter({- videoUrl: dualAudioUrl,- width: 320,- height: 180,- frameRate: 15,- bitrate: 1_000_000,- wallpaper: "#1a1a2e",- zoomRegions: [],- // A speed region routes audio through renderOfflineTimelineAudio, a distinct- // mixing branch from the trim-only path exercised above.- speedRegions: [{ id: "speed", startMs: 500, endMs: 1500, speed: 2 }],- showShadow: false,- shadowIntensity: 0,- showBlur: false,- cropRegion: { x: 0, y: 0, width: 1, height: 1 },- });-- const result = await exporter.export();- expect(result.success, result.error).toBe(true);-- const { rms, hasAudio } = await measureAudioRms(result.blob!);- expect(hasAudio).toBe(true);- expect(rms).toBeGreaterThan(0.05);- });-});diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.tsindex 8dd763470..54f4b9f8d 100644--- a/src/lib/exporter/streamingDecoder.ts+++ b/src/lib/exporter/streamingDecoder.ts@@ -67,8 +67,6 @@ export interface DecodedVideoInfo {codec: string;hasAudio: boolean;audioCodec?: string;- /** Number of audio streams in the container (native macOS writes system + mic separately). */- audioStreamCount: number;}type EarlyDecodeEndCheck = {@@ -285,8 +283,7 @@ export class StreamingVideoDecoder {}}- const audioStreams = mediaInfo.streams.filter((s) => s.codec_type_string === "audio");- const audioStream = audioStreams[0];+ const audioStream = mediaInfo.streams.find((s) => s.codec_type_string === "audio");// Scan video packets for the true content boundary; MediaRecorder (especially on// Linux) writes unreliable container durations and packet timestamps are ground truth.@@ -332,7 +329,6 @@ export class StreamingVideoDecoder {codec: videoStream?.codec_string || "unknown",hasAudio: !!audioStream,audioCodec: audioStream?.codec_string,- audioStreamCount: audioStreams.length,};return this.metadata;diff --git a/tests/fixtures/sample-dual-audio.mp4 b/tests/fixtures/sample-dual-audio.mp4deleted file mode 100644index e0a504dd4..000000000Binary files a/tests/fixtures/sample-dual-audio.mp4 and /dev/null differ