Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5267aa35ee | ||
|
|
40792e2779 | ||
|
|
822657972d | ||
|
|
ae71b7bc64 | ||
|
|
e15bbed554 | ||
|
|
65e63c206e | ||
|
|
f104b5ffae | ||
|
|
e4db04fa62 | ||
|
|
e6e7d8cdfd | ||
|
|
c4e9fa1650 | ||
|
|
8210b23d31 | ||
|
|
bd83c10b9b | ||
|
|
e03edad824 | ||
|
|
26d14f7cb0 | ||
|
|
b9f828ae88 | ||
|
|
098a472670 | ||
|
|
780a1ea180 | ||
|
|
917f6a2839 | ||
|
|
2101f1d7f0 | ||
|
|
a561777456 | ||
|
|
b4575c9780 | ||
|
|
0ef1e773bb | ||
|
|
cd88f73f05 | ||
|
|
d1c4ae83eb | ||
|
|
858952929b | ||
|
|
b676ef6c56 | ||
|
|
a9493f4f0e | ||
|
|
fe8d405a56 | ||
|
|
754c54761a | ||
|
|
7ecadffdb1 | ||
|
|
6506f36843 | ||
|
|
97f7508067 | ||
|
|
a481fc1000 | ||
|
|
b7078448ea | ||
|
|
359a6bf02a | ||
|
|
a5449a1430 | ||
|
|
6182c34448 | ||
|
|
699e73bcd5 | ||
|
|
352aa04d3e | ||
|
|
c81a1f9a97 | ||
|
|
34be331024 | ||
|
|
ceae98b75f | ||
|
|
5328865639 | ||
|
|
f78089edf8 | ||
|
|
c0d8951677 | ||
|
|
2e830d3f97 | ||
|
|
649eaa4cce | ||
|
|
80344a630f | ||
|
|
2a128777f1 | ||
|
|
baf3c41a44 | ||
|
|
f7f4e3a992 | ||
|
|
6890cd8690 | ||
|
|
c84b8b4792 | ||
|
|
3d36ecf094 | ||
|
|
eaa60cc2b5 | ||
|
|
de5234b59f | ||
|
|
69cf5fb8a1 | ||
|
|
a0f153e5ab | ||
|
|
0135318ded | ||
|
|
f4ec6ccf20 | ||
|
|
5f8d263d63 | ||
|
|
242cc8616c | ||
|
|
2ebc1e250d | ||
|
|
5876a602c3 | ||
|
|
79dabaf125 | ||
|
|
65d3d8e471 | ||
|
|
aa230983d5 | ||
|
|
1b9ef3b3b6 | ||
|
|
7ed342b345 | ||
|
|
29c029f04a | ||
|
|
777780926c | ||
|
|
f08fceaee0 | ||
|
|
0ddd0a6c25 | ||
|
|
8a8b4f3a61 | ||
|
|
cdec9d1514 | ||
|
|
9da047de70 | ||
|
|
18835d92dd | ||
|
|
967c25b11d | ||
|
|
877e8880cf | ||
|
|
ac9c236b6b | ||
|
|
df7fa08e40 | ||
|
|
c58013b818 | ||
|
|
b925705173 | ||
|
|
7a0e838017 | ||
|
|
bc55aea701 | ||
|
|
dca51a752a | ||
|
|
0db6eb6f2e | ||
|
|
d1a67828b6 | ||
|
|
048fb77c8c | ||
|
|
a63369c247 | ||
|
|
6d94880c2f | ||
|
|
9c6fcbc841 | ||
|
|
a809cbbcef | ||
|
|
e4b0680158 | ||
|
|
64db84c3e2 | ||
|
|
4a81246986 | ||
|
|
a23c7f215c | ||
|
|
5af3a926d7 | ||
|
|
2679745941 | ||
|
|
4443b76145 | ||
|
|
3a982c2a7a | ||
|
|
e07172ade4 | ||
|
|
c86d40f8dd | ||
|
|
d86e328169 | ||
|
|
02a032d287 | ||
|
|
03651d6c73 | ||
|
|
9b6c12d086 | ||
|
|
c5c7dd614f | ||
|
|
f87d6e5a52 | ||
|
|
c885c0c6bc | ||
|
|
3bf72d7237 | ||
|
|
d07d849fe4 | ||
|
|
e6ffc54c56 | ||
|
|
b5d8ff5332 | ||
|
|
7509077d63 | ||
|
|
cbabdf2151 | ||
|
|
1acc83572e | ||
|
|
b46107cb58 | ||
|
|
1261852514 | ||
|
|
04daf89a20 | ||
|
|
f94b8c6586 | ||
|
|
b4943f8c50 | ||
|
|
2aa084287d | ||
|
|
dcdbbc8483 | ||
|
|
4e6ea5b4c5 | ||
|
|
ede80d225f | ||
|
|
397de2698d | ||
|
|
632d2ec16b | ||
|
|
2c13438d71 | ||
|
|
fe5d6d8d96 | ||
|
|
e2ad28ca32 | ||
|
|
ed183a855e | ||
|
|
5867809560 | ||
|
|
a4a2942546 | ||
|
|
71d644c4ae | ||
|
|
574b8d524f | ||
|
|
94852e49cb | ||
|
|
4a3295b7fd | ||
|
|
ef75887504 | ||
|
|
49d4b433a7 | ||
|
|
5bb8b1b9f2 | ||
|
|
04c0714881 | ||
|
|
5f7925f350 | ||
|
|
226be37f85 | ||
|
|
32c4810c21 | ||
|
|
28bc4a5df8 | ||
|
|
73be8ab1c8 | ||
|
|
4de38f4b17 | ||
|
|
adf732a1a1 | ||
|
|
214a7c13dc | ||
|
|
fcdef343eb | ||
|
|
a4d40486c1 | ||
|
|
338a53a036 | ||
|
|
4da489d4dc | ||
|
|
db18ee4b34 | ||
|
|
764345f021 | ||
|
|
7d6a747aa7 | ||
|
|
422db75b5b | ||
|
|
05a631415e | ||
|
|
fff559da06 | ||
|
|
c87a9060f9 | ||
|
|
ee3c75ba9e | ||
|
|
90c4fe5458 | ||
|
|
97901cba87 | ||
|
|
7f81a0d4fd | ||
|
|
173117602a | ||
|
|
d9130cd932 | ||
|
|
be072365fc | ||
|
|
61f7d33fdf | ||
|
|
3766b2c2d3 | ||
|
|
0dfe013928 | ||
|
|
25c7893a8e | ||
|
|
28ec9cacb2 | ||
|
|
aaf27a7f9e | ||
|
|
0fb0c7fb4c | ||
|
|
f97ab03111 | ||
|
|
3981fac0db | ||
|
|
4a43ae2771 | ||
|
|
c4184c6148 | ||
|
|
87eaafe3c4 | ||
|
|
aee48f6956 | ||
|
|
3d5a1ec966 | ||
|
|
2e4ba352f4 | ||
|
|
31e8c2e1e0 | ||
|
|
96510f8aac | ||
|
|
6e83aeda88 | ||
|
|
7b1c150e18 | ||
|
|
cd8212fb53 | ||
|
|
11f7fd766d | ||
|
|
d80a1ed15a | ||
|
|
f1422feff1 | ||
|
|
d7c0af9ad0 | ||
|
|
87aea49ab6 | ||
|
|
c8ca8a7875 | ||
|
|
d9b365b012 | ||
|
|
05e70ab56d | ||
|
|
f9abcd44fe | ||
|
|
3cad91736b | ||
|
|
632d66f6ac | ||
|
|
ed843b4b89 | ||
|
|
27596bb919 | ||
|
|
6b7aac3372 | ||
|
|
6af4289289 | ||
|
|
eb8796fa26 | ||
|
|
8fe66f6e36 | ||
|
|
837fdf4031 | ||
|
|
dd09e421bf | ||
|
|
50261398bf | ||
|
|
7632d4bea7 | ||
|
|
30de8be2cd | ||
|
|
536e8e3d2a | ||
|
|
3f9c25fe5e | ||
|
|
fd4291aafb | ||
|
|
8fa91fe444 | ||
|
|
7972743a2f | ||
|
|
6d95e35448 | ||
|
|
86abf3e9da | ||
|
|
0e3c592205 | ||
|
|
5f49dddb4d | ||
|
|
074f92d144 | ||
|
|
6274facc3c | ||
|
|
b08b3b846a | ||
|
|
1059658515 | ||
|
|
d193633a5d | ||
|
|
2b7142bdcd | ||
|
|
44be03d39c | ||
|
|
f9123eb40f | ||
|
|
2025e1f9fd | ||
|
|
6e8320f782 | ||
|
|
bfcd11538e | ||
|
|
72d37f2362 | ||
|
|
e8a99c1108 | ||
|
|
48568fd412 | ||
|
|
320bde7f33 | ||
|
|
868a1469a3 | ||
|
|
43ab5d3246 | ||
|
|
c38f24aee9 | ||
|
|
a5041cb3db | ||
|
|
7143bb380f | ||
|
|
d5df426ab6 | ||
|
|
1d2dea214c | ||
|
|
e07f54921c | ||
|
|
ba112d7aa6 | ||
|
|
28e6e349b3 | ||
|
|
2d30686857 | ||
|
|
ea86ce5a4b | ||
|
|
4cf94683ae | ||
|
|
6c96830033 | ||
|
|
ec1473af5e | ||
|
|
675886673e | ||
|
|
19806d9b54 | ||
|
|
79b75483bd | ||
|
|
78090d8bd6 | ||
|
|
2fe0fdb975 | ||
|
|
930534ee31 | ||
|
|
3b611a1e18 | ||
|
|
120749e442 | ||
|
|
d333ac2382 | ||
|
|
c3ca6e4c49 | ||
|
|
ad6ed04901 | ||
|
|
25e5ea042f | ||
|
|
4462b44e9b | ||
|
|
7df969cb90 | ||
|
|
719f317b5d | ||
|
|
c32806d987 | ||
|
|
86637012dc | ||
|
|
bd7f37a3f6 | ||
|
|
d5c575cbfe | ||
|
|
f29030c3a0 | ||
|
|
f04691d321 | ||
|
|
dbe804f8db | ||
|
|
37e4153602 | ||
|
|
b0b14bcd18 | ||
|
|
7b917462c7 | ||
|
|
791433bceb | ||
|
|
e90835c234 | ||
|
|
8affbb7af6 | ||
|
|
21c4ab430e | ||
|
|
c9dc15b1d8 | ||
|
|
b4967ca075 | ||
|
|
cd1978ee1c | ||
|
|
a5e422d284 | ||
|
|
5a1d378b42 | ||
|
|
19abd7831f | ||
|
|
0d78020fbf | ||
|
|
7e1d5ad4c4 | ||
|
|
94f2daa22e | ||
|
|
075e4aeb32 | ||
|
|
52d70dd97d | ||
|
|
d9b03160f0 | ||
|
|
b11c63f557 | ||
|
|
a75cf5fd35 | ||
|
|
6f39a286d3 | ||
|
|
66b80a33ba | ||
|
|
84b9eac09b | ||
|
|
39788ab64a | ||
|
|
4cd289b4b8 | ||
|
|
d49bd20fa0 | ||
|
|
618251b8eb | ||
|
|
9437956b83 | ||
|
|
f602925896 | ||
|
|
1aecb9d2d2 | ||
|
|
4a5731976a | ||
|
|
8198ea9522 | ||
|
|
e069d30555 | ||
|
|
1aa06ffe90 | ||
|
|
1b29cb3ef7 | ||
|
|
ba22dca9e5 | ||
|
|
b5a9f09f12 | ||
|
|
8bf5dbb379 | ||
|
|
5fc599439e | ||
|
|
27723e6f29 | ||
|
|
a4c444435f | ||
|
|
6292685b5d | ||
|
|
7195702242 | ||
|
|
b459c5150c | ||
|
|
dba292cbfb | ||
|
|
01a5d11ef5 | ||
|
|
5e2bd4efa8 | ||
|
|
b23ba4c839 |
+120
-225
@@ -373,60 +373,26 @@ jobs:
|
||||
macos-ed-signature.txt
|
||||
macos-dmg-size.txt
|
||||
|
||||
build-windows-x64:
|
||||
build-windows:
|
||||
name: Build Windows (${{ matrix.arch }})
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\AppData\Local\Pub\Cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache Windows native dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: build/windows/x64/_deps
|
||||
key: windows-native-x64-${{ hashFiles('windows/CMakeLists.txt') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build Windows x64
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-x64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-x64
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-windows-x64
|
||||
run: .\scripts\upload-symbols.ps1 windows-x64
|
||||
|
||||
- name: Upload x64 build
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x64-build
|
||||
path: build/windows/x64/runner/Release/
|
||||
|
||||
build-windows-arm64:
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-11-arm
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: windows-latest
|
||||
flutter_setup: action
|
||||
native_cache_path: build/windows/x64/_deps
|
||||
- arch: arm64
|
||||
runner: windows-11-arm
|
||||
flutter_setup: git
|
||||
native_cache_path: |
|
||||
build/windows/arm64/_deps
|
||||
build/windows/arm64/mpv-dev-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -434,23 +400,37 @@ jobs:
|
||||
id: windows-native-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
build/windows/arm64/_deps
|
||||
build/windows/arm64/mpv-dev-arm64
|
||||
key: windows-native-arm64-${{ hashFiles('windows/CMakeLists.txt') }}
|
||||
path: ${{ matrix.native_cache_path }}
|
||||
key: windows-native-${{ matrix.arch }}-${{ hashFiles('windows/CMakeLists.txt') }}
|
||||
|
||||
- name: Install 7-Zip
|
||||
if: steps.windows-native-cache.outputs.cache-hit != 'true'
|
||||
if: matrix.arch == 'arm64' && steps.windows-native-cache.outputs.cache-hit != 'true'
|
||||
shell: pwsh
|
||||
run: choco install 7zip -y
|
||||
|
||||
- name: Setup Flutter
|
||||
if: matrix.flutter_setup == 'action'
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "master"
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Set up Flutter 3.44.0 (git tag)
|
||||
if: matrix.flutter_setup == 'git'
|
||||
# Flutter publishes no windows-arm64 SDK archive, so subosito can't
|
||||
# resolve 3.44.0 for arm64: the stable manifest has no arm64 entry, and
|
||||
# `channel: master` would git-clone master HEAD (whose engine != our
|
||||
# patched 3.44.0). Clone the 3.44.0 tag directly to get engine rev
|
||||
# 4c525dac, which install-patched-engine.ps1 asserts before swapping.
|
||||
shell: pwsh
|
||||
run: |
|
||||
$root = "$env:RUNNER_TEMP\flutter"
|
||||
git clone --depth 1 --branch 3.44.0 https://github.com/flutter/flutter.git $root
|
||||
"$root\bin" | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
|
||||
& "$root\bin\flutter.bat" --version
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
@@ -459,27 +439,35 @@ jobs:
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get --no-example
|
||||
shell: pwsh
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build Windows arm64
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-arm64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-arm64
|
||||
- name: Install patched Flutter engine (DComp)
|
||||
shell: pwsh
|
||||
run: |
|
||||
flutter precache --windows
|
||||
.\windows\tool\install-patched-engine.ps1
|
||||
|
||||
- name: Build Windows ${{ matrix.arch }}
|
||||
shell: pwsh
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-${{ matrix.arch }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-${{ matrix.arch }}
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-windows-arm64
|
||||
run: .\scripts\upload-symbols.ps1 windows-arm64
|
||||
SENTRY_DIST: github-windows-${{ matrix.arch }}
|
||||
run: .\scripts\upload-symbols.ps1 windows-${{ matrix.arch }}
|
||||
|
||||
- name: Upload arm64 build
|
||||
- name: Upload ${{ matrix.arch }} build
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-arm64-build
|
||||
path: build/windows/arm64/runner/Release/
|
||||
name: windows-${{ matrix.arch }}-build
|
||||
path: build/windows/${{ matrix.arch }}/runner/Release/
|
||||
|
||||
package-windows:
|
||||
needs: [build-windows-x64, build-windows-arm64]
|
||||
needs: build-windows
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
@@ -562,20 +550,33 @@ jobs:
|
||||
win-ed-signature.txt
|
||||
win-installer-size.txt
|
||||
|
||||
build-linux-x64:
|
||||
build-linux:
|
||||
name: Build Linux (${{ matrix.arch }})
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: ubuntu-latest
|
||||
flutter_channel: stable
|
||||
pkg_config_arch: x86_64-linux-gnu
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
flutter_channel: master
|
||||
pkg_config_arch: aarch64-linux-gnu
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
channel: ${{ matrix.flutter_channel }}
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
@@ -594,6 +595,7 @@ jobs:
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
read -r -a packages <<< "$LINUX_APT_PACKAGES"
|
||||
|
||||
@@ -618,182 +620,73 @@ jobs:
|
||||
|
||||
- name: Build libmpv
|
||||
if: steps.libmpv-cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: bash linux/packaging/build-libmpv.sh
|
||||
|
||||
- name: Install fpm
|
||||
shell: bash
|
||||
run: sudo gem install fpm
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build Linux x64
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-x64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-x64
|
||||
- name: Build Linux ${{ matrix.arch }}
|
||||
shell: bash
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-${{ matrix.arch }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-${{ matrix.arch }}
|
||||
env:
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/x86_64-linux-gnu/pkgconfig
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/${{ matrix.pkg_config_arch }}/pkgconfig
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: bash
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-linux-x64
|
||||
run: ./scripts/upload-symbols.sh linux-x64
|
||||
SENTRY_DIST: github-linux-${{ matrix.arch }}
|
||||
run: ./scripts/upload-symbols.sh linux-${{ matrix.arch }}
|
||||
|
||||
- name: Build Linux Packages
|
||||
run: ARCH_SUFFIX=x64 OUTPUT_DIR=$GITHUB_WORKSPACE python3 linux/packaging/build-packages.py
|
||||
|
||||
- name: Copy libmpv into bundle
|
||||
- name: Resolve bundle directory
|
||||
shell: bash
|
||||
run: |
|
||||
BUNDLE_LIB=build/linux/x64/release/bundle/lib
|
||||
LIBMPV_DIR=$(dirname "$(find libmpv-prefix -name 'libmpv.so' | head -1)")
|
||||
cp -a "$LIBMPV_DIR"/libmpv.so* "$BUNDLE_LIB/"
|
||||
cp -a libmpv-prefix/lib/libshaderc_shared.so* "$BUNDLE_LIB/"
|
||||
|
||||
- name: Bundle shared libraries for portable tarball
|
||||
run: bash linux/packaging/bundle-libs.sh build/linux/x64/release/bundle
|
||||
|
||||
- name: Copy wrapper script into bundle
|
||||
run: cp linux/packaging/plezy.sh build/linux/x64/release/bundle/plezy.sh
|
||||
|
||||
- name: Verify no missing dependencies
|
||||
run: |
|
||||
cd build/linux/x64/release/bundle
|
||||
MISSING=$(LD_LIBRARY_PATH=lib ldd ./plezy 2>&1 | grep "not found" || true)
|
||||
if [[ -n "$MISSING" ]]; then
|
||||
echo "ERROR: Unresolved dependencies found:" >&2
|
||||
echo "$MISSING" >&2
|
||||
if [[ "${{ matrix.arch }}" == "x64" ]]; then
|
||||
bundle_dir=build/linux/x64/release/bundle
|
||||
else
|
||||
bundle_dir=$(find build/linux -path "*/release/bundle" -type d | head -1)
|
||||
fi
|
||||
if [[ -z "$bundle_dir" || ! -d "$bundle_dir" ]]; then
|
||||
echo "ERROR: Linux bundle directory not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "All dependencies resolved."
|
||||
|
||||
- name: Create tarball
|
||||
run: |
|
||||
cd build/linux/x64/release/bundle
|
||||
tar -czf $GITHUB_WORKSPACE/plezy-linux-x64.tar.gz *
|
||||
|
||||
- name: Attest Linux x64 artifacts
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: |
|
||||
plezy-linux-x64.tar.gz
|
||||
plezy-linux-x64.deb
|
||||
plezy-linux-x64.rpm
|
||||
plezy-linux-x64.pkg.tar.zst
|
||||
|
||||
- name: Upload Linux x64 artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-x64
|
||||
path: |
|
||||
plezy-linux-x64.tar.gz
|
||||
plezy-linux-x64.deb
|
||||
plezy-linux-x64.rpm
|
||||
plezy-linux-x64.pkg.tar.zst
|
||||
|
||||
build-linux-arm64:
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "master"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: ${{ env.LINUX_APT_PACKAGES }}
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
read -r -a packages <<< "$LINUX_APT_PACKAGES"
|
||||
|
||||
for attempt in 1 2 3; do
|
||||
if sudo apt-get update -o Acquire::Retries=3 && sudo apt-get install -y -o Acquire::Retries=3 "${packages[@]}"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sudo apt-get clean
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
sleep $((attempt * 15))
|
||||
done
|
||||
|
||||
exit 1
|
||||
|
||||
- name: Cache libmpv build
|
||||
id: libmpv-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: libmpv-prefix
|
||||
key: libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh') }}
|
||||
|
||||
- name: Build libmpv
|
||||
if: steps.libmpv-cache.outputs.cache-hit != 'true'
|
||||
run: bash linux/packaging/build-libmpv.sh
|
||||
|
||||
- name: Install fpm
|
||||
run: sudo gem install fpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get --no-example
|
||||
|
||||
- name: Build Linux arm64
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-arm64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-arm64
|
||||
env:
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/aarch64-linux-gnu/pkgconfig
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-linux-arm64
|
||||
run: ./scripts/upload-symbols.sh linux-arm64
|
||||
|
||||
- name: Find bundle directory
|
||||
id: find-bundle
|
||||
run: |
|
||||
BUNDLE_DIR=$(find build/linux -path "*/release/bundle" -type d | head -1)
|
||||
echo "bundle_dir=$BUNDLE_DIR" >> $GITHUB_OUTPUT
|
||||
echo "BUNDLE_DIR=$bundle_dir" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build Linux Packages
|
||||
shell: bash
|
||||
run: |
|
||||
BUILD_DIR=${{ steps.find-bundle.outputs.bundle_dir }} \
|
||||
ARCH_SUFFIX=arm64 \
|
||||
OUTPUT_DIR=$GITHUB_WORKSPACE \
|
||||
BUILD_DIR="$BUNDLE_DIR" \
|
||||
ARCH_SUFFIX=${{ matrix.arch }} \
|
||||
OUTPUT_DIR="$GITHUB_WORKSPACE" \
|
||||
python3 linux/packaging/build-packages.py
|
||||
|
||||
- name: Copy libmpv into bundle
|
||||
shell: bash
|
||||
run: |
|
||||
BUNDLE_LIB=${{ steps.find-bundle.outputs.bundle_dir }}/lib
|
||||
BUNDLE_LIB="$BUNDLE_DIR/lib"
|
||||
LIBMPV_DIR=$(dirname "$(find libmpv-prefix -name 'libmpv.so' | head -1)")
|
||||
cp -a "$LIBMPV_DIR"/libmpv.so* "$BUNDLE_LIB/"
|
||||
cp -a libmpv-prefix/lib/libshaderc_shared.so* "$BUNDLE_LIB/"
|
||||
|
||||
- name: Bundle shared libraries for portable tarball
|
||||
run: bash linux/packaging/bundle-libs.sh ${{ steps.find-bundle.outputs.bundle_dir }}
|
||||
shell: bash
|
||||
run: bash linux/packaging/bundle-libs.sh "$BUNDLE_DIR"
|
||||
|
||||
- name: Copy wrapper script into bundle
|
||||
run: cp linux/packaging/plezy.sh ${{ steps.find-bundle.outputs.bundle_dir }}/plezy.sh
|
||||
shell: bash
|
||||
run: cp linux/packaging/plezy.sh "$BUNDLE_DIR/plezy.sh"
|
||||
|
||||
- name: Verify no missing dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
cd ${{ steps.find-bundle.outputs.bundle_dir }}
|
||||
cd "$BUNDLE_DIR"
|
||||
MISSING=$(LD_LIBRARY_PATH=lib ldd ./plezy 2>&1 | grep "not found" || true)
|
||||
if [[ -n "$MISSING" ]]; then
|
||||
echo "ERROR: Unresolved dependencies found:" >&2
|
||||
@@ -803,31 +696,32 @@ jobs:
|
||||
echo "All dependencies resolved."
|
||||
|
||||
- name: Create tarball
|
||||
shell: bash
|
||||
run: |
|
||||
cd ${{ steps.find-bundle.outputs.bundle_dir }}
|
||||
tar -czf $GITHUB_WORKSPACE/plezy-linux-arm64.tar.gz *
|
||||
cd "$BUNDLE_DIR"
|
||||
tar -czf "$GITHUB_WORKSPACE/plezy-linux-${{ matrix.arch }}.tar.gz" *
|
||||
|
||||
- name: Attest Linux arm64 artifacts
|
||||
- name: Attest Linux ${{ matrix.arch }} artifacts
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: |
|
||||
plezy-linux-arm64.tar.gz
|
||||
plezy-linux-arm64.deb
|
||||
plezy-linux-arm64.rpm
|
||||
plezy-linux-arm64.pkg.tar.zst
|
||||
plezy-linux-${{ matrix.arch }}.tar.gz
|
||||
plezy-linux-${{ matrix.arch }}.deb
|
||||
plezy-linux-${{ matrix.arch }}.rpm
|
||||
plezy-linux-${{ matrix.arch }}.pkg.tar.zst
|
||||
|
||||
- name: Upload Linux arm64 artifacts
|
||||
- name: Upload Linux ${{ matrix.arch }} artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-arm64
|
||||
name: linux-${{ matrix.arch }}
|
||||
path: |
|
||||
plezy-linux-arm64.tar.gz
|
||||
plezy-linux-arm64.deb
|
||||
plezy-linux-arm64.rpm
|
||||
plezy-linux-arm64.pkg.tar.zst
|
||||
plezy-linux-${{ matrix.arch }}.tar.gz
|
||||
plezy-linux-${{ matrix.arch }}.deb
|
||||
plezy-linux-${{ matrix.arch }}.rpm
|
||||
plezy-linux-${{ matrix.arch }}.pkg.tar.zst
|
||||
|
||||
create-release:
|
||||
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, package-windows, build-linux-x64, build-linux-arm64]
|
||||
needs: [build-android, build-ios, build-macos, build-windows, package-windows, build-linux]
|
||||
if: ${{ always() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && (inputs.build_android || inputs.build_ios || inputs.build_macos || inputs.build_windows || inputs.build_linux) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -1005,8 +899,9 @@ jobs:
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.version.outputs.version }}
|
||||
files: ${{ steps.release-files.outputs.files }}
|
||||
draft: true
|
||||
prerelease: false
|
||||
|
||||
+73
-32
@@ -39,44 +39,31 @@ jobs:
|
||||
|
||||
flutter pub get
|
||||
|
||||
- name: Install saf_util development dependencies
|
||||
working-directory: packages/saf_util
|
||||
run: flutter pub get
|
||||
|
||||
- name: Verify generated files committed
|
||||
run: scripts/codegen.sh --check
|
||||
|
||||
- name: Verify translation hygiene
|
||||
run: python3 scripts/clean_translations.py --check --strict
|
||||
|
||||
- name: Verify workflow and script guards
|
||||
run: |
|
||||
scripts/codegen.sh
|
||||
if ! git diff --exit-code lib/; then
|
||||
echo "::error::Generated files (.g.dart / .freezed.dart) are out of date."
|
||||
echo "Run 'scripts/codegen.sh' and commit the result."
|
||||
exit 1
|
||||
fi
|
||||
python3 scripts/check_build_workflow.py
|
||||
python3 scripts/check_update_packages_workflow.py
|
||||
python3 scripts/test_pubspec_version.py
|
||||
python3 scripts/test_clean_translations.py
|
||||
|
||||
- name: Verify formatting
|
||||
run: |
|
||||
# Find all Dart files excluding generated files
|
||||
find lib $([ -d test ] && echo test) -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f 2>/dev/null | while IFS= read -r file; do
|
||||
files_found=true
|
||||
break
|
||||
done
|
||||
if [ "$files_found" != "true" ]; then
|
||||
echo "No Dart files found to format"
|
||||
exit 0
|
||||
fi
|
||||
find lib $([ -d test ] && echo test) -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f 2>/dev/null -print0 | xargs -0 dart format --output=none --set-exit-if-changed
|
||||
paths=(lib)
|
||||
[ ! -d test ] || paths+=(test)
|
||||
find "${paths[@]}" -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f -print0 |
|
||||
xargs -0 -r dart format --output=none --set-exit-if-changed
|
||||
- name: Analyze code
|
||||
run: |
|
||||
# Run flutter analyze
|
||||
# Fails on errors or warnings only (info messages are allowed)
|
||||
flutter analyze 2>&1 | tee analyze_output.txt || true
|
||||
|
||||
# Check output for errors or warnings
|
||||
if grep -q "error •" analyze_output.txt; then
|
||||
echo "❌ Analysis failed with errors"
|
||||
exit 1
|
||||
elif grep -q "warning •" analyze_output.txt; then
|
||||
echo "⚠️ Analysis completed with warnings"
|
||||
exit 1
|
||||
else
|
||||
echo "✅ Analysis passed!"
|
||||
exit 0
|
||||
fi
|
||||
run: dart run scripts/check_analyzer.dart
|
||||
|
||||
- name: Check for unused code
|
||||
run: |
|
||||
@@ -139,6 +126,60 @@ jobs:
|
||||
echo "No tests found, skipping test execution"
|
||||
fi
|
||||
|
||||
android-test:
|
||||
name: Android JVM Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Cache Gradle
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-gradle-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Configure Android local properties
|
||||
run: printf 'flutter.sdk=%s\nsdk.dir=%s\n' "$FLUTTER_ROOT" "$ANDROID_HOME" > android/local.properties
|
||||
|
||||
- name: Run Android JVM unit tests
|
||||
working-directory: android
|
||||
run: ./gradlew :app:testDebugUnitTest :saf_util:testDebugUnitTest :libass:testDebugUnitTest -x :app:compileFlutterBuildDebug --continue
|
||||
|
||||
- name: Check Android API compatibility
|
||||
working-directory: android
|
||||
run: ./gradlew :app:lintDebug
|
||||
|
||||
native-format:
|
||||
name: Native Formatting
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -32,10 +32,8 @@ jobs:
|
||||
- name: Extract current build number
|
||||
id: get_build
|
||||
run: |
|
||||
# Extract current build number from pubspec.yaml
|
||||
CURRENT_VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //')
|
||||
CURRENT_BUILD=$(echo "$CURRENT_VERSION" | cut -d'+' -f2)
|
||||
NEW_BUILD=$((CURRENT_BUILD + 1))
|
||||
CURRENT_BUILD=$(python3 scripts/pubspec_version.py --build-number pubspec.yaml)
|
||||
NEW_BUILD=$((10#$CURRENT_BUILD + 1))
|
||||
|
||||
echo "current_build=$CURRENT_BUILD" >> $GITHUB_OUTPUT
|
||||
echo "new_build=$NEW_BUILD" >> $GITHUB_OUTPUT
|
||||
@@ -71,7 +69,7 @@ jobs:
|
||||
|
||||
- name: Trigger build workflow
|
||||
run: |
|
||||
curl -L \
|
||||
curl --fail-with-body -L \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
|
||||
|
||||
@@ -4,12 +4,61 @@ on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Published release tag to update packages for
|
||||
required: true
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
resolve-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
tag: ${{ steps.release.outputs.tag }}
|
||||
steps:
|
||||
- name: Resolve published release tag
|
||||
id: release
|
||||
env:
|
||||
EVENT_TAG: ${{ github.event.release.tag_name }}
|
||||
INPUT_TAG: ${{ inputs.release_tag }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$GITHUB_EVENT_NAME" = "release" ]; then
|
||||
REQUESTED_TAG="$EVENT_TAG"
|
||||
else
|
||||
REQUESTED_TAG="$INPUT_TAG"
|
||||
fi
|
||||
|
||||
if [ -z "$REQUESTED_TAG" ]; then
|
||||
echo "A release tag is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
RELEASE=$(gh release view "$REQUESTED_TAG" --repo "$GITHUB_REPOSITORY" \
|
||||
--json tagName,isDraft,publishedAt)
|
||||
RESOLVED_TAG=$(jq -r '.tagName' <<< "$RELEASE")
|
||||
IS_DRAFT=$(jq -r '.isDraft' <<< "$RELEASE")
|
||||
PUBLISHED_AT=$(jq -r '.publishedAt // empty' <<< "$RELEASE")
|
||||
|
||||
if [ "$RESOLVED_TAG" != "$REQUESTED_TAG" ] || \
|
||||
[ "$IS_DRAFT" != "false" ] || [ -z "$PUBLISHED_AT" ]; then
|
||||
echo "Tag '$REQUESTED_TAG' is not an exact published release tag." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "tag=$RESOLVED_TAG" >> "$GITHUB_OUTPUT"
|
||||
|
||||
update-homebrew:
|
||||
needs: resolve-release
|
||||
runs-on: macos-latest
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.resolve-release.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -19,16 +68,14 @@ jobs:
|
||||
- name: Download and hash release
|
||||
id: release
|
||||
run: |
|
||||
VERSION="${{ github.event.release.tag_name || github.ref_name }}"
|
||||
curl -L -o plezy-macos.dmg \
|
||||
"https://github.com/edde746/plezy/releases/download/$VERSION/plezy-macos.dmg"
|
||||
curl --fail-with-body -L -o plezy-macos.dmg \
|
||||
"https://github.com/edde746/plezy/releases/download/$RELEASE_TAG/plezy-macos.dmg"
|
||||
SHA256=$(shasum -a 256 plezy-macos.dmg | cut -d' ' -f1)
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "sha256=$SHA256" >> $GITHUB_OUTPUT
|
||||
echo "sha256=$SHA256" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Update cask
|
||||
run: |
|
||||
sed -i '' "s/version \".*\"/version \"${{ steps.release.outputs.version }}\"/" Casks/plezy.rb
|
||||
sed -i '' "s/version \".*\"/version \"$RELEASE_TAG\"/" Casks/plezy.rb
|
||||
sed -i '' "s/sha256 \".*\"/sha256 \"${{ steps.release.outputs.sha256 }}\"/" Casks/plezy.rb
|
||||
|
||||
- name: Commit
|
||||
@@ -38,41 +85,45 @@ jobs:
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add Casks/plezy.rb
|
||||
if ! git diff --staged --quiet; then
|
||||
git commit -m "chore: update cask to ${{ steps.release.outputs.version }}"
|
||||
git commit -m "chore: update cask to $RELEASE_TAG"
|
||||
git push origin "HEAD:$BRANCH"
|
||||
else
|
||||
echo "No cask changes to commit."
|
||||
fi
|
||||
|
||||
update-winget:
|
||||
needs: resolve-release
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: vedantmgoyal9/winget-releaser@v2
|
||||
with:
|
||||
identifier: edde746.Plezy
|
||||
installers-regex: 'plezy-windows-installer\.exe$'
|
||||
release-tag: ${{ needs.resolve-release.outputs.tag }}
|
||||
token: ${{ secrets.WINGET_TOKEN }}
|
||||
|
||||
update-appcast-branch:
|
||||
needs: resolve-release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.resolve-release.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Download appcast.xml from release
|
||||
run: |
|
||||
gh release download "${{ github.event.release.tag_name }}" \
|
||||
gh release download "$RELEASE_TAG" \
|
||||
--pattern "appcast.xml"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Push to appcast branch
|
||||
run: |
|
||||
VERSION="${{ github.event.release.tag_name }}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
BLOB=$(git hash-object -w appcast.xml)
|
||||
TREE=$(printf "100644 blob %s\tappcast.xml\n" "$BLOB" | git mktree)
|
||||
COMMIT=$(git commit-tree "$TREE" -m "Update appcast for $VERSION")
|
||||
COMMIT=$(git commit-tree "$TREE" -m "Update appcast for $RELEASE_TAG")
|
||||
git push origin "$COMMIT:refs/heads/appcast" --force
|
||||
|
||||
+2
-1
@@ -70,4 +70,5 @@ duplication-report/
|
||||
**/fastlane/report.xml
|
||||
maestro/**/*.png
|
||||
|
||||
server/deploy.sh
|
||||
server/deploy.sh
|
||||
server/Caddyfile
|
||||
|
||||
+5
-2
@@ -4,7 +4,7 @@
|
||||
|
||||
1. Fork and clone the repository
|
||||
2. Run `flutter pub get` to install dependencies
|
||||
3. Run `dart run build_runner build` to generate code
|
||||
3. Run `scripts/codegen.sh` to generate translations and Dart model code
|
||||
4. Start developing!
|
||||
|
||||
## Development
|
||||
@@ -30,7 +30,10 @@ The project includes automated CI checks that run on all pull requests:
|
||||
- Run locally: `flutter analyze`
|
||||
- Note: CI excludes generated files from analysis (configured in `analysis_options.yaml`)
|
||||
|
||||
3. **Tests**: Runs unit and widget tests (when available)
|
||||
3. **Generated Code**: Ensures generated translations and model files are current
|
||||
- Run locally: `scripts/codegen.sh --check`
|
||||
|
||||
4. **Tests**: Runs unit and widget tests (when available)
|
||||
- Run locally: `flutter test`
|
||||
|
||||
All these checks must pass before your changes can be merged.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
cask "plezy" do
|
||||
version "2.6.0"
|
||||
sha256 "e408fe84c07e0ff4a2f1a78e8dcfc418233c66ca98c79028a7b099499307a59e"
|
||||
version "2.9.0"
|
||||
sha256 "d7f939bdab4421d53f49b5d8b840e5f9d005e1c48269ccc1fa53a350e7d1e65c"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
|
||||
@@ -87,15 +87,15 @@ Package managers:
|
||||
- Real-time play / pause / seek sync
|
||||
|
||||
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
|
||||
- Discord Rich Presence[^7]
|
||||
- Discord Rich Presence[^6]
|
||||
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
|
||||
- Plezy Remote — control desktop and TV from mobile
|
||||
- Watch Next row[^6]
|
||||
- Watch Next row
|
||||
|
||||
### <img src="assets/readme_icons/customization.svg" height="20" alt="" align="center" /> Platform & Customization
|
||||
- Desktop, mobile, and TV — full D-pad, keyboard, and gamepad support
|
||||
- Customizable keyboard shortcuts[^7]
|
||||
- Metadata and artwork editing[^2]
|
||||
- Customizable keyboard shortcuts[^6]
|
||||
- Metadata and artwork editing
|
||||
- Settings import/export
|
||||
- Localized in English plus 14 translations
|
||||
|
||||
@@ -104,8 +104,7 @@ Package managers:
|
||||
[^3]: Not available on iOS or tvOS.
|
||||
[^4]: Android, iOS, and macOS.
|
||||
[^5]: Windows, Android, and tvOS.
|
||||
[^6]: Android TV only.
|
||||
[^7]: Desktop only.
|
||||
[^6]: Desktop only.
|
||||
|
||||
## Building from Source
|
||||
|
||||
|
||||
@@ -18,6 +18,11 @@ linter:
|
||||
avoid_print: true
|
||||
|
||||
dart_code_linter:
|
||||
rules-exclude:
|
||||
- "test/**"
|
||||
metrics-exclude:
|
||||
- "test/**"
|
||||
|
||||
extends:
|
||||
- package:dart_code_linter/presets/recommended.yaml
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
gradle-wrapper.jar
|
||||
/.gradle
|
||||
/captures/
|
||||
/gradlew
|
||||
/gradlew.bat
|
||||
/local.properties
|
||||
GeneratedPluginRegistrant.java
|
||||
.cxx/
|
||||
|
||||
@@ -152,46 +152,41 @@ android {
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// Three copies of libc++_shared.so reach the merge: the libmpv AAR's
|
||||
// (NDK r29 — exports std::from_chars<float> that libmpv.so needs), the
|
||||
// :libass module's CMake-contributed copy (NDK 28.2 — lacks it), and
|
||||
// peerless2012:ass's bundled copy (also old). pickFirst keeps the merge
|
||||
// from erroring on the duplicates; WHICH copy wins is pinned by the
|
||||
// sourceSets block below: extractMpvLibcxx unpacks the libmpv AAR's copy
|
||||
// into an app jniLibs dir, and PROJECT-scope sources beat sub-projects
|
||||
// and external AARs. libc++ is backward ABI-compatible, so the older-NDK
|
||||
// consumers (libass.so, libasskt.so, ffmpeg decoder, cronet) run fine
|
||||
// against the newer copy.
|
||||
// pickFirst only suppresses the duplicate libc++ merge error; the
|
||||
// sourceSets rule below makes libmpv's newer runtime win for
|
||||
// std::from_chars<float>, while older native consumers remain ABI-compatible.
|
||||
pickFirsts.add("lib/*/libc++_shared.so")
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
// libc++_shared.so extracted from the libmpv AAR by extractMpvLibcxx.
|
||||
// App source-set jniLibs sit in the PROJECT scope, merged ahead of
|
||||
// subprojects (:libass) and external AARs, so with the pickFirst rule
|
||||
// above this copy deterministically wins regardless of dependency order.
|
||||
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
|
||||
// order cannot accidentally select the older libc++ copy.
|
||||
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
|
||||
}
|
||||
}
|
||||
|
||||
lint {
|
||||
// Enforce the app-owned minSdk boundary without auditing upstream AndroidX.
|
||||
checkDependencies = false
|
||||
checkOnly += setOf("NewApi")
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
// Download libdovi before any CMake/native build task
|
||||
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
|
||||
dependsOn(downloadLibdovi)
|
||||
}
|
||||
|
||||
// Download the libmpv AAR before compilation
|
||||
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
|
||||
dependsOn(downloadLibmpv, extractMpvLibcxx)
|
||||
}
|
||||
// merge{Debug,Profile,Release}JniLibFolders snapshot jniLibs source dirs as inputs;
|
||||
// Gradle 8 requires an explicit dependency on the producing task.
|
||||
// Gradle snapshots jniLibs source dirs before task execution; this keeps the
|
||||
// extracted libmpv libc++ directory present during input discovery.
|
||||
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
|
||||
dependsOn(extractMpvLibcxx)
|
||||
}
|
||||
@@ -216,13 +211,12 @@ dependencies {
|
||||
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
|
||||
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
|
||||
|
||||
// libass ASS/SSA subtitle rendering: optimized native core (libass.so +
|
||||
// prefab headers) from the edde746/libass-android fork's releases; Kotlin/JNI
|
||||
// bindings + Media3 glue live in the android/libass module. -PlocalAssCore
|
||||
// swaps in a mavenLocal()-published core (0.4.0-local) for native A/B tests.
|
||||
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
|
||||
implementation("io.github.peerless2012:ass:$assCoreVersion@aar")
|
||||
// Keeping libass in-project lets its static core share the app's native
|
||||
// packaging rules.
|
||||
implementation(project(":libass"))
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
// Real android.util.* implementations for tests exercising media3 classes
|
||||
// (MatroskaExtractor uses SparseArray, which is a no-op stub on plain JVM)
|
||||
testImplementation("org.robolectric:robolectric:4.15.1")
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/LaunchTheme"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|navigation|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<!-- Specifies an Android theme to apply to this Activity as soon as
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.TextureView
|
||||
|
||||
internal class DeferredSurfaceTextureListener(
|
||||
private val delegate: TextureView.SurfaceTextureListener,
|
||||
private val handler: Handler = Handler(Looper.getMainLooper()),
|
||||
private val onSurfaceAvailable: () -> Unit = {},
|
||||
private val isCurrentSurface: (SurfaceTexture) -> Boolean
|
||||
) : TextureView.SurfaceTextureListener {
|
||||
|
||||
private var pendingResize: Runnable? = null
|
||||
|
||||
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
delegate.onSurfaceTextureAvailable(surface, width, height)
|
||||
onSurfaceAvailable()
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
pendingResize?.let(handler::removeCallbacks)
|
||||
pendingResize = Runnable {
|
||||
pendingResize = null
|
||||
if (isCurrentSurface(surface)) {
|
||||
delegate.onSurfaceTextureSizeChanged(surface, width, height)
|
||||
}
|
||||
}
|
||||
handler.postDelayed(pendingResize!!, RESIZE_DELAY_MILLIS)
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
|
||||
delegate.onSurfaceTextureUpdated(surface)
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
|
||||
pendingResize?.let(handler::removeCallbacks)
|
||||
pendingResize = null
|
||||
return delegate.onSurfaceTextureDestroyed(surface)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val RESIZE_DELAY_MILLIS = 100L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.core.content.FileProvider
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.io.File
|
||||
|
||||
internal class ExternalPlayerChannel(private val activity: Activity) {
|
||||
companion object {
|
||||
private const val CHANNEL = "com.plezy/external_player"
|
||||
const val REQUEST_CODE = 7461
|
||||
|
||||
private const val API_MX_RETURN_RESULT = "return_result"
|
||||
private const val API_MX_RESULT_ID = "com.mxtech.intent.result.VIEW"
|
||||
private const val API_MX_RESULT_POSITION = "position"
|
||||
private const val API_MX_RESULT_DURATION = "duration"
|
||||
private const val API_MX_RESULT_END_BY = "end_by"
|
||||
private const val API_MX_RESULT_END_BY_PLAYBACK_COMPLETION = "playback_completion"
|
||||
private const val API_MX_TITLE = "title"
|
||||
private const val API_MX_FILENAME = "filename"
|
||||
private const val API_MX_SECURE_URI = "secure_uri"
|
||||
private const val API_VLC_RESULT_POSITION = "extra_position"
|
||||
private const val API_VLC_RESULT_DURATION = "extra_duration"
|
||||
|
||||
private const val API_VIMU_TITLE = "forcename"
|
||||
private const val API_VIMU_SEEK_POSITION = "startfrom"
|
||||
private const val API_VIMU_RESUME = "forceresume"
|
||||
private const val API_VIMU_RESULT_ID = "net.gtvbox.videoplayer.result"
|
||||
private const val API_VIMU_RESULT_ERROR = 4
|
||||
private const val API_VIMU_RESULT_PLAYBACK_COMPLETED = 1
|
||||
|
||||
private val positionExtras = arrayOf(API_MX_RESULT_POSITION, API_VLC_RESULT_POSITION)
|
||||
private val durationExtras = arrayOf(API_MX_RESULT_DURATION, API_VLC_RESULT_DURATION)
|
||||
}
|
||||
|
||||
private var pendingResult: MethodChannel.Result? = null
|
||||
|
||||
fun attach(messenger: BinaryMessenger) {
|
||||
MethodChannel(messenger, CHANNEL).setMethodCallHandler(::onMethodCall)
|
||||
}
|
||||
|
||||
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
|
||||
if (requestCode != REQUEST_CODE) return false
|
||||
val result = pendingResult
|
||||
pendingResult = null
|
||||
if (result == null) {
|
||||
android.util.Log.w("ExternalPlayerChannel", "Result received without a pending channel call")
|
||||
} else {
|
||||
result.success(buildResult(resultCode, data))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
pendingResult?.error("ACTIVITY_DESTROYED", "Activity was destroyed while external player was active", null)
|
||||
pendingResult = null
|
||||
}
|
||||
|
||||
internal fun buildResult(resultCode: Int, data: Intent?): Map<String, Any?> {
|
||||
val extras = data?.extras
|
||||
val endPosition = firstNumberExtra(extras, positionExtras)
|
||||
val duration = firstNumberExtra(extras, durationExtras)
|
||||
val action = data?.action
|
||||
val playbackCompleted = when (action) {
|
||||
API_MX_RESULT_ID -> extras?.getString(API_MX_RESULT_END_BY) == API_MX_RESULT_END_BY_PLAYBACK_COMPLETION
|
||||
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_PLAYBACK_COMPLETED
|
||||
else -> false
|
||||
}
|
||||
val playbackError = action == API_VIMU_RESULT_ID && resultCode == API_VIMU_RESULT_ERROR
|
||||
|
||||
return mapOf(
|
||||
"launched" to true,
|
||||
"resultCode" to resultCode,
|
||||
"resultOk" to (resultCode == Activity.RESULT_OK),
|
||||
"action" to action,
|
||||
"positionMs" to endPosition,
|
||||
"durationMs" to duration,
|
||||
"playbackCompleted" to playbackCompleted,
|
||||
"playbackError" to playbackError
|
||||
)
|
||||
}
|
||||
|
||||
private fun firstNumberExtra(extras: Bundle?, keys: Array<String>): Long? {
|
||||
if (extras == null) return null
|
||||
for (key in keys) {
|
||||
@Suppress("DEPRECATION")
|
||||
val value = extras.get(key)
|
||||
when (value) {
|
||||
is Number -> return value.toLong()
|
||||
is String -> value.toLongOrNull()?.let { return it }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
if (call.method != "openVideo") {
|
||||
result.notImplemented()
|
||||
return
|
||||
}
|
||||
|
||||
val filePath = call.argument<String>("filePath")
|
||||
val packageNames = call.argument<List<Any?>>("packages")
|
||||
?.mapNotNull { (it as? String)?.trim()?.takeIf(String::isNotEmpty) }
|
||||
?: emptyList()
|
||||
val title = call.argument<String>("title")?.trim()?.takeIf(String::isNotEmpty)
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
|
||||
if (filePath == null) {
|
||||
result.error("INVALID_ARGUMENT", "filePath is required", null)
|
||||
return
|
||||
}
|
||||
if (pendingResult != null) {
|
||||
result.error("ALREADY_ACTIVE", "An external player is already active", null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
val source = resolveSource(filePath)
|
||||
val targetPackages = if (packageNames.isEmpty()) listOf<String?>(null) else packageNames
|
||||
for (packageName in targetPackages) {
|
||||
try {
|
||||
pendingResult = result
|
||||
activity.startActivityForResult(
|
||||
buildIntent(source, packageName, startPositionMs, title),
|
||||
REQUEST_CODE
|
||||
)
|
||||
return
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
pendingResult = null
|
||||
}
|
||||
}
|
||||
|
||||
val message = if (packageNames.isEmpty()) {
|
||||
"No app found for video"
|
||||
} else {
|
||||
"No app found for packages: ${packageNames.joinToString(", ")}"
|
||||
}
|
||||
result.error("APP_NOT_FOUND", message, null)
|
||||
} catch (error: Exception) {
|
||||
pendingResult = null
|
||||
result.error("LAUNCH_FAILED", error.message ?: error.javaClass.simpleName, null)
|
||||
}
|
||||
}
|
||||
|
||||
private data class Source(val uri: Uri, val grantRead: Boolean, val fileName: String?)
|
||||
|
||||
private fun resolveSource(filePath: String): Source {
|
||||
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
|
||||
val uri = Uri.parse(filePath)
|
||||
return Source(uri, grantRead = false, fileName = uri.lastPathSegment)
|
||||
}
|
||||
if (filePath.startsWith("content://")) {
|
||||
val uri = Uri.parse(filePath)
|
||||
return Source(uri, grantRead = true, fileName = uri.lastPathSegment)
|
||||
}
|
||||
|
||||
val path = if (filePath.startsWith("file://")) filePath.removePrefix("file://") else filePath
|
||||
val file = File(path)
|
||||
val uri = FileProvider.getUriForFile(activity, "com.edde746.plezy.fileprovider", file)
|
||||
return Source(uri, grantRead = true, fileName = file.name)
|
||||
}
|
||||
|
||||
private fun buildIntent(
|
||||
source: Source,
|
||||
packageName: String?,
|
||||
startPositionMs: Long,
|
||||
title: String?
|
||||
): Intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(source.uri, "video/*")
|
||||
if (source.grantRead) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
packageName?.let(::setPackage)
|
||||
val startPosition = startPositionMs.coerceAtLeast(0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
if (startPosition > 0) {
|
||||
putExtra(API_MX_RESULT_POSITION, startPosition)
|
||||
putExtra(API_VIMU_SEEK_POSITION, startPosition)
|
||||
}
|
||||
putExtra(API_MX_RETURN_RESULT, true)
|
||||
putExtra(API_MX_SECURE_URI, true)
|
||||
putExtra(API_VIMU_RESUME, false)
|
||||
title?.let {
|
||||
putExtra(API_MX_TITLE, it)
|
||||
putExtra(API_VIMU_TITLE, it)
|
||||
}
|
||||
source.fileName?.let { putExtra(API_MX_FILENAME, it) }
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,29 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityManager
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import android.util.Rational
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.TextureView
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowManager
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.annotation.RequiresApi
|
||||
import com.edde746.plezy.exoplayer.ExoPlayerPlugin
|
||||
import com.edde746.plezy.mpv.MpvAudioPlayerPlugin
|
||||
import com.edde746.plezy.mpv.MpvPlayerPlugin
|
||||
import com.edde746.plezy.shared.DeviceQuirks
|
||||
import com.edde746.plezy.shared.ThemeHelper
|
||||
@@ -41,7 +35,6 @@ import io.flutter.embedding.android.TransparencyMode
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.embedding.engine.FlutterShellArgs
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
@@ -49,46 +42,27 @@ class MainActivity : FlutterActivity() {
|
||||
companion object {
|
||||
private const val TAG = "MainActivity"
|
||||
private const val TEXT_INPUT_DIAGNOSTICS_ENABLED = false
|
||||
private const val EXTERNAL_PLAYER_REQUEST_CODE = 7461
|
||||
|
||||
// External player result APIs used by Jellyfin Android TV.
|
||||
private const val API_MX_RETURN_RESULT = "return_result"
|
||||
private const val API_MX_RESULT_ID = "com.mxtech.intent.result.VIEW"
|
||||
private const val API_MX_RESULT_POSITION = "position"
|
||||
private const val API_MX_RESULT_DURATION = "duration"
|
||||
private const val API_MX_RESULT_END_BY = "end_by"
|
||||
private const val API_MX_RESULT_END_BY_PLAYBACK_COMPLETION = "playback_completion"
|
||||
private const val API_MX_TITLE = "title"
|
||||
private const val API_MX_FILENAME = "filename"
|
||||
private const val API_MX_SECURE_URI = "secure_uri"
|
||||
private const val API_VLC_RESULT_POSITION = "extra_position"
|
||||
private const val API_VLC_RESULT_DURATION = "extra_duration"
|
||||
|
||||
private const val API_VIMU_TITLE = "forcename"
|
||||
private const val API_VIMU_SEEK_POSITION = "startfrom"
|
||||
private const val API_VIMU_RESUME = "forceresume"
|
||||
private const val API_VIMU_RESULT_ID = "net.gtvbox.videoplayer.result"
|
||||
private const val API_VIMU_RESULT_ERROR = 4
|
||||
private const val API_VIMU_RESULT_PLAYBACK_COMPLETED = 1
|
||||
|
||||
private val externalPlayerPositionExtras = arrayOf(API_MX_RESULT_POSITION, API_VLC_RESULT_POSITION)
|
||||
private val externalPlayerDurationExtras = arrayOf(API_MX_RESULT_DURATION, API_VLC_RESULT_DURATION)
|
||||
// Mirrors DevicePerformance._lowMemThresholdBytes (2252 MiB): nominal
|
||||
// "2GB" devices report totalMem slightly above 2 GiB after carve-outs.
|
||||
private const val LOW_MEM_THRESHOLD_BYTES = 2252L shl 20
|
||||
|
||||
var usingSkia = false
|
||||
}
|
||||
|
||||
private val PIP_CHANNEL = "com.plezy/pip"
|
||||
private val EXTERNAL_PLAYER_CHANNEL = "com.plezy/external_player"
|
||||
private val THEME_CHANNEL = "com.plezy/theme"
|
||||
private val DEVICE_CHANNEL = "com.plezy/device"
|
||||
private val DEVICE_ADJUSTMENT_CHANNEL = "com.plezy/device_adjustment"
|
||||
private val TEXT_INPUT_CHANNEL = "com.plezy/text_input"
|
||||
private val APP_EXIT_CHANNEL = "com.plezy/app_exit"
|
||||
private val APP_FOREGROUND_CHANNEL = "com.plezy/app_foreground"
|
||||
private var watchNextPlugin: WatchNextPlugin? = null
|
||||
private var nativeTextInputFocused = false
|
||||
private var pendingExternalPlayerResult: MethodChannel.Result? = null
|
||||
private var originalWindowBrightness: Float? = null
|
||||
private var flutterTextureView: FlutterTextureView? = null
|
||||
private var flutterSurfaceReconnectPending = false
|
||||
private var activityStarted = false
|
||||
private val externalPlayerChannel = ExternalPlayerChannel(this)
|
||||
|
||||
private inline fun logTextInputDiag(message: () -> String) {
|
||||
if (TEXT_INPUT_DIAGNOSTICS_ENABLED) {
|
||||
@@ -210,6 +184,18 @@ class MainActivity : FlutterActivity() {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Same triple DevicePerformance uses for the reduced tier on the Dart
|
||||
* side — keep the two in sync. Evaluated here too because engine shell
|
||||
* args must be decided before Dart runs.
|
||||
*/
|
||||
private fun isLowRamClass(): Boolean {
|
||||
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
val memoryInfo = ActivityManager.MemoryInfo()
|
||||
activityManager.getMemoryInfo(memoryInfo)
|
||||
return !Process.is64Bit() || activityManager.isLowRamDevice || memoryInfo.totalMem <= LOW_MEM_THRESHOLD_BYTES
|
||||
}
|
||||
|
||||
/** User-assigned device name (Settings > About > Device name), or null. */
|
||||
private fun getDeviceName(): String? {
|
||||
// The name the user gave the device; also used by Cast/Nearby.
|
||||
@@ -310,63 +296,16 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (requestCode == EXTERNAL_PLAYER_REQUEST_CODE) {
|
||||
val pendingResult = pendingExternalPlayerResult
|
||||
pendingExternalPlayerResult = null
|
||||
if (pendingResult == null) {
|
||||
Log.w(TAG, "External player result received without a pending channel result")
|
||||
} else {
|
||||
pendingResult.success(buildExternalPlayerResult(resultCode, data))
|
||||
}
|
||||
return
|
||||
if (!externalPlayerChannel.onActivityResult(requestCode, resultCode, data)) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
private fun buildExternalPlayerResult(resultCode: Int, data: Intent?): Map<String, Any?> {
|
||||
val extras = data?.extras
|
||||
val endPosition = firstNumberExtra(extras, externalPlayerPositionExtras)
|
||||
val duration = firstNumberExtra(extras, externalPlayerDurationExtras)
|
||||
val action = data?.action
|
||||
val playbackCompleted = when (action) {
|
||||
API_MX_RESULT_ID -> extras?.getString(API_MX_RESULT_END_BY) == API_MX_RESULT_END_BY_PLAYBACK_COMPLETION
|
||||
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_PLAYBACK_COMPLETED
|
||||
else -> false
|
||||
}
|
||||
val playbackError = when (action) {
|
||||
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_ERROR
|
||||
else -> false
|
||||
}
|
||||
|
||||
return mapOf(
|
||||
"launched" to true,
|
||||
"resultCode" to resultCode,
|
||||
"resultOk" to (resultCode == Activity.RESULT_OK),
|
||||
"action" to action,
|
||||
"positionMs" to endPosition,
|
||||
"durationMs" to duration,
|
||||
"playbackCompleted" to playbackCompleted,
|
||||
"playbackError" to playbackError
|
||||
)
|
||||
}
|
||||
|
||||
private fun firstNumberExtra(extras: Bundle?, keys: Array<String>): Long? {
|
||||
if (extras == null) return null
|
||||
for (key in keys) {
|
||||
@Suppress("DEPRECATION")
|
||||
val value = extras.get(key)
|
||||
when (value) {
|
||||
is Number -> return value.toLong()
|
||||
is String -> value.toLongOrNull()?.let { return it }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
pendingExternalPlayerResult?.error("ACTIVITY_DESTROYED", "Activity was destroyed while external player was active", null)
|
||||
pendingExternalPlayerResult = null
|
||||
externalPlayerChannel.dispose()
|
||||
activityStarted = false
|
||||
flutterSurfaceReconnectPending = false
|
||||
flutterTextureView = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -382,12 +321,19 @@ class MainActivity : FlutterActivity() {
|
||||
val args = super.getFlutterShellArgs()
|
||||
usingSkia = shouldDisableImpeller()
|
||||
if (usingSkia) args.add("--enable-impeller=false")
|
||||
if (isLowRamClass()) {
|
||||
// Bound the memory pools Dart can't reach: Skia's GPU resource cache
|
||||
// is sized from the surface area (hundreds of MB on a 4K-composited
|
||||
// TV) and the Dart old gen defaults to a large fraction of physical
|
||||
// RAM. Both drive LMK kills on 2GB boxes (#1349).
|
||||
if (usingSkia) args.add("--resource-cache-max-bytes-threshold=50331648")
|
||||
args.add("--old-gen-heap-size=256")
|
||||
Log.i(TAG, "Low-RAM device: capped engine caches (skia=$usingSkia, oldGen=256MB)")
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
private fun shouldDisableImpeller(): Boolean {
|
||||
// Android TV devices — weaker GPUs, less Impeller testing
|
||||
if (isAndroidTvDevice()) return true
|
||||
if (DeviceQuirks.isEWaste) return true
|
||||
// NVIDIA Tegra (Shield TV)
|
||||
if (Build.MANUFACTURER.equals("NVIDIA", ignoreCase = true)) return true
|
||||
@@ -397,9 +343,21 @@ class MainActivity : FlutterActivity() {
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (isAndroidTvDevice()) return !tvSupportsImpeller()
|
||||
return false
|
||||
}
|
||||
|
||||
// Impeller froze API 30 Fire TV hardware (#749) and Flutter's Vulkan → GLES
|
||||
// fallback still miscompiles gradients/SVGs, so only TV devices on Android 12+
|
||||
// with a Vulkan 1.1 driver leave the Skia path.
|
||||
private fun tvSupportsImpeller(): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
|
||||
// Fire OS reports modern API levels on GPUs whose drivers can't back it up
|
||||
if (Build.MANUFACTURER.equals("Amazon", ignoreCase = true)) return false
|
||||
val vulkan11 = 0x401000 // FEATURE_VULKAN_HARDWARE_VERSION encodes 1.1.0 as 0x401000
|
||||
return packageManager.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, vulkan11)
|
||||
}
|
||||
|
||||
override fun getRenderMode(): RenderMode {
|
||||
// Keep Flutter in the normal View hierarchy so video/subtitle SurfaceViews
|
||||
// remain the only native composition layers. This restores the pre-1.35.0
|
||||
@@ -413,41 +371,49 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
|
||||
override fun onFlutterTextureViewCreated(flutterTextureView: FlutterTextureView) {
|
||||
this.flutterTextureView = flutterTextureView
|
||||
val original = flutterTextureView.surfaceTextureListener ?: return
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
var pendingResize: Runnable? = null
|
||||
var lastWidth = 0
|
||||
var lastHeight = 0
|
||||
flutterTextureView.surfaceTextureListener =
|
||||
DeferredSurfaceTextureListener(
|
||||
delegate = original,
|
||||
onSurfaceAvailable = ::tryReconnectFlutterSurface
|
||||
) { surface ->
|
||||
flutterTextureView.isAvailable && flutterTextureView.surfaceTexture === surface
|
||||
}
|
||||
}
|
||||
|
||||
flutterTextureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
|
||||
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
original.onSurfaceTextureAvailable(surface, width, height)
|
||||
override fun onStop() {
|
||||
activityStarted = false
|
||||
if (isAndroidTvDevice()) flutterSurfaceReconnectPending = true
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
activityStarted = true
|
||||
tryReconnectFlutterSurface()
|
||||
}
|
||||
|
||||
private fun tryReconnectFlutterSurface() {
|
||||
if (!activityStarted || !flutterSurfaceReconnectPending) return
|
||||
val textureView = flutterTextureView ?: return
|
||||
textureView.post {
|
||||
if (!activityStarted ||
|
||||
!flutterSurfaceReconnectPending ||
|
||||
textureView !== flutterTextureView ||
|
||||
!textureView.isAttachedToWindow ||
|
||||
!textureView.isAvailable
|
||||
) {
|
||||
return@post
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
if (width == lastWidth && height == lastHeight) return
|
||||
lastWidth = width
|
||||
lastHeight = height
|
||||
pendingResize?.let { handler.removeCallbacks(it) }
|
||||
pendingResize = Runnable {
|
||||
if (flutterTextureView.isAvailable) {
|
||||
original.onSurfaceTextureSizeChanged(surface, width, height)
|
||||
}
|
||||
}
|
||||
handler.postDelayed(pendingResize!!, 100)
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
|
||||
original.onSurfaceTextureUpdated(surface)
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
|
||||
pendingResize?.let { handler.removeCallbacks(it) }
|
||||
pendingResize = null
|
||||
lastWidth = 0
|
||||
lastHeight = 0
|
||||
return original.onSurfaceTextureDestroyed(surface)
|
||||
}
|
||||
// Some TV firmware retains an available TextureView while invalidating
|
||||
// its compositor surface during standby. Force Flutter's supported
|
||||
// surface-swap path so rendering resumes without restarting the engine.
|
||||
Log.i(TAG, "Reconnecting Flutter texture surface after Android TV standby")
|
||||
textureView.pause()
|
||||
textureView.resume()
|
||||
flutterSurfaceReconnectPending = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -455,6 +421,7 @@ class MainActivity : FlutterActivity() {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
flutterEngine.plugins.add(MpvPlayerPlugin())
|
||||
flutterEngine.plugins.add(ExoPlayerPlugin())
|
||||
flutterEngine.plugins.add(MpvAudioPlayerPlugin())
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DEVICE_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
@@ -495,101 +462,7 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, APP_FOREGROUND_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"requestForeground" -> result.success(requestForeground())
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
// External player: open local video files with proper content:// URIs
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, EXTERNAL_PLAYER_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"openVideo" -> {
|
||||
val filePath = call.argument<String>("filePath")
|
||||
val packageNames = call.argument<List<Any?>>("packages")
|
||||
?.mapNotNull { (it as? String)?.trim()?.takeIf { value -> value.isNotEmpty() } }
|
||||
?: emptyList()
|
||||
val title = call.argument<String>("title")?.trim()?.takeIf { it.isNotEmpty() }
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
|
||||
if (filePath == null) {
|
||||
result.error("INVALID_ARGUMENT", "filePath is required", null)
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
if (pendingExternalPlayerResult != null) {
|
||||
result.error("ALREADY_ACTIVE", "An external player is already active", null)
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
try {
|
||||
val uri: Uri
|
||||
val grantRead: Boolean
|
||||
val fileName: String?
|
||||
|
||||
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
|
||||
uri = Uri.parse(filePath)
|
||||
grantRead = false
|
||||
fileName = uri.lastPathSegment
|
||||
} else if (filePath.startsWith("content://")) {
|
||||
uri = Uri.parse(filePath)
|
||||
grantRead = true
|
||||
fileName = uri.lastPathSegment
|
||||
} else {
|
||||
val path = if (filePath.startsWith("file://")) filePath.removePrefix("file://") else filePath
|
||||
fileName = File(path).name
|
||||
uri = FileProvider.getUriForFile(this, "com.edde746.plezy.fileprovider", File(path))
|
||||
grantRead = true
|
||||
}
|
||||
|
||||
fun buildIntent(packageName: String?): Intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, "video/*")
|
||||
if (grantRead) {
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
packageName?.let { setPackage(it) }
|
||||
val startPosition = startPositionMs.coerceAtLeast(0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
if (startPosition > 0) {
|
||||
putExtra(API_MX_RESULT_POSITION, startPosition)
|
||||
putExtra(API_VIMU_SEEK_POSITION, startPosition)
|
||||
}
|
||||
putExtra(API_MX_RETURN_RESULT, true)
|
||||
putExtra(API_MX_SECURE_URI, true)
|
||||
putExtra(API_VIMU_RESUME, false)
|
||||
title?.let {
|
||||
putExtra(API_MX_TITLE, it)
|
||||
putExtra(API_VIMU_TITLE, it)
|
||||
}
|
||||
fileName?.let { putExtra(API_MX_FILENAME, it) }
|
||||
}
|
||||
|
||||
val targetPackages = if (packageNames.isEmpty()) listOf<String?>(null) else packageNames
|
||||
for (packageName in targetPackages) {
|
||||
try {
|
||||
pendingExternalPlayerResult = result
|
||||
startActivityForResult(buildIntent(packageName), EXTERNAL_PLAYER_REQUEST_CODE)
|
||||
return@setMethodCallHandler
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
pendingExternalPlayerResult = null
|
||||
}
|
||||
}
|
||||
|
||||
pendingExternalPlayerResult = null
|
||||
val message = if (packageNames.isEmpty()) {
|
||||
"No app found for video"
|
||||
} else {
|
||||
"No app found for packages: ${packageNames.joinToString(", ")}"
|
||||
}
|
||||
result.error("APP_NOT_FOUND", message, null)
|
||||
} catch (e: Exception) {
|
||||
pendingExternalPlayerResult = null
|
||||
result.error("LAUNCH_FAILED", e.message ?: e.javaClass.simpleName, null)
|
||||
}
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
externalPlayerChannel.attach(flutterEngine.dartExecutor.binaryMessenger)
|
||||
|
||||
// Splash screen theme: persist user's chosen theme for next launch (API 31+)
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, THEME_CHANNEL).setMethodCallHandler { call, result ->
|
||||
@@ -686,31 +559,6 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestForeground(): Boolean = try {
|
||||
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
activityManager.moveTaskToFront(taskId, 0)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to move task to foreground", e)
|
||||
try {
|
||||
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)?.apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
|
||||
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
if (launchIntent != null) {
|
||||
startActivity(launchIntent)
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} catch (launchError: Exception) {
|
||||
Log.w(TAG, "Failed to start foreground activity", launchError)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleDeviceAdjustmentCall(method: String, arguments: Any?, result: MethodChannel.Result) {
|
||||
try {
|
||||
when (method) {
|
||||
@@ -829,6 +677,7 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.O)
|
||||
private fun isPipPermissionGranted(): Boolean {
|
||||
val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
|
||||
return appOpsManager.checkOpNoThrow(
|
||||
@@ -838,6 +687,7 @@ class MainActivity : FlutterActivity() {
|
||||
) == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.O)
|
||||
private fun buildPipParams(width: Int, height: Int, autoEnterEnabled: Boolean? = null): PictureInPictureParams {
|
||||
val (w, h) = if (width <= 0 || height <= 0) {
|
||||
Pair(16, 9)
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
|
||||
/**
|
||||
* Native mirror of MainActivity.getAndroidTvDetection(): any TV signal counts.
|
||||
* Kept in sync with the Dart-facing detection so native gating matches
|
||||
* PlatformDetector.isTV().
|
||||
*/
|
||||
object TvDetection {
|
||||
fun isTv(context: Context): Boolean {
|
||||
val pm = context.packageManager
|
||||
val uiModeType = context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
return uiModeType == Configuration.UI_MODE_TYPE_TELEVISION ||
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION) ||
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
|
||||
pm.hasSystemFeature("amazon.hardware.fire_tv") ||
|
||||
!pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.os.Build
|
||||
import android.view.SurfaceControl
|
||||
import android.view.SurfaceView
|
||||
import androidx.annotation.RequiresApi
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Auto-calibrates [ExoPlayerCore]'s subtitle/video layer offset by measuring, per device, how much
|
||||
* later the codec VIDEO plane reaches the display than the GL subtitle OVERLAY plane — the
|
||||
* inter-plane latency (a deep video VPP on TV boxes) that otherwise makes subtitles a frame ahead.
|
||||
*
|
||||
* Both planes are pinned to the same video-frame target (releaseTimeNs). Measuring BOTH with the
|
||||
* same mechanism — [SurfaceTxProbe] + the API-34 previous-release fence — the per-SoC buffer-recycle
|
||||
* bias cancels in the difference, leaving the pure offset:
|
||||
*
|
||||
* offsetFrames = round( (median(videoReleaseVsTarget) − median(overlayReleaseVsTarget)) / frameMs )
|
||||
*
|
||||
* This is a MEDIAN-of-each-plane model, NOT a per-frame paired difference: every sample is
|
||||
* self-paired to its own frame's target, and the per-plane release-vs-target is a steady hardware
|
||||
* constant, so the two medians need not come from the same frames — only from the same (stable)
|
||||
* device. Both medians use a recent-sample window so they stay roughly contemporaneous, and a
|
||||
* confidence gate refuses to converge on an ambiguous (~half-frame) result.
|
||||
*
|
||||
* Video samples arrive every few frames from the metadata listener (codec thread); overlay samples
|
||||
* from the libass GL thread's pre-swap hook (sparse — only when subtitles swap). Once both planes
|
||||
* have enough samples and the result is confident it converges ONCE, applies + persists, and stops
|
||||
* all probing (zero steady-state overhead). Re-runs each play to re-confirm.
|
||||
*
|
||||
* Threads: probeVideo (codec), probeOverlay (libass GL), onResult (probe reader). The lock guards
|
||||
* only counter/sample state and is NEVER held across the binder/JNI `applyTransactionToFrame` call
|
||||
* (so the GL swap path is never stalled by it). The native slot ring is allocated atomically.
|
||||
*/
|
||||
internal class AssLatencyCalibrator(
|
||||
private val videoSurface: SurfaceView,
|
||||
private val overlaySurface: SurfaceView,
|
||||
private val onCalibrated: (Int) -> Unit,
|
||||
private val onDone: () -> Unit,
|
||||
private val log: (String) -> Unit
|
||||
) {
|
||||
private val lock = Any()
|
||||
private val finished = AtomicBoolean(false)
|
||||
private val applyFail = AtomicInteger(0)
|
||||
|
||||
@Volatile private var frameIntervalNs: Long = 0L
|
||||
|
||||
@Volatile private var converged = false
|
||||
|
||||
@Volatile private var stopped = false
|
||||
|
||||
private var videoFrames = 0
|
||||
private var videoAttempts = 0
|
||||
private var overlaySwaps = 0
|
||||
private var overlayAttempts = 0
|
||||
private val videoRel = ArrayDeque<Double>()
|
||||
private val overlayRel = ArrayDeque<Double>()
|
||||
|
||||
fun start() {
|
||||
SurfaceTxProbe.sink = { tag, latch, release, count, state, source, cb ->
|
||||
onResult(tag, latch, release, count, state, source, cb)
|
||||
}
|
||||
log("calibration started (API ${Build.VERSION.SDK_INT})")
|
||||
}
|
||||
|
||||
fun probeVideo(releaseTimeNs: Long, fps: Float) {
|
||||
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
|
||||
if (fps > 1f) frameIntervalNs = (1_000_000_000.0 / fps).toLong()
|
||||
var doAttach = false
|
||||
var giveUp = false
|
||||
synchronized(lock) {
|
||||
videoFrames++
|
||||
if (videoFrames > GIVEUP_FRAMES) {
|
||||
giveUp = true
|
||||
} else if (videoAttempts < VIDEO_ATTEMPT_CAP && videoFrames % VIDEO_EVERY == 0) {
|
||||
videoAttempts++
|
||||
doAttach = true
|
||||
}
|
||||
}
|
||||
if (giveUp) {
|
||||
finishIncomplete()
|
||||
} else if (doAttach) {
|
||||
attach(videoSurface, releaseTimeNs, SurfaceTxProbe.SOURCE_VIDEO)
|
||||
}
|
||||
}
|
||||
|
||||
fun probeOverlay(releaseTimeNs: Long) {
|
||||
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
|
||||
var doAttach = false
|
||||
synchronized(lock) {
|
||||
overlaySwaps++
|
||||
if (overlayAttempts < OVERLAY_ATTEMPT_CAP && overlaySwaps % OVERLAY_EVERY == 0) {
|
||||
overlayAttempts++
|
||||
doAttach = true
|
||||
}
|
||||
}
|
||||
if (doAttach) attach(overlaySurface, releaseTimeNs, SurfaceTxProbe.SOURCE_OVERLAY)
|
||||
}
|
||||
|
||||
/** Never called while holding [lock]: applyTransactionToFrame is a binder call and runs on the
|
||||
* GL swap path. The native slot allocation is atomic, so concurrent callers are safe. */
|
||||
@RequiresApi(34)
|
||||
private fun attach(surface: SurfaceView, releaseTimeNs: Long, source: Int) {
|
||||
try {
|
||||
val tx = SurfaceControl.Transaction()
|
||||
SurfaceTxProbe.nativeAttach(tx, releaseTimeNs, source)
|
||||
surface.applyTransactionToFrame(tx)
|
||||
} catch (t: Throwable) {
|
||||
if (applyFail.incrementAndGet() == 1) {
|
||||
log("applyTransactionToFrame failed: ${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onResult(
|
||||
tag: Long,
|
||||
latchNs: Long,
|
||||
releaseNs: Long,
|
||||
surfaceCount: Int,
|
||||
fenceState: Int,
|
||||
source: Int,
|
||||
callbackNs: Long
|
||||
) {
|
||||
if (surfaceCount <= 0 || fenceState != FENCE_OK || releaseNs <= 0) return
|
||||
val relMs = (releaseNs - tag) / 1_000_000.0
|
||||
var result: Int? = null
|
||||
synchronized(lock) {
|
||||
if (converged || stopped) return
|
||||
val list = if (source == SurfaceTxProbe.SOURCE_OVERLAY) overlayRel else videoRel
|
||||
val window = if (source == SurfaceTxProbe.SOURCE_OVERLAY) OVERLAY_WINDOW else VIDEO_WINDOW
|
||||
list.addLast(relMs)
|
||||
while (list.size > window) list.removeFirst() // keep a recent window so medians stay fresh
|
||||
result = tryComputeOffset()
|
||||
}
|
||||
result?.let {
|
||||
onCalibrated(it)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
private fun tryComputeOffset(): Int? {
|
||||
val frameMs = frameIntervalNs / 1_000_000.0
|
||||
if (frameMs <= 0.5) return null
|
||||
if (videoRel.size < VIDEO_MIN || overlayRel.size < OVERLAY_MIN) return null
|
||||
val medV = median(videoRel)
|
||||
val medO = median(overlayRel)
|
||||
val offsetMs = medV - medO
|
||||
val raw = offsetMs / frameMs
|
||||
val frames = raw.roundToInt()
|
||||
// Confidence gate: only trust a measurement that points clearly at an integer frame count.
|
||||
// An ambiguous ~half-frame result (corruption / drift / wrong fps) keeps collecting instead.
|
||||
if (abs(raw - frames) > CONFIDENCE_TOL) return null
|
||||
val clamped = frames.coerceIn(-2, 2)
|
||||
converged = true
|
||||
log(
|
||||
"CALIBRATED offsetFrames=$clamped raw=${"%.2f".format(raw)} " +
|
||||
"(video=${"%.1f".format(medV)}ms − overlay=${"%.1f".format(medO)}ms = ${"%.1f".format(offsetMs)}ms " +
|
||||
"/ frameMs=${"%.2f".format(frameMs)}) samples video=${videoRel.size} overlay=${overlayRel.size} " +
|
||||
"applyFail=${applyFail.get()}"
|
||||
)
|
||||
return clamped
|
||||
}
|
||||
|
||||
private fun finishIncomplete() {
|
||||
if (converged || stopped) return
|
||||
log(
|
||||
"calibration incomplete after $videoFrames frames " +
|
||||
"(video=${videoRel.size} overlay=${overlayRel.size}); keeping seed"
|
||||
)
|
||||
finish()
|
||||
}
|
||||
|
||||
fun stop() = finish()
|
||||
|
||||
private fun finish() {
|
||||
if (!finished.compareAndSet(false, true)) return
|
||||
stopped = true
|
||||
SurfaceTxProbe.sink = null
|
||||
onDone()
|
||||
}
|
||||
|
||||
private fun median(xs: Collection<Double>): Double {
|
||||
val s = xs.sorted()
|
||||
val n = s.size
|
||||
return if (n % 2 == 1) s[n / 2] else (s[n / 2 - 1] + s[n / 2]) / 2.0
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val FENCE_OK = 3
|
||||
private const val VIDEO_EVERY = 2
|
||||
private const val OVERLAY_EVERY = 1 // overlay swaps are already sparse
|
||||
private const val VIDEO_MIN = 40
|
||||
private const val OVERLAY_MIN = 12
|
||||
private const val VIDEO_WINDOW = 60 // recent-sample window for the median
|
||||
private const val OVERLAY_WINDOW = 40
|
||||
private const val VIDEO_ATTEMPT_CAP = 200 // ~16s @24fps/2 of video probing, then the window freezes
|
||||
private const val OVERLAY_ATTEMPT_CAP = 60
|
||||
private const val CONFIDENCE_TOL = 0.33 // |raw − round(raw)| must be within ⅓ frame to converge
|
||||
private const val GIVEUP_FRAMES = 1800 // ~75s @24fps without enough confident overlay samples
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.MimeTypes
|
||||
|
||||
internal fun isPassthroughAudioMimeType(mimeType: String): Boolean = when (mimeType) {
|
||||
"audio/ac3",
|
||||
"audio/eac3",
|
||||
"audio/eac3-joc",
|
||||
"audio/ac4",
|
||||
"audio/vnd.dts",
|
||||
"audio/vnd.dts.hd",
|
||||
"audio/vnd.dts.uhd",
|
||||
MimeTypes.AUDIO_TRUEHD -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
internal fun shouldBlockDirectOutputForPassthrough(mimeType: String, audioPassthroughEnabled: Boolean): Boolean = !audioPassthroughEnabled && isPassthroughAudioMimeType(mimeType)
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.io.EOFException
|
||||
|
||||
/** Shared whole-sample buffering protocol for TrackOutput transforms. */
|
||||
abstract class BufferedTransformingTrackOutput(
|
||||
protected val delegate: TrackOutput,
|
||||
initialBufferSize: Int,
|
||||
initialReadBufferSize: Int = initialBufferSize
|
||||
) : TrackOutput {
|
||||
protected var inputBuffer = ByteArray(initialBufferSize)
|
||||
private set
|
||||
|
||||
private var inputLength = 0
|
||||
private var buffering = false
|
||||
private var readBuffer = ByteArray(initialReadBufferSize)
|
||||
private val outputParsable = ParsableByteArray()
|
||||
|
||||
protected abstract val transformEnabled: Boolean
|
||||
protected abstract val transformedBuffer: ByteArray
|
||||
|
||||
/** Returns transformed length, or a negative value to drop the sample. */
|
||||
protected abstract fun transformSample(inputLength: Int, flags: Int): Int
|
||||
open override fun format(format: Format) = delegate.format(format)
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (!transformEnabled) {
|
||||
return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
}
|
||||
|
||||
buffering = true
|
||||
if (readBuffer.size < length) readBuffer = ByteArray(length)
|
||||
val bytesRead = input.read(readBuffer, 0, length)
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT && !allowEndOfInput) throw EOFException()
|
||||
if (bytesRead > 0) appendInput(readBuffer, bytesRead)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (!transformEnabled) {
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = true
|
||||
ensureInputCapacity(inputLength + length)
|
||||
data.readBytes(inputBuffer, inputLength, length)
|
||||
inputLength += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (!transformEnabled || !buffering) {
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = false
|
||||
val sourceLength = inputLength
|
||||
inputLength = 0
|
||||
val transformedLength = transformSample(sourceLength, flags)
|
||||
if (transformedLength < 0) return
|
||||
|
||||
outputParsable.reset(transformedBuffer, transformedLength)
|
||||
delegate.sampleData(outputParsable, transformedLength, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
delegate.sampleMetadata(timeUs, flags, transformedLength, 0, cryptoData)
|
||||
}
|
||||
|
||||
private fun appendInput(source: ByteArray, length: Int) {
|
||||
ensureInputCapacity(inputLength + length)
|
||||
System.arraycopy(source, 0, inputBuffer, inputLength, length)
|
||||
inputLength += length
|
||||
}
|
||||
|
||||
private fun ensureInputCapacity(needed: Int) {
|
||||
if (inputBuffer.size < needed) {
|
||||
inputBuffer = inputBuffer.copyOf(maxOf(needed, inputBuffer.size * 2))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,24 +258,40 @@ object DoviBridge {
|
||||
}
|
||||
|
||||
private fun describeDisplayHdrCapabilities(display: Display): String {
|
||||
val hdrCapabilities = display.hdrCapabilities
|
||||
val hdrCapabilities = getDisplayHdrCapabilities(display)
|
||||
val parts = mutableListOf(
|
||||
"display=${display.displayId}:${display.name}",
|
||||
"activeMode=${describeDisplayMode(display.mode)}",
|
||||
"hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}",
|
||||
"desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
|
||||
"activeMode=${describeDisplayMode(display.mode)}"
|
||||
)
|
||||
if (hdrCapabilities == null) {
|
||||
parts += "hdrCapabilities=unavailable"
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
parts += "hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}"
|
||||
parts += "desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
|
||||
"maxAvg=${formatLuminance(hdrCapabilities.desiredMaxAverageLuminance)}, " +
|
||||
"min=${formatLuminance(hdrCapabilities.desiredMinLuminance)}"
|
||||
)
|
||||
}
|
||||
parts += "supportedModes=${display.supportedModes.joinToString(prefix = "[", postfix = "]") { describeDisplayMode(it) }}"
|
||||
return parts.joinToString(prefix = "{", postfix = "}")
|
||||
}
|
||||
|
||||
private fun getDisplayHdrTypes(display: Display): IntArray = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
display.mode.supportedHdrTypes
|
||||
} else {
|
||||
private fun getDisplayHdrCapabilities(display: Display): Display.HdrCapabilities? = runCatching {
|
||||
display.hdrCapabilities
|
||||
}.onFailure { Log.w(TAG, "Failed to query display HDR capabilities", it) }.getOrNull()
|
||||
|
||||
private fun getDisplayHdrTypes(display: Display): IntArray {
|
||||
val hdrCapabilities = getDisplayHdrCapabilities(display) ?: return IntArray(0)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
return runCatching { display.mode.supportedHdrTypes }.getOrElse { error ->
|
||||
Log.w(TAG, "Failed to query mode HDR types; falling back to display HDR capabilities", error)
|
||||
@Suppress("DEPRECATION")
|
||||
hdrCapabilities.supportedHdrTypes
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
display.hdrCapabilities.supportedHdrTypes
|
||||
return hdrCapabilities.supportedHdrTypes
|
||||
}
|
||||
|
||||
private fun describeDisplayMode(mode: Display.Mode): String {
|
||||
|
||||
+43
-99
@@ -2,10 +2,8 @@ package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
|
||||
/**
|
||||
@@ -28,10 +26,10 @@ import androidx.media3.extractor.TrackOutput
|
||||
* All buffers are reused across samples to minimize GC pressure on the hot path.
|
||||
*/
|
||||
class DoviConvertingTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
delegate: TrackOutput,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val emitLog: ((String, String, String) -> Unit)? = null
|
||||
) : TrackOutput {
|
||||
) : BufferedTransformingTrackOutput(delegate, INITIAL_BUFFER_SIZE) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DoviConvertTrack"
|
||||
@@ -65,12 +63,8 @@ class DoviConvertingTrackOutput(
|
||||
get() = if (sampleCount > 0) totalSampleProcessingTimeUs / sampleCount else 0L
|
||||
|
||||
// Reusable buffers — grown as needed, never shrunk
|
||||
private var sampleBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var sampleLen = 0
|
||||
private var outputBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var outputLen = 0
|
||||
private val outputParsable = ParsableByteArray()
|
||||
private var buffering = false
|
||||
|
||||
// Sample counter for periodic logging
|
||||
private var sampleCount = 0L
|
||||
@@ -79,6 +73,7 @@ class DoviConvertingTrackOutput(
|
||||
private var totalSampleProcessingTimeUs = 0L
|
||||
private var loggedSupplementalWrapper = false
|
||||
private var loggedEncryptedSupplementalPassthrough = false
|
||||
private var outputIsProcessed = false
|
||||
|
||||
override fun format(format: Format) {
|
||||
if (!conversionActive) {
|
||||
@@ -135,55 +130,15 @@ class DoviConvertingTrackOutput(
|
||||
delegate.format(format)
|
||||
}
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (!conversionActive) {
|
||||
return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
}
|
||||
override val transformEnabled: Boolean
|
||||
get() = conversionActive
|
||||
|
||||
buffering = true
|
||||
ensureSampleCapacity(sampleLen + length)
|
||||
val bytesRead = input.read(sampleBuf, sampleLen, length)
|
||||
if (bytesRead > 0) {
|
||||
sampleLen += bytesRead
|
||||
}
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (!conversionActive) {
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = true
|
||||
ensureSampleCapacity(sampleLen + length)
|
||||
data.readBytes(sampleBuf, sampleLen, length)
|
||||
sampleLen += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (!conversionActive || !buffering) {
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = false
|
||||
val srcLen = sampleLen
|
||||
sampleLen = 0
|
||||
override val transformedBuffer: ByteArray
|
||||
get() = if (outputIsProcessed) outputBuf else inputBuffer
|
||||
|
||||
override fun transformSample(inputLength: Int, flags: Int): Int {
|
||||
val processStartNs = System.nanoTime()
|
||||
val success = if ((flags and C.BUFFER_FLAG_ENCRYPTED) != 0) {
|
||||
outputIsProcessed = if ((flags and C.BUFFER_FLAG_ENCRYPTED) != 0) {
|
||||
if (!loggedEncryptedSupplementalPassthrough && (flags and C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA) != 0) {
|
||||
loggedEncryptedSupplementalPassthrough = true
|
||||
logWarn("Encrypted supplemental sample encountered, passing raw sample")
|
||||
@@ -191,25 +146,20 @@ class DoviConvertingTrackOutput(
|
||||
false
|
||||
} else {
|
||||
try {
|
||||
processSampleData(flags, srcLen)
|
||||
processSampleData(flags, inputLength)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
logError("NAL processing failed, passing raw sample", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
val outLen = if (success) outputLen else srcLen
|
||||
val outBuf = if (success) outputBuf else sampleBuf
|
||||
if (success) {
|
||||
val transformedLength = if (outputIsProcessed) outputLen else inputLength
|
||||
if (outputIsProcessed) {
|
||||
recordSampleProcessing((System.nanoTime() - processStartNs) / 1_000L)
|
||||
}
|
||||
|
||||
// Skip empty samples (all NALs were DV layers) — don't confuse the decoder
|
||||
if (outLen == 0) return
|
||||
|
||||
outputParsable.reset(outBuf, outLen)
|
||||
delegate.sampleData(outputParsable, outLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
delegate.sampleMetadata(timeUs, flags, outLen, 0, cryptoData)
|
||||
// Skip empty samples (all NALs were DV layers) — don't confuse the decoder.
|
||||
return if (transformedLength == 0) -1 else transformedLength
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -231,7 +181,7 @@ class DoviConvertingTrackOutput(
|
||||
return
|
||||
}
|
||||
|
||||
val mainSampleLen = readInt32BE(sampleBuf, 0)
|
||||
val mainSampleLen = readInt32BE(inputBuffer, 0)
|
||||
if (mainSampleLen < 0 || mainSampleLen > dataLen - 4) {
|
||||
logWarn("Bad supplemental sample: mainLen=$mainSampleLen total=$dataLen")
|
||||
copyRawSample(dataLen)
|
||||
@@ -243,7 +193,7 @@ class DoviConvertingTrackOutput(
|
||||
loggedSupplementalWrapper = true
|
||||
logDebug(
|
||||
"Supplemental wrapper detected: total=${dataLen}B, main=${mainSampleLen}B, " +
|
||||
"supplemental=${supplementalLen}B, innerFirstBytes=${formatBytes(sampleBuf, 4, 8)}"
|
||||
"supplemental=${supplementalLen}B, innerFirstBytes=${formatBytes(inputBuffer, 4, 8)}"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -259,7 +209,7 @@ class DoviConvertingTrackOutput(
|
||||
System.arraycopy(outputBuf, 0, outputBuf, 4, processedMainLen)
|
||||
writeInt32BE(outputBuf, 0, processedMainLen)
|
||||
if (supplementalLen > 0) {
|
||||
System.arraycopy(sampleBuf, 4 + mainSampleLen, outputBuf, 4 + processedMainLen, supplementalLen)
|
||||
System.arraycopy(inputBuffer, 4 + mainSampleLen, outputBuf, 4 + processedMainLen, supplementalLen)
|
||||
}
|
||||
outputLen = 4 + processedMainLen + supplementalLen
|
||||
|
||||
@@ -282,7 +232,7 @@ class DoviConvertingTrackOutput(
|
||||
outputLen = 0
|
||||
if (dataLen < 4) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
System.arraycopy(sampleBuf, dataOffset, outputBuf, 0, dataLen)
|
||||
System.arraycopy(inputBuffer, dataOffset, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
return
|
||||
}
|
||||
@@ -290,22 +240,22 @@ class DoviConvertingTrackOutput(
|
||||
// Auto-detect: Annex B starts with 00 00 00 01 or 00 00 01
|
||||
val isAnnexB = (
|
||||
dataLen >= 4 &&
|
||||
sampleBuf[dataOffset] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 1] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 2] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 3] == 1.toByte()
|
||||
inputBuffer[dataOffset] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 1] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 2] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 3] == 1.toByte()
|
||||
) ||
|
||||
(
|
||||
dataLen >= 3 &&
|
||||
sampleBuf[dataOffset] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 1] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 2] == 1.toByte()
|
||||
inputBuffer[dataOffset] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 1] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 2] == 1.toByte()
|
||||
)
|
||||
|
||||
if (sampleCount == 0L) {
|
||||
logDebug(
|
||||
"NAL format detected: ${if (isAnnexB) "Annex B" else "length-prefixed"}, " +
|
||||
"first bytes: ${formatBytes(sampleBuf, dataOffset, 8)}"
|
||||
"first bytes: ${formatBytes(inputBuffer, dataOffset, 8)}"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -323,11 +273,11 @@ class DoviConvertingTrackOutput(
|
||||
var scEnd = -1
|
||||
var i = dataOffset
|
||||
while (i < dataEnd - 2) {
|
||||
if (sampleBuf[i] == 0.toByte() && sampleBuf[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataEnd && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
|
||||
if (inputBuffer[i] == 0.toByte() && inputBuffer[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataEnd && inputBuffer[i + 2] == 0.toByte() && inputBuffer[i + 3] == 1.toByte()) {
|
||||
scEnd = i + 4
|
||||
break
|
||||
} else if (sampleBuf[i + 2] == 1.toByte()) {
|
||||
} else if (inputBuffer[i + 2] == 1.toByte()) {
|
||||
scEnd = i + 3
|
||||
break
|
||||
}
|
||||
@@ -337,7 +287,7 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
if (scEnd < 0) {
|
||||
// No start codes found — pass through
|
||||
System.arraycopy(sampleBuf, dataOffset, outputBuf, 0, dataLen)
|
||||
System.arraycopy(inputBuffer, dataOffset, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
sampleCount++
|
||||
return
|
||||
@@ -350,11 +300,11 @@ class DoviConvertingTrackOutput(
|
||||
var nalEnd = dataEnd
|
||||
i = nalStart
|
||||
while (i < dataEnd - 2) {
|
||||
if (sampleBuf[i] == 0.toByte() && sampleBuf[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataEnd && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
|
||||
if (inputBuffer[i] == 0.toByte() && inputBuffer[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataEnd && inputBuffer[i + 2] == 0.toByte() && inputBuffer[i + 3] == 1.toByte()) {
|
||||
nalEnd = i
|
||||
break
|
||||
} else if (sampleBuf[i + 2] == 1.toByte()) {
|
||||
} else if (inputBuffer[i + 2] == 1.toByte()) {
|
||||
nalEnd = i
|
||||
break
|
||||
}
|
||||
@@ -369,7 +319,7 @@ class DoviConvertingTrackOutput(
|
||||
ensureOutputCapacity(outputLen + 4 + nalLen)
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
System.arraycopy(sampleBuf, nalStart, outputBuf, outputLen, nalLen)
|
||||
System.arraycopy(inputBuffer, nalStart, outputBuf, outputLen, nalLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
} else if (action == NalAction.CONVERT) {
|
||||
@@ -392,7 +342,7 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
// Advance past the next start code
|
||||
if (nalEnd >= dataEnd) break
|
||||
nalStart = if (nalEnd + 3 < dataEnd && sampleBuf[nalEnd + 2] == 0.toByte() && sampleBuf[nalEnd + 3] == 1.toByte()) {
|
||||
nalStart = if (nalEnd + 3 < dataEnd && inputBuffer[nalEnd + 2] == 0.toByte() && inputBuffer[nalEnd + 3] == 1.toByte()) {
|
||||
nalEnd + 4
|
||||
} else {
|
||||
nalEnd + 3
|
||||
@@ -417,10 +367,10 @@ class DoviConvertingTrackOutput(
|
||||
var stripped = 0
|
||||
|
||||
while (pos + 4 <= dataEnd) {
|
||||
val nalLen = ((sampleBuf[pos].toInt() and 0xFF) shl 24) or
|
||||
((sampleBuf[pos + 1].toInt() and 0xFF) shl 16) or
|
||||
((sampleBuf[pos + 2].toInt() and 0xFF) shl 8) or
|
||||
(sampleBuf[pos + 3].toInt() and 0xFF)
|
||||
val nalLen = ((inputBuffer[pos].toInt() and 0xFF) shl 24) or
|
||||
((inputBuffer[pos + 1].toInt() and 0xFF) shl 16) or
|
||||
((inputBuffer[pos + 2].toInt() and 0xFF) shl 8) or
|
||||
(inputBuffer[pos + 3].toInt() and 0xFF)
|
||||
|
||||
if (nalLen <= 0 || pos + 4 + nalLen > dataEnd) {
|
||||
if (sampleCount < 5) {
|
||||
@@ -435,7 +385,7 @@ class DoviConvertingTrackOutput(
|
||||
ensureOutputCapacity(outputLen + 4 + nalLen)
|
||||
writeInt32BE(outputBuf, outputLen, nalLen)
|
||||
outputLen += 4
|
||||
System.arraycopy(sampleBuf, nalStart, outputBuf, outputLen, nalLen)
|
||||
System.arraycopy(inputBuffer, nalStart, outputBuf, outputLen, nalLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
} else if (action == NalAction.CONVERT) {
|
||||
@@ -486,7 +436,7 @@ class DoviConvertingTrackOutput(
|
||||
while (true) {
|
||||
val startNs = System.nanoTime()
|
||||
val written = DoviBridge.convertRpuNalu(
|
||||
payload = sampleBuf,
|
||||
payload = inputBuffer,
|
||||
payloadOffset = nalStart,
|
||||
payloadLength = nalLen,
|
||||
output = outputBuf,
|
||||
@@ -630,7 +580,7 @@ class DoviConvertingTrackOutput(
|
||||
}
|
||||
|
||||
/** Classify a NAL at sampleBuf[offset..offset+len) without copying. */
|
||||
private fun processNalInline(offset: Int, len: Int): NalAction = classifyNal(sampleBuf, offset, len, convertRpu = dvMode == DvConversionMode.DV81)
|
||||
private fun processNalInline(offset: Int, len: Int): NalAction = classifyNal(inputBuffer, offset, len, convertRpu = dvMode == DvConversionMode.DV81)
|
||||
|
||||
private fun isDvProfile7Codec(codecs: String?): Boolean {
|
||||
val normalized = codecs?.lowercase() ?: return false
|
||||
@@ -662,7 +612,7 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
private fun copyRawSample(dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
System.arraycopy(sampleBuf, 0, outputBuf, 0, dataLen)
|
||||
System.arraycopy(inputBuffer, 0, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
}
|
||||
|
||||
@@ -672,12 +622,6 @@ class DoviConvertingTrackOutput(
|
||||
return (offset until end).joinToString(" ") { "%02X".format(data[it]) }
|
||||
}
|
||||
|
||||
private fun ensureSampleCapacity(needed: Int) {
|
||||
if (sampleBuf.size < needed) {
|
||||
sampleBuf = sampleBuf.copyOf(maxOf(needed, sampleBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureOutputCapacity(needed: Int) {
|
||||
if (outputBuf.size < needed) {
|
||||
outputBuf = outputBuf.copyOf(maxOf(needed, outputBuf.size * 2))
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Stereo downmix coefficient builder (Kodi-style center boost).
|
||||
*
|
||||
* Channel-order assumptions per input count follow the Android channel-mask
|
||||
* bit order that MediaCodec / the FFmpeg extension emit:
|
||||
* 3 = FL FR FC, 4 = FL FR BL BR, 5 = FL FR FC BL BR, 6 = FL FR FC LFE BL BR,
|
||||
* 7 = 6.1 (5.1 + BC), 8 = 7.1 (5.1 + SL SR). LFE is dropped, matching
|
||||
* ffmpeg's default lfe_mix_level=0 (and what the mpv backends produce).
|
||||
*
|
||||
* All coefficients must stay >= 0: ChannelMixingMatrix throws on negatives.
|
||||
*/
|
||||
object DownmixMatrices {
|
||||
const val MIN_DOWNMIX_INPUT_CHANNELS = 3
|
||||
const val MAX_DOWNMIX_INPUT_CHANNELS = 8
|
||||
const val MAX_CENTER_BOOST_DB = 12
|
||||
|
||||
const val SURROUND_GAIN = 0.70710678f // -3 dB
|
||||
private const val BACK_CENTER_GAIN = 0.5f // SURROUND_GAIN split across both outputs
|
||||
|
||||
/** Kodi's mechanism: center coefficient = 10^((-3 + boostDb) / 20); boost 0 is the standard -3 dB. */
|
||||
fun centerGain(centerBoostDb: Int): Float = 10f.pow((-3f + centerBoostDb.coerceIn(0, MAX_CENTER_BOOST_DB)) / 20f)
|
||||
|
||||
/**
|
||||
* Row-major stereo coefficients ([inputChannel * 2 + outputChannel]), or null
|
||||
* when [inputChannels] is not downmixed (mono/stereo pass through; >8ch
|
||||
* unsupported, the caller keeps an identity matrix).
|
||||
*
|
||||
* [normalize] scales the matrix so the loudest output sum is <= 1 (cannot
|
||||
* clip); disabled keeps the original level like Kodi's "maintain original
|
||||
* volume" (the 16-bit mix saturates on clip).
|
||||
*/
|
||||
fun stereoCoefficients(inputChannels: Int, centerBoostDb: Int, normalize: Boolean): FloatArray? {
|
||||
val c = centerGain(centerBoostDb)
|
||||
val s = SURROUND_GAIN
|
||||
val rows: List<FloatArray> = when (inputChannels) {
|
||||
3 -> listOf(fl(), fr(), both(c))
|
||||
4 -> listOf(fl(), fr(), left(s), right(s))
|
||||
5 -> listOf(fl(), fr(), both(c), left(s), right(s))
|
||||
6 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s))
|
||||
7 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s), both(BACK_CENTER_GAIN))
|
||||
8 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s), left(s), right(s))
|
||||
else -> return null
|
||||
}
|
||||
val flat = FloatArray(rows.size * 2)
|
||||
rows.forEachIndexed { i, row ->
|
||||
flat[i * 2] = row[0]
|
||||
flat[i * 2 + 1] = row[1]
|
||||
}
|
||||
if (normalize) {
|
||||
var sumL = 0f
|
||||
var sumR = 0f
|
||||
for (i in rows.indices) {
|
||||
sumL += flat[i * 2]
|
||||
sumR += flat[i * 2 + 1]
|
||||
}
|
||||
val peak = maxOf(sumL, sumR, 1f)
|
||||
if (peak > 1f) {
|
||||
for (i in flat.indices) flat[i] /= peak
|
||||
}
|
||||
}
|
||||
return flat
|
||||
}
|
||||
|
||||
private fun fl() = floatArrayOf(1f, 0f)
|
||||
private fun fr() = floatArrayOf(0f, 1f)
|
||||
private fun left(gain: Float) = floatArrayOf(gain, 0f)
|
||||
private fun right(gain: Float) = floatArrayOf(0f, gain)
|
||||
private fun both(gain: Float) = floatArrayOf(gain, gain)
|
||||
private fun lfe() = floatArrayOf(0f, 0f)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,13 +2,12 @@ package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityManager
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.mpv.MpvPlayerCore
|
||||
import com.edde746.plezy.shared.MpvContentUriResolver
|
||||
import com.edde746.plezy.shared.PlayerChannelBinding
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
@@ -26,18 +25,14 @@ class ExoPlayerPlugin :
|
||||
companion object {
|
||||
private const val TAG = "ExoPlayerPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/exo_player"
|
||||
private const val EVENT_CHANNEL = "com.plezy/exo_player/events"
|
||||
private const val MPV_FALLBACK_SWITCH_TIMEOUT_MS = 15_000L
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
private val channels = PlayerChannelBinding(METHOD_CHANNEL, this, this, TAG)
|
||||
private val mainHandler get() = channels.mainHandler
|
||||
private var playerCore: ExoPlayerCore? = null
|
||||
private var mpvCore: MpvPlayerCore? = null // MPV fallback player
|
||||
private var usingMpvFallback: Boolean = false
|
||||
private var fallbackInProgress: Boolean = false
|
||||
private var pendingMpvFallbackSwitchGeneration: Int? = null
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
|
||||
@@ -47,7 +42,6 @@ class ExoPlayerPlugin :
|
||||
private data class ObservedProperty(val id: Int, val format: String)
|
||||
private val observedProperties = LinkedHashMap<String, ObservedProperty>()
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private var configuredBufferSizeBytes: Int? = null
|
||||
|
||||
private var sessionGeneration = 0
|
||||
@@ -60,23 +54,16 @@ class ExoPlayerPlugin :
|
||||
// fallback is already active) so one playback's properties never leak into
|
||||
// the next session's fallback.
|
||||
private val pendingMpvProperties = LinkedHashMap<String, String>()
|
||||
private var currentExternalSubtitles: List<Map<String, Any?>>? = null
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
|
||||
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
|
||||
eventChannel.setStreamHandler(this)
|
||||
|
||||
Log.d(TAG, "Attached to engine")
|
||||
channels.attach(binding)
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
eventChannel.setStreamHandler(null)
|
||||
Log.d(TAG, "Detached from engine")
|
||||
channels.detach()
|
||||
}
|
||||
|
||||
// ActivityAware
|
||||
@@ -95,7 +82,7 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
currentExternalSubtitles = null
|
||||
pendingMpvProperties.clear()
|
||||
activity = null
|
||||
activityBinding = null
|
||||
@@ -111,7 +98,6 @@ class ExoPlayerPlugin :
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
sessionGeneration++
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity for config changes")
|
||||
@@ -120,13 +106,11 @@ class ExoPlayerPlugin :
|
||||
// EventChannel.StreamHandler
|
||||
|
||||
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
|
||||
eventSink = events
|
||||
Log.d(TAG, "Event stream connected")
|
||||
channels.listen(events)
|
||||
}
|
||||
|
||||
override fun onCancel(arguments: Any?) {
|
||||
eventSink = null
|
||||
Log.d(TAG, "Event stream disconnected")
|
||||
channels.cancel()
|
||||
}
|
||||
|
||||
// MethodChannel.MethodCallHandler
|
||||
@@ -169,6 +153,8 @@ class ExoPlayerPlugin :
|
||||
"setVideoZoom" -> handleSetVideoZoom(call, result)
|
||||
"setDvConversionMode" -> handleSetDvConversionMode(call, result)
|
||||
"setAudioNormalization" -> handleSetAudioNormalization(call, result)
|
||||
"setAudioPassthrough" -> handleSetAudioPassthrough(call, result)
|
||||
"setAudioDownmix" -> handleSetAudioDownmix(call, result)
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"setMpvProperty" -> handleSetMpvProperty(call, result)
|
||||
"setLogLevel" -> {
|
||||
@@ -201,7 +187,13 @@ class ExoPlayerPlugin :
|
||||
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
|
||||
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
|
||||
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
|
||||
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
|
||||
val assVideoLatencyFrames = call.argument<Int>("assVideoLatencyFrames") ?: 0
|
||||
val subtitleRenderScale = call.argument<Double>("subtitleRenderScale")?.toFloat() ?: 1.0f
|
||||
configuredBufferSizeBytes = bufferSizeBytes
|
||||
// Global libass overlay render scale — set before the player/handler is built below so the
|
||||
// first frame-size apply already uses it.
|
||||
AssHandler.setRenderScale(subtitleRenderScale)
|
||||
|
||||
currentActivity.runOnUiThread {
|
||||
sessionGeneration++
|
||||
@@ -214,29 +206,37 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
}
|
||||
|
||||
try {
|
||||
playerCore = ExoPlayerCore(currentActivity).apply {
|
||||
val core = ExoPlayerCore(currentActivity).apply {
|
||||
delegate = this@ExoPlayerPlugin
|
||||
this.debugLoggingEnabled = this@ExoPlayerPlugin.debugLoggingEnabled
|
||||
}
|
||||
val success = playerCore?.initialize(
|
||||
playerCore = core
|
||||
val success = core.initialize(
|
||||
bufferSizeBytes = bufferSizeBytes,
|
||||
tunnelingEnabled = tunnelingEnabled
|
||||
) ?: false
|
||||
if (success && playerCore?.setDebugDvConversionMode(dvConversionMode) != true) {
|
||||
tunnelingEnabled = tunnelingEnabled,
|
||||
audioPassthroughEnabled = audioPassthroughEnabled
|
||||
)
|
||||
if (!success) {
|
||||
if (playerCore === core) playerCore = null
|
||||
result.success(false)
|
||||
return@runOnUiThread
|
||||
}
|
||||
if (core.setDebugDvConversionMode(dvConversionMode) != true) {
|
||||
Log.w(TAG, "Invalid DV conversion mode during initialize: $dvConversionMode")
|
||||
}
|
||||
// Seed from this device's persisted calibration, falling back to the Dart perf-tier proxy.
|
||||
core.seedAssVideoLatencyFrames(assVideoLatencyFrames)
|
||||
core.setVisible(false)
|
||||
|
||||
// Start hidden
|
||||
playerCore?.setVisible(false)
|
||||
|
||||
Log.d(TAG, "Initialized: $success")
|
||||
result.success(success)
|
||||
Log.d(TAG, "Initialized: true")
|
||||
result.success(true)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to initialize: ${e.message}", e)
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
result.error("INIT_FAILED", e.message, null)
|
||||
}
|
||||
}
|
||||
@@ -251,7 +251,7 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
currentExternalSubtitles = null
|
||||
pendingMpvProperties.clear()
|
||||
Log.d(TAG, "Disposed")
|
||||
result.success(null)
|
||||
@@ -263,6 +263,7 @@ class ExoPlayerPlugin :
|
||||
val uri = call.argument<String>("uri")
|
||||
val headers = call.argument<Map<String, String>>("headers")
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
val hasStartPosition = call.argument<Boolean>("hasStartPosition") ?: (startPositionMs > 0L)
|
||||
val autoPlay = call.argument<Boolean>("autoPlay") ?: true
|
||||
val isLive = call.argument<Boolean>("isLive") ?: false
|
||||
val externalSubtitles = call.argument<List<Map<String, Any?>>>("externalSubtitles")
|
||||
@@ -271,37 +272,68 @@ class ExoPlayerPlugin :
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
val currentActivity = activity
|
||||
if (currentActivity == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
return
|
||||
}
|
||||
val externalSubtitleSnapshot = externalSubtitles?.map { it.toMap() }
|
||||
currentExternalSubtitles = externalSubtitleSnapshot
|
||||
|
||||
// Only clear pending MPV state when MPV is the active backend. A same-core
|
||||
// MPV reload must not inherit a fallback switch that was armed for the
|
||||
// previous load. When ExoPlayer is active, keep queued properties for a
|
||||
// potential ExoPlayer→MPV fallback.
|
||||
if (usingMpvFallback) {
|
||||
clearPendingMpvFallbackSwitch()
|
||||
pendingMpvProperties.clear()
|
||||
val generation = sessionGeneration
|
||||
MpvContentUriResolver.resolve(uri, currentActivity.contentResolver, mainHandler) { source ->
|
||||
if (generation != sessionGeneration || activity !== currentActivity || !usingMpvFallback) {
|
||||
source.closeIfUnused()
|
||||
result.success(null)
|
||||
return@resolve
|
||||
}
|
||||
loadMpvMedia(
|
||||
source.value,
|
||||
headers,
|
||||
startPositionMs,
|
||||
hasStartPosition,
|
||||
autoPlay,
|
||||
externalSubtitleSnapshot
|
||||
)
|
||||
result.success(null)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
// MPV: Build loadfile command with options
|
||||
val startSeconds = startPositionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add("start=$startSeconds")
|
||||
if (!autoPlay) options.add("pause=yes")
|
||||
options.add("sid=no")
|
||||
options.add("secondary-sid=no")
|
||||
headers?.forEach { (key, value) ->
|
||||
options.add("http-header-fields-append=$key: $value")
|
||||
}
|
||||
val optionsStr = options.joinToString(",")
|
||||
// Convert content:// URIs to fdclose:// for MPV (SAF SD card downloads)
|
||||
val mpvUri = openContentFd(uri)?.let { "fdclose://$it" } ?: uri
|
||||
mpvCore?.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
|
||||
} else {
|
||||
playerCore?.open(uri, headers, startPositionMs, autoPlay, isLive, externalSubtitles)
|
||||
}
|
||||
currentActivity.runOnUiThread {
|
||||
playerCore?.open(uri, headers, startPositionMs, autoPlay, isLive, externalSubtitleSnapshot)
|
||||
result.success(null)
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadMpvMedia(
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
startPositionMs: Long,
|
||||
hasStartPosition: Boolean,
|
||||
autoPlay: Boolean,
|
||||
externalSubtitles: List<Map<String, Any?>>?
|
||||
) {
|
||||
val startSeconds = startPositionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add(if (hasStartPosition && startPositionMs > 0L) "start=$startSeconds" else "start=none")
|
||||
if (!autoPlay) options.add("pause=yes")
|
||||
options.add("sid=no")
|
||||
options.add("secondary-sid=no")
|
||||
appendExternalSubtitleOptions(options, externalSubtitles)
|
||||
appendHttpHeaderOptions(options, headers)
|
||||
val optionsStr = options.joinToString(",")
|
||||
mpvCore?.command(arrayOf("loadfile", uri, "replace", "-1", optionsStr)) { success ->
|
||||
if (success && autoPlay) {
|
||||
mpvCore?.setProperty("pause", "no")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handlePlay(result: MethodChannel.Result) {
|
||||
@@ -441,11 +473,18 @@ class ExoPlayerPlugin :
|
||||
activity?.runOnUiThread {
|
||||
if (usingMpvFallback) {
|
||||
val selectFlag = if (select) "select" else "auto"
|
||||
mpvCore?.command(arrayOf("sub-add", uri, selectFlag, title ?: "External"))
|
||||
val core = mpvCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
} else {
|
||||
core.command(arrayOf("sub-add", uri, selectFlag, title ?: "External")) {
|
||||
result.success(null)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
playerCore?.addSubtitleTrack(uri, title, language, mimeType, select)
|
||||
result.success(null)
|
||||
}
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
@@ -478,22 +517,24 @@ class ExoPlayerPlugin :
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
|
||||
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
|
||||
val onComplete: (Boolean) -> Unit = { switched -> result.success(switched) }
|
||||
if (usingMpvFallback) {
|
||||
val core = mpvCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
} else {
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, onComplete)
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, onComplete)
|
||||
}
|
||||
} else {
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
} else {
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, onComplete)
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, onComplete)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -635,6 +676,45 @@ class ExoPlayerPlugin :
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
|
||||
private fun handleSetAudioDownmix(call: MethodCall, result: MethodChannel.Result) {
|
||||
val enabled = call.argument<Boolean>("enabled")
|
||||
if (enabled == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'enabled'", null)
|
||||
return
|
||||
}
|
||||
val centerBoostDb = call.argument<Int>("centerBoostDb") ?: 0
|
||||
val normalize = call.argument<Boolean>("normalize") ?: true
|
||||
if (usingMpvFallback) {
|
||||
// mpv applies downmix via the audio-channels/audio-swresample-o
|
||||
// properties the Dart layer also sends through setMpvProperty.
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
playerCore?.setAudioDownmix(enabled, centerBoostDb, normalize)
|
||||
result.success(true)
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
|
||||
private fun handleSetAudioPassthrough(call: MethodCall, result: MethodChannel.Result) {
|
||||
val enabled = call.argument<Boolean>("enabled")
|
||||
if (enabled == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'enabled'", null)
|
||||
return
|
||||
}
|
||||
val audioSpdif = if (enabled) "ac3,eac3,dts,dts-hd,truehd" else ""
|
||||
pendingMpvProperties["audio-spdif"] = audioSpdif
|
||||
if (usingMpvFallback) {
|
||||
mpvCore?.setProperty("audio-spdif", audioSpdif)
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
playerCore?.setAudioPassthrough(enabled)
|
||||
result.success(true)
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
|
||||
private fun handleSetMpvProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val value = call.argument<String>("value")
|
||||
@@ -652,6 +732,7 @@ class ExoPlayerPlugin :
|
||||
// mpv semantics mirrored on the libass overlay: anchor non-positioned ASS
|
||||
// events to the visible screen (Dart sets 'yes' for cover mode / zoom > 1)
|
||||
"sub-ass-force-margins" -> playerCore?.setAssForceMargins(value == "yes")
|
||||
"force-seekable" -> playerCore?.setForceSeekable(value == "yes")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -667,8 +748,15 @@ class ExoPlayerPlugin :
|
||||
private fun handleGetStats(result: MethodChannel.Result) {
|
||||
if (usingMpvFallback) {
|
||||
Thread {
|
||||
val stats = getMpvStats()
|
||||
activity?.runOnUiThread { result.success(stats) }
|
||||
val stats = try {
|
||||
getMpvStats()
|
||||
} catch (error: Throwable) {
|
||||
Log.w(TAG, "Failed to collect mpv fallback stats", error)
|
||||
mapOf("playerType" to "mpv")
|
||||
}
|
||||
// Platform-channel replies must return to Android's platform thread.
|
||||
// Do not depend on an Activity: it may detach while this work runs.
|
||||
mainHandler.post { result.success(stats) }
|
||||
}.start()
|
||||
} else {
|
||||
activity?.runOnUiThread {
|
||||
@@ -683,59 +771,7 @@ class ExoPlayerPlugin :
|
||||
* Queries relevant MPV properties and returns them in a map format
|
||||
* compatible with the performance overlay.
|
||||
*/
|
||||
private fun getMpvStats(): Map<String, Any?> {
|
||||
val mpv = mpvCore ?: return mapOf("playerType" to "mpv")
|
||||
|
||||
val hasVideo = mpv.getProperty("video-params/w") != null
|
||||
|
||||
val stats = mutableMapOf<String, Any?>(
|
||||
"playerType" to "mpv",
|
||||
// Video metrics
|
||||
"video-codec" to mpv.getProperty("video-codec"),
|
||||
"video-params/w" to mpv.getProperty("video-params/w"),
|
||||
"video-params/h" to mpv.getProperty("video-params/h"),
|
||||
"videoWidth" to mpv.getProperty("dwidth"),
|
||||
"videoHeight" to mpv.getProperty("dheight"),
|
||||
"container-fps" to mpv.getProperty("container-fps"),
|
||||
"estimated-vf-fps" to mpv.getProperty("estimated-vf-fps"),
|
||||
"video-bitrate" to mpv.getProperty("video-bitrate"),
|
||||
"hwdec-current" to mpv.getProperty("hwdec-current"),
|
||||
// Audio metrics
|
||||
"audio-codec-name" to mpv.getProperty("audio-codec-name"),
|
||||
"audio-params/samplerate" to mpv.getProperty("audio-params/samplerate"),
|
||||
"audio-params/hr-channels" to mpv.getProperty("audio-params/hr-channels"),
|
||||
"audio-bitrate" to mpv.getProperty("audio-bitrate"),
|
||||
// Performance metrics
|
||||
"total-avsync-change" to mpv.getProperty("total-avsync-change"),
|
||||
"cache-used" to mpv.getProperty("cache-used"),
|
||||
"demuxer-max-bytes" to mpv.getProperty("demuxer-max-bytes"),
|
||||
"cache-speed" to mpv.getProperty("cache-speed"),
|
||||
"frame-drop-count" to mpv.getProperty("frame-drop-count"),
|
||||
"decoder-frame-drop-count" to mpv.getProperty("decoder-frame-drop-count"),
|
||||
"demuxer-cache-duration" to mpv.getProperty("demuxer-cache-duration")
|
||||
)
|
||||
|
||||
// Only query properties that require an active video track
|
||||
if (hasVideo) {
|
||||
stats["display-fps"] = mpv.getProperty("display-fps")
|
||||
// Color/Format properties
|
||||
stats["video-params/pixelformat"] = mpv.getProperty("video-params/pixelformat")
|
||||
stats["video-params/hw-pixelformat"] = mpv.getProperty("video-params/hw-pixelformat")
|
||||
stats["video-params/colormatrix"] = mpv.getProperty("video-params/colormatrix")
|
||||
stats["video-params/primaries"] = mpv.getProperty("video-params/primaries")
|
||||
stats["video-params/gamma"] = mpv.getProperty("video-params/gamma")
|
||||
// HDR metadata
|
||||
stats["video-params/max-luma"] = mpv.getProperty("video-params/max-luma")
|
||||
stats["video-params/min-luma"] = mpv.getProperty("video-params/min-luma")
|
||||
stats["video-params/max-cll"] = mpv.getProperty("video-params/max-cll")
|
||||
stats["video-params/max-fall"] = mpv.getProperty("video-params/max-fall")
|
||||
// Other
|
||||
stats["video-params/aspect-name"] = mpv.getProperty("video-params/aspect-name")
|
||||
stats["video-params/rotate"] = mpv.getProperty("video-params/rotate")
|
||||
}
|
||||
|
||||
return stats
|
||||
}
|
||||
private fun getMpvStats(): Map<String, Any?> = mpvCore?.getStats() ?: mapOf("playerType" to "mpv")
|
||||
|
||||
// PiP Mode handling
|
||||
|
||||
@@ -753,68 +789,42 @@ class ExoPlayerPlugin :
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = observedProperties[name]?.id ?: return
|
||||
mainHandler.post { eventSink?.success(listOf(propId, value)) }
|
||||
}
|
||||
|
||||
private fun eventPayload(name: String, data: Map<String, Any>? = null): Map<String, Any> {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
return event
|
||||
channels.emitProperty(propId, value)
|
||||
}
|
||||
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
val pendingFallbackSwitch =
|
||||
name == "file-loaded" && pendingMpvFallbackSwitchGeneration == sessionGeneration && usingMpvFallback
|
||||
if (pendingFallbackSwitch) {
|
||||
clearPendingMpvFallbackSwitch()
|
||||
}
|
||||
|
||||
val event = eventPayload(name, data)
|
||||
mainHandler.post {
|
||||
eventSink?.success(event)
|
||||
if (pendingFallbackSwitch) {
|
||||
eventSink?.success(eventPayload("backend-switched"))
|
||||
}
|
||||
}
|
||||
channels.emitEvent(name, data)
|
||||
}
|
||||
|
||||
private fun armPendingMpvFallbackSwitch(generation: Int) {
|
||||
pendingMpvFallbackSwitchGeneration = generation
|
||||
mainHandler.postDelayed({
|
||||
if (pendingMpvFallbackSwitchGeneration == generation && sessionGeneration == generation && usingMpvFallback) {
|
||||
Log.w(TAG, "Timed out waiting for MPV fallback file-loaded before backend-switched")
|
||||
clearPendingMpvFallbackSwitch()
|
||||
onEvent("backend-switched", null)
|
||||
}
|
||||
}, MPV_FALLBACK_SWITCH_TIMEOUT_MS)
|
||||
private fun notifyBackendSwitched() {
|
||||
channels.emitEvent("backend-switched")
|
||||
}
|
||||
|
||||
private fun clearPendingMpvFallbackSwitch() {
|
||||
pendingMpvFallbackSwitchGeneration = null
|
||||
private fun appendExternalSubtitleOptions(
|
||||
options: MutableList<String>,
|
||||
externalSubtitles: List<Map<String, Any?>>?
|
||||
) {
|
||||
val escapedUris = externalSubtitles.orEmpty()
|
||||
.mapNotNull { it["uri"] as? String }
|
||||
.filter { it.isNotEmpty() }
|
||||
.map(::escapeMpvPathListEntry)
|
||||
.toList()
|
||||
|
||||
if (escapedUris.isEmpty()) return
|
||||
|
||||
val pathList = escapedUris.joinToString(":")
|
||||
options.add("sub-files=%${pathList.toByteArray(Charsets.UTF_8).size}%$pathList")
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a content:// URI via ContentResolver and returns the raw FD number,
|
||||
* or null if the URI is not a content:// scheme or opening fails.
|
||||
* The returned FD is detached so MPV can own and close it via fdclose://.
|
||||
*/
|
||||
private fun openContentFd(
|
||||
uriString: String,
|
||||
resolver: ContentResolver? = activity?.contentResolver
|
||||
): Int? {
|
||||
if (!uriString.startsWith("content://")) return null
|
||||
return try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val pfd = resolver?.openFileDescriptor(uri, "r") ?: return null
|
||||
val fd = pfd.detachFd()
|
||||
Log.d(TAG, "Opened content FD $fd for $uriString")
|
||||
fd
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
|
||||
null
|
||||
private fun escapeMpvPathListEntry(value: String): String = value.replace("\\", "\\\\").replace(":", "\\:")
|
||||
|
||||
private fun appendHttpHeaderOptions(options: MutableList<String>, headers: Map<String, String>?) {
|
||||
if (headers.isNullOrEmpty()) return
|
||||
|
||||
options.add("http-header-fields-clr=")
|
||||
headers.forEach { (key, value) ->
|
||||
val header = "$key: $value"
|
||||
options.add("http-header-fields-append=%${header.toByteArray(Charsets.UTF_8).size}%$header")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -829,84 +839,80 @@ class ExoPlayerPlugin :
|
||||
act: Activity,
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
positionMs: Long
|
||||
positionMs: Long,
|
||||
externalSubtitles: List<Map<String, Any?>>?,
|
||||
playWhenReady: Boolean,
|
||||
generation: Int
|
||||
) {
|
||||
// Snapshot Dart-registered state on main thread before clearing
|
||||
// Snapshot Dart-registered state on main thread before clearing.
|
||||
val pendingProps = pendingMpvProperties.toList()
|
||||
pendingMpvProperties.clear()
|
||||
val observedProps = observedProperties.toList()
|
||||
|
||||
// Compute content FD on main thread (needs contentResolver)
|
||||
val mpvUri = openContentFd(uri, act.contentResolver)
|
||||
?.let { "fdclose://$it" } ?: uri
|
||||
|
||||
// Buffer size for closure
|
||||
val bufferSize = configuredBufferSizeBytes
|
||||
|
||||
if (mpvCore !== core) {
|
||||
core.dispose()
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return
|
||||
}
|
||||
// Configure basic MPV properties for Plex playback
|
||||
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
|
||||
core.setProperty("vo", "gpu")
|
||||
core.setProperty("ao", "audiotrack")
|
||||
|
||||
// Forward user's buffer config to MPV fallback
|
||||
if (bufferSize != null && bufferSize > 0) {
|
||||
core.setProperty("demuxer-max-bytes", bufferSize.toString())
|
||||
}
|
||||
|
||||
// Apply pending MPV properties from Dart
|
||||
for ((propName, propValue) in pendingProps) {
|
||||
core.setProperty(propName, propValue)
|
||||
}
|
||||
|
||||
// Re-observe exactly what Dart registered via observeProperty, so the
|
||||
// event stream keeps flowing for every property the Dart side consumes.
|
||||
for ((propName, observed) in observedProps) {
|
||||
core.observeProperty(propName, observed.format)
|
||||
}
|
||||
|
||||
// Show the MPV surface (internally posts to UI)
|
||||
core.setVisible(true)
|
||||
|
||||
// Load media at the same position
|
||||
val startSeconds = positionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add("start=$startSeconds")
|
||||
headers?.forEach { (key, value) ->
|
||||
options.add("http-header-fields-append=$key: $value")
|
||||
}
|
||||
val optionsStr = options.joinToString(",")
|
||||
armPendingMpvFallbackSwitch(sessionGeneration)
|
||||
core.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
|
||||
|
||||
// On GPUs without compute shaders, MPV can't do dynamic peak detection
|
||||
// and spline tone-mapping produces dim/washed-out results with extreme
|
||||
// static HDR peak metadata. Use reinhard which handles this better.
|
||||
Thread {
|
||||
val peakDetection = core.getProperty("hdr-compute-peak")
|
||||
if (peakDetection == "no") {
|
||||
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
|
||||
core.setProperty("tone-mapping", "reinhard")
|
||||
core.setProperty("tone-mapping-param", "0.7")
|
||||
core.setProperty("tone-mapping-mode", "luma")
|
||||
MpvContentUriResolver.resolve(uri, act.contentResolver, mainHandler) { source ->
|
||||
if (generation != sessionGeneration || mpvCore !== core || activity !== act || !usingMpvFallback) {
|
||||
source.closeIfUnused()
|
||||
core.dispose()
|
||||
return@resolve
|
||||
}
|
||||
}.start()
|
||||
|
||||
// Request audio focus
|
||||
core.requestAudioFocus()
|
||||
// Configure basic MPV properties for Plex playback.
|
||||
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
|
||||
core.setProperty("vo", "gpu")
|
||||
core.setProperty("ao", "audiotrack")
|
||||
|
||||
Log.i(TAG, "Successfully switched to MPV fallback")
|
||||
if (bufferSize != null && bufferSize > 0) {
|
||||
core.setProperty("demuxer-max-bytes", bufferSize.toString())
|
||||
}
|
||||
|
||||
for ((propName, propValue) in pendingProps) {
|
||||
core.setProperty(propName, propValue)
|
||||
}
|
||||
|
||||
// Re-observe exactly what Dart registered via observeProperty, so the
|
||||
// event stream keeps flowing for every property the Dart side consumes.
|
||||
for ((propName, observed) in observedProps) {
|
||||
core.observeProperty(propName, observed.format)
|
||||
}
|
||||
|
||||
core.setVisible(true)
|
||||
|
||||
val startSeconds = positionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add(if (positionMs > 0L) "start=$startSeconds" else "start=none")
|
||||
if (!playWhenReady) options.add("pause=yes")
|
||||
options.add("sid=no")
|
||||
options.add("secondary-sid=no")
|
||||
appendExternalSubtitleOptions(options, externalSubtitles)
|
||||
appendHttpHeaderOptions(options, headers)
|
||||
val optionsStr = options.joinToString(",")
|
||||
notifyBackendSwitched()
|
||||
core.command(arrayOf("loadfile", source.value, "replace", "-1", optionsStr))
|
||||
|
||||
// On GPUs without compute shaders, MPV can't do dynamic peak detection
|
||||
// and spline tone-mapping produces dim/washed-out results with extreme
|
||||
// static HDR peak metadata. Use reinhard which handles this better.
|
||||
Thread {
|
||||
val peakDetection = core.getProperty("hdr-compute-peak")
|
||||
if (peakDetection == "no") {
|
||||
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
|
||||
core.setProperty("tone-mapping", "reinhard")
|
||||
core.setProperty("tone-mapping-param", "0.7")
|
||||
core.setProperty("tone-mapping-mode", "luma")
|
||||
}
|
||||
}.start()
|
||||
|
||||
core.requestAudioFocus()
|
||||
Log.i(TAG, "Successfully switched to MPV fallback")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFormatUnsupported(
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
positionMs: Long,
|
||||
playWhenReady: Boolean,
|
||||
errorMessage: String
|
||||
): Boolean {
|
||||
if (usingMpvFallback || fallbackInProgress) {
|
||||
@@ -915,6 +921,7 @@ class ExoPlayerPlugin :
|
||||
}
|
||||
|
||||
val currentActivity = activity ?: return false
|
||||
val fallbackExternalSubtitles = currentExternalSubtitles?.map { it.toMap() }
|
||||
fallbackInProgress = true
|
||||
|
||||
Log.i(TAG, "ExoPlayer error, switching to MPV fallback at ${positionMs}ms: $errorMessage")
|
||||
@@ -937,20 +944,17 @@ class ExoPlayerPlugin :
|
||||
mpvCore?.dispose()
|
||||
mpvCore = null
|
||||
usingMpvFallback = false // Clear before handoff
|
||||
clearPendingMpvFallbackSwitch()
|
||||
|
||||
val generation = sessionGeneration
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
mainHandler.post {
|
||||
if (generation != sessionGeneration) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return@post
|
||||
}
|
||||
val act = activity
|
||||
if (act == null) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return@post
|
||||
}
|
||||
|
||||
@@ -967,7 +971,6 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
}
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return@initialize
|
||||
}
|
||||
if (!success) {
|
||||
@@ -976,7 +979,6 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
}
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
Log.e(TAG, "Failed to initialize MPV fallback")
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: $errorMessage"))
|
||||
return@initialize
|
||||
@@ -985,18 +987,16 @@ class ExoPlayerPlugin :
|
||||
usingMpvFallback = true
|
||||
fallbackInProgress = false
|
||||
|
||||
setupMpvFallback(core, act, uri, headers, positionMs)
|
||||
setupMpvFallback(core, act, uri, headers, positionMs, fallbackExternalSubtitles, playWhenReady, generation)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
Log.e(TAG, "Failed to switch to MPV fallback", e)
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
Log.e(TAG, "Failed to switch to MPV fallback", e)
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
|
||||
/** MKV CodecID for Microsoft ACM compatibility mode. */
|
||||
private const val CODEC_ID_ACM = "A_MS/ACM"
|
||||
|
||||
/**
|
||||
* MatroskaExtractor.init is final and extractorOutput private; subclasses swap
|
||||
* in wrapping outputs via reflection once the Segment element starts (shared
|
||||
* with ZlibMatroskaExtractor).
|
||||
*/
|
||||
internal val matroskaExtractorOutputField by lazy {
|
||||
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
|
||||
/** WAVEFORMATEX format tag for LOAS/LATM-wrapped AAC (WAVE_FORMAT_MPEG_LOAS). */
|
||||
private const val WAVE_FORMAT_MPEG_LOAS = 0x1602
|
||||
|
||||
/**
|
||||
* Returns whether a track is LOAS/LATM AAC muxed as A_MS/ACM — ffmpeg's (and
|
||||
* therefore Plex's) fallback mapping for aac_latm, which Matroska has no native
|
||||
* codec ID for. The WAVEFORMATEX wFormatTag is the first 2 bytes (LE) of
|
||||
* CodecPrivate.
|
||||
*/
|
||||
fun isLoasAcmTrack(codecId: String?, codecPrivate: ByteArray?): Boolean = codecId == CODEC_ID_ACM &&
|
||||
codecPrivate != null &&
|
||||
codecPrivate.size >= 2 &&
|
||||
((codecPrivate[0].toInt() and 0xFF) or ((codecPrivate[1].toInt() and 0xFF) shl 8)) == WAVE_FORMAT_MPEG_LOAS
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps marked tracks with [LatmTrackOutput].
|
||||
* Call [markNextTrackLatm] before the parent extractor creates the track
|
||||
* (i.e. before super.endMasterElement(ID_TRACK_ENTRY)).
|
||||
*/
|
||||
class LatmExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
private var nextTrackIsLatm = false
|
||||
private val latmOutputs = mutableListOf<LatmTrackOutput>()
|
||||
|
||||
fun markNextTrackLatm() {
|
||||
nextTrackIsLatm = true
|
||||
}
|
||||
|
||||
/** Resets LATM parser state after an extractor seek. */
|
||||
fun resetTracks() {
|
||||
latmOutputs.forEach { it.reset() }
|
||||
}
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (!nextTrackIsLatm) return original
|
||||
nextTrackIsLatm = false
|
||||
return LatmTrackOutput(original, id).also { latmOutputs.add(it) }
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
|
||||
/**
|
||||
* MatroskaExtractor with LOAS/LATM AAC support, used for Plex Live TV MKV
|
||||
* streams (which bypass the ASS/DV extractor chain). VOD playback gets the
|
||||
* same LATM handling via ZlibMatroskaExtractor.
|
||||
*/
|
||||
class LatmMatroskaExtractor(flags: Int) : MatroskaExtractor(flags) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "LatmMkvExtractor"
|
||||
private const val ID_SEGMENT = 0x18538067
|
||||
private const val ID_TRACK_ENTRY = 0xAE
|
||||
}
|
||||
|
||||
private var latmWrapper: LatmExtractorOutputWrapper? = null
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
|
||||
// init() is final, so install the wrapping output when the Segment starts —
|
||||
// before any TrackEntry can create a track through it.
|
||||
if (id == ID_SEGMENT && latmWrapper == null) {
|
||||
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
|
||||
val wrapper = LatmExtractorOutputWrapper(currentOutput)
|
||||
latmWrapper = wrapper
|
||||
matroskaExtractorOutputField.set(this, wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
if (id == ID_TRACK_ENTRY) {
|
||||
val track = getCurrentTrack(id)
|
||||
if (isLoasAcmTrack(track.codecId, track.codecPrivate)) {
|
||||
Log.i(TAG, "Track ${track.number} is LOAS/LATM AAC, unwrapping to raw AAC")
|
||||
latmWrapper?.markNextTrackLatm()
|
||||
}
|
||||
}
|
||||
super.endMasterElement(id)
|
||||
}
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
latmWrapper?.resetTracks()
|
||||
super.seek(position, timeUs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.ts.LatmReader
|
||||
import androidx.media3.extractor.ts.TsPayloadReader
|
||||
import java.io.EOFException
|
||||
|
||||
/**
|
||||
* TrackOutput wrapper that unwraps LOAS/LATM-framed AAC (MKV A_MS/ACM with
|
||||
* WAVEFORMATEX tag 0x1602) into raw AAC access units MediaCodec can decode.
|
||||
*
|
||||
* Each MKV block payload is one or more complete LOAS AudioSyncStream frames.
|
||||
* Blocks are buffered between sampleData() and sampleMetadata(), then fed to
|
||||
* media3's LatmReader, which parses the StreamMuxConfig (emitting a proper AAC
|
||||
* Format with AudioSpecificConfig) and outputs byte-aligned raw AAC samples.
|
||||
*
|
||||
* The parent extractor's audio/x-unknown Format is swallowed; its track-selection
|
||||
* metadata (id, label, language, selection flags) is merged onto the Format
|
||||
* LatmReader derives from the stream.
|
||||
*/
|
||||
class LatmTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val trackId: Int
|
||||
) : TrackOutput {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "LatmTrackOutput"
|
||||
private const val INITIAL_BUFFER_SIZE = 4 * 1024
|
||||
private const val MAX_LOGGED_ERRORS = 3
|
||||
}
|
||||
|
||||
private var latmReader: LatmReader? = null
|
||||
private var originalFormat: Format? = null
|
||||
private val parsable = ParsableByteArray()
|
||||
|
||||
// Reusable block buffer — grown as needed, never shrunk
|
||||
private var buf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var bufLen = 0
|
||||
private var readBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var errorCount = 0
|
||||
|
||||
/** Forwards LatmReader's decoded Format merged with the original track metadata. */
|
||||
private val mergeProxy = object : TrackOutput {
|
||||
override fun format(format: Format) {
|
||||
val original = originalFormat
|
||||
val merged = if (original == null) {
|
||||
format
|
||||
} else {
|
||||
format.buildUpon()
|
||||
.setId(original.id)
|
||||
.setLabel(original.label)
|
||||
.setLanguage(original.language ?: format.language)
|
||||
.setSelectionFlags(original.selectionFlags)
|
||||
.build()
|
||||
}
|
||||
delegate.format(merged)
|
||||
}
|
||||
|
||||
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int = delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) = delegate.sampleData(data, length, sampleDataPart)
|
||||
|
||||
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) = delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
}
|
||||
|
||||
private val readerExtractorOutput = object : ExtractorOutput {
|
||||
override fun track(id: Int, type: Int): TrackOutput = mergeProxy
|
||||
override fun endTracks() {}
|
||||
override fun seekMap(seekMap: SeekMap) {}
|
||||
}
|
||||
|
||||
override fun format(format: Format) {
|
||||
originalFormat = format
|
||||
if (latmReader == null) {
|
||||
latmReader = LatmReader(format.language, format.roleFlags, MimeTypes.VIDEO_MATROSKA).also {
|
||||
it.createTracks(readerExtractorOutput, TsPayloadReader.TrackIdGenerator(trackId, 1))
|
||||
}
|
||||
}
|
||||
// Swallow the parent's audio/x-unknown Format; LatmReader emits the real
|
||||
// AAC Format (with AudioSpecificConfig) from the first StreamMuxConfig.
|
||||
}
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (readBuf.size < length) readBuf = ByteArray(length)
|
||||
val bytesRead = input.read(readBuf, 0, length)
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT && !allowEndOfInput) throw EOFException()
|
||||
if (bytesRead > 0) append(readBuf, bytesRead)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
ensureCapacity(bufLen + length)
|
||||
data.readBytes(buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
// offset counts down to 0 across a laced BlockGroup; the buffer holds the
|
||||
// whole block's data, so slice this sample out and clear at the last one.
|
||||
val start = bufLen - offset - size
|
||||
val reader = latmReader
|
||||
if (reader == null || start < 0) {
|
||||
if (errorCount++ < MAX_LOGGED_ERRORS) {
|
||||
Log.e(TAG, "Dropping sample (reader=${reader != null}, start=$start, size=$size, offset=$offset)")
|
||||
}
|
||||
if (offset == 0) bufLen = 0
|
||||
return
|
||||
}
|
||||
try {
|
||||
reader.packetStarted(timeUs, 0)
|
||||
parsable.reset(buf, start + size)
|
||||
parsable.position = start
|
||||
reader.consume(parsable)
|
||||
} catch (e: Exception) {
|
||||
if (errorCount++ < MAX_LOGGED_ERRORS) {
|
||||
Log.e(TAG, "LATM parse failed (${size}B), dropping sample", e)
|
||||
}
|
||||
reader.seek() // resync on the next LOAS syncword
|
||||
}
|
||||
if (offset == 0) bufLen = 0
|
||||
}
|
||||
|
||||
/** Drops buffered MKV data while retaining the LATM StreamMuxConfig. */
|
||||
fun reset() {
|
||||
bufLen = 0
|
||||
}
|
||||
|
||||
private fun append(src: ByteArray, length: Int) {
|
||||
ensureCapacity(bufLen + length)
|
||||
System.arraycopy(src, 0, buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
private fun ensureCapacity(needed: Int) {
|
||||
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.PlaybackParameters
|
||||
import androidx.media3.common.audio.ChannelMixingAudioProcessor
|
||||
import androidx.media3.common.audio.ChannelMixingMatrix
|
||||
import androidx.media3.common.util.Clock
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.decoder.DecoderInputBuffer
|
||||
@@ -25,6 +27,7 @@ import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter
|
||||
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
|
||||
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
|
||||
import androidx.media3.exoplayer.video.VideoRendererEventListener
|
||||
import com.edde746.plezy.TvDetection
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.math.abs
|
||||
@@ -32,9 +35,26 @@ import kotlin.math.abs
|
||||
@OptIn(UnstableApi::class)
|
||||
class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context) {
|
||||
|
||||
/**
|
||||
* Android TV: MediaCodec.setOutputSurface is broken on many TV SoCs (Sony Bravia
|
||||
* MediaTek etc., ExoPlayer #5119/#8329) — force full codec re-init on surface
|
||||
* changes instead (#1481). TV-only: phones keep the fast path for PiP churn.
|
||||
*/
|
||||
private val forceSetOutputSurfaceWorkaround: Boolean = TvDetection.isTv(context)
|
||||
|
||||
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
|
||||
val audioDelayUs = AtomicLong(0L)
|
||||
|
||||
/**
|
||||
* Stereo-downmix processor; inactive while every registered matrix is identity.
|
||||
* Pre-populated for counts 1..12 so sink configure can never hit
|
||||
* "No mixing matrix for input channel count". ExoPlayerCore swaps in
|
||||
* downmix matrices via [DownmixMatrices] when the setting is enabled.
|
||||
*/
|
||||
val channelMixProcessor = ChannelMixingAudioProcessor().apply {
|
||||
for (count in 1..12) putChannelMixingMatrix(ChannelMixingMatrix.create(count, count))
|
||||
}
|
||||
|
||||
/** Returns whether direct encoded output should be hidden so decoded PCM output can be selected. */
|
||||
var shouldBlockDirectAudioOutput: ((Format) -> Boolean)? = null
|
||||
|
||||
@@ -79,6 +99,7 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
.setEventHandler(eventHandler)
|
||||
.setEventListener(eventListener)
|
||||
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
|
||||
forceSetOutputSurfaceWorkaround,
|
||||
videoDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
@@ -107,6 +128,9 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
val defaultSink = DefaultAudioSink.Builder(context)
|
||||
.setEnableFloatOutput(enableFloatOutput)
|
||||
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
|
||||
// Wraps in DefaultAudioProcessorChain, keeping stock silence-skip +
|
||||
// Sonic; the downmix runs first and only in the decoded-PCM path.
|
||||
.setAudioProcessors(arrayOf(channelMixProcessor))
|
||||
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs, audioDiagnosticsLogger))
|
||||
.build()
|
||||
|
||||
@@ -341,6 +365,7 @@ internal class SubtitleDelayRenderer(
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class DvSanitizingVideoRenderer(
|
||||
builder: Builder,
|
||||
private val forceSetOutputSurfaceWorkaround: Boolean,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : MediaCodecVideoRenderer(builder) {
|
||||
|
||||
@@ -348,6 +373,26 @@ internal class DvSanitizingVideoRenderer(
|
||||
|
||||
private var stripHdr10PlusSei = false
|
||||
private var stripDvRpu = false
|
||||
private var loggedSurfaceWorkaround = false
|
||||
|
||||
// On TV SoCs MediaCodec.setOutputSurface() silently yields a black picture after
|
||||
// the screensaver/background destroys and recreates the surface (#1481). Returning
|
||||
// true makes media3 release + re-init the codec instead. media3's built-in device
|
||||
// list doesn't cover 2019+ Bravias; consulted once per codec init.
|
||||
override fun codecNeedsSetOutputSurfaceWorkaround(name: String): Boolean {
|
||||
if (forceSetOutputSurfaceWorkaround) {
|
||||
if (!loggedSurfaceWorkaround) {
|
||||
loggedSurfaceWorkaround = true
|
||||
log?.invoke(
|
||||
"info",
|
||||
"video",
|
||||
"TV setOutputSurface workaround active: codec will fully re-init on surface changes (codec=$name)"
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return super.codecNeedsSetOutputSurfaceWorkaround(name)
|
||||
}
|
||||
|
||||
// Sanitize diagnostics — playback-thread only, cumulative for the renderer's lifetime.
|
||||
private var sanitizedSampleCount = 0L
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
|
||||
/**
|
||||
* Decision logic for the post-resume video stall watchdog (#1454).
|
||||
*
|
||||
* Some TV SoCs (the Amlogic Mi Box class) stall the MediaCodec output path after a
|
||||
* pause -> resume: the playback clock and audio keep advancing but no new video
|
||||
* frame reaches the screen until the codec is flushed by a seek. The watchdog
|
||||
* snapshots the rendered-frame counter when playback resumes and evaluates it one
|
||||
* check window later; a confirmed stall is recovered with a small backward seek
|
||||
* (ExoPlayer short-circuits a same-position seek without resetting renderers, so
|
||||
* the recovery must move by a nonzero delta to force the codec flush).
|
||||
*/
|
||||
internal object ResumeStallPolicy {
|
||||
/** Floor for the check window; frame-interval scaling only ever raises it. */
|
||||
const val DEFAULT_CHECK_WINDOW_MS = 1000L
|
||||
|
||||
/** Frames that must have been due within the window before calling it a stall. */
|
||||
const val MIN_FRAME_INTERVALS = 4
|
||||
|
||||
/** Assumed fps when neither the format nor timestamp detection knows it. */
|
||||
const val FALLBACK_FPS = 24f
|
||||
|
||||
/** Recovery seek delta. Must stay under the 350ms watch-together drift deadband. */
|
||||
const val SEEK_BACK_MS = 250L
|
||||
|
||||
/** Re-checks allowed while the clock itself is not advancing (generic stall, not this bug). */
|
||||
const val MAX_RECHECKS = 2
|
||||
|
||||
/** Recovery cap per media session; a pathological stream stops arming after this. */
|
||||
const val MAX_RECOVERIES_PER_SESSION = 5
|
||||
|
||||
enum class Verdict { HEALTHY, RECHECK, SKIP_NEAR_EOF, STALLED }
|
||||
|
||||
/** Window sized so even low-fps or slowed-down content has had several frames due. */
|
||||
fun checkWindowMs(formatFps: Float?, detectedFps: Float?, speed: Float): Long {
|
||||
val fps = formatFps?.takeIf { it > 1f } ?: detectedFps?.takeIf { it > 1f } ?: FALLBACK_FPS
|
||||
val frameIntervalMs = (1000f / fps / speed.coerceAtLeast(0.25f)).toLong()
|
||||
return maxOf(DEFAULT_CHECK_WINDOW_MS, MIN_FRAME_INTERVALS * frameIntervalMs)
|
||||
}
|
||||
|
||||
fun evaluate(
|
||||
baselineFrames: Int,
|
||||
currentFrames: Int,
|
||||
baselinePositionMs: Long,
|
||||
currentPositionMs: Long,
|
||||
durationMs: Long,
|
||||
windowMs: Long
|
||||
): Verdict = when {
|
||||
// Any counter movement counts as healthy, including a renderer re-enable
|
||||
// resetting DecoderCounters below the baseline.
|
||||
currentFrames != baselineFrames -> Verdict.HEALTHY
|
||||
currentPositionMs - baselinePositionMs < windowMs / 2 -> Verdict.RECHECK
|
||||
durationMs != C.TIME_UNSET && durationMs - currentPositionMs < 2 * windowMs -> Verdict.SKIP_NEAR_EOF
|
||||
else -> Verdict.STALLED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.text.Cue
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
internal object SubtitleCueLayout {
|
||||
|
||||
fun layout(cues: List<Cue>, positionPercent: Int, fontSize: Float): List<Cue> = applyPosition(stackUnpositioned(cues), positionPercent, fontSize)
|
||||
|
||||
// SRT carries no per-cue positioning, so SubripParser emits cues with
|
||||
// lineType = TYPE_UNSET. SubtitlePainter then renders every such cue at the
|
||||
// same default bottom-anchored position, causing visible overlap when more
|
||||
// than one is active. Reassign line numbers from the bottom up so concurrent
|
||||
// unpositioned cues stack instead. Workaround for
|
||||
// https://github.com/androidx/media/issues/2237; can be removed once
|
||||
// https://github.com/androidx/media/pull/3151 lands and we upgrade Media3.
|
||||
private fun stackUnpositioned(cues: List<Cue>): List<Cue> {
|
||||
if (cues.size < 2) return cues
|
||||
val toStack = cues.indices.filter {
|
||||
cues[it].lineType == Cue.TYPE_UNSET && cues[it].text != null
|
||||
}
|
||||
if (toStack.size < 2) return cues
|
||||
val rebuilt = cues.toMutableList()
|
||||
var nextRow = -1
|
||||
// Reverse so the last cue in the group lands on row -1 (bottom).
|
||||
for (idx in toStack.reversed()) {
|
||||
val cue = cues[idx]
|
||||
rebuilt[idx] = cue.buildUpon()
|
||||
.setLine(nextRow.toFloat(), Cue.LINE_TYPE_NUMBER)
|
||||
.setLineAnchor(Cue.ANCHOR_TYPE_END)
|
||||
.build()
|
||||
val rowsConsumed = (cue.text?.toString()?.count { it == '\n' } ?: 0) + 1
|
||||
nextRow -= rowsConsumed
|
||||
}
|
||||
return rebuilt
|
||||
}
|
||||
|
||||
private fun applyPosition(cues: List<Cue>, positionPercent: Int, fontSize: Float): List<Cue> {
|
||||
val clampedPosition = positionPercent.coerceIn(0, 100)
|
||||
if (clampedPosition == 100 || cues.isEmpty()) return cues
|
||||
|
||||
val baseLine = clampedPosition / 100f
|
||||
val rowHeight = (fontSize / 720f * 1.2f).coerceAtLeast(0.01f)
|
||||
var changed = false
|
||||
|
||||
val rebuilt = cues.map { cue ->
|
||||
if (!usesDefaultVerticalPlacement(cue)) return@map cue
|
||||
|
||||
val rowOffset = if (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f) {
|
||||
(-cue.line - 1f).coerceAtLeast(0f)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
val line = if (clampedPosition == 0) {
|
||||
(rowOffset * rowHeight).coerceAtMost(1f)
|
||||
} else {
|
||||
(baseLine - rowOffset * rowHeight).coerceIn(0f, 1f)
|
||||
}
|
||||
val lineAnchor = if (clampedPosition == 0) Cue.ANCHOR_TYPE_START else Cue.ANCHOR_TYPE_END
|
||||
|
||||
changed = true
|
||||
cue.buildUpon()
|
||||
.setLine(line, Cue.LINE_TYPE_FRACTION)
|
||||
.setLineAnchor(lineAnchor)
|
||||
.build()
|
||||
}
|
||||
|
||||
return if (changed) rebuilt else cues
|
||||
}
|
||||
|
||||
private fun usesDefaultVerticalPlacement(cue: Cue): Boolean {
|
||||
if (cue.text == null || cue.bitmap != null || cue.verticalType != Cue.TYPE_UNSET) return false
|
||||
return cue.line == Cue.DIMEN_UNSET || (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.ui.AspectRatioFrameLayout
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal data class SubtitleViewDimensions(val width: Int, val height: Int)
|
||||
|
||||
internal object SubtitleViewLayout {
|
||||
fun textDimensions(
|
||||
containerWidth: Int,
|
||||
containerHeight: Int,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
pixelRatio: Float,
|
||||
resizeMode: Int,
|
||||
zoomScale: Float
|
||||
): SubtitleViewDimensions? {
|
||||
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
|
||||
if (containerWidth <= 0 || containerHeight <= 0) return null
|
||||
|
||||
if (resizeMode != AspectRatioFrameLayout.RESIZE_MODE_FIT) {
|
||||
return SubtitleViewDimensions(containerWidth, containerHeight)
|
||||
}
|
||||
|
||||
val base = fit(containerWidth, containerHeight, videoAspect)
|
||||
return when {
|
||||
zoomScale < 0.999f -> scale(base, zoomScale)
|
||||
zoomScale > 1.001f -> SubtitleViewDimensions(containerWidth, containerHeight)
|
||||
else -> base
|
||||
}
|
||||
}
|
||||
|
||||
fun bitmapDimensions(
|
||||
containerWidth: Int,
|
||||
containerHeight: Int,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
pixelRatio: Float,
|
||||
resizeMode: Int,
|
||||
zoomScale: Float
|
||||
): SubtitleViewDimensions? {
|
||||
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
|
||||
if (containerWidth <= 0 || containerHeight <= 0) return null
|
||||
|
||||
// PGS/VOB cues are authored in video coordinates, but users expect them to
|
||||
// remain readable and fully visible when the video is cropped or zoomed.
|
||||
// Fit to the visible container instead of following the cropped video rect.
|
||||
return fit(containerWidth, containerHeight, videoAspect)
|
||||
}
|
||||
|
||||
private fun videoAspect(videoWidth: Int, videoHeight: Int, pixelRatio: Float): Float? {
|
||||
if (videoWidth <= 0 || videoHeight <= 0 || pixelRatio <= 0f) return null
|
||||
val aspect = (videoWidth * pixelRatio) / videoHeight
|
||||
return if (aspect.isFinite() && aspect > 0f) aspect else null
|
||||
}
|
||||
|
||||
// Largest [videoAspect] rectangle that fits inside the container, as (width, height)
|
||||
// in float pixels. Shared by the SubtitleView sizing (rounded to ints in [fit]) and
|
||||
// the libass FIT-mode margins in updateAssMargins() (kept as floats for the zoom
|
||||
// multiply) so both agree on the video dst rect.
|
||||
fun letterbox(containerWidth: Int, containerHeight: Int, videoAspect: Float): Pair<Float, Float> {
|
||||
val containerAspect = containerWidth.toFloat() / containerHeight
|
||||
return if (videoAspect > containerAspect) {
|
||||
containerWidth.toFloat() to containerWidth / videoAspect
|
||||
} else {
|
||||
containerHeight * videoAspect to containerHeight.toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
private fun fit(containerWidth: Int, containerHeight: Int, videoAspect: Float): SubtitleViewDimensions {
|
||||
val (width, height) = letterbox(containerWidth, containerHeight, videoAspect)
|
||||
return SubtitleViewDimensions(
|
||||
width.roundToInt().coerceAtLeast(1),
|
||||
height.roundToInt().coerceAtLeast(1)
|
||||
)
|
||||
}
|
||||
|
||||
private fun scale(dimensions: SubtitleViewDimensions, scale: Float): SubtitleViewDimensions {
|
||||
val safeScale = scale.coerceAtLeast(0.001f)
|
||||
return SubtitleViewDimensions(
|
||||
(dimensions.width * safeScale).roundToInt().coerceAtLeast(1),
|
||||
(dimensions.height * safeScale).roundToInt().coerceAtLeast(1)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.view.SurfaceControl
|
||||
import androidx.annotation.Keep
|
||||
|
||||
/**
|
||||
* EXPERIMENTAL SPIKE: the API-34 transaction callback path is the only in-app signal we have
|
||||
* for comparing the codec video plane and the libass overlay plane with the same clock.
|
||||
*/
|
||||
// R8 cannot see the JNI-by-name callback edge, and class-level @Keep is not enough for members.
|
||||
@Keep
|
||||
object SurfaceTxProbe {
|
||||
init {
|
||||
System.loadLibrary("asskt")
|
||||
}
|
||||
|
||||
const val SOURCE_VIDEO = 0
|
||||
const val SOURCE_OVERLAY = 1
|
||||
|
||||
// CLOCK_MONOTONIC keeps native callback times comparable with ExoPlayer release targets.
|
||||
@Volatile
|
||||
@JvmStatic
|
||||
var sink: ((Long, Long, Long, Int, Int, Int, Long) -> Unit)? = null
|
||||
|
||||
// The same transaction must be applied to the frame so the callback follows that buffer.
|
||||
@JvmStatic
|
||||
external fun nativeAttach(transaction: SurfaceControl.Transaction, tag: Long, source: Int)
|
||||
|
||||
// JNI calls this by name after shrink.
|
||||
@Keep
|
||||
@JvmStatic
|
||||
fun onResult(
|
||||
tag: Long,
|
||||
latchNs: Long,
|
||||
releaseNs: Long,
|
||||
surfaceCount: Int,
|
||||
fenceState: Int,
|
||||
source: Int,
|
||||
callbackNs: Long
|
||||
) {
|
||||
val s = sink ?: return
|
||||
s.invoke(tag, latchNs, releaseNs, surfaceCount, fenceState, source, callbackNs)
|
||||
}
|
||||
}
|
||||
+21
-88
@@ -1,9 +1,6 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.util.zip.DataFormatException
|
||||
import java.util.zip.Inflater
|
||||
@@ -16,8 +13,8 @@ import java.util.zip.Inflater
|
||||
* All buffers are reused across samples to minimize GC pressure on the hot path.
|
||||
*/
|
||||
class ZlibInflatingTrackOutput(
|
||||
private val delegate: TrackOutput
|
||||
) : TrackOutput {
|
||||
delegate: TrackOutput
|
||||
) : BufferedTransformingTrackOutput(delegate, INITIAL_BUFFER_SIZE, INFLATE_CHUNK) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ZlibTrackOutput"
|
||||
@@ -28,94 +25,30 @@ class ZlibInflatingTrackOutput(
|
||||
var active = false
|
||||
|
||||
private val inflater = Inflater()
|
||||
|
||||
// Reusable buffers — grown as needed, never shrunk
|
||||
private var compressedBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var compressedLen = 0
|
||||
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var readBuf = ByteArray(INFLATE_CHUNK)
|
||||
private val outputParsable = ParsableByteArray()
|
||||
private var buffering = false
|
||||
|
||||
override fun format(format: Format) = delegate.format(format)
|
||||
override val transformEnabled: Boolean
|
||||
get() = active
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (!active) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
override val transformedBuffer: ByteArray
|
||||
get() = inflateBuf
|
||||
|
||||
buffering = true
|
||||
if (readBuf.size < length) readBuf = ByteArray(length)
|
||||
val bytesRead = input.read(readBuf, 0, length)
|
||||
if (bytesRead > 0) appendCompressed(readBuf, 0, bytesRead)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (!active) {
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = true
|
||||
ensureCompressedCapacity(compressedLen + length)
|
||||
data.readBytes(compressedBuf, compressedLen, length)
|
||||
compressedLen += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (!active || !buffering) {
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = false
|
||||
val srcLen = compressedLen
|
||||
compressedLen = 0
|
||||
|
||||
val inflatedLen = try {
|
||||
inflater.reset()
|
||||
inflater.setInput(compressedBuf, 0, srcLen)
|
||||
var written = 0
|
||||
while (!inflater.finished()) {
|
||||
if (written == inflateBuf.size) growInflateBuf()
|
||||
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
|
||||
if (count == 0 && !inflater.finished()) break
|
||||
written += count
|
||||
}
|
||||
written
|
||||
} catch (e: DataFormatException) {
|
||||
Log.e(TAG, "Zlib inflate failed (${srcLen}B), passing raw", e)
|
||||
// Fall back to raw compressed data
|
||||
ensureInflateCapacity(srcLen)
|
||||
System.arraycopy(compressedBuf, 0, inflateBuf, 0, srcLen)
|
||||
srcLen
|
||||
}
|
||||
|
||||
outputParsable.reset(inflateBuf, inflatedLen)
|
||||
delegate.sampleData(outputParsable, inflatedLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
delegate.sampleMetadata(timeUs, flags, inflatedLen, 0, cryptoData)
|
||||
}
|
||||
|
||||
private fun appendCompressed(src: ByteArray, offset: Int, length: Int) {
|
||||
ensureCompressedCapacity(compressedLen + length)
|
||||
System.arraycopy(src, offset, compressedBuf, compressedLen, length)
|
||||
compressedLen += length
|
||||
}
|
||||
|
||||
private fun ensureCompressedCapacity(needed: Int) {
|
||||
if (compressedBuf.size < needed) {
|
||||
compressedBuf = compressedBuf.copyOf(maxOf(needed, compressedBuf.size * 2))
|
||||
override fun transformSample(inputLength: Int, flags: Int): Int = try {
|
||||
inflater.reset()
|
||||
inflater.setInput(inputBuffer, 0, inputLength)
|
||||
var written = 0
|
||||
while (!inflater.finished()) {
|
||||
if (written == inflateBuf.size) growInflateBuf()
|
||||
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
|
||||
if (count == 0 && !inflater.finished()) break
|
||||
written += count
|
||||
}
|
||||
written
|
||||
} catch (e: DataFormatException) {
|
||||
Log.e(TAG, "Zlib inflate failed (${inputLength}B), passing raw", e)
|
||||
ensureInflateCapacity(inputLength)
|
||||
System.arraycopy(inputBuffer, 0, inflateBuf, 0, inputLength)
|
||||
inputLength
|
||||
}
|
||||
|
||||
private fun ensureInflateCapacity(needed: Int) {
|
||||
|
||||
@@ -5,19 +5,24 @@ import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
|
||||
/**
|
||||
* Extends AssMatroskaExtractor to add support for MKV ContentCompAlgo 0 (zlib).
|
||||
* Extends AssMatroskaExtractor to add support for MKV quirks media3 rejects:
|
||||
*
|
||||
* Media3's MatroskaExtractor only supports ContentCompAlgo 3 (header stripping).
|
||||
* This subclass intercepts the compression algorithm during track header parsing:
|
||||
* ContentCompAlgo 0 (zlib) — media3 only supports ContentCompAlgo 3 (header
|
||||
* stripping). This subclass intercepts the compression algorithm during track
|
||||
* header parsing:
|
||||
* - Tells the parent it's header stripping (algo 3) to avoid the ParserException
|
||||
* - Wraps TrackOutputs with ZlibInflatingTrackOutput to decompress per-sample data
|
||||
* - Skips ContentCompSettings for zlib tracks (not applicable)
|
||||
*
|
||||
* LOAS/LATM AAC as A_MS/ACM — media3 sets audio/x-unknown for non-PCM ACM
|
||||
* tracks (silent playback). Detected tracks are wrapped with LatmTrackOutput,
|
||||
* which unwraps LOAS frames to raw AAC (see LatmMatroskaExtractor for the
|
||||
* Live TV counterpart).
|
||||
*/
|
||||
class ZlibMatroskaExtractor(
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
@@ -32,27 +37,25 @@ class ZlibMatroskaExtractor(
|
||||
private const val ID_TRACK_ENTRY = 0xAE
|
||||
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
|
||||
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
|
||||
|
||||
private val extractorOutputField by lazy {
|
||||
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var zlibOutput: ZlibExtractorOutputWrapper? = null
|
||||
private var latmOutput: LatmExtractorOutputWrapper? = null
|
||||
private var currentTrackUsesZlib = false
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
|
||||
// After super installs AssSubtitleExtractorOutput, wrap it with our zlib layer
|
||||
// After super installs AssSubtitleExtractorOutput, wrap it with our zlib +
|
||||
// LATM layers (zlib outermost so inflation runs before LATM parsing).
|
||||
if (id == ID_SEGMENT && zlibOutput == null) {
|
||||
val currentOutput = extractorOutputField.get(this) as ExtractorOutput
|
||||
val wrapper = ZlibExtractorOutputWrapper(currentOutput)
|
||||
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
|
||||
val latmWrapper = LatmExtractorOutputWrapper(currentOutput)
|
||||
latmOutput = latmWrapper
|
||||
val wrapper = ZlibExtractorOutputWrapper(latmWrapper)
|
||||
zlibOutput = wrapper
|
||||
extractorOutputField.set(this, wrapper)
|
||||
Log.d(TAG, "Installed zlib ExtractorOutput wrapper")
|
||||
matroskaExtractorOutputField.set(this, wrapper)
|
||||
Log.d(TAG, "Installed zlib+LATM ExtractorOutput wrapper")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +81,16 @@ class ZlibMatroskaExtractor(
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
if (id == ID_TRACK_ENTRY) {
|
||||
// Must mark before super — the track output is created inside super's
|
||||
// endMasterElement, and the x-unknown format must never reach the queue.
|
||||
val track = getCurrentTrack(id)
|
||||
if (isLoasAcmTrack(track.codecId, track.codecPrivate)) {
|
||||
Log.i(TAG, "Track ${track.number} is LOAS/LATM AAC, unwrapping to raw AAC")
|
||||
latmOutput?.markNextTrackLatm()
|
||||
}
|
||||
}
|
||||
|
||||
val wasZlib = currentTrackUsesZlib
|
||||
super.endMasterElement(id)
|
||||
|
||||
@@ -88,6 +101,11 @@ class ZlibMatroskaExtractor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
latmOutput?.resetTracks()
|
||||
super.seek(position, timeUs)
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
|
||||
* Tracks are created inactive; activateLast() enables inflation for the most recently
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import dev.jdtech.mpv.EndFileReason
|
||||
import dev.jdtech.mpv.LogLevel
|
||||
import dev.jdtech.mpv.LogMessage
|
||||
import dev.jdtech.mpv.MpvEvent
|
||||
|
||||
/** Adds the native diagnostic that libmpv-android exposes separately via logFlow. */
|
||||
internal class MpvEndFileDiagnostics {
|
||||
private var errorMessage: String? = null
|
||||
|
||||
fun onStartFile() {
|
||||
errorMessage = null
|
||||
}
|
||||
|
||||
fun onLogMessage(message: LogMessage) {
|
||||
if (message.level == LogLevel.Fatal || message.level == LogLevel.Error) {
|
||||
errorMessage = message.text.takeIf { it.isNotBlank() }
|
||||
}
|
||||
}
|
||||
|
||||
fun onEndFile(event: MpvEvent.EndFile): Map<String, Any>? {
|
||||
val reason = event.reason
|
||||
if (reason == null) {
|
||||
errorMessage = null
|
||||
return null
|
||||
}
|
||||
val data = mutableMapOf<String, Any>("reason" to reason.id)
|
||||
if (reason == EndFileReason.Error) {
|
||||
errorMessage?.let { data["message"] = it }
|
||||
}
|
||||
errorMessage = null
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import android.app.Activity
|
||||
import android.graphics.Color
|
||||
import android.content.Context
|
||||
import android.graphics.PixelFormat
|
||||
import android.media.AudioAttributes
|
||||
import android.media.ImageReader
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
@@ -14,20 +16,39 @@ import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewTreeObserver
|
||||
import com.edde746.plezy.shared.AudioFocusManager
|
||||
import com.edde746.plezy.shared.FlutterOverlayHelper
|
||||
import com.edde746.plezy.shared.FrameRateManager
|
||||
import com.edde746.plezy.shared.PlayerDelegate
|
||||
import com.edde746.plezy.shared.PlayerSurfaceHost
|
||||
import dev.jdtech.mpv.*
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
/**
|
||||
* mpv playback core. Two modes:
|
||||
* - Video (default): [context] is the host Activity, which is needed for the
|
||||
* SurfaceView/window hierarchy, display refresh-rate reads and frame-rate
|
||||
* matching.
|
||||
* - Audio-only ([audioOnly]): the music core. Built on the application
|
||||
* context (no Activity dependency, so it survives activity teardown);
|
||||
* never creates a surface, view, or frame-rate manager, and mpv is
|
||||
* configured before init to never open a video output (`vid=no`,
|
||||
* `force-window=no`, `audio-display=no`, plus `gapless-audio=weak`).
|
||||
*/
|
||||
class MpvPlayerCore(
|
||||
private val context: Context,
|
||||
private val audioOnly: Boolean = false
|
||||
) : SurfaceHolder.Callback {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerCore"
|
||||
}
|
||||
|
||||
/** Video-only paths. The plugin always constructs video cores with the
|
||||
* host Activity, and audio-only mode never touches these paths. */
|
||||
private val activity: Activity
|
||||
get() = context as Activity
|
||||
|
||||
private var surfaceView: SurfaceView? = null
|
||||
private var surfaceContainer: android.widget.FrameLayout? = null
|
||||
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
|
||||
@@ -52,11 +73,28 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
|
||||
@Volatile private var player: MpvPlayer? = null
|
||||
private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
private val endFileDiagnostics = MpvEndFileDiagnostics()
|
||||
|
||||
// mpv writes must stay off the main thread but run in submission order:
|
||||
// setupMpvFallback sets vo/ao/hwdec immediately before the loadfile command,
|
||||
// and an unordered pool can run loadfile first, leaving mpv with no video
|
||||
// output (#1482).
|
||||
private val mpvWriteDispatcher = Dispatchers.IO.limitedParallelism(1)
|
||||
|
||||
// Frame rate matching
|
||||
private var frameRateManager: FrameRateManager? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
// Result-callback marshaling. Separate from [handler], whose queued
|
||||
// messages dispose() clears — pending method-channel results must still
|
||||
// complete after dispose.
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
/** Same semantics as Activity.runOnUiThread, without needing an Activity. */
|
||||
private fun runOnMain(block: () -> Unit) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post(block)
|
||||
}
|
||||
|
||||
// Audio focus
|
||||
private var audioFocusManager: AudioFocusManager? = null
|
||||
|
||||
@@ -82,18 +120,11 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
private var flutterOverlayApplied = false
|
||||
|
||||
private fun ensureFlutterOverlayOnTop() {
|
||||
if (disposing || flutterOverlayApplied) return
|
||||
if (audioOnly || disposing || flutterOverlayApplied) return
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.post {
|
||||
if (disposing || !isInitialized) return@post
|
||||
val container = FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)
|
||||
?: return@post
|
||||
if (contentView.getChildAt(contentView.childCount - 1) == container) {
|
||||
flutterOverlayApplied = true
|
||||
return@post
|
||||
}
|
||||
FlutterOverlayHelper.configureFlutterZOrder(contentView, container, compositionOrder = 1)
|
||||
flutterOverlayApplied = true
|
||||
flutterOverlayApplied = PlayerSurfaceHost.ensureFlutterOverlayOnTop(contentView, surfaceContainer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,26 +136,42 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
Log.d(TAG, "Created MPV placeholder surface")
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun currentDisplayFpsOverride(): String? {
|
||||
val refreshRate = activity.display?.mode?.refreshRate ?: return null
|
||||
if (audioOnly) return null
|
||||
val display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
activity.display
|
||||
} else {
|
||||
activity.windowManager.defaultDisplay
|
||||
}
|
||||
val refreshRate = display?.mode?.refreshRate ?: return null
|
||||
if (refreshRate <= 0f) return null
|
||||
return refreshRate.toString()
|
||||
}
|
||||
|
||||
private fun updateDisplayFpsOverride(p: MpvPlayer, reason: String) {
|
||||
private fun updateDisplayFpsOverride(p: MpvPlayer, reason: String, onComplete: () -> Unit = {}) {
|
||||
val fps = currentDisplayFpsOverride()
|
||||
if (fps == null) {
|
||||
Log.d(TAG, "Skipping display-fps-override update ($reason): no display rate")
|
||||
onComplete()
|
||||
return
|
||||
}
|
||||
if (!scope.isActive) {
|
||||
onComplete()
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
runBlocking(Dispatchers.IO) {
|
||||
scope.launch(mpvWriteDispatcher) {
|
||||
try {
|
||||
p.setProperty("display-fps-override", fps)
|
||||
Log.d(TAG, "Updated display-fps-override=$fps ($reason)")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to update display-fps-override ($reason)", e)
|
||||
} finally {
|
||||
withContext(NonCancellable + Dispatchers.Main) {
|
||||
onComplete()
|
||||
}
|
||||
}
|
||||
Log.d(TAG, "Updated display-fps-override=$fps ($reason)")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to update display-fps-override ($reason)", e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +184,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
|
||||
try {
|
||||
disposing = false
|
||||
endFileDiagnostics.onStartFile()
|
||||
cachedPaused = true
|
||||
pausedForSurfaceLoss = false
|
||||
pendingSurface = null
|
||||
@@ -152,12 +200,15 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
lastAppliedSurfaceSize = null
|
||||
lastKnownSurfaceWidth = 0
|
||||
lastKnownSurfaceHeight = 0
|
||||
ensurePlaceholderSurface()
|
||||
if (!audioOnly) ensurePlaceholderSurface()
|
||||
|
||||
// Initialize audio focus handling
|
||||
// Initialize audio focus handling. mpv has none built in, so both modes
|
||||
// use the shared manager: pause on (transient) loss, auto-resume on
|
||||
// regain when the loss interrupted active playback.
|
||||
audioFocusManager = AudioFocusManager(
|
||||
context = activity,
|
||||
context = context,
|
||||
handler = handler,
|
||||
contentType = if (audioOnly) AudioAttributes.CONTENT_TYPE_MUSIC else AudioAttributes.CONTENT_TYPE_MOVIE,
|
||||
onPause = {
|
||||
scope.launch {
|
||||
try {
|
||||
@@ -172,57 +223,29 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
},
|
||||
isPaused = { cachedPaused }
|
||||
)
|
||||
frameRateManager = FrameRateManager(
|
||||
activity = activity,
|
||||
handler = handler,
|
||||
log = { emitLog("info", "framerate", it) }
|
||||
)
|
||||
|
||||
// Create FrameLayout container for video
|
||||
surfaceContainer = android.widget.FrameLayout(activity).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
if (!audioOnly) {
|
||||
frameRateManager = FrameRateManager(
|
||||
activity = activity,
|
||||
handler = handler,
|
||||
log = { emitLog("info", "framerate", it) }
|
||||
)
|
||||
setBackgroundColor(Color.BLACK)
|
||||
}
|
||||
|
||||
// Create SurfaceView for video rendering
|
||||
surfaceView = SurfaceView(activity).apply {
|
||||
layoutParams = android.widget.FrameLayout.LayoutParams(
|
||||
android.widget.FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
android.widget.FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
holder.addCallback(this@MpvPlayerCore)
|
||||
setZOrderOnTop(false)
|
||||
setZOrderMediaOverlay(false)
|
||||
FlutterOverlayHelper.applyCompositionOrder(this, -2)
|
||||
}
|
||||
surfaceContainer = PlayerSurfaceHost.createContainer(activity)
|
||||
surfaceView = PlayerSurfaceHost.createVideoSurface(activity, this@MpvPlayerCore)
|
||||
surfaceContainer!!.addView(surfaceView)
|
||||
|
||||
// Add SurfaceView to container
|
||||
surfaceContainer!!.addView(surfaceView)
|
||||
|
||||
// Insert container at bottom of view hierarchy (behind Flutter)
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.addView(surfaceContainer, 0)
|
||||
|
||||
// Find FlutterView and set it on top of our video surface.
|
||||
// compositionOrder maps directly to SurfaceView mSubLayer on API 36+:
|
||||
// negative is hole-punched behind the parent canvas, non-negative is above.
|
||||
// Stack (back → front): video (-2, hole-punched) → parent canvas → Flutter UI (+1).
|
||||
FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)?.let { container ->
|
||||
FlutterOverlayHelper.configureFlutterZOrder(contentView, container, compositionOrder = 1)
|
||||
flutterOverlayApplied = true
|
||||
}
|
||||
ensureFlutterOverlayOnTop()
|
||||
overlayLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
|
||||
val contentView = PlayerSurfaceHost.attachToContent(activity, surfaceContainer!!)
|
||||
flutterOverlayApplied = PlayerSurfaceHost.ensureFlutterOverlayOnTop(contentView, surfaceContainer)
|
||||
ensureFlutterOverlayOnTop()
|
||||
val sv = surfaceView
|
||||
if (sv != null) applySurfaceSize(sv.width, sv.height)
|
||||
}
|
||||
contentView.viewTreeObserver.addOnGlobalLayoutListener(overlayLayoutListener)
|
||||
overlayLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
|
||||
ensureFlutterOverlayOnTop()
|
||||
val sv = surfaceView
|
||||
if (sv != null) applySurfaceSize(sv.width, sv.height)
|
||||
}
|
||||
contentView.viewTreeObserver.addOnGlobalLayoutListener(overlayLayoutListener)
|
||||
|
||||
Log.d(TAG, "SurfaceView added to content view")
|
||||
Log.d(TAG, "SurfaceView added to content view")
|
||||
}
|
||||
|
||||
// Create MpvPlayer on background thread via coroutine
|
||||
scope.launch {
|
||||
@@ -232,18 +255,31 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
return@launch
|
||||
}
|
||||
val displayFpsOverride = currentDisplayFpsOverride()
|
||||
val p = MpvPlayer.create(activity.applicationContext) {
|
||||
setOption("vo", "gpu")
|
||||
setOption("gpu-context", "android")
|
||||
setOption("opengl-es", "yes")
|
||||
setOption("vd-lavc-film-grain", "cpu")
|
||||
val p = MpvPlayer.create(context.applicationContext) {
|
||||
if (audioOnly) {
|
||||
// Pure audio core (all set before mpv_initialize, mirroring the
|
||||
// Windows/Linux audio instances): vid=no keeps embedded cover
|
||||
// art from ever becoming a video track, force-window and
|
||||
// audio-display make sure mpv never opens a video output for
|
||||
// it, and gapless-audio splices the pre-armed next playlist
|
||||
// entry into the running audio stream.
|
||||
setOption("vid", "no")
|
||||
setOption("force-window", "no")
|
||||
setOption("audio-display", "no")
|
||||
setOption("gapless-audio", "weak")
|
||||
} else {
|
||||
setOption("vo", "gpu")
|
||||
setOption("gpu-context", "android")
|
||||
setOption("opengl-es", "yes")
|
||||
setOption("vd-lavc-film-grain", "cpu")
|
||||
if (displayFpsOverride != null) {
|
||||
setOption("display-fps-override", displayFpsOverride)
|
||||
}
|
||||
}
|
||||
setOption("ao", "audiotrack,opensles")
|
||||
// Pause on the last frame at EOF instead of unloading the file, so a
|
||||
// seek after the video ends still works (matches Linux/Windows).
|
||||
setOption("keep-open", "yes")
|
||||
if (displayFpsOverride != null) {
|
||||
setOption("display-fps-override", displayFpsOverride)
|
||||
}
|
||||
}
|
||||
if (displayFpsOverride != null) {
|
||||
Log.d(TAG, "Initial display-fps-override=$displayFpsOverride")
|
||||
@@ -258,7 +294,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
player = p
|
||||
isInitialized = true
|
||||
|
||||
refreshVideoOutput("initialize")
|
||||
if (!audioOnly) refreshVideoOutput("initialize")
|
||||
|
||||
// Start collecting events/properties/logs
|
||||
collectEvents(p)
|
||||
@@ -296,9 +332,9 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
p.eventFlow.collect { event ->
|
||||
when (event) {
|
||||
is MpvEvent.EndFile -> {
|
||||
val data = event.reason?.let { mapOf("reason" to it.id) }
|
||||
delegate?.onEvent("end-file", data)
|
||||
delegate?.onEvent("end-file", endFileDiagnostics.onEndFile(event))
|
||||
}
|
||||
is MpvEvent.StartFile -> endFileDiagnostics.onStartFile()
|
||||
is MpvEvent.FileLoaded -> delegate?.onEvent("file-loaded", null)
|
||||
is MpvEvent.PlaybackRestart -> delegate?.onEvent("playback-restart", null)
|
||||
else -> {}
|
||||
@@ -332,6 +368,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
private fun collectLogMessages(p: MpvPlayer) {
|
||||
scope.launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
p.logFlow.collect { msg ->
|
||||
endFileDiagnostics.onLogMessage(msg)
|
||||
emitLog(msg.level.name.lowercase(), msg.prefix, msg.text)
|
||||
}
|
||||
}
|
||||
@@ -393,7 +430,9 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
|
||||
private fun hasAttachedRealSurface(): Boolean = hasAttachedSurface && !attachedToPlaceholder && (attachedSurface?.isValid == true)
|
||||
|
||||
private fun hasReadyVideoOutput(): Boolean = hasAttachedRealSurface() && !videoOutputRestoring
|
||||
// Audio-only mode has no video output to wait for — playback and resume
|
||||
// paths gated on output readiness must always proceed there.
|
||||
private fun hasReadyVideoOutput(): Boolean = audioOnly || (hasAttachedRealSurface() && !videoOutputRestoring)
|
||||
|
||||
private fun isCurrentVideoOutputEpoch(epoch: Long): Boolean = !disposing && epoch == videoOutputEpoch
|
||||
|
||||
@@ -404,7 +443,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun refreshVideoOutput(reason: String) {
|
||||
if (disposing) return
|
||||
if (audioOnly || disposing) return
|
||||
|
||||
rememberCurrentSurfaceSize()
|
||||
val p = player
|
||||
@@ -649,8 +688,11 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
|
||||
// Public API
|
||||
|
||||
fun setProperty(name: String, value: String) {
|
||||
if (!isInitialized || disposing) return
|
||||
fun setProperty(name: String, value: String, onComplete: ((Boolean) -> Unit)? = null) {
|
||||
if (!isInitialized || disposing || !scope.isActive) {
|
||||
onComplete?.invoke(false)
|
||||
return
|
||||
}
|
||||
if (name == "pause") {
|
||||
val paused = normalizePauseValue(value)
|
||||
if (paused == true) {
|
||||
@@ -664,6 +706,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
if (!hasReadyVideoOutput()) {
|
||||
deferredResumeRequested = true
|
||||
Log.d(TAG, "Deferring public resume until video output is ready")
|
||||
onComplete?.invoke(true)
|
||||
return
|
||||
}
|
||||
cachedPaused = false
|
||||
@@ -671,16 +714,30 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
Log.d(TAG, "Public pause state updated: paused=false")
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
scope.launch(mpvWriteDispatcher) {
|
||||
var success = false
|
||||
try {
|
||||
player?.setProperty(name, value)
|
||||
success = true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "setProperty($name) failed", e)
|
||||
} finally {
|
||||
withContext(NonCancellable + Dispatchers.Main) {
|
||||
onComplete?.invoke(success)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getProperty(name: String): String? {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
Log.w(TAG, "Refusing synchronous getProperty($name) on the main thread")
|
||||
return null
|
||||
}
|
||||
return getPropertyBlocking(name)
|
||||
}
|
||||
|
||||
private fun getPropertyBlocking(name: String): String? {
|
||||
if (!isInitialized || disposing) return null
|
||||
return try {
|
||||
runBlocking(Dispatchers.IO) { player?.getString(name) }
|
||||
@@ -689,6 +746,75 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
}
|
||||
}
|
||||
|
||||
fun getPropertyAsync(name: String, onResult: (String?) -> Unit) {
|
||||
if (!isInitialized || disposing) {
|
||||
onResult(null)
|
||||
return
|
||||
}
|
||||
|
||||
Thread {
|
||||
val value = getPropertyBlocking(name)
|
||||
runOnMain {
|
||||
onResult(if (!disposing && isInitialized) value else null)
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns MPV stats in the same key format used by the performance overlay.
|
||||
* This method performs synchronous native property reads and must not be
|
||||
* called on Android's main thread.
|
||||
*/
|
||||
fun getStats(): Map<String, Any?> {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
Log.w(TAG, "Refusing synchronous getStats() on the main thread")
|
||||
return mapOf("playerType" to "mpv")
|
||||
}
|
||||
|
||||
val hasVideo = getProperty("video-params/w") != null
|
||||
|
||||
val stats = mutableMapOf<String, Any?>(
|
||||
"playerType" to "mpv",
|
||||
"video-codec" to getProperty("video-codec"),
|
||||
"video-params/w" to getProperty("video-params/w"),
|
||||
"video-params/h" to getProperty("video-params/h"),
|
||||
"videoWidth" to getProperty("dwidth"),
|
||||
"videoHeight" to getProperty("dheight"),
|
||||
"container-fps" to getProperty("container-fps"),
|
||||
"estimated-vf-fps" to getProperty("estimated-vf-fps"),
|
||||
"video-bitrate" to getProperty("video-bitrate"),
|
||||
"hwdec-current" to getProperty("hwdec-current"),
|
||||
"audio-codec-name" to getProperty("audio-codec-name"),
|
||||
"audio-params/samplerate" to getProperty("audio-params/samplerate"),
|
||||
"audio-params/hr-channels" to getProperty("audio-params/hr-channels"),
|
||||
"audio-bitrate" to getProperty("audio-bitrate"),
|
||||
"total-avsync-change" to getProperty("total-avsync-change"),
|
||||
"cache-used" to getProperty("cache-used"),
|
||||
"demuxer-max-bytes" to getProperty("demuxer-max-bytes"),
|
||||
"cache-speed" to getProperty("cache-speed"),
|
||||
"frame-drop-count" to getProperty("frame-drop-count"),
|
||||
"decoder-frame-drop-count" to getProperty("decoder-frame-drop-count"),
|
||||
"demuxer-cache-duration" to getProperty("demuxer-cache-duration")
|
||||
)
|
||||
|
||||
if (hasVideo) {
|
||||
stats["display-fps"] = getProperty("display-fps")
|
||||
stats["video-params/pixelformat"] = getProperty("video-params/pixelformat")
|
||||
stats["video-params/hw-pixelformat"] = getProperty("video-params/hw-pixelformat")
|
||||
stats["video-params/colormatrix"] = getProperty("video-params/colormatrix")
|
||||
stats["video-params/primaries"] = getProperty("video-params/primaries")
|
||||
stats["video-params/gamma"] = getProperty("video-params/gamma")
|
||||
stats["video-params/max-luma"] = getProperty("video-params/max-luma")
|
||||
stats["video-params/min-luma"] = getProperty("video-params/min-luma")
|
||||
stats["video-params/max-cll"] = getProperty("video-params/max-cll")
|
||||
stats["video-params/max-fall"] = getProperty("video-params/max-fall")
|
||||
stats["video-params/aspect-name"] = getProperty("video-params/aspect-name")
|
||||
stats["video-params/rotate"] = getProperty("video-params/rotate")
|
||||
}
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
fun observeProperty(name: String, format: String) {
|
||||
val p = player ?: return
|
||||
if (!isInitialized) return
|
||||
@@ -706,7 +832,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
onComplete?.invoke(false)
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
scope.launch(mpvWriteDispatcher) {
|
||||
var success = false
|
||||
try {
|
||||
player?.command(*args)
|
||||
@@ -714,15 +840,18 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "command failed", e)
|
||||
} finally {
|
||||
onComplete?.invoke(success)
|
||||
withContext(NonCancellable + Dispatchers.Main) {
|
||||
onComplete?.invoke(success)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setVisible(visible: Boolean) {
|
||||
if (disposing) return
|
||||
activity.runOnUiThread {
|
||||
if (disposing) return@runOnUiThread
|
||||
// Audio-only: no render layer to show or hide — tolerated no-op.
|
||||
if (audioOnly || disposing) return
|
||||
runOnMain {
|
||||
if (disposing) return@runOnMain
|
||||
surfaceContainer?.visibility = if (visible) View.VISIBLE else View.INVISIBLE
|
||||
if (visible) {
|
||||
flutterOverlayApplied = false
|
||||
@@ -748,16 +877,17 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
fun updateFrame() {
|
||||
if (disposing) return
|
||||
activity.runOnUiThread {
|
||||
if (disposing) return@runOnUiThread
|
||||
// Audio-only: no surface to refresh — tolerated no-op.
|
||||
if (audioOnly || disposing) return
|
||||
runOnMain {
|
||||
if (disposing) return@runOnMain
|
||||
flutterOverlayApplied = false
|
||||
ensureFlutterOverlayOnTop()
|
||||
rememberCurrentSurfaceSize()
|
||||
val p = player
|
||||
if (p == null) {
|
||||
Log.d(TAG, "updateFrame(): skipping Android MPV surface refresh because player is not ready")
|
||||
return@runOnUiThread
|
||||
return@runOnMain
|
||||
}
|
||||
if (!hasReadyVideoOutput()) {
|
||||
val surface = currentCandidateSurface()
|
||||
@@ -767,7 +897,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
} else {
|
||||
Log.d(TAG, "updateFrame(): skipping Android MPV surface refresh because no surface is attached")
|
||||
}
|
||||
return@runOnUiThread
|
||||
return@runOnMain
|
||||
}
|
||||
scope.launch {
|
||||
try {
|
||||
@@ -785,6 +915,8 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
fps: Float,
|
||||
videoDurationMs: Long,
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
val mgr = frameRateManager
|
||||
@@ -792,9 +924,12 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs) { switched ->
|
||||
player?.let { updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") }
|
||||
onComplete(switched)
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight) { switched ->
|
||||
player?.let {
|
||||
updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") {
|
||||
onComplete(switched)
|
||||
}
|
||||
} ?: onComplete(switched)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -848,17 +983,17 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
videoOutputEpoch += 1L
|
||||
}
|
||||
|
||||
// Capture locals for deferred cleanup
|
||||
// Capture locals for deferred cleanup (audio-only has no views)
|
||||
val sv = surfaceView
|
||||
val container = surfaceContainer
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
val contentView = if (audioOnly) null else activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
|
||||
surfaceContainer = null
|
||||
surfaceView = null
|
||||
|
||||
// Remove layout listener synchronously
|
||||
overlayLayoutListener?.let { listener ->
|
||||
contentView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
|
||||
contentView?.viewTreeObserver?.removeOnGlobalLayoutListener(listener)
|
||||
}
|
||||
overlayLayoutListener = null
|
||||
|
||||
@@ -880,15 +1015,18 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
if (p != null) {
|
||||
Thread {
|
||||
try {
|
||||
// Detach surface BEFORE close to prevent GPU mutex contention with view removal
|
||||
try {
|
||||
runBlocking {
|
||||
p.setProperty("force-window", "no")
|
||||
p.setProperty("vo", "null")
|
||||
// Detach surface BEFORE close to prevent GPU mutex contention with
|
||||
// view removal (audio-only never attached one)
|
||||
if (!audioOnly) {
|
||||
try {
|
||||
runBlocking {
|
||||
p.setProperty("force-window", "no")
|
||||
p.setProperty("vo", "null")
|
||||
}
|
||||
p.detachSurface()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to detach surface during dispose", e)
|
||||
}
|
||||
p.detachSurface()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to detach surface during dispose", e)
|
||||
}
|
||||
p.close()
|
||||
} catch (e: Exception) {
|
||||
@@ -899,7 +1037,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
sv?.holder?.removeCallback(this)
|
||||
if (container?.parent != null) {
|
||||
contentView.removeView(container)
|
||||
contentView?.removeView(container)
|
||||
}
|
||||
onComplete?.invoke()
|
||||
}
|
||||
@@ -909,7 +1047,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
Handler(Looper.getMainLooper()).postAtFrontOfQueue {
|
||||
sv?.holder?.removeCallback(this)
|
||||
if (container?.parent != null) {
|
||||
contentView.removeView(container)
|
||||
contentView?.removeView(container)
|
||||
}
|
||||
}
|
||||
onComplete?.invoke()
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import com.edde746.plezy.shared.PlayerChannelBinding
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
@@ -10,28 +13,39 @@ import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
class MpvPlayerPlugin :
|
||||
FlutterPlugin,
|
||||
/**
|
||||
* Channel plumbing for [MpvPlayerCore]. The default instance is the video
|
||||
* player; the [audioOnly] instance (see [MpvAudioPlayerPlugin]) drives the
|
||||
* dedicated music core on its own channel pair with two lifecycle
|
||||
* differences:
|
||||
* - the core is built on the application context, not the Activity, so
|
||||
* background music playback survives activity teardown — it is only
|
||||
* disposed on explicit Dart `dispose` or engine detach, never in
|
||||
* [onDetachedFromActivity];
|
||||
* - all video-only surface work is skipped inside the core.
|
||||
*/
|
||||
open class MpvPlayerPlugin(
|
||||
private val channelBase: String = "com.plezy/mpv_player",
|
||||
private val audioOnly: Boolean = false
|
||||
) : FlutterPlugin,
|
||||
MethodChannel.MethodCallHandler,
|
||||
EventChannel.StreamHandler,
|
||||
ActivityAware,
|
||||
com.edde746.plezy.shared.PlayerDelegate {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/mpv_player"
|
||||
private const val EVENT_CHANNEL = "com.plezy/mpv_player/events"
|
||||
}
|
||||
private val tag = if (audioOnly) "MpvAudioPlayerPlugin" else "MpvPlayerPlugin"
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
private val channels = PlayerChannelBinding(channelBase, this, this, tag)
|
||||
private var playerCore: MpvPlayerCore? = null
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private var applicationContext: Context? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
private var sessionGeneration = 0
|
||||
|
||||
/** Same semantics as Activity.runOnUiThread, without needing an Activity. */
|
||||
private fun runOnMain(block: () -> Unit) = channels.runOnMain(block)
|
||||
|
||||
// Pending `MethodChannel.Result`s for an init that is currently in flight.
|
||||
// Concurrent `invoke('initialize')` calls share the same outcome instead
|
||||
// of each tearing down the in-flight core and starting their own — which
|
||||
@@ -43,19 +57,27 @@ class MpvPlayerPlugin :
|
||||
// FlutterPlugin
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
|
||||
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
|
||||
eventChannel.setStreamHandler(this)
|
||||
|
||||
Log.d(TAG, "Attached to engine")
|
||||
applicationContext = binding.applicationContext
|
||||
channels.attach(binding)
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
eventChannel.setStreamHandler(null)
|
||||
Log.d(TAG, "Detached from engine")
|
||||
channels.detach()
|
||||
if (audioOnly) {
|
||||
// The audio core is not activity-bound; engine detach is its terminal
|
||||
// native lifecycle event (mirrors the video core's activity detach).
|
||||
disposeCoreForTeardown()
|
||||
}
|
||||
applicationContext = null
|
||||
}
|
||||
|
||||
private fun disposeCoreForTeardown() {
|
||||
++sessionGeneration
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
// Any in-flight init callback would never fire (its scope is cancelled
|
||||
// by dispose), so close out queued callers explicitly.
|
||||
completePendingInits(success = false)
|
||||
}
|
||||
|
||||
// ActivityAware
|
||||
@@ -63,43 +85,40 @@ class MpvPlayerPlugin :
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(TAG, "Attached to activity")
|
||||
Log.d(tag, "Attached to activity")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {
|
||||
++sessionGeneration
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
// Any in-flight init callback would never fire (its scope is cancelled
|
||||
// by dispose), so close out queued callers explicitly.
|
||||
completePendingInits(success = false)
|
||||
// The audio-only core deliberately outlives the activity (background
|
||||
// music); it is torn down on engine detach / Dart dispose instead.
|
||||
if (!audioOnly) {
|
||||
disposeCoreForTeardown()
|
||||
}
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
Log.d(tag, "Detached from activity")
|
||||
}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(TAG, "Reattached to activity for config changes")
|
||||
Log.d(tag, "Reattached to activity for config changes")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity for config changes")
|
||||
Log.d(tag, "Detached from activity for config changes")
|
||||
}
|
||||
|
||||
// EventChannel.StreamHandler
|
||||
|
||||
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
|
||||
eventSink = events
|
||||
Log.d(TAG, "Event stream connected")
|
||||
channels.listen(events)
|
||||
}
|
||||
|
||||
override fun onCancel(arguments: Any?) {
|
||||
eventSink = null
|
||||
Log.d(TAG, "Event stream disconnected")
|
||||
channels.cancel()
|
||||
}
|
||||
|
||||
// MethodChannel.MethodCallHandler
|
||||
@@ -110,6 +129,7 @@ class MpvPlayerPlugin :
|
||||
"dispose" -> handleDispose(result)
|
||||
"setProperty" -> handleSetProperty(call, result)
|
||||
"getProperty" -> handleGetProperty(call, result)
|
||||
"getStats" -> handleGetStats(result)
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"command" -> handleCommand(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
@@ -119,21 +139,28 @@ class MpvPlayerPlugin :
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"openContentFd" -> handleOpenContentFd(call, result)
|
||||
"closeContentFd" -> handleCloseContentFd(call, result)
|
||||
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
|
||||
"setLogLevel" -> result.success(null)
|
||||
"setLogLevel" -> handleSetLogLevel(call, result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleInitialize(result: MethodChannel.Result) {
|
||||
val currentActivity = activity
|
||||
if (currentActivity == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
// Video cores need the Activity (surface/view hierarchy); the audio-only
|
||||
// core is built on the application context so it can outlive it.
|
||||
val coreContext: Context? = if (audioOnly) applicationContext else activity
|
||||
if (coreContext == null) {
|
||||
if (audioOnly) {
|
||||
result.error("NO_CONTEXT", "Application context not available", null)
|
||||
} else {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (playerCore?.isInitialized == true) {
|
||||
Log.d(TAG, "Already initialized")
|
||||
Log.d(tag, "Already initialized")
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
@@ -145,13 +172,13 @@ class MpvPlayerPlugin :
|
||||
synchronized(pendingInitResults) {
|
||||
pendingInitResults += result
|
||||
if (isInitializing) {
|
||||
Log.d(TAG, "Init already in flight, queuing caller")
|
||||
Log.d(tag, "Init already in flight, queuing caller")
|
||||
return
|
||||
}
|
||||
isInitializing = true
|
||||
}
|
||||
|
||||
currentActivity.runOnUiThread {
|
||||
runOnMain {
|
||||
val gen: Int
|
||||
val core: MpvPlayerCore
|
||||
try {
|
||||
@@ -159,31 +186,32 @@ class MpvPlayerPlugin :
|
||||
// OR `playerCore?.isInitialized == true` and we early-exited
|
||||
// above. We never tear down a core that's mid-initialization.
|
||||
if (playerCore != null && playerCore?.isInitialized != true) {
|
||||
Log.w(TAG, "Discarding stale uninitialized core before re-init")
|
||||
Log.w(tag, "Discarding stale uninitialized core before re-init")
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
}
|
||||
|
||||
gen = ++sessionGeneration
|
||||
core = MpvPlayerCore(currentActivity).apply {
|
||||
core = MpvPlayerCore(coreContext, audioOnly).apply {
|
||||
delegate = this@MpvPlayerPlugin
|
||||
}
|
||||
playerCore = core
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to initialize: ${e.message}", e)
|
||||
Log.e(tag, "Failed to initialize: ${e.message}", e)
|
||||
completePendingInits(success = false, errorMessage = e.message)
|
||||
return@runOnUiThread
|
||||
return@runOnMain
|
||||
}
|
||||
|
||||
core.initialize { success ->
|
||||
val stale = gen != sessionGeneration || playerCore !== core
|
||||
if (stale) {
|
||||
Log.d(TAG, "Stale init callback (gen=$gen, current=$sessionGeneration)")
|
||||
Log.d(tag, "Stale init callback (gen=$gen, current=$sessionGeneration)")
|
||||
} else {
|
||||
// Start hidden - now safe because setVisible operates on the container,
|
||||
// not the SurfaceView directly (matching ExoPlayer's approach)
|
||||
// not the SurfaceView directly (matching ExoPlayer's approach).
|
||||
// No-op on the audio-only core, which has no render layer.
|
||||
core.setVisible(false)
|
||||
Log.d(TAG, "Initialized: $success")
|
||||
Log.d(tag, "Initialized: $success")
|
||||
}
|
||||
completePendingInits(success = !stale && success)
|
||||
}
|
||||
@@ -207,7 +235,7 @@ class MpvPlayerPlugin :
|
||||
}
|
||||
|
||||
private fun handleDispose(result: MethodChannel.Result) {
|
||||
activity?.runOnUiThread {
|
||||
runOnMain {
|
||||
val core = playerCore
|
||||
++sessionGeneration
|
||||
playerCore = null
|
||||
@@ -217,10 +245,10 @@ class MpvPlayerPlugin :
|
||||
completePendingInits(success = false)
|
||||
|
||||
core?.dispose {
|
||||
Log.d(TAG, "Disposed")
|
||||
Log.d(tag, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
@@ -232,8 +260,15 @@ class MpvPlayerPlugin :
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.setProperty(name, value)
|
||||
result.success(null)
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
|
||||
core.setProperty(name, value) {
|
||||
result.success(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
@@ -244,8 +279,40 @@ class MpvPlayerPlugin :
|
||||
return
|
||||
}
|
||||
|
||||
val value = playerCore?.getProperty(name)
|
||||
result.success(value)
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
|
||||
val gen = sessionGeneration
|
||||
core.getPropertyAsync(name) { value ->
|
||||
if (gen != sessionGeneration || playerCore !== core) {
|
||||
result.success(null)
|
||||
} else {
|
||||
result.success(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetStats(result: MethodChannel.Result) {
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(mapOf("playerType" to "mpv"))
|
||||
return
|
||||
}
|
||||
|
||||
val gen = sessionGeneration
|
||||
Thread {
|
||||
val stats = core.getStats()
|
||||
runOnMain {
|
||||
if (gen != sessionGeneration || playerCore !== core) {
|
||||
result.success(mapOf("playerType" to "mpv"))
|
||||
} else {
|
||||
result.success(stats)
|
||||
}
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
@@ -273,14 +340,30 @@ class MpvPlayerPlugin :
|
||||
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
result.error("NOT_INITIALIZED", "Player not initialized", null)
|
||||
return
|
||||
}
|
||||
core.command(args.toTypedArray()) {
|
||||
result.success(null)
|
||||
core.command(args.toTypedArray()) { success ->
|
||||
if (success) {
|
||||
result.success(null)
|
||||
} else {
|
||||
result.error("COMMAND_FAILED", "mpv command failed", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSetLogLevel(call: MethodCall, result: MethodChannel.Result) {
|
||||
if (call.argument<String>("level") == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'level'", null)
|
||||
return
|
||||
}
|
||||
result.error(
|
||||
"UNSUPPORTED",
|
||||
"Runtime mpv log level changes are not supported on Android",
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
|
||||
val visible = call.argument<Boolean>("visible")
|
||||
|
||||
@@ -302,32 +385,34 @@ class MpvPlayerPlugin :
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
|
||||
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
|
||||
Log.d(tag, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs) { switched ->
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
|
||||
result.success(switched)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
Log.d(tag, "clearVideoFrameRate")
|
||||
playerCore?.clearVideoFrameRate()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "requestAudioFocus")
|
||||
Log.d(tag, "requestAudioFocus")
|
||||
val granted = playerCore?.requestAudioFocus() ?: false
|
||||
result.success(granted)
|
||||
}
|
||||
|
||||
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(TAG, "abandonAudioFocus")
|
||||
Log.d(tag, "abandonAudioFocus")
|
||||
playerCore?.abandonAudioFocus()
|
||||
result.success(null)
|
||||
}
|
||||
@@ -339,9 +424,11 @@ class MpvPlayerPlugin :
|
||||
return
|
||||
}
|
||||
|
||||
val contentResolver = activity?.contentResolver
|
||||
// The audio instance may run without an Activity (background music), so
|
||||
// resolve SAF content URIs through the application context there.
|
||||
val contentResolver = (if (audioOnly) applicationContext else activity)?.contentResolver
|
||||
if (contentResolver == null) {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
result.error(if (audioOnly) "NO_CONTEXT" else "NO_ACTIVITY", "Context not available", null)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -351,35 +438,58 @@ class MpvPlayerPlugin :
|
||||
val uri = Uri.parse(uriString)
|
||||
val pfd = contentResolver.openFileDescriptor(uri, "r")
|
||||
if (pfd == null) {
|
||||
activity?.runOnUiThread {
|
||||
runOnMain {
|
||||
result.error("OPEN_FAILED", "Failed to open file descriptor for $uriString", null)
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
|
||||
val fd = pfd.detachFd()
|
||||
Log.d(TAG, "Opened content FD $fd for $uriString")
|
||||
activity?.runOnUiThread { result.success(fd) }
|
||||
Log.d(tag, "Opened content FD $fd for $uriString")
|
||||
runOnMain { result.success(fd) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
|
||||
activity?.runOnUiThread { result.error("OPEN_FAILED", e.message, null) }
|
||||
Log.e(tag, "Failed to open content FD: ${e.message}", e)
|
||||
runOnMain { result.error("OPEN_FAILED", e.message, null) }
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
// Reclaims a detached fd from handleOpenContentFd that mpv will never
|
||||
// consume (a gapless-armed entry dropped before mpv opened it). The Dart
|
||||
// side guarantees single-close and only calls this when the entry provably
|
||||
// never played.
|
||||
private fun handleCloseContentFd(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fd = call.argument<Int>("fd")
|
||||
if (fd == null || fd < 0) {
|
||||
result.error("INVALID_ARGS", "Missing 'fd'", null)
|
||||
return
|
||||
}
|
||||
try {
|
||||
ParcelFileDescriptor.adoptFd(fd).close()
|
||||
Log.d(tag, "Closed content FD $fd")
|
||||
result.success(null)
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Failed to close content FD $fd: ${e.message}", e)
|
||||
result.error("CLOSE_FAILED", e.message, null)
|
||||
}
|
||||
}
|
||||
|
||||
// PlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = nameToId[name] ?: return
|
||||
eventSink?.success(listOf(propId, value))
|
||||
channels.emitProperty(propId, value)
|
||||
}
|
||||
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
eventSink?.success(event)
|
||||
channels.emitEvent(name, data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The audio-only music instance on `com.plezy/mpv_audio_player[/events]`.
|
||||
* A distinct class (not just a configured [MpvPlayerPlugin]) because
|
||||
* FlutterEngine's plugin registry keys plugins by class and would silently
|
||||
* drop a second [MpvPlayerPlugin] registration.
|
||||
*/
|
||||
class MpvAudioPlayerPlugin : MpvPlayerPlugin(channelBase = "com.plezy/mpv_audio_player", audioOnly = true)
|
||||
|
||||
@@ -14,7 +14,8 @@ class AudioFocusManager(
|
||||
private val onPause: () -> Unit,
|
||||
private val onResume: () -> Unit,
|
||||
private val isPaused: () -> Boolean,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) }
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) },
|
||||
private val contentType: Int = AudioAttributes.CONTENT_TYPE_MOVIE
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "AudioFocusManager"
|
||||
@@ -62,7 +63,7 @@ class AudioFocusManager(
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||
.setContentType(contentType)
|
||||
.build()
|
||||
)
|
||||
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
|
||||
|
||||
@@ -37,6 +37,8 @@ class FrameRateManager(
|
||||
)
|
||||
|
||||
private var currentVideoFps: Float = 0f
|
||||
private var currentVideoWidth: Int = 0
|
||||
private var currentVideoHeight: Int = 0
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private var pendingSettleRunnable: Runnable? = null
|
||||
private var watchdogRunnable: Runnable? = null
|
||||
@@ -57,9 +59,13 @@ class FrameRateManager(
|
||||
fps: Float,
|
||||
videoDurationMs: Long,
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int = 0,
|
||||
videoHeight: Int = 0,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
currentVideoFps = fps
|
||||
currentVideoWidth = videoWidth
|
||||
currentVideoHeight = videoHeight
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
onComplete(false)
|
||||
@@ -68,7 +74,7 @@ class FrameRateManager(
|
||||
|
||||
log(
|
||||
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
|
||||
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
@@ -208,17 +214,42 @@ class FrameRateManager(
|
||||
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun findBestModeMatch(fps: Float, currentMode: Display.Mode, supportedModes: Array<Display.Mode>): DisplayModeCandidate? = supportedModes.asSequence()
|
||||
.filter { mode ->
|
||||
mode.physicalHeight == currentMode.physicalHeight &&
|
||||
mode.physicalWidth == currentMode.physicalWidth
|
||||
}
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<DisplayModeCandidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
private fun findBestModeMatch(
|
||||
fps: Float,
|
||||
currentMode: Display.Mode,
|
||||
supportedModes: Array<Display.Mode>,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int
|
||||
): DisplayModeCandidate? {
|
||||
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
|
||||
// switch, the least disruptive (no resolution/HDMI renegotiation).
|
||||
supportedModes.asSequence()
|
||||
.filter { it.physicalHeight == currentMode.physicalHeight && it.physicalWidth == currentMode.physicalWidth }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<DisplayModeCandidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
?.let { return it }
|
||||
|
||||
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
|
||||
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
|
||||
// that downscales the video below its native size (trading detail for cadence).
|
||||
// Requires known video dimensions; without them keep Tier-1-only behaviour.
|
||||
if (videoWidth <= 0 || videoHeight <= 0) return null
|
||||
val currentArea = currentMode.physicalWidth.toLong() * currentMode.physicalHeight
|
||||
return supportedModes.asSequence()
|
||||
.filter { it.physicalWidth >= videoWidth && it.physicalHeight >= videoHeight }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
// Prefer the resolution closest to the panel's current one (least change,
|
||||
// keeps panel-native res when a high-res match exists), then refresh match.
|
||||
compareBy<DisplayModeCandidate> { abs(it.mode.physicalWidth.toLong() * it.mode.physicalHeight - currentArea) }
|
||||
.thenBy { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
)
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
@@ -239,9 +270,12 @@ class FrameRateManager(
|
||||
val currentMode = display.mode
|
||||
log("supported modes=${describeSupportedModes(supportedModes)}")
|
||||
|
||||
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes)
|
||||
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes, currentVideoWidth, currentVideoHeight)
|
||||
if (modeMatch == null) {
|
||||
log("no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight}")
|
||||
log(
|
||||
"no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight} " +
|
||||
"(video=${currentVideoWidth}x$currentVideoHeight)"
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaCodecList
|
||||
import android.os.Build
|
||||
import java.util.Locale
|
||||
|
||||
/** Canonical decoder lookup and hardware classification for native playback. */
|
||||
internal object MediaCodecQuery {
|
||||
fun findHardwareDecoder(
|
||||
mimeType: String,
|
||||
codecKind: Int = MediaCodecList.REGULAR_CODECS,
|
||||
predicate: (MediaCodecInfo, String) -> Boolean = { _, _ -> true }
|
||||
): MediaCodecInfo? {
|
||||
for (info in MediaCodecList(codecKind).codecInfos) {
|
||||
if (info.isEncoder || !isHardwareAccelerated(info)) continue
|
||||
for (type in info.supportedTypes) {
|
||||
if (type.equals(mimeType, ignoreCase = true) && predicate(info, type)) {
|
||||
return info
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun isHardwareAccelerated(info: MediaCodecInfo): Boolean {
|
||||
val name = info.name
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
isHardwareAccelerated(Build.VERSION.SDK_INT, info.isHardwareAccelerated, name)
|
||||
} else {
|
||||
// MediaCodecInfo.isHardwareAccelerated() does not exist before API 29.
|
||||
// Keep the call inside the version gate so older Fire OS releases do not
|
||||
// fail with NoSuchMethodError while initializing playback.
|
||||
isHardwareAccelerated(Build.VERSION.SDK_INT, false, name)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isHardwareAccelerated(
|
||||
sdkInt: Int,
|
||||
platformReportsHardware: Boolean,
|
||||
name: String
|
||||
): Boolean {
|
||||
// API 29 added manufacturer-provided classification, but some Codec2
|
||||
// builders still flag known software components as hardware. Require both
|
||||
// signals there; older releases expose only component names.
|
||||
return if (sdkInt >= Build.VERSION_CODES.Q) {
|
||||
platformReportsHardware && !isSoftwareCodecName(name)
|
||||
} else {
|
||||
!isSoftwareCodecName(name)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isSoftwareCodecName(name: String): Boolean {
|
||||
val normalized = name.lowercase(Locale.ROOT)
|
||||
return normalized.startsWith("omx.google.") ||
|
||||
normalized.startsWith("omx.ffmpeg.") ||
|
||||
normalized.startsWith("c2.android.") ||
|
||||
normalized.startsWith("c2.google.") ||
|
||||
normalized.startsWith("c2.ffmpeg.") ||
|
||||
normalized.contains(".sw.")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
|
||||
internal data class ResolvedMpvUri(
|
||||
val value: String,
|
||||
private val ownedFd: Int? = null
|
||||
) {
|
||||
fun closeIfUnused() {
|
||||
val fd = ownedFd ?: return
|
||||
try {
|
||||
ParcelFileDescriptor.adoptFd(fd).close()
|
||||
} catch (error: Exception) {
|
||||
Log.w("MpvContentUriResolver", "Failed to close unused content FD $fd", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object MpvContentUriResolver {
|
||||
private const val TAG = "MpvContentUriResolver"
|
||||
|
||||
fun resolve(
|
||||
uriString: String,
|
||||
resolver: ContentResolver,
|
||||
mainHandler: Handler,
|
||||
onResolved: (ResolvedMpvUri) -> Unit
|
||||
) {
|
||||
resolve(uriString, mainHandler, opener = {
|
||||
val descriptor = resolver.openFileDescriptor(Uri.parse(uriString), "r") ?: return@resolve null
|
||||
descriptor.detachFd()
|
||||
}, onResolved = onResolved)
|
||||
}
|
||||
|
||||
internal fun resolve(
|
||||
uriString: String,
|
||||
mainHandler: Handler,
|
||||
opener: () -> Int?,
|
||||
onResolved: (ResolvedMpvUri) -> Unit
|
||||
) {
|
||||
if (!uriString.startsWith("content://")) {
|
||||
onResolved(ResolvedMpvUri(uriString))
|
||||
return
|
||||
}
|
||||
|
||||
Thread {
|
||||
check(Looper.myLooper() != Looper.getMainLooper()) {
|
||||
"Content file descriptors must not be opened on the main thread"
|
||||
}
|
||||
val fd = try {
|
||||
opener()
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "Failed to open content FD for $uriString", error)
|
||||
null
|
||||
}
|
||||
val resolved = if (fd == null) {
|
||||
ResolvedMpvUri(uriString)
|
||||
} else {
|
||||
Log.d(TAG, "Opened content FD $fd for $uriString")
|
||||
ResolvedMpvUri("fdclose://$fd", fd)
|
||||
}
|
||||
mainHandler.post { onResolved(resolved) }
|
||||
}.start()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
/** Owns the identical MethodChannel/EventChannel lifecycle for native players. */
|
||||
internal class PlayerChannelBinding(
|
||||
private val channelBase: String,
|
||||
private val methodCallHandler: MethodChannel.MethodCallHandler,
|
||||
private val streamHandler: EventChannel.StreamHandler,
|
||||
private val logTag: String
|
||||
) {
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
|
||||
val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
fun attach(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, channelBase)
|
||||
methodChannel.setMethodCallHandler(methodCallHandler)
|
||||
|
||||
eventChannel = EventChannel(binding.binaryMessenger, "$channelBase/events")
|
||||
eventChannel.setStreamHandler(streamHandler)
|
||||
|
||||
Log.d(logTag, "Attached to engine")
|
||||
}
|
||||
|
||||
fun detach() {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
eventChannel.setStreamHandler(null)
|
||||
eventSink = null
|
||||
Log.d(logTag, "Detached from engine")
|
||||
}
|
||||
|
||||
fun listen(events: EventChannel.EventSink?) {
|
||||
eventSink = events
|
||||
Log.d(logTag, "Event stream connected")
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
eventSink = null
|
||||
Log.d(logTag, "Event stream disconnected")
|
||||
}
|
||||
|
||||
fun runOnMain(block: () -> Unit) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
block()
|
||||
} else {
|
||||
mainHandler.post(block)
|
||||
}
|
||||
}
|
||||
|
||||
fun emitProperty(id: Int, value: Any?) {
|
||||
runOnMain { eventSink?.success(listOf(id, value)) }
|
||||
}
|
||||
|
||||
fun emitEvent(name: String, data: Map<String, Any>? = null) {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
runOnMain { eventSink?.success(event) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.app.Activity
|
||||
import android.graphics.Color
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
|
||||
/** Shared Android view scaffold beneath the ExoPlayer and mpv cores. */
|
||||
internal object PlayerSurfaceHost {
|
||||
fun createContainer(activity: Activity, clipChildren: Boolean = false): FrameLayout = FrameLayout(activity).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
setBackgroundColor(Color.BLACK)
|
||||
this.clipChildren = clipChildren
|
||||
}
|
||||
|
||||
fun createVideoSurface(activity: Activity, callback: SurfaceHolder.Callback): SurfaceView = SurfaceView(activity).apply {
|
||||
layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
holder.addCallback(callback)
|
||||
setZOrderOnTop(false)
|
||||
setZOrderMediaOverlay(false)
|
||||
FlutterOverlayHelper.applyCompositionOrder(this, -2)
|
||||
}
|
||||
|
||||
fun attachToContent(activity: Activity, container: FrameLayout): ViewGroup {
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.addView(container, 0)
|
||||
ensureFlutterOverlayOnTop(contentView, container)
|
||||
return contentView
|
||||
}
|
||||
|
||||
fun ensureFlutterOverlayOnTop(contentView: ViewGroup, surfaceContainer: ViewGroup?): Boolean {
|
||||
val flutterContainer = FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)
|
||||
?: return false
|
||||
if (contentView.getChildAt(contentView.childCount - 1) !== flutterContainer) {
|
||||
FlutterOverlayHelper.configureFlutterZOrder(contentView, flutterContainer, compositionOrder = 1)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,6 @@
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
@@ -15,30 +13,24 @@
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<!-- Splash theme variants for setSplashScreenTheme -->
|
||||
<style name="SplashTheme.Dark" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_dark</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Oled" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_oled</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Light" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_light</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.System" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
@@ -15,30 +13,24 @@
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<!-- Splash theme variants for setSplashScreenTheme -->
|
||||
<style name="SplashTheme.Dark" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_dark</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Oled" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_oled</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Light" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_light</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.System" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.os.Looper
|
||||
import android.view.TextureView
|
||||
import java.time.Duration
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.LooperMode
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class DeferredSurfaceTextureListenerTest {
|
||||
|
||||
private lateinit var surface: SurfaceTexture
|
||||
private lateinit var delegate: RecordingListener
|
||||
private lateinit var listener: DeferredSurfaceTextureListener
|
||||
private var currentSurface: SurfaceTexture? = null
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
surface = SurfaceTexture(0)
|
||||
currentSurface = surface
|
||||
delegate = RecordingListener()
|
||||
listener = DeferredSurfaceTextureListener(delegate) { candidate -> candidate === currentSurface }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
surface.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forwardsRepeatedSameSizeCallbacks() {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
idlePastResizeDelay()
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(listOf(1920 to 1080, 1920 to 1080), delegate.sizes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coalescesPendingCallbacksToLatestSize() {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1280, 720)
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(listOf(1920 to 1080), delegate.sizes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ignoresCallbackForObsoleteSurface() {
|
||||
val replacement = SurfaceTexture(0)
|
||||
try {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
currentSurface = replacement
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(emptyList<Pair<Int, Int>>(), delegate.sizes)
|
||||
} finally {
|
||||
replacement.release()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun destroyingSurfaceCancelsPendingCallback() {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
listener.onSurfaceTextureDestroyed(surface)
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(emptyList<Pair<Int, Int>>(), delegate.sizes)
|
||||
assertEquals(1, delegate.destroyedCount)
|
||||
}
|
||||
|
||||
private fun idlePastResizeDelay() {
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(101))
|
||||
}
|
||||
|
||||
private class RecordingListener : TextureView.SurfaceTextureListener {
|
||||
val sizes = mutableListOf<Pair<Int, Int>>()
|
||||
var destroyedCount = 0
|
||||
|
||||
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) = Unit
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
sizes += width to height
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) = Unit
|
||||
|
||||
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
|
||||
destroyedCount++
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ExternalPlayerChannelTest {
|
||||
|
||||
@Test
|
||||
fun mxPlayerResultPreservesPositionDurationAndCompletion() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).get()
|
||||
val channel = ExternalPlayerChannel(activity)
|
||||
val data = Intent("com.mxtech.intent.result.VIEW")
|
||||
.putExtra("position", 123)
|
||||
.putExtra("duration", "456")
|
||||
.putExtra("end_by", "playback_completion")
|
||||
|
||||
val result = channel.buildResult(Activity.RESULT_OK, data)
|
||||
|
||||
assertEquals(123L, result["positionMs"])
|
||||
assertEquals(456L, result["durationMs"])
|
||||
assertEquals(true, result["playbackCompleted"])
|
||||
assertEquals(false, result["playbackError"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activityDestroyCompletesPendingChannelCall() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).get()
|
||||
val channel = ExternalPlayerChannel(activity)
|
||||
val result = RecordingResult()
|
||||
channel.javaClass.getDeclaredField("pendingResult").apply {
|
||||
isAccessible = true
|
||||
set(channel, result)
|
||||
}
|
||||
|
||||
channel.dispose()
|
||||
|
||||
assertTrue(result.completed)
|
||||
assertEquals("ACTIVITY_DESTROYED", result.errorCode)
|
||||
}
|
||||
|
||||
private class RecordingResult : MethodChannel.Result {
|
||||
var completed = false
|
||||
var errorCode: String? = null
|
||||
|
||||
override fun success(result: Any?) {
|
||||
completed = true
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
|
||||
completed = true
|
||||
this.errorCode = errorCode
|
||||
}
|
||||
|
||||
override fun notImplemented() {
|
||||
completed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.MimeTypes
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class AudioOutputPolicyTest {
|
||||
|
||||
@Test
|
||||
fun passthroughDisabledBlocksBitstreamFormats() {
|
||||
val bitstreamFormats = listOf(
|
||||
"audio/ac3",
|
||||
"audio/eac3",
|
||||
"audio/eac3-joc",
|
||||
"audio/ac4",
|
||||
"audio/vnd.dts",
|
||||
"audio/vnd.dts.hd",
|
||||
"audio/vnd.dts.uhd",
|
||||
MimeTypes.AUDIO_TRUEHD
|
||||
)
|
||||
|
||||
for (mimeType in bitstreamFormats) {
|
||||
assertTrue(mimeType, shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled = false))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passthroughEnabledAllowsBitstreamFormats() {
|
||||
assertFalse(shouldBlockDirectOutputForPassthrough("audio/ac3", audioPassthroughEnabled = true))
|
||||
assertFalse(shouldBlockDirectOutputForPassthrough(MimeTypes.AUDIO_TRUEHD, audioPassthroughEnabled = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passthroughDisabledLeavesDecodedFormatsAvailable() {
|
||||
val decodedFormats = listOf(
|
||||
MimeTypes.AUDIO_AAC,
|
||||
MimeTypes.AUDIO_OPUS,
|
||||
MimeTypes.AUDIO_RAW,
|
||||
MimeTypes.AUDIO_FLAC
|
||||
)
|
||||
|
||||
for (mimeType in decodedFormats) {
|
||||
assertFalse(mimeType, shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled = false))
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.EOFException
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class BufferedTransformingTrackOutputTest {
|
||||
|
||||
@Test
|
||||
fun activeTransformBuffersChunksAndEmitsOneNormalizedSample() {
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = IncrementingTrackOutput(delegate)
|
||||
|
||||
output.sampleData(ParsableByteArray(byteArrayOf(1, 2)), 2, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleData(ParsableByteArray(byteArrayOf(3)), 1, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(42, C.BUFFER_FLAG_KEY_FRAME, 3, 7, null)
|
||||
|
||||
assertArrayEquals(byteArrayOf(2, 3, 4), delegate.bytes.toByteArray())
|
||||
assertEquals(42, delegate.timeUs)
|
||||
assertEquals(3, delegate.sampleSize)
|
||||
assertEquals(0, delegate.sampleOffset)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeTransformHonorsDataReaderEndOfInputContract() {
|
||||
val output = IncrementingTrackOutput(RecordingTrackOutput())
|
||||
val exhausted = DataReader { _, _, _ -> C.RESULT_END_OF_INPUT }
|
||||
|
||||
assertThrows(EOFException::class.java) {
|
||||
output.sampleData(exhausted, 1, false, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
}
|
||||
assertEquals(
|
||||
C.RESULT_END_OF_INPUT,
|
||||
output.sampleData(exhausted, 1, true, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
)
|
||||
}
|
||||
|
||||
private class IncrementingTrackOutput(delegate: TrackOutput) : BufferedTransformingTrackOutput(delegate, initialBufferSize = 2) {
|
||||
private var transformed = ByteArray(2)
|
||||
|
||||
override val transformEnabled = true
|
||||
override val transformedBuffer: ByteArray
|
||||
get() = transformed
|
||||
|
||||
override fun transformSample(inputLength: Int, flags: Int): Int {
|
||||
if (transformed.size < inputLength) transformed = ByteArray(inputLength)
|
||||
for (index in 0 until inputLength) {
|
||||
transformed[index] = (inputBuffer[index] + 1).toByte()
|
||||
}
|
||||
return inputLength
|
||||
}
|
||||
}
|
||||
|
||||
private class RecordingTrackOutput : TrackOutput {
|
||||
val bytes = ByteArrayOutputStream()
|
||||
var timeUs = C.TIME_UNSET
|
||||
var sampleSize = -1
|
||||
var sampleOffset = -1
|
||||
|
||||
override fun format(format: Format) = Unit
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
val buffer = ByteArray(length)
|
||||
val read = input.read(buffer, 0, length)
|
||||
if (read > 0) bytes.write(buffer, 0, read)
|
||||
return read
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
val buffer = ByteArray(length)
|
||||
data.readBytes(buffer, 0, length)
|
||||
bytes.write(buffer)
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
this.timeUs = timeUs
|
||||
sampleSize = size
|
||||
sampleOffset = offset
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import kotlin.math.pow
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DownmixMatricesTest {
|
||||
|
||||
private fun coeff(matrix: FloatArray, input: Int, output: Int) = matrix[input * 2 + output]
|
||||
|
||||
private fun columnSum(matrix: FloatArray, output: Int): Float {
|
||||
var sum = 0f
|
||||
for (input in 0 until matrix.size / 2) sum += coeff(matrix, input, output)
|
||||
return sum
|
||||
}
|
||||
|
||||
@Test
|
||||
fun centerGainMatchesKodiFormula() {
|
||||
// Kodi: center_mix_level = 10^((-3 + boost) / 20)
|
||||
assertEquals(0.70795f, DownmixMatrices.centerGain(0), 1e-3f)
|
||||
assertEquals(1.0f, DownmixMatrices.centerGain(3), 1e-3f)
|
||||
assertEquals(2.81838f, DownmixMatrices.centerGain(12), 1e-3f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun centerGainClampsBoost() {
|
||||
assertEquals(DownmixMatrices.centerGain(12), DownmixMatrices.centerGain(20), 0f)
|
||||
assertEquals(DownmixMatrices.centerGain(0), DownmixMatrices.centerGain(-5), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fivePointOneLayoutUnnormalized() {
|
||||
val m = DownmixMatrices.stereoCoefficients(6, centerBoostDb = 0, normalize = false)!!
|
||||
val c = DownmixMatrices.centerGain(0)
|
||||
val s = DownmixMatrices.SURROUND_GAIN
|
||||
// FL FR FC LFE BL BR
|
||||
assertEquals(1f, coeff(m, 0, 0), 0f)
|
||||
assertEquals(0f, coeff(m, 0, 1), 0f)
|
||||
assertEquals(0f, coeff(m, 1, 0), 0f)
|
||||
assertEquals(1f, coeff(m, 1, 1), 0f)
|
||||
assertEquals(c, coeff(m, 2, 0), 0f)
|
||||
assertEquals(c, coeff(m, 2, 1), 0f)
|
||||
assertEquals(0f, coeff(m, 3, 0), 0f) // LFE dropped
|
||||
assertEquals(0f, coeff(m, 3, 1), 0f)
|
||||
assertEquals(s, coeff(m, 4, 0), 0f)
|
||||
assertEquals(0f, coeff(m, 4, 1), 0f)
|
||||
assertEquals(0f, coeff(m, 5, 0), 0f)
|
||||
assertEquals(s, coeff(m, 5, 1), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sixPointOneBackCenterMixesHalfToEachSide() {
|
||||
val m = DownmixMatrices.stereoCoefficients(7, centerBoostDb = 0, normalize = false)!!
|
||||
assertEquals(0.5f, coeff(m, 6, 0), 0f)
|
||||
assertEquals(0.5f, coeff(m, 6, 1), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeScalesMaxColumnSumToOne() {
|
||||
for (channels in intArrayOf(6, 8)) {
|
||||
val m = DownmixMatrices.stereoCoefficients(channels, centerBoostDb = 6, normalize = true)!!
|
||||
assertEquals("channels=$channels L", 1f, columnSum(m, 0), 1e-4f)
|
||||
assertEquals("channels=$channels R", 1f, columnSum(m, 1), 1e-4f)
|
||||
// Relative balance is preserved: FC/FL ratio equals the raw center gain.
|
||||
assertEquals(DownmixMatrices.centerGain(6), coeff(m, 2, 0) / coeff(m, 0, 0), 1e-4f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeNeverAmplifies() {
|
||||
for (channels in DownmixMatrices.MIN_DOWNMIX_INPUT_CHANNELS..DownmixMatrices.MAX_DOWNMIX_INPUT_CHANNELS) {
|
||||
val raw = DownmixMatrices.stereoCoefficients(channels, centerBoostDb = 6, normalize = false)!!
|
||||
val normalized = DownmixMatrices.stereoCoefficients(channels, centerBoostDb = 6, normalize = true)!!
|
||||
for (i in raw.indices) {
|
||||
assertTrue("channels=$channels i=$i", normalized[i] <= raw[i] + 1e-6f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun boostRaisesOnlyTheCenterChannel() {
|
||||
val base = DownmixMatrices.stereoCoefficients(6, centerBoostDb = 0, normalize = false)!!
|
||||
val boosted = DownmixMatrices.stereoCoefficients(6, centerBoostDb = 6, normalize = false)!!
|
||||
val expectedRatio = 10f.pow(6f / 20f)
|
||||
assertEquals(expectedRatio, coeff(boosted, 2, 0) / coeff(base, 2, 0), 1e-4f)
|
||||
for (input in intArrayOf(0, 1, 3, 4, 5)) {
|
||||
assertEquals("input=$input L", coeff(base, input, 0), coeff(boosted, input, 0), 0f)
|
||||
assertEquals("input=$input R", coeff(base, input, 1), coeff(boosted, input, 1), 0f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passThroughCountsReturnNull() {
|
||||
for (channels in intArrayOf(1, 2, 9, 12)) {
|
||||
assertNull("channels=$channels", DownmixMatrices.stereoCoefficients(channels, 0, true))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun allCoefficientsNonNegative() {
|
||||
// ChannelMixingMatrix throws on negative coefficients; guard every combination.
|
||||
for (channels in DownmixMatrices.MIN_DOWNMIX_INPUT_CHANNELS..DownmixMatrices.MAX_DOWNMIX_INPUT_CHANNELS) {
|
||||
for (boost in intArrayOf(0, 6, 12)) {
|
||||
for (normalize in booleanArrayOf(true, false)) {
|
||||
val m = DownmixMatrices.stereoCoefficients(channels, boost, normalize)
|
||||
assertNotNull(m)
|
||||
for (value in m!!) {
|
||||
assertTrue("channels=$channels boost=$boost normalize=$normalize", value >= 0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,17 +26,6 @@ class DvBitstreamSanitizerTest {
|
||||
assertEquals(0, buffer.position())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsSuffixSei() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
|
||||
val buffer = bufferOf(vcl, suffixSei)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(vcl, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handles3ByteStartCodes() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02), startCodeLen = 3)
|
||||
@@ -141,16 +130,6 @@ class DvBitstreamSanitizerTest {
|
||||
assertEquals(0xBB.toByte(), buffer.get(1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun worksOnDirectBuffers() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val buffer = directBufferOf(vcl, hdr10PlusSei())
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(vcl, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyBufferIsNoOp() {
|
||||
val buffer = ByteBuffer.allocate(0)
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.app.Activity
|
||||
import android.os.Looper
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewTreeObserver
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ExoPlayerInitializationCleanupTest {
|
||||
|
||||
@Test
|
||||
fun disposeRemovesPartiallyAttachedViewAndLayoutListener() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
activity.setContentView(FrameLayout(activity))
|
||||
val content = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
val container = FrameLayout(activity)
|
||||
content.addView(container)
|
||||
var layoutCallbacks = 0
|
||||
val listener = ViewTreeObserver.OnGlobalLayoutListener { layoutCallbacks++ }
|
||||
content.viewTreeObserver.addOnGlobalLayoutListener(listener)
|
||||
|
||||
val core = ExoPlayerCore(activity)
|
||||
core.setPrivateField("surfaceContainer", container)
|
||||
core.setPrivateField("overlayLayoutListener", listener)
|
||||
|
||||
core.dispose()
|
||||
content.viewTreeObserver.dispatchOnGlobalLayout()
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
|
||||
assertEquals(0, layoutCallbacks)
|
||||
assertNull(container.parent)
|
||||
assertNull(core.getPrivateField("overlayLayoutListener"))
|
||||
}
|
||||
|
||||
private fun Any.setPrivateField(name: String, value: Any?) {
|
||||
javaClass.getDeclaredField(name).apply {
|
||||
isAccessible = true
|
||||
set(this@setPrivateField, value)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Any.getPrivateField(name: String): Any? = javaClass.getDeclaredField(name).apply { isAccessible = true }.get(this)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.os.Looper
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ExoPlayerPluginTest {
|
||||
|
||||
@Test
|
||||
fun fallbackGetStatsCompletesAfterActivityDetach() {
|
||||
val plugin = ExoPlayerPlugin()
|
||||
plugin.javaClass.getDeclaredField("usingMpvFallback").apply {
|
||||
isAccessible = true
|
||||
setBoolean(plugin, true)
|
||||
}
|
||||
val result = RecordingResult()
|
||||
|
||||
plugin.onMethodCall(MethodCall("getStats", null), result)
|
||||
|
||||
var completed = false
|
||||
repeat(100) {
|
||||
shadowOf(Looper.getMainLooper()).idle()
|
||||
if (result.completed.await(10, TimeUnit.MILLISECONDS)) {
|
||||
completed = true
|
||||
return@repeat
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue("fallback getStats never completed", completed)
|
||||
assertEquals(mapOf("playerType" to "mpv"), result.successValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun eventCallbacksKeepTheSharedPlayerEnvelope() {
|
||||
val plugin = ExoPlayerPlugin()
|
||||
val sink = RecordingEventSink()
|
||||
plugin.onListen(null, sink)
|
||||
|
||||
plugin.onEvent("ready", mapOf("position" to 42))
|
||||
|
||||
assertEquals(
|
||||
mapOf(
|
||||
"type" to "event",
|
||||
"name" to "ready",
|
||||
"data" to mapOf("position" to 42)
|
||||
),
|
||||
sink.successValue
|
||||
)
|
||||
}
|
||||
|
||||
private class RecordingResult : MethodChannel.Result {
|
||||
val completed = CountDownLatch(1)
|
||||
var successValue: Any? = null
|
||||
|
||||
override fun success(result: Any?) {
|
||||
successValue = result
|
||||
completed.countDown()
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
|
||||
completed.countDown()
|
||||
}
|
||||
|
||||
override fun notImplemented() {
|
||||
completed.countDown()
|
||||
}
|
||||
}
|
||||
|
||||
private class RecordingEventSink : EventChannel.EventSink {
|
||||
var successValue: Any? = null
|
||||
|
||||
override fun success(event: Any?) {
|
||||
successValue = event
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) = Unit
|
||||
|
||||
override fun endOfStream() = Unit
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.DefaultExtractorInput
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.PositionHolder
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
import java.io.EOFException
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* Extracts the committed fixture (1s 440Hz sine, AAC-LC 48kHz stereo, LATM/LOAS
|
||||
* muxed into MKV as A_MS/ACM tag 0x1602 — the layout Plex produces when
|
||||
* Direct-Streaming HDHomeRun aac_latm audio) and verifies LOAS frames are
|
||||
* unwrapped to raw AAC with a synthesized AudioSpecificConfig.
|
||||
*
|
||||
* Robolectric provides real android.util.* implementations — MatroskaExtractor
|
||||
* stores tracks in a SparseArray, which is a no-op stub on plain JVM.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class LatmMatroskaExtractorTest {
|
||||
|
||||
private class CapturedSample(val timeUs: Long, val flags: Int, val data: ByteArray)
|
||||
|
||||
private class FakeTrackOutput : TrackOutput {
|
||||
val formats = mutableListOf<Format>()
|
||||
val samples = mutableListOf<CapturedSample>()
|
||||
private var buf = ByteArray(64 * 1024)
|
||||
private var bufLen = 0
|
||||
|
||||
override fun format(format: Format) {
|
||||
formats.add(format)
|
||||
}
|
||||
|
||||
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {
|
||||
ensureCapacity(bufLen + length)
|
||||
val read = input.read(buf, bufLen, length)
|
||||
if (read > 0) bufLen += read
|
||||
return read
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
ensureCapacity(bufLen + length)
|
||||
data.readBytes(buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
|
||||
val start = bufLen - offset - size
|
||||
samples.add(CapturedSample(timeUs, flags, buf.copyOfRange(start, start + size)))
|
||||
if (offset == 0) bufLen = 0
|
||||
}
|
||||
|
||||
private fun ensureCapacity(needed: Int) {
|
||||
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private class FakeExtractorOutput : ExtractorOutput {
|
||||
val tracks = mutableMapOf<Int, FakeTrackOutput>()
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput = tracks.getOrPut(id) { FakeTrackOutput() }
|
||||
override fun endTracks() {}
|
||||
override fun seekMap(seekMap: SeekMap) {}
|
||||
}
|
||||
|
||||
private class ByteArrayDataReader(private val data: ByteArray) : DataReader {
|
||||
var position = 0L
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (position >= data.size) return C.RESULT_END_OF_INPUT
|
||||
val toRead = minOf(length, data.size - position.toInt())
|
||||
System.arraycopy(data, position.toInt(), buffer, offset, toRead)
|
||||
position += toRead
|
||||
return toRead
|
||||
}
|
||||
}
|
||||
|
||||
private fun fixtureData(): ByteArray = checkNotNull(javaClass.getResourceAsStream("/latm_loas.mkv")) {
|
||||
"fixture latm_loas.mkv missing from test resources"
|
||||
}.use { it.readBytes() }
|
||||
|
||||
private fun loasFrames(count: Int): List<ByteArray> {
|
||||
val data = fixtureData()
|
||||
val frames = mutableListOf<ByteArray>()
|
||||
var position = 0
|
||||
while (position <= data.size - 3 && frames.size < count) {
|
||||
val isSyncWord = (data[position].toInt() and 0xFF) == 0x56 &&
|
||||
(data[position + 1].toInt() and 0xE0) == 0xE0
|
||||
if (isSyncWord) {
|
||||
val payloadSize = ((data[position + 1].toInt() and 0x1F) shl 8) or
|
||||
(data[position + 2].toInt() and 0xFF)
|
||||
val end = position + 3 + payloadSize
|
||||
if (payloadSize > 0 && end <= data.size) {
|
||||
frames.add(data.copyOfRange(position, end))
|
||||
position = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
position++
|
||||
}
|
||||
check(frames.size == count) { "expected $count LOAS frames, found ${frames.size}" }
|
||||
return frames
|
||||
}
|
||||
|
||||
private fun extractFixture(): FakeExtractorOutput {
|
||||
val data = fixtureData()
|
||||
|
||||
val extractor = LatmMatroskaExtractor(MatroskaExtractor.FLAG_DISABLE_SEEK_FOR_CUES)
|
||||
val output = FakeExtractorOutput()
|
||||
extractor.init(output)
|
||||
|
||||
val reader = ByteArrayDataReader(data)
|
||||
var input = DefaultExtractorInput(reader, 0, data.size.toLong())
|
||||
val seekPosition = PositionHolder()
|
||||
while (true) {
|
||||
when (extractor.read(input, seekPosition)) {
|
||||
Extractor.RESULT_END_OF_INPUT -> return output
|
||||
Extractor.RESULT_SEEK -> {
|
||||
reader.position = seekPosition.position
|
||||
input = DefaultExtractorInput(reader, seekPosition.position, data.size.toLong())
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unwrapsLoasAcmTrackToRawAac() {
|
||||
val output = extractFixture()
|
||||
|
||||
assertEquals(1, output.tracks.size)
|
||||
val track = output.tracks.values.first()
|
||||
|
||||
// No audio/x-unknown format may reach the queue; the LATM-derived AAC
|
||||
// format must carry the AudioSpecificConfig for MediaCodec.
|
||||
assertFalse(track.formats.any { it.sampleMimeType == MimeTypes.AUDIO_UNKNOWN })
|
||||
val format = track.formats.last()
|
||||
assertEquals(MimeTypes.AUDIO_AAC, format.sampleMimeType)
|
||||
assertEquals(48000, format.sampleRate)
|
||||
assertEquals(2, format.channelCount)
|
||||
assertTrue(format.initializationData.isNotEmpty())
|
||||
assertTrue(format.initializationData[0].isNotEmpty())
|
||||
|
||||
// 1s at 48kHz / 1024 samples per AAC frame ≈ 47 frames
|
||||
assertTrue("expected ~47 samples, got ${track.samples.size}", track.samples.size in 40..55)
|
||||
|
||||
// Raw AAC payloads: smaller than the LOAS wrapping, no LOAS syncword,
|
||||
// keyframe-flagged, monotonic timestamps spanning ~1s.
|
||||
var prevTimeUs = Long.MIN_VALUE
|
||||
for (sample in track.samples) {
|
||||
assertTrue(sample.data.isNotEmpty())
|
||||
val isLoasSync = sample.data.size >= 2 &&
|
||||
(sample.data[0].toInt() and 0xFF) == 0x56 &&
|
||||
(sample.data[1].toInt() and 0xE0) == 0xE0
|
||||
assertFalse("sample still LOAS-framed", isLoasSync)
|
||||
assertEquals(C.BUFFER_FLAG_KEY_FRAME, sample.flags and C.BUFFER_FLAG_KEY_FRAME)
|
||||
assertTrue(sample.timeUs >= prevTimeUs)
|
||||
prevTimeUs = sample.timeUs
|
||||
}
|
||||
val spanUs = track.samples.last().timeUs - track.samples.first().timeUs
|
||||
assertTrue("expected ~1s span, got ${spanUs}us", spanUs in 800_000..1_200_000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detectsLoasAcmCodecPrivate() {
|
||||
val loas = byteArrayOf(0x02, 0x16, 0, 0, 0, 0)
|
||||
assertTrue(isLoasAcmTrack("A_MS/ACM", loas))
|
||||
// Wrong tag (PCM), wrong codec, or missing private data must not match
|
||||
assertFalse(isLoasAcmTrack("A_MS/ACM", byteArrayOf(0x01, 0x00, 0, 0)))
|
||||
assertFalse(isLoasAcmTrack("A_AAC", loas))
|
||||
assertFalse(isLoasAcmTrack("A_MS/ACM", null))
|
||||
assertFalse(isLoasAcmTrack("A_MS/ACM", byteArrayOf(0x02)))
|
||||
assertFalse(isLoasAcmTrack(null, loas))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsUnexpectedEndOfInput() {
|
||||
val output = LatmTrackOutput(FakeTrackOutput(), 1)
|
||||
val reader = ByteArrayDataReader(ByteArray(0))
|
||||
|
||||
assertThrows(EOFException::class.java) {
|
||||
output.sampleData(reader, 1, false, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
}
|
||||
assertEquals(
|
||||
C.RESULT_END_OF_INPUT,
|
||||
output.sampleData(reader, 1, true, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesStreamMuxConfigAcrossExtractorSeek() {
|
||||
val frames = loasFrames(2)
|
||||
assertEquals(0, frames[0][3].toInt() and 0x80)
|
||||
assertEquals(0x80, frames[1][3].toInt() and 0x80)
|
||||
|
||||
val delegate = FakeTrackOutput()
|
||||
val output = LatmTrackOutput(delegate, 1)
|
||||
output.format(
|
||||
Format.Builder()
|
||||
.setId("1")
|
||||
.setSampleMimeType(MimeTypes.AUDIO_UNKNOWN)
|
||||
.build()
|
||||
)
|
||||
|
||||
output.sampleData(ParsableByteArray(frames[0]), frames[0].size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(0, C.BUFFER_FLAG_KEY_FRAME, frames[0].size, 0, null)
|
||||
assertEquals(1, delegate.samples.size)
|
||||
|
||||
output.reset()
|
||||
output.sampleData(ParsableByteArray(frames[1]), frames[1].size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(21_000, C.BUFFER_FLAG_KEY_FRAME, frames[1].size, 0, null)
|
||||
assertEquals(2, delegate.samples.size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import com.edde746.plezy.exoplayer.ResumeStallPolicy.Verdict
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ResumeStallPolicyTest {
|
||||
|
||||
// checkWindowMs
|
||||
|
||||
@Test
|
||||
fun windowFloorsAtDefaultForNormalFrameRates() {
|
||||
// 24fps → 4 × 42ms = 168ms, floored to 1000ms
|
||||
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = 24f, detectedFps = -1f, speed = 1f))
|
||||
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = 60f, detectedFps = -1f, speed = 1f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun windowScalesUpForLowFrameRates() {
|
||||
// 2fps → 4 × 500ms = 2000ms
|
||||
assertEquals(2000L, ResumeStallPolicy.checkWindowMs(formatFps = 2f, detectedFps = -1f, speed = 1f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun windowScalesUpForSlowedPlayback() {
|
||||
// 8fps at 0.25× speed → effective 2fps → 2000ms
|
||||
assertEquals(2000L, ResumeStallPolicy.checkWindowMs(formatFps = 8f, detectedFps = -1f, speed = 0.25f))
|
||||
// fast playback shrinks the interval; still floored
|
||||
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = 24f, detectedFps = -1f, speed = 2f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun windowFallsBackThroughDetectedFpsToDefault() {
|
||||
// Format fps unknown (NO_VALUE = -1) → detected fps wins
|
||||
assertEquals(2000L, ResumeStallPolicy.checkWindowMs(formatFps = -1f, detectedFps = 2f, speed = 1f))
|
||||
// Neither known → 24fps assumption → floor
|
||||
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = -1f, detectedFps = -1f, speed = 1f))
|
||||
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = null, detectedFps = null, speed = 1f))
|
||||
}
|
||||
|
||||
// evaluate
|
||||
|
||||
@Test
|
||||
fun advancingFramesAreHealthy() {
|
||||
assertEquals(
|
||||
Verdict.HEALTHY,
|
||||
ResumeStallPolicy.evaluate(
|
||||
baselineFrames = 100,
|
||||
currentFrames = 124,
|
||||
baselinePositionMs = 60_000,
|
||||
currentPositionMs = 61_000,
|
||||
durationMs = 3_600_000,
|
||||
windowMs = 1000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun counterResetCountsAsHealthy() {
|
||||
// Renderer re-enable resets DecoderCounters below the baseline — not a stall.
|
||||
assertEquals(
|
||||
Verdict.HEALTHY,
|
||||
ResumeStallPolicy.evaluate(
|
||||
baselineFrames = 100,
|
||||
currentFrames = 3,
|
||||
baselinePositionMs = 60_000,
|
||||
currentPositionMs = 61_000,
|
||||
durationMs = 3_600_000,
|
||||
windowMs = 1000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stalledClockRequestsRecheck() {
|
||||
// Frames frozen but the position isn't advancing either: generic buffering
|
||||
// stall, not the decoder freeze this watchdog targets.
|
||||
assertEquals(
|
||||
Verdict.RECHECK,
|
||||
ResumeStallPolicy.evaluate(
|
||||
baselineFrames = 100,
|
||||
currentFrames = 100,
|
||||
baselinePositionMs = 60_000,
|
||||
currentPositionMs = 60_200,
|
||||
durationMs = 3_600_000,
|
||||
windowMs = 1000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nearEndOfStreamIsSkipped() {
|
||||
// Video track ending before audio is legitimate near EOF.
|
||||
assertEquals(
|
||||
Verdict.SKIP_NEAR_EOF,
|
||||
ResumeStallPolicy.evaluate(
|
||||
baselineFrames = 100,
|
||||
currentFrames = 100,
|
||||
baselinePositionMs = 3_598_000,
|
||||
currentPositionMs = 3_599_000,
|
||||
durationMs = 3_600_000,
|
||||
windowMs = 1000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun frozenFramesWithAdvancingClockMidFileIsStalled() {
|
||||
assertEquals(
|
||||
Verdict.STALLED,
|
||||
ResumeStallPolicy.evaluate(
|
||||
baselineFrames = 100,
|
||||
currentFrames = 100,
|
||||
baselinePositionMs = 60_000,
|
||||
currentPositionMs = 61_000,
|
||||
durationMs = 3_600_000,
|
||||
windowMs = 1000
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownDurationSkipsEofGuardAndStalls() {
|
||||
// Live/unknown duration (C.TIME_UNSET) must not suppress detection.
|
||||
assertEquals(
|
||||
Verdict.STALLED,
|
||||
ResumeStallPolicy.evaluate(
|
||||
baselineFrames = 100,
|
||||
currentFrames = 100,
|
||||
baselinePositionMs = 60_000,
|
||||
currentPositionMs = 61_000,
|
||||
durationMs = C.TIME_UNSET,
|
||||
windowMs = 1000
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.text.Cue
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Test
|
||||
|
||||
class SubtitleCueLayoutTest {
|
||||
|
||||
@Test
|
||||
fun concurrentUnpositionedCuesStackFromBottom() {
|
||||
val first = Cue.Builder().setText("first").build()
|
||||
val second = Cue.Builder().setText("second").build()
|
||||
|
||||
val laidOut = SubtitleCueLayout.layout(listOf(first, second), positionPercent = 100, fontSize = 36f)
|
||||
|
||||
assertEquals(Cue.LINE_TYPE_NUMBER, laidOut[0].lineType)
|
||||
assertEquals(-2f, laidOut[0].line)
|
||||
assertEquals(Cue.ANCHOR_TYPE_END, laidOut[0].lineAnchor)
|
||||
assertEquals(-1f, laidOut[1].line)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun userPositionPreservesStackSpacing() {
|
||||
val first = Cue.Builder().setText("first").build()
|
||||
val second = Cue.Builder().setText("second").build()
|
||||
|
||||
val laidOut = SubtitleCueLayout.layout(listOf(first, second), positionPercent = 50, fontSize = 36f)
|
||||
|
||||
assertEquals(Cue.LINE_TYPE_FRACTION, laidOut[0].lineType)
|
||||
assertEquals(0.44f, laidOut[0].line, 0.0001f)
|
||||
assertEquals(0.5f, laidOut[1].line, 0.0001f)
|
||||
assertEquals(Cue.ANCHOR_TYPE_END, laidOut[0].lineAnchor)
|
||||
assertEquals(Cue.ANCHOR_TYPE_END, laidOut[1].lineAnchor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitCuePositionIsNotOverridden() {
|
||||
val positioned = Cue.Builder()
|
||||
.setText("positioned")
|
||||
.setLine(0.25f, Cue.LINE_TYPE_FRACTION)
|
||||
.setLineAnchor(Cue.ANCHOR_TYPE_START)
|
||||
.build()
|
||||
|
||||
val laidOut = SubtitleCueLayout.layout(listOf(positioned), positionPercent = 50, fontSize = 36f)
|
||||
|
||||
assertSame(positioned, laidOut.single())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.ui.AspectRatioFrameLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SubtitleViewLayoutTest {
|
||||
|
||||
@Test
|
||||
fun letterboxUsesVisibleVideoRectForTextAndBitmapSubtitles() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
|
||||
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coverKeepsTextOnScreenAndBitmapSubtitlesFullyVisible() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
assertAspectCloseTo16By9(bitmap!!)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualZoomKeepsBitmapSubtitlesFullyVisible() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, zoomScale = 1.5f)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, zoomScale = 1.5f)
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
assertAspectCloseTo16By9(bitmap!!)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stretchDoesNotStretchBitmapSubtitlesToScreenAspect() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
assertAspectCloseTo16By9(bitmap!!)
|
||||
}
|
||||
|
||||
private fun textDimensions(
|
||||
resizeMode: Int,
|
||||
zoomScale: Float = 1f
|
||||
): SubtitleViewDimensions? = SubtitleViewLayout.textDimensions(
|
||||
containerWidth = 2424,
|
||||
containerHeight = 1080,
|
||||
videoWidth = 1920,
|
||||
videoHeight = 1080,
|
||||
pixelRatio = 1f,
|
||||
resizeMode = resizeMode,
|
||||
zoomScale = zoomScale
|
||||
)
|
||||
|
||||
private fun bitmapDimensions(
|
||||
resizeMode: Int,
|
||||
zoomScale: Float = 1f
|
||||
): SubtitleViewDimensions? = SubtitleViewLayout.bitmapDimensions(
|
||||
containerWidth = 2424,
|
||||
containerHeight = 1080,
|
||||
videoWidth = 1920,
|
||||
videoHeight = 1080,
|
||||
pixelRatio = 1f,
|
||||
resizeMode = resizeMode,
|
||||
zoomScale = zoomScale
|
||||
)
|
||||
|
||||
private fun assertAspectCloseTo16By9(dimensions: SubtitleViewDimensions) {
|
||||
val aspect = dimensions.width.toDouble() / dimensions.height
|
||||
assertEquals(16.0 / 9.0, aspect, 0.001)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import dev.jdtech.mpv.EndFileReason
|
||||
import dev.jdtech.mpv.LogLevel
|
||||
import dev.jdtech.mpv.LogMessage
|
||||
import dev.jdtech.mpv.MpvEvent
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class MpvPlayerPluginTest {
|
||||
|
||||
@Test
|
||||
fun commandWithoutCoreReportsNotInitialized() {
|
||||
val result = RecordingResult()
|
||||
|
||||
MpvPlayerPlugin().onMethodCall(
|
||||
MethodCall("command", mapOf("args" to listOf("seek", "1", "absolute"))),
|
||||
result
|
||||
)
|
||||
|
||||
assertEquals("NOT_INITIALIZED", result.errorCode)
|
||||
assertNull(result.successValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disposeCompletesEveryPendingInitialization() {
|
||||
val plugin = MpvPlayerPlugin()
|
||||
val first = RecordingResult()
|
||||
val second = RecordingResult()
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val pending = plugin.javaClass.getDeclaredField("pendingInitResults").apply {
|
||||
isAccessible = true
|
||||
}.get(plugin) as MutableList<MethodChannel.Result>
|
||||
pending += first
|
||||
pending += second
|
||||
plugin.javaClass.getDeclaredField("isInitializing").apply {
|
||||
isAccessible = true
|
||||
setBoolean(plugin, true)
|
||||
}
|
||||
val dispose = RecordingResult()
|
||||
|
||||
plugin.onMethodCall(MethodCall("dispose", null), dispose)
|
||||
|
||||
assertEquals(false, first.successValue)
|
||||
assertEquals(false, second.successValue)
|
||||
assertNull(dispose.successValue)
|
||||
assertTrue(first.completed)
|
||||
assertTrue(second.completed)
|
||||
assertTrue(dispose.completed)
|
||||
assertEquals(0, pending.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setLogLevelReportsUnsupported() {
|
||||
val result = RecordingResult()
|
||||
|
||||
MpvPlayerPlugin().onMethodCall(
|
||||
MethodCall("setLogLevel", mapOf("level" to "warn")),
|
||||
result
|
||||
)
|
||||
|
||||
assertEquals("UNSUPPORTED", result.errorCode)
|
||||
assertNull(result.successValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun endFileDiagnosticsPreserveReasonIdAndExposeDependencyErrorLog() {
|
||||
val diagnostics = MpvEndFileDiagnostics()
|
||||
diagnostics.onStartFile()
|
||||
diagnostics.onLogMessage(LogMessage("ffmpeg", LogLevel.Error, "Invalid data found when processing input"))
|
||||
|
||||
assertEquals(
|
||||
mapOf(
|
||||
"reason" to 4,
|
||||
"message" to "Invalid data found when processing input"
|
||||
),
|
||||
diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error))
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun endFileDiagnosticsDoNotAttachStaleOrInventedDetails() {
|
||||
val diagnostics = MpvEndFileDiagnostics()
|
||||
diagnostics.onLogMessage(LogMessage("ffmpeg", LogLevel.Error, "old failure"))
|
||||
diagnostics.onStartFile()
|
||||
|
||||
assertEquals(mapOf("reason" to 0), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Eof)))
|
||||
assertEquals(mapOf("reason" to 4), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error)))
|
||||
assertNull(diagnostics.onEndFile(MpvEvent.EndFile(null)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun endFileEventChannelPayloadKeepsExistingEnvelopeAndAddsMessage() {
|
||||
val sink = RecordingEventSink()
|
||||
val plugin = MpvPlayerPlugin()
|
||||
plugin.onListen(null, sink)
|
||||
|
||||
plugin.onEvent(
|
||||
"end-file",
|
||||
mapOf(
|
||||
"reason" to 4,
|
||||
"message" to "Failed to open stream"
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
mapOf(
|
||||
"type" to "event",
|
||||
"name" to "end-file",
|
||||
"data" to mapOf(
|
||||
"reason" to 4,
|
||||
"message" to "Failed to open stream"
|
||||
)
|
||||
),
|
||||
sink.successValue
|
||||
)
|
||||
}
|
||||
|
||||
private class RecordingResult : MethodChannel.Result {
|
||||
var successValue: Any? = null
|
||||
var errorCode: String? = null
|
||||
var completed: Boolean = false
|
||||
|
||||
override fun success(result: Any?) {
|
||||
completed = true
|
||||
successValue = result
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
|
||||
completed = true
|
||||
this.errorCode = errorCode
|
||||
}
|
||||
|
||||
override fun notImplemented() = Unit
|
||||
}
|
||||
|
||||
private class RecordingEventSink : EventChannel.EventSink {
|
||||
var successValue: Any? = null
|
||||
|
||||
override fun success(event: Any?) {
|
||||
successValue = event
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) = Unit
|
||||
|
||||
override fun endOfStream() = Unit
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.MediaCodecInfoBuilder
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [25, 28])
|
||||
class MediaCodecQueryTest {
|
||||
|
||||
@Test
|
||||
fun preApi29CodecQueryDoesNotInvokeApi29HardwareFlag() {
|
||||
val codecInfo = MediaCodecInfoBuilder.newBuilder()
|
||||
.setName("OMX.qcom.video.decoder.avc")
|
||||
.setIsHardwareAccelerated(false)
|
||||
.build()
|
||||
|
||||
assertTrue(MediaCodecQuery.isHardwareAccelerated(codecInfo))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recognizesKnownPlatformAndFfmpegSoftwareCodecNames() {
|
||||
listOf(
|
||||
"OMX.google.h264.decoder",
|
||||
"OMX.FFMPEG.VIDEO.DECODER",
|
||||
"c2.android.avc.decoder",
|
||||
"c2.google.av1.decoder",
|
||||
"c2.ffmpeg.vp9.decoder",
|
||||
"vendor.video.sw.decoder"
|
||||
).forEach { name ->
|
||||
assertTrue("expected software codec: $name", MediaCodecQuery.isSoftwareCodecName(name))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun doesNotMisclassifyVendorHardwareCodecNames() {
|
||||
listOf(
|
||||
"OMX.qcom.video.decoder.avc",
|
||||
"OMX.MTK.VIDEO.DECODER.HEVC",
|
||||
"c2.qti.avc.decoder",
|
||||
"c2.exynos.hevc.decoder"
|
||||
).forEach { name ->
|
||||
assertFalse("expected hardware codec: $name", MediaCodecQuery.isSoftwareCodecName(name))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun api29RequiresPlatformHardwareFlagAndNonSoftwareComponentName() {
|
||||
assertFalse(MediaCodecQuery.isHardwareAccelerated(29, true, "c2.ffmpeg.aac.decoder"))
|
||||
assertFalse(MediaCodecQuery.isHardwareAccelerated(29, false, "c2.qti.avc.decoder"))
|
||||
assertTrue(MediaCodecQuery.isHardwareAccelerated(29, true, "c2.qti.avc.decoder"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preApi29RetainsNameBasedFallback() {
|
||||
assertFalse(MediaCodecQuery.isHardwareAccelerated(28, true, "OMX.google.h264.decoder"))
|
||||
assertTrue(MediaCodecQuery.isHardwareAccelerated(28, false, "OMX.qcom.video.decoder.avc"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class MpvContentUriResolverTest {
|
||||
|
||||
@Test
|
||||
fun contentDescriptorOpensOffMainAndCompletesOnMain() {
|
||||
val mainLooper = Looper.getMainLooper()
|
||||
val openedOnMain = AtomicBoolean(true)
|
||||
val completedOnMain = AtomicBoolean(false)
|
||||
val completed = CountDownLatch(1)
|
||||
|
||||
MpvContentUriResolver.resolve(
|
||||
uriString = "content://downloads/video.mkv",
|
||||
mainHandler = Handler(mainLooper),
|
||||
opener = {
|
||||
openedOnMain.set(Looper.myLooper() == mainLooper)
|
||||
null
|
||||
},
|
||||
onResolved = {
|
||||
completedOnMain.set(Looper.myLooper() == mainLooper)
|
||||
completed.countDown()
|
||||
}
|
||||
)
|
||||
|
||||
var didComplete = false
|
||||
repeat(100) {
|
||||
shadowOf(mainLooper).idle()
|
||||
if (completed.await(10, TimeUnit.MILLISECONDS)) {
|
||||
didComplete = true
|
||||
return@repeat
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue("content URI resolution never completed", didComplete)
|
||||
assertFalse("content descriptor opened on the main thread", openedOnMain.get())
|
||||
assertTrue("resolved URI callback did not return on the main thread", completedOnMain.get())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.app.Activity
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class PlayerSurfaceHostTest {
|
||||
|
||||
@Test
|
||||
fun scaffoldCreatesFullScreenBlackVideoLayerBehindFlutterContent() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
|
||||
activity.setContentView(FrameLayout(activity))
|
||||
val callback = object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) = Unit
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) = Unit
|
||||
}
|
||||
|
||||
val container = PlayerSurfaceHost.createContainer(activity, clipChildren = true)
|
||||
val surface = PlayerSurfaceHost.createVideoSurface(activity, callback)
|
||||
container.addView(surface)
|
||||
val content = PlayerSurfaceHost.attachToContent(activity, container)
|
||||
|
||||
assertSame(content, container.parent)
|
||||
assertEquals(0, content.indexOfChild(container))
|
||||
assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, container.layoutParams.width)
|
||||
assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, container.layoutParams.height)
|
||||
assertEquals(Color.BLACK, (container.background as ColorDrawable).color)
|
||||
assertTrue(container.clipChildren)
|
||||
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, surface.layoutParams.width)
|
||||
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, surface.layoutParams.height)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -2,28 +2,6 @@ allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
if (providers.gradleProperty("localAssCore").isPresent) {
|
||||
// Opt-in A/B of a locally built libass native core: build it in the
|
||||
// libass-android fork with `./gradlew :lib_ass:publishToMavenLocal
|
||||
// -PVERSION_NAME=0.4.0-local`, then build this app with -PlocalAssCore.
|
||||
mavenLocal()
|
||||
} else {
|
||||
// Production libass native core: the -O3/NEON/asm AAR published on
|
||||
// the edde746/libass-android fork's releases (the upstream Maven
|
||||
// artifact io.github.peerless2012:ass ships un-optimized natives —
|
||||
// see the fork's pinned libass-cmake fix). Resolved as
|
||||
// <tag>/ass-<tag>.aar with no metadata probing.
|
||||
exclusiveContent {
|
||||
forRepository {
|
||||
ivy {
|
||||
url = uri("https://github.com/edde746/libass-android/releases/download")
|
||||
patternLayout { artifact("[revision]/[artifact]-[revision].[ext]") }
|
||||
metadataSources { artifact() }
|
||||
}
|
||||
}
|
||||
filter { includeModule("io.github.peerless2012", "ass") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
# All bundled dependencies use AndroidX. Jetifier also cannot process modern
|
||||
# JVM-only test artifacts when Android lint builds dependency models.
|
||||
android.enableJetifier=false
|
||||
# This builtInKotlin flag was added automatically by Flutter migrator
|
||||
android.builtInKotlin=false
|
||||
# This newDsl flag was added automatically by Flutter migrator
|
||||
|
||||
BIN
Binary file not shown.
+160
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn ( ) {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die ( ) {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
esac
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
|
||||
function splitJvmOpts() {
|
||||
JVM_OPTS=("$@")
|
||||
}
|
||||
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
|
||||
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
|
||||
|
||||
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windowz variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
if "%@eval[2+2]" == "4" goto 4NT_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
goto execute
|
||||
|
||||
:4NT_args
|
||||
@rem Get arguments from the 4NT Shell from JP Software
|
||||
set CMD_LINE_ARGS=%$
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -1,7 +1,5 @@
|
||||
// libass ASS subtitle rendering: Kotlin/JNI bindings + Media3 integration
|
||||
// (extractor, parsers, AssHandler, GL atlas overlay). The native libass core
|
||||
// (libass.so + prefab headers) comes from the Maven artifact
|
||||
// io.github.peerless2012:ass; this module compiles its JNI against it.
|
||||
// Static-linking the native core here avoids shipping a separate libass.so with
|
||||
// different merge rules from the app.
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
@@ -20,34 +18,19 @@ android {
|
||||
defaultConfig {
|
||||
minSdk = 21
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
if (project.hasProperty("localAssCore")) {
|
||||
// The locally published A/B core only ships device ABIs (x86 would need
|
||||
// nasm on the host); match it so prefab resolution doesn't fail.
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
|
||||
}
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
// libass.so in the prefab AAR is built against c++_shared (abi.json: stl=c++_shared);
|
||||
// prefab validates consumer STL compatibility.
|
||||
arguments += listOf("-DANDROID_STL=c++_shared")
|
||||
// HarfBuzz pulls in C++, so the JNI library must use the shared STL that
|
||||
// the app already pins through libmpv.
|
||||
// A shared cache keeps per-ABI CMake runs from redownloading libass.
|
||||
arguments += listOf(
|
||||
"-DANDROID_STL=c++_shared",
|
||||
"-DLIBASS_CACHE_DIR=${layout.buildDirectory.get().asFile}/libass-prebuilt"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
prefab = true
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// libass.so is a prefab IMPORTED target (linked, not owned) — the app packages
|
||||
// it from the io.github.peerless2012:ass AAR; don't duplicate it here.
|
||||
excludes.add("**/libass.so")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
@@ -66,13 +49,6 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// compileOnly: prefab headers + link-time libass.so come from the AAR; runtime
|
||||
// packaging of libass.so is the app's implementation dependency.
|
||||
// -PlocalAssCore swaps in a mavenLocal()-published core for A/B tests (must
|
||||
// match the app module's version so one libass.so is linked and packaged).
|
||||
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
|
||||
compileOnly("io.github.peerless2012:ass:$assCoreVersion@aar")
|
||||
|
||||
implementation("androidx.annotation:annotation:1.9.1")
|
||||
implementation("androidx.annotation:annotation-experimental:1.5.1")
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# Constructed from JNI via FindClass/NewObject (AssKt.c).
|
||||
-keep class com.edde746.plezy.libass.AssAtlasFrame { *; }
|
||||
# JNI exports bind by name (Java_com_edde746_plezy_libass_*); keep the names stable.
|
||||
-keepclasseswithmembernames class com.edde746.plezy.libass.* {
|
||||
native <methods>;
|
||||
|
||||
+440
-116
@@ -1,10 +1,15 @@
|
||||
// JNI bindings for libass. Exports use standard Java_<package>_<Class>_<method>
|
||||
// naming so no RegisterNatives/JNI_OnLoad registration is needed.
|
||||
#include <EGL/egl.h>
|
||||
#include <EGL/eglext.h>
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <limits.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
|
||||
static inline long long nowMs(void) {
|
||||
@@ -61,7 +66,13 @@ JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssDeinit(JNIEnv*
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackInit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
return (jlong)ass_new_track((ASS_Library*)ass);
|
||||
ASS_Track* track = ass_new_track((ASS_Library*)ass);
|
||||
if (track != NULL) {
|
||||
if (ass_track_set_feature(track, ASS_FEATURE_FAST_BLUR, 1) != 0) {
|
||||
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "ASS_FEATURE_FAST_BLUR unavailable in libass build");
|
||||
}
|
||||
}
|
||||
return (jlong)track;
|
||||
}
|
||||
|
||||
// Shared body of readBuffer/readChunk: pins the byte array and feeds libass.
|
||||
@@ -132,10 +143,54 @@ JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNex
|
||||
|
||||
// --- AssRender ---
|
||||
|
||||
// The fork's fontconfig build has no Android font search defaults. A tiny
|
||||
// process-local config lets /system fonts resolve without adding Context/JNI plumbing.
|
||||
static char* ensureFontsConf(void) {
|
||||
const char* tmp = getenv("TMPDIR");
|
||||
if (tmp == NULL || tmp[0] == '\0') tmp = "/data/local/tmp";
|
||||
|
||||
char cacheDir[PATH_MAX];
|
||||
snprintf(cacheDir, sizeof(cacheDir), "%s/fontconfig", tmp);
|
||||
mkdir(cacheDir, 0700);
|
||||
|
||||
char* confPath = (char*)malloc(PATH_MAX);
|
||||
if (confPath == NULL) return NULL;
|
||||
snprintf(confPath, PATH_MAX, "%s/fonts.conf", tmp);
|
||||
|
||||
FILE* f = fopen(confPath, "w");
|
||||
if (f == NULL) {
|
||||
free(confPath);
|
||||
return NULL;
|
||||
}
|
||||
fprintf(
|
||||
f,
|
||||
"<?xml version=\"1.0\"?>\n"
|
||||
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n"
|
||||
"<fontconfig>\n"
|
||||
" <dir>/system/fonts</dir>\n"
|
||||
" <dir>/system/font</dir>\n"
|
||||
" <dir>/product/fonts</dir>\n"
|
||||
" <dir>/data/fonts</dir>\n"
|
||||
" <cachedir>%s</cachedir>\n"
|
||||
"</fontconfig>\n",
|
||||
cacheDir);
|
||||
fclose(f);
|
||||
return confPath;
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderInit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
ASS_Renderer* assRenderer = ass_renderer_init((ASS_Library*)ass);
|
||||
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, NULL, 1);
|
||||
if (assRenderer == NULL) return 0;
|
||||
unsigned threads = ass_set_threads(assRenderer, 0);
|
||||
if (threads == 0) {
|
||||
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "libass threading unavailable in native build");
|
||||
} else {
|
||||
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "libass rendering threads enabled: %u", threads);
|
||||
}
|
||||
char* fontsConf = ensureFontsConf();
|
||||
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, fontsConf, 1);
|
||||
free(fontsConf);
|
||||
return (jlong)assRenderer;
|
||||
}
|
||||
|
||||
@@ -182,178 +237,312 @@ Java_com_edde746_plezy_libass_AssRender_nativeAssRenderDeinit(JNIEnv* env, jclas
|
||||
}
|
||||
}
|
||||
|
||||
// (image, original-list index) pair so packing can run in height-sorted order
|
||||
// while slots stay keyed by list position (= blend order) for pass 2.
|
||||
typedef struct {
|
||||
ASS_Image* img;
|
||||
int idx;
|
||||
} PackItem;
|
||||
// Hard cap on atlas pages (see the packing comment below). 4 pages of a GL-max
|
||||
// texture is far above the worst real frame measured (a 4K-rendered full-screen
|
||||
// typeset letter needs 3); beyond it tiles are dropped and counted in truncated.
|
||||
#define MAX_ATLAS_PAGES 4
|
||||
|
||||
static int comparePackItemsByHeightDesc(const void* a, const void* b) {
|
||||
const PackItem* ia = (const PackItem*)a;
|
||||
const PackItem* ib = (const PackItem*)b;
|
||||
return ib->img->h - ia->img->h;
|
||||
// A tile is a <= atlasMaxW x atlasMaxH sub-rect of an ASS_Image. A single image
|
||||
// can exceed one atlas page only when the render frame is larger than a page
|
||||
// (>4K, or a GPU whose max texture is below the frame) — multi-page can't split
|
||||
// one image across pages (a quad samples one texture), so tiling does, keeping
|
||||
// the never-drop guarantee. (#1436 itself was atlas-AREA overflow, fixed by the
|
||||
// multi-page pack below, not oversized single images.) Tiles are built in list
|
||||
// order (= libass blend/painter order, preserved for emission); the single-page
|
||||
// pack runs height-sorted via a separate key array so emission order is untouched.
|
||||
typedef struct {
|
||||
ASS_Image* img; // source image (for bitmap/stride/color/dst_x/dst_y)
|
||||
int ox, oy; // tile offset within the source bitmap
|
||||
int tw, th; // tile size (<= atlasMaxW x atlasMaxH)
|
||||
int page; // atlas page the tile is packed into; -1 if dropped for capacity
|
||||
int sx, sy; // packed slot within the page; valid when page >= 0
|
||||
} PackTile;
|
||||
|
||||
typedef struct {
|
||||
int th; // tile height (the sort key)
|
||||
int idx; // index into the build-order tiles[] array
|
||||
} TileSortKey;
|
||||
|
||||
static int compareTileKeysByHeightDesc(const void* a, const void* b) {
|
||||
return ((const TileSortKey*)b)->th - ((const TileSortKey*)a)->th;
|
||||
}
|
||||
|
||||
static int imageListHasOutput(ASS_Image* image) {
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Throttle for truncation warnings (shared across renderers; logging only).
|
||||
static int truncationLogCounter = 0;
|
||||
|
||||
// Frame metadata crosses to Kotlin through a fixed-layout int[] header (filled here,
|
||||
// read + turned into an AssAtlasFrame by AssRender.kt) instead of constructing the
|
||||
// object in JNI. A NewObject on an overloaded constructor is fragile under R8: the
|
||||
// minified release build stripped/rewrote the (I[I[IIIIZ)V ctor the lookup bound by,
|
||||
// crashing with NoSuchMethodError (#1436 follow-up). Binding a native method by name
|
||||
// + populating a primitive array has no such reflective dependency. Layout:
|
||||
// [0]=atlasWidth [1]=quadCount [2]=changed [3]=truncated [4]=requiredPages
|
||||
// [5]=hasOutput [6]=pageCount
|
||||
// [7 .. 7+MAX-1] = pageHeights[pageCount]
|
||||
// [7+MAX .. 7+2*MAX-1] = pageQuadCounts[pageCount]
|
||||
#define ASS_HEADER_INTS (7 + 2 * MAX_ATLAS_PAGES)
|
||||
|
||||
static jint writeAtlasHeader(
|
||||
JNIEnv* env, jintArray headerBuf, int atlasWidth, int quadCount, int changed, int truncated, int requiredPages,
|
||||
int hasOutput, int pageCount, const int* pageHeights, const int* pageQuads) {
|
||||
int hdr[ASS_HEADER_INTS];
|
||||
memset(hdr, 0, sizeof(hdr));
|
||||
hdr[0] = atlasWidth;
|
||||
hdr[1] = quadCount;
|
||||
hdr[2] = changed;
|
||||
hdr[3] = truncated;
|
||||
hdr[4] = requiredPages;
|
||||
hdr[5] = hasOutput;
|
||||
hdr[6] = pageCount;
|
||||
for (int i = 0; i < pageCount && i < MAX_ATLAS_PAGES; i++) {
|
||||
hdr[7 + i] = pageHeights ? pageHeights[i] : 0;
|
||||
hdr[7 + MAX_ATLAS_PAGES + i] = pageQuads ? pageQuads[i] : 0;
|
||||
}
|
||||
(*env)->SetIntArrayRegion(env, headerBuf, 0, ASS_HEADER_INTS, hdr);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Renders a frame into the provided atlas + vertex direct ByteBuffers.
|
||||
//
|
||||
// - atlasBuf holds packed ALPHA_8 pixels with row stride atlasMaxW. Only the first
|
||||
// atlasHeight rows are written; the caller uploads that region to a texture
|
||||
// allocated once at atlasMaxW × atlasMaxH.
|
||||
// - atlasBuf holds one or more vertically-stacked ALPHA_8 *pages*, each atlasMaxW ×
|
||||
// atlasMaxH (row stride atlasMaxW); page p starts at byte offset p*atlasMaxW*atlasMaxH.
|
||||
// The buffer's capacity bounds how many pages this render may fill; AssAtlasFrame
|
||||
// reports pageHeights (rows worth uploading per page) and requiredPages.
|
||||
// - vertexBuf holds a per-quad vertex stream (6 vertices × (2 pos + 2 uv + 4 color)
|
||||
// floats = 48 floats = 192 bytes per quad). Must match BYTES_PER_QUAD/VERTEX in
|
||||
// AssSubtitleAtlasPipeline.kt. Ready for a single glDrawArrays(GL_TRIANGLES, 0, N * 6).
|
||||
// - UVs are normalized against atlasMaxW × atlasMaxH (the allocated texture dims),
|
||||
// not the packed region, so the texture never needs reallocation.
|
||||
// - Images are packed in height-sorted rows (minimizes packed height) but vertices
|
||||
// are emitted in original list order — the list order is libass's painter order.
|
||||
// AssSubtitleAtlasPipeline.kt. UVs are page-local, normalized against atlasMaxW ×
|
||||
// atlasMaxH (the per-page texture dims).
|
||||
// - The common case packs everything into a single height-sorted page (minimizes
|
||||
// packed height, byte-identical to the prior single-page packer). When that
|
||||
// overflows (a 4K full-screen sign can exceed one GL-max texture), the packer
|
||||
// spills into additional pages in list order: page assignment is monotonic in
|
||||
// libass's painter order, so each page's quads are one contiguous run in the
|
||||
// vertex stream and drawing the pages in turn reproduces the blend order.
|
||||
// - Vertices are always emitted in original list order (= libass's painter order).
|
||||
//
|
||||
// Never fails on content size: images that don't fit the remaining atlas/vertex
|
||||
// capacity are dropped and counted in AssAtlasFrame.truncated, so a heavy frame
|
||||
// degrades instead of going stale. Returns NULL only for missing buffers/handles.
|
||||
// On changed == 0, returns (0, 0, 0, changed, 0) without touching the buffers —
|
||||
// caller reuses the atlas texture already on the GPU.
|
||||
JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFrameAtlas(
|
||||
// Never fails on content size: when the frame needs more pages than the buffer holds
|
||||
// (requiredPages > pageHeights.size) the caller grows the buffer and re-renders; any
|
||||
// genuinely undrawable tiles (past MAX_ATLAS_PAGES / the vertex budget) are dropped
|
||||
// and counted in truncated.
|
||||
//
|
||||
// Returns 0 for missing buffers/handles (the caller maps that to a null frame); 1 when
|
||||
// the header was written. On changed == 0 the header carries (atlasWidth=0, quadCount=0,
|
||||
// changed, hasOutput) without touching the atlas/vertex buffers — hasOutput lets Kotlin
|
||||
// distinguish "reuse the previous atlas" from "blank, clear the GL surface."
|
||||
JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFrameAtlas(
|
||||
JNIEnv* env, jclass clazz, jlong render, jlong track, jlong time, jobject atlasBuf, jint atlasMaxW, jint atlasMaxH,
|
||||
jobject vertexBuf) {
|
||||
if (!render || !track || !atlasBuf || !vertexBuf || atlasMaxW <= 0 || atlasMaxH <= 0) return NULL;
|
||||
|
||||
jclass atlasFrameClass = (*env)->FindClass(env, "com/edde746/plezy/libass/AssAtlasFrame");
|
||||
if (!atlasFrameClass) return NULL;
|
||||
jmethodID ctor = (*env)->GetMethodID(env, atlasFrameClass, "<init>", "(IIIII)V");
|
||||
if (!ctor) return NULL;
|
||||
jobject vertexBuf, jintArray headerBuf) {
|
||||
if (!render || !track || !atlasBuf || !vertexBuf || !headerBuf || atlasMaxW <= 0 || atlasMaxH <= 0) return 0;
|
||||
|
||||
const long long t0 = nowMs();
|
||||
int changed;
|
||||
ASS_Image* image = ass_render_frame((ASS_Renderer*)render, (ASS_Track*)track, time, &changed);
|
||||
const long long tAss = nowMs();
|
||||
|
||||
if (changed == 0 || image == NULL) {
|
||||
if (changed == 0) {
|
||||
const int hasOutput = imageListHasOutput(image) ? 1 : 0;
|
||||
if (tAss - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, hasOutput=%d)", (long long)time,
|
||||
tAss - t0, changed, hasOutput);
|
||||
}
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, hasOutput, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
if (image == NULL) {
|
||||
if (tAss - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, no output)", (long long)time,
|
||||
tAss - t0, changed);
|
||||
}
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
uint8_t* atlasPixels = (uint8_t*)(*env)->GetDirectBufferAddress(env, atlasBuf);
|
||||
jlong atlasCap = (*env)->GetDirectBufferCapacity(env, atlasBuf);
|
||||
float* vertices = (float*)(*env)->GetDirectBufferAddress(env, vertexBuf);
|
||||
jlong vertexCap = (*env)->GetDirectBufferCapacity(env, vertexBuf);
|
||||
if (!atlasPixels || !vertices) return NULL;
|
||||
if (!atlasPixels || !vertices) return 0;
|
||||
if ((jlong)atlasMaxW * atlasMaxH > atlasCap) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR, LOG_TAG, "atlas buffer smaller than %dx%d (capacity %lld bytes)", atlasMaxW, atlasMaxH,
|
||||
(long long)atlasCap);
|
||||
return NULL;
|
||||
return 0;
|
||||
}
|
||||
// 48 floats per quad × 4 bytes = 192 bytes/quad
|
||||
const int maxQuads = (int)(vertexCap / 192);
|
||||
const size_t pageBytes = (size_t)atlasMaxW * atlasMaxH;
|
||||
int providedPages = (int)(atlasCap / (jlong)pageBytes);
|
||||
if (providedPages < 1) return 0; // one page is guaranteed above; keep the page math safe
|
||||
if (providedPages > MAX_ATLAS_PAGES) providedPages = MAX_ATLAS_PAGES;
|
||||
|
||||
// Split every image into <= atlasMaxW x atlasMaxH tiles, then pack the tiles.
|
||||
// tiles[] stays in list order (= blend/painter order for emission); keys[] is
|
||||
// sorted by height for the single-page pack so it produces tight rows.
|
||||
int total = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) total++;
|
||||
}
|
||||
if (total == 0) {
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
|
||||
}
|
||||
|
||||
// Pass 1: assign packing slots in height-sorted order so mixed-size frames pack
|
||||
// tight rows. slotX/slotY are keyed by the image's position in the original
|
||||
// list; -1 marks images dropped for capacity.
|
||||
PackItem* items = (PackItem*)malloc(sizeof(PackItem) * (size_t)total);
|
||||
int* slotX = (int*)malloc(sizeof(int) * (size_t)total);
|
||||
int* slotY = (int*)malloc(sizeof(int) * (size_t)total);
|
||||
if (!items || !slotX || !slotY) {
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
return NULL;
|
||||
}
|
||||
int n = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) {
|
||||
items[n].img = img;
|
||||
items[n].idx = n;
|
||||
n++;
|
||||
int cols = (img->w + atlasMaxW - 1) / atlasMaxW;
|
||||
int rows = (img->h + atlasMaxH - 1) / atlasMaxH;
|
||||
total += cols * rows;
|
||||
}
|
||||
}
|
||||
qsort(items, (size_t)n, sizeof(PackItem), comparePackItemsByHeightDesc);
|
||||
if (total == 0) {
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
int cursorX = 0, cursorY = 0, rowH = 0;
|
||||
int truncated = 0;
|
||||
int packedH = 0;
|
||||
int accepted = 0;
|
||||
PackTile* tiles = (PackTile*)malloc(sizeof(PackTile) * (size_t)total);
|
||||
TileSortKey* keys = (TileSortKey*)malloc(sizeof(TileSortKey) * (size_t)total);
|
||||
if (!tiles || !keys) {
|
||||
free(tiles);
|
||||
free(keys);
|
||||
return 0;
|
||||
}
|
||||
int n = 0;
|
||||
long long srcPixels = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
ASS_Image* img = items[i].img;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
srcPixels += (long long)img->w * img->h;
|
||||
int sx = -1, sy = -1;
|
||||
if (img->w <= atlasMaxW && accepted < maxQuads) {
|
||||
int cx = cursorX, cy = cursorY, rh = rowH;
|
||||
if (cx + img->w > atlasMaxW) {
|
||||
for (int oy = 0; oy < img->h; oy += atlasMaxH) {
|
||||
int th = img->h - oy;
|
||||
if (th > atlasMaxH) th = atlasMaxH;
|
||||
for (int ox = 0; ox < img->w; ox += atlasMaxW) {
|
||||
int tw = img->w - ox;
|
||||
if (tw > atlasMaxW) tw = atlasMaxW;
|
||||
tiles[n] = (PackTile){.img = img, .ox = ox, .oy = oy, .tw = tw, .th = th, .page = -1, .sx = -1, .sy = -1};
|
||||
keys[n] = (TileSortKey){.th = th, .idx = n};
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
int pageHeights[MAX_ATLAS_PAGES] = {0};
|
||||
int pageQuads[MAX_ATLAS_PAGES] = {0};
|
||||
int pageCount = 1;
|
||||
int requiredPages = 1;
|
||||
int truncated = 0;
|
||||
|
||||
// Pass 1a: height-sorted single page — the common case, minimal packed height
|
||||
// (byte-identical to the prior single-page packer when the frame fits one page).
|
||||
qsort(keys, (size_t)n, sizeof(TileSortKey), compareTileKeysByHeightDesc);
|
||||
int cursorX = 0, cursorY = 0, rowH = 0, packedH = 0, accepted = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[keys[i].idx];
|
||||
if (accepted >= maxQuads) break;
|
||||
int cx = cursorX, cy = cursorY, rh = rowH;
|
||||
if (cx + t->tw > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + t->th > atlasMaxH) continue; // doesn't fit a single page
|
||||
t->page = 0;
|
||||
t->sx = cx;
|
||||
t->sy = cy;
|
||||
cursorX = cx + t->tw;
|
||||
cursorY = cy;
|
||||
rowH = (t->th > rh) ? t->th : rh;
|
||||
if (cy + t->th > packedH) packedH = cy + t->th;
|
||||
accepted++;
|
||||
}
|
||||
|
||||
if (accepted == n) {
|
||||
pageHeights[0] = packedH;
|
||||
pageQuads[0] = accepted;
|
||||
} else {
|
||||
// Pass 1b: the frame overflows one page. Re-pack in list order, starting a new
|
||||
// page whenever a tile won't fit the current one. List order keeps the page
|
||||
// index monotonic in painter order, so each page's quads stay one contiguous run.
|
||||
for (int i = 0; i < n; i++) {
|
||||
tiles[i].page = -1;
|
||||
tiles[i].sx = -1;
|
||||
tiles[i].sy = -1;
|
||||
}
|
||||
int page = 0, cx = 0, cy = 0, rh = 0, placed = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[i];
|
||||
if (cx + t->tw > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + img->h <= atlasMaxH) {
|
||||
sx = cx;
|
||||
sy = cy;
|
||||
cursorX = cx + img->w;
|
||||
cursorY = cy;
|
||||
rowH = (img->h > rh) ? img->h : rh;
|
||||
if (cy + img->h > packedH) packedH = cy + img->h;
|
||||
accepted++;
|
||||
if (cy + t->th > atlasMaxH) {
|
||||
page++;
|
||||
cx = 0;
|
||||
cy = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (page + 1 > requiredPages) requiredPages = page + 1;
|
||||
if (page < providedPages && placed < maxQuads) {
|
||||
t->page = page;
|
||||
t->sx = cx;
|
||||
t->sy = cy;
|
||||
if (cy + t->th > pageHeights[page]) pageHeights[page] = cy + t->th;
|
||||
pageQuads[page]++;
|
||||
placed++;
|
||||
}
|
||||
cx += t->tw;
|
||||
rh = (t->th > rh) ? t->th : rh;
|
||||
}
|
||||
if (sx < 0) truncated++;
|
||||
slotX[items[i].idx] = sx;
|
||||
slotY[items[i].idx] = sy;
|
||||
pageCount = (requiredPages < providedPages) ? requiredPages : providedPages;
|
||||
accepted = placed;
|
||||
truncated = n - placed;
|
||||
}
|
||||
|
||||
if (truncated > 0 && (truncationLogCounter++ & 63) == 0) {
|
||||
// Warn only for genuinely-unrecoverable loss. A frame that needs more pages than
|
||||
// the buffer currently holds, yet fits within MAX_ATLAS_PAGES and the vertex
|
||||
// budget, is recoverable: the caller grows the buffer and re-renders, so the
|
||||
// first (discarded) render's truncated > 0 is a false alarm, not data loss. Tiles
|
||||
// are only truly lost past the page cap or the vertex budget.
|
||||
const int recoverableGrow = requiredPages <= MAX_ATLAS_PAGES && n <= maxQuads;
|
||||
if (truncated > 0 && !recoverableGrow && (truncationLogCounter++ & 63) == 0) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d images dropped (atlas %dx%d, %d quads max)", truncated,
|
||||
n, atlasMaxW, atlasMaxH, maxQuads);
|
||||
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d tiles dropped (atlas %dx%d, need %d pages have %d)",
|
||||
truncated, n, atlasMaxW, atlasMaxH, requiredPages, providedPages);
|
||||
}
|
||||
if (accepted == 0) {
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated);
|
||||
free(tiles);
|
||||
free(keys);
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, truncated, requiredPages, 1, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
memset(atlasPixels, 0, (size_t)atlasMaxW * packedH);
|
||||
// Clear only the packed rows of each written page.
|
||||
for (int p = 0; p < pageCount; p++) {
|
||||
memset(atlasPixels + (size_t)p * pageBytes, 0, (size_t)atlasMaxW * pageHeights[p]);
|
||||
}
|
||||
|
||||
// Pass 2: walk the original list (= libass's painter/blend order), copying each
|
||||
// accepted image into its assigned slot and emitting its quad.
|
||||
// Emit tiles in list order (= libass's painter/blend order), copying each placed
|
||||
// tile into its page slot and emitting its quad. Monotonic page assignment makes
|
||||
// each page's quads a contiguous run, matching pageQuads[] for the per-page draw.
|
||||
int qi = 0;
|
||||
int k = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
const int px = slotX[k];
|
||||
const int py = slotY[k];
|
||||
k++;
|
||||
if (px < 0) continue;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[i];
|
||||
if (t->page < 0) continue;
|
||||
ASS_Image* img = t->img;
|
||||
const int px = t->sx;
|
||||
const int py = t->sy;
|
||||
uint8_t* pageBase = atlasPixels + (size_t)t->page * pageBytes;
|
||||
|
||||
for (int y = 0; y < img->h; y++) {
|
||||
uint8_t* dst = atlasPixels + (size_t)(py + y) * atlasMaxW + px;
|
||||
const uint8_t* src = img->bitmap + (size_t)y * img->stride;
|
||||
memcpy(dst, src, (size_t)img->w);
|
||||
for (int y = 0; y < t->th; y++) {
|
||||
uint8_t* dst = pageBase + (size_t)(py + y) * atlasMaxW + px;
|
||||
const uint8_t* src = img->bitmap + (size_t)(t->oy + y) * img->stride + t->ox;
|
||||
memcpy(dst, src, (size_t)t->tw);
|
||||
}
|
||||
|
||||
const float x0 = (float)img->dst_x;
|
||||
const float y0 = (float)img->dst_y;
|
||||
const float x1 = x0 + (float)img->w;
|
||||
const float y1 = y0 + (float)img->h;
|
||||
const float x0 = (float)(img->dst_x + t->ox);
|
||||
const float y0 = (float)(img->dst_y + t->oy);
|
||||
const float x1 = x0 + (float)t->tw;
|
||||
const float y1 = y0 + (float)t->th;
|
||||
const float u0 = (float)px / (float)atlasMaxW;
|
||||
const float v0 = (float)py / (float)atlasMaxH;
|
||||
const float u1 = (float)(px + img->w) / (float)atlasMaxW;
|
||||
const float v1 = (float)(py + img->h) / (float)atlasMaxH;
|
||||
const float u1 = (float)(px + t->tw) / (float)atlasMaxW;
|
||||
const float v1 = (float)(py + t->th) / (float)atlasMaxH;
|
||||
const unsigned int c = img->color;
|
||||
const float r = (float)((c >> 24) & 0xFFu) / 255.0f;
|
||||
const float g = (float)((c >> 16) & 0xFFu) / 255.0f;
|
||||
@@ -416,9 +605,8 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
|
||||
qi++;
|
||||
}
|
||||
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
free(tiles);
|
||||
free(keys);
|
||||
|
||||
// Slow-render breakdown: separates libass's own cost (rasterize/blur/shape)
|
||||
// from this function's packing + memcpy, so device logs attribute the time.
|
||||
@@ -426,11 +614,147 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
|
||||
if (tEnd - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG,
|
||||
"slow render t=%lldms: total=%lldms ass=%lldms pack+copy=%lldms images=%d srcPx=%lldk atlas=%dx%d quads=%d",
|
||||
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, packedH, qi);
|
||||
"slow render t=%lldms: total=%lldms ass=%lldms pack+copy=%lldms images=%d srcPx=%lldk "
|
||||
"atlas=%dx%d pages=%d quads=%d",
|
||||
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, atlasMaxH, pageCount, qi);
|
||||
}
|
||||
|
||||
// atlasWidth is the full row stride (GLES2 can't upload with stride ≠ width);
|
||||
// atlasHeight is the packed height — the only rows worth uploading.
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, atlasMaxW, packedH, qi, changed, truncated);
|
||||
// pageHeights/pageQuadCounts describe the per-page upload + draw ranges.
|
||||
return writeAtlasHeader(
|
||||
env, headerBuf, atlasMaxW, qi, changed, truncated, requiredPages, 1, pageCount, pageHeights, pageQuads);
|
||||
}
|
||||
|
||||
// --- AssFrameTimestamps (EGL_ANDROID_get_frame_timestamps) ---
|
||||
//
|
||||
// Measures the overlay buffer's ACTUAL on-screen present time so subtitle
|
||||
// frame-perfection can be checked against the video frame's release time as
|
||||
// ground truth, instead of the queue time (eglSwapBuffers return) the swap loop
|
||||
// otherwise sees. The Java EGLExt only exposes eglPresentationTimeANDROID, so the
|
||||
// frame-timestamp entry points are resolved here via eglGetProcAddress.
|
||||
//
|
||||
// All functions run on the GL thread with the pipeline's EGL context current.
|
||||
|
||||
// Older NDK eglext.h may predate the extension; fall back to the spec values.
|
||||
#ifndef EGL_TIMESTAMPS_ANDROID
|
||||
#define EGL_TIMESTAMPS_ANDROID 0x3430
|
||||
#endif
|
||||
#ifndef EGL_COMPOSITION_LATCH_TIME_ANDROID
|
||||
#define EGL_COMPOSITION_LATCH_TIME_ANDROID 0x3436
|
||||
#endif
|
||||
#ifndef EGL_FIRST_COMPOSITION_START_TIME_ANDROID
|
||||
#define EGL_FIRST_COMPOSITION_START_TIME_ANDROID 0x3437
|
||||
#endif
|
||||
#ifndef EGL_DISPLAY_PRESENT_TIME_ANDROID
|
||||
#define EGL_DISPLAY_PRESENT_TIME_ANDROID 0x343A
|
||||
#endif
|
||||
#ifndef EGL_TIMESTAMP_INVALID_ANDROID
|
||||
#define EGL_TIMESTAMP_INVALID_ANDROID (-1)
|
||||
#endif
|
||||
#ifndef EGL_TIMESTAMP_PENDING_ANDROID
|
||||
#define EGL_TIMESTAMP_PENDING_ANDROID (-2)
|
||||
#endif
|
||||
#ifndef EGL_ANDROID_get_frame_timestamps
|
||||
typedef khronos_stime_nanoseconds_t EGLnsecsANDROID;
|
||||
typedef EGLBoolean(EGLAPIENTRYP PFNEGLGETNEXTFRAMEIDANDROIDPROC)(EGLDisplay, EGLSurface, EGLuint64KHR*);
|
||||
typedef EGLBoolean(EGLAPIENTRYP PFNEGLGETFRAMETIMESTAMPSANDROIDPROC)(
|
||||
EGLDisplay, EGLSurface, EGLuint64KHR, EGLint, const EGLint*, EGLnsecsANDROID*);
|
||||
typedef EGLBoolean(EGLAPIENTRYP PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC)(EGLDisplay, EGLSurface, EGLint);
|
||||
#endif
|
||||
|
||||
// nativeInit status: success codes are the chosen timestamp source (≥ 0); the
|
||||
// actual display present time on code 0, and SurfaceFlinger composition timestamps
|
||||
// (a near-constant ~1-vsync earlier than scanout) on codes 1/2 — a constant bias
|
||||
// that doesn't hide the inter-layer jitter / multi-vsync outliers we look for.
|
||||
// Negative codes are failure reasons surfaced to the stats path for diagnosis.
|
||||
#define FT_SRC_PRESENT 0
|
||||
#define FT_SRC_COMPOSITION_START 1
|
||||
#define FT_SRC_COMPOSITION_LATCH 2
|
||||
#define FT_ERR_NO_SURFACE (-1)
|
||||
#define FT_ERR_NO_EXTENSION (-2)
|
||||
#define FT_ERR_NO_PROC (-3)
|
||||
#define FT_ERR_UNSUPPORTED (-4)
|
||||
#define FT_ERR_ENABLE_FAILED (-5)
|
||||
|
||||
static PFNEGLGETNEXTFRAMEIDANDROIDPROC pEglGetNextFrameId = NULL;
|
||||
static PFNEGLGETFRAMETIMESTAMPSANDROIDPROC pEglGetFrameTimestamps = NULL;
|
||||
static PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC pEglGetFrameTimestampSupported = NULL;
|
||||
static EGLDisplay gFtDisplay = EGL_NO_DISPLAY;
|
||||
static EGLSurface gFtSurface = EGL_NO_SURFACE;
|
||||
static EGLint gFtPresentName = EGL_DISPLAY_PRESENT_TIME_ANDROID;
|
||||
|
||||
// Probes the extension on the currently-current draw surface and enables capture.
|
||||
// Re-resolves the display/surface each call so surface recreation is handled.
|
||||
// Returns one of the FT_* codes above.
|
||||
JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssFrameTimestamps_nativeInit(JNIEnv* env, jclass clazz) {
|
||||
gFtSurface = EGL_NO_SURFACE;
|
||||
EGLDisplay dpy = eglGetCurrentDisplay();
|
||||
EGLSurface surf = eglGetCurrentSurface(EGL_DRAW);
|
||||
if (dpy == EGL_NO_DISPLAY || surf == EGL_NO_SURFACE) return FT_ERR_NO_SURFACE;
|
||||
|
||||
const char* exts = eglQueryString(dpy, EGL_EXTENSIONS);
|
||||
if (exts == NULL || strstr(exts, "EGL_ANDROID_get_frame_timestamps") == NULL) {
|
||||
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frame-timestamps: extension not present");
|
||||
return FT_ERR_NO_EXTENSION;
|
||||
}
|
||||
if (pEglGetNextFrameId == NULL) {
|
||||
pEglGetNextFrameId = (PFNEGLGETNEXTFRAMEIDANDROIDPROC)eglGetProcAddress("eglGetNextFrameIdANDROID");
|
||||
pEglGetFrameTimestamps = (PFNEGLGETFRAMETIMESTAMPSANDROIDPROC)eglGetProcAddress("eglGetFrameTimestampsANDROID");
|
||||
pEglGetFrameTimestampSupported =
|
||||
(PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC)eglGetProcAddress("eglGetFrameTimestampSupportedANDROID");
|
||||
}
|
||||
if (pEglGetNextFrameId == NULL || pEglGetFrameTimestamps == NULL || pEglGetFrameTimestampSupported == NULL) {
|
||||
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "frame-timestamps: entry points unresolved");
|
||||
return FT_ERR_NO_PROC;
|
||||
}
|
||||
|
||||
// Prefer true display present; many TV HWCs (e.g. Amlogic) don't report present
|
||||
// fences but do report SurfaceFlinger composition timestamps. Take the first
|
||||
// supported — composition timing still pins the swap to a vsync for A-vs-B.
|
||||
jint status;
|
||||
if (pEglGetFrameTimestampSupported(dpy, surf, EGL_DISPLAY_PRESENT_TIME_ANDROID)) {
|
||||
gFtPresentName = EGL_DISPLAY_PRESENT_TIME_ANDROID;
|
||||
status = FT_SRC_PRESENT;
|
||||
} else if (pEglGetFrameTimestampSupported(dpy, surf, EGL_FIRST_COMPOSITION_START_TIME_ANDROID)) {
|
||||
gFtPresentName = EGL_FIRST_COMPOSITION_START_TIME_ANDROID;
|
||||
status = FT_SRC_COMPOSITION_START;
|
||||
} else if (pEglGetFrameTimestampSupported(dpy, surf, EGL_COMPOSITION_LATCH_TIME_ANDROID)) {
|
||||
gFtPresentName = EGL_COMPOSITION_LATCH_TIME_ANDROID;
|
||||
status = FT_SRC_COMPOSITION_LATCH;
|
||||
} else {
|
||||
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frame-timestamps: no supported timestamp name");
|
||||
return FT_ERR_UNSUPPORTED;
|
||||
}
|
||||
|
||||
if (!eglSurfaceAttrib(dpy, surf, EGL_TIMESTAMPS_ANDROID, EGL_TRUE)) {
|
||||
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "frame-timestamps: enable failed 0x%x", eglGetError());
|
||||
return FT_ERR_ENABLE_FAILED;
|
||||
}
|
||||
gFtDisplay = dpy;
|
||||
gFtSurface = surf;
|
||||
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frame-timestamps: enabled (source=%d)", status);
|
||||
return status;
|
||||
}
|
||||
|
||||
// Frame id the next eglSwapBuffers will produce; call immediately before it.
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssFrameTimestamps_nativeGetNextFrameId(JNIEnv* env, jclass clazz) {
|
||||
if (pEglGetNextFrameId == NULL || gFtSurface == EGL_NO_SURFACE) return -1;
|
||||
EGLuint64KHR id = 0;
|
||||
if (!pEglGetNextFrameId(gFtDisplay, gFtSurface, &id)) return -1;
|
||||
return (jlong)id;
|
||||
}
|
||||
|
||||
// Present (or composition) time for frameId (System.nanoTime() domain), or the
|
||||
// PENDING(-2)/INVALID(-1) sentinels. Reported a few frames after the swap.
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssFrameTimestamps_nativeGetDisplayPresentTime(JNIEnv* env, jclass clazz, jlong frameId) {
|
||||
if (pEglGetFrameTimestamps == NULL || gFtSurface == EGL_NO_SURFACE) return EGL_TIMESTAMP_INVALID_ANDROID;
|
||||
const EGLint names[1] = {gFtPresentName};
|
||||
EGLnsecsANDROID values[1] = {0};
|
||||
if (!pEglGetFrameTimestamps(gFtDisplay, gFtSurface, (EGLuint64KHR)frameId, 1, names, values)) {
|
||||
// Frame id evicted from SurfaceFlinger's history, or bad surface.
|
||||
return EGL_TIMESTAMP_INVALID_ANDROID;
|
||||
}
|
||||
return (jlong)values[0];
|
||||
}
|
||||
|
||||
@@ -2,9 +2,54 @@ cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
project("asskt")
|
||||
|
||||
# libass headers + libass.so come from the io.github.peerless2012:ass AAR via prefab.
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c)
|
||||
find_package(lib_ass REQUIRED CONFIG)
|
||||
# Fetching the fork release at configure time keeps per-ABI static archives out
|
||||
# of git; the pinned hash makes that network step reproducible.
|
||||
set(LIBASS_VERSION "0.18.3")
|
||||
set(LIBASS_SHA256 "fc98637752695d7cf9e26b02befaa634dd4cad25a2f38fba80de814bfd310a17")
|
||||
set(LIBASS_ZIP_URL "https://github.com/edde746/libass/releases/download/${LIBASS_VERSION}/libass-android-${LIBASS_VERSION}.zip")
|
||||
|
||||
# Gradle passes one cache root so per-ABI CMake builds share the download.
|
||||
if(NOT DEFINED LIBASS_CACHE_DIR)
|
||||
set(LIBASS_CACHE_DIR "${CMAKE_BINARY_DIR}/libass-prebuilt")
|
||||
endif()
|
||||
set(LIBASS_ROOT "${LIBASS_CACHE_DIR}/libass-android-${LIBASS_VERSION}")
|
||||
set(LIBASS_ARCHIVE "${LIBASS_ROOT}/lib/${ANDROID_ABI}/libass.a")
|
||||
set(LIBASS_HEADER "${LIBASS_ROOT}/include/ass/ass.h")
|
||||
|
||||
# The downloaded archive lives under Flutter's root build/ directory, which can
|
||||
# be deleted without invalidating android/libass/.cxx. Model it as a Ninja output
|
||||
# so stale CMake configure caches can regenerate it during the build step.
|
||||
file(MAKE_DIRECTORY "${LIBASS_ROOT}/include")
|
||||
add_custom_command(
|
||||
OUTPUT "${LIBASS_ARCHIVE}" "${LIBASS_HEADER}"
|
||||
COMMAND "${CMAKE_COMMAND}"
|
||||
"-DLIBASS_VERSION=${LIBASS_VERSION}"
|
||||
"-DLIBASS_SHA256=${LIBASS_SHA256}"
|
||||
"-DLIBASS_ZIP_URL=${LIBASS_ZIP_URL}"
|
||||
"-DLIBASS_CACHE_DIR=${LIBASS_CACHE_DIR}"
|
||||
"-DLIBASS_ROOT=${LIBASS_ROOT}"
|
||||
"-DLIBASS_ARCHIVE=${LIBASS_ARCHIVE}"
|
||||
"-DLIBASS_HEADER=${LIBASS_HEADER}"
|
||||
"-DANDROID_ABI=${ANDROID_ABI}"
|
||||
-P "${CMAKE_CURRENT_LIST_DIR}/FetchLibass.cmake"
|
||||
COMMENT "Preparing fork libass ${LIBASS_VERSION} for ${ANDROID_ABI}"
|
||||
VERBATIM)
|
||||
|
||||
string(REPLACE "-" "_" LIBASS_ABI_TARGET "${ANDROID_ABI}")
|
||||
add_custom_target(libass_prebuilt_${LIBASS_ABI_TARGET}
|
||||
DEPENDS "${LIBASS_ARCHIVE}" "${LIBASS_HEADER}")
|
||||
|
||||
add_library(ass STATIC IMPORTED)
|
||||
set_target_properties(ass PROPERTIES
|
||||
IMPORTED_LOCATION "${LIBASS_ARCHIVE}")
|
||||
target_include_directories(ass INTERFACE "${LIBASS_ROOT}/include")
|
||||
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c SurfaceTxProbe.c)
|
||||
add_dependencies(${CMAKE_PROJECT_NAME} libass_prebuilt_${LIBASS_ABI_TARGET})
|
||||
# HarfBuzz brings C++; link the shared STL that the app already packages.
|
||||
# (SurfaceTxProbe resolves its libandroid/libsync entry points via dlsym, so no extra link.)
|
||||
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE
|
||||
lib_ass::ass
|
||||
log)
|
||||
ass
|
||||
log
|
||||
EGL
|
||||
c++_shared)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
foreach(_var IN ITEMS
|
||||
LIBASS_VERSION
|
||||
LIBASS_SHA256
|
||||
LIBASS_ZIP_URL
|
||||
LIBASS_CACHE_DIR
|
||||
LIBASS_ROOT
|
||||
LIBASS_ARCHIVE
|
||||
LIBASS_HEADER
|
||||
ANDROID_ABI)
|
||||
if(NOT DEFINED ${_var} OR "${${_var}}" STREQUAL "")
|
||||
message(FATAL_ERROR "${_var} is required")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
get_filename_component(_cache_parent "${LIBASS_CACHE_DIR}" DIRECTORY)
|
||||
file(MAKE_DIRECTORY "${_cache_parent}")
|
||||
|
||||
# Android Gradle can build ABI variants in parallel; serialize the shared cache.
|
||||
file(LOCK "${LIBASS_CACHE_DIR}.lock" GUARD PROCESS TIMEOUT 300)
|
||||
|
||||
if(NOT EXISTS "${LIBASS_ARCHIVE}" OR NOT EXISTS "${LIBASS_HEADER}")
|
||||
file(MAKE_DIRECTORY "${LIBASS_CACHE_DIR}")
|
||||
set(_libass_zip "${LIBASS_CACHE_DIR}/libass-android-${LIBASS_VERSION}.zip")
|
||||
|
||||
message(STATUS "Fetching fork libass ${LIBASS_VERSION} from ${LIBASS_ZIP_URL}")
|
||||
file(DOWNLOAD "${LIBASS_ZIP_URL}" "${_libass_zip}"
|
||||
EXPECTED_HASH "SHA256=${LIBASS_SHA256}"
|
||||
TLS_VERIFY ON
|
||||
STATUS _libass_dl)
|
||||
list(GET _libass_dl 0 _libass_dl_code)
|
||||
if(NOT _libass_dl_code EQUAL 0)
|
||||
file(REMOVE "${_libass_zip}")
|
||||
message(FATAL_ERROR "Failed to download libass: ${_libass_dl}")
|
||||
endif()
|
||||
|
||||
file(REMOVE_RECURSE "${LIBASS_ROOT}")
|
||||
file(ARCHIVE_EXTRACT INPUT "${_libass_zip}" DESTINATION "${LIBASS_CACHE_DIR}")
|
||||
endif()
|
||||
|
||||
if(NOT EXISTS "${LIBASS_ARCHIVE}")
|
||||
message(FATAL_ERROR "libass archive for ${ANDROID_ABI} was not extracted: ${LIBASS_ARCHIVE}")
|
||||
endif()
|
||||
if(NOT EXISTS "${LIBASS_HEADER}")
|
||||
message(FATAL_ERROR "libass headers were not extracted: ${LIBASS_HEADER}")
|
||||
endif()
|
||||
@@ -0,0 +1,317 @@
|
||||
// EXPERIMENTAL SPIKE — does the codec VIDEO plane's actual present time differ from a
|
||||
// GL OSD overlay's, and is that difference measurable in-app? (See the memory note
|
||||
// project_libass_present_time_instrumentation.)
|
||||
//
|
||||
// Android exposes no present time for a codec-owned video layer. The one runtime lead is
|
||||
// API 34 `SurfaceView.applyTransactionToFrame()`: it merges an otherwise-empty,
|
||||
// callback-bearing transaction with the codec's *next buffer* transaction. The completion
|
||||
// stats then carry, per surface, the PREVIOUS-RELEASE fence — the moment the buffer the new
|
||||
// frame replaced stopped being read by the display ≈ when the new codec frame actually
|
||||
// reached the video plane. Compared in Kotlin to that frame's `releaseTimeNs` target (the
|
||||
// overlay's own present error is ~0), the delta is the inter-plane lag.
|
||||
//
|
||||
// The SurfaceControl transaction-stats / fromJava APIs are API 29/34 while this module's
|
||||
// minSdk is 21; clang's __builtin_available doesn't guard the Android availability domain in
|
||||
// this toolchain. So the libandroid entry points are resolved by dlsym (no
|
||||
// availability-attributed declarations get compiled). Every call site is additionally
|
||||
// hard-gated to API >= 34 in Kotlin (VideoLayerLatencyProbe).
|
||||
//
|
||||
// Fence timestamps are read with the raw SYNC_IOC_FILE_INFO ioctl rather than libsync:
|
||||
// libsync.so is NOT a public NDK library, so an app's linker namespace blocks dlopen of it.
|
||||
//
|
||||
// Compiled into the libass "asskt" .so; called from app Kotlin SurfaceTxProbe.
|
||||
#include <android/log.h>
|
||||
#include <dlfcn.h>
|
||||
#include <jni.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define LOG_TAG "SurfaceTxProbe"
|
||||
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
|
||||
|
||||
#ifndef SYNC_IOC_MAGIC
|
||||
#define SYNC_IOC_MAGIC '>'
|
||||
#endif
|
||||
struct stp_fence_info {
|
||||
char obj_name[32];
|
||||
char driver_name[32];
|
||||
int32_t status;
|
||||
uint32_t flags;
|
||||
uint64_t timestamp_ns;
|
||||
};
|
||||
struct stp_file_info {
|
||||
char name[32];
|
||||
int32_t status;
|
||||
uint32_t flags;
|
||||
uint32_t num_fences;
|
||||
uint32_t pad;
|
||||
uint64_t sync_fence_info;
|
||||
};
|
||||
#ifndef SYNC_IOC_FILE_INFO
|
||||
#define SYNC_IOC_FILE_INFO _IOWR(SYNC_IOC_MAGIC, 4, struct stp_file_info)
|
||||
#endif
|
||||
|
||||
// libsync is hidden from app linker namespaces, so use the kernel ioctl directly.
|
||||
static int64_t readFenceTimeNs(int fd, int* outStatus) {
|
||||
*outStatus = -1;
|
||||
if (fd < 0) return -1;
|
||||
struct stp_file_info probe;
|
||||
memset(&probe, 0, sizeof(probe));
|
||||
if (ioctl(fd, SYNC_IOC_FILE_INFO, &probe) < 0) return -1;
|
||||
*outStatus = probe.status;
|
||||
if (probe.status != 1 || probe.num_fences == 0) return -1;
|
||||
struct stp_fence_info* arr = (struct stp_fence_info*)calloc(probe.num_fences, sizeof(struct stp_fence_info));
|
||||
if (!arr) return -1;
|
||||
struct stp_file_info req;
|
||||
memset(&req, 0, sizeof(req));
|
||||
req.num_fences = probe.num_fences;
|
||||
req.sync_fence_info = (uint64_t)(uintptr_t)arr;
|
||||
int64_t t = -1;
|
||||
if (ioctl(fd, SYNC_IOC_FILE_INFO, &req) == 0) {
|
||||
for (uint32_t i = 0; i < req.num_fences; i++) {
|
||||
if ((int64_t)arr[i].timestamp_ns > t) t = (int64_t)arr[i].timestamp_ns;
|
||||
}
|
||||
}
|
||||
free(arr);
|
||||
return t;
|
||||
}
|
||||
|
||||
typedef struct ASurfaceTransaction ASurfaceTransaction;
|
||||
typedef struct ASurfaceControl ASurfaceControl;
|
||||
typedef struct ASurfaceTransactionStats ASurfaceTransactionStats;
|
||||
typedef void (*OnCompleteFn)(void* context, ASurfaceTransactionStats* stats);
|
||||
|
||||
typedef ASurfaceTransaction* (*pf_fromJava)(JNIEnv*, jobject);
|
||||
typedef void (*pf_setOnComplete)(ASurfaceTransaction*, void*, OnCompleteFn);
|
||||
typedef int64_t (*pf_latchTime)(ASurfaceTransactionStats*);
|
||||
typedef void (*pf_getControls)(ASurfaceTransactionStats*, ASurfaceControl***, size_t*);
|
||||
typedef int (*pf_prevRelease)(ASurfaceTransactionStats*, ASurfaceControl*);
|
||||
typedef void (*pf_releaseControls)(ASurfaceControl**);
|
||||
|
||||
static pf_fromJava p_fromJava = NULL;
|
||||
static pf_setOnComplete p_setOnComplete = NULL;
|
||||
static pf_latchTime p_latchTime = NULL;
|
||||
static pf_getControls p_getControls = NULL;
|
||||
static pf_prevRelease p_prevRelease = NULL;
|
||||
static pf_releaseControls p_releaseControls = NULL;
|
||||
static int gScResolved = 0;
|
||||
static int gScOk = 0;
|
||||
static int gScWarningLogged = 0;
|
||||
|
||||
// Runtime lookup keeps this API-34 probe buildable with the module's minSdk 21.
|
||||
static int resolveSc(void) {
|
||||
if (gScResolved) return gScOk;
|
||||
gScResolved = 1;
|
||||
void* h = dlopen("libandroid.so", RTLD_NOW | RTLD_GLOBAL);
|
||||
if (!h) return 0;
|
||||
p_fromJava = (pf_fromJava)dlsym(h, "ASurfaceTransaction_fromJava");
|
||||
p_setOnComplete = (pf_setOnComplete)dlsym(h, "ASurfaceTransaction_setOnComplete");
|
||||
p_latchTime = (pf_latchTime)dlsym(h, "ASurfaceTransactionStats_getLatchTime");
|
||||
p_getControls = (pf_getControls)dlsym(h, "ASurfaceTransactionStats_getASurfaceControls");
|
||||
p_prevRelease = (pf_prevRelease)dlsym(h, "ASurfaceTransactionStats_getPreviousReleaseFenceFd");
|
||||
p_releaseControls = (pf_releaseControls)dlsym(h, "ASurfaceTransactionStats_releaseASurfaceControls");
|
||||
gScOk = (p_fromJava && p_setOnComplete && p_latchTime && p_getControls && p_prevRelease && p_releaseControls) ? 1 : 0;
|
||||
return gScOk;
|
||||
}
|
||||
|
||||
// The completion context is pointer-width, so 32-bit devices need an index side-channel.
|
||||
#define TAG_RING_SIZE 256
|
||||
static int64_t gTagRing[TAG_RING_SIZE];
|
||||
static int gSrcRing[TAG_RING_SIZE];
|
||||
static int gTagSeq = 0;
|
||||
|
||||
static JavaVM* gVm = NULL;
|
||||
static jclass gProbeClass = NULL;
|
||||
static jmethodID gOnResult = NULL;
|
||||
static int gCallbackLookupAttempted = 0;
|
||||
static pthread_mutex_t gInitLock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
static int64_t nowMonoNs(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
}
|
||||
|
||||
static void reportResult(
|
||||
JNIEnv* env, int64_t tag, int64_t latchNs, int64_t releaseNs, int count, int fenceState, int source, int64_t cbNs) {
|
||||
if (!env || !gProbeClass || !gOnResult) return;
|
||||
(*env)->CallStaticVoidMethod(
|
||||
env, gProbeClass, gOnResult, (jlong)tag, (jlong)latchNs, (jlong)releaseNs, (jint)count, (jint)fenceState,
|
||||
(jint)source, (jlong)cbNs);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
// Previous-release fences can still be pending in the binder callback; a worker
|
||||
// thread keeps SurfaceFlinger's callback dispatch unblocked.
|
||||
struct fenceJob {
|
||||
int fd;
|
||||
int64_t tag;
|
||||
int64_t latch;
|
||||
int count;
|
||||
int source;
|
||||
};
|
||||
#define JOB_RING 64
|
||||
static struct fenceJob gJobs[JOB_RING];
|
||||
static int gJobHead = 0, gJobTail = 0;
|
||||
static int gJobDrops = 0;
|
||||
static pthread_mutex_t gJobLock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t gJobCond = PTHREAD_COND_INITIALIZER;
|
||||
static pthread_t gReader;
|
||||
static int gReaderStarted = 0;
|
||||
|
||||
static void* readerMain(void* arg);
|
||||
|
||||
static int ensureProbeInit(JNIEnv* env, jclass clazz) {
|
||||
int scOk = 0;
|
||||
pthread_mutex_lock(&gInitLock);
|
||||
if (!gVm && (*env)->GetJavaVM(env, &gVm) != JNI_OK) {
|
||||
LOGW("GetJavaVM failed — transaction probe disabled");
|
||||
pthread_mutex_unlock(&gInitLock);
|
||||
return 0;
|
||||
}
|
||||
if (!gProbeClass) {
|
||||
gProbeClass = (*env)->NewGlobalRef(env, clazz);
|
||||
if (!gProbeClass) {
|
||||
LOGW("NewGlobalRef(SurfaceTxProbe) failed — transaction probe disabled");
|
||||
pthread_mutex_unlock(&gInitLock);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (!gCallbackLookupAttempted) {
|
||||
gCallbackLookupAttempted = 1;
|
||||
gOnResult = (*env)->GetStaticMethodID(env, clazz, "onResult", "(JJJIIIJ)V");
|
||||
if (!gOnResult) {
|
||||
(*env)->ExceptionClear(env);
|
||||
LOGW("onResult(JJJIIIJ)V not found — JNI callback disabled (R8 stripped it?)");
|
||||
}
|
||||
}
|
||||
if (!gOnResult) {
|
||||
pthread_mutex_unlock(&gInitLock);
|
||||
return 0;
|
||||
}
|
||||
scOk = resolveSc();
|
||||
if (!scOk) {
|
||||
if (!gScWarningLogged) {
|
||||
gScWarningLogged = 1;
|
||||
LOGW("libandroid SurfaceControl transaction-stats API unavailable");
|
||||
}
|
||||
pthread_mutex_unlock(&gInitLock);
|
||||
return 0;
|
||||
}
|
||||
if (!gReaderStarted) {
|
||||
const int rc = pthread_create(&gReader, NULL, readerMain, NULL);
|
||||
if (rc != 0) {
|
||||
LOGW("fence reader thread start failed: %d", rc);
|
||||
pthread_mutex_unlock(&gInitLock);
|
||||
return 0;
|
||||
}
|
||||
gReaderStarted = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&gInitLock);
|
||||
return scOk;
|
||||
}
|
||||
|
||||
static void* readerMain(void* arg) {
|
||||
(void)arg;
|
||||
JNIEnv* env = NULL;
|
||||
if ((*gVm)->AttachCurrentThread(gVm, &env, NULL) != JNI_OK) return NULL;
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&gJobLock);
|
||||
while (gJobHead == gJobTail) pthread_cond_wait(&gJobCond, &gJobLock);
|
||||
struct fenceJob job = gJobs[gJobTail];
|
||||
gJobTail = (gJobTail + 1) % JOB_RING;
|
||||
pthread_mutex_unlock(&gJobLock);
|
||||
|
||||
int64_t releaseNs = -1;
|
||||
int fenceState;
|
||||
struct pollfd pfd = {.fd = job.fd, .events = POLLIN, .revents = 0};
|
||||
int pr = poll(&pfd, 1, 250);
|
||||
if (pr > 0 && (pfd.revents & POLLIN)) {
|
||||
int st = -1;
|
||||
releaseNs = readFenceTimeNs(job.fd, &st);
|
||||
fenceState = (releaseNs > 0) ? 3 : 1;
|
||||
} else {
|
||||
fenceState = 2;
|
||||
}
|
||||
close(job.fd);
|
||||
reportResult(env, job.tag, job.latch, releaseNs, job.count, fenceState, job.source, nowMonoNs());
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void onComplete(void* context, ASurfaceTransactionStats* stats) {
|
||||
int slot = (int)(intptr_t)context;
|
||||
__atomic_thread_fence(__ATOMIC_ACQUIRE);
|
||||
int64_t tag = gTagRing[slot & (TAG_RING_SIZE - 1)];
|
||||
int source = gSrcRing[slot & (TAG_RING_SIZE - 1)];
|
||||
int64_t latchNs = p_latchTime ? p_latchTime(stats) : -1;
|
||||
|
||||
// Display-global present fences are abort-prone; per-surface release fences are stable here.
|
||||
int chosenFd = -1;
|
||||
int count = 0;
|
||||
ASurfaceControl** controls = NULL;
|
||||
size_t n = 0;
|
||||
if (p_getControls) p_getControls(stats, &controls, &n);
|
||||
count = (int)n;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
int rfd = p_prevRelease ? p_prevRelease(stats, controls[i]) : -1;
|
||||
if (rfd < 0) continue;
|
||||
if (chosenFd < 0)
|
||||
chosenFd = rfd;
|
||||
else
|
||||
close(rfd);
|
||||
}
|
||||
if (controls && p_releaseControls) p_releaseControls(controls);
|
||||
|
||||
if (chosenFd < 0) {
|
||||
JNIEnv* env = NULL;
|
||||
int didAttach = 0;
|
||||
if ((*gVm)->GetEnv(gVm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
|
||||
if ((*gVm)->AttachCurrentThread(gVm, &env, NULL) != JNI_OK) return;
|
||||
didAttach = 1;
|
||||
}
|
||||
reportResult(env, tag, latchNs, -1, count, 0, source, nowMonoNs());
|
||||
if (didAttach) (*gVm)->DetachCurrentThread(gVm);
|
||||
return;
|
||||
}
|
||||
|
||||
pthread_mutex_lock(&gJobLock);
|
||||
int next = (gJobHead + 1) % JOB_RING;
|
||||
if (next == gJobTail) {
|
||||
close(chosenFd);
|
||||
if (gJobDrops++ == 0) LOGW("fence job ring full — dropping samples (slow fence reader?)");
|
||||
} else {
|
||||
gJobs[gJobHead].fd = chosenFd;
|
||||
gJobs[gJobHead].tag = tag;
|
||||
gJobs[gJobHead].latch = latchNs;
|
||||
gJobs[gJobHead].count = count;
|
||||
gJobs[gJobHead].source = source;
|
||||
gJobHead = next;
|
||||
pthread_cond_signal(&gJobCond);
|
||||
}
|
||||
pthread_mutex_unlock(&gJobLock);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_exoplayer_SurfaceTxProbe_nativeAttach(
|
||||
JNIEnv* env, jclass clazz, jobject jtransaction, jlong tag, jint source) {
|
||||
if (!ensureProbeInit(env, clazz)) return;
|
||||
int slot = __atomic_fetch_add(&gTagSeq, 1, __ATOMIC_RELAXED) & (TAG_RING_SIZE - 1);
|
||||
gTagRing[slot] = (int64_t)tag;
|
||||
gSrcRing[slot] = (int)source;
|
||||
// Binder carries only the slot index, so the ring write has to win publication.
|
||||
__atomic_thread_fence(__ATOMIC_RELEASE);
|
||||
|
||||
ASurfaceTransaction* tx = p_fromJava(env, jtransaction);
|
||||
if (!tx) {
|
||||
LOGW("ASurfaceTransaction_fromJava returned null");
|
||||
return;
|
||||
}
|
||||
p_setOnComplete(tx, (void*)(intptr_t)slot, onComplete);
|
||||
}
|
||||
@@ -4,18 +4,65 @@ package com.edde746.plezy.libass
|
||||
* Result of a packed-atlas render. The atlas pixel data is stored in the direct ByteBuffer
|
||||
* that was passed into [AssRender.renderFrameAtlas]; the vertex stream is in the other.
|
||||
*
|
||||
* @param atlasWidth atlas row stride in pixels (= the allocated width; 0 when [changed] == 0)
|
||||
* @param atlasHeight packed atlas height in pixels — the rows worth uploading
|
||||
* @param quadCount number of quads; the vertex buffer holds [quadCount] * 6 vertices
|
||||
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
|
||||
* @param truncated images dropped because they exceeded the atlas/vertex capacity;
|
||||
* the frame is incomplete but never stale (> 0 should be rare —
|
||||
* it means even the GL-max-sized atlas couldn't fit the frame)
|
||||
* The atlas may span more than one *page* — a heavy full-screen sign can produce more
|
||||
* sub-pixels than a single GL-max texture holds. Pages are vertically stacked in the
|
||||
* atlas ByteBuffer (page `p` at byte offset `p * atlasWidth * atlasMaxHeight`), each its
|
||||
* own texture, and are drawn in turn. Quads are emitted in libass painter order and page
|
||||
* assignment is monotonic in that order, so each page's quads form one contiguous run in
|
||||
* the vertex stream ([pageQuadCounts]); the runner uploads page `p`, then draws its run.
|
||||
*
|
||||
* Built in Kotlin by [AssRender.renderFrameAtlas] from the int[] header the native
|
||||
* renderer fills (see `writeAtlasHeader` in AssKt.c) — never constructed from JNI, so
|
||||
* the minifier may obfuscate it freely without breaking the native boundary.
|
||||
*
|
||||
* @param atlasWidth atlas row stride in pixels (= the allocated width; same for every
|
||||
* page; 0 when [changed] == 0)
|
||||
* @param pageHeights packed height (rows worth uploading) of each page; `size` = page count
|
||||
* @param pageQuadCounts quads on each page, contiguous in the vertex stream in this order;
|
||||
* `size` = page count, `sum` = [quadCount]
|
||||
* @param quadCount total quads; the vertex buffer holds [quadCount] * 6 vertices
|
||||
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
|
||||
* @param truncated images dropped because the frame needed more than [requiredPages]
|
||||
* pages of capacity or exceeded the vertex budget; the frame is
|
||||
* incomplete but never stale (should be unreachable for real content)
|
||||
* @param requiredPages pages this frame needs to render completely. When it exceeds
|
||||
* [pageHeights].size the caller must grow the atlas buffer and
|
||||
* re-render; the rendered pages are still valid in the meantime.
|
||||
* @param hasOutput true when libass reported at least one visible image for this
|
||||
* timestamp, even when [changed] is 0 and the buffers were not
|
||||
* rewritten. false means this timestamp should be blank.
|
||||
*/
|
||||
class AssAtlasFrame(
|
||||
val atlasWidth: Int,
|
||||
val atlasHeight: Int,
|
||||
val pageHeights: IntArray,
|
||||
val pageQuadCounts: IntArray,
|
||||
val quadCount: Int,
|
||||
val changed: Int,
|
||||
val truncated: Int
|
||||
)
|
||||
val truncated: Int,
|
||||
val requiredPages: Int,
|
||||
val hasOutput: Boolean
|
||||
) {
|
||||
/** Number of atlas pages this frame occupies. */
|
||||
val pageCount: Int get() = pageHeights.size
|
||||
|
||||
/** Packed height of the first page; the only page in the common single-page case. */
|
||||
val atlasHeight: Int get() = if (pageHeights.isNotEmpty()) pageHeights[0] else 0
|
||||
|
||||
/** Single-page convenience: blank/unchanged frames and tests. */
|
||||
constructor(
|
||||
atlasWidth: Int,
|
||||
atlasHeight: Int,
|
||||
quadCount: Int,
|
||||
changed: Int,
|
||||
truncated: Int,
|
||||
hasOutput: Boolean
|
||||
) : this(atlasWidth, intArrayOf(atlasHeight), intArrayOf(quadCount), quadCount, changed, truncated, 1, hasOutput)
|
||||
|
||||
constructor(
|
||||
atlasWidth: Int,
|
||||
atlasHeight: Int,
|
||||
quadCount: Int,
|
||||
changed: Int,
|
||||
truncated: Int
|
||||
) : this(atlasWidth, atlasHeight, quadCount, changed, truncated, quadCount > 0)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
/**
|
||||
* Thin binding over the `EGL_ANDROID_get_frame_timestamps` extension.
|
||||
*
|
||||
* The atlas pipeline pins each overlay swap to the video frame's `releaseTimeNs`,
|
||||
* but the swap loop can only measure when [android.opengl.EGL14.eglSwapBuffers]
|
||||
* *returns* — i.e. when the buffer was queued, not when SurfaceFlinger actually
|
||||
* presented it. That can't reveal a one-vsync compositor latch offset, which is
|
||||
* exactly the error frame-perfection work chases. This binding reads the buffer's
|
||||
* *actual on-screen present time* so it can be compared against `releaseTimeNs`
|
||||
* (the video frame's vsync target) as ground truth.
|
||||
*
|
||||
* `android.opengl.EGLExt` exposes only `eglPresentationTimeANDROID`; the
|
||||
* frame-timestamp entry points are resolved natively via `eglGetProcAddress`.
|
||||
*
|
||||
* Requires Android 10 (API 29)+ and the extension; probe with [nativeInit].
|
||||
* All calls must run on the GL thread with the pipeline's EGL context current.
|
||||
*/
|
||||
internal object AssFrameTimestamps {
|
||||
/** Present time not yet reported by SurfaceFlinger; query the frame again later. */
|
||||
const val PENDING = -2L
|
||||
|
||||
/** The frame was dropped/never presented, or its id was evicted from history. */
|
||||
const val INVALID = -1L
|
||||
|
||||
// [nativeInit] status. Success codes are the timestamp source in use (≥ 0):
|
||||
// true scanout present (SRC_PRESENT) or — where the HWC reports no present fence,
|
||||
// common on TV SoCs — a SurfaceFlinger composition timestamp ~1 vsync earlier
|
||||
// (SRC_COMPOSITION_*; a constant bias, harmless to the jitter/outlier analysis).
|
||||
// Negative codes are failure reasons, surfaced to the stats path for diagnosis.
|
||||
const val SRC_PRESENT = 0
|
||||
const val SRC_COMPOSITION_START = 1
|
||||
const val SRC_COMPOSITION_LATCH = 2
|
||||
const val ERR_NO_SURFACE = -1
|
||||
const val ERR_NO_EXTENSION = -2
|
||||
const val ERR_NO_PROC = -3
|
||||
const val ERR_UNSUPPORTED = -4
|
||||
const val ERR_ENABLE_FAILED = -5
|
||||
|
||||
/** Short label for a [nativeInit] status code, for logs/getStats. */
|
||||
fun sourceLabel(status: Int): String = when (status) {
|
||||
SRC_PRESENT -> "present"
|
||||
SRC_COMPOSITION_START -> "comp-start"
|
||||
SRC_COMPOSITION_LATCH -> "comp-latch"
|
||||
ERR_NO_SURFACE -> "off:no-surface"
|
||||
ERR_NO_EXTENSION -> "off:no-ext"
|
||||
ERR_NO_PROC -> "off:no-proc"
|
||||
ERR_UNSUPPORTED -> "off:unsupported"
|
||||
ERR_ENABLE_FAILED -> "off:enable-failed"
|
||||
else -> "off:$status"
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes the extension on the currently-current draw surface and enables
|
||||
* timestamp capture, preferring true present then composition timestamps.
|
||||
* Returns an `SRC_*` code (≥ 0) on success or an `ERR_*` code (< 0). Re-resolves
|
||||
* the surface each call, so it is safe to re-invoke after surface recreation.
|
||||
*/
|
||||
@JvmStatic external fun nativeInit(): Int
|
||||
|
||||
/** Frame id the next `eglSwapBuffers` will produce; call immediately before it. */
|
||||
@JvmStatic external fun nativeGetNextFrameId(): Long
|
||||
|
||||
/**
|
||||
* Present (or composition) time for [frameId] in the `System.nanoTime()` domain,
|
||||
* or the [PENDING]/[INVALID] sentinels. Results are deferred a few frames past
|
||||
* the swap, so a caller drains pending ids lazily.
|
||||
*/
|
||||
@JvmStatic external fun nativeGetDisplayPresentTime(frameId: Long): Long
|
||||
}
|
||||
@@ -8,6 +8,10 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
|
||||
companion object {
|
||||
|
||||
/** Must match MAX_ATLAS_PAGES + the header layout in AssKt.c (`writeAtlasHeader`). */
|
||||
private const val MAX_ATLAS_PAGES = 4
|
||||
private const val HEADER_INTS = 7 + 2 * MAX_ATLAS_PAGES
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderInit(ass: Long): Long
|
||||
|
||||
@@ -29,6 +33,12 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetUseMargins(render: Long, use: Boolean)
|
||||
|
||||
/**
|
||||
* Renders into [atlasBuf]/[vertexBuf] and writes frame metadata into [header]
|
||||
* (layout per `writeAtlasHeader` in AssKt.c). Returns 1 when the header was written,
|
||||
* 0 for missing buffers/handles. The frame object is built on the Kotlin side from
|
||||
* the header so the JNI boundary never constructs it (R8-safe; see [renderFrameAtlas]).
|
||||
*/
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderFrameAtlas(
|
||||
render: Long,
|
||||
@@ -37,8 +47,9 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
atlasBuf: ByteBuffer,
|
||||
atlasMaxWidth: Int,
|
||||
atlasMaxHeight: Int,
|
||||
vertexBuf: ByteBuffer
|
||||
): AssAtlasFrame?
|
||||
vertexBuf: ByteBuffer,
|
||||
header: IntArray
|
||||
): Int
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderDeinit(render: Long)
|
||||
@@ -46,6 +57,10 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
|
||||
private var nativeRender: Long = nativeAssRenderInit(nativeAss)
|
||||
|
||||
/** Reusable JNI frame-metadata header (see `writeAtlasHeader` in AssKt.c). Calls to
|
||||
* [renderFrameAtlas] are serialized by [lock], so one buffer is safe to reuse. */
|
||||
private val frameHeader = IntArray(HEADER_INTS)
|
||||
|
||||
@Volatile
|
||||
var released = false
|
||||
private set
|
||||
@@ -109,26 +124,31 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
withNative { nativeAssRenderSetUseMargins(it, use) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a frame into a packed ALPHA_8 texture atlas plus a single vertex stream
|
||||
* ready for `glDrawArrays(GL_TRIANGLES, 0, quadCount * 6)`.
|
||||
*
|
||||
* UVs are normalized against ([atlasMaxW], [atlasMaxH]) — the allocated texture
|
||||
* dims — so the caller can allocate the texture once and `glTexSubImage2D` only
|
||||
* the packed rows. Images that exceed the capacity are dropped and counted in
|
||||
* [AssAtlasFrame.truncated]; the render never fails on content size.
|
||||
*
|
||||
* @param atlasBuf direct ByteBuffer receiving the packed pixels (≥ atlasMaxW × atlasMaxH)
|
||||
* @param atlasMaxW atlas row stride in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param atlasMaxH atlas height in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param vertexBuf direct ByteBuffer receiving the vertex stream (192 bytes per quad)
|
||||
*/
|
||||
/** How long the most recent [renderFrameAtlas] waited to acquire the shared
|
||||
* libass lock (contended by track dialogue/font feeding), in milliseconds. */
|
||||
@Volatile
|
||||
var lastLockWaitMs: Long = 0
|
||||
private set
|
||||
|
||||
/**
|
||||
* Renders a frame into a packed ALPHA_8 texture atlas plus a vertex stream.
|
||||
*
|
||||
* The atlas may span one or more vertically-stacked pages (a dense full-screen
|
||||
* sign can exceed a single GL-max texture); vertices stay in libass painter order,
|
||||
* grouped per page ([AssAtlasFrame.pageQuadCounts]). The caller uploads each page
|
||||
* to its own texture and draws it with its own `glDrawArrays`, reproducing the
|
||||
* blend order. UVs are page-local, normalized against ([atlasMaxW], [atlasMaxH]).
|
||||
*
|
||||
* Never fails on content size: when the frame needs more pages than [atlasBuf]
|
||||
* holds, [AssAtlasFrame.requiredPages] signals the caller to grow the buffer and
|
||||
* re-render; only tiles past `MAX_ATLAS_PAGES` or the vertex budget are dropped
|
||||
* and counted in [AssAtlasFrame.truncated].
|
||||
*
|
||||
* @param atlasBuf direct ByteBuffer receiving the stacked pages (≥ atlasMaxW × atlasMaxH per page)
|
||||
* @param atlasMaxW per-page atlas row stride in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param atlasMaxH per-page atlas height in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param vertexBuf direct ByteBuffer receiving the vertex stream (192 bytes per quad)
|
||||
*/
|
||||
fun renderFrameAtlas(
|
||||
time: Long,
|
||||
atlasBuf: ByteBuffer,
|
||||
@@ -142,7 +162,21 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
if (released || nativeRender == 0L) return null
|
||||
val t = track ?: return null
|
||||
if (t.released || t.nativeAssTrack == 0L) return null
|
||||
return nativeAssRenderFrameAtlas(nativeRender, t.nativeAssTrack, time, atlasBuf, atlasMaxW, atlasMaxH, vertexBuf)
|
||||
val header = frameHeader
|
||||
val status =
|
||||
nativeAssRenderFrameAtlas(nativeRender, t.nativeAssTrack, time, atlasBuf, atlasMaxW, atlasMaxH, vertexBuf, header)
|
||||
if (status == 0) return null
|
||||
val pageCount = header[6]
|
||||
return AssAtlasFrame(
|
||||
atlasWidth = header[0],
|
||||
pageHeights = IntArray(pageCount) { header[7 + it] },
|
||||
pageQuadCounts = IntArray(pageCount) { header[7 + MAX_ATLAS_PAGES + it] },
|
||||
quadCount = header[1],
|
||||
changed = header[2],
|
||||
truncated = header[3],
|
||||
requiredPages = header[4],
|
||||
hasOutput = header[5] != 0
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import com.edde746.plezy.libass.Ass
|
||||
import com.edde746.plezy.libass.AssRender
|
||||
import com.edde746.plezy.libass.AssTrack
|
||||
import com.edde746.plezy.libass.media.parser.AssHeaderParser
|
||||
import com.edde746.plezy.libass.media.widget.AssAtlasPipelineConfig
|
||||
|
||||
/**
|
||||
* Handles ASS subtitle rendering and integration with ExoPlayer.
|
||||
@@ -185,13 +186,15 @@ class AssHandler(
|
||||
* (re)created or the selected track changes, so renderer state survives both.
|
||||
*/
|
||||
private fun applyRenderState(render: AssRender) {
|
||||
// Storage (script/video authoring size) stays full-res; only the frame and
|
||||
// margins follow RENDER_SCALE so the raster shrinks while layout is unchanged.
|
||||
if (videoSize.isValid) render.setStorageSize(videoSize.width, videoSize.height)
|
||||
when {
|
||||
surfaceSize.isValid -> render.setFrameSize(surfaceSize.width, surfaceSize.height)
|
||||
surfaceSize.isValid -> render.setFrameSize(scaledForRender(surfaceSize.width), scaledForRender(surfaceSize.height))
|
||||
// Fallback frame until the overlay surface reports its size.
|
||||
videoSize.isValid -> render.setFrameSize(videoSize.width, videoSize.height)
|
||||
videoSize.isValid -> render.setFrameSize(scaledForRender(videoSize.width), scaledForRender(videoSize.height))
|
||||
}
|
||||
margins?.let { m -> render.setMargins(m[0], m[1], m[2], m[3]) }
|
||||
margins?.let { m -> render.setMargins(scaledForRender(m[0]), scaledForRender(m[1]), scaledForRender(m[2]), scaledForRender(m[3])) }
|
||||
render.setUseMargins(useMargins)
|
||||
}
|
||||
|
||||
@@ -220,7 +223,7 @@ class AssHandler(
|
||||
if (surfaceSize.width == width && surfaceSize.height == height) return
|
||||
Log.i("AssHandler", "setOverlaySurfaceSize: width = $width, height = $height")
|
||||
surfaceSize = Size(width, height)
|
||||
render?.setFrameSize(width, height)
|
||||
render?.setFrameSize(scaledForRender(width), scaledForRender(height))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -230,9 +233,13 @@ class AssHandler(
|
||||
*/
|
||||
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
|
||||
margins = intArrayOf(top, bottom, left, right)
|
||||
render?.setMargins(top, bottom, left, right)
|
||||
render?.setMargins(scaledForRender(top), scaledForRender(bottom), scaledForRender(left), scaledForRender(right))
|
||||
}
|
||||
|
||||
/** Frame/margin extents go to libass at the overlay's render resolution; the GL
|
||||
* side scales the result back up. Identity unless RENDER_SCALE < 1. */
|
||||
private fun scaledForRender(px: Int): Int = AssAtlasPipelineConfig.scaledForRender(px)
|
||||
|
||||
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
|
||||
fun setUseMargins(use: Boolean) {
|
||||
useMargins = use
|
||||
@@ -383,4 +390,16 @@ class AssHandler(
|
||||
*/
|
||||
private val Size.isValid
|
||||
get() = width > 0 && height > 0
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Sets the global libass overlay render scale (fraction of the surface resolution; 1.0 = no
|
||||
* downscale). Cheaper raster for the render-bound tail on weak GPUs, at some sharpness. Set
|
||||
* before/at playback init — [AssAtlasPipelineConfig.scaledForRender] reads it on the next
|
||||
* frame-size apply (overlay surface create / size change), so it takes effect from playback.
|
||||
*/
|
||||
fun setRenderScale(scale: Float) {
|
||||
AssAtlasPipelineConfig.renderScale = scale.coerceIn(0.2f, 1.0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+725
-128
File diff suppressed because it is too large
Load Diff
+76
-2
@@ -23,6 +23,7 @@ class AssSubtitleSurfaceView(
|
||||
SurfaceHolder.Callback {
|
||||
|
||||
private var pipeline: AssAtlasPipeline? = null
|
||||
private var preSwapProbe: ((Long) -> Unit)? = null
|
||||
|
||||
init {
|
||||
setZOrderMediaOverlay(true)
|
||||
@@ -30,6 +31,16 @@ class AssSubtitleSurfaceView(
|
||||
holder.addCallback(this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook invoked on the GL thread just before each pinned overlay swap, with that swap's target
|
||||
* releaseTimeNs. Set by the app's latency calibrator; cleared (null) once it converges.
|
||||
* Survives pipeline recreation (re-applied in [surfaceCreated]).
|
||||
*/
|
||||
fun setPreSwapProbe(hook: ((Long) -> Unit)?) {
|
||||
preSwapProbe = hook
|
||||
pipeline?.preSwapProbe = hook
|
||||
}
|
||||
|
||||
fun requestRender(presentationTimeUs: Long, releaseTimeNs: Long) {
|
||||
pipeline?.requestRender(presentationTimeUs, releaseTimeNs)
|
||||
}
|
||||
@@ -75,20 +86,83 @@ class AssSubtitleSurfaceView(
|
||||
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
|
||||
val specSkips: Long get() = pipeline?.specSkips ?: 0L
|
||||
|
||||
/** changed==0/no-output renders forced into explicit transparent swaps. */
|
||||
val blankClearCount: Long get() = pipeline?.blankClearCount ?: 0L
|
||||
|
||||
/** Cache-warming prefetch renders of upcoming events. */
|
||||
val prefetchCount: Long get() = pipeline?.prefetchCount ?: 0L
|
||||
|
||||
/** Frame requests replaced before the libass worker serviced them. */
|
||||
val coalescedRequestCount: Long get() = pipeline?.coalescedRequestCount ?: 0L
|
||||
|
||||
/** Completed libass results discarded because renderer state changed before handoff. */
|
||||
val staleGenerationCount: Long get() = pipeline?.staleGenerationCount ?: 0L
|
||||
|
||||
/** Completed overlay snapshots skipped because newer completed content superseded them. */
|
||||
val supersededBeforeSwapCount: Long get() = pipeline?.supersededBeforeSwapCount ?: 0L
|
||||
|
||||
/** Completed overlay snapshots skipped because renderer state changed before swap. */
|
||||
val staleBeforeSwapCount: Long get() = pipeline?.staleBeforeSwapCount ?: 0L
|
||||
|
||||
/** Minimum lead of changed-content pinned swaps vs the video frame's release
|
||||
* time, in ms (negative = late); null until one happened. */
|
||||
val minLeadChangedMs: Long? get() = pipeline?.minLeadChangedMs?.takeIf { it != Long.MAX_VALUE }
|
||||
|
||||
/** Current compositor phase lead applied by the atlas pipeline, in ms. */
|
||||
val phaseLeadMs: Long get() = pipeline?.phaseLeadMs ?: 0L
|
||||
|
||||
/** Most recent pinned swap lead vs its target release time, in ms. */
|
||||
val lastSwapLeadMs: Long get() = pipeline?.lastSwapLeadMs ?: 0L
|
||||
|
||||
/** Most recent pinned swap headroom when GL work started, in ms. */
|
||||
val lastSwapHeadroomMs: Long get() = pipeline?.lastSwapHeadroomMs ?: 0L
|
||||
|
||||
/** Most recent phase-led wait before swap, in ms. */
|
||||
val lastScheduledSleepMs: Long get() = pipeline?.lastScheduledSleepMs ?: 0L
|
||||
|
||||
/** Adaptive swap lead actually in effect (half the measured refresh interval), in ms. */
|
||||
val swapLeadMs: Long get() = pipeline?.swapLeadMs ?: 0L
|
||||
|
||||
/** True once the EGL frame-timestamp extension is probed and capturing present
|
||||
* times (API 26+, real device). False on the emulator / pre-26 / no driver support. */
|
||||
val presentTimingEnabled: Boolean get() = pipeline?.presentTimingEnabled ?: false
|
||||
|
||||
/** Active present-time source, or why it's off (present/comp-start/comp-latch/off:…). */
|
||||
val presentSource: String get() = pipeline?.presentSource ?: "off:no-pipeline"
|
||||
|
||||
/** Actual on-screen present time of the most recent measured swap minus its
|
||||
* target release time, in ms (negative = before the video frame's vsync). The
|
||||
* frame-perfection ground truth; null until a swap has been measured. */
|
||||
val lastPresentErrorMs: Long? get() = pipeline?.lastPresentErrorMs.takeIf { presentMeasuredCount > 0 }
|
||||
|
||||
/** Largest-magnitude present error observed, in ms; null until measured. */
|
||||
val worstPresentErrorMs: Long? get() = pipeline?.worstPresentErrorMs.takeIf { presentMeasuredCount > 0 }
|
||||
|
||||
/** Pinned swaps whose actual present time was read back from SurfaceFlinger. */
|
||||
val presentMeasuredCount: Long get() = pipeline?.presentMeasuredCount ?: 0L
|
||||
|
||||
/** Swaps SurfaceFlinger reported as dropped/never-presented. */
|
||||
val presentInvalidCount: Long get() = pipeline?.presentInvalidCount ?: 0L
|
||||
|
||||
/** Pending present-time reads evicted unread because the ring filled. */
|
||||
val presentDroppedCount: Long get() = pipeline?.presentDroppedCount ?: 0L
|
||||
|
||||
/** Present-error distribution in vsync-interval units:
|
||||
* [≤−1.5, (−1.5,−0.5), (−0.5,+0.5), [+0.5,+1.5), ≥+1.5]. Middle = frame-perfect. */
|
||||
val presentErrorHistogram: List<Long> get() = pipeline?.presentErrorHistogram ?: emptyList()
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
val rect = holder.surfaceFrame
|
||||
assHandler.setOverlaySurfaceSize(rect.width(), rect.height())
|
||||
val lowRam = (context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)
|
||||
?.isLowRamDevice ?: false
|
||||
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam)
|
||||
.also { it.start() }
|
||||
// Display refresh drives the present-error histogram's vsync-relative buckets.
|
||||
val refreshRate = display?.refreshRate?.takeIf { it >= 1f } ?: 60f
|
||||
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam, refreshRate)
|
||||
.also {
|
||||
it.preSwapProbe = preSwapProbe
|
||||
it.start()
|
||||
}
|
||||
}
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
|
||||
+35
-13
@@ -1,7 +1,6 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* Decision core of the speculative render-ahead pipeline.
|
||||
@@ -99,6 +98,10 @@ internal class SpecRenderEngine(
|
||||
var specSkips = 0L
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var blankClearCount = 0L
|
||||
private set
|
||||
|
||||
/**
|
||||
* Services a render request for [ptsUs]. [pinned] is false for invalidate
|
||||
* repaints (paused margin changes etc.), which never feed the cadence
|
||||
@@ -107,10 +110,11 @@ internal class SpecRenderEngine(
|
||||
fun service(ptsUs: Long, pinned: Boolean): Outcome {
|
||||
if (pinned) updateDeltaEstimator(ptsUs)
|
||||
|
||||
val ptsMs = toLibassMs(ptsUs)
|
||||
if (specPtsUs != UNSET) {
|
||||
val eps = epsilonUs()
|
||||
val specPtsMs = toLibassMs(specPtsUs)
|
||||
val genNow = stateGeneration()
|
||||
val hit = genNow == specGen && eps > 0 && abs(ptsUs - specPtsUs) <= eps
|
||||
val hit = genNow == specGen && ptsMs == specPtsMs
|
||||
val slot = if (specIsLibassLast) libassLastSlot else specSlot
|
||||
val frame = libassLastFrame
|
||||
val specPts = specPtsUs
|
||||
@@ -118,23 +122,32 @@ internal class SpecRenderEngine(
|
||||
if (hit && slot >= 0 && frame != null) {
|
||||
specHits++
|
||||
lastPostedSlot = slot
|
||||
debugLog?.invoke("hit pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms slot=$slot")
|
||||
debugLog?.invoke(
|
||||
"hit pts=${ptsMs}ms spec=${specPtsMs}ms dUs=${ptsUs - specPts} slot=$slot"
|
||||
)
|
||||
return Outcome.Post(slot, frame, newContent = false, specHit = true)
|
||||
}
|
||||
specMisses++
|
||||
debugLog?.invoke(
|
||||
"miss pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms eps=${eps / 1000}ms " +
|
||||
"miss pts=${ptsMs}ms spec=${specPtsMs}ms dUs=${ptsUs - specPts} " +
|
||||
"gen=${if (genNow == specGen) "ok" else "CHANGED"} slot=$slot frame=${frame != null}"
|
||||
)
|
||||
} else {
|
||||
debugLog?.invoke("no-spec pts=${ptsUs / 1000}ms")
|
||||
debugLog?.invoke("no-spec pts=${ptsMs}ms")
|
||||
}
|
||||
|
||||
// On-demand render. Preferring libassLastSlot as the target makes changed == 0
|
||||
// unambiguous: the buffers were untouched and already hold the right content.
|
||||
// On-demand render. For changed == 0 with visible output, the buffers were
|
||||
// untouched and libassLastSlot already holds the right content.
|
||||
val target = renderTargetSlot() ?: return Outcome.Skip
|
||||
val frame = renderAt(ptsUs / 1000, target) ?: return Outcome.Skip
|
||||
val frame = renderAt(ptsMs, target) ?: return Outcome.Skip
|
||||
if (frame.changed == 0) {
|
||||
if (isImplicitBlank(frame)) {
|
||||
blankClearCount++
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
lastPostedSlot = target
|
||||
return Outcome.Post(target, frame, newContent = true, specHit = false)
|
||||
}
|
||||
val lastSlot = libassLastSlot
|
||||
val lastFrame = libassLastFrame ?: return Outcome.Skip
|
||||
if (lastSlot < 0) return Outcome.Skip
|
||||
@@ -169,13 +182,21 @@ internal class SpecRenderEngine(
|
||||
}
|
||||
val gen = stateGeneration()
|
||||
val specPts = servicedPtsUs + medianDeltaUs()
|
||||
val frame = renderAt(specPts / 1000, target) ?: run {
|
||||
val frame = renderAt(toLibassMs(specPts), target) ?: run {
|
||||
specSkips++
|
||||
return null
|
||||
}
|
||||
specGen = gen
|
||||
specPtsUs = specPts
|
||||
if (frame.changed == 0) {
|
||||
if (isImplicitBlank(frame)) {
|
||||
blankClearCount++
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
specIsLibassLast = false
|
||||
specSlot = target
|
||||
return SpecWrite(target, frame)
|
||||
}
|
||||
// Content at specPts is identical to libass's last render — nothing was
|
||||
// written; a hit will repost libassLastSlot (and GL will skip the upload).
|
||||
specIsLibassLast = true
|
||||
@@ -189,6 +210,8 @@ internal class SpecRenderEngine(
|
||||
return SpecWrite(target, frame)
|
||||
}
|
||||
|
||||
private fun isImplicitBlank(frame: AssAtlasFrame): Boolean = !frame.hasOutput && libassLastFrame?.hasOutput == true
|
||||
|
||||
/**
|
||||
* Pre-renders [ptsUs] (an upcoming event's start) purely to warm the
|
||||
* renderer's glyph/bitmap caches before that content is actually needed —
|
||||
@@ -204,7 +227,7 @@ internal class SpecRenderEngine(
|
||||
fun prefetch(ptsUs: Long): SpecWrite? {
|
||||
specPtsUs = UNSET
|
||||
val target = renderTargetSlot() ?: return null
|
||||
val frame = renderAt(ptsUs / 1000, target) ?: return null
|
||||
val frame = renderAt(toLibassMs(ptsUs), target) ?: return null
|
||||
prefetchCount++
|
||||
if (frame.changed == 0) return null
|
||||
libassLastSlot = target
|
||||
@@ -253,13 +276,12 @@ internal class SpecRenderEngine(
|
||||
return copy[deltaCount / 2]
|
||||
}
|
||||
|
||||
private fun epsilonUs(): Long = if (deltaValid()) minOf(medianDeltaUs() / 2, EPSILON_CAP_US) else 0L
|
||||
private fun toLibassMs(ptsUs: Long): Long = Math.floorDiv(ptsUs, 1_000L)
|
||||
|
||||
private companion object {
|
||||
const val UNSET = Long.MIN_VALUE
|
||||
const val DELTA_SAMPLES = 8
|
||||
const val MIN_DELTA_SAMPLES = 4
|
||||
const val MAX_DELTA_US = 250_000L
|
||||
const val EPSILON_CAP_US = 8_000L
|
||||
}
|
||||
}
|
||||
|
||||
+76
-5
@@ -53,7 +53,9 @@ class SpecRenderEngineTest {
|
||||
|
||||
fun changed(quads: Int = 5) = AssAtlasFrame(2048, 100, quads, 2, 0)
|
||||
|
||||
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0)
|
||||
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = true)
|
||||
|
||||
fun blankUnchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = false)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -74,15 +76,40 @@ class SpecRenderEngineTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hit tolerates jitter within epsilon`() {
|
||||
fun `hit tolerates jitter only within the same libass millisecond`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
val outcome = h.engine.service(last + DELTA + 3_000, pinned = true)
|
||||
val outcome = h.engine.service(last + DELTA + 999, pinned = true)
|
||||
|
||||
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `jitter crossing a libass millisecond boundary misses`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
val before = h.calls.size
|
||||
|
||||
h.script.add(changed())
|
||||
val outcome = h.engine.service(last + DELTA + 1_000, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
assertEquals(before + 1, h.calls.size)
|
||||
assertEquals(1L, h.engine.specMisses)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `negative pts floors to the preceding libass millisecond`() {
|
||||
val h = Harness()
|
||||
|
||||
h.script.add(changed())
|
||||
h.engine.service(-1, pinned = true)
|
||||
|
||||
assertEquals(-1L, h.calls.last().timeMs)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `seek misses and renders on demand into the spec slot`() {
|
||||
val h = Harness()
|
||||
@@ -201,6 +228,23 @@ class SpecRenderEngineTest {
|
||||
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `changed 0 without output clears previous content`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
|
||||
h.script.add(blankUnchanged())
|
||||
val outcome = h.engine.service(DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
|
||||
assertTrue(outcome.newContent)
|
||||
assertFalse(outcome.specHit)
|
||||
assertFalse(outcome.frame.hasOutput)
|
||||
assertEquals(0, outcome.frame.quadCount)
|
||||
assertTrue("blank frame should use a fresh metadata slot", outcome.slot != first.slot)
|
||||
assertEquals(1L, h.engine.blankClearCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `renderer gone skips`() {
|
||||
val h = Harness()
|
||||
@@ -228,7 +272,7 @@ class SpecRenderEngineTest {
|
||||
// last-rendered slot so GL skips the upload entirely.
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
h.engine.service(0, pinned = true)
|
||||
var pts = 0L
|
||||
repeat(4) {
|
||||
// build cadence; renders return changed for simplicity
|
||||
@@ -243,7 +287,34 @@ class SpecRenderEngineTest {
|
||||
assertTrue(outcome.specHit)
|
||||
assertFalse(outcome.newContent)
|
||||
assertEquals(before, h.calls.size)
|
||||
assertNotNull(first) // first slot existed; hit reposts whichever slot was last rendered
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `speculative changed 0 without output clears on hit`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
h.engine.service(0, pinned = true)
|
||||
var pts = 0L
|
||||
repeat(4) {
|
||||
pts += DELTA
|
||||
h.script.add(changed())
|
||||
h.engine.service(pts, pinned = true)
|
||||
}
|
||||
|
||||
h.script.add(blankUnchanged())
|
||||
val write = h.engine.speculateAfter(pts, pinned = true, hasPending = false)
|
||||
assertNotNull(write)
|
||||
assertFalse(write!!.frame.hasOutput)
|
||||
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(pts + DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
|
||||
assertTrue(outcome.specHit)
|
||||
assertFalse(outcome.newContent)
|
||||
assertFalse(outcome.frame.hasOutput)
|
||||
assertEquals(0, outcome.frame.quadCount)
|
||||
assertEquals(before, h.calls.size)
|
||||
assertEquals(1L, h.engine.blankClearCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -24,6 +24,4 @@ plugins {
|
||||
}
|
||||
|
||||
include(":app")
|
||||
// libass subtitle module (Kotlin/JNI bindings + Media3 glue); the native libass
|
||||
// core stays the upstream Maven artifact io.github.peerless2012:ass.
|
||||
include(":libass")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96"><path fill="currentColor" fill-rule="evenodd" d="M48 96C74.5097 96 96 74.5097 96 48C96 21.4903 74.5097 0 48 0C21.4903 0 0 21.4903 0 48C0 74.5097 21.4903 96 48 96ZM80.0001 52C80.0001 67.464 67.4641 80 52.0001 80C36.5361 80 24.0001 67.464 24.0001 52C24.0001 49.1303 24.4318 46.3615 25.2338 43.7548C27.4288 48.6165 32.3194 52 38.0001 52C45.7321 52 52.0001 45.732 52.0001 38C52.0001 32.3192 48.6166 27.4287 43.755 25.2337C46.3616 24.4317 49.1304 24 52.0001 24C67.4641 24 80.0001 36.536 80.0001 52Z" clip-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 583 B |
@@ -22,6 +22,9 @@
|
||||
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
|
||||
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */; };
|
||||
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */; };
|
||||
B1D51A6A2F0011000000000C /* MpvAudioPlayerCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F0011000000000D /* MpvAudioPlayerCore.swift */; };
|
||||
B1D51A6A2F0011000000000E /* MpvAudioPlayerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F0011000000000F /* MpvAudioPlayerPlugin.swift */; };
|
||||
B1D51A6A2F0011000000000A /* AtmosProbePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F0011000000000B /* AtmosProbePlugin.swift */; };
|
||||
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */; };
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
||||
/* End PBXBuildFile section */
|
||||
@@ -75,6 +78,9 @@
|
||||
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvPlayerCoreBase.swift; path = ../shared/apple/MpvPlayer/MpvPlayerCoreBase.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvPlayerPluginShared.swift; path = ../shared/apple/MpvPlayer/MpvPlayerPluginShared.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F0011000000000D /* MpvAudioPlayerCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvAudioPlayerCore.swift; path = ../shared/apple/MpvPlayer/MpvAudioPlayerCore.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F0011000000000F /* MpvAudioPlayerPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvAudioPlayerPlugin.swift; path = ../shared/apple/MpvPlayer/MpvAudioPlayerPlugin.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F0011000000000B /* AtmosProbePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AtmosProbePlugin.swift; path = ../shared/apple/AtmosProbe/AtmosProbePlugin.swift; sourceTree = SOURCE_ROOT; };
|
||||
B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalDisplayManager.swift; sourceTree = "<group>"; };
|
||||
BB346A1D0705AB171F80B11B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
DE48FF2E074644167608B23D /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
|
||||
@@ -126,6 +132,9 @@
|
||||
children = (
|
||||
B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */,
|
||||
B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */,
|
||||
B1D51A6A2F0011000000000D /* MpvAudioPlayerCore.swift */,
|
||||
B1D51A6A2F0011000000000F /* MpvAudioPlayerPlugin.swift */,
|
||||
B1D51A6A2F0011000000000B /* AtmosProbePlugin.swift */,
|
||||
B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */,
|
||||
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */,
|
||||
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */,
|
||||
@@ -417,6 +426,9 @@
|
||||
files = (
|
||||
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */,
|
||||
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */,
|
||||
B1D51A6A2F0011000000000C /* MpvAudioPlayerCore.swift in Sources */,
|
||||
B1D51A6A2F0011000000000E /* MpvAudioPlayerPlugin.swift in Sources */,
|
||||
B1D51A6A2F0011000000000A /* AtmosProbePlugin.swift in Sources */,
|
||||
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */,
|
||||
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */,
|
||||
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */,
|
||||
@@ -715,6 +727,7 @@
|
||||
MARKETING_VERSION = 1.0.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.edde746.plezy;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
@@ -788,8 +801,8 @@
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/edde746/MPVKit";
|
||||
requirement = {
|
||||
kind = revision;
|
||||
revision = 245b69dce22156e81b79c84cfcb748358b674e47;
|
||||
kind = exactVersion;
|
||||
version = 1.0.12;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
|
||||
"revision" : "a453d675493a8abe26dc90f9dc484bc582628358",
|
||||
"version" : "1.0.12"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -57,8 +58,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/getsentry/sentry-cocoa",
|
||||
"state" : {
|
||||
"revision" : "16cd512711375fa73f25ae5e373f596bdf4251ae",
|
||||
"version" : "8.58.0"
|
||||
"revision" : "dad229c665bfd043c5d80ac7aa77717cbd19a1c3",
|
||||
"version" : "8.58.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
|
||||
"revision" : "a453d675493a8abe26dc90f9dc484bc582628358",
|
||||
"version" : "1.0.12"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -14,11 +14,12 @@ import MediaPlayer
|
||||
_ application: UIApplication,
|
||||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
|
||||
) -> Bool {
|
||||
// Configure audio session for media playback
|
||||
// Configure audio session for media playback. Not activated here: the
|
||||
// session is non-mixing, so activation stops other apps' audio — it is
|
||||
// claimed when playback actually starts.
|
||||
do {
|
||||
let session = AVAudioSession.sharedInstance()
|
||||
try session.setCategory(.playback, mode: .default)
|
||||
try session.setActive(true)
|
||||
} catch {
|
||||
print("Failed to configure audio session: \(error)")
|
||||
}
|
||||
@@ -36,6 +37,15 @@ import MediaPlayer
|
||||
MpvPlayerPlugin.register(with: registrar)
|
||||
}
|
||||
|
||||
// Register the audio-only MPV player plugin (music playback)
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "MpvAudioPlayerPlugin") {
|
||||
MpvAudioPlayerPlugin.register(with: registrar)
|
||||
}
|
||||
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "AtmosProbePlugin") {
|
||||
AtmosProbePlugin.register(with: registrar)
|
||||
}
|
||||
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "DeviceAdjustmentChannel") {
|
||||
registerDeviceAdjustmentChannel(messenger: registrar.messenger())
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import Flutter
|
||||
import UIKit
|
||||
import XCTest
|
||||
|
||||
class RunnerTests: XCTestCase {
|
||||
|
||||
func testExample() {
|
||||
// If you add code to the Runner application, consider adding tests here.
|
||||
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import '../media/media_backend.dart';
|
||||
import '../models/plex/plex_home_user.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../utils/url_utils.dart';
|
||||
|
||||
/// Identifier of a backend kind a [Connection] points at. Lighter-weight than
|
||||
/// [MediaBackend] for places that only care about persistence/auth shape
|
||||
@@ -233,7 +234,7 @@ class JellyfinConnection extends Connection {
|
||||
|
||||
JellyfinConnection({
|
||||
required this.id,
|
||||
required this.baseUrl,
|
||||
required String baseUrl,
|
||||
List<String>? baseUrls,
|
||||
required this.serverName,
|
||||
required this.serverMachineId,
|
||||
@@ -245,7 +246,8 @@ class JellyfinConnection extends Connection {
|
||||
this.status = ConnectionStatus.unknown,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
}) : baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
|
||||
}) : baseUrl = canonicalizeBaseUrl(baseUrl),
|
||||
baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
|
||||
|
||||
@override
|
||||
ConnectionKind get kind => ConnectionKind.jellyfin;
|
||||
@@ -273,9 +275,9 @@ class JellyfinConnection extends Connection {
|
||||
final seen = <String>{};
|
||||
|
||||
void add(String url) {
|
||||
final trimmed = url.trim();
|
||||
if (trimmed.isEmpty || !seen.add(trimmed)) return;
|
||||
result.add(trimmed);
|
||||
final normalized = canonicalizeBaseUrl(url);
|
||||
if (normalized.isEmpty || !seen.add(normalized)) return;
|
||||
result.add(normalized);
|
||||
}
|
||||
|
||||
add(activeBaseUrl);
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
||||
import '../models/plex/plex_home.dart';
|
||||
import '../models/plex/plex_home_user.dart';
|
||||
import '../profiles/profile.dart';
|
||||
import '../profiles/plex_home_cache_codec.dart';
|
||||
import '../profiles/profile_registry.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../services/server_registry.dart';
|
||||
@@ -225,9 +226,7 @@ class ConnectionBootstrap {
|
||||
final raw = storage.getPlexHomeUsersCacheJson(connectionId);
|
||||
if (raw == null || raw.isEmpty) return null;
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is! List) return null;
|
||||
return decoded.whereType<Map<String, dynamic>>().map(PlexHomeUser.fromJson).toList();
|
||||
return decodePlexHomeUsersCache(raw);
|
||||
} catch (e, st) {
|
||||
appLogger.w('Migration: failed to read Plex Home cache for $connectionId', error: e, stackTrace: st);
|
||||
return null;
|
||||
@@ -238,7 +237,7 @@ class ConnectionBootstrap {
|
||||
try {
|
||||
final users = await _plexHomeUserFetcher(account.accountToken);
|
||||
if (users.isNotEmpty) {
|
||||
await storage.savePlexHomeUsersCache(account.id, users.map((u) => u.toJson()).toList());
|
||||
await storage.savePlexHomeUsersCache(account.id, encodePlexHomeUsersCache(users));
|
||||
appLogger.i('Migration: fetched ${users.length} Plex Home users for ${account.id}');
|
||||
}
|
||||
return users;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
|
||||
import '../database/app_database.dart';
|
||||
@@ -41,17 +40,6 @@ class ConnectionRegistry {
|
||||
return _rowToConnection(row);
|
||||
}
|
||||
|
||||
/// Returns the user's preferred connection — either the row marked
|
||||
/// [Connections.isDefault], or the only row if exactly one exists, or
|
||||
/// null when no connections are stored.
|
||||
Future<Connection?> getDefault() async {
|
||||
final rows = await _db.select(_db.connections).get();
|
||||
if (rows.isEmpty) return null;
|
||||
final flagged = rows.firstWhereOrNull((r) => r.isDefault);
|
||||
final picked = flagged ?? (rows.length == 1 ? rows.single : null);
|
||||
return picked == null ? null : _rowToConnection(picked);
|
||||
}
|
||||
|
||||
/// Insert or replace [connection]. If this is the first stored connection
|
||||
/// it is automatically marked default; re-upserting an existing row keeps
|
||||
/// the row's current `isDefault` (so token/metadata refreshes don't clear
|
||||
@@ -130,13 +118,6 @@ class ConnectionRegistry {
|
||||
return all.whereType<PlexAccountConnection>().toList();
|
||||
}
|
||||
|
||||
/// All Jellyfin connections in insertion order. Symmetric helper to
|
||||
/// [listPlexAccounts].
|
||||
Future<List<JellyfinConnection>> listJellyfin() async {
|
||||
final all = await list();
|
||||
return all.whereType<JellyfinConnection>().toList();
|
||||
}
|
||||
|
||||
/// Lookup a [PlexAccountConnection] by id. Returns `null` if no row
|
||||
/// matches OR the row exists but isn't a Plex account.
|
||||
Future<PlexAccountConnection?> getPlexAccount(String id) async {
|
||||
@@ -144,13 +125,6 @@ class ConnectionRegistry {
|
||||
return c is PlexAccountConnection ? c : null;
|
||||
}
|
||||
|
||||
/// Lookup a [JellyfinConnection] by id. Returns `null` if no row matches
|
||||
/// OR the row exists but isn't a Jellyfin connection.
|
||||
Future<JellyfinConnection?> getJellyfin(String id) async {
|
||||
final c = await get(id);
|
||||
return c is JellyfinConnection ? c : null;
|
||||
}
|
||||
|
||||
Future<Connection?> _rowToConnection(ConnectionRow row) async {
|
||||
try {
|
||||
final json = jsonDecode(row.configJson) as Map<String, dynamic>;
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import '../profiles/plex_home_service.dart';
|
||||
import '../profiles/profile_connection_registry.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'connection.dart';
|
||||
import 'connection_registry.dart';
|
||||
|
||||
/// Outcome of [registerPlexAccountFromToken]. [homeUsersFetched] is false
|
||||
/// when the `/home/users` fetch failed — first-sign-in flows can't build
|
||||
/// any profile without it and must not conflate that with "no users".
|
||||
/// [existedBefore] tells add-flows whether a cancelled attach should
|
||||
/// remove the account again (it was created solely for the attach).
|
||||
typedef PlexAccountRegistration = ({
|
||||
PlexAccountConnection connection,
|
||||
bool homeUsersFetched,
|
||||
bool existedBefore,
|
||||
String username,
|
||||
String email,
|
||||
});
|
||||
|
||||
/// Shared post-auth pipeline for a fresh plex.tv [token]: resolve the
|
||||
/// account identity, persist the [PlexAccountConnection] (folding in a
|
||||
/// legacy client-id-keyed row from an earlier failed identity lookup), and
|
||||
/// refresh its Plex Home users. Used by the first-sign-in AuthScreen and
|
||||
/// the add-account settings flow so identity/dedup policy can't drift.
|
||||
Future<PlexAccountRegistration> registerPlexAccountFromToken({
|
||||
required String token,
|
||||
required ConnectionRegistry connections,
|
||||
required ProfileConnectionRegistry profileConnections,
|
||||
required StorageService storage,
|
||||
required PlexHomeService plexHome,
|
||||
}) async {
|
||||
final auth = await PlexAuthService.create();
|
||||
try {
|
||||
// Account identity from plex.tv — the uuid is what makes multi-account
|
||||
// work (the clientIdentifier is per-device and identical for every Plex
|
||||
// account on this install). Falls back to the client identifier only
|
||||
// when the user-info call fails outright; a later successful sign-in
|
||||
// migrates that legacy row below.
|
||||
String username = '';
|
||||
String email = '';
|
||||
String accountUuid = '';
|
||||
try {
|
||||
final info = await auth.getUserInfo(token);
|
||||
username = (info['username'] as String?) ?? '';
|
||||
email = (info['email'] as String?) ?? '';
|
||||
accountUuid = (info['uuid'] as String?)?.trim() ?? '';
|
||||
} catch (e) {
|
||||
appLogger.d('getUserInfo after Plex sign-in failed (using fallback identity): $e');
|
||||
}
|
||||
|
||||
final servers = await auth.fetchServers(token);
|
||||
final connection = PlexAccountConnection(
|
||||
id: 'plex.${accountUuid.isNotEmpty ? accountUuid : auth.clientIdentifier}',
|
||||
accountToken: token,
|
||||
clientIdentifier: auth.clientIdentifier,
|
||||
accountLabel: username.isNotEmpty ? username : (email.isNotEmpty ? email : 'Plex'),
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
);
|
||||
final legacyId = 'plex.${auth.clientIdentifier}';
|
||||
final existedBefore =
|
||||
await connections.get(connection.id) != null ||
|
||||
(accountUuid.isNotEmpty &&
|
||||
legacyId != connection.id &&
|
||||
await connections.get(legacyId) is PlexAccountConnection);
|
||||
await connections.upsert(connection);
|
||||
|
||||
if (accountUuid.isNotEmpty) {
|
||||
await _migrateLegacyClientIdRow(
|
||||
replacement: connection,
|
||||
clientIdentifier: auth.clientIdentifier,
|
||||
connections: connections,
|
||||
profileConnections: profileConnections,
|
||||
storage: storage,
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch home users now so pickers surface the account's virtual
|
||||
// profiles immediately.
|
||||
final homeUsersFetched = await plexHome.refresh(connection);
|
||||
return (
|
||||
connection: connection,
|
||||
homeUsersFetched: homeUsersFetched,
|
||||
existedBefore: existedBefore,
|
||||
username: username,
|
||||
email: email,
|
||||
);
|
||||
} finally {
|
||||
auth.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// A row keyed by the per-device client identifier (created when an earlier
|
||||
/// sign-in couldn't resolve the account uuid) would duplicate the account —
|
||||
/// and collides with every other account on this device. Fold it into the
|
||||
/// uuid-keyed [replacement]: re-point its join rows, then remove it.
|
||||
///
|
||||
/// Virtual profile ids that embedded the legacy account id are not
|
||||
/// rewritten; their (rare) borrowed rows become orphans that the startup
|
||||
/// prune and post-removal settle already clean up.
|
||||
Future<void> _migrateLegacyClientIdRow({
|
||||
required PlexAccountConnection replacement,
|
||||
required String clientIdentifier,
|
||||
required ConnectionRegistry connections,
|
||||
required ProfileConnectionRegistry profileConnections,
|
||||
required StorageService storage,
|
||||
}) async {
|
||||
final legacyId = 'plex.$clientIdentifier';
|
||||
if (legacyId == replacement.id) return;
|
||||
final legacy = await connections.get(legacyId);
|
||||
if (legacy is! PlexAccountConnection) return;
|
||||
|
||||
final rows = await profileConnections.listForConnection(legacyId);
|
||||
for (final row in rows) {
|
||||
await profileConnections.upsert(row.copyWith(connectionId: replacement.id));
|
||||
}
|
||||
await storage.clearPlexHomeUsersCache(legacyId);
|
||||
// The FK cascade drops the legacy rows we just re-pointed copies of.
|
||||
await connections.remove(legacyId);
|
||||
appLogger.i('Migrated legacy Plex account row $legacyId → ${replacement.id}');
|
||||
}
|
||||
@@ -61,7 +61,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase.forTesting(super.e);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 15;
|
||||
int get schemaVersion => 16;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
@@ -214,6 +214,13 @@ class AppDatabase extends _$AppDatabase {
|
||||
() => m.addColumn(downloadedMedia, downloadedMedia.mediaSourceId),
|
||||
);
|
||||
}
|
||||
if (from < 16) {
|
||||
appLogger.i('Adding includeSpecials column to SyncRules (v16 migration)');
|
||||
await _ignoreAlreadyExists(
|
||||
'SyncRules.includeSpecials column',
|
||||
() => m.addColumn(syncRules, syncRules.includeSpecials),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -270,6 +277,23 @@ class AppDatabase extends _$AppDatabase {
|
||||
.get();
|
||||
}
|
||||
|
||||
SimpleSelectStatement<$OfflineWatchProgressTable, OfflineWatchProgressItem> _watchActionsQuery(
|
||||
Expression<bool> Function($OfflineWatchProgressTable table) matchesKey, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
matchesKey(t) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]);
|
||||
}
|
||||
|
||||
/// Get the latest action for a specific item
|
||||
Future<OfflineWatchProgressItem?> getLatestWatchAction(
|
||||
String globalKey, {
|
||||
@@ -278,16 +302,13 @@ class AppDatabase extends _$AppDatabase {
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)])
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
return (_watchActionsQuery(
|
||||
(t) => t.globalKey.equals(globalKey),
|
||||
profileId: profileId,
|
||||
filterProfile: filterProfile,
|
||||
clientScopeId: clientScopeId,
|
||||
filterClientScope: filterClientScope,
|
||||
)..limit(1)).getSingleOrNull();
|
||||
}
|
||||
|
||||
Future<List<OfflineWatchProgressItem>> getWatchActionsForKey(
|
||||
@@ -297,15 +318,13 @@ class AppDatabase extends _$AppDatabase {
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
return _watchActionsQuery(
|
||||
(t) => t.globalKey.equals(globalKey),
|
||||
profileId: profileId,
|
||||
filterProfile: filterProfile,
|
||||
clientScopeId: clientScopeId,
|
||||
filterClientScope: filterClientScope,
|
||||
).get();
|
||||
}
|
||||
|
||||
Future<Map<String, List<OfflineWatchProgressItem>>> getWatchActionsForKeys(
|
||||
@@ -315,15 +334,11 @@ class AppDatabase extends _$AppDatabase {
|
||||
Map<String, String?>? clientScopeIdsByGlobalKey,
|
||||
}) async {
|
||||
if (globalKeys.isEmpty) return const {};
|
||||
final rows =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.isIn(globalKeys) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
final rows = await _watchActionsQuery(
|
||||
(t) => t.globalKey.isIn(globalKeys),
|
||||
profileId: profileId,
|
||||
filterProfile: filterProfile,
|
||||
).get();
|
||||
|
||||
final result = <String, List<OfflineWatchProgressItem>>{};
|
||||
for (final action in rows) {
|
||||
@@ -346,31 +361,13 @@ class AppDatabase extends _$AppDatabase {
|
||||
bool filterProfile = false,
|
||||
Map<String, String?>? clientScopeIdsByGlobalKey,
|
||||
}) async {
|
||||
if (globalKeys.isEmpty) return {};
|
||||
|
||||
// Query all actions for the given keys
|
||||
final allActions =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.isIn(globalKeys) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
|
||||
// Group by globalKey and take the latest (first due to ordering)
|
||||
final result = <String, OfflineWatchProgressItem>{};
|
||||
for (final action in allActions) {
|
||||
if (clientScopeIdsByGlobalKey != null && clientScopeIdsByGlobalKey.containsKey(action.globalKey)) {
|
||||
final expectedScope = clientScopeIdsByGlobalKey[action.globalKey];
|
||||
if (!_clientScopeValuesMatch(action.clientScopeId, expectedScope)) continue;
|
||||
}
|
||||
// Only keep the first (latest) action for each key
|
||||
result.putIfAbsent(action.globalKey, () => action);
|
||||
}
|
||||
|
||||
return result;
|
||||
final actionsByKey = await getWatchActionsForKeys(
|
||||
globalKeys,
|
||||
profileId: profileId,
|
||||
filterProfile: filterProfile,
|
||||
clientScopeIdsByGlobalKey: clientScopeIdsByGlobalKey,
|
||||
);
|
||||
return {for (final entry in actionsByKey.entries) entry.key: entry.value.first};
|
||||
}
|
||||
|
||||
bool _clientScopeValuesMatch(String? actual, String? expected) {
|
||||
@@ -511,6 +508,11 @@ class AppDatabase extends _$AppDatabase {
|
||||
return delete(offlineWatchProgress).go();
|
||||
}
|
||||
|
||||
/// Drop a removed profile's queued watch actions (profile teardown).
|
||||
Future<void> deleteWatchActionsForProfile(String profileId) async {
|
||||
await (delete(offlineWatchProgress)..where((t) => t.profileId.equals(profileId))).go();
|
||||
}
|
||||
|
||||
Future<List<SyncRuleItem>> getSyncRules({String? profileId}) {
|
||||
final query = select(syncRules);
|
||||
if (profileId != null) {
|
||||
@@ -532,6 +534,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
required int episodeCount,
|
||||
int mediaIndex = 0,
|
||||
String downloadFilter = 'unwatched',
|
||||
bool includeSpecials = true,
|
||||
}) async {
|
||||
// [insertOnConflictUpdate] defaults the conflict target to the primary
|
||||
// key (`id`), which is auto-incremented — the conflict never triggers
|
||||
@@ -549,6 +552,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
createdAt: DateTime.now().millisecondsSinceEpoch,
|
||||
mediaIndex: Value(mediaIndex),
|
||||
downloadFilter: Value(downloadFilter),
|
||||
includeSpecials: Value(includeSpecials),
|
||||
),
|
||||
onConflict: DoUpdate(
|
||||
(_) => SyncRulesCompanion(
|
||||
@@ -559,6 +563,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
episodeCount: Value(episodeCount),
|
||||
mediaIndex: Value(mediaIndex),
|
||||
downloadFilter: Value(downloadFilter),
|
||||
includeSpecials: Value(includeSpecials),
|
||||
),
|
||||
target: [syncRules.globalKey],
|
||||
),
|
||||
@@ -611,6 +616,16 @@ class AppDatabase extends _$AppDatabase {
|
||||
await (delete(syncRules)..where((t) => t.globalKey.equals(globalKey))).go();
|
||||
}
|
||||
|
||||
/// Drop a removed profile's sync rules (profile teardown).
|
||||
Future<void> deleteSyncRulesForProfile(String profileId) async {
|
||||
await (delete(syncRules)..where((t) => t.profileId.equals(profileId))).go();
|
||||
}
|
||||
|
||||
/// Drop every sync rule (full logout).
|
||||
Future<void> clearAllSyncRules() async {
|
||||
await delete(syncRules).go();
|
||||
}
|
||||
|
||||
/// Get all downloaded media items (for syncing watch states)
|
||||
Future<List<DownloadedMediaItem>> getAllDownloadedMetadata() {
|
||||
return (select(downloadedMedia)..where((t) => t.status.equals(DownloadStatus.completed.index))).get();
|
||||
|
||||
@@ -3150,6 +3150,21 @@ class $SyncRulesTable extends SyncRules
|
||||
requiredDuringInsert: false,
|
||||
defaultValue: const Constant('unwatched'),
|
||||
);
|
||||
static const VerificationMeta _includeSpecialsMeta = const VerificationMeta(
|
||||
'includeSpecials',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<bool> includeSpecials = GeneratedColumn<bool>(
|
||||
'include_specials',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.bool,
|
||||
requiredDuringInsert: false,
|
||||
defaultConstraints: GeneratedColumn.constraintIsAlways(
|
||||
'CHECK ("include_specials" IN (0, 1))',
|
||||
),
|
||||
defaultValue: const Constant(true),
|
||||
);
|
||||
@override
|
||||
List<GeneratedColumn> get $columns => [
|
||||
id,
|
||||
@@ -3164,6 +3179,7 @@ class $SyncRulesTable extends SyncRules
|
||||
lastExecutedAt,
|
||||
mediaIndex,
|
||||
downloadFilter,
|
||||
includeSpecials,
|
||||
];
|
||||
@override
|
||||
String get aliasedName => _alias ?? actualTableName;
|
||||
@@ -3267,6 +3283,15 @@ class $SyncRulesTable extends SyncRules
|
||||
),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('include_specials')) {
|
||||
context.handle(
|
||||
_includeSpecialsMeta,
|
||||
includeSpecials.isAcceptableOrUnknown(
|
||||
data['include_specials']!,
|
||||
_includeSpecialsMeta,
|
||||
),
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -3324,6 +3349,10 @@ class $SyncRulesTable extends SyncRules
|
||||
DriftSqlType.string,
|
||||
data['${effectivePrefix}download_filter'],
|
||||
)!,
|
||||
includeSpecials: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}include_specials'],
|
||||
)!,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3346,6 +3375,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
final int? lastExecutedAt;
|
||||
final int mediaIndex;
|
||||
final String downloadFilter;
|
||||
final bool includeSpecials;
|
||||
const SyncRuleItem({
|
||||
required this.id,
|
||||
required this.profileId,
|
||||
@@ -3359,6 +3389,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
this.lastExecutedAt,
|
||||
required this.mediaIndex,
|
||||
required this.downloadFilter,
|
||||
required this.includeSpecials,
|
||||
});
|
||||
@override
|
||||
Map<String, Expression> toColumns(bool nullToAbsent) {
|
||||
@@ -3377,6 +3408,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
}
|
||||
map['media_index'] = Variable<int>(mediaIndex);
|
||||
map['download_filter'] = Variable<String>(downloadFilter);
|
||||
map['include_specials'] = Variable<bool>(includeSpecials);
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -3396,6 +3428,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
: Value(lastExecutedAt),
|
||||
mediaIndex: Value(mediaIndex),
|
||||
downloadFilter: Value(downloadFilter),
|
||||
includeSpecials: Value(includeSpecials),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3417,6 +3450,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
lastExecutedAt: serializer.fromJson<int?>(json['lastExecutedAt']),
|
||||
mediaIndex: serializer.fromJson<int>(json['mediaIndex']),
|
||||
downloadFilter: serializer.fromJson<String>(json['downloadFilter']),
|
||||
includeSpecials: serializer.fromJson<bool>(json['includeSpecials']),
|
||||
);
|
||||
}
|
||||
@override
|
||||
@@ -3435,6 +3469,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
'lastExecutedAt': serializer.toJson<int?>(lastExecutedAt),
|
||||
'mediaIndex': serializer.toJson<int>(mediaIndex),
|
||||
'downloadFilter': serializer.toJson<String>(downloadFilter),
|
||||
'includeSpecials': serializer.toJson<bool>(includeSpecials),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3451,6 +3486,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
Value<int?> lastExecutedAt = const Value.absent(),
|
||||
int? mediaIndex,
|
||||
String? downloadFilter,
|
||||
bool? includeSpecials,
|
||||
}) => SyncRuleItem(
|
||||
id: id ?? this.id,
|
||||
profileId: profileId ?? this.profileId,
|
||||
@@ -3466,6 +3502,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
: this.lastExecutedAt,
|
||||
mediaIndex: mediaIndex ?? this.mediaIndex,
|
||||
downloadFilter: downloadFilter ?? this.downloadFilter,
|
||||
includeSpecials: includeSpecials ?? this.includeSpecials,
|
||||
);
|
||||
SyncRuleItem copyWithCompanion(SyncRulesCompanion data) {
|
||||
return SyncRuleItem(
|
||||
@@ -3491,6 +3528,9 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
downloadFilter: data.downloadFilter.present
|
||||
? data.downloadFilter.value
|
||||
: this.downloadFilter,
|
||||
includeSpecials: data.includeSpecials.present
|
||||
? data.includeSpecials.value
|
||||
: this.includeSpecials,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3508,7 +3548,8 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
..write('createdAt: $createdAt, ')
|
||||
..write('lastExecutedAt: $lastExecutedAt, ')
|
||||
..write('mediaIndex: $mediaIndex, ')
|
||||
..write('downloadFilter: $downloadFilter')
|
||||
..write('downloadFilter: $downloadFilter, ')
|
||||
..write('includeSpecials: $includeSpecials')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
@@ -3527,6 +3568,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
lastExecutedAt,
|
||||
mediaIndex,
|
||||
downloadFilter,
|
||||
includeSpecials,
|
||||
);
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
@@ -3543,7 +3585,8 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
|
||||
other.createdAt == this.createdAt &&
|
||||
other.lastExecutedAt == this.lastExecutedAt &&
|
||||
other.mediaIndex == this.mediaIndex &&
|
||||
other.downloadFilter == this.downloadFilter);
|
||||
other.downloadFilter == this.downloadFilter &&
|
||||
other.includeSpecials == this.includeSpecials);
|
||||
}
|
||||
|
||||
class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
@@ -3559,6 +3602,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
final Value<int?> lastExecutedAt;
|
||||
final Value<int> mediaIndex;
|
||||
final Value<String> downloadFilter;
|
||||
final Value<bool> includeSpecials;
|
||||
const SyncRulesCompanion({
|
||||
this.id = const Value.absent(),
|
||||
this.profileId = const Value.absent(),
|
||||
@@ -3572,6 +3616,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
this.lastExecutedAt = const Value.absent(),
|
||||
this.mediaIndex = const Value.absent(),
|
||||
this.downloadFilter = const Value.absent(),
|
||||
this.includeSpecials = const Value.absent(),
|
||||
});
|
||||
SyncRulesCompanion.insert({
|
||||
this.id = const Value.absent(),
|
||||
@@ -3586,6 +3631,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
this.lastExecutedAt = const Value.absent(),
|
||||
this.mediaIndex = const Value.absent(),
|
||||
this.downloadFilter = const Value.absent(),
|
||||
this.includeSpecials = const Value.absent(),
|
||||
}) : serverId = Value(serverId),
|
||||
ratingKey = Value(ratingKey),
|
||||
globalKey = Value(globalKey),
|
||||
@@ -3605,6 +3651,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
Expression<int>? lastExecutedAt,
|
||||
Expression<int>? mediaIndex,
|
||||
Expression<String>? downloadFilter,
|
||||
Expression<bool>? includeSpecials,
|
||||
}) {
|
||||
return RawValuesInsertable({
|
||||
if (id != null) 'id': id,
|
||||
@@ -3619,6 +3666,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
if (lastExecutedAt != null) 'last_executed_at': lastExecutedAt,
|
||||
if (mediaIndex != null) 'media_index': mediaIndex,
|
||||
if (downloadFilter != null) 'download_filter': downloadFilter,
|
||||
if (includeSpecials != null) 'include_specials': includeSpecials,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3635,6 +3683,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
Value<int?>? lastExecutedAt,
|
||||
Value<int>? mediaIndex,
|
||||
Value<String>? downloadFilter,
|
||||
Value<bool>? includeSpecials,
|
||||
}) {
|
||||
return SyncRulesCompanion(
|
||||
id: id ?? this.id,
|
||||
@@ -3649,6 +3698,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
lastExecutedAt: lastExecutedAt ?? this.lastExecutedAt,
|
||||
mediaIndex: mediaIndex ?? this.mediaIndex,
|
||||
downloadFilter: downloadFilter ?? this.downloadFilter,
|
||||
includeSpecials: includeSpecials ?? this.includeSpecials,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3691,6 +3741,9 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
if (downloadFilter.present) {
|
||||
map['download_filter'] = Variable<String>(downloadFilter.value);
|
||||
}
|
||||
if (includeSpecials.present) {
|
||||
map['include_specials'] = Variable<bool>(includeSpecials.value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -3708,7 +3761,8 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
|
||||
..write('createdAt: $createdAt, ')
|
||||
..write('lastExecutedAt: $lastExecutedAt, ')
|
||||
..write('mediaIndex: $mediaIndex, ')
|
||||
..write('downloadFilter: $downloadFilter')
|
||||
..write('downloadFilter: $downloadFilter, ')
|
||||
..write('includeSpecials: $includeSpecials')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
@@ -6842,6 +6896,7 @@ typedef $$SyncRulesTableCreateCompanionBuilder =
|
||||
Value<int?> lastExecutedAt,
|
||||
Value<int> mediaIndex,
|
||||
Value<String> downloadFilter,
|
||||
Value<bool> includeSpecials,
|
||||
});
|
||||
typedef $$SyncRulesTableUpdateCompanionBuilder =
|
||||
SyncRulesCompanion Function({
|
||||
@@ -6857,6 +6912,7 @@ typedef $$SyncRulesTableUpdateCompanionBuilder =
|
||||
Value<int?> lastExecutedAt,
|
||||
Value<int> mediaIndex,
|
||||
Value<String> downloadFilter,
|
||||
Value<bool> includeSpecials,
|
||||
});
|
||||
|
||||
class $$SyncRulesTableFilterComposer
|
||||
@@ -6927,6 +6983,11 @@ class $$SyncRulesTableFilterComposer
|
||||
column: $table.downloadFilter,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<bool> get includeSpecials => $composableBuilder(
|
||||
column: $table.includeSpecials,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$SyncRulesTableOrderingComposer
|
||||
@@ -6997,6 +7058,11 @@ class $$SyncRulesTableOrderingComposer
|
||||
column: $table.downloadFilter,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<bool> get includeSpecials => $composableBuilder(
|
||||
column: $table.includeSpecials,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$SyncRulesTableAnnotationComposer
|
||||
@@ -7053,6 +7119,11 @@ class $$SyncRulesTableAnnotationComposer
|
||||
column: $table.downloadFilter,
|
||||
builder: (column) => column,
|
||||
);
|
||||
|
||||
GeneratedColumn<bool> get includeSpecials => $composableBuilder(
|
||||
column: $table.includeSpecials,
|
||||
builder: (column) => column,
|
||||
);
|
||||
}
|
||||
|
||||
class $$SyncRulesTableTableManager
|
||||
@@ -7098,6 +7169,7 @@ class $$SyncRulesTableTableManager
|
||||
Value<int?> lastExecutedAt = const Value.absent(),
|
||||
Value<int> mediaIndex = const Value.absent(),
|
||||
Value<String> downloadFilter = const Value.absent(),
|
||||
Value<bool> includeSpecials = const Value.absent(),
|
||||
}) => SyncRulesCompanion(
|
||||
id: id,
|
||||
profileId: profileId,
|
||||
@@ -7111,6 +7183,7 @@ class $$SyncRulesTableTableManager
|
||||
lastExecutedAt: lastExecutedAt,
|
||||
mediaIndex: mediaIndex,
|
||||
downloadFilter: downloadFilter,
|
||||
includeSpecials: includeSpecials,
|
||||
),
|
||||
createCompanionCallback:
|
||||
({
|
||||
@@ -7126,6 +7199,7 @@ class $$SyncRulesTableTableManager
|
||||
Value<int?> lastExecutedAt = const Value.absent(),
|
||||
Value<int> mediaIndex = const Value.absent(),
|
||||
Value<String> downloadFilter = const Value.absent(),
|
||||
Value<bool> includeSpecials = const Value.absent(),
|
||||
}) => SyncRulesCompanion.insert(
|
||||
id: id,
|
||||
profileId: profileId,
|
||||
@@ -7139,6 +7213,7 @@ class $$SyncRulesTableTableManager
|
||||
lastExecutedAt: lastExecutedAt,
|
||||
mediaIndex: mediaIndex,
|
||||
downloadFilter: downloadFilter,
|
||||
includeSpecials: includeSpecials,
|
||||
),
|
||||
withReferenceMapper: (p0) => p0
|
||||
.map((e) => (e.readTable(table), BaseReferences(db, table, e)))
|
||||
|
||||
@@ -22,9 +22,8 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
await (delete(downloadOwners)..where((t) => t.profileId.equals(profileId) & t.globalKey.equals(globalKey))).go();
|
||||
}
|
||||
|
||||
Future<void> removeDownloadOwnersForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return;
|
||||
await (delete(downloadOwners)..where((t) => t.profileId.equals(profileId))).go();
|
||||
Future<void> clearAllDownloadOwners() async {
|
||||
await delete(downloadOwners).go();
|
||||
}
|
||||
|
||||
Future<Set<String>> getDownloadOwnerKeysForProfile(String profileId) async {
|
||||
@@ -55,22 +54,32 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
final connectionRows = await select(connections).get();
|
||||
final connectionIds = connectionRows.map((row) => row.id).toSet();
|
||||
return candidates
|
||||
.where((row) {
|
||||
if (localProfileIds.contains(row.profileId)) return true;
|
||||
final plexHome = parsePlexHomeProfileId(row.profileId);
|
||||
if (plexHome != null) return connectionIds.contains(plexHome.accountConnectionId);
|
||||
return localProfileIds.isEmpty;
|
||||
})
|
||||
.where((row) => _isValidDownloadOwner(row, localProfileIds: localProfileIds, connectionIds: connectionIds))
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
/// Claim pre-v17 shared download rows for [profileId]. Rows that already
|
||||
/// have any owner are left untouched so later profiles do not inherit them.
|
||||
/// have any valid owner are left untouched so later profiles do not
|
||||
/// inherit them.
|
||||
///
|
||||
/// Runs on every profile switch — validity context is computed once and
|
||||
/// applied in memory instead of the per-download full-table rescan
|
||||
/// `getDownloadOwnerCount` would do.
|
||||
Future<void> adoptLegacyDownloadsForProfile(String profileId) async {
|
||||
if (profileId.isEmpty) return;
|
||||
final rows = await select(downloadedMedia).get();
|
||||
if (rows.isEmpty) return;
|
||||
|
||||
final owners = await select(downloadOwners).get();
|
||||
final localProfileIds = (await select(profiles).get()).map((row) => row.id).toSet();
|
||||
final connectionIds = (await select(connections).get()).map((row) => row.id).toSet();
|
||||
final ownedKeys = <String>{
|
||||
for (final owner in owners)
|
||||
if (_isValidDownloadOwner(owner, localProfileIds: localProfileIds, connectionIds: connectionIds))
|
||||
owner.globalKey,
|
||||
};
|
||||
for (final row in rows) {
|
||||
if (await getDownloadOwnerCount(row.globalKey) == 0) {
|
||||
if (!ownedKeys.contains(row.globalKey)) {
|
||||
await addDownloadOwner(profileId: profileId, globalKey: row.globalKey);
|
||||
}
|
||||
}
|
||||
@@ -238,6 +247,43 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
.get();
|
||||
}
|
||||
|
||||
/// Downloaded tracks belonging to an album (parentRatingKey). Mirrors
|
||||
/// [getEpisodesBySeason] but filters on type so an id collision with a
|
||||
/// season key can never mix media kinds.
|
||||
Future<List<DownloadedMediaItem>> getTracksByAlbum(
|
||||
String albumKey, {
|
||||
ServerId? serverId,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(downloadedMedia)..where(
|
||||
(t) =>
|
||||
t.type.equals('track') &
|
||||
t.parentRatingKey.equals(albumKey) &
|
||||
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
|
||||
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
||||
/// Downloaded tracks belonging to an artist (grandparentRatingKey). Mirrors
|
||||
/// [getEpisodesByShow] with the same type filter as [getTracksByAlbum].
|
||||
Future<List<DownloadedMediaItem>> getTracksByArtist(
|
||||
String artistKey, {
|
||||
ServerId? serverId,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(downloadedMedia)..where(
|
||||
(t) =>
|
||||
t.type.equals('track') &
|
||||
t.grandparentRatingKey.equals(artistKey) &
|
||||
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
|
||||
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
||||
Future<List<DownloadedMediaItem>> getDownloadsByServerId(ServerId serverId) {
|
||||
return (select(downloadedMedia)..where((t) => t.serverId.equals(serverId))).get();
|
||||
}
|
||||
@@ -271,3 +317,14 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
return item?.bgTaskId;
|
||||
}
|
||||
}
|
||||
|
||||
bool _isValidDownloadOwner(
|
||||
DownloadOwnerItem owner, {
|
||||
required Set<String> localProfileIds,
|
||||
required Set<String> connectionIds,
|
||||
}) {
|
||||
if (localProfileIds.contains(owner.profileId)) return true;
|
||||
final plexHome = parsePlexHomeProfileId(owner.profileId);
|
||||
if (plexHome != null) return connectionIds.contains(plexHome.accountConnectionId);
|
||||
return localProfileIds.isEmpty;
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ class SyncRules extends Table {
|
||||
IntColumn get lastExecutedAt => integer().nullable()();
|
||||
IntColumn get mediaIndex => integer().withDefault(const Constant(0))();
|
||||
TextColumn get downloadFilter => text().withDefault(const Constant('unwatched'))();
|
||||
BoolColumn get includeSpecials => boolean().withDefault(const Constant(true))();
|
||||
}
|
||||
|
||||
/// Persisted media-server connections.
|
||||
@@ -192,9 +193,9 @@ class ProfileConnections extends Table {
|
||||
// No FK on profile_id: Plex Home profiles are virtual (built by
|
||||
// Profile.virtualPlexHome from PlexHomeService's live cache, never
|
||||
// persisted in `profiles`), so an FK here would reject every join row
|
||||
// they need. The two profile-delete sites clean up join rows manually
|
||||
// via ProfileConnectionRegistry.removeAllForProfile before calling
|
||||
// ProfileRegistry.remove.
|
||||
// they need. Profile deletion instead cleans up join rows explicitly
|
||||
// (removeAllProfileConnectionsAndCleanup in profile_connection_cleanup)
|
||||
// before calling ProfileRegistry.remove.
|
||||
TextColumn get profileId => text()();
|
||||
TextColumn get connectionId => text().references(Connections, #id, onDelete: KeyAction.cascade)();
|
||||
TextColumn get userToken => text().withDefault(const Constant(''))();
|
||||
|
||||
@@ -92,6 +92,12 @@ class MediaServerHttpException extends MediaServerException {
|
||||
type == MediaServerHttpErrorType.connectionError ||
|
||||
type == MediaServerHttpErrorType.receiveTimeout;
|
||||
|
||||
/// Whether the request was aborted client-side (client teardown or an
|
||||
/// explicit abort), as opposed to failing against the server. A cancelled
|
||||
/// fetch says nothing about the server's actual content — callers must not
|
||||
/// treat it as an empty result.
|
||||
bool get isCancellation => type == MediaServerHttpErrorType.cancelled;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final parts = <String>[type.name];
|
||||
|
||||
@@ -37,12 +37,17 @@ class CardFocusScope extends InheritedWidget {
|
||||
class CardFocusBorder extends StatelessWidget {
|
||||
const CardFocusBorder({
|
||||
super.key,
|
||||
required this.borderRadius,
|
||||
this.borderRadius = FocusTheme.defaultBorderRadius,
|
||||
this.borderRadii,
|
||||
this.strokeAlign = BorderSide.strokeAlignOutside,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final double borderRadius;
|
||||
|
||||
/// Per-corner radii; overrides [borderRadius] when set (M3E grouped cards).
|
||||
final BorderRadius? borderRadii;
|
||||
|
||||
final double strokeAlign;
|
||||
final Widget child;
|
||||
|
||||
@@ -58,6 +63,7 @@ class CardFocusBorder extends StatelessWidget {
|
||||
context,
|
||||
isFocused: showFocus,
|
||||
borderRadius: borderRadius,
|
||||
radii: borderRadii,
|
||||
borderStrokeAlign: strokeAlign,
|
||||
),
|
||||
child: child,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart' show KeyEventResult, VoidCallback;
|
||||
|
||||
import 'dpad_navigator.dart';
|
||||
|
||||
/// Tracks the timer and physical key state for a D-pad SELECT long press.
|
||||
///
|
||||
/// Focus loss, context-menu dispatch, and transferred/touch gesture suppression
|
||||
/// stay with the caller because their behavior differs between widgets.
|
||||
class DpadSelectLongPressController {
|
||||
static const defaultDuration = Duration(milliseconds: 500);
|
||||
|
||||
Timer? _timer;
|
||||
bool _isKeyDown = false;
|
||||
|
||||
KeyEventResult handleKeyEvent(
|
||||
KeyEvent event, {
|
||||
Duration duration = defaultDuration,
|
||||
required bool Function() isOwnerActive,
|
||||
required VoidCallback onShortPress,
|
||||
required VoidCallback onLongPress,
|
||||
}) {
|
||||
if (!event.logicalKey.isSelectKey) return KeyEventResult.ignored;
|
||||
|
||||
if (event is KeyDownEvent) {
|
||||
// Some platforms report another down instead of a repeat. Only the
|
||||
// transition from up to down may start (or restart) the timer.
|
||||
if (!_isKeyDown) {
|
||||
_isKeyDown = true;
|
||||
_timer?.cancel();
|
||||
_timer = Timer(duration, () {
|
||||
if (!isOwnerActive() || !_isKeyDown) return;
|
||||
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
|
||||
onLongPress();
|
||||
});
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event is KeyRepeatEvent) return KeyEventResult.handled;
|
||||
|
||||
if (event is KeyUpEvent) {
|
||||
final timerWasActive = _timer?.isActive ?? false;
|
||||
_timer?.cancel();
|
||||
if (timerWasActive && _isKeyDown) onShortPress();
|
||||
_isKeyDown = false;
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
_timer?.cancel();
|
||||
_isKeyDown = false;
|
||||
}
|
||||
|
||||
void dispose() => reset();
|
||||
}
|
||||
@@ -24,17 +24,20 @@ class FocusTheme {
|
||||
return Theme.of(context).extension<MonoTokens>()?.fast ?? const Duration(milliseconds: 150);
|
||||
}
|
||||
|
||||
/// [radii] overrides [borderRadius] when per-corner radii are needed
|
||||
/// (M3E grouped cards: large outer / small inner corners).
|
||||
static BoxDecoration focusDecoration(
|
||||
BuildContext context, {
|
||||
required bool isFocused,
|
||||
double borderRadius = defaultBorderRadius,
|
||||
BorderRadius? radii,
|
||||
double borderStrokeAlign = BorderSide.strokeAlignInside,
|
||||
Color? color,
|
||||
}) {
|
||||
final focusColor = color ?? getFocusBorderColor(context);
|
||||
|
||||
return BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
borderRadius: radii ?? BorderRadius.circular(borderRadius),
|
||||
border: Border.all(
|
||||
color: isFocused ? focusColor : Colors.transparent,
|
||||
width: focusBorderWidth,
|
||||
@@ -65,10 +68,32 @@ class FocusTheme {
|
||||
|
||||
/// Build focus decoration with background color instead of border.
|
||||
/// Useful for video controls where it should match the native hover style.
|
||||
static BoxDecoration focusBackgroundDecoration({required bool isFocused, double borderRadius = defaultBorderRadius}) {
|
||||
/// [radii] overrides [borderRadius] when per-corner radii are needed.
|
||||
static BoxDecoration focusBackgroundDecoration({
|
||||
required bool isFocused,
|
||||
double borderRadius = defaultBorderRadius,
|
||||
BorderRadius? radii,
|
||||
}) {
|
||||
return BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
borderRadius: radii ?? BorderRadius.circular(borderRadius),
|
||||
color: isFocused ? Colors.white.withValues(alpha: 0.2) : Colors.transparent,
|
||||
);
|
||||
}
|
||||
|
||||
/// Focus background fill derived from the theme's text color, so it stays
|
||||
/// visible on BOTH light and dark surfaces — the white-based
|
||||
/// [focusBackgroundDecoration] disappears on light ones. This is the mono
|
||||
/// convention used by [TrackRow], the navigation rail, and the music player
|
||||
/// surfaces. Prefer this for any new mono-themed surface.
|
||||
static BoxDecoration textFillFocusDecoration(
|
||||
BuildContext context, {
|
||||
required bool isFocused,
|
||||
double borderRadius = defaultBorderRadius,
|
||||
BorderRadius? radii,
|
||||
}) {
|
||||
return BoxDecoration(
|
||||
borderRadius: radii ?? BorderRadius.circular(borderRadius),
|
||||
color: isFocused ? tokens(context).text.withValues(alpha: 0.12) : Colors.transparent,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import '../widgets/clickable_cursor.dart';
|
||||
import 'focus_theme.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
import 'key_event_utils.dart';
|
||||
import 'owned_focus_node_binding.dart';
|
||||
|
||||
typedef FocusableActionBuilder = Widget Function(BuildContext context, FocusableActionBuildState state);
|
||||
|
||||
@@ -28,6 +29,7 @@ class FocusableAction {
|
||||
final IconData icon;
|
||||
final Color? iconColor;
|
||||
final double iconFill;
|
||||
final double iconSize;
|
||||
|
||||
final String? debugLabel;
|
||||
final FocusNode? focusNode;
|
||||
@@ -42,6 +44,7 @@ class FocusableAction {
|
||||
this.icon = Icons.circle,
|
||||
this.iconColor,
|
||||
this.iconFill = 1.0,
|
||||
this.iconSize = 24,
|
||||
this.debugLabel,
|
||||
this.focusNode,
|
||||
this.autofocus = false,
|
||||
@@ -94,9 +97,8 @@ class FocusableActionBar extends StatefulWidget {
|
||||
}
|
||||
|
||||
class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
late List<OwnedFocusNodeBinding> _focusBindings;
|
||||
late List<FocusNode> _focusNodes;
|
||||
late List<bool> _ownsFocusNodes;
|
||||
late List<VoidCallback> _focusListeners;
|
||||
late List<bool> _focusStates;
|
||||
bool _hasAnyFocus = false;
|
||||
|
||||
@@ -131,27 +133,28 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
}
|
||||
|
||||
void _initNodes() {
|
||||
_focusNodes = List.generate(
|
||||
widget.actions.length,
|
||||
(i) => widget.actions[i].focusNode ?? FocusNode(debugLabel: widget.actions[i].debugLabel ?? 'ActionBar[$i]'),
|
||||
);
|
||||
_ownsFocusNodes = List.generate(widget.actions.length, (i) => widget.actions[i].focusNode == null);
|
||||
_focusListeners = [];
|
||||
_focusStates = List.generate(widget.actions.length, (i) => _focusNodes[i].hasFocus);
|
||||
_hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
|
||||
for (var i = 0; i < _focusNodes.length; i++) {
|
||||
final idx = i;
|
||||
void listener() {
|
||||
final hasFocus = _focusNodes[idx].hasFocus;
|
||||
if (_focusStates[idx] != hasFocus) {
|
||||
setState(() => _focusStates[idx] = hasFocus);
|
||||
}
|
||||
_notifyRowFocusIfChanged();
|
||||
}
|
||||
|
||||
_focusListeners.add(listener);
|
||||
_focusNodes[i].addListener(listener);
|
||||
_focusBindings = [];
|
||||
_focusNodes = [];
|
||||
_focusStates = List<bool>.filled(widget.actions.length, false);
|
||||
for (var i = 0; i < widget.actions.length; i++) {
|
||||
final index = i;
|
||||
final binding = OwnedFocusNodeBinding();
|
||||
binding.bind(
|
||||
externalNode: widget.actions[i].focusNode,
|
||||
debugLabel: widget.actions[i].debugLabel ?? 'ActionBar[$i]',
|
||||
listener: () {
|
||||
final hasFocus = _focusNodes[index].hasFocus;
|
||||
if (_focusStates[index] != hasFocus) {
|
||||
setState(() => _focusStates[index] = hasFocus);
|
||||
}
|
||||
_notifyRowFocusIfChanged();
|
||||
},
|
||||
);
|
||||
_focusBindings.add(binding);
|
||||
_focusNodes.add(binding.node);
|
||||
_focusStates[i] = binding.node.hasFocus;
|
||||
}
|
||||
_hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
|
||||
}
|
||||
|
||||
void _notifyRowFocusIfChanged() {
|
||||
@@ -162,11 +165,8 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
}
|
||||
|
||||
void _disposeNodes() {
|
||||
for (var i = 0; i < _focusNodes.length; i++) {
|
||||
_focusNodes[i].removeListener(_focusListeners[i]);
|
||||
if (_ownsFocusNodes[i]) {
|
||||
_focusNodes[i].dispose();
|
||||
}
|
||||
for (final binding in _focusBindings) {
|
||||
binding.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,7 +181,7 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
final isKeyboard = InputModeTracker.isKeyboardMode(context);
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
|
||||
return Row(
|
||||
final row = Row(
|
||||
mainAxisSize: widget.mainAxisSize,
|
||||
children: [
|
||||
for (var i = 0; i < widget.actions.length; i++) ...[
|
||||
@@ -190,13 +190,20 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
],
|
||||
],
|
||||
);
|
||||
// While focus is outside the row (the common state — the user is browsing
|
||||
// content), every button is equally dimmed, so dim once at row level:
|
||||
// each sub-1.0 opacity is its own saveLayer, i.e. a full render-pass
|
||||
// switch on the tiled GPUs low-end TVs use, and these bars sit on screen
|
||||
// permanently. Per-button dims (below) take over only while the row holds
|
||||
// focus; mid-transition the two multiply, which stays visually seamless.
|
||||
return AnimatedOpacity(opacity: isKeyboard && !_hasAnyFocus ? 0.6 : 1.0, duration: duration, child: row);
|
||||
}
|
||||
|
||||
Widget _buildButton(int index, bool isKeyboard, Duration duration) {
|
||||
final action = widget.actions[index];
|
||||
final isFocused = _focusStates[index];
|
||||
final showFocus = isFocused && isKeyboard;
|
||||
final opacity = isKeyboard && !isFocused ? 0.6 : 1.0;
|
||||
final opacity = isKeyboard && _hasAnyFocus && !isFocused ? 0.6 : 1.0;
|
||||
|
||||
final buildState = FocusableActionBuildState(
|
||||
focusNode: _focusNodes[index],
|
||||
@@ -241,7 +248,7 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
child:
|
||||
action.child ??
|
||||
IconButton(
|
||||
icon: AppIcon(action.icon, fill: action.iconFill, color: action.iconColor),
|
||||
icon: AppIcon(action.icon, size: action.iconSize, fill: action.iconFill, color: action.iconColor),
|
||||
tooltip: action.tooltip,
|
||||
onPressed: action.onPressed,
|
||||
),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user