Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
06bd9d775d | ||
|
|
d6487e24c9 | ||
|
|
c404589382 | ||
|
|
f1689a7794 | ||
|
|
a861a4110f | ||
|
|
e7809b3160 | ||
|
|
edd0618e64 | ||
|
|
849e62df7e | ||
|
|
e1c0df3bd7 | ||
|
|
349b5b0513 | ||
|
|
3ad049cb28 | ||
|
|
656cf1158b | ||
|
|
f3cb508649 | ||
|
|
c39b5a5cf1 | ||
|
|
9ff3099a9d | ||
|
|
c24a2aade0 | ||
|
|
8f862d1ca0 | ||
|
|
b56608f94f | ||
|
|
2876e1bf78 | ||
|
|
ebd850b0d5 | ||
|
|
f3f962a7c9 | ||
|
|
49ae1fdc34 | ||
|
|
dc769bda41 | ||
|
|
75ba6b0627 | ||
|
|
1e40d21bd8 | ||
|
|
3c43874342 | ||
|
|
4f422f1485 | ||
|
|
85d9b6ebab | ||
|
|
90662e2173 | ||
|
|
24980aff95 | ||
|
|
804261605b | ||
|
|
8a65c78999 | ||
|
|
979db254d1 | ||
|
|
18ebe77806 | ||
|
|
0de856e929 | ||
|
|
a6d82b4637 | ||
|
|
acfb79c857 | ||
|
|
dcfe0f8308 | ||
|
|
23a423fe85 | ||
|
|
b2cb874b73 | ||
|
|
f671f367ea | ||
|
|
665603b314 | ||
|
|
0d7dd093c4 | ||
|
|
c849a213f0 | ||
|
|
49ff0854c0 | ||
|
|
5047057521 | ||
|
|
e28e2b9371 | ||
|
|
bb92b6083b | ||
|
|
acdae74587 | ||
|
|
5e4449247b | ||
|
|
c2fe142293 | ||
|
|
431b0f9b0c | ||
|
|
959e6e9398 | ||
|
|
18e47d2327 | ||
|
|
b2e5e02204 | ||
|
|
e6a488a4e2 | ||
|
|
75d0164a8b | ||
|
|
05251edaf3 | ||
|
|
892dfee381 | ||
|
|
7f1eb3a818 | ||
|
|
bd0a0c5d6b | ||
|
|
71b05fd4b2 | ||
|
|
587609d7f6 | ||
|
|
cceba28d0a | ||
|
|
03c623e8c7 | ||
|
|
2b34f4a9d7 | ||
|
|
ad3cc6b986 | ||
|
|
133db721a2 | ||
|
|
a03d30fa45 | ||
|
|
62abd3c30a | ||
|
|
97ba02f45e | ||
|
|
0f1bf5e011 | ||
|
|
d816d82a38 | ||
|
|
c89c88647e | ||
|
|
3599b0b0e1 | ||
|
|
1adb89c6b3 | ||
|
|
7ec1c2ebdc | ||
|
|
7ec062deaf | ||
|
|
a5c7d5b52a | ||
|
|
e54bbd11f1 | ||
|
|
38afdab2e4 | ||
|
|
f214c50c15 | ||
|
|
1fc081ed6b | ||
|
|
cbaed8cdfb | ||
|
|
eac0e26696 | ||
|
|
77af810d1f | ||
|
|
1292d7ac34 | ||
|
|
e75ab94eb9 | ||
|
|
804bea8e9a | ||
|
|
0502dd7ba0 | ||
|
|
3221a0cb1a | ||
|
|
e7efa458e5 | ||
|
|
9b48f26463 | ||
|
|
903b8eced8 | ||
|
|
3753967caf | ||
|
|
516925cf50 | ||
|
|
cd9498abb8 | ||
|
|
18642cae15 | ||
|
|
92063bd58f | ||
|
|
726281ed44 | ||
|
|
e02daa89b8 | ||
|
|
7de7802368 | ||
|
|
d44a8994ce | ||
|
|
42d9168941 | ||
|
|
38616770e5 | ||
|
|
bf7558f80d | ||
|
|
381e82d61a | ||
|
|
9cebcb97c5 | ||
|
|
eef73e6447 | ||
|
|
e8df18e7b2 | ||
|
|
54512b8f93 |
+119
-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,7 +899,7 @@ jobs:
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: ${{ steps.release-files.outputs.files }}
|
||||
draft: true
|
||||
|
||||
+69
-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,56 @@ 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
|
||||
|
||||
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.4.1"
|
||||
sha256 "c0658bf43b793a04755a9beaedd27c05c897f2c72298cd5da6531463baf15e0c"
|
||||
version "2.8.0"
|
||||
sha256 "78df0227fc9a578c259fa7cdda526a2679fe46f5be6620f7a020e18d08f206f5"
|
||||
|
||||
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/
|
||||
|
||||
@@ -23,21 +23,28 @@ val downloadLibmpv by tasks.registering {
|
||||
}
|
||||
}
|
||||
|
||||
val assVersion = "fp-3"
|
||||
val assDir = layout.buildDirectory.dir("libass").get().asFile
|
||||
val assAars = listOf("lib_ass-release.aar", "lib_ass_kt-release.aar", "lib_ass_media-release.aar")
|
||||
|
||||
val downloadLibass by tasks.registering {
|
||||
val stamp = File(assDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == assVersion }
|
||||
// Extract libc++_shared.so from the libmpv AAR so the app source set can package
|
||||
// it with top merge priority (see packaging { jniLibs } and sourceSets below).
|
||||
val extractMpvLibcxx by tasks.registering {
|
||||
dependsOn(downloadLibmpv)
|
||||
val aar = File(mpvDir, mpvAar)
|
||||
val outDir = File(mpvDir, "libcxx")
|
||||
inputs.file(aar)
|
||||
outputs.dir(outDir)
|
||||
doLast {
|
||||
assDir.mkdirs()
|
||||
val baseUrl = "https://github.com/edde746/libass-android/releases/download/$assVersion"
|
||||
assAars.forEach { name ->
|
||||
val dest = File(assDir, name)
|
||||
exec { commandLine("curl", "-sfL", "$baseUrl/$name", "-o", dest.absolutePath) }
|
||||
outDir.deleteRecursively() // drop stale ABIs from a previous AAR version
|
||||
outDir.mkdirs()
|
||||
exec {
|
||||
commandLine(
|
||||
"unzip",
|
||||
"-q",
|
||||
"-o",
|
||||
aar.absolutePath,
|
||||
"jni/*/libc++_shared.so",
|
||||
"-d",
|
||||
outDir.absolutePath
|
||||
)
|
||||
}
|
||||
stamp.writeText(assVersion)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,25 +152,37 @@ android {
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// Resolve conflict between libass-android and libmpv native libraries
|
||||
// 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") {
|
||||
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
|
||||
// order cannot accidentally select the older libc++ copy.
|
||||
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
// Download libdovi before any CMake/native build task
|
||||
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
|
||||
dependsOn(downloadLibdovi)
|
||||
}
|
||||
|
||||
// Download libmpv and libass AARs before compilation
|
||||
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
|
||||
dependsOn(downloadLibmpv)
|
||||
dependsOn(downloadLibass)
|
||||
dependsOn(downloadLibmpv, extractMpvLibcxx)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -186,6 +205,12 @@ dependencies {
|
||||
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
|
||||
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
|
||||
|
||||
// libass-android for ASS/SSA subtitle rendering
|
||||
assAars.forEach { implementation(files(File(assDir, it))) }
|
||||
// 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")
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
<!-- Internet access permissions -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
|
||||
|
||||
|
||||
<!-- PIP and media session foreground service permissions -->
|
||||
@@ -48,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,6 +1,5 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityManager
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
@@ -8,24 +7,22 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.net.Uri
|
||||
import android.media.AudioManager
|
||||
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 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
|
||||
@@ -37,51 +34,34 @@ 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() {
|
||||
|
||||
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) {
|
||||
@@ -190,6 +170,31 @@ class MainActivity : FlutterActivity() {
|
||||
)
|
||||
}
|
||||
|
||||
/** Hardware capability signals used by Dart to pick the visual-effects tier. */
|
||||
private fun getPerformanceSignals(): Map<String, Any> {
|
||||
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
val memoryInfo = ActivityManager.MemoryInfo()
|
||||
activityManager.getMemoryInfo(memoryInfo)
|
||||
return mapOf(
|
||||
// Actual process bitness: low-end TV boxes often run 32-bit userspace.
|
||||
"is64Bit" to Process.is64Bit(),
|
||||
"isLowRamDevice" to activityManager.isLowRamDevice,
|
||||
"totalMemBytes" to memoryInfo.totalMem
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -290,63 +295,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()
|
||||
}
|
||||
|
||||
@@ -362,12 +320,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
|
||||
@@ -377,9 +342,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
|
||||
@@ -393,41 +370,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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,15 +420,21 @@ 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) {
|
||||
"getTvDetection" -> result.success(getAndroidTvDetection())
|
||||
"getDeviceName" -> result.success(getDeviceName())
|
||||
"getPerformanceSignals" -> result.success(getPerformanceSignals())
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DEVICE_ADJUSTMENT_CHANNEL).setMethodCallHandler { call, result ->
|
||||
handleDeviceAdjustmentCall(call.method, call.arguments, result)
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, TEXT_INPUT_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"setNativeTextInputFocused" -> {
|
||||
@@ -470,87 +461,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 packageName = call.argument<String>("package")
|
||||
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
|
||||
}
|
||||
|
||||
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, "video/*")
|
||||
if (grantRead) {
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
if (packageName != null) {
|
||||
setPackage(packageName)
|
||||
}
|
||||
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) }
|
||||
}
|
||||
pendingExternalPlayerResult = result
|
||||
startActivityForResult(intent, EXTERNAL_PLAYER_REQUEST_CODE)
|
||||
} catch (e: android.content.ActivityNotFoundException) {
|
||||
pendingExternalPlayerResult = null
|
||||
result.error("APP_NOT_FOUND", "No app found for package: $packageName", 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 ->
|
||||
@@ -647,31 +558,92 @@ 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)
|
||||
private fun handleDeviceAdjustmentCall(method: String, arguments: Any?, result: MethodChannel.Result) {
|
||||
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)
|
||||
when (method) {
|
||||
"getBrightness" -> result.success(getScreenBrightnessFraction())
|
||||
"setBrightness" -> {
|
||||
setScreenBrightnessFraction(argumentAsDouble(arguments))
|
||||
result.success(null)
|
||||
}
|
||||
"restoreBrightness" -> {
|
||||
restoreScreenBrightness()
|
||||
result.success(null)
|
||||
}
|
||||
"getMediaVolume" -> result.success(getMediaVolumeFraction())
|
||||
"setMediaVolume" -> {
|
||||
setMediaVolumeFraction(argumentAsDouble(arguments))
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
if (launchIntent != null) {
|
||||
startActivity(launchIntent)
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} catch (launchError: Exception) {
|
||||
Log.w(TAG, "Failed to start foreground activity", launchError)
|
||||
false
|
||||
} catch (e: IllegalArgumentException) {
|
||||
result.error("INVALID_ARGUMENT", e.message ?: e.javaClass.simpleName, null)
|
||||
} catch (e: Exception) {
|
||||
result.error("DEVICE_ADJUSTMENT_FAILED", e.message ?: e.javaClass.simpleName, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun argumentAsDouble(arguments: Any?): Double {
|
||||
val value = (arguments as? Number)?.toDouble()
|
||||
?: throw IllegalArgumentException("Expected a numeric value")
|
||||
if (value.isNaN() || value.isInfinite()) {
|
||||
throw IllegalArgumentException("Expected a finite numeric value")
|
||||
}
|
||||
return value.coerceIn(0.0, 1.0)
|
||||
}
|
||||
|
||||
private fun getScreenBrightnessFraction(): Double {
|
||||
val windowBrightness = window.attributes.screenBrightness
|
||||
if (windowBrightness >= 0f) return windowBrightness.coerceIn(0f, 1f).toDouble()
|
||||
|
||||
return try {
|
||||
Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS).coerceIn(0, 255) / 255.0
|
||||
} catch (e: Settings.SettingNotFoundException) {
|
||||
0.5
|
||||
}
|
||||
}
|
||||
|
||||
private fun setScreenBrightnessFraction(value: Double) {
|
||||
if (originalWindowBrightness == null) originalWindowBrightness = window.attributes.screenBrightness
|
||||
val attributes = window.attributes
|
||||
attributes.screenBrightness = value.coerceIn(0.0, 1.0).toFloat()
|
||||
window.attributes = attributes
|
||||
}
|
||||
|
||||
private fun restoreScreenBrightness() {
|
||||
val attributes = window.attributes
|
||||
attributes.screenBrightness = originalWindowBrightness ?: WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
|
||||
window.attributes = attributes
|
||||
originalWindowBrightness = null
|
||||
}
|
||||
|
||||
private fun getMediaVolumeFraction(): Double {
|
||||
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
|
||||
val minVolume = streamMinVolume(audioManager)
|
||||
if (maxVolume <= minVolume) return 0.0
|
||||
|
||||
val volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC).coerceIn(minVolume, maxVolume)
|
||||
return (volume - minVolume).toDouble() / (maxVolume - minVolume).toDouble()
|
||||
}
|
||||
|
||||
private fun setMediaVolumeFraction(value: Double) {
|
||||
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
|
||||
val minVolume = streamMinVolume(audioManager)
|
||||
val target = (minVolume + value.coerceIn(0.0, 1.0) * (maxVolume - minVolume))
|
||||
.roundToInt()
|
||||
.coerceIn(minVolume, maxVolume)
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, target, 0)
|
||||
}
|
||||
|
||||
private fun streamMinVolume(audioManager: AudioManager): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
flutterEngine?.let { engine ->
|
||||
|
||||
@@ -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,202 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.os.Build
|
||||
import android.view.SurfaceControl
|
||||
import android.view.SurfaceView
|
||||
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. */
|
||||
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,206 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.media.audiofx.DynamicsProcessing
|
||||
import android.media.audiofx.LoudnessEnhancer
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
|
||||
/**
|
||||
* Session-bound loudness normalization approximating mpv's
|
||||
* `loudnorm=I=-14:TP=-3:LRA=4` filter (#1289).
|
||||
*
|
||||
* API 28+: DynamicsProcessing with a single full-range compressor band as a
|
||||
* slow AGC plus a limiter for the true-peak ceiling. API 25-27, or when the
|
||||
* device lacks the DynamicsProcessing effect HAL: LoudnessEnhancer (fixed
|
||||
* makeup gain with built-in limiting).
|
||||
*
|
||||
* Effects bind to the audio session, so they survive AudioTrack re-creation
|
||||
* (seeks, format changes) while the session id is stable. They only process
|
||||
* PCM mixer streams — the caller must force decoded PCM output and disable
|
||||
* tunneling while enabled. DynamicsProcessing parameters are per-channel, so
|
||||
* the effect is re-created when the output channel count changes (dialogue
|
||||
* lives in the center channel of 5.1 PCM).
|
||||
*/
|
||||
class AudioNormalizationEffect(private val log: (String, String, String) -> Unit) {
|
||||
|
||||
private companion object {
|
||||
const val EFFECT_PRIORITY = 0
|
||||
|
||||
// DynamicsProcessing — tuned for movie mixes whose dialogue sits around
|
||||
// -27 LUFS: compress above threshold, make up toward I=-14, limit at TP=-3.
|
||||
const val FRAME_DURATION_MS = 10f
|
||||
const val MBC_CUTOFF_HZ = 20_000f
|
||||
const val MBC_ATTACK_MS = 30f
|
||||
const val MBC_RELEASE_MS = 300f
|
||||
const val MBC_RATIO = 4f
|
||||
const val MBC_THRESHOLD_DB = -34f
|
||||
const val MBC_KNEE_DB = 6f
|
||||
const val MBC_NOISE_GATE_DB = -90f // effectively disabled
|
||||
const val MBC_EXPANDER_RATIO = 1f // no downward expansion
|
||||
const val MBC_POST_GAIN_DB = 15f
|
||||
const val LIMITER_ATTACK_MS = 1f
|
||||
const val LIMITER_RELEASE_MS = 60f
|
||||
const val LIMITER_RATIO = 10f
|
||||
const val LIMITER_THRESHOLD_DB = -3f
|
||||
const val DEFAULT_CHANNEL_COUNT = 2
|
||||
const val MAX_CHANNEL_COUNT = 8
|
||||
|
||||
// LoudnessEnhancer fallback: fixed boost, internally limited.
|
||||
const val LOUDNESS_ENHANCER_GAIN_MB = 900 // +9 dB
|
||||
}
|
||||
|
||||
private var dynamicsProcessing: DynamicsProcessing? = null
|
||||
private var loudnessEnhancer: LoudnessEnhancer? = null
|
||||
private var attachedSessionId = 0
|
||||
private var attachedChannelCount = 0
|
||||
|
||||
val isActive: Boolean get() = dynamicsProcessing != null || loudnessEnhancer != null
|
||||
|
||||
/** For stats/QA: which engine is processing. */
|
||||
val describe: String
|
||||
get() = when {
|
||||
dynamicsProcessing != null -> "DynamicsProcessing"
|
||||
loudnessEnhancer != null -> "LoudnessEnhancer"
|
||||
else -> "off"
|
||||
}
|
||||
|
||||
/** Attach to [sessionId]; idempotent for an unchanged (session, channels) pair. */
|
||||
fun attach(sessionId: Int, channelCount: Int?) {
|
||||
val channels = (channelCount ?: DEFAULT_CHANNEL_COUNT).coerceIn(1, MAX_CHANNEL_COUNT)
|
||||
if (sessionId == attachedSessionId && channels == attachedChannelCount && isActive) return
|
||||
release()
|
||||
if (sessionId == 0) return // AUDIO_SESSION_ID_UNSET — retry on onAudioSessionIdChanged
|
||||
attachedSessionId = sessionId
|
||||
attachedChannelCount = channels
|
||||
if (Build.VERSION.SDK_INT >= 28 && tryDynamicsProcessing(sessionId, channels)) return
|
||||
tryLoudnessEnhancer(sessionId)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
dynamicsProcessing?.let { effect ->
|
||||
runCatching { effect.setEnabled(false) }
|
||||
runCatching { effect.release() }
|
||||
}
|
||||
dynamicsProcessing = null
|
||||
loudnessEnhancer?.let { effect ->
|
||||
runCatching { effect.setEnabled(false) }
|
||||
runCatching { effect.release() }
|
||||
}
|
||||
loudnessEnhancer = null
|
||||
attachedSessionId = 0
|
||||
attachedChannelCount = 0
|
||||
}
|
||||
|
||||
@RequiresApi(28)
|
||||
private fun tryDynamicsProcessing(sessionId: Int, channelCount: Int): Boolean = try {
|
||||
val band = DynamicsProcessing.MbcBand(
|
||||
// inUse
|
||||
true,
|
||||
MBC_CUTOFF_HZ,
|
||||
MBC_ATTACK_MS,
|
||||
MBC_RELEASE_MS,
|
||||
MBC_RATIO,
|
||||
MBC_THRESHOLD_DB,
|
||||
MBC_KNEE_DB,
|
||||
MBC_NOISE_GATE_DB,
|
||||
MBC_EXPANDER_RATIO,
|
||||
// preGain
|
||||
0f,
|
||||
MBC_POST_GAIN_DB
|
||||
)
|
||||
val mbc = DynamicsProcessing.Mbc(
|
||||
// inUse
|
||||
true,
|
||||
// enabled
|
||||
true,
|
||||
// bandCount
|
||||
1
|
||||
).apply { setBand(0, band) }
|
||||
val limiter = DynamicsProcessing.Limiter(
|
||||
// inUse
|
||||
true,
|
||||
// enabled
|
||||
true,
|
||||
// linkGroup
|
||||
0,
|
||||
LIMITER_ATTACK_MS,
|
||||
LIMITER_RELEASE_MS,
|
||||
LIMITER_RATIO,
|
||||
LIMITER_THRESHOLD_DB,
|
||||
// postGain
|
||||
0f
|
||||
)
|
||||
val channel = DynamicsProcessing.Channel(
|
||||
// inputGain
|
||||
0f,
|
||||
// preEqInUse
|
||||
false,
|
||||
// preEqBandCount
|
||||
0,
|
||||
// mbcInUse
|
||||
true,
|
||||
// mbcBandCount
|
||||
1,
|
||||
// postEqInUse
|
||||
false,
|
||||
// postEqBandCount
|
||||
0,
|
||||
// limiterInUse
|
||||
true
|
||||
).apply {
|
||||
setMbc(mbc)
|
||||
setLimiter(limiter)
|
||||
}
|
||||
val config = DynamicsProcessing.Config.Builder(
|
||||
DynamicsProcessing.VARIANT_FAVOR_FREQUENCY_RESOLUTION,
|
||||
channelCount,
|
||||
// preEqInUse
|
||||
false,
|
||||
// preEqBandCount
|
||||
0,
|
||||
// mbcInUse
|
||||
true,
|
||||
// mbcBandCount
|
||||
1,
|
||||
// postEqInUse
|
||||
false,
|
||||
// postEqBandCount
|
||||
0,
|
||||
// limiterInUse
|
||||
true
|
||||
)
|
||||
.setPreferredFrameDuration(FRAME_DURATION_MS)
|
||||
.setAllChannelsTo(channel)
|
||||
.build()
|
||||
dynamicsProcessing = DynamicsProcessing(EFFECT_PRIORITY, sessionId, config).apply { setEnabled(true) }
|
||||
log("info", "audio-normalization", "DynamicsProcessing attached (session=$sessionId, channels=$channelCount)")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
log(
|
||||
"warn",
|
||||
"audio-normalization",
|
||||
"DynamicsProcessing unavailable (${e.javaClass.simpleName}: ${e.message}); trying LoudnessEnhancer"
|
||||
)
|
||||
dynamicsProcessing = null
|
||||
false
|
||||
}
|
||||
|
||||
private fun tryLoudnessEnhancer(sessionId: Int) {
|
||||
try {
|
||||
loudnessEnhancer = LoudnessEnhancer(sessionId).apply {
|
||||
setTargetGain(LOUDNESS_ENHANCER_GAIN_MB)
|
||||
setEnabled(true)
|
||||
}
|
||||
log("info", "audio-normalization", "LoudnessEnhancer attached (session=$sessionId, gain=${LOUDNESS_ENHANCER_GAIN_MB}mB)")
|
||||
} catch (e: Exception) {
|
||||
loudnessEnhancer = null
|
||||
attachedSessionId = 0
|
||||
attachedChannelCount = 0
|
||||
log(
|
||||
"warn",
|
||||
"audio-normalization",
|
||||
"No loudness effect available on this device (${e.javaClass.simpleName}: ${e.message})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* In-place sanitizer for HEVC Annex B buffers carrying both Dolby Vision and HDR10+
|
||||
* dynamic metadata. Buggy chipsets (Fire TV 4K Max, MediaTek-based Google TV, ...)
|
||||
* crash or black-screen when a native DV codec also receives in-band HDR10+ SEI, so
|
||||
* only the metadata the active decode path consumes may be kept:
|
||||
*
|
||||
* - Native DV codec: strip HDR10+ SEI NALs (types 39/40 with ST 2094-40 payload),
|
||||
* the decoder follows the DV RPU. Port of androidx/media#3085 / Kodi xbmc#24584.
|
||||
* - HEVC fallback for a DV format: strip DV RPU/EL NALs (types 62/63) instead,
|
||||
* leaving HDR10+ for the display.
|
||||
*
|
||||
* Runs on the playback thread against MediaCodec's direct input buffers, where
|
||||
* per-byte ByteBuffer accessor calls are far too slow for high-bitrate UHD remuxes
|
||||
* (#1313). Each sample is therefore staged through a reusable heap array with a
|
||||
* single bulk get, scanned and compacted with array ops, and only the modified tail
|
||||
* is written back. Instances are not thread-safe: use one per renderer.
|
||||
*
|
||||
* Pure JVM (no android/media3 imports) so it stays unit-testable on the host.
|
||||
*/
|
||||
class DvBitstreamSanitizer {
|
||||
|
||||
private companion object {
|
||||
const val NAL_TYPE_PREFIX_SEI = 39
|
||||
const val NAL_TYPE_SUFFIX_SEI = 40
|
||||
const val NAL_TYPE_UNSPEC62 = 62 // DV RPU
|
||||
const val NAL_TYPE_UNSPEC63 = 63 // DV Enhancement Layer
|
||||
|
||||
const val SEI_PAYLOAD_TYPE_ITU_T_T35 = 4
|
||||
|
||||
const val INITIAL_SCRATCH_SIZE = 256 * 1024
|
||||
}
|
||||
|
||||
/** Reusable staging buffer — grown as needed, never shrunk. */
|
||||
private var scratch = ByteArray(INITIAL_SCRATCH_SIZE)
|
||||
|
||||
/**
|
||||
* Scans `[position, limit)` of [data] for Annex B NAL units and removes the selected
|
||||
* metadata NALs by compacting the buffer in place and reducing its limit. The position
|
||||
* is left unchanged. Returns the number of NAL units stripped.
|
||||
*
|
||||
* A sample with no start codes at all is left untouched: it cannot contain the
|
||||
* targeted NALs, and emptying it would only confuse the decoder.
|
||||
*/
|
||||
fun sanitize(data: ByteBuffer, stripHdr10PlusSei: Boolean, stripDvRpu: Boolean): Int {
|
||||
val startPos = data.position()
|
||||
val len = data.limit() - startPos
|
||||
if (len == 0) return 0
|
||||
if (scratch.size < len) scratch = ByteArray(maxOf(len, scratch.size * 2))
|
||||
val buf = scratch
|
||||
data.get(buf, 0, len)
|
||||
data.position(startPos)
|
||||
|
||||
var writeLen = 0
|
||||
var firstModified = -1
|
||||
var strippedCount = 0
|
||||
var nalStartIndex = -1
|
||||
var startCodeLen = 0
|
||||
|
||||
var i = 0
|
||||
while (i <= len) {
|
||||
// Find next start code or end of buffer.
|
||||
val atEnd = i == len
|
||||
var foundStartCode = false
|
||||
var nextStartCodeLen = 0
|
||||
if (!atEnd && i + 2 < len && buf[i].toInt() == 0 && buf[i + 1].toInt() == 0) {
|
||||
if (buf[i + 2].toInt() == 1) {
|
||||
foundStartCode = true
|
||||
nextStartCodeLen = 3
|
||||
} else if (buf[i + 2].toInt() == 0 && i + 3 < len && buf[i + 3].toInt() == 1) {
|
||||
foundStartCode = true
|
||||
nextStartCodeLen = 4
|
||||
}
|
||||
}
|
||||
|
||||
if (foundStartCode || atEnd) {
|
||||
if (nalStartIndex >= 0) {
|
||||
// Complete NAL unit (including its start code) from nalStartIndex to i.
|
||||
val nalDataStart = nalStartIndex + startCodeLen
|
||||
val nalEnd = i
|
||||
var strip = false
|
||||
|
||||
if (nalEnd - nalDataStart >= 2) {
|
||||
// HEVC NAL header: forbidden_zero_bit(1) + nal_unit_type(6) + nuh_layer_id MSB(1).
|
||||
val nalUnitType = (buf[nalDataStart].toInt() and 0x7E) shr 1
|
||||
strip = when (nalUnitType) {
|
||||
NAL_TYPE_UNSPEC62, NAL_TYPE_UNSPEC63 -> stripDvRpu
|
||||
NAL_TYPE_PREFIX_SEI, NAL_TYPE_SUFFIX_SEI ->
|
||||
stripHdr10PlusSei && isHdr10PlusSeiNalUnit(buf, nalDataStart + 2, nalEnd)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
if (strip) {
|
||||
strippedCount++
|
||||
if (firstModified < 0) firstModified = writeLen
|
||||
} else {
|
||||
if (writeLen != nalStartIndex) {
|
||||
// Also reached with zero strips when bytes precede the first start code.
|
||||
if (firstModified < 0) firstModified = writeLen
|
||||
System.arraycopy(buf, nalStartIndex, buf, writeLen, nalEnd - nalStartIndex)
|
||||
}
|
||||
writeLen += nalEnd - nalStartIndex
|
||||
}
|
||||
}
|
||||
nalStartIndex = i
|
||||
startCodeLen = nextStartCodeLen
|
||||
i += if (nextStartCodeLen > 0) nextStartCodeLen else 1
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if (writeLen == len || firstModified < 0) return 0
|
||||
|
||||
// Bytes before firstModified are byte-identical to the buffer; write back only the tail.
|
||||
data.position(startPos + firstModified)
|
||||
data.put(buf, firstModified, writeLen - firstModified)
|
||||
data.limit(startPos + writeLen)
|
||||
data.position(startPos)
|
||||
return strippedCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the SEI RBSP (starting after the 2-byte HEVC NAL header) begins with an
|
||||
* HDR10+ message: user_data_registered_itu_t_t35 with country code 0xB5 (United States),
|
||||
* provider code 0x003C (Samsung), provider oriented code 0x0001, application identifier 4
|
||||
* (ST 2094-40), application version 0 or 1. Malformed/truncated data returns false so the
|
||||
* NAL is kept.
|
||||
*/
|
||||
private fun isHdr10PlusSeiNalUnit(buf: ByteArray, rbspStart: Int, nalEnd: Int): Boolean {
|
||||
var pos = rbspStart
|
||||
if (pos >= nalEnd) return false
|
||||
|
||||
// SEI payload type: accumulated 0xFF bytes plus the final byte.
|
||||
var payloadType = 0
|
||||
while (pos < nalEnd) {
|
||||
val b = buf[pos++].toInt() and 0xFF
|
||||
payloadType += b
|
||||
if (b != 0xFF) break
|
||||
}
|
||||
|
||||
// SEI payload size, same encoding.
|
||||
var payloadSize = 0
|
||||
while (pos < nalEnd) {
|
||||
val b = buf[pos++].toInt() and 0xFF
|
||||
payloadSize += b
|
||||
if (b != 0xFF) break
|
||||
}
|
||||
|
||||
if (payloadType != SEI_PAYLOAD_TYPE_ITU_T_T35 || payloadSize < 7 || pos + 7 > nalEnd) {
|
||||
return false
|
||||
}
|
||||
|
||||
// The identifier bytes (B5 00 3C 00 01 04 00/01) cannot contain the 0x000003 emulation
|
||||
// prevention pattern, so they can be read without RBSP unescaping.
|
||||
val countryCode = buf[pos].toInt() and 0xFF
|
||||
val providerCode = ((buf[pos + 1].toInt() and 0xFF) shl 8) or (buf[pos + 2].toInt() and 0xFF)
|
||||
val orientedCode = ((buf[pos + 3].toInt() and 0xFF) shl 8) or (buf[pos + 4].toInt() and 0xFF)
|
||||
val appIdentifier = buf[pos + 5].toInt() and 0xFF
|
||||
val appVersion = buf[pos + 6].toInt() and 0xFF
|
||||
|
||||
return countryCode == 0xB5 &&
|
||||
providerCode == 0x003C &&
|
||||
orientedCode == 0x0001 &&
|
||||
appIdentifier == 4 &&
|
||||
(appVersion == 0 || appVersion == 1)
|
||||
}
|
||||
}
|
||||
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,42 +25,45 @@ 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 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 activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
// Every Dart observeProperty registration, kept so an ExoPlayer→MPV
|
||||
// fallback can re-observe exactly what Dart asked for instead of
|
||||
// maintaining a parallel hard-coded list.
|
||||
private data class ObservedProperty(val id: Int, val format: String)
|
||||
private val observedProperties = LinkedHashMap<String, ObservedProperty>()
|
||||
|
||||
private var configuredBufferSizeBytes: Int? = null
|
||||
|
||||
private var sessionGeneration = 0
|
||||
private var debugLoggingEnabled: Boolean = false
|
||||
private val pendingMpvProperties = mutableListOf<Pair<String, String>>()
|
||||
|
||||
// mpv properties set while ExoPlayer is active (including before
|
||||
// initialize — Dart queues its startup properties first), replayed into a
|
||||
// fallback MPV core. Keyed by property name (last write wins) and cleared
|
||||
// only at real session boundaries (dispose, engine detach, open while the
|
||||
// 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
|
||||
@@ -80,6 +82,8 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
currentExternalSubtitles = null
|
||||
pendingMpvProperties.clear()
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
@@ -102,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
|
||||
@@ -150,6 +152,9 @@ class ExoPlayerPlugin :
|
||||
"setBoxFitMode" -> handleSetBoxFitMode(call, result)
|
||||
"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" -> {
|
||||
@@ -182,10 +187,19 @@ 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++
|
||||
// Do NOT clear pendingMpvProperties here: Dart queues its startup
|
||||
// properties (sub-ass, subtitle fonts, ...) before initialize, and the
|
||||
// fallback replay in setupMpvFallback needs them. Dispose/detach clear.
|
||||
|
||||
if (mpvCore != null || fallbackInProgress) {
|
||||
mpvCore?.dispose()
|
||||
@@ -195,25 +209,34 @@ class ExoPlayerPlugin :
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -228,6 +251,8 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
currentExternalSubtitles = null
|
||||
pendingMpvProperties.clear()
|
||||
Log.d(TAG, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
@@ -238,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")
|
||||
@@ -246,34 +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 properties when MPV is the active backend.
|
||||
// When ExoPlayer is active, keep them for potential ExoPlayer→MPV fallback.
|
||||
// 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) {
|
||||
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) {
|
||||
@@ -413,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)
|
||||
}
|
||||
|
||||
@@ -450,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -503,13 +572,14 @@ class ExoPlayerPlugin :
|
||||
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val id = call.argument<Int>("id")
|
||||
val format = call.argument<String>("format") ?: "string"
|
||||
|
||||
if (name == null || id == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name' or 'id'", null)
|
||||
return
|
||||
}
|
||||
|
||||
nameToId[name] = id
|
||||
observedProperties[name] = ObservedProperty(id, format)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
@@ -589,6 +659,62 @@ class ExoPlayerPlugin :
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
|
||||
private fun handleSetAudioNormalization(call: MethodCall, result: MethodChannel.Result) {
|
||||
val enabled = call.argument<Boolean>("enabled")
|
||||
if (enabled == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'enabled'", null)
|
||||
return
|
||||
}
|
||||
if (usingMpvFallback) {
|
||||
// mpv applies loudnorm via the 'af' property the Dart layer also sends.
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
playerCore?.setAudioNormalization(enabled)
|
||||
result.success(true)
|
||||
} ?: 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")
|
||||
@@ -603,6 +729,10 @@ class ExoPlayerPlugin :
|
||||
when (name) {
|
||||
"audio-delay" -> playerCore?.setAudioDelay(value.toDoubleOrNull() ?: 0.0)
|
||||
"sub-delay" -> playerCore?.setSubtitleDelay(value.toDoubleOrNull() ?: 0.0)
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -610,7 +740,7 @@ class ExoPlayerPlugin :
|
||||
mpvCore?.setProperty(name, value)
|
||||
} else {
|
||||
// Store for later application if ExoPlayer falls back to MPV
|
||||
pendingMpvProperties.add(Pair(name, value))
|
||||
pendingMpvProperties[name] = value
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
@@ -618,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 {
|
||||
@@ -634,57 +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-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
|
||||
|
||||
@@ -701,38 +788,123 @@ class ExoPlayerPlugin :
|
||||
// ExoPlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = nameToId[name] ?: return
|
||||
mainHandler.post { eventSink?.success(listOf(propId, value)) }
|
||||
val propId = observedProperties[name]?.id ?: return
|
||||
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 }
|
||||
mainHandler.post { eventSink?.success(event) }
|
||||
channels.emitEvent(name, data)
|
||||
}
|
||||
|
||||
private fun notifyBackendSwitched() {
|
||||
channels.emitEvent("backend-switched")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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://.
|
||||
* Configure a freshly initialized MPV fallback core: replay the properties
|
||||
* and observers Dart registered against the ExoPlayer session, then resume
|
||||
* the media at the handoff position. Runs in MpvPlayerCore.initialize's
|
||||
* completion callback on the main thread.
|
||||
*/
|
||||
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 setupMpvFallback(
|
||||
core: MpvPlayerCore,
|
||||
act: Activity,
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
positionMs: Long,
|
||||
externalSubtitles: List<Map<String, Any?>>?,
|
||||
playWhenReady: Boolean,
|
||||
generation: Int
|
||||
) {
|
||||
// Snapshot Dart-registered state on main thread before clearing.
|
||||
val pendingProps = pendingMpvProperties.toList()
|
||||
pendingMpvProperties.clear()
|
||||
val observedProps = observedProperties.toList()
|
||||
val bufferSize = configuredBufferSizeBytes
|
||||
|
||||
MpvContentUriResolver.resolve(uri, act.contentResolver, mainHandler) { source ->
|
||||
if (generation != sessionGeneration || mpvCore !== core || activity !== act || !usingMpvFallback) {
|
||||
source.closeIfUnused()
|
||||
core.dispose()
|
||||
return@resolve
|
||||
}
|
||||
|
||||
// Configure basic MPV properties for Plex playback.
|
||||
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
|
||||
core.setProperty("vo", "gpu")
|
||||
core.setProperty("ao", "audiotrack")
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -740,6 +912,7 @@ class ExoPlayerPlugin :
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
positionMs: Long,
|
||||
playWhenReady: Boolean,
|
||||
errorMessage: String
|
||||
): Boolean {
|
||||
if (usingMpvFallback || fallbackInProgress) {
|
||||
@@ -748,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")
|
||||
@@ -773,7 +947,7 @@ class ExoPlayerPlugin :
|
||||
|
||||
val generation = sessionGeneration
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
mainHandler.post {
|
||||
if (generation != sessionGeneration) {
|
||||
fallbackInProgress = false
|
||||
return@post
|
||||
@@ -813,86 +987,7 @@ class ExoPlayerPlugin :
|
||||
usingMpvFallback = true
|
||||
fallbackInProgress = false
|
||||
|
||||
// Snapshot pending properties on main thread before clearing
|
||||
val pendingProps = pendingMpvProperties.toList()
|
||||
pendingMpvProperties.clear()
|
||||
|
||||
// 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
|
||||
return@initialize
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
|
||||
// Setup property observers
|
||||
core.observeProperty("time-pos", "double")
|
||||
core.observeProperty("duration", "double")
|
||||
core.observeProperty("seekable", "flag")
|
||||
core.observeProperty("pause", "flag")
|
||||
core.observeProperty("paused-for-cache", "flag")
|
||||
core.observeProperty("demuxer-cache-time", "double")
|
||||
core.observeProperty("eof-reached", "flag")
|
||||
core.observeProperty("track-list", "string")
|
||||
core.observeProperty("aid", "string")
|
||||
core.observeProperty("sid", "string")
|
||||
core.observeProperty("volume", "double")
|
||||
core.observeProperty("speed", "double")
|
||||
|
||||
// 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(",")
|
||||
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")
|
||||
}
|
||||
}.start()
|
||||
|
||||
// Request audio focus
|
||||
core.requestAudioFocus()
|
||||
|
||||
// Emit backend-switched event on main thread
|
||||
activity?.runOnUiThread {
|
||||
onEvent("backend-switched", null)
|
||||
}
|
||||
|
||||
Log.i(TAG, "Successfully switched to MPV fallback")
|
||||
setupMpvFallback(core, act, uri, headers, positionMs, fallbackExternalSubtitles, playWhenReady, generation)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallbackInProgress = false
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,16 @@ package com.edde746.plezy.exoplayer
|
||||
import android.content.Context
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
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
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.Renderer
|
||||
import androidx.media3.exoplayer.analytics.PlayerId
|
||||
@@ -18,6 +23,11 @@ import androidx.media3.exoplayer.audio.AudioTrackAudioOutputProvider
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioSink
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioTrackBufferSizeProvider
|
||||
import androidx.media3.exoplayer.audio.ForwardingAudioSink
|
||||
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
|
||||
@@ -25,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
|
||||
|
||||
@@ -36,6 +63,47 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
|
||||
var audioDiagnosticsLogger: ((String, String, String) -> Unit)? = null
|
||||
|
||||
var videoDiagnosticsLogger: ((String, String, String) -> Unit)? = null
|
||||
|
||||
override fun buildVideoRenderers(
|
||||
context: Context,
|
||||
extensionRendererMode: Int,
|
||||
mediaCodecSelector: MediaCodecSelector,
|
||||
enableDecoderFallback: Boolean,
|
||||
eventHandler: Handler,
|
||||
eventListener: VideoRendererEventListener,
|
||||
allowedVideoJoiningTimeMs: Long,
|
||||
out: ArrayList<Renderer>
|
||||
) {
|
||||
// Let super build the full list (it also appends extension renderers reflectively,
|
||||
// e.g. the jellyfin ffmpeg artifact's video renderer), then swap the stock
|
||||
// MediaCodecVideoRenderer for the DV-sanitizing variant at the same index.
|
||||
super.buildVideoRenderers(
|
||||
context,
|
||||
extensionRendererMode,
|
||||
mediaCodecSelector,
|
||||
enableDecoderFallback,
|
||||
eventHandler,
|
||||
eventListener,
|
||||
allowedVideoJoiningTimeMs,
|
||||
out
|
||||
)
|
||||
val index = out.indexOfFirst { it.javaClass == MediaCodecVideoRenderer::class.java }
|
||||
if (index < 0) return
|
||||
out[index] = DvSanitizingVideoRenderer(
|
||||
MediaCodecVideoRenderer.Builder(context)
|
||||
.setCodecAdapterFactory(codecAdapterFactory)
|
||||
.setMediaCodecSelector(mediaCodecSelector)
|
||||
.setAllowedJoiningTimeMs(allowedVideoJoiningTimeMs)
|
||||
.setEnableDecoderFallback(enableDecoderFallback)
|
||||
.setEventHandler(eventHandler)
|
||||
.setEventListener(eventListener)
|
||||
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
|
||||
forceSetOutputSurfaceWorkaround,
|
||||
videoDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
|
||||
override fun buildAudioSink(
|
||||
context: Context,
|
||||
enableFloatOutput: Boolean,
|
||||
@@ -60,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()
|
||||
|
||||
@@ -280,6 +351,117 @@ internal class SubtitleDelayRenderer(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MediaCodecVideoRenderer that resolves the DV / HDR10+ dual-dynamic-metadata conflict
|
||||
* per decode path (#1296, generalizes androidx/media#3085):
|
||||
* - native DV codec selected (media3 only selects one when decoder AND display support DV):
|
||||
* strip in-band HDR10+ SEI — conflicting dynamic metadata crashes Fire TV-class chipsets
|
||||
* - HEVC fallback for an HEVC-based DV format: strip DV RPU/EL NALs (profiles 7/8, where the
|
||||
* base layer remains valid HDR10/HLG), keeping HDR10+ for the display
|
||||
*
|
||||
* Flags are reassigned on every codec init: tunneling toggles and DV retries re-init the
|
||||
* codec without recreating renderers, and decoder fallback can switch the codec MIME.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class DvSanitizingVideoRenderer(
|
||||
builder: Builder,
|
||||
private val forceSetOutputSurfaceWorkaround: Boolean,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : MediaCodecVideoRenderer(builder) {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
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
|
||||
private var totalSanitizeTimeUs = 0L
|
||||
private var maxSanitizeTimeUs = 0L
|
||||
private var totalStrippedNals = 0L
|
||||
private var totalStrippedBytes = 0L
|
||||
|
||||
override fun onCodecInitialized(
|
||||
name: String,
|
||||
configuration: MediaCodecAdapter.Configuration,
|
||||
initializedTimestampMs: Long,
|
||||
initializationDurationMs: Long
|
||||
) {
|
||||
super.onCodecInitialized(name, configuration, initializedTimestampMs, initializationDurationMs)
|
||||
val codecs = configuration.format.codecs?.lowercase() ?: ""
|
||||
val dvHevcFormat = configuration.format.sampleMimeType == MimeTypes.VIDEO_DOLBY_VISION &&
|
||||
(codecs.startsWith("dvhe.") || codecs.startsWith("dvh1."))
|
||||
val codecMimeType = configuration.codecInfo.codecMimeType
|
||||
val newStripHdr10PlusSei = dvHevcFormat && codecMimeType == MimeTypes.VIDEO_DOLBY_VISION
|
||||
val newStripDvRpu = dvHevcFormat &&
|
||||
codecMimeType == MimeTypes.VIDEO_H265 &&
|
||||
isBlCompatibleDvProfile(codecs)
|
||||
if (newStripHdr10PlusSei != stripHdr10PlusSei || newStripDvRpu != stripDvRpu) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"video",
|
||||
"DV bitstream sanitizing: stripHdr10PlusSei=$newStripHdr10PlusSei, " +
|
||||
"stripDvRpu=$newStripDvRpu (codec=$name, codecs=${configuration.format.codecs})"
|
||||
)
|
||||
}
|
||||
stripHdr10PlusSei = newStripHdr10PlusSei
|
||||
stripDvRpu = newStripDvRpu
|
||||
}
|
||||
|
||||
override fun onQueueInputBuffer(buffer: DecoderInputBuffer) {
|
||||
if (stripHdr10PlusSei || stripDvRpu) {
|
||||
val data = buffer.data
|
||||
if (data != null && data.hasRemaining() && !buffer.isEncrypted) {
|
||||
val sizeBefore = data.remaining()
|
||||
val startNs = System.nanoTime()
|
||||
val stripped = sanitizer.sanitize(data, stripHdr10PlusSei, stripDvRpu)
|
||||
val elapsedUs = (System.nanoTime() - startNs) / 1_000
|
||||
sanitizedSampleCount++
|
||||
totalSanitizeTimeUs += elapsedUs
|
||||
if (elapsedUs > maxSanitizeTimeUs) maxSanitizeTimeUs = elapsedUs
|
||||
totalStrippedNals += stripped
|
||||
totalStrippedBytes += sizeBefore - data.remaining()
|
||||
if (sanitizedSampleCount <= 3 || sanitizedSampleCount % 500 == 0L) {
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"dv-sanitize",
|
||||
"Sample #$sanitizedSampleCount: ${sizeBefore}B -> ${data.remaining()}B, " +
|
||||
"stripped=$stripped, took=${elapsedUs}us " +
|
||||
"(avg=${totalSanitizeTimeUs / sanitizedSampleCount}us, max=${maxSanitizeTimeUs}us, " +
|
||||
"totalNals=$totalStrippedNals, totalBytes=${totalStrippedBytes}B)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
super.onQueueInputBuffer(buffer)
|
||||
}
|
||||
|
||||
private fun isBlCompatibleDvProfile(codecs: String): Boolean = codecs.startsWith("dvhe.07") ||
|
||||
codecs.startsWith("dvh1.07") ||
|
||||
codecs.startsWith("dvhe.08") ||
|
||||
codecs.startsWith("dvh1.08")
|
||||
}
|
||||
|
||||
// --- AudioOutput wrapping: shares raw position with PositionFixAudioSink ---
|
||||
// Also implements AudioTrack reuse across seeks to avoid expensive teardown/recreation.
|
||||
// DefaultAudioSink releases the AudioOutput on every flush (seek), which destroys the
|
||||
|
||||
@@ -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 io.github.peerless2012.ass.media.AssHandler
|
||||
import io.github.peerless2012.ass.media.extractor.AssMatroskaExtractor
|
||||
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,8 +1,9 @@
|
||||
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.Handler
|
||||
import android.os.Looper
|
||||
@@ -14,20 +15,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 +72,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 +119,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,25 +136,35 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
}
|
||||
|
||||
private fun currentDisplayFpsOverride(): String? {
|
||||
if (audioOnly) return null
|
||||
val refreshRate = activity.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 +177,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
|
||||
try {
|
||||
disposing = false
|
||||
endFileDiagnostics.onStartFile()
|
||||
cachedPaused = true
|
||||
pausedForSurfaceLoss = false
|
||||
pendingSurface = null
|
||||
@@ -152,12 +193,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 +216,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 +248,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 +287,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 +325,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 +361,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 +423,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 +436,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 +681,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 +699,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 +707,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 +739,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 +825,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 +833,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 +870,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 +890,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 +908,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 +917,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -813,6 +941,11 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
check(Looper.myLooper() == Looper.getMainLooper())
|
||||
Log.d(TAG, "Disposing")
|
||||
|
||||
surfaceContainer?.let { container ->
|
||||
container.visibility = View.INVISIBLE
|
||||
Log.d(TAG, "Hiding surface container during dispose")
|
||||
}
|
||||
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
|
||||
// Clean up frame rate and audio focus.
|
||||
@@ -843,17 +976,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
|
||||
|
||||
@@ -875,15 +1008,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) {
|
||||
@@ -894,7 +1030,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()
|
||||
}
|
||||
@@ -904,7 +1040,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,52 @@
|
||||
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 = isHardwareAccelerated(Build.VERSION.SDK_INT, info.isHardwareAccelerated, info.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
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@android:color/white" />
|
||||
<item android:drawable="@color/splash_background" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- TV (Android TV / Google TV / Fire TV) launch + window background.
|
||||
The television UI-mode qualifier outranks night/notnight, so this wins
|
||||
even on TVs that report notnight (most do) where values/ would resolve
|
||||
the near-white #F7F7F8. Black matches the OLED default theme on TV. -->
|
||||
<color name="splash_background">#000000</color>
|
||||
</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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DvBitstreamSanitizerTest {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
// --- HDR10+ SEI stripping (native DV codec path) ---
|
||||
|
||||
@Test
|
||||
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
|
||||
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
|
||||
val originalLimit = buffer.limit()
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
assertTrue(buffer.limit() < originalLimit)
|
||||
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)
|
||||
val sei = annexBNal(39, hdr10PlusSeiPayload(), startCodeLen = 3)
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03), startCodeLen = 3)
|
||||
val buffer = bufferOf(vcl1, sei, vcl2)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesNonHdr10PlusT35Sei() {
|
||||
// Same T.35 layout but wrong country code (0x00 instead of 0xB5).
|
||||
val sei = annexBNal(
|
||||
39,
|
||||
byteArrayOf(0x04, 0x07, 0x00, 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00)
|
||||
)
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), sei, annexBNal(1, byteArrayOf(0x02)))
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noOpWithoutSeiNals() {
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01, 0x02)), annexBNal(1, byteArrayOf(0x03)))
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsTruncatedSei() {
|
||||
// Declares payload size 7 but the identifier bytes are cut short.
|
||||
val truncated = annexBNal(39, byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C))
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), truncated)
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsHdr10PlusSeiWhenFlagOff() {
|
||||
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), hdr10PlusSei())
|
||||
val original = remainingBytes(buffer)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = false)
|
||||
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- DV RPU/EL stripping (HEVC fallback path) ---
|
||||
|
||||
@Test
|
||||
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
|
||||
val el = annexBNal(63, byteArrayOf(0x42))
|
||||
val sei = hdr10PlusSei()
|
||||
val buffer = bufferOf(vcl, rpu, sei, el)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
|
||||
|
||||
assertArrayEquals(concat(vcl, sei), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bothFlagsStripBothMetadataKinds() {
|
||||
val vcl1 = annexBNal(19, byteArrayOf(0x00)) // IDR_W_RADL
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x05))
|
||||
val buffer = bufferOf(vcl1, annexBNal(62, byteArrayOf(0x19)), hdr10PlusSei(), vcl2)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- Buffer handling ---
|
||||
|
||||
@Test
|
||||
fun respectsPositionAndRestoresIt() {
|
||||
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
val content = concat(prefix, vcl, hdr10PlusSei())
|
||||
val buffer = ByteBuffer.wrap(content.copyOf())
|
||||
buffer.position(prefix.size)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(prefix.size, buffer.position())
|
||||
assertArrayEquals(vcl, remainingBytes(buffer))
|
||||
// Bytes before the position are untouched.
|
||||
assertEquals(0xAA.toByte(), buffer.get(0))
|
||||
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)
|
||||
|
||||
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertEquals(0, buffer.position())
|
||||
assertEquals(0, buffer.limit())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsOnDirectBufferWithNonZeroPosition() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val buffer = directBufferOf(byteArrayOf(0xAA.toByte(), 0xBB.toByte()), vcl1, hdr10PlusSei(), vcl2)
|
||||
buffer.position(2)
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(1, stripped)
|
||||
assertEquals(2, buffer.position())
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
// Bytes before the position are untouched.
|
||||
assertEquals(0xAA.toByte(), buffer.get(0))
|
||||
assertEquals(0xBB.toByte(), buffer.get(1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noStripLeavesDirectBufferStateUntouched() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val buffer = directBufferOf(vcl1, vcl2)
|
||||
val originalLimit = buffer.limit()
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertEquals(0, stripped)
|
||||
assertEquals(0, buffer.position())
|
||||
assertEquals(originalLimit, buffer.limit())
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsTrailingRpuWithZeroByteTailWriteBack() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
|
||||
val buffer = directBufferOf(vcl1, vcl2, rpu)
|
||||
val originalLimit = buffer.limit()
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
|
||||
|
||||
assertEquals(1, stripped)
|
||||
assertEquals(originalLimit - rpu.size, buffer.limit())
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun growsScratchForLargeSamples() {
|
||||
// Exceeds the initial 256KB scratch and one doubling; non-zero filler so no
|
||||
// accidental start codes appear in the payloads.
|
||||
val vcl1 = annexBNal(1, ByteArray(800_000) { 0xAB.toByte() })
|
||||
val vcl2 = annexBNal(1, ByteArray(700_000) { 0xCD.toByte() })
|
||||
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(1, stripped)
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reusesSanitizerAcrossSequentialBuffers() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
|
||||
|
||||
val first = bufferOf(vcl1, hdr10PlusSei(), vcl2)
|
||||
assertEquals(1, sanitizer.sanitize(first, stripHdr10PlusSei = true, stripDvRpu = false))
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(first))
|
||||
|
||||
val second = bufferOf(vcl1, vcl2)
|
||||
assertEquals(0, sanitizer.sanitize(second, stripHdr10PlusSei = true, stripDvRpu = false))
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(second))
|
||||
|
||||
val third = bufferOf(hdr10PlusSei(), vcl1, annexBNal(62, byteArrayOf(0x19)), vcl2, hdr10PlusSei())
|
||||
assertEquals(3, sanitizer.sanitize(third, stripHdr10PlusSei = true, stripDvRpu = true))
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(third))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsBufferWithoutStartCodes() {
|
||||
val content = byteArrayOf(0x12, 0x34, 0x56, 0x78)
|
||||
val buffer = ByteBuffer.wrap(content.copyOf())
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
|
||||
|
||||
assertEquals(0, stripped)
|
||||
assertEquals(0, buffer.position())
|
||||
assertEquals(content.size, buffer.limit())
|
||||
assertArrayEquals(content, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stripsMultipleSeisInOneAccessUnit() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
val vcl2 = annexBNal(1, byteArrayOf(0x03))
|
||||
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
|
||||
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2, suffixSei)
|
||||
|
||||
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
|
||||
|
||||
assertEquals(2, stripped)
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
/** Builds an HEVC NAL unit: start code + 2-byte NAL header encoding [nalUnitType] + payload. */
|
||||
private fun annexBNal(nalUnitType: Int, payload: ByteArray, startCodeLen: Int = 4): ByteArray {
|
||||
val startCode = if (startCodeLen == 3) byteArrayOf(0, 0, 1) else byteArrayOf(0, 0, 0, 1)
|
||||
val header = byteArrayOf(((nalUnitType shl 1) and 0x7E).toByte(), 0x01)
|
||||
return concat(startCode, header, payload)
|
||||
}
|
||||
|
||||
/**
|
||||
* SEI payload: type 4 (user_data_registered_itu_t_t35), size 7, then the HDR10+
|
||||
* identifiers — country 0xB5, provider 0x003C, oriented code 0x0001, app id 4, version 0 —
|
||||
* closed by the rbsp_trailing_bits stop byte real SEI NALs always end with (a trailing 0x00
|
||||
* would otherwise be ambiguous against a following 3-byte start code).
|
||||
*/
|
||||
private fun hdr10PlusSeiPayload(): ByteArray = byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00, 0x80.toByte())
|
||||
|
||||
private fun hdr10PlusSei(): ByteArray = annexBNal(39, hdr10PlusSeiPayload())
|
||||
|
||||
private fun concat(vararg parts: ByteArray): ByteArray {
|
||||
val result = ByteArray(parts.sumOf { it.size })
|
||||
var offset = 0
|
||||
for (part in parts) {
|
||||
part.copyInto(result, offset)
|
||||
offset += part.size
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun bufferOf(vararg parts: ByteArray): ByteBuffer = ByteBuffer.wrap(concat(*parts))
|
||||
|
||||
private fun directBufferOf(vararg parts: ByteArray): ByteBuffer {
|
||||
val content = concat(*parts)
|
||||
val buffer = ByteBuffer.allocateDirect(content.size)
|
||||
buffer.put(content)
|
||||
buffer.flip()
|
||||
return buffer
|
||||
}
|
||||
|
||||
private fun remainingBytes(buffer: ByteBuffer): ByteArray {
|
||||
val copy = ByteArray(buffer.remaining())
|
||||
buffer.duplicate().get(copy)
|
||||
return copy
|
||||
}
|
||||
}
|
||||
+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,241 @@
|
||||
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.assertNotNull
|
||||
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 formatIsEmittedBeforeFirstSample() {
|
||||
val output = extractFixture()
|
||||
val track = output.tracks.values.first()
|
||||
assertNotNull(track.formats.firstOrNull())
|
||||
// LatmReader emits the format from the first StreamMuxConfig, which arrives
|
||||
// with the first LOAS frame — before any sample metadata is committed.
|
||||
assertTrue(track.samples.isNotEmpty())
|
||||
}
|
||||
|
||||
@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,47 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MediaCodecQueryTest {
|
||||
|
||||
@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.
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
|
||||
@@ -0,0 +1,58 @@
|
||||
// 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")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.edde746.plezy.libass"
|
||||
compileSdk = 36
|
||||
// Matches flutter.ndkVersion so only one NDK is provisioned. This module's
|
||||
// CMake build (-DANDROID_STL=c++_shared) contributes NDK 28.2's
|
||||
// libc++_shared.so to packaging, but that copy is NOT what ships: the app
|
||||
// packages the libmpv AAR's newer copy with top merge priority (see
|
||||
// app/build.gradle.kts packaging { jniLibs } + sourceSets).
|
||||
ndkVersion = "28.2.13676358"
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 21
|
||||
consumerProguardFiles("consumer-rules.pro")
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
// 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"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
version = "3.22.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.annotation:annotation:1.9.1")
|
||||
implementation("androidx.annotation:annotation-experimental:1.5.1")
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
implementation("androidx.media3:media3-ui:1.9.2")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# JNI exports bind by name (Java_com_edde746_plezy_libass_*); keep the names stable.
|
||||
-keepclasseswithmembernames class com.edde746.plezy.libass.* {
|
||||
native <methods>;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,760 @@
|
||||
// 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) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
#include "ass/ass.h"
|
||||
|
||||
#define LOG_TAG "SubtitleRenderer"
|
||||
|
||||
static void assMessageCallback(int level, const char* fmt, va_list args, void* data) {
|
||||
if (level > 4) return;
|
||||
|
||||
if (level >= 2) {
|
||||
__android_log_vprint(ANDROID_LOG_WARN, LOG_TAG, fmt, args);
|
||||
} else {
|
||||
__android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, fmt, args);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Ass (library) ---
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssInit(JNIEnv* env, jclass clazz) {
|
||||
ASS_Library* assLibrary = ass_library_init();
|
||||
ass_set_message_cb(assLibrary, assMessageCallback, NULL);
|
||||
ass_set_extract_fonts(assLibrary, 1);
|
||||
return (jlong)assLibrary;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssAddFont(
|
||||
JNIEnv* env, jclass clazz, jlong ass, jstring name, jbyteArray byteArray) {
|
||||
jsize length = (*env)->GetArrayLength(env, byteArray);
|
||||
jbyte* bytePtr = (*env)->GetByteArrayElements(env, byteArray, NULL);
|
||||
if (bytePtr == NULL) {
|
||||
return;
|
||||
}
|
||||
const char* cName = (*env)->GetStringUTFChars(env, name, NULL);
|
||||
ass_add_font(((ASS_Library*)ass), cName, (char*)bytePtr, length);
|
||||
(*env)->ReleaseByteArrayElements(env, byteArray, bytePtr, 0);
|
||||
if (cName != NULL) {
|
||||
(*env)->ReleaseStringUTFChars(env, name, cName);
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssDeinit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
if (ass) {
|
||||
ass_library_done((ASS_Library*)ass);
|
||||
}
|
||||
}
|
||||
|
||||
// --- AssTrack ---
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackInit(JNIEnv* env, jclass clazz, jlong 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.
|
||||
// chunked != 0 routes to ass_process_chunk (timed dialogue), else ass_process_data.
|
||||
static void processTrackBytes(
|
||||
JNIEnv* env, jlong track, jbyteArray buffer, jint offset, jint length, jlong start, jlong duration, int chunked) {
|
||||
if (!track) return;
|
||||
jbyte* elements = (*env)->GetByteArrayElements(env, buffer, NULL);
|
||||
if (elements == NULL) {
|
||||
return;
|
||||
}
|
||||
if (chunked) {
|
||||
ass_process_chunk((ASS_Track*)track, (char*)(elements + offset), length, start, duration);
|
||||
} else {
|
||||
ass_process_data((ASS_Track*)track, (char*)(elements + offset), length);
|
||||
}
|
||||
(*env)->ReleaseByteArrayElements(env, buffer, elements, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackReadBuffer(
|
||||
JNIEnv* env, jclass clazz, jlong track, jbyteArray buffer, jint offset, jint length) {
|
||||
processTrackBytes(env, track, buffer, offset, length, 0, 0, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackReadChunk(
|
||||
JNIEnv* env, jclass clazz, jlong track, jlong start, jlong duration, jbyteArray buffer, jint offset, jint length) {
|
||||
processTrackBytes(env, track, buffer, offset, length, start, duration, 1);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackDeinit(JNIEnv* env, jclass clazz, jlong track) {
|
||||
if (!track) return;
|
||||
ass_free_track((ASS_Track*)track);
|
||||
}
|
||||
|
||||
// Earliest event Start strictly after afterMs, or -1. Lets the render pipeline
|
||||
// pre-render (cache-warm) the next upcoming event during idle stretches so
|
||||
// heavy typesetting doesn't pay its cache-cold rasterization at appearance.
|
||||
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNextEventStart(
|
||||
JNIEnv* env, jclass clazz, jlong track, jlong afterMs) {
|
||||
if (!track) return -1;
|
||||
ASS_Track* t = (ASS_Track*)track;
|
||||
long long best = -1;
|
||||
for (int i = 0; i < t->n_events; i++) {
|
||||
const long long start = t->events[i].Start;
|
||||
if (start > afterMs && (best < 0 || start < best)) best = start;
|
||||
}
|
||||
return (jlong)best;
|
||||
}
|
||||
|
||||
// Earliest visible-content boundary (event Start OR End) strictly after afterMs,
|
||||
// or -1. A cache-warming prefetch is only invisible while no boundary passes:
|
||||
// the render pipeline uses this to ensure nothing on screen is due to change
|
||||
// before the event it is about to warm.
|
||||
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNextEventChange(
|
||||
JNIEnv* env, jclass clazz, jlong track, jlong afterMs) {
|
||||
if (!track) return -1;
|
||||
ASS_Track* t = (ASS_Track*)track;
|
||||
long long best = -1;
|
||||
for (int i = 0; i < t->n_events; i++) {
|
||||
const long long start = t->events[i].Start;
|
||||
const long long end = start + t->events[i].Duration;
|
||||
if (start > afterMs && (best < 0 || start < best)) best = start;
|
||||
if (end > afterMs && (best < 0 || end < best)) best = end;
|
||||
}
|
||||
return (jlong)best;
|
||||
}
|
||||
|
||||
// --- 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);
|
||||
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;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetFontScale(
|
||||
JNIEnv* env, jclass clazz, jlong render, jfloat scale) {
|
||||
if (!render) return;
|
||||
ass_set_font_scale((ASS_Renderer*)render, scale);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetCacheLimit(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint glyphMax, jint bitmapMaxSize) {
|
||||
if (!render) return;
|
||||
ass_set_cache_limits((ASS_Renderer*)render, glyphMax, bitmapMaxSize);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetFrameSize(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint width, jint height) {
|
||||
if (!render) return;
|
||||
ass_set_frame_size((ASS_Renderer*)render, width, height);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetStorageSize(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint width, jint height) {
|
||||
if (!render) return;
|
||||
ass_set_storage_size((ASS_Renderer*)render, width, height);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetMargins(
|
||||
JNIEnv* env, jclass clazz, jlong render, jint top, jint bottom, jint left, jint right) {
|
||||
if (!render) return;
|
||||
ass_set_margins((ASS_Renderer*)render, top, bottom, left, right);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetUseMargins(
|
||||
JNIEnv* env, jclass clazz, jlong render, jboolean use) {
|
||||
if (!render) return;
|
||||
ass_set_use_margins((ASS_Renderer*)render, use ? 1 : 0);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderDeinit(JNIEnv* env, jclass clazz, jlong render) {
|
||||
if (render) {
|
||||
ass_renderer_done((ASS_Renderer*)render);
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
// 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 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. 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: 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, 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) {
|
||||
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 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 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 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) {
|
||||
int cols = (img->w + atlasMaxW - 1) / atlasMaxW;
|
||||
int rows = (img->h + atlasMaxH - 1) / atlasMaxH;
|
||||
total += cols * rows;
|
||||
}
|
||||
}
|
||||
if (total == 0) {
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
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 (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
srcPixels += (long long)img->w * img->h;
|
||||
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 + 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;
|
||||
}
|
||||
pageCount = (requiredPages < providedPages) ? requiredPages : providedPages;
|
||||
accepted = placed;
|
||||
truncated = n - placed;
|
||||
}
|
||||
|
||||
// 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 tiles dropped (atlas %dx%d, need %d pages have %d)",
|
||||
truncated, n, atlasMaxW, atlasMaxH, requiredPages, providedPages);
|
||||
}
|
||||
if (accepted == 0) {
|
||||
free(tiles);
|
||||
free(keys);
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, truncated, requiredPages, 1, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
// 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]);
|
||||
}
|
||||
|
||||
// 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;
|
||||
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 < 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 + 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 + 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;
|
||||
const float b = (float)((c >> 8) & 0xFFu) / 255.0f;
|
||||
const float a = (float)(0xFFu - (c & 0xFFu)) / 255.0f;
|
||||
|
||||
float* vx = vertices + (size_t)qi * 48;
|
||||
// 8 floats per vertex: x, y, u, v, r, g, b, a.
|
||||
// Triangle 1: (x0,y0) (x1,y0) (x0,y1)
|
||||
vx[0] = x0;
|
||||
vx[1] = y0;
|
||||
vx[2] = u0;
|
||||
vx[3] = v0;
|
||||
vx[4] = r;
|
||||
vx[5] = g;
|
||||
vx[6] = b;
|
||||
vx[7] = a;
|
||||
vx[8] = x1;
|
||||
vx[9] = y0;
|
||||
vx[10] = u1;
|
||||
vx[11] = v0;
|
||||
vx[12] = r;
|
||||
vx[13] = g;
|
||||
vx[14] = b;
|
||||
vx[15] = a;
|
||||
vx[16] = x0;
|
||||
vx[17] = y1;
|
||||
vx[18] = u0;
|
||||
vx[19] = v1;
|
||||
vx[20] = r;
|
||||
vx[21] = g;
|
||||
vx[22] = b;
|
||||
vx[23] = a;
|
||||
// Triangle 2: (x1,y0) (x1,y1) (x0,y1)
|
||||
vx[24] = x1;
|
||||
vx[25] = y0;
|
||||
vx[26] = u1;
|
||||
vx[27] = v0;
|
||||
vx[28] = r;
|
||||
vx[29] = g;
|
||||
vx[30] = b;
|
||||
vx[31] = a;
|
||||
vx[32] = x1;
|
||||
vx[33] = y1;
|
||||
vx[34] = u1;
|
||||
vx[35] = v1;
|
||||
vx[36] = r;
|
||||
vx[37] = g;
|
||||
vx[38] = b;
|
||||
vx[39] = a;
|
||||
vx[40] = x0;
|
||||
vx[41] = y1;
|
||||
vx[42] = u0;
|
||||
vx[43] = v1;
|
||||
vx[44] = r;
|
||||
vx[45] = g;
|
||||
vx[46] = b;
|
||||
vx[47] = a;
|
||||
|
||||
qi++;
|
||||
}
|
||||
|
||||
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.
|
||||
const long long tEnd = nowMs();
|
||||
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 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);
|
||||
// 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];
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
project("asskt")
|
||||
|
||||
# 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
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class Ass {
|
||||
|
||||
companion object {
|
||||
|
||||
init {
|
||||
System.loadLibrary("asskt")
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssInit(): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssAddFont(ptr: Long, name: String, buffer: ByteArray)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssDeinit(ptr: Long)
|
||||
}
|
||||
|
||||
/** Single lock for all libass calls on this library instance. */
|
||||
val lock = ReentrantLock()
|
||||
|
||||
private var nativeAss: Long = nativeAssInit()
|
||||
|
||||
@Volatile
|
||||
var released = false
|
||||
private set
|
||||
|
||||
private fun <T> create(block: (Long) -> T): T = lock.withLock {
|
||||
check(!released && nativeAss != 0L) { "Ass already released" }
|
||||
block(nativeAss)
|
||||
}
|
||||
|
||||
fun createTrack(): AssTrack = create { AssTrack(it, lock) }
|
||||
|
||||
fun createRender(): AssRender = create { AssRender(it, lock) }
|
||||
|
||||
fun addFont(name: String, buffer: ByteArray) {
|
||||
lock.withLock {
|
||||
if (!released && nativeAss != 0L) nativeAssAddFont(nativeAss, name, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
lock.withLock {
|
||||
if (released) return
|
||||
released = true
|
||||
if (nativeAss != 0L) {
|
||||
nativeAssDeinit(nativeAss)
|
||||
nativeAss = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected fun finalize() {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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.
|
||||
*
|
||||
* 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 pageHeights: IntArray,
|
||||
val pageQuadCounts: IntArray,
|
||||
val quadCount: Int,
|
||||
val changed: 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
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
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
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetFontScale(render: Long, scale: Float)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetCacheLimit(render: Long, glyphMax: Int, bitmapMaxSize: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetStorageSize(render: Long, width: Int, height: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetFrameSize(render: Long, width: Int, height: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderSetMargins(render: Long, top: Int, bottom: Int, left: Int, right: Int)
|
||||
|
||||
@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,
|
||||
track: Long,
|
||||
time: Long,
|
||||
atlasBuf: ByteBuffer,
|
||||
atlasMaxWidth: Int,
|
||||
atlasMaxHeight: Int,
|
||||
vertexBuf: ByteBuffer,
|
||||
header: IntArray
|
||||
): Int
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderDeinit(render: Long)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
private var track: AssTrack? = null
|
||||
|
||||
/**
|
||||
* Bumped on every renderer-state mutation (track, sizes, margins, font scale).
|
||||
* Lets the render-ahead pipeline detect that a speculatively rendered frame was
|
||||
* produced against stale state and must not be presented.
|
||||
*/
|
||||
private val generation = java.util.concurrent.atomic.AtomicInteger(0)
|
||||
|
||||
/** Current renderer-state generation; see [generation]. */
|
||||
val stateGeneration: Int get() = generation.get()
|
||||
|
||||
/** Runs [block] with the native handle under the shared libass lock; no-op once released. */
|
||||
private inline fun withNative(block: (Long) -> Unit) {
|
||||
lock.withLock {
|
||||
if (!released && nativeRender != 0L) block(nativeRender)
|
||||
}
|
||||
}
|
||||
|
||||
fun setTrack(track: AssTrack?) {
|
||||
generation.incrementAndGet()
|
||||
lock.withLock { this.track = track }
|
||||
}
|
||||
|
||||
fun setFontScale(scale: Float) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetFontScale(it, scale) }
|
||||
}
|
||||
|
||||
fun setCacheLimit(glyphMax: Int, bitmapMaxSize: Int) = withNative { nativeAssRenderSetCacheLimit(it, glyphMax, bitmapMaxSize) }
|
||||
|
||||
fun setStorageSize(width: Int, height: Int) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetStorageSize(it, width, height) }
|
||||
}
|
||||
|
||||
fun setFrameSize(width: Int, height: Int) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetFrameSize(it, width, height) }
|
||||
}
|
||||
|
||||
/**
|
||||
* mpv-style frame margins: offsets of the video dst rect within the frame set by
|
||||
* [setFrameSize]. Negative when the video extends beyond the frame (zoomed in / cover).
|
||||
*/
|
||||
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetMargins(it, top, bottom, left, right) }
|
||||
}
|
||||
|
||||
/**
|
||||
* mpv's sub-ass-force-margins: lay out non-positioned events against the full frame
|
||||
* (kept on the visible screen) instead of the video rect between the margins.
|
||||
*/
|
||||
fun setUseMargins(use: Boolean) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetUseMargins(it, use) }
|
||||
}
|
||||
|
||||
/** 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,
|
||||
atlasMaxW: Int,
|
||||
atlasMaxH: Int,
|
||||
vertexBuf: ByteBuffer
|
||||
): AssAtlasFrame? {
|
||||
val tQueue = System.nanoTime()
|
||||
lock.withLock {
|
||||
lastLockWaitMs = (System.nanoTime() - tQueue) / 1_000_000
|
||||
if (released || nativeRender == 0L) return null
|
||||
val t = track ?: return null
|
||||
if (t.released || t.nativeAssTrack == 0L) return null
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
lock.withLock {
|
||||
if (released) return
|
||||
released = true
|
||||
track = null
|
||||
if (nativeRender != 0L) {
|
||||
nativeAssRenderDeinit(nativeRender)
|
||||
nativeRender = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected fun finalize() {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class AssTrack(private val ass: Long, private val lock: ReentrantLock) {
|
||||
|
||||
companion object {
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackInit(track: Long): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackReadBuffer(track: Long, byteArray: ByteArray, offset: Int, length: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackReadChunk(track: Long, start: Long, duration: Long, byteArray: ByteArray, offset: Int, length: Int)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackDeinit(track: Long)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackNextEventStart(track: Long, afterMs: Long): Long
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssTrackNextEventChange(track: Long, afterMs: Long): Long
|
||||
}
|
||||
|
||||
var nativeAssTrack = nativeAssTrackInit(ass)
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var released = false
|
||||
private set
|
||||
|
||||
/** Runs [block] with the native handle under the shared libass lock; no-op once released. */
|
||||
private inline fun withNative(block: (Long) -> Unit) {
|
||||
lock.withLock {
|
||||
if (!released && nativeAssTrack != 0L) block(nativeAssTrack)
|
||||
}
|
||||
}
|
||||
|
||||
fun readBuffer(array: ByteArray, offset: Int = 0, length: Int = array.size) = withNative { nativeAssTrackReadBuffer(it, array, offset, length) }
|
||||
|
||||
fun readChunk(start: Long, duration: Long, array: ByteArray, offset: Int = 0, length: Int = array.size) = withNative { nativeAssTrackReadChunk(it, start, duration, array, offset, length) }
|
||||
|
||||
/** Earliest event start strictly after [afterMs], or -1 if none (yet). */
|
||||
fun nextEventStartMs(afterMs: Long): Long {
|
||||
lock.withLock {
|
||||
if (released || nativeAssTrack == 0L) return -1
|
||||
return nativeAssTrackNextEventStart(nativeAssTrack, afterMs)
|
||||
}
|
||||
}
|
||||
|
||||
/** Earliest event start OR end strictly after [afterMs], or -1 if none (yet). */
|
||||
fun nextEventChangeMs(afterMs: Long): Long {
|
||||
lock.withLock {
|
||||
if (released || nativeAssTrack == 0L) return -1
|
||||
return nativeAssTrackNextEventChange(nativeAssTrack, afterMs)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
lock.withLock {
|
||||
if (released) return
|
||||
released = true
|
||||
if (nativeAssTrack != 0L) {
|
||||
nativeAssTrackDeinit(nativeAssTrack)
|
||||
nativeAssTrack = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected fun finalize() {
|
||||
release()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package com.edde746.plezy.libass.media
|
||||
|
||||
import android.util.Log
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.MimeTypes.TEXT_SSA
|
||||
import androidx.media3.common.Player.Listener
|
||||
import androidx.media3.common.Tracks
|
||||
import androidx.media3.common.VideoSize
|
||||
import androidx.media3.common.util.Size
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.video.VideoFrameMetadataListener
|
||||
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.
|
||||
*
|
||||
* This class listens to ExoPlayer events and manages the creation, selection, and rendering of ASS
|
||||
* subtitle tracks. Rendering always happens on a GL overlay surface (atlas pipeline) — the
|
||||
* libass frame is the overlay surface, not the video.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class AssHandler(
|
||||
val config: AssHandlerConfig = AssHandlerConfig()
|
||||
) : Listener {
|
||||
|
||||
/** The ASS instance used for creating tracks and renderers. This is lazy to avoid loading
|
||||
* libass if the played media does not have ASS tracks. */
|
||||
private val assDelegate = lazy { Ass() }
|
||||
val ass by assDelegate
|
||||
|
||||
/** The current ASS renderer. It's created as soon as a ASS track is detected. */
|
||||
var render: AssRender? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* AssRender changed callback
|
||||
*/
|
||||
var renderCallback: ((AssRender?) -> Unit)? = null
|
||||
|
||||
/** The currently selected ASS track. */
|
||||
var track: AssTrack? = null
|
||||
private set
|
||||
|
||||
/** The available ASS tracks in the current media. */
|
||||
private val availableTracks = mutableMapOf<String, AssTrack>()
|
||||
|
||||
/** Fonts encountered before any ASS track was created. Flushed in [createTrack]. */
|
||||
private val pendingFonts = mutableListOf<Pair<String, ByteArray>>()
|
||||
|
||||
/** The size of the video track. */
|
||||
var videoSize = Size.ZERO
|
||||
private set
|
||||
|
||||
/** The size of the surface on which subtitles are rendered. */
|
||||
var surfaceSize = Size.ZERO
|
||||
private set
|
||||
|
||||
/**
|
||||
* True once an overlay widget reported its surface size via [setOverlaySurfaceSize].
|
||||
* From then on the Player.Listener surface size (= the video output surface, which
|
||||
* may differ from the subtitle overlay once the overlay is parented elsewhere) is
|
||||
* ignored as a frame-size source.
|
||||
*/
|
||||
private var overlaySizeFromWidget = false
|
||||
|
||||
/** mpv-style margins of the video rect within the frame: top, bottom, left, right. */
|
||||
private var margins: IntArray? = null
|
||||
|
||||
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
|
||||
private var useMargins = false
|
||||
|
||||
/**
|
||||
* Per-video-frame callback. Fired by ExoPlayer just before MediaCodec releases the frame
|
||||
* to the output surface. Carries the exact PTS of the frame and the System.nanoTime()
|
||||
* domain target release time, so subtitle renderers can align composition to the same
|
||||
* display vsync as the video.
|
||||
*
|
||||
* - [presentationTimeUs] is track-relative microseconds matching the subtitle track's PTS.
|
||||
* - [releaseTimeNs] may be [androidx.media3.common.C.TIME_UNSET] in rare paths.
|
||||
*
|
||||
* Invoked on the playback thread.
|
||||
*/
|
||||
var videoFrameCallback: ((presentationTimeUs: Long, releaseTimeNs: Long) -> Unit)? = null
|
||||
|
||||
private val videoFrameMetadataListener = VideoFrameMetadataListener { pts, releaseNs, _, _ ->
|
||||
videoFrameCallback?.invoke(pts, releaseNs)
|
||||
}
|
||||
|
||||
private var player: ExoPlayer? = null
|
||||
|
||||
/** The current selected ass format. */
|
||||
private var format: Format? = null
|
||||
|
||||
/**
|
||||
* Initializes the handler with the provided ExoPlayer instance.
|
||||
* @param player The ExoPlayer instance to attach to.
|
||||
*/
|
||||
fun init(player: ExoPlayer) {
|
||||
this.player = player
|
||||
player.addListener(this)
|
||||
player.setVideoFrameMetadataListener(videoFrameMetadataListener)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles transitions between media items in the player and resets everything to the initial
|
||||
* state.
|
||||
*/
|
||||
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
||||
super.onMediaItemTransition(mediaItem, reason)
|
||||
Log.i("AssHandler", "onMediaItemTransition: item = $mediaItem, reason = $reason")
|
||||
resetMediaState(releaseNative = true)
|
||||
}
|
||||
|
||||
private fun resetMediaState(releaseNative: Boolean) {
|
||||
val oldRender = render
|
||||
val oldTracks = availableTracks.values.toList()
|
||||
|
||||
render = null
|
||||
track = null
|
||||
format = null
|
||||
availableTracks.clear()
|
||||
pendingFonts.clear()
|
||||
videoSize = Size.ZERO
|
||||
renderCallback?.invoke(null)
|
||||
|
||||
if (releaseNative) {
|
||||
oldRender?.release()
|
||||
oldTracks.forEach { it.release() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles changes to the tracks available in the current media.
|
||||
* Configures the selected ASS track if available.
|
||||
* @param tracks The selected tracks.
|
||||
*/
|
||||
override fun onTracksChanged(tracks: Tracks) {
|
||||
Log.i("AssHandler", "onTracksChanged $tracks")
|
||||
|
||||
val selectedVideoTrack = getSelectedVideoTrack(tracks)
|
||||
if (selectedVideoTrack != null) {
|
||||
setVideoSize(selectedVideoTrack.width, selectedVideoTrack.height)
|
||||
}
|
||||
|
||||
format = getSelectedAssTrack(tracks)
|
||||
if (format == null) {
|
||||
Log.i("AssHandler", "subtitle track disabled")
|
||||
track = null
|
||||
render?.setTrack(null)
|
||||
return
|
||||
}
|
||||
|
||||
updateTrack()
|
||||
}
|
||||
|
||||
private fun updateTrack() {
|
||||
val track = availableTracks.firstNotNullOfOrNull {
|
||||
// When media without external subtitles, format id will not change.
|
||||
// When media with external subtitles, format will become like 1:1 .
|
||||
// So to compat both situation, we extract the actual id after the colon.
|
||||
if (format?.id?.substringAfter(":") == it.key) {
|
||||
it.value
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
if (track == null || this.track == track) return
|
||||
|
||||
Log.i("AssHandler", "subtitle track changed to $format")
|
||||
this.track = track
|
||||
val render = requireNotNull(render)
|
||||
applyRenderState(render)
|
||||
render.setTrack(track)
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)applies sizing and margin state to [render]. Called whenever a render is
|
||||
* (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(scaledForRender(surfaceSize.width), scaledForRender(surfaceSize.height))
|
||||
// Fallback frame until the overlay surface reports its size.
|
||||
videoSize.isValid -> render.setFrameSize(scaledForRender(videoSize.width), scaledForRender(videoSize.height))
|
||||
}
|
||||
margins?.let { m -> render.setMargins(scaledForRender(m[0]), scaledForRender(m[1]), scaledForRender(m[2]), scaledForRender(m[3])) }
|
||||
render.setUseMargins(useMargins)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles changes to the surface size for video playback.
|
||||
* Notifies the callback if the size has changed.
|
||||
* @param width The new width of the surface.
|
||||
* @param height The new height of the surface.
|
||||
*/
|
||||
override fun onSurfaceSizeChanged(width: Int, height: Int) {
|
||||
super.onSurfaceSizeChanged(width, height)
|
||||
Log.i("AssHandler", "onSurfaceSizeChanged: width = $width, height = $height")
|
||||
// The video output surface is only a frame-size proxy until an overlay widget
|
||||
// reports its own size — they diverge when the overlay isn't video-rect-sized.
|
||||
if (overlaySizeFromWidget) return
|
||||
if (surfaceSize.width == width && surfaceSize.height == height) return
|
||||
surfaceSize = Size(width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports the subtitle overlay widget's actual surface size — the authoritative
|
||||
* libass frame size for OVERLAY render types.
|
||||
*/
|
||||
fun setOverlaySurfaceSize(width: Int, height: Int) {
|
||||
overlaySizeFromWidget = true
|
||||
if (surfaceSize.width == width && surfaceSize.height == height) return
|
||||
Log.i("AssHandler", "setOverlaySurfaceSize: width = $width, height = $height")
|
||||
surfaceSize = Size(width, height)
|
||||
render?.setFrameSize(scaledForRender(width), scaledForRender(height))
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets mpv-style frame margins: the offsets of the video dst rect within the libass
|
||||
* frame ([setOverlaySurfaceSize]); negative when the video extends beyond the frame.
|
||||
* Applied to the current render and re-applied whenever a render is (re)created.
|
||||
*/
|
||||
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
|
||||
margins = intArrayOf(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
|
||||
render?.setUseMargins(use)
|
||||
}
|
||||
|
||||
override fun onVideoSizeChanged(videoSize: VideoSize) {
|
||||
super.onVideoSizeChanged(videoSize)
|
||||
this.videoSize = Size(videoSize.width, videoSize.height)
|
||||
Log.i("AssHandler", "onVideoSizeChanged: width = ${videoSize.width}, height = ${videoSize.height}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the video size for the ASS renderer. Called as soon as the video size is known in
|
||||
* order to properly render subtitles.
|
||||
* @param width The width of the video.
|
||||
* @param height The height of the video.
|
||||
*/
|
||||
fun setVideoSize(width: Int, height: Int) {
|
||||
Log.i("AssHandler", "setVideoSize: width = $width, height = $height")
|
||||
videoSize = Size(width, height)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the current media has ASS tracks, false otherwise.
|
||||
*/
|
||||
fun hasTracks(): Boolean = availableTracks.isNotEmpty()
|
||||
|
||||
/**
|
||||
* Adds a font to the ASS library. If no tracks have been created yet, the font is buffered
|
||||
* and will be added when the first track is created via [createTrack].
|
||||
*/
|
||||
@Synchronized
|
||||
fun addFont(name: String, data: ByteArray) {
|
||||
if (hasTracks()) {
|
||||
ass.addFont(name, data)
|
||||
} else {
|
||||
pendingFonts.add(name to data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new ASS track from the given format and saves it in the [availableTracks].
|
||||
* The renderer and libass are also created if needed.
|
||||
* @param format The format of the ASS track.
|
||||
* @return The created ASS track.
|
||||
*/
|
||||
@Synchronized
|
||||
fun createTrack(format: Format): AssTrack {
|
||||
Log.i("AssHandler", "createTrack: format = $format")
|
||||
// Ensure the renderer is created before creating tracks.
|
||||
createRenderIfNeeded()
|
||||
|
||||
// Flush any fonts that were buffered before the first track was created.
|
||||
if (pendingFonts.isNotEmpty()) {
|
||||
for ((name, data) in pendingFonts) {
|
||||
ass.addFont(name, data)
|
||||
}
|
||||
pendingFonts.clear()
|
||||
}
|
||||
|
||||
val track = ass.createTrack()
|
||||
if (format.initializationData.size > 0) {
|
||||
val header = AssHeaderParser.parse(format)
|
||||
track.readBuffer(header)
|
||||
}
|
||||
availableTracks[format.id!!] = track
|
||||
|
||||
updateTrack()
|
||||
|
||||
return track
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the ASS renderer is created if it does not already exist.
|
||||
*/
|
||||
private fun createRenderIfNeeded() {
|
||||
if (render != null) return
|
||||
Log.i("AssHandler", "createRender (cacheSize: ${config.cacheSize}MB, glyphSize: ${config.glyphSize})")
|
||||
render = ass.createRender().also { render ->
|
||||
render.setCacheLimit(config.glyphSize, config.cacheSize)
|
||||
applyRenderState(render)
|
||||
}
|
||||
renderCallback?.invoke(render)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a dialogue into the track of the given [trackId].
|
||||
* Thread-safe: AssTrack.readChunk internally acquires the shared libass lock.
|
||||
*/
|
||||
fun readTrackDialogue(
|
||||
trackId: String?,
|
||||
start: Long,
|
||||
duration: Long,
|
||||
data: ByteArray,
|
||||
offset: Int = 0,
|
||||
length: Int = data.size
|
||||
) {
|
||||
val t = availableTracks[trackId] ?: return
|
||||
t.readChunk(start, duration, data, offset, length)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the selected video track, if any.
|
||||
*/
|
||||
private fun getSelectedVideoTrack(tracks: Tracks): Format? = tracks.groups.find { group ->
|
||||
if (group.isSelected) {
|
||||
(0 until group.length).any { index ->
|
||||
val track = group.getTrackFormat(index)
|
||||
MimeTypes.isVideo(track.sampleMimeType)
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}?.getTrackFormat(0)
|
||||
|
||||
/**
|
||||
* Retrieves the ID of the selected ASS track, if any.
|
||||
* @param tracks The selected tracks.
|
||||
* @return The ID of the selected ASS track, or null if none.
|
||||
*/
|
||||
private fun getSelectedAssTrack(tracks: Tracks): Format? = tracks.groups.find { group ->
|
||||
if (group.isSelected) {
|
||||
(0 until group.length).any { index ->
|
||||
val track = group.getTrackFormat(index)
|
||||
track.sampleMimeType == TEXT_SSA || track.codecs == TEXT_SSA
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}?.getTrackFormat(0)
|
||||
|
||||
/**
|
||||
* Releases all native resources held by this handler.
|
||||
*/
|
||||
fun release() {
|
||||
videoFrameCallback = null
|
||||
player?.clearVideoFrameMetadataListener(videoFrameMetadataListener)
|
||||
player = null
|
||||
resetMediaState(releaseNative = true)
|
||||
if (assDelegate.isInitialized()) {
|
||||
ass.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the size is valid (both width and height are greater than 0).
|
||||
*/
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.edde746.plezy.libass.media
|
||||
|
||||
data class AssHandlerConfig(
|
||||
val glyphSize: Int = 10000,
|
||||
val cacheSize: Int = 128
|
||||
)
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.edde746.plezy.libass.media.extractor
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.mkv.EbmlProcessor
|
||||
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.text.AssSubtitleExtractorOutput
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
open class AssMatroskaExtractor(
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
private val assHandler: AssHandler,
|
||||
flags: Int = 0
|
||||
) : MatroskaExtractor(subtitleParserFactory, flags) {
|
||||
|
||||
private var currentAttachmentName: String? = null
|
||||
private var currentAttachmentMime: String? = null
|
||||
|
||||
internal val subtitleSample = subtitleSampleField.get(this) as ParsableByteArray
|
||||
|
||||
override fun getElementType(id: Int): Int = when (id) {
|
||||
ID_ATTACHMENTS -> EbmlProcessor.ELEMENT_TYPE_MASTER
|
||||
ID_ATTACHED_FILE -> EbmlProcessor.ELEMENT_TYPE_MASTER
|
||||
ID_FILE_NAME -> EbmlProcessor.ELEMENT_TYPE_STRING
|
||||
ID_FILE_MIME_TYPE -> EbmlProcessor.ELEMENT_TYPE_STRING
|
||||
ID_FILE_DATA -> EbmlProcessor.ELEMENT_TYPE_BINARY
|
||||
else -> super.getElementType(id)
|
||||
}
|
||||
|
||||
override fun isLevel1Element(id: Int): Boolean = super.isLevel1Element(id) || id == ID_ATTACHMENTS
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
when (id) {
|
||||
ID_EBML -> {
|
||||
val currentExtractor = extractorOutput.get(this) as ExtractorOutput
|
||||
if (currentExtractor !is AssSubtitleExtractorOutput) {
|
||||
extractorOutput.set(
|
||||
this,
|
||||
AssSubtitleExtractorOutput(currentExtractor, assHandler, this)
|
||||
)
|
||||
}
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
}
|
||||
ID_ATTACHED_FILE -> clearAttachment()
|
||||
else -> super.startMasterElement(id, contentPosition, contentSize)
|
||||
}
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
when (id) {
|
||||
ID_VIDEO -> {
|
||||
// We need to get the video dimensions very early
|
||||
val track = getCurrentTrack(id)
|
||||
assHandler.setVideoSize(track.width, track.height)
|
||||
super.endMasterElement(id)
|
||||
}
|
||||
ID_ATTACHED_FILE -> clearAttachment()
|
||||
else -> super.endMasterElement(id)
|
||||
}
|
||||
}
|
||||
|
||||
override fun stringElement(id: Int, value: String) {
|
||||
when (id) {
|
||||
ID_FILE_NAME -> currentAttachmentName = value
|
||||
ID_FILE_MIME_TYPE -> currentAttachmentMime = value
|
||||
else -> super.stringElement(id, value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
|
||||
when (id) {
|
||||
ID_FILE_DATA -> {
|
||||
val attachmentName = requireNotNull(currentAttachmentName)
|
||||
val attachmentMime = requireNotNull(currentAttachmentMime)
|
||||
|
||||
if (attachmentMime in fontMimeTypes) {
|
||||
val data = ByteArray(contentSize)
|
||||
input.readFully(data, 0, contentSize)
|
||||
assHandler.addFont(attachmentName, data)
|
||||
} else {
|
||||
input.skipFully(contentSize)
|
||||
}
|
||||
}
|
||||
else -> super.binaryElement(id, contentSize, input)
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearAttachment() {
|
||||
currentAttachmentName = null
|
||||
currentAttachmentMime = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ID_EBML = 0x1A45DFA3
|
||||
const val ID_VIDEO = 0xE0
|
||||
const val ID_ATTACHMENTS = 0x1941A469
|
||||
const val ID_ATTACHED_FILE = 0x61A7
|
||||
const val ID_FILE_NAME = 0x466E
|
||||
const val ID_FILE_MIME_TYPE = 0x4660
|
||||
const val ID_FILE_DATA = 0x465C
|
||||
|
||||
val fontMimeTypes = listOf(
|
||||
"font/ttf",
|
||||
"font/otf",
|
||||
"font/sfnt",
|
||||
"font/woff",
|
||||
"font/woff2",
|
||||
"application/font-sfnt",
|
||||
"application/font-woff",
|
||||
"application/x-truetype-font",
|
||||
"application/vnd.ms-opentype",
|
||||
"application/x-font-ttf"
|
||||
)
|
||||
|
||||
val extractorOutput = MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
val subtitleSampleField = MatroskaExtractor::class.java.getDeclaredField("subtitleSample").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.Consumer
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.text.CuesWithTiming
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.AssTrack
|
||||
|
||||
/**
|
||||
* Parser for full (non-embedded) ASS documents, e.g. external sidecar files.
|
||||
* Feeds the whole document into the libass track; rendering happens on the
|
||||
* overlay surface, so no Media3 cues are emitted.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssFullSubtitleParser(private val track: AssTrack) : SubtitleParser {
|
||||
|
||||
override fun parse(
|
||||
data: ByteArray,
|
||||
offset: Int,
|
||||
length: Int,
|
||||
outputOptions: SubtitleParser.OutputOptions,
|
||||
output: Consumer<CuesWithTiming>
|
||||
) {
|
||||
track.readBuffer(data, offset, length)
|
||||
}
|
||||
|
||||
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
object AssHeaderParser {
|
||||
|
||||
private const val ASS_EVENTS = "[Events]\n" +
|
||||
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
|
||||
|
||||
/**
|
||||
* Fix some ass header with error end.
|
||||
* https://github.com/jellyfin/jellyfin-ffmpeg/issues/506
|
||||
*/
|
||||
private fun fixAssHeaderIfNeed(buffer: ByteArray): ByteArray = if (buffer[buffer.size - 1] != 0.toByte()) {
|
||||
// validate ass header
|
||||
buffer
|
||||
} else {
|
||||
// remote the last null character and append the events tag
|
||||
(String(buffer, 0, buffer.size - 1) + "\n" + ASS_EVENTS).toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the headers from the initialization data of the given [format]. The original
|
||||
* headers are preserved (duplication checks are handled by libass).
|
||||
*/
|
||||
fun parse(format: Format): ByteArray = fixAssHeaderIfNeed(format.initializationData[1])
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.Consumer
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.text.CuesWithTiming
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
|
||||
/**
|
||||
* No operation subtitle parser.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssNoOpSubtitleParser : SubtitleParser {
|
||||
override fun parse(
|
||||
p0: ByteArray,
|
||||
p1: Int,
|
||||
p2: Int,
|
||||
p3: SubtitleParser.OutputOptions,
|
||||
p4: Consumer<CuesWithTiming>
|
||||
) {
|
||||
}
|
||||
|
||||
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.edde746.plezy.libass.media.parser
|
||||
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
|
||||
@UnstableApi
|
||||
class AssSubtitleParserFactory(private val assHandler: AssHandler) : SubtitleParser.Factory {
|
||||
|
||||
private val defaultSubtitleParserFactory = DefaultSubtitleParserFactory()
|
||||
|
||||
override fun supportsFormat(format: Format): Boolean = defaultSubtitleParserFactory.supportsFormat(format)
|
||||
|
||||
override fun getCueReplacementBehavior(format: Format): Int = defaultSubtitleParserFactory.getCueReplacementBehavior(format)
|
||||
|
||||
override fun create(format: Format): SubtitleParser = if (format.sampleMimeType == MimeTypes.TEXT_SSA) {
|
||||
val embeddedSubtitles = MimeTypes.VIDEO_MATROSKA
|
||||
.contentEquals(format.containerMimeType)
|
||||
val track = assHandler.createTrack(format)
|
||||
if (embeddedSubtitles) {
|
||||
// Embedded dialogue lines reach libass via AssTrackOutput; nothing to parse here.
|
||||
AssNoOpSubtitleParser()
|
||||
} else {
|
||||
AssFullSubtitleParser(track)
|
||||
}
|
||||
} else {
|
||||
defaultSubtitleParserFactory.create(format)
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.edde746.plezy.libass.media.text
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
|
||||
/**
|
||||
* This class is only used by the overlay renderer. It's needed to get the start time of the subtitles.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssSubtitleExtractorOutput(
|
||||
private val delegate: ExtractorOutput,
|
||||
private val assHandler: AssHandler,
|
||||
private val extractor: AssMatroskaExtractor
|
||||
) : ExtractorOutput by delegate {
|
||||
override fun track(id: Int, type: Int): TrackOutput = if (type == C.TRACK_TYPE_TEXT) {
|
||||
// We can't know at this time if the subtitle track is ASS or other format, so we wrap
|
||||
// every subtitle track
|
||||
AssTrackOutput(delegate.track(id, type), assHandler, extractor)
|
||||
} else {
|
||||
delegate.track(id, type)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.edde746.plezy.libass.media.text
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.common.util.Util
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
import java.util.regex.Pattern
|
||||
|
||||
/**
|
||||
* This class is only used by the overlay renderer. It's needed to get the start time of the subtitles.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val assHandler: AssHandler,
|
||||
private val extractor: AssMatroskaExtractor
|
||||
) : TrackOutput by delegate {
|
||||
|
||||
private var isAss = false
|
||||
|
||||
private var trackId: String? = null
|
||||
|
||||
override fun format(format: Format) {
|
||||
if (format.sampleMimeType == MimeTypes.TEXT_SSA || format.codecs == MimeTypes.TEXT_SSA) {
|
||||
isAss = true
|
||||
trackId = format.id
|
||||
}
|
||||
delegate.format(format)
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (isAss && timeUs.isValidTs) {
|
||||
val sample = extractor.subtitleSample
|
||||
val endIndex = findTokenIndex(sample.data, 1)
|
||||
val lineIndex = findTokenIndex(sample.data, 2)
|
||||
|
||||
val rawDuration = sample.data.decodeToString(endIndex, lineIndex - 1)
|
||||
val durationUs = parseTimecodeUs(rawDuration)
|
||||
|
||||
assHandler.readTrackDialogue(
|
||||
trackId = trackId,
|
||||
start = timeUs / 1000,
|
||||
duration = durationUs / 1000,
|
||||
data = sample.data,
|
||||
offset = lineIndex,
|
||||
length = sample.limit() - lineIndex
|
||||
)
|
||||
}
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
}
|
||||
|
||||
private fun parseTimecodeUs(timeString: String): Long {
|
||||
val matcher = SSA_TIMECODE_PATTERN.matcher(timeString.trim { it <= ' ' })
|
||||
if (!matcher.matches()) {
|
||||
return C.TIME_UNSET
|
||||
}
|
||||
var timestampUs =
|
||||
Util.castNonNull(matcher.group(1)).toLong() * 60 * 60 * C.MICROS_PER_SECOND
|
||||
timestampUs += Util.castNonNull(matcher.group(2)).toLong() * 60 * C.MICROS_PER_SECOND
|
||||
timestampUs += Util.castNonNull(matcher.group(3)).toLong() * C.MICROS_PER_SECOND
|
||||
timestampUs += Util.castNonNull(matcher.group(4)).toLong() * 10000
|
||||
return timestampUs
|
||||
}
|
||||
|
||||
private fun findTokenIndex(array: ByteArray, tokenNumber: Int): Int {
|
||||
if (tokenNumber == 0) return 0
|
||||
var tokensFound = 0
|
||||
array.forEachIndexed { index, byte ->
|
||||
if (byte == COMMA && ++tokensFound == tokenNumber) {
|
||||
return index + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
private val Long.isValidTs
|
||||
get() = this != C.TIME_UNSET
|
||||
|
||||
private companion object {
|
||||
val SSA_TIMECODE_PATTERN: Pattern =
|
||||
Pattern.compile("""(?:(\d+):)?(\d+):(\d+)[:.](\d+)""")
|
||||
|
||||
const val COMMA = ','.code.toByte()
|
||||
}
|
||||
}
|
||||
+1588
File diff suppressed because it is too large
Load Diff
+177
@@ -0,0 +1,177 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.graphics.PixelFormat
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
|
||||
/**
|
||||
* Subtitle overlay rendered through a dedicated [SurfaceView] layer.
|
||||
*
|
||||
* Uses a SurfaceFlinger layer directly, which lets the atlas-based pipeline
|
||||
* vsync-align its swap with the corresponding video frame via
|
||||
* `eglPresentationTimeANDROID`.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssSubtitleSurfaceView(
|
||||
context: Context,
|
||||
private val assHandler: AssHandler
|
||||
) : SurfaceView(context),
|
||||
SurfaceHolder.Callback {
|
||||
|
||||
private var pipeline: AssAtlasPipeline? = null
|
||||
private var preSwapProbe: ((Long) -> Unit)? = null
|
||||
|
||||
init {
|
||||
setZOrderMediaOverlay(true)
|
||||
holder.setFormat(PixelFormat.TRANSLUCENT)
|
||||
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)
|
||||
}
|
||||
|
||||
/** Re-renders the last position, e.g. after margin changes while paused. */
|
||||
fun invalidateSubtitles() {
|
||||
pipeline?.invalidate()
|
||||
}
|
||||
|
||||
/** Vsync-pinned swaps performed by the current pipeline. */
|
||||
val swapCount: Long get() = pipeline?.swapCount ?: 0L
|
||||
|
||||
/** Pinned swaps that finished past the swap-time budget (possible missed vsync). */
|
||||
val lateSwapCount: Long get() = pipeline?.lateSwapCount ?: 0L
|
||||
|
||||
/** Worst observed swap lateness past the target release time, in milliseconds. */
|
||||
val maxLateMs: Long get() = pipeline?.maxLateMs ?: 0L
|
||||
|
||||
/** Total libass renders performed by the current pipeline. */
|
||||
val renderCount: Long get() = pipeline?.renderCount ?: 0L
|
||||
|
||||
/** Renders where libass reported changed content. */
|
||||
val changedRenderCount: Long get() = pipeline?.changedRenderCount ?: 0L
|
||||
|
||||
/** Renders that overflowed the atlas/vertex capacity. */
|
||||
val overflowCount: Long get() = pipeline?.overflowCount ?: 0L
|
||||
|
||||
/** Duration of the most recent libass render, in milliseconds. */
|
||||
val lastLibassMs: Long get() = pipeline?.lastLibassMs ?: 0L
|
||||
|
||||
/** Worst observed libass render duration, in milliseconds. */
|
||||
val maxLibassMs: Long get() = pipeline?.maxLibassMs ?: 0L
|
||||
|
||||
/** Changed-render duration histogram: [≤10ms, ≤25ms, ≤42ms, ≤84ms, >84ms]. */
|
||||
val libassMsHistogram: List<Long> get() = pipeline?.libassMsHistogram ?: emptyList()
|
||||
|
||||
/** Requests served from a pre-rendered (speculative) frame. */
|
||||
val specHits: Long get() = pipeline?.specHits ?: 0L
|
||||
|
||||
/** Requests where speculation existed but didn't match (seek, state change). */
|
||||
val specMisses: Long get() = pipeline?.specMisses ?: 0L
|
||||
|
||||
/** 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
|
||||
// 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) {
|
||||
assHandler.setOverlaySurfaceSize(width, height)
|
||||
pipeline?.onSurfaceSizeChanged(width, height)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
pipeline?.releaseAndWait()
|
||||
pipeline = null
|
||||
}
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
|
||||
/**
|
||||
* Decision core of the speculative render-ahead pipeline.
|
||||
*
|
||||
* The problem it solves: ExoPlayer's frame-metadata callback gives only ~40 ms
|
||||
* between "video frame scheduled" and that frame's vsync, while a changed-content
|
||||
* libass render can take longer — so a render started at the callback lands a
|
||||
* frame (or more) late. The engine renders the *predicted next* PTS right after
|
||||
* servicing the current one, in the dead time between frames; when the next
|
||||
* request matches the prediction, only the GL upload+swap (~6–11 ms) sits inside
|
||||
* the deadline.
|
||||
*
|
||||
* Pure logic, single-threaded (the libass worker) — rendering, buffers and GL
|
||||
* are behind injected closures, so the state machine is unit-testable. Only the
|
||||
* stat fields are read from other threads.
|
||||
*
|
||||
* Slot ownership invariant: a slot handed to GL ([lastPostedSlot]) or currently
|
||||
* read by GL ([glTakenSlot]) is never chosen as a render target. With 3 slots and
|
||||
* at most 2 exclusions a target always exists; with 2 slots (low-RAM devices)
|
||||
* speculation must be disabled and the legacy alternation behavior falls out.
|
||||
*
|
||||
* Key subtlety inherited from libass: `ass_render_frame`'s `changed` flag compares
|
||||
* against libass's *previous render* — which, with speculation, may be content
|
||||
* that never reached the screen. The engine therefore tracks [libassLastSlot]
|
||||
* (the slot holding libass's most recent render output) rather than the last
|
||||
* *posted* slot, and prefers it as the render target: on `changed == 0` the
|
||||
* buffers were untouched and that slot already holds exactly the right content.
|
||||
*/
|
||||
internal class SpecRenderEngine(
|
||||
private val slotCount: Int,
|
||||
private val speculationEnabled: Boolean,
|
||||
/**
|
||||
* Renders the current track at [timeMs] into the slot's buffers. Returns null
|
||||
* when the renderer/track is gone. The closure owns timing/stat accounting.
|
||||
*/
|
||||
private val renderAt: (timeMs: Long, slot: Int) -> AssAtlasFrame?,
|
||||
/**
|
||||
* Renderer identity + state generation as one comparable value. Must change
|
||||
* whenever a speculatively rendered frame could be stale: margins, sizes,
|
||||
* track switches, renderer recreation.
|
||||
*/
|
||||
private val stateGeneration: () -> Long,
|
||||
/** Slot the GL thread most recently took for drawing, or -1. Never write it. */
|
||||
private val glTakenSlot: () -> Int,
|
||||
/** Diagnostic sink for hit/miss/skip decisions; null disables (no string cost). */
|
||||
private val debugLog: ((String) -> Unit)? = null
|
||||
) {
|
||||
|
||||
/** What the caller should do after [service]. */
|
||||
sealed class Outcome {
|
||||
/** Nothing to post (no renderer, or no rendered content exists yet). */
|
||||
object Skip : Outcome()
|
||||
|
||||
/**
|
||||
* Post [slot] to GL. [newContent] means this call wrote fresh content into
|
||||
* the slot (the caller bumps the payload's content seq). [specHit] means the
|
||||
* content was pre-rendered — no libass render ran inside the deadline.
|
||||
*/
|
||||
class Post(val slot: Int, val frame: AssAtlasFrame, val newContent: Boolean, val specHit: Boolean) : Outcome()
|
||||
}
|
||||
|
||||
/** A speculative render that wrote new content into [slot] (bump its seq). */
|
||||
class SpecWrite(val slot: Int, val frame: AssAtlasFrame)
|
||||
|
||||
// Speculation state: content for specPtsUs is pre-rendered and lives either in
|
||||
// specSlot, or — when the spec render returned changed == 0 — is identical to
|
||||
// libassLastSlot's content (specIsLibassLast).
|
||||
private var specPtsUs = UNSET
|
||||
private var specSlot = -1
|
||||
private var specIsLibassLast = false
|
||||
private var specGen = 0L
|
||||
|
||||
// The slot holding libass's most recent render output and its frame.
|
||||
private var libassLastSlot = -1
|
||||
private var libassLastFrame: AssAtlasFrame? = null
|
||||
private var lastPostedSlot = -1
|
||||
|
||||
// Request-cadence estimator over pinned (playing) requests: median of the last
|
||||
// 8 PTS deltas, valid after 4, reset on any non-monotonic or > 250 ms jump.
|
||||
private val deltas = LongArray(DELTA_SAMPLES)
|
||||
private var deltaCount = 0
|
||||
private var deltaIndex = 0
|
||||
private var lastPinnedPtsUs = UNSET
|
||||
|
||||
// Stats; single-writer (the libass thread), read from the stats path.
|
||||
@Volatile
|
||||
var specHits = 0L
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var specMisses = 0L
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
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
|
||||
* estimator and never count as speculation misses against playback.
|
||||
*/
|
||||
fun service(ptsUs: Long, pinned: Boolean): Outcome {
|
||||
if (pinned) updateDeltaEstimator(ptsUs)
|
||||
|
||||
val ptsMs = toLibassMs(ptsUs)
|
||||
if (specPtsUs != UNSET) {
|
||||
val specPtsMs = toLibassMs(specPtsUs)
|
||||
val genNow = stateGeneration()
|
||||
val hit = genNow == specGen && ptsMs == specPtsMs
|
||||
val slot = if (specIsLibassLast) libassLastSlot else specSlot
|
||||
val frame = libassLastFrame
|
||||
val specPts = specPtsUs
|
||||
specPtsUs = UNSET
|
||||
if (hit && slot >= 0 && frame != null) {
|
||||
specHits++
|
||||
lastPostedSlot = 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=${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=${ptsMs}ms")
|
||||
}
|
||||
|
||||
// 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(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
|
||||
lastPostedSlot = lastSlot
|
||||
return Outcome.Post(lastSlot, lastFrame, newContent = false, specHit = false)
|
||||
}
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
lastPostedSlot = target
|
||||
return Outcome.Post(target, frame, newContent = true, specHit = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Speculatively renders the predicted next request ([servicedPtsUs] + median
|
||||
* delta) into a free slot. Call after posting the current frame; skipped while
|
||||
* paused ([pinned] false), when a newer request is already waiting, or while
|
||||
* the cadence estimator has no confident delta.
|
||||
*/
|
||||
fun speculateAfter(servicedPtsUs: Long, pinned: Boolean, hasPending: Boolean): SpecWrite? {
|
||||
if (!speculationEnabled) return null
|
||||
if (!pinned || hasPending || !deltaValid()) {
|
||||
specSkips++
|
||||
debugLog?.invoke(
|
||||
"spec-skip after=${servicedPtsUs / 1000}ms pinned=$pinned pending=$hasPending cadence=${deltaValid()}"
|
||||
)
|
||||
return null
|
||||
}
|
||||
val target = renderTargetSlot() ?: run {
|
||||
specSkips++
|
||||
debugLog?.invoke("spec-skip after=${servicedPtsUs / 1000}ms no-free-slot")
|
||||
return null
|
||||
}
|
||||
val gen = stateGeneration()
|
||||
val specPts = servicedPtsUs + medianDeltaUs()
|
||||
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
|
||||
specSlot = -1
|
||||
return null
|
||||
}
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
specIsLibassLast = false
|
||||
specSlot = target
|
||||
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 —
|
||||
* heavy typesetting otherwise pays its cache-cold rasterization (measured
|
||||
* 0.8–2.6 s on weak devices) exactly when the sign appears. The result is
|
||||
* never posted; like any render it becomes libass's last-rendered content,
|
||||
* so any pending speculation is invalidated first (its slot/content
|
||||
* references would go stale).
|
||||
*
|
||||
* Returns the slot written (caller bumps its content seq) or null when
|
||||
* nothing was rendered.
|
||||
*/
|
||||
fun prefetch(ptsUs: Long): SpecWrite? {
|
||||
specPtsUs = UNSET
|
||||
val target = renderTargetSlot() ?: return null
|
||||
val frame = renderAt(toLibassMs(ptsUs), target) ?: return null
|
||||
prefetchCount++
|
||||
if (frame.changed == 0) return null
|
||||
libassLastSlot = target
|
||||
libassLastFrame = frame
|
||||
return SpecWrite(target, frame)
|
||||
}
|
||||
|
||||
/** Cache-warming prefetch renders performed; single-writer, read cross-thread. */
|
||||
@Volatile
|
||||
var prefetchCount = 0L
|
||||
private set
|
||||
|
||||
private fun renderTargetSlot(): Int? {
|
||||
// The GL exclusion only exists in ≥3-slot mode; with 2 slots this reduces to
|
||||
// the legacy "don't write the posted slot" alternation.
|
||||
val taken = if (slotCount > 2) glTakenSlot() else -1
|
||||
val last = libassLastSlot
|
||||
if (last >= 0 && last != lastPostedSlot && last != taken) return last
|
||||
for (s in 0 until slotCount) {
|
||||
if (s != lastPostedSlot && s != taken) return s
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun updateDeltaEstimator(ptsUs: Long) {
|
||||
val prev = lastPinnedPtsUs
|
||||
lastPinnedPtsUs = ptsUs
|
||||
if (prev == UNSET) return
|
||||
val d = ptsUs - prev
|
||||
if (d <= 0 || d > MAX_DELTA_US) {
|
||||
// Seek/discontinuity (or duplicate PTS): forget the cadence.
|
||||
deltaCount = 0
|
||||
deltaIndex = 0
|
||||
return
|
||||
}
|
||||
deltas[deltaIndex] = d
|
||||
deltaIndex = (deltaIndex + 1) % DELTA_SAMPLES
|
||||
if (deltaCount < DELTA_SAMPLES) deltaCount++
|
||||
}
|
||||
|
||||
private fun deltaValid() = deltaCount >= MIN_DELTA_SAMPLES
|
||||
|
||||
private fun medianDeltaUs(): Long {
|
||||
val copy = deltas.copyOfRange(0, deltaCount)
|
||||
copy.sort()
|
||||
return copy[deltaCount / 2]
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Tests for the speculative render-ahead state machine. The render function is
|
||||
* scripted: each call records (timeMs, slot) and returns the next queued frame.
|
||||
*/
|
||||
class SpecRenderEngineTest {
|
||||
|
||||
private class RenderCall(val timeMs: Long, val slot: Int)
|
||||
|
||||
private class Harness(
|
||||
slotCount: Int = 3,
|
||||
speculationEnabled: Boolean = true
|
||||
) {
|
||||
val calls = mutableListOf<RenderCall>()
|
||||
val script = ArrayDeque<AssAtlasFrame?>()
|
||||
var generation = 0L
|
||||
var glTaken = -1
|
||||
|
||||
val engine = SpecRenderEngine(
|
||||
slotCount = slotCount,
|
||||
speculationEnabled = speculationEnabled,
|
||||
renderAt = { timeMs, slot ->
|
||||
calls.add(RenderCall(timeMs, slot))
|
||||
if (script.isEmpty()) changed() else script.removeFirst()
|
||||
},
|
||||
stateGeneration = { generation },
|
||||
glTakenSlot = { glTaken }
|
||||
)
|
||||
|
||||
/** Primes the cadence estimator with [n] steady requests; returns last pts. */
|
||||
fun prime(n: Int = 5, startUs: Long = 0L, deltaUs: Long = 42_000L): Long {
|
||||
var pts = startUs
|
||||
repeat(n) {
|
||||
engine.service(pts, pinned = true)
|
||||
engine.speculateAfter(pts, pinned = true, hasPending = false)
|
||||
pts += deltaUs
|
||||
}
|
||||
return pts - deltaUs
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val DELTA = 42_000L
|
||||
|
||||
fun changed(quads: Int = 5) = AssAtlasFrame(2048, 100, quads, 2, 0)
|
||||
|
||||
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = true)
|
||||
|
||||
fun blankUnchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = false)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `steady state hits serve without rendering`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
// Cadence is confident by now: the last speculateAfter pre-rendered last+Δ.
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(last + DELTA, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
outcome as SpecRenderEngine.Outcome.Post
|
||||
assertTrue(outcome.specHit)
|
||||
assertFalse(outcome.newContent) // content was written (and seq-bumped) at spec time
|
||||
assertEquals("service must not render on a hit", before, h.calls.size)
|
||||
assertEquals(1L, h.engine.specHits)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hit tolerates jitter only within the same libass millisecond`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
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()
|
||||
val last = h.prime()
|
||||
val specSlot = h.calls.last().slot // where the speculative content went
|
||||
|
||||
val before = h.calls.size
|
||||
h.script.add(changed())
|
||||
val outcome = h.engine.service(last + 1_000_000, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
outcome as SpecRenderEngine.Outcome.Post
|
||||
assertFalse(outcome.specHit)
|
||||
assertTrue(outcome.newContent)
|
||||
assertEquals(before + 1, h.calls.size)
|
||||
assertEquals("miss must render into the slot holding libass's last content", specSlot, h.calls.last().slot)
|
||||
assertEquals(1L, h.engine.specMisses)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `miss with changed 0 posts the spec slot not stale screen content`() {
|
||||
// The trap: spec rendered NEW content (never posted); a mismatched request
|
||||
// then returns changed == 0 (identical to libass's LAST render = the spec
|
||||
// content). Posting "last posted" content would be stale — the engine must
|
||||
// post the slot libass last wrote.
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
val specSlot = h.calls.last().slot
|
||||
|
||||
h.script.add(unchanged())
|
||||
val outcome = h.engine.service(last + 200_000, pinned = true) // > ε, miss; estimator resets too
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
outcome as SpecRenderEngine.Outcome.Post
|
||||
assertFalse(outcome.specHit)
|
||||
assertFalse(outcome.newContent)
|
||||
assertEquals("changed==0 must repost libass's last-rendered slot", specSlot, outcome.slot)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `state generation change invalidates speculation`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
h.generation++ // margins/zoom/track switch between spec render and the request
|
||||
h.script.add(changed())
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(last + DELTA, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
assertEquals("stale spec must be re-rendered", before + 1, h.calls.size)
|
||||
assertEquals(1L, h.engine.specMisses)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unpinned requests never feed the estimator or speculate`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
// Paused invalidate-repaint at an arbitrary position.
|
||||
h.script.add(changed())
|
||||
h.engine.service(last, pinned = false)
|
||||
val specBefore = h.calls.size
|
||||
assertNull(h.engine.speculateAfter(last, pinned = false, hasPending = false))
|
||||
assertEquals("unpinned must not speculate", specBefore, h.calls.size)
|
||||
|
||||
// Cadence survives the unpinned request: the next pinned pair still hits.
|
||||
h.engine.service(last + DELTA, pinned = true)
|
||||
h.engine.speculateAfter(last + DELTA, pinned = true, hasPending = false)
|
||||
val outcome = h.engine.service(last + 2 * DELTA, pinned = true)
|
||||
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `speculation skipped while a request is pending`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
val before = h.calls.size
|
||||
|
||||
assertNull(h.engine.speculateAfter(last, pinned = true, hasPending = true))
|
||||
assertEquals(before, h.calls.size)
|
||||
assertTrue(h.engine.specSkips > 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no speculation until cadence is confident`() {
|
||||
val h = Harness()
|
||||
h.engine.service(0, pinned = true)
|
||||
// Only one delta sample so far (needs 4).
|
||||
h.engine.service(DELTA, pinned = true)
|
||||
val before = h.calls.size
|
||||
assertNull(h.engine.speculateAfter(DELTA, pinned = true, hasPending = false))
|
||||
assertEquals(before, h.calls.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `render target avoids posted and gl taken slots`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
val posted = first.slot
|
||||
|
||||
h.glTaken = (posted + 1) % 3
|
||||
h.script.add(changed())
|
||||
val second = h.engine.service(1_000_000, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
|
||||
val expected = (0 until 3).first { it != posted && it != h.glTaken }
|
||||
assertEquals(expected, second.slot)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `changed 0 before any content skips`() {
|
||||
val h = Harness()
|
||||
h.script.add(unchanged())
|
||||
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()
|
||||
h.script.add(null)
|
||||
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two slot mode alternates and never speculates`() {
|
||||
val h = Harness(slotCount = 2, speculationEnabled = false)
|
||||
h.script.add(changed())
|
||||
val a = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertNull(h.engine.speculateAfter(0, pinned = true, hasPending = false))
|
||||
|
||||
h.script.add(changed())
|
||||
val b = h.engine.service(DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertTrue(a.slot != b.slot)
|
||||
assertTrue(a.slot in 0..1 && b.slot in 0..1)
|
||||
assertEquals(0, h.calls.count { it.slot >= 2 })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `static dialogue hit reposts the same slot without new content`() {
|
||||
// Spec render returns changed == 0 (nothing moves): a hit must repost the
|
||||
// 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
|
||||
var pts = 0L
|
||||
repeat(4) {
|
||||
// build cadence; renders return changed for simplicity
|
||||
pts += DELTA
|
||||
h.engine.service(pts, pinned = true)
|
||||
}
|
||||
h.script.add(unchanged()) // speculative render: nothing changes at pts+Δ
|
||||
assertNull(h.engine.speculateAfter(pts, pinned = true, hasPending = false))
|
||||
|
||||
val before = h.calls.size
|
||||
val outcome = h.engine.service(pts + DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
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
|
||||
fun `speculative write reports slot for seq bump`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
h.script.add(changed())
|
||||
val write = h.engine.speculateAfter(last, pinned = true, hasPending = false)
|
||||
assertNotNull(write)
|
||||
assertEquals(h.calls.last().slot, write!!.slot)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `spec predicts pts plus median delta`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
h.script.add(changed())
|
||||
h.engine.speculateAfter(last, pinned = true, hasPending = false)
|
||||
assertEquals((last + DELTA) / 1000, h.calls.last().timeMs)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefetch renders the requested future pts and reports its slot`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
h.engine.service(0, pinned = true) // some content on screen
|
||||
|
||||
h.script.add(changed())
|
||||
val write = h.engine.prefetch(5_000_000)
|
||||
|
||||
assertNotNull(write)
|
||||
assertEquals(5_000L, h.calls.last().timeMs)
|
||||
assertEquals(h.calls.last().slot, write!!.slot)
|
||||
assertEquals(1L, h.engine.prefetchCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefetch invalidates pending speculation`() {
|
||||
// Prefetch rewrites libass's last-rendered content (and possibly the spec
|
||||
// slot itself); a stale spec hit would post future-event content.
|
||||
val h = Harness()
|
||||
val last = h.prime() // leaves a valid spec for last+Δ
|
||||
|
||||
h.script.add(changed())
|
||||
h.engine.prefetch(last + 5_000_000)
|
||||
|
||||
val before = h.calls.size
|
||||
h.script.add(changed())
|
||||
val outcome = h.engine.service(last + DELTA, pinned = true)
|
||||
|
||||
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
|
||||
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
assertEquals("post-prefetch request must render on demand", before + 1, h.calls.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `render after prefetch with changed 0 posts the prefetched slot`() {
|
||||
// changed==0 after a prefetch means "identical to libass's last render" =
|
||||
// the prefetched content — correct exactly when playback reached the
|
||||
// prefetched event. The engine must post that slot, not older content.
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
h.engine.service(0, pinned = true)
|
||||
|
||||
h.script.add(changed())
|
||||
val write = h.engine.prefetch(5_000_000)!!
|
||||
|
||||
h.script.add(unchanged())
|
||||
val outcome = h.engine.service(5_000_000, pinned = true) as SpecRenderEngine.Outcome.Post
|
||||
assertEquals(write.slot, outcome.slot)
|
||||
assertFalse(outcome.newContent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefetch avoids posted and gl taken slots`() {
|
||||
val h = Harness()
|
||||
h.script.add(changed())
|
||||
val posted = (h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post).slot
|
||||
h.glTaken = (posted + 1) % 3
|
||||
|
||||
h.script.add(changed())
|
||||
val write = h.engine.prefetch(5_000_000)
|
||||
|
||||
val expected = (0 until 3).first { it != posted && it != h.glTaken }
|
||||
assertEquals(expected, write!!.slot)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,9 @@ pluginManagement {
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "8.9.1" apply false
|
||||
id("com.android.library") version "8.9.1" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
|
||||
}
|
||||
|
||||
include(":app")
|
||||
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 = 1b0134a2ea04a3b967f61a726b5864351280b420;
|
||||
kind = exactVersion;
|
||||
version = 1.0.12;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "1b0134a2ea04a3b967f61a726b5864351280b420"
|
||||
"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" : "1b0134a2ea04a3b967f61a726b5864351280b420"
|
||||
"revision" : "a453d675493a8abe26dc90f9dc484bc582628358",
|
||||
"version" : "1.0.12"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
import Flutter
|
||||
import UIKit
|
||||
import AVFoundation
|
||||
import MediaPlayer
|
||||
|
||||
@main
|
||||
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
|
||||
private var deviceAdjustmentChannel: FlutterMethodChannel?
|
||||
private var originalBrightness: CGFloat?
|
||||
private var volumeView: MPVolumeView?
|
||||
private weak var volumeSlider: UISlider?
|
||||
|
||||
override func application(
|
||||
_ 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)")
|
||||
}
|
||||
@@ -29,5 +36,128 @@ import AVFoundation
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "MpvPlayerPlugin") {
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
private func registerDeviceAdjustmentChannel(messenger: FlutterBinaryMessenger) {
|
||||
let channel = FlutterMethodChannel(name: "com.plezy/device_adjustment", binaryMessenger: messenger)
|
||||
channel.setMethodCallHandler { [weak self] call, result in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleDeviceAdjustmentCall(call, result: result)
|
||||
}
|
||||
}
|
||||
deviceAdjustmentChannel = channel
|
||||
}
|
||||
|
||||
private func handleDeviceAdjustmentCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
switch call.method {
|
||||
case "getBrightness":
|
||||
result(Double(UIScreen.main.brightness))
|
||||
case "setBrightness":
|
||||
guard let value = normalizedArgument(call.arguments, result: result) else { return }
|
||||
if originalBrightness == nil {
|
||||
originalBrightness = UIScreen.main.brightness
|
||||
}
|
||||
UIScreen.main.brightness = CGFloat(value)
|
||||
result(nil)
|
||||
case "restoreBrightness":
|
||||
if let originalBrightness = originalBrightness {
|
||||
UIScreen.main.brightness = originalBrightness
|
||||
self.originalBrightness = nil
|
||||
}
|
||||
result(nil)
|
||||
case "getMediaVolume":
|
||||
result(Double(AVAudioSession.sharedInstance().outputVolume))
|
||||
case "setMediaVolume":
|
||||
guard let value = normalizedArgument(call.arguments, result: result) else { return }
|
||||
if setMediaVolume(value) {
|
||||
result(nil)
|
||||
} else {
|
||||
result(
|
||||
FlutterError(code: "DEVICE_ADJUSTMENT_UNAVAILABLE", message: "System volume slider unavailable", details: nil)
|
||||
)
|
||||
}
|
||||
default:
|
||||
result(FlutterMethodNotImplemented)
|
||||
}
|
||||
}
|
||||
|
||||
private func normalizedArgument(_ arguments: Any?, result: @escaping FlutterResult) -> Double? {
|
||||
guard let value = arguments as? NSNumber else {
|
||||
result(FlutterError(code: "INVALID_ARGUMENT", message: "Expected a numeric value", details: nil))
|
||||
return nil
|
||||
}
|
||||
let doubleValue = value.doubleValue
|
||||
guard doubleValue.isFinite else {
|
||||
result(FlutterError(code: "INVALID_ARGUMENT", message: "Expected a finite numeric value", details: nil))
|
||||
return nil
|
||||
}
|
||||
return min(1.0, max(0.0, doubleValue))
|
||||
}
|
||||
|
||||
private func setMediaVolume(_ value: Double) -> Bool {
|
||||
guard let slider = ensureVolumeSlider() else { return false }
|
||||
slider.setValue(Float(value), animated: false)
|
||||
slider.sendActions(for: .valueChanged)
|
||||
slider.sendActions(for: .touchUpInside)
|
||||
return true
|
||||
}
|
||||
|
||||
private func ensureVolumeSlider() -> UISlider? {
|
||||
if let volumeSlider = volumeSlider { return volumeSlider }
|
||||
|
||||
let volumeView = self.volumeView ?? MPVolumeView(frame: CGRect(x: -1000, y: -1000, width: 1, height: 1))
|
||||
volumeView.showsRouteButton = false
|
||||
volumeView.showsVolumeSlider = true
|
||||
volumeView.alpha = 0.01
|
||||
volumeView.isUserInteractionEnabled = false
|
||||
|
||||
if volumeView.superview == nil {
|
||||
activeWindow?.addSubview(volumeView)
|
||||
}
|
||||
volumeView.layoutIfNeeded()
|
||||
|
||||
self.volumeView = volumeView
|
||||
let slider = findVolumeSlider(in: volumeView)
|
||||
volumeSlider = slider
|
||||
return slider
|
||||
}
|
||||
|
||||
private func findVolumeSlider(in view: UIView) -> UISlider? {
|
||||
if let slider = view as? UISlider { return slider }
|
||||
for subview in view.subviews {
|
||||
if let slider = findVolumeSlider(in: subview) { return slider }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private var activeWindow: UIWindow? {
|
||||
if #available(iOS 13.0, *) {
|
||||
for scene in UIApplication.shared.connectedScenes {
|
||||
guard let windowScene = scene as? UIWindowScene else { continue }
|
||||
if let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow }) {
|
||||
return keyWindow
|
||||
}
|
||||
}
|
||||
for scene in UIApplication.shared.connectedScenes {
|
||||
guard let windowScene = scene as? UIWindowScene, let window = windowScene.windows.first else { continue }
|
||||
return window
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return UIApplication.shared.windows.first(where: { $0.isKeyWindow }) ?? UIApplication.shared.windows.first
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : {
|
||||
"alpha" : "1.000",
|
||||
"blue" : "0xF8",
|
||||
"green" : "0xF7",
|
||||
"red" : "0xF7"
|
||||
}
|
||||
},
|
||||
"idiom" : "universal"
|
||||
},
|
||||
{
|
||||
"appearances" : [
|
||||
{
|
||||
"appearance" : "luminosity",
|
||||
"value" : "dark"
|
||||
}
|
||||
],
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : {
|
||||
"alpha" : "1.000",
|
||||
"blue" : "0x12",
|
||||
"green" : "0x0F",
|
||||
"red" : "0x0E"
|
||||
}
|
||||
},
|
||||
"idiom" : "universal"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
|
||||
<capability name="Named colors" minToolsVersion="9.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--View Controller-->
|
||||
@@ -19,7 +20,7 @@
|
||||
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
|
||||
</imageView>
|
||||
</subviews>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<color key="backgroundColor" name="LaunchBackground"/>
|
||||
<constraints>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
|
||||
@@ -33,5 +34,8 @@
|
||||
</scenes>
|
||||
<resources>
|
||||
<image name="LaunchImage" width="168" height="185"/>
|
||||
<namedColor name="LaunchBackground">
|
||||
<color red="0.96862745098039216" green="0.96862745098039216" blue="0.97254901960784312" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
</namedColor>
|
||||
</resources>
|
||||
</document>
|
||||
|
||||
@@ -13,10 +13,19 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
private var mainBlankView: UIView?
|
||||
private var isVisible = false
|
||||
private var isDisposed = false
|
||||
private var activeDisplayCriteriaKey: String?
|
||||
private static var activeDisplayCriteriaKey: String?
|
||||
private var lastDisplayCriteriaMutation: DisplayCriteriaMutation = .skipped
|
||||
#if os(tvOS)
|
||||
private var displayModeSwitchWaiter: DisplayModeSwitchWaiter?
|
||||
private var displayModeSwitchWaiterGeneration = 0
|
||||
#endif
|
||||
|
||||
var isPipStarting = false
|
||||
|
||||
private static func log(_ message: String) {
|
||||
NSLog("[MpvPlayerCore] %@", message)
|
||||
}
|
||||
|
||||
func initialize(in window: UIWindow) -> Bool {
|
||||
guard !isInitialized else {
|
||||
print("[MpvPlayerCore] Already initialized")
|
||||
@@ -245,6 +254,7 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
colorMatrix: String?
|
||||
) -> Bool {
|
||||
#if os(tvOS)
|
||||
lastDisplayCriteriaMutation = .skipped
|
||||
guard let window = containerView?.window ?? self.window else { return false }
|
||||
let displayManager = window.avDisplayManager
|
||||
|
||||
@@ -255,7 +265,9 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
|
||||
let refreshRate = Float(fps > 0 ? fps : 0)
|
||||
let sourceHasDolbyVision = doviProfile > 0
|
||||
guard sourceHasDolbyVision || sigPeak > 0 || gamma != nil || primaries != nil || colorMatrix != nil else {
|
||||
guard
|
||||
refreshRate > 0 || sourceHasDolbyVision || sigPeak > 0 || gamma != nil || primaries != nil || colorMatrix != nil
|
||||
else {
|
||||
clearDisplayCriteria(displayManager, reason: "no display metadata")
|
||||
return false
|
||||
}
|
||||
@@ -315,15 +327,20 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
|
||||
let criteriaKey =
|
||||
"\(displayRange.rawValue)|\(refreshRate)|\(width)x\(height)|\(doviProfile)|\(doviLevel)|\(doviCompatibilityId ?? -1)"
|
||||
if activeDisplayCriteriaKey == criteriaKey { return true }
|
||||
if Self.activeDisplayCriteriaKey == criteriaKey && displayManager.preferredDisplayCriteria != nil {
|
||||
lastDisplayCriteriaMutation = .unchanged
|
||||
return true
|
||||
}
|
||||
|
||||
displayManager.preferredDisplayCriteria = AVDisplayCriteria(
|
||||
let displayCriteria = AVDisplayCriteria(
|
||||
refreshRate: refreshRate,
|
||||
formatDescription: formatDescription
|
||||
)
|
||||
activeDisplayCriteriaKey = criteriaKey
|
||||
print(
|
||||
"[MpvPlayerCore] preferredDisplayCriteria set to \(displayRange.rawValue) (source: \(sourceRange.rawValue), fps: \(refreshRate), \(width)x\(height), DV profile: \(doviProfile), level: \(doviLevel), compat: \(doviCompatibilityId ?? -1))"
|
||||
displayManager.preferredDisplayCriteria = displayCriteria
|
||||
Self.activeDisplayCriteriaKey = criteriaKey
|
||||
lastDisplayCriteriaMutation = .set
|
||||
Self.log(
|
||||
"preferredDisplayCriteria set to \(displayRange.rawValue) (source: \(sourceRange.rawValue), fps: \(refreshRate), \(width)x\(height), DV profile: \(doviProfile), level: \(doviLevel), compat: \(doviCompatibilityId ?? -1))"
|
||||
)
|
||||
return true
|
||||
#else
|
||||
@@ -331,6 +348,49 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
#endif
|
||||
}
|
||||
|
||||
func setServerDisplayCriteriaForPlayback(
|
||||
_ criteria: ServerDisplayCriteria?,
|
||||
extraDelayMs: Int,
|
||||
completion: @escaping () -> Void
|
||||
) {
|
||||
let apply = { [weak self] in
|
||||
guard let self else {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
|
||||
self.setServerDisplayCriteria(criteria) { [weak self] applied in
|
||||
guard let self else {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
|
||||
#if os(tvOS)
|
||||
guard applied || self.lastDisplayCriteriaMutation == .cleared else {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
self.waitForDisplayModeSwitchIfNeeded(extraDelayMs: extraDelayMs, completion: completion)
|
||||
#else
|
||||
completion()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
if Thread.isMainThread {
|
||||
apply()
|
||||
} else {
|
||||
DispatchQueue.main.async(execute: apply)
|
||||
}
|
||||
}
|
||||
|
||||
private enum DisplayCriteriaMutation {
|
||||
case skipped
|
||||
case unchanged
|
||||
case set
|
||||
case cleared
|
||||
}
|
||||
|
||||
#if os(tvOS)
|
||||
private enum DisplayDynamicRange: String {
|
||||
case sdr = "SDR"
|
||||
@@ -340,10 +400,197 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
}
|
||||
|
||||
private func clearDisplayCriteria(_ displayManager: AVDisplayManager, reason: String) {
|
||||
if activeDisplayCriteriaKey != nil || displayManager.preferredDisplayCriteria != nil {
|
||||
if Self.activeDisplayCriteriaKey != nil || displayManager.preferredDisplayCriteria != nil {
|
||||
displayManager.preferredDisplayCriteria = nil
|
||||
activeDisplayCriteriaKey = nil
|
||||
print("[MpvPlayerCore] preferredDisplayCriteria cleared (\(reason))")
|
||||
Self.activeDisplayCriteriaKey = nil
|
||||
lastDisplayCriteriaMutation = .cleared
|
||||
Self.log("preferredDisplayCriteria cleared (\(reason))")
|
||||
} else {
|
||||
lastDisplayCriteriaMutation = .unchanged
|
||||
}
|
||||
}
|
||||
|
||||
private func waitForDisplayModeSwitchIfNeeded(extraDelayMs: Int, completion: @escaping () -> Void) {
|
||||
guard let window = containerView?.window ?? self.window else {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
|
||||
let displayManager = window.avDisplayManager
|
||||
let mutation = lastDisplayCriteriaMutation
|
||||
let shouldWaitForStart = mutation == .set || mutation == .cleared
|
||||
if !shouldWaitForStart && !displayManager.isDisplayModeSwitchInProgress {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
|
||||
displayModeSwitchWaiter?.cancel(complete: true)
|
||||
displayModeSwitchWaiterGeneration += 1
|
||||
let waiterGeneration = displayModeSwitchWaiterGeneration
|
||||
let waiter = DisplayModeSwitchWaiter(
|
||||
displayManager: displayManager,
|
||||
shouldWaitForStart: shouldWaitForStart,
|
||||
extraDelayMs: extraDelayMs
|
||||
) { [weak self] in
|
||||
if let self, self.displayModeSwitchWaiterGeneration == waiterGeneration {
|
||||
self.displayModeSwitchWaiter = nil
|
||||
}
|
||||
completion()
|
||||
}
|
||||
displayModeSwitchWaiter = waiter
|
||||
waiter.start()
|
||||
}
|
||||
|
||||
private final class DisplayModeSwitchWaiter {
|
||||
private weak var displayManager: AVDisplayManager?
|
||||
private let shouldWaitForStart: Bool
|
||||
private let extraDelayMs: Int
|
||||
private let completion: () -> Void
|
||||
private var startObserver: NSObjectProtocol?
|
||||
private var endObserver: NSObjectProtocol?
|
||||
private var startWatchdog: DispatchWorkItem?
|
||||
private var endWatchdog: DispatchWorkItem?
|
||||
private var settleWorkItem: DispatchWorkItem?
|
||||
private var finished = false
|
||||
private var completionDelivered = false
|
||||
|
||||
private static let startWindowMs = 500
|
||||
private static let switchWatchdogMs = 8000
|
||||
private static let settleMs = 200
|
||||
|
||||
init(
|
||||
displayManager: AVDisplayManager,
|
||||
shouldWaitForStart: Bool,
|
||||
extraDelayMs: Int,
|
||||
completion: @escaping () -> Void
|
||||
) {
|
||||
self.displayManager = displayManager
|
||||
self.shouldWaitForStart = shouldWaitForStart
|
||||
self.extraDelayMs = max(0, min(extraDelayMs, 10_000))
|
||||
self.completion = completion
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard let displayManager else {
|
||||
finish(waited: false, reason: "manager unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
if displayManager.isDisplayModeSwitchInProgress {
|
||||
beginWaitingForEnd(reason: "already in progress")
|
||||
return
|
||||
}
|
||||
|
||||
guard shouldWaitForStart else {
|
||||
finish(waited: false, reason: "no switch in progress")
|
||||
return
|
||||
}
|
||||
|
||||
let center = NotificationCenter.default
|
||||
startObserver = center.addObserver(
|
||||
forName: .AVDisplayManagerModeSwitchStart,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] _ in
|
||||
self?.beginWaitingForEnd(reason: "start notification")
|
||||
}
|
||||
|
||||
let watchdog = DispatchWorkItem { [weak self] in
|
||||
guard let self else { return }
|
||||
if self.displayManager?.isDisplayModeSwitchInProgress == true {
|
||||
self.beginWaitingForEnd(reason: "progress poll")
|
||||
} else {
|
||||
self.finish(waited: false, reason: "start watchdog")
|
||||
}
|
||||
}
|
||||
startWatchdog = watchdog
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Self.startWindowMs), execute: watchdog)
|
||||
}
|
||||
|
||||
func cancel(complete: Bool = false) {
|
||||
finished = true
|
||||
cleanup()
|
||||
if complete { completeOnce() }
|
||||
}
|
||||
|
||||
private func beginWaitingForEnd(reason: String) {
|
||||
guard !finished else { return }
|
||||
startWatchdog?.cancel()
|
||||
startWatchdog = nil
|
||||
if let startObserver {
|
||||
NotificationCenter.default.removeObserver(startObserver)
|
||||
self.startObserver = nil
|
||||
}
|
||||
|
||||
guard displayManager?.isDisplayModeSwitchInProgress == true else {
|
||||
finish(waited: true, reason: "ended before wait (\(reason))")
|
||||
return
|
||||
}
|
||||
|
||||
let center = NotificationCenter.default
|
||||
endObserver = center.addObserver(
|
||||
forName: .AVDisplayManagerModeSwitchEnd,
|
||||
object: nil,
|
||||
queue: .main
|
||||
) { [weak self] _ in
|
||||
self?.finish(waited: true, reason: "end notification")
|
||||
}
|
||||
|
||||
let watchdog = DispatchWorkItem { [weak self] in
|
||||
self?.finish(waited: true, reason: "end watchdog")
|
||||
}
|
||||
endWatchdog = watchdog
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Self.switchWatchdogMs), execute: watchdog)
|
||||
}
|
||||
|
||||
private func finish(waited: Bool, reason: String) {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
cleanup()
|
||||
|
||||
let delayMs = waited ? Self.settleMs + extraDelayMs : 0
|
||||
MpvPlayerCore.log(
|
||||
"display mode switch wait complete "
|
||||
+ "(\(reason), waited: \(waited), extraDelayMs: \(extraDelayMs))"
|
||||
)
|
||||
guard delayMs > 0 else {
|
||||
completeOnce()
|
||||
return
|
||||
}
|
||||
let workItem = DispatchWorkItem { [weak self] in
|
||||
self?.completeOnce()
|
||||
}
|
||||
settleWorkItem = workItem
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delayMs), execute: workItem)
|
||||
}
|
||||
|
||||
private func completeOnce() {
|
||||
guard !completionDelivered else { return }
|
||||
completionDelivered = true
|
||||
settleWorkItem?.cancel()
|
||||
settleWorkItem = nil
|
||||
completion()
|
||||
}
|
||||
|
||||
private func cleanup() {
|
||||
startWatchdog?.cancel()
|
||||
endWatchdog?.cancel()
|
||||
settleWorkItem?.cancel()
|
||||
startWatchdog = nil
|
||||
endWatchdog = nil
|
||||
settleWorkItem = nil
|
||||
if let startObserver {
|
||||
NotificationCenter.default.removeObserver(startObserver)
|
||||
self.startObserver = nil
|
||||
}
|
||||
if let endObserver {
|
||||
NotificationCenter.default.removeObserver(endObserver)
|
||||
self.endObserver = nil
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,21 +776,37 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
}
|
||||
#endif
|
||||
|
||||
func dispose() {
|
||||
func dispose(preserveDisplayCriteria: Bool = false) {
|
||||
// Guard double-dispose: the plugin calls dispose() then drops the
|
||||
// strong ref, which fires deinit → dispose() again. The second call
|
||||
// would re-enter and crash on weak-ref formation during dealloc.
|
||||
guard !isDisposed else { return }
|
||||
isDisposed = true
|
||||
|
||||
#if os(tvOS)
|
||||
if preserveDisplayCriteria {
|
||||
Self.log("dispose preserving display criteria (key: \(Self.activeDisplayCriteriaKey ?? "nil"))")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Reset the HDMI mode hint synchronously while self is still alive
|
||||
// and on main. An async-to-main dispatch here would be drained after
|
||||
// dealloc (the plugin sets playerCore = nil right after this call
|
||||
// returns), leaving the link stuck at the last clip's refresh rate.
|
||||
updateDisplayCriteria(
|
||||
doviProfile: 0, doviLevel: 0, doviCompatibilityId: nil,
|
||||
fps: 0, width: 0, height: 0, sigPeak: 0,
|
||||
gamma: nil, primaries: nil, colorMatrix: nil)
|
||||
// During video-to-video replacement, keep the hint so tvOS doesn't
|
||||
// renegotiate back to default before the replacement route can set its
|
||||
// next criteria.
|
||||
if !preserveDisplayCriteria {
|
||||
updateDisplayCriteria(
|
||||
doviProfile: 0, doviLevel: 0, doviCompatibilityId: nil,
|
||||
fps: 0, width: 0, height: 0, sigPeak: 0,
|
||||
gamma: nil, primaries: nil, colorMatrix: nil)
|
||||
}
|
||||
|
||||
#if os(tvOS)
|
||||
displayModeSwitchWaiter?.cancel(complete: true)
|
||||
displayModeSwitchWaiter = nil
|
||||
#endif
|
||||
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
#if os(iOS)
|
||||
@@ -558,7 +821,8 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
mainBlankView?.removeFromSuperview()
|
||||
mainBlankView = nil
|
||||
isInitialized = false
|
||||
print("[MpvPlayerCore] Disposed")
|
||||
|
||||
Self.log("Disposed")
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user