Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
1e0988e381 | ||
|
|
8efd8f1dc8 | ||
|
|
38868e0078 | ||
|
|
273d0c7985 | ||
|
|
4728564e0c | ||
|
|
489bf914af | ||
|
|
248b5fd91a | ||
|
|
bbf7b1f9da | ||
|
|
83899a38f3 | ||
|
|
cda4c1e78a | ||
|
|
01e5814943 | ||
|
|
3cca29512d | ||
|
|
8139fc2b17 | ||
|
|
1ef4032666 | ||
|
|
4c4b18e2cd | ||
|
|
f74314bbf0 | ||
|
|
32421e4c84 | ||
|
|
d90cc61541 | ||
|
|
6b3e49d410 | ||
|
|
a9b812f66c | ||
|
|
0fd0506551 | ||
|
|
e6ca5f254d | ||
|
|
de3219abb9 | ||
|
|
8201d8dcda | ||
|
|
aed420525c | ||
|
|
75b1c86306 | ||
|
|
43012da2b8 | ||
|
|
145881318e | ||
|
|
79c06b82d3 | ||
|
|
e5bbdc06f9 | ||
|
|
0e7ff609b6 | ||
|
|
f3e108e867 | ||
|
|
92bfae322e | ||
|
|
08491511e9 | ||
|
|
24b5080c38 | ||
|
|
985c279b1f | ||
|
|
cb2e56442d | ||
|
|
a425798bae | ||
|
|
1020188883 | ||
|
|
caf192fd78 | ||
|
|
74b8dc4561 | ||
|
|
7b59dac26b | ||
|
|
09f5121732 | ||
|
|
8f9d20a2e4 | ||
|
|
273f129b68 | ||
|
|
483c0b504e | ||
|
|
7c38668a51 | ||
|
|
eba553413c | ||
|
|
f8658027b8 | ||
|
|
58bceb29cb | ||
|
|
c5d8f9c62b | ||
|
|
4ffa3d30f6 | ||
|
|
d5c8778074 | ||
|
|
c6c76d6828 | ||
|
|
9cfc6c0f4a | ||
|
|
2eae450aa0 | ||
|
|
1b5334e72f | ||
|
|
e3db54940d | ||
|
|
656d512858 | ||
|
|
d9135e0d25 | ||
|
|
4f636dfffd | ||
|
|
6438b444bf | ||
|
|
8413e1e5a7 | ||
|
|
5671f6e5d1 | ||
|
|
a4a0475fdb | ||
|
|
9a740b91c1 | ||
|
|
63ab80fa82 | ||
|
|
0bb085c70c | ||
|
|
9825ce3c7c | ||
|
|
f5012b36ea | ||
|
|
6111c381af | ||
|
|
00fce3a997 | ||
|
|
b8417f0277 | ||
|
|
4148c1c8ff | ||
|
|
9e5098f356 | ||
|
|
139eed9ca9 | ||
|
|
23efb02636 | ||
|
|
294996eac1 | ||
|
|
a4f0b92b4e | ||
|
|
7cac050500 | ||
|
|
1685ecc991 | ||
|
|
a71711de5f | ||
|
|
7534a6c60a | ||
|
|
dba01f14bb | ||
|
|
d93ea9813f | ||
|
|
7501f461b9 | ||
|
|
5e5702c961 | ||
|
|
4b477a4fe3 | ||
|
|
50ff514be8 | ||
|
|
1c7a083d6c | ||
|
|
097e48d705 | ||
|
|
a931d5910b | ||
|
|
1cd585eecb | ||
|
|
9981b277c6 | ||
|
|
2b7ea5fe02 | ||
|
|
47276e1bac | ||
|
|
c8670a8d6a | ||
|
|
9cc32e125b | ||
|
|
4217da1a8f | ||
|
|
704c37f97f | ||
|
|
0c8e0fc2ec | ||
|
|
d6315a0f75 | ||
|
|
92cdbdd723 | ||
|
|
3939ba809f | ||
|
|
6642348a96 | ||
|
|
0b29673a5e | ||
|
|
3747a74cb3 | ||
|
|
bcb7f1d3c1 | ||
|
|
7b56b90f24 | ||
|
|
ba62129414 | ||
|
|
e559a6125d | ||
|
|
869b4fe230 | ||
|
|
3b4110d7e5 | ||
|
|
7b4e399013 | ||
|
|
5788d93e89 | ||
|
|
08a806e457 | ||
|
|
e45bfadc14 | ||
|
|
56cfb95af5 | ||
|
|
8e8942fb36 | ||
|
|
02f2657d18 | ||
|
|
39709e5c42 | ||
|
|
a101ee76d6 | ||
|
|
4eadec5b17 | ||
|
|
be86a33057 | ||
|
|
ce19b9dfa7 | ||
|
|
15cc85147a | ||
|
|
3fc3baef83 | ||
|
|
91b926acac | ||
|
|
8b2ff18842 | ||
|
|
1958f8ca7e | ||
|
|
8e53232961 | ||
|
|
cec8993b80 | ||
|
|
366ae67341 | ||
|
|
50be8565d9 | ||
|
|
9365fcf246 | ||
|
|
8d4ef2757a | ||
|
|
6b147e2053 | ||
|
|
5fa8326341 | ||
|
|
c8cded70ef | ||
|
|
8fe51075be | ||
|
|
d24c95f1e1 | ||
|
|
1c8be031ae | ||
|
|
83c47b529c | ||
|
|
9dce396fb4 | ||
|
|
eeaa831cc2 | ||
|
|
f1a02ade17 | ||
|
|
dcd0b03096 | ||
|
|
a189ee5774 | ||
|
|
e74df0d245 | ||
|
|
d980540c09 | ||
|
|
a51215952f | ||
|
|
993a0e4666 | ||
|
|
4c43d6fdec | ||
|
|
1c58a12c90 | ||
|
|
b6d23ed089 | ||
|
|
3a042d79f6 | ||
|
|
1a73fc585b | ||
|
|
8ec2795da1 | ||
|
|
cbea1c8d8f | ||
|
|
048d22cb99 | ||
|
|
31c01ab3e0 | ||
|
|
16e31303ae | ||
|
|
e301fec38c | ||
|
|
e1e9adbb01 | ||
|
|
636ecc9d3a | ||
|
|
fc231a9e72 | ||
|
|
c354193187 | ||
|
|
bb7ed72073 | ||
|
|
fea973a72a | ||
|
|
487c7b87f6 | ||
|
|
afc94a50fc | ||
|
|
2ebd730201 | ||
|
|
0dd7d7c522 | ||
|
|
eaf0f4fa1a | ||
|
|
743a8668ec | ||
|
|
6a74ff083f | ||
|
|
9dc3a1a1b1 | ||
|
|
2b45557743 | ||
|
|
11b97e626e | ||
|
|
d8f69f7acd | ||
|
|
b547f8a47f | ||
|
|
f4c83bedc0 | ||
|
|
0582ab2947 | ||
|
|
209101796b | ||
|
|
448a5d084c | ||
|
|
1ebfee9354 | ||
|
|
29e0654d47 | ||
|
|
f565684842 | ||
|
|
5d6f34f756 | ||
|
|
73735c5a00 | ||
|
|
c93a266722 | ||
|
|
2b167a60f5 | ||
|
|
63e807dd58 | ||
|
|
16e3500c49 | ||
|
|
6e47a5fbcf | ||
|
|
b18774d60b | ||
|
|
0383a77b56 | ||
|
|
d58007a9e2 | ||
|
|
7d60875e19 | ||
|
|
6be1b7c486 | ||
|
|
88c65e1857 | ||
|
|
95ff95d397 | ||
|
|
1978d710da | ||
|
|
423be62218 | ||
|
|
d2650667b8 | ||
|
|
48cf8accfa | ||
|
|
565885cc1e | ||
|
|
d0e74151b8 | ||
|
|
89c9c6c49b | ||
|
|
e98d7febdd | ||
|
|
55ee2c270d | ||
|
|
81b05f00df | ||
|
|
f4f2571168 | ||
|
|
d85a622fbe | ||
|
|
d3e8dcef86 | ||
|
|
e9c93415a8 | ||
|
|
68e27fdbb3 | ||
|
|
a679bae354 | ||
|
|
5a68711f7b | ||
|
|
324d145292 | ||
|
|
d004342c98 | ||
|
|
d3d7957b62 | ||
|
|
0e94558548 | ||
|
|
8d14a14781 | ||
|
|
20f704a56d | ||
|
|
93f0da7a27 | ||
|
|
8b3f8856f7 | ||
|
|
39fb828580 | ||
|
|
3e0f7b4f86 | ||
|
|
7e9f62dc7f | ||
|
|
c855dba3be | ||
|
|
e726f9f528 | ||
|
|
2c54baca34 | ||
|
|
232d98c4ce | ||
|
|
d93c81a7cb | ||
|
|
326d53415b | ||
|
|
87db591792 | ||
|
|
6bad454830 | ||
|
|
cfd4aa307d | ||
|
|
3798a0c332 | ||
|
|
be0e9686b5 | ||
|
|
7ec45274bd | ||
|
|
3e74937386 | ||
|
|
310c4280fc | ||
|
|
ee6e327b12 | ||
|
|
e71dcdaa6c | ||
|
|
1b969953b5 | ||
|
|
7690a16efe | ||
|
|
91298294b0 | ||
|
|
5df3ec0c12 | ||
|
|
ef4980db09 | ||
|
|
e37602421b | ||
|
|
562d19c207 | ||
|
|
e54bbb2214 | ||
|
|
db2a2c34d2 | ||
|
|
12b006ee0c | ||
|
|
be3efa8335 | ||
|
|
d1d549d602 | ||
|
|
7de2a62c55 | ||
|
|
7b4a37e576 | ||
|
|
5a46857035 | ||
|
|
7ffb20b501 | ||
|
|
856ac83e6a | ||
|
|
fb8fc1db1c | ||
|
|
76e8ea6901 | ||
|
|
e8c27f00a7 | ||
|
|
9f19f550c3 | ||
|
|
fce794cd6c | ||
|
|
8f9947a874 | ||
|
|
126e6b9349 | ||
|
|
fcbe459177 | ||
|
|
0e296f8659 | ||
|
|
12073ea134 | ||
|
|
8aea796dbd | ||
|
|
9af6f32157 | ||
|
|
b0f1a5d4f1 | ||
|
|
de62c8530f | ||
|
|
0f4629f52b | ||
|
|
de129fbb0a | ||
|
|
3a01fa25a7 | ||
|
|
86c19fc1fc | ||
|
|
ae1f6d7822 | ||
|
|
4577f26aa8 | ||
|
|
fd26f470a5 | ||
|
|
bae127e459 | ||
|
|
606627cd0c | ||
|
|
3ddd89113c | ||
|
|
5139e39ed4 | ||
|
|
3a6012cc21 | ||
|
|
37b1a26cde | ||
|
|
e5922f4870 | ||
|
|
ae7f4a7871 | ||
|
|
9e85aa7be6 | ||
|
|
fd69fe668a | ||
|
|
9085d4d94b | ||
|
|
0775ea0d26 | ||
|
|
d901f5efc2 | ||
|
|
fcd8198fcb | ||
|
|
fd1eaf9d96 | ||
|
|
d0bd919ff4 | ||
|
|
2bbd31d927 | ||
|
|
617f200cb5 | ||
|
|
b96d734e8c | ||
|
|
89f256138d | ||
|
|
9b248a7a5b | ||
|
|
8d76dff353 |
@@ -82,6 +82,8 @@ body:
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: device
|
||||
@@ -89,6 +91,8 @@ body:
|
||||
label: Device Information
|
||||
description: What device are you using?
|
||||
placeholder: e.g., iPhone 14 Pro, Pixel 7, Chrome on macOS
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
|
||||
@@ -41,6 +41,8 @@ body:
|
||||
1. As a user, I would...
|
||||
2. This would help me...
|
||||
3. The benefit would be...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: platform
|
||||
@@ -57,17 +59,20 @@ body:
|
||||
- tvOS
|
||||
- Linux
|
||||
- All platforms
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: media-server
|
||||
attributes:
|
||||
label: Media Server
|
||||
description: Is this for Jellyfin, Plex, or both?
|
||||
description: Which media server(s) is this for?
|
||||
multiple: true
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
- Both
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
|
||||
@@ -2,15 +2,45 @@ name: Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_android:
|
||||
description: Build Android
|
||||
default: true
|
||||
type: boolean
|
||||
build_ios:
|
||||
description: Build iOS
|
||||
default: true
|
||||
type: boolean
|
||||
build_macos:
|
||||
description: Build macOS
|
||||
default: true
|
||||
type: boolean
|
||||
build_windows:
|
||||
description: Build Windows
|
||||
default: true
|
||||
type: boolean
|
||||
build_linux:
|
||||
description: Build Linux
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
env:
|
||||
SENTRY_DART_DEFINE: ${{ github.repository == 'edde746/plezy' && '--dart-define=ENABLE_SENTRY=true' || '' }}
|
||||
GIT_COMMIT_DART_DEFINE: --dart-define=GIT_COMMIT=${{ github.sha }}
|
||||
SENTRY_ENV_DART_DEFINE: --dart-define=SENTRY_ENVIRONMENT=github
|
||||
DONATIONS_DART_DEFINE: --dart-define=ENABLE_DONATIONS=true
|
||||
LINUX_APT_PACKAGES: >
|
||||
clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev
|
||||
libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev
|
||||
libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev
|
||||
libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev
|
||||
libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev
|
||||
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
|
||||
ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
if: ${{ inputs.build_android }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -29,6 +59,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -63,39 +94,14 @@ jobs:
|
||||
EOF
|
||||
|
||||
- name: Build APKs
|
||||
run: flutter build apk --release --split-per-abi --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --obfuscate --split-debug-info=debug-info/android-apk
|
||||
run: flutter build apk --release --split-per-abi --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-android-apk ${{ env.DONATIONS_DART_DEFINE }} --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/android-apk"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/android-apk" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/android-apk" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/app/intermediates/merged_native_libs" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/app/intermediates/merged_native_libs -name '*.so' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-android-apk
|
||||
path: symbol-inputs/android-apk
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-android-apk
|
||||
run: ./scripts/upload-symbols.sh android-apk
|
||||
|
||||
- name: Clean up keystore
|
||||
if: always()
|
||||
@@ -125,6 +131,7 @@ jobs:
|
||||
plezy-android-x86_64.tar.gz
|
||||
|
||||
build-ios:
|
||||
if: ${{ inputs.build_ios }}
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -137,6 +144,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -162,39 +170,14 @@ jobs:
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build iOS (no codesign)
|
||||
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/ios
|
||||
run: flutter build ios --release --no-codesign --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-ios ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/ios
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/ios"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/ios" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/ios" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/ios" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/ios -path '*.dSYM/Contents/Resources/DWARF/*' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-ios
|
||||
path: symbol-inputs/ios
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-ios
|
||||
run: ./scripts/upload-symbols.sh ios
|
||||
|
||||
- name: Create IPA
|
||||
run: |
|
||||
@@ -214,6 +197,7 @@ jobs:
|
||||
path: plezy-ios.ipa
|
||||
|
||||
build-macos:
|
||||
if: ${{ inputs.build_macos }}
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -226,6 +210,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -251,39 +236,14 @@ jobs:
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build macOS
|
||||
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/macos
|
||||
run: flutter build macos --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-macos ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/macos
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/macos"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/macos" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/macos" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/macos/Build/Products/Release" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/macos/Build/Products/Release -path '*.dSYM/Contents/Resources/DWARF/*' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-macos
|
||||
path: symbol-inputs/macos
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-macos
|
||||
run: ./scripts/upload-symbols.sh macos
|
||||
|
||||
- name: Import Code Signing Certificate
|
||||
env:
|
||||
@@ -339,6 +299,11 @@ jobs:
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
echo "Verifying signature..."
|
||||
codesign -dvvv "$APP_PATH"
|
||||
echo "Verifying signed entitlements..."
|
||||
codesign -d --entitlements :- "$APP_PATH" > "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-jit" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-unsigned-executable-memory" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
|
||||
- name: Notarize Application
|
||||
@@ -409,6 +374,7 @@ jobs:
|
||||
macos-dmg-size.txt
|
||||
|
||||
build-windows-x64:
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -419,6 +385,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -439,47 +406,15 @@ jobs:
|
||||
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 }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/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: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
continue-on-error: true
|
||||
run: |
|
||||
$symbolRoot = 'symbol-inputs/windows-x64'
|
||||
Remove-Item -Path $symbolRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Path $symbolRoot -Force | Out-Null
|
||||
|
||||
$debugInfo = 'debug-info/windows-x64'
|
||||
if (Test-Path $debugInfo) {
|
||||
$debugInfoRoot = Join-Path $symbolRoot 'debug-info'
|
||||
New-Item -ItemType Directory -Path $debugInfoRoot -Force | Out-Null
|
||||
Copy-Item -Path $debugInfo -Destination $debugInfoRoot -Recurse -Force
|
||||
}
|
||||
|
||||
$pdbRoot = 'build/windows/x64/runner/Release'
|
||||
if (Test-Path $pdbRoot) {
|
||||
Get-ChildItem -Path $pdbRoot -Filter '*.pdb' -Recurse | ForEach-Object {
|
||||
$relative = [System.IO.Path]::GetRelativePath((Get-Location).Path, $_.FullName)
|
||||
$destination = Join-Path $symbolRoot $relative
|
||||
New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force | Out-Null
|
||||
Copy-Item -Path $_.FullName -Destination $destination -Force
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Get-ChildItem -Path $symbolRoot -File -Recurse)) {
|
||||
throw 'No symbol files staged'
|
||||
}
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-windows-x64
|
||||
path: symbol-inputs/windows-x64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
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
|
||||
@@ -488,6 +423,7 @@ jobs:
|
||||
path: build/windows/x64/runner/Release/
|
||||
|
||||
build-windows-arm64:
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-11-arm
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -511,6 +447,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "master"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -525,47 +462,15 @@ jobs:
|
||||
run: flutter pub get --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 }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/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: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
continue-on-error: true
|
||||
run: |
|
||||
$symbolRoot = 'symbol-inputs/windows-arm64'
|
||||
Remove-Item -Path $symbolRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Path $symbolRoot -Force | Out-Null
|
||||
|
||||
$debugInfo = 'debug-info/windows-arm64'
|
||||
if (Test-Path $debugInfo) {
|
||||
$debugInfoRoot = Join-Path $symbolRoot 'debug-info'
|
||||
New-Item -ItemType Directory -Path $debugInfoRoot -Force | Out-Null
|
||||
Copy-Item -Path $debugInfo -Destination $debugInfoRoot -Recurse -Force
|
||||
}
|
||||
|
||||
$pdbRoot = 'build/windows/arm64/runner/Release'
|
||||
if (Test-Path $pdbRoot) {
|
||||
Get-ChildItem -Path $pdbRoot -Filter '*.pdb' -Recurse | ForEach-Object {
|
||||
$relative = [System.IO.Path]::GetRelativePath((Get-Location).Path, $_.FullName)
|
||||
$destination = Join-Path $symbolRoot $relative
|
||||
New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force | Out-Null
|
||||
Copy-Item -Path $_.FullName -Destination $destination -Force
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Get-ChildItem -Path $symbolRoot -File -Recurse)) {
|
||||
throw 'No symbol files staged'
|
||||
}
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-windows-arm64
|
||||
path: symbol-inputs/windows-arm64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-windows-arm64
|
||||
run: .\scripts\upload-symbols.ps1 windows-arm64
|
||||
|
||||
- name: Upload arm64 build
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -575,6 +480,7 @@ jobs:
|
||||
|
||||
package-windows:
|
||||
needs: [build-windows-x64, build-windows-arm64]
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -657,6 +563,7 @@ jobs:
|
||||
win-installer-size.txt
|
||||
|
||||
build-linux-x64:
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -669,6 +576,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -682,13 +590,24 @@ jobs:
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
packages: ${{ env.LINUX_APT_PACKAGES }}
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
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
|
||||
@@ -708,41 +627,16 @@ jobs:
|
||||
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 }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/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
|
||||
env:
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/x86_64-linux-gnu/pkgconfig
|
||||
|
||||
- name: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/linux-x64"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/linux-x64" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/linux-x64" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/linux" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/linux -path '*/release/bundle/plezy' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-linux-x64
|
||||
path: symbol-inputs/linux-x64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-linux-x64
|
||||
run: ./scripts/upload-symbols.sh linux-x64
|
||||
|
||||
- name: Build Linux Packages
|
||||
run: ARCH_SUFFIX=x64 OUTPUT_DIR=$GITHUB_WORKSPACE python3 linux/packaging/build-packages.py
|
||||
@@ -796,6 +690,7 @@ jobs:
|
||||
plezy-linux-x64.pkg.tar.zst
|
||||
|
||||
build-linux-arm64:
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
id-token: write
|
||||
@@ -808,6 +703,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "master"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -821,13 +717,24 @@ jobs:
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
packages: ${{ env.LINUX_APT_PACKAGES }}
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
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
|
||||
@@ -847,41 +754,16 @@ jobs:
|
||||
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 }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/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: Stage symbols for upload
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
SYMBOL_ROOT="symbol-inputs/linux-arm64"
|
||||
rm -rf "$SYMBOL_ROOT"
|
||||
mkdir -p "$SYMBOL_ROOT"
|
||||
|
||||
if [ -d "debug-info/linux-arm64" ]; then
|
||||
mkdir -p "$SYMBOL_ROOT/debug-info"
|
||||
cp -R "debug-info/linux-arm64" "$SYMBOL_ROOT/debug-info/"
|
||||
fi
|
||||
|
||||
if [ -d "build/linux" ]; then
|
||||
while IFS= read -r -d '' file; do
|
||||
mkdir -p "$SYMBOL_ROOT/$(dirname "$file")"
|
||||
cp "$file" "$SYMBOL_ROOT/$file"
|
||||
done < <(find build/linux -path '*/release/bundle/plezy' -type f -print0)
|
||||
fi
|
||||
|
||||
find "$SYMBOL_ROOT" -type f -print -quit | grep -q .
|
||||
|
||||
- name: Upload symbols artifact
|
||||
if: github.repository == 'edde746/plezy'
|
||||
continue-on-error: true
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: symbols-linux-arm64
|
||||
path: symbol-inputs/linux-arm64
|
||||
retention-days: 3
|
||||
if-no-files-found: error
|
||||
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
|
||||
@@ -944,53 +826,9 @@ jobs:
|
||||
plezy-linux-arm64.rpm
|
||||
plezy-linux-arm64.pkg.tar.zst
|
||||
|
||||
upload-symbols:
|
||||
if: github.repository == 'edde746/plezy'
|
||||
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, build-linux-x64, build-linux-arm64]
|
||||
runs-on: ${{ matrix.os }}
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: android-apk
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh android-apk symbol-inputs/android-apk
|
||||
- platform: ios
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh ios symbol-inputs/ios
|
||||
- platform: macos
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh macos symbol-inputs/macos
|
||||
- platform: windows-x64
|
||||
os: windows-latest
|
||||
command: ./scripts/upload-symbols.ps1 windows-x64 symbol-inputs/windows-x64
|
||||
- platform: windows-arm64
|
||||
os: windows-latest
|
||||
command: ./scripts/upload-symbols.ps1 windows-arm64 symbol-inputs/windows-arm64
|
||||
- platform: linux-x64
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh linux-x64 symbol-inputs/linux-x64
|
||||
- platform: linux-arm64
|
||||
os: ubuntu-latest
|
||||
command: ./scripts/upload-symbols.sh linux-arm64 symbol-inputs/linux-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Download symbols artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: symbols-${{ matrix.platform }}
|
||||
path: symbol-inputs/${{ matrix.platform }}
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
run: ${{ matrix.command }}
|
||||
|
||||
create-release:
|
||||
needs: [build-android, build-ios, build-macos, package-windows, build-linux-x64, build-linux-arm64]
|
||||
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, package-windows, build-linux-x64, build-linux-arm64]
|
||||
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:
|
||||
contents: write
|
||||
@@ -1001,48 +839,56 @@ jobs:
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Download Android artifacts
|
||||
if: ${{ inputs.build_android }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: android-apk
|
||||
path: artifacts/android-apk
|
||||
|
||||
- name: Download iOS artifact
|
||||
if: ${{ inputs.build_ios }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ios-ipa
|
||||
path: artifacts/ios-ipa
|
||||
|
||||
- name: Download macOS artifact
|
||||
if: ${{ inputs.build_macos }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: macos-dmg
|
||||
path: artifacts/macos-dmg
|
||||
|
||||
- name: Download Windows x64 artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-x64-portable
|
||||
path: artifacts/windows-x64-portable
|
||||
|
||||
- name: Download Windows arm64 artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-arm64-portable
|
||||
path: artifacts/windows-arm64-portable
|
||||
|
||||
- name: Download Windows installer artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-installer
|
||||
path: artifacts/windows-installer
|
||||
|
||||
- name: Download Linux x64 artifacts
|
||||
if: ${{ inputs.build_linux }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: linux-x64
|
||||
path: artifacts/linux-x64
|
||||
|
||||
- name: Download Linux arm64 artifacts
|
||||
if: ${{ inputs.build_linux }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: linux-arm64
|
||||
@@ -1129,21 +975,39 @@ jobs:
|
||||
echo "Generated appcast.xml:"
|
||||
cat appcast.xml
|
||||
|
||||
- name: Collect release files
|
||||
id: release-files
|
||||
run: |
|
||||
{
|
||||
echo 'files<<EOF'
|
||||
if [ "${{ inputs.build_android }}" = "true" ]; then
|
||||
echo artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
|
||||
echo artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
|
||||
echo artifacts/android-apk/plezy-android-x86_64.tar.gz
|
||||
fi
|
||||
if [ "${{ inputs.build_ios }}" = "true" ]; then
|
||||
echo artifacts/ios-ipa/plezy-ios.ipa
|
||||
fi
|
||||
if [ "${{ inputs.build_macos }}" = "true" ]; then
|
||||
echo artifacts/macos-dmg/plezy-macos.dmg
|
||||
fi
|
||||
if [ "${{ inputs.build_windows }}" = "true" ]; then
|
||||
echo artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
|
||||
echo artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
|
||||
echo artifacts/windows-installer/plezy-windows-installer.exe
|
||||
fi
|
||||
if [ "${{ inputs.build_linux }}" = "true" ]; then
|
||||
echo 'artifacts/linux-x64/*'
|
||||
echo 'artifacts/linux-arm64/*'
|
||||
fi
|
||||
echo appcast.xml
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: |
|
||||
artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
|
||||
artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
|
||||
artifacts/android-apk/plezy-android-x86_64.tar.gz
|
||||
artifacts/ios-ipa/plezy-ios.ipa
|
||||
artifacts/macos-dmg/plezy-macos.dmg
|
||||
artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
|
||||
artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
|
||||
artifacts/windows-installer/plezy-windows-installer.exe
|
||||
artifacts/linux-x64/*
|
||||
artifacts/linux-arm64/*
|
||||
appcast.xml
|
||||
files: ${{ steps.release-files.outputs.files }}
|
||||
draft: true
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -23,6 +23,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -38,6 +39,15 @@ jobs:
|
||||
|
||||
flutter pub get
|
||||
|
||||
- name: Verify generated files committed
|
||||
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
|
||||
|
||||
- name: Verify formatting
|
||||
run: |
|
||||
# Find all Dart files excluding generated files
|
||||
@@ -105,6 +115,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
@@ -159,6 +170,7 @@ jobs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
cask "plezy" do
|
||||
version "1.35.2"
|
||||
sha256 "e3a65f5688bd8ac010b0dad2238a24f6f3b4b5a6f5ca2b5127a9e1a817dd73d9"
|
||||
version "2.6.0"
|
||||
sha256 "e408fe84c07e0ff4a2f1a78e8dcfc418233c66ca98c79028a7b099499307a59e"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
|
||||
@@ -3,13 +3,19 @@
|
||||
Plezy
|
||||
</h1>
|
||||
|
||||
A modern client for Plex and Jellyfin on desktop and mobile. Built with Flutter for native performance and a clean interface.
|
||||
A modern client for Plex and Jellyfin on desktop, mobile, and TV. Built with Flutter for native performance and a clean interface.
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
|
||||
<p>
|
||||
<a href="https://plezy.app">Website</a> ·
|
||||
<a href="https://plezy.app/#screenshots">Screenshots</a> ·
|
||||
<a href="#download">Download</a> ·
|
||||
<a href="CONTRIBUTING.md">Contributing</a> ·
|
||||
<a href="LICENSE">License</a>
|
||||
</p>
|
||||
|
||||
*More screenshots in the [screenshots folder](assets/screenshots/#readme)*
|
||||
<p align="center">
|
||||
<img src="assets/readme-showcase.webp" alt="Plezy mobile screenshots" width="900" />
|
||||
</p>
|
||||
|
||||
## Download
|
||||
|
||||
@@ -17,9 +23,15 @@ A modern client for Plex and Jellyfin on desktop and mobile. Built with Flutter
|
||||
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
|
||||
<a href='https://www.amazon.com/gp/product/B0GK65CVS1'><img height='60' alt='Available at the Amazon App Store' src='./assets/amazon-badge.png'/></a>
|
||||
|
||||
- [Windows (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
|
||||
- [macOS (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
|
||||
- [Linux (x64, arm64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
|
||||
| Platform | Download |
|
||||
| --- | --- |
|
||||
| Windows | [Installer (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe) · [Portable x64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-x64-portable.7z) · [Portable arm64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-arm64-portable.7z) |
|
||||
| macOS | [DMG (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg) |
|
||||
| Linux x64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz) |
|
||||
| Linux arm64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.tar.gz) |
|
||||
|
||||
Package managers:
|
||||
|
||||
- [Nix](https://search.nixos.org/packages?channel=unstable&query=plezy) - Community package by [@mio-19](https://github.com/mio-19) and [@MiniHarinn](https://github.com/MiniHarinn)
|
||||
- **Homebrew** (macOS):
|
||||
```bash
|
||||
@@ -32,7 +44,7 @@ A modern client for Plex and Jellyfin on desktop and mobile. Built with Flutter
|
||||
```
|
||||
- **WinGet** (Windows):
|
||||
```bash
|
||||
winget install edde746.plezy
|
||||
winget install edde746.Plezy
|
||||
```
|
||||
|
||||
## Features
|
||||
@@ -46,22 +58,22 @@ A modern client for Plex and Jellyfin on desktop and mobile. Built with Flutter
|
||||
|
||||
### <img src="assets/readme_icons/playback.svg" height="20" alt="" align="center" /> Playback
|
||||
- Wide codec support (HEVC, AV1, VP9, and more)
|
||||
- HDR and Dolby Vision (not Linux)
|
||||
- HDR and Dolby Vision[^1]
|
||||
- Full ASS/SSA subtitles with customizable styling
|
||||
- Online subtitle search & download
|
||||
- Audio & subtitle preferences synced with your server profile
|
||||
- Online subtitle search & download[^2]
|
||||
- Audio & subtitle choices remembered per title
|
||||
- Progress sync and resume
|
||||
- Auto-play next episode with skip intro / skip credits
|
||||
- Chapter navigation with thumbnail scrub previews
|
||||
- Playback speed, audio sync offset, sleep timer
|
||||
- Ambient lighting and GLSL shader presets
|
||||
- Picture-in-Picture on Android, iOS, and macOS
|
||||
- Refresh-rate matching on Windows and Android
|
||||
- Ambient lighting and GLSL shader presets[^3]
|
||||
- Picture-in-Picture[^4]
|
||||
- Refresh-rate matching[^5]
|
||||
- External player launch (VLC, MX Player, etc.)
|
||||
|
||||
### <img src="assets/readme_icons/live-tv.svg" height="20" alt="" align="center" /> Live TV & DVR
|
||||
- Live TV channel browsing with favorites
|
||||
- Plex DVR support with EPG guide, recording rules, and scheduled recordings
|
||||
- DVR support with EPG guide, recording rules, and scheduled recordings[^2]
|
||||
- Multi-server Live TV support where available
|
||||
|
||||
### <img src="assets/readme_icons/downloads.svg" height="20" alt="" align="center" /> Downloads & Offline
|
||||
@@ -75,21 +87,30 @@ A modern client for Plex and Jellyfin on desktop and mobile. Built with Flutter
|
||||
- Real-time play / pause / seek sync
|
||||
|
||||
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
|
||||
- Discord Rich Presence for Plex
|
||||
- Trakt scrobbling
|
||||
- Discord Rich Presence[^7]
|
||||
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
|
||||
- Plezy Remote — control desktop and TV from mobile
|
||||
- Android TV Watch Next row
|
||||
- Watch Next row[^6]
|
||||
|
||||
### <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 on desktop
|
||||
- Plex metadata and artwork editing
|
||||
- Localized in 14 languages
|
||||
- Customizable keyboard shortcuts[^7]
|
||||
- Metadata and artwork editing[^2]
|
||||
- Settings import/export
|
||||
- Localized in English plus 14 translations
|
||||
|
||||
[^1]: Not available on Linux.
|
||||
[^2]: Plex only.
|
||||
[^3]: Not available on iOS or tvOS.
|
||||
[^4]: Android, iOS, and macOS.
|
||||
[^5]: Windows, Android, and tvOS.
|
||||
[^6]: Android TV only.
|
||||
[^7]: Desktop only.
|
||||
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites
|
||||
- Flutter SDK 3.8.1+
|
||||
- Flutter SDK 3.38.4+
|
||||
- A Plex account or Jellyfin server with user credentials
|
||||
|
||||
### Setup
|
||||
@@ -98,20 +119,46 @@ A modern client for Plex and Jellyfin on desktop and mobile. Built with Flutter
|
||||
git clone https://github.com/edde746/plezy.git
|
||||
cd plezy
|
||||
flutter pub get
|
||||
dart run build_runner build
|
||||
scripts/codegen.sh
|
||||
flutter run
|
||||
```
|
||||
|
||||
### Code Generation
|
||||
|
||||
After modifying model classes:
|
||||
After modifying model classes or other generated sources:
|
||||
|
||||
```bash
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
scripts/codegen.sh
|
||||
```
|
||||
|
||||
After modifying translations:
|
||||
|
||||
```bash
|
||||
dart run slang
|
||||
```
|
||||
|
||||
### Local Checks
|
||||
|
||||
```bash
|
||||
scripts/ci_checks.sh
|
||||
```
|
||||
|
||||
To install the same pre-commit checks locally:
|
||||
|
||||
```bash
|
||||
scripts/setup_hooks.sh
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for development workflow, formatting, tests, and translation guidelines.
|
||||
|
||||
## License
|
||||
|
||||
Plezy is licensed under [GPL-3.0](LICENSE).
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
- Built with [Flutter](https://flutter.dev)
|
||||
- Supports [Plex Media Server](https://www.plex.tv) and [Jellyfin](https://jellyfin.org)
|
||||
- Playback powered by [mpv](https://mpv.io) via [MPVKit](https://github.com/mpvkit/MPVKit) and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
|
||||
- Playback powered by [mpv](https://mpv.io), [MPVKit](https://github.com/mpvkit/MPVKit), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), [libass-android](https://github.com/peerless2012/libass-android), and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
|
||||
|
||||
@@ -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,10 +152,29 @@ android {
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// Resolve conflict between libass-android and libmpv native libraries
|
||||
// Three copies of libc++_shared.so reach the merge: the libmpv AAR's
|
||||
// (NDK r29 — exports std::from_chars<float> that libmpv.so needs), the
|
||||
// :libass module's CMake-contributed copy (NDK 28.2 — lacks it), and
|
||||
// peerless2012:ass's bundled copy (also old). pickFirst keeps the merge
|
||||
// from erroring on the duplicates; WHICH copy wins is pinned by the
|
||||
// sourceSets block below: extractMpvLibcxx unpacks the libmpv AAR's copy
|
||||
// into an app jniLibs dir, and PROJECT-scope sources beat sub-projects
|
||||
// and external AARs. libc++ is backward ABI-compatible, so the older-NDK
|
||||
// consumers (libass.so, libasskt.so, ffmpeg decoder, cronet) run fine
|
||||
// against the newer copy.
|
||||
pickFirsts.add("lib/*/libc++_shared.so")
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
// libc++_shared.so extracted from the libmpv AAR by extractMpvLibcxx.
|
||||
// App source-set jniLibs sit in the PROJECT scope, merged ahead of
|
||||
// subprojects (:libass) and external AARs, so with the pickFirst rule
|
||||
// above this copy deterministically wins regardless of dependency order.
|
||||
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
@@ -160,10 +186,14 @@ tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative")
|
||||
dependsOn(downloadLibdovi)
|
||||
}
|
||||
|
||||
// Download libmpv and libass AARs before compilation
|
||||
// Download the libmpv AAR before compilation
|
||||
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
|
||||
dependsOn(downloadLibmpv)
|
||||
dependsOn(downloadLibass)
|
||||
dependsOn(downloadLibmpv, extractMpvLibcxx)
|
||||
}
|
||||
// merge{Debug,Profile,Release}JniLibFolders snapshot jniLibs source dirs as inputs;
|
||||
// Gradle 8 requires an explicit dependency on the producing task.
|
||||
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
|
||||
dependsOn(extractMpvLibcxx)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -186,6 +216,13 @@ 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))) }
|
||||
// libass ASS/SSA subtitle rendering: optimized native core (libass.so +
|
||||
// prefab headers) from the edde746/libass-android fork's releases; Kotlin/JNI
|
||||
// bindings + Media3 glue live in the android/libass module. -PlocalAssCore
|
||||
// swaps in a mavenLocal()-published core (0.4.0-local) for native A/B tests.
|
||||
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
|
||||
implementation("io.github.peerless2012:ass:$assCoreVersion@aar")
|
||||
implementation(project(":libass"))
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
|
||||
@@ -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 -->
|
||||
@@ -59,6 +60,9 @@
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"
|
||||
/>
|
||||
<meta-data
|
||||
android:name="flutter_deeplinking_enabled"
|
||||
android:value="false" />
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
|
||||
@@ -86,7 +86,7 @@ extern "C" JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_DoviBridge_na
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to target profile (mode 2 = P8.1 with no-op curves)
|
||||
// Mode 2 matches Kodi's P8.1 compatibility path and sets luma/chroma curves to no-op.
|
||||
int32_t ret = dovi_convert_rpu_with_mode(rpu, static_cast<uint8_t>(mode));
|
||||
if (ret != 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
|
||||
@@ -1,38 +1,79 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.ActivityManager
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import android.util.Rational
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.TextureView
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowManager
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.content.FileProvider
|
||||
import com.edde746.plezy.exoplayer.ExoPlayerPlugin
|
||||
import com.edde746.plezy.mpv.MpvPlayerPlugin
|
||||
import com.edde746.plezy.shared.DeviceQuirks
|
||||
import com.edde746.plezy.shared.ThemeHelper
|
||||
import com.edde746.plezy.watchnext.WatchNextPlugin
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.android.FlutterTextureView
|
||||
import io.flutter.embedding.android.RenderMode
|
||||
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)
|
||||
|
||||
var usingSkia = false
|
||||
}
|
||||
|
||||
@@ -40,9 +81,20 @@ class MainActivity : FlutterActivity() {
|
||||
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 inline fun logTextInputDiag(message: () -> String) {
|
||||
if (TEXT_INPUT_DIAGNOSTICS_ENABLED) {
|
||||
Log.i(TAG, "TextInputDiag ${message()}")
|
||||
}
|
||||
}
|
||||
|
||||
// Auto PiP state
|
||||
private var autoPipReady = false
|
||||
@@ -51,6 +103,67 @@ class MainActivity : FlutterActivity() {
|
||||
|
||||
private fun isAndroidTvDevice(): Boolean = getAndroidTvDetection()["isTv"] as Boolean
|
||||
|
||||
private fun isImeVisible(): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return false
|
||||
return window.decorView.rootWindowInsets?.isVisible(WindowInsets.Type.ime()) == true
|
||||
}
|
||||
|
||||
private fun keyActionName(action: Int): String = when (action) {
|
||||
KeyEvent.ACTION_DOWN -> "down"
|
||||
KeyEvent.ACTION_UP -> "up"
|
||||
KeyEvent.ACTION_MULTIPLE -> "multiple"
|
||||
else -> "unknown($action)"
|
||||
}
|
||||
|
||||
private fun sourceNames(source: Int): String {
|
||||
val names = mutableListOf<String>()
|
||||
if ((source and InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD) names.add("keyboard")
|
||||
if ((source and InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) names.add("dpad")
|
||||
if ((source and InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) names.add("gamepad")
|
||||
if ((source and InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) names.add("joystick")
|
||||
if ((source and InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN) names.add("touchscreen")
|
||||
if ((source and InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) names.add("mouse")
|
||||
return names.ifEmpty { listOf("unknown") }.joinToString("+")
|
||||
}
|
||||
|
||||
private fun isDpadKeyCode(keyCode: Int): Boolean = when (keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent.KEYCODE_DPAD_CENTER,
|
||||
KeyEvent.KEYCODE_BACK,
|
||||
KeyEvent.KEYCODE_ENTER,
|
||||
KeyEvent.KEYCODE_NUMPAD_ENTER -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun describeDevice(event: KeyEvent): String {
|
||||
val device = event.device ?: return "device=null deviceId=${event.deviceId}"
|
||||
return "deviceId=${event.deviceId} name=${device.name} vendor=${device.vendorId} product=${device.productId} " +
|
||||
"keyboardType=${device.keyboardType} sources=0x${Integer.toHexString(device.sources)}[${sourceNames(device.sources)}]"
|
||||
}
|
||||
|
||||
private fun describeKeyEvent(event: KeyEvent): String = "action=${keyActionName(event.action)} key=${KeyEvent.keyCodeToString(event.keyCode)}(${event.keyCode}) " +
|
||||
"scan=${event.scanCode} repeat=${event.repeatCount} source=0x${Integer.toHexString(event.source)}[${sourceNames(event.source)}] " +
|
||||
"flags=0x${Integer.toHexString(event.flags)} meta=0x${Integer.toHexString(event.metaState)} ${describeDevice(event)}"
|
||||
|
||||
private fun describeImeState(): String {
|
||||
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
val focus = currentFocus
|
||||
return "nativeTextInputFocused=$nativeTextInputFocused imeVisible=${isImeVisible()} " +
|
||||
"acceptingText=${imm.isAcceptingText} activeDecor=${imm.isActive(window.decorView)} " +
|
||||
"decorHasFocus=${window.decorView.hasFocus()} currentFocus=${focus?.javaClass?.name} " +
|
||||
"currentFocusHasFocus=${focus?.hasFocus()} currentFocusFocused=${focus?.isFocused}"
|
||||
}
|
||||
|
||||
private fun shouldForwardDpadBeforeIme(): Boolean {
|
||||
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
val forward = !nativeTextInputFocused && !isImeVisible() && !imm.isAcceptingText
|
||||
logTextInputDiag { "shouldForwardDpadBeforeIme=$forward ${describeImeState()}" }
|
||||
return forward
|
||||
}
|
||||
|
||||
private fun getAndroidTvDetection(): Map<String, Any> {
|
||||
val pm = packageManager
|
||||
val uiModeType = resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK
|
||||
@@ -84,6 +197,30 @@ 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
|
||||
)
|
||||
}
|
||||
|
||||
/** 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.
|
||||
val name = Settings.Global.getString(contentResolver, Settings.Global.DEVICE_NAME)
|
||||
if (!name.isNullOrBlank()) return name
|
||||
// Fallback: the Bluetooth name usually mirrors the device name. Reading the
|
||||
// settings string needs no BLUETOOTH permission (unlike BluetoothAdapter).
|
||||
val bt = Settings.Secure.getString(contentResolver, "bluetooth_name")
|
||||
return if (!bt.isNullOrBlank()) bt else null
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
// Apply persisted theme color to the window background before anything
|
||||
// else renders. This prevents a white flash between the native splash
|
||||
@@ -112,20 +249,28 @@ class MainActivity : FlutterActivity() {
|
||||
val content = findViewById<ViewGroup>(android.R.id.content)
|
||||
val wrapper = object : FrameLayout(this) {
|
||||
override fun dispatchKeyEventPreIme(event: KeyEvent): Boolean {
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag { "preIme received ${describeKeyEvent(event)} ${describeImeState()}" }
|
||||
}
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent.KEYCODE_DPAD_CENTER -> {
|
||||
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
if (!imm.isAcceptingText) {
|
||||
if (shouldForwardDpadBeforeIme()) {
|
||||
logTextInputDiag { "preIme forwarding-to-Flutter-and-consuming ${describeKeyEvent(event)}" }
|
||||
super.dispatchKeyEvent(event)
|
||||
return true
|
||||
}
|
||||
logTextInputDiag { "preIme letting-IME-handle ${describeKeyEvent(event)}" }
|
||||
}
|
||||
}
|
||||
return super.dispatchKeyEventPreIme(event)
|
||||
val handled = super.dispatchKeyEventPreIme(event)
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag { "preIme superResult=$handled ${describeKeyEvent(event)} ${describeImeState()}" }
|
||||
}
|
||||
return handled
|
||||
}
|
||||
}
|
||||
while (content.childCount > 0) {
|
||||
@@ -151,6 +296,80 @@ class MainActivity : FlutterActivity() {
|
||||
handleWatchNextIntent(intent)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag { "activity.dispatchKeyEvent before ${describeKeyEvent(event)} ${describeImeState()}" }
|
||||
}
|
||||
val handled = super.dispatchKeyEvent(event)
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag {
|
||||
"activity.dispatchKeyEvent after handled=$handled ${describeKeyEvent(event)} ${describeImeState()}"
|
||||
}
|
||||
}
|
||||
return handled
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun handleWatchNextIntent(intent: Intent?) {
|
||||
val contentId = WatchNextPlugin.handleIntent(intent)
|
||||
if (contentId != null) {
|
||||
@@ -169,16 +388,7 @@ class MainActivity : FlutterActivity() {
|
||||
private fun shouldDisableImpeller(): Boolean {
|
||||
// Android TV devices — weaker GPUs, less Impeller testing
|
||||
if (isAndroidTvDevice()) return true
|
||||
// Google Tensor SoC (Mali GPU) — Pixel 6+
|
||||
// SOC_MODEL may return marketing name ("Tensor G2") or internal ID ("GS201")
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val soc = Build.SOC_MODEL
|
||||
if (soc.startsWith("Tensor", ignoreCase = true) ||
|
||||
soc.startsWith("GS", ignoreCase = true)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (DeviceQuirks.isEWaste) return true
|
||||
// NVIDIA Tegra (Shield TV)
|
||||
if (Build.MANUFACTURER.equals("NVIDIA", ignoreCase = true)) return true
|
||||
// Huawei/HONOR Kirin SoCs use Mali GPUs
|
||||
@@ -190,13 +400,57 @@ class MainActivity : FlutterActivity() {
|
||||
return false
|
||||
}
|
||||
|
||||
override fun getRenderMode(): RenderMode = RenderMode.surface
|
||||
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
|
||||
// behavior and avoids compositor regressions with Dolby Vision playback.
|
||||
return RenderMode.texture
|
||||
}
|
||||
|
||||
override fun getTransparencyMode(): TransparencyMode {
|
||||
// Keep Flutter transparent so video/subtitles are visible below.
|
||||
return TransparencyMode.transparent
|
||||
}
|
||||
|
||||
override fun onFlutterTextureViewCreated(flutterTextureView: FlutterTextureView) {
|
||||
val original = flutterTextureView.surfaceTextureListener ?: return
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
var pendingResize: Runnable? = null
|
||||
var lastWidth = 0
|
||||
var lastHeight = 0
|
||||
|
||||
flutterTextureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
|
||||
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
original.onSurfaceTextureAvailable(surface, width, height)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
flutterEngine.plugins.add(MpvPlayerPlugin())
|
||||
@@ -205,6 +459,26 @@ class MainActivity : FlutterActivity() {
|
||||
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" -> {
|
||||
val oldValue = nativeTextInputFocused
|
||||
nativeTextInputFocused = call.arguments as? Boolean ?: false
|
||||
logTextInputDiag {
|
||||
"methodChannel setNativeTextInputFocused old=$oldValue new=$nativeTextInputFocused ${describeImeState()}"
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
@@ -233,44 +507,83 @@ class MainActivity : FlutterActivity() {
|
||||
when (call.method) {
|
||||
"openVideo" -> {
|
||||
val filePath = call.argument<String>("filePath")
|
||||
val packageName = call.argument<String>("package")
|
||||
val packageNames = call.argument<List<Any?>>("packages")
|
||||
?.mapNotNull { (it as? String)?.trim()?.takeIf { value -> value.isNotEmpty() } }
|
||||
?: emptyList()
|
||||
val title = call.argument<String>("title")?.trim()?.takeIf { it.isNotEmpty() }
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
|
||||
if (filePath == null) {
|
||||
result.error("INVALID_ARGUMENT", "filePath is required", null)
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
if (pendingExternalPlayerResult != null) {
|
||||
result.error("ALREADY_ACTIVE", "An external player is already active", null)
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
try {
|
||||
val uri: Uri
|
||||
val grantRead: Boolean
|
||||
val fileName: String?
|
||||
|
||||
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
|
||||
uri = Uri.parse(filePath)
|
||||
grantRead = false
|
||||
fileName = uri.lastPathSegment
|
||||
} else if (filePath.startsWith("content://")) {
|
||||
uri = Uri.parse(filePath)
|
||||
grantRead = true
|
||||
fileName = uri.lastPathSegment
|
||||
} else {
|
||||
val path = if (filePath.startsWith("file://")) filePath.removePrefix("file://") else filePath
|
||||
fileName = File(path).name
|
||||
uri = FileProvider.getUriForFile(this, "com.edde746.plezy.fileprovider", File(path))
|
||||
grantRead = true
|
||||
}
|
||||
|
||||
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
fun buildIntent(packageName: String?): Intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, "video/*")
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (grantRead) {
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
if (packageName != null) {
|
||||
setPackage(packageName)
|
||||
packageName?.let { setPackage(it) }
|
||||
val startPosition = startPositionMs.coerceAtLeast(0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
if (startPosition > 0) {
|
||||
putExtra(API_MX_RESULT_POSITION, startPosition)
|
||||
putExtra(API_VIMU_SEEK_POSITION, startPosition)
|
||||
}
|
||||
putExtra(API_MX_RETURN_RESULT, true)
|
||||
putExtra(API_MX_SECURE_URI, true)
|
||||
putExtra(API_VIMU_RESUME, false)
|
||||
title?.let {
|
||||
putExtra(API_MX_TITLE, it)
|
||||
putExtra(API_VIMU_TITLE, it)
|
||||
}
|
||||
fileName?.let { putExtra(API_MX_FILENAME, it) }
|
||||
}
|
||||
|
||||
val targetPackages = if (packageNames.isEmpty()) listOf<String?>(null) else packageNames
|
||||
for (packageName in targetPackages) {
|
||||
try {
|
||||
pendingExternalPlayerResult = result
|
||||
startActivityForResult(buildIntent(packageName), EXTERNAL_PLAYER_REQUEST_CODE)
|
||||
return@setMethodCallHandler
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
pendingExternalPlayerResult = null
|
||||
}
|
||||
}
|
||||
startActivity(intent)
|
||||
result.success(true)
|
||||
} catch (e: android.content.ActivityNotFoundException) {
|
||||
result.error("APP_NOT_FOUND", "No app found for package: $packageName", null)
|
||||
|
||||
pendingExternalPlayerResult = null
|
||||
val message = if (packageNames.isEmpty()) {
|
||||
"No app found for video"
|
||||
} else {
|
||||
"No app found for packages: ${packageNames.joinToString(", ")}"
|
||||
}
|
||||
result.error("APP_NOT_FOUND", message, null)
|
||||
} catch (e: Exception) {
|
||||
pendingExternalPlayerResult = null
|
||||
result.error("LAUNCH_FAILED", e.message ?: e.javaClass.simpleName, null)
|
||||
}
|
||||
}
|
||||
@@ -398,6 +711,92 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleDeviceAdjustmentCall(method: String, arguments: Any?, result: MethodChannel.Result) {
|
||||
try {
|
||||
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()
|
||||
}
|
||||
} 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,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})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,63 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.content.Context
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaCodecList
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
|
||||
enum class DvConversionMode { DISABLED, DV81, HEVC_STRIP }
|
||||
|
||||
object DoviBridge {
|
||||
private const val TAG = "DoviBridge"
|
||||
|
||||
data class DvAutoDecision(
|
||||
val mode: DvConversionMode,
|
||||
val reason: String,
|
||||
val bridgeReady: Boolean,
|
||||
val displayDv: Boolean,
|
||||
val nativeDecoder: Boolean,
|
||||
val advertisedP7: Boolean,
|
||||
val advertisedP8: Boolean,
|
||||
val decoders: String,
|
||||
val displayHdr: String
|
||||
) {
|
||||
fun logMessage(): String = "AUTO P7 DV decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
|
||||
"displayDV=$displayDv, nativeDecoder=$nativeDecoder, advertisedP7=$advertisedP7, " +
|
||||
"advertisedP8=$advertisedP8, decoders=$decoders, displayHdr=$displayHdr"
|
||||
}
|
||||
|
||||
data class Dv7FallbackDecision(
|
||||
val mode: DvConversionMode,
|
||||
val reason: String,
|
||||
val bridgeReady: Boolean,
|
||||
val displayDv: Boolean,
|
||||
val advertisedP8: Boolean,
|
||||
val displayHdr: String
|
||||
) {
|
||||
fun logMessage(): String = "DV7 fallback decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
|
||||
"displayDV=$displayDv, advertisedP8=$advertisedP8, displayHdr=$displayHdr"
|
||||
}
|
||||
|
||||
private val DOLBY_VISION_MIME_TYPES = setOf(
|
||||
"video/dolby-vision",
|
||||
"video/hevcdv",
|
||||
"video/dv_hevc"
|
||||
)
|
||||
|
||||
const val CONVERT_FAILED = -1
|
||||
const val DESTINATION_TOO_SMALL = -2
|
||||
|
||||
private data class DvProfileLevel(val profile: Int, val level: Int)
|
||||
|
||||
private data class DvDecoderCapability(
|
||||
val name: String,
|
||||
val mimeType: String,
|
||||
val profileLevels: List<DvProfileLevel>
|
||||
)
|
||||
|
||||
private val nativeLoaded: Boolean by lazy {
|
||||
try {
|
||||
System.loadLibrary("dovi_bridge")
|
||||
@@ -29,46 +74,253 @@ object DoviBridge {
|
||||
|
||||
fun isAvailable(): Boolean = conversionPathReady
|
||||
|
||||
private fun deviceSupportsDvProfile(profile: Int, minApi: Int = 0): Boolean {
|
||||
private val dolbyVisionDecoders: List<DvDecoderCapability> by lazy {
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT < minApi) return false
|
||||
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
|
||||
return codecList.codecInfos.any { info ->
|
||||
!info.isEncoder &&
|
||||
info.supportedTypes.any { type ->
|
||||
type.equals("video/dolby-vision", ignoreCase = true) &&
|
||||
info.getCapabilitiesForType(type).profileLevels.any { it.profile == profile }
|
||||
codecList.codecInfos.flatMap { info ->
|
||||
if (info.isEncoder) {
|
||||
emptyList()
|
||||
} else {
|
||||
info.supportedTypes.mapNotNull { type ->
|
||||
if (!DOLBY_VISION_MIME_TYPES.contains(type.lowercase())) return@mapNotNull null
|
||||
val capabilities = runCatching { info.getCapabilitiesForType(type) }
|
||||
.onFailure { Log.w(TAG, "Failed to query ${info.name} capabilities for $type", it) }
|
||||
.getOrNull()
|
||||
?: return@mapNotNull null
|
||||
DvDecoderCapability(
|
||||
name = info.name,
|
||||
mimeType = type,
|
||||
profileLevels = capabilities.profileLevels.map { DvProfileLevel(it.profile, it.level) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to query DV profile $profile support", e)
|
||||
return false
|
||||
Log.w(TAG, "Failed to query native Dolby Vision decoder support", e)
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
val hasNativeDolbyVisionDecoder: Boolean by lazy {
|
||||
dolbyVisionDecoders.isNotEmpty().also {
|
||||
Log.i(TAG, "Native Dolby Vision decoder available: $it; decoders=${describeDolbyVisionDecoders()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceAdvertisesDvProfile(profile: Int, minApi: Int = 0): Boolean {
|
||||
if (Build.VERSION.SDK_INT < minApi) return false
|
||||
return dolbyVisionDecoders.any { decoder ->
|
||||
decoder.profileLevels.any { it.profile == profile }
|
||||
}
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile7: Boolean by lazy {
|
||||
deviceSupportsDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr)
|
||||
.also { Log.i(TAG, "Device DV Profile 7 support: $it") }
|
||||
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb)
|
||||
.also { Log.i(TAG, "Device advertises exact DV Profile 7 (DvheDtb): $it") }
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile8: Boolean by lazy {
|
||||
deviceSupportsDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
|
||||
.also { Log.i(TAG, "Device DV Profile 8 support: $it") }
|
||||
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
|
||||
.also { Log.i(TAG, "Device advertises DV Profile 8 (DvheSt): $it") }
|
||||
}
|
||||
|
||||
fun getConversionMode(): DvConversionMode = when {
|
||||
!isAvailable() -> DvConversionMode.DISABLED
|
||||
deviceSupportsDvProfile7 -> DvConversionMode.DISABLED // try native first; ExoPlayerCore retries with conversion on failure
|
||||
deviceSupportsDvProfile8 -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
fun displaySupportsDolbyVision(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||
Log.i(TAG, "Display Dolby Vision support: false (HDR capabilities require API 24, device API=${Build.VERSION.SDK_INT})")
|
||||
return false
|
||||
}
|
||||
|
||||
val display = getCurrentDisplay(context)
|
||||
if (display == null) {
|
||||
Log.i(TAG, "Display Dolby Vision support: false (no active display)")
|
||||
return false
|
||||
}
|
||||
|
||||
val hdrTypes = runCatching { getDisplayHdrTypes(display) }.getOrElse { error ->
|
||||
Log.w(TAG, "Display Dolby Vision support: false (failed to query HDR types)", error)
|
||||
return false
|
||||
}
|
||||
val supported = hdrTypes.contains(Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION)
|
||||
Log.i(TAG, "Display Dolby Vision support: $supported; ${describeDisplayHdrCapabilities(display)}")
|
||||
return supported
|
||||
}
|
||||
|
||||
fun describeDisplayHdrCapabilities(context: Context): String {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "HDR capabilities unavailable (API=${Build.VERSION.SDK_INT})"
|
||||
val display = getCurrentDisplay(context) ?: return "HDR capabilities unavailable (no active display)"
|
||||
return describeDisplayHdrCapabilities(display)
|
||||
}
|
||||
|
||||
fun logSupportSummary(context: Context) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"DV support summary: bridgeReady=${isAvailable()}, displayDV=${displaySupportsDolbyVision(context)}, " +
|
||||
"nativeDecoder=$hasNativeDolbyVisionDecoder, advertisedP7=$deviceSupportsDvProfile7, " +
|
||||
"advertisedP8=$deviceSupportsDvProfile8, decoders=${describeDolbyVisionDecoders()}, " +
|
||||
"displayHdr=${describeDisplayHdrCapabilities(context)}"
|
||||
)
|
||||
}
|
||||
|
||||
fun getConversionDecision(context: Context): DvAutoDecision {
|
||||
val bridgeReady = isAvailable()
|
||||
val displayDv = displaySupportsDolbyVision(context)
|
||||
val nativeDecoder = hasNativeDolbyVisionDecoder
|
||||
val advertisedP7 = deviceSupportsDvProfile7
|
||||
val advertisedP8 = deviceSupportsDvProfile8
|
||||
|
||||
val mode = when {
|
||||
!displayDv -> DvConversionMode.HEVC_STRIP
|
||||
advertisedP7 -> DvConversionMode.DISABLED
|
||||
advertisedP8 && bridgeReady -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
}
|
||||
val reason = when {
|
||||
!displayDv -> "active display does not support Dolby Vision; stripping DV metadata for HEVC fallback"
|
||||
advertisedP7 -> "active display supports Dolby Vision and decoder advertises exact Profile 7; trying native DV first"
|
||||
advertisedP8 && bridgeReady -> "active display supports Dolby Vision and decoder advertises Profile 8; converting to Profile 8.1"
|
||||
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
|
||||
else -> "Dolby Vision output path is unavailable; stripping DV metadata for HEVC fallback"
|
||||
}
|
||||
val decision = DvAutoDecision(
|
||||
mode = mode,
|
||||
reason = reason,
|
||||
bridgeReady = bridgeReady,
|
||||
displayDv = displayDv,
|
||||
nativeDecoder = nativeDecoder,
|
||||
advertisedP7 = advertisedP7,
|
||||
advertisedP8 = advertisedP8,
|
||||
decoders = describeDolbyVisionDecoders(),
|
||||
displayHdr = describeDisplayHdrCapabilities(context)
|
||||
)
|
||||
Log.i(TAG, decision.logMessage())
|
||||
return decision
|
||||
}
|
||||
|
||||
fun getConversionMode(context: Context): DvConversionMode = getConversionDecision(context).mode
|
||||
|
||||
/** Get the fallback mode when native DV7 decoding fails. */
|
||||
fun getDv7FallbackMode(): DvConversionMode = when {
|
||||
deviceSupportsDvProfile8 -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
fun getDv7FallbackDecision(context: Context): Dv7FallbackDecision {
|
||||
val bridgeReady = isAvailable()
|
||||
val displayDv = displaySupportsDolbyVision(context)
|
||||
val advertisedP8 = deviceSupportsDvProfile8
|
||||
val mode = if (displayDv && advertisedP8 && bridgeReady) DvConversionMode.DV81 else DvConversionMode.HEVC_STRIP
|
||||
val reason = when {
|
||||
mode == DvConversionMode.DV81 -> "display supports Dolby Vision and decoder advertises Profile 8"
|
||||
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
|
||||
else -> "Dolby Vision output or Profile 8 support is unavailable"
|
||||
}
|
||||
val decision = Dv7FallbackDecision(
|
||||
mode = mode,
|
||||
reason = reason,
|
||||
bridgeReady = bridgeReady,
|
||||
displayDv = displayDv,
|
||||
advertisedP8 = advertisedP8,
|
||||
displayHdr = describeDisplayHdrCapabilities(context)
|
||||
)
|
||||
Log.i(TAG, decision.logMessage())
|
||||
return decision
|
||||
}
|
||||
|
||||
fun getDv7FallbackMode(context: Context): DvConversionMode = getDv7FallbackDecision(context).mode
|
||||
|
||||
private fun getCurrentDisplay(context: Context): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
context.display
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
(context.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.defaultDisplay
|
||||
}
|
||||
|
||||
private fun describeDolbyVisionDecoders(): String {
|
||||
if (dolbyVisionDecoders.isEmpty()) return "none"
|
||||
return dolbyVisionDecoders.joinToString { decoder ->
|
||||
val profiles = if (decoder.profileLevels.isEmpty()) {
|
||||
"none"
|
||||
} else {
|
||||
decoder.profileLevels.joinToString(prefix = "[", postfix = "]") {
|
||||
"${describeDvProfile(it.profile)}/${describeDvLevel(it.level)}"
|
||||
}
|
||||
}
|
||||
"${decoder.name}(${decoder.mimeType}, profiles=$profiles)"
|
||||
}
|
||||
}
|
||||
|
||||
private fun describeHdrTypes(hdrTypes: IntArray): String {
|
||||
if (hdrTypes.isEmpty()) return "none"
|
||||
return hdrTypes.joinToString(prefix = "[", postfix = "]") { type ->
|
||||
when (type) {
|
||||
Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "DOLBY_VISION"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10"
|
||||
Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10_PLUS"
|
||||
else -> "unknown(${hex(type)})"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun describeDisplayHdrCapabilities(display: Display): String {
|
||||
val hdrCapabilities = display.hdrCapabilities
|
||||
val parts = mutableListOf(
|
||||
"display=${display.displayId}:${display.name}",
|
||||
"activeMode=${describeDisplayMode(display.mode)}",
|
||||
"hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}",
|
||||
"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 {
|
||||
@Suppress("DEPRECATION")
|
||||
display.hdrCapabilities.supportedHdrTypes
|
||||
}
|
||||
|
||||
private fun describeDisplayMode(mode: Display.Mode): String {
|
||||
val hdr = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
", hdr=${describeHdrTypes(mode.supportedHdrTypes)}"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz$hdr"
|
||||
}
|
||||
|
||||
private fun formatLuminance(value: Float): String = if (value.isNaN() || value <= 0f) "unknown" else "${value}nits"
|
||||
|
||||
private fun describeDvProfile(profile: Int): String = when (profile) {
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPer -> "P0/DvavPer"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPen -> "P1/DvavPen"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDer -> "P2/DvheDer"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDen -> "P3/DvheDen"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr -> "P4/DvheDtr"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheStn -> "P5/DvheStn"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDth -> "P6/DvheDth"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb -> "P7/DvheDtb"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt -> "P8/DvheSt"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavSe -> "P9/DvavSe"
|
||||
else -> "unknown(${hex(profile)})"
|
||||
}
|
||||
|
||||
private fun describeDvLevel(level: Int): String = when (level) {
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd24 -> "L1/Hd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd30 -> "L2/Hd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd24 -> "L3/Fhd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd30 -> "L4/Fhd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd60 -> "L5/Fhd60"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd24 -> "L6/Uhd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd30 -> "L7/Uhd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd48 -> "L8/Uhd48"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd60 -> "L9/Uhd60"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd120 -> "L10/Uhd120"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k30 -> "L11/8k30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k60 -> "L12/8k60"
|
||||
else -> "unknown(${hex(level)})"
|
||||
}
|
||||
|
||||
private fun hex(value: Int): String = "0x${value.toString(16)}"
|
||||
|
||||
fun convertRpuNalu(
|
||||
payload: ByteArray,
|
||||
payloadOffset: Int,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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
|
||||
@@ -10,9 +11,10 @@ import androidx.media3.extractor.TrackOutput
|
||||
/**
|
||||
* TrackOutput wrapper that processes DV Profile 7 HEVC samples based on conversion mode:
|
||||
*
|
||||
* - DV81: Convert RPU NALs via libdovi to Profile 8.1, present as video/dolby-vision
|
||||
* with dvhe.08.XX codec string. Preserves dynamic tone mapping metadata.
|
||||
* - HEVC_STRIP: Strip all DV enhancement layers, present as plain video/hevc.
|
||||
* - DV81: Convert RPU NALs via libdovi mode 2 to Profile 8.1, present as
|
||||
* video/dolby-vision with dvhe.08.XX codec string. Conversion failures drop
|
||||
* that RPU instead of forwarding Profile 7 metadata into a Profile 8.1 stream.
|
||||
* - HEVC_STRIP: Strip DV RPU/EL NALs, present as plain video/hevc.
|
||||
*
|
||||
* Two modes of NAL framing (auto-detected):
|
||||
* - Annex B (MKV path): MatroskaExtractor outputs 00 00 00 01 start codes
|
||||
@@ -21,14 +23,14 @@ import androidx.media3.extractor.TrackOutput
|
||||
* NAL processing:
|
||||
* - Type 62 (UNSPEC62): DV RPU → convert (DV81) or strip (HEVC_STRIP)
|
||||
* - Type 63 (UNSPEC63): DV Enhancement Layer → strip
|
||||
* - nuh_layer_id > 0: Enhancement layer NAL → strip
|
||||
* - All retained NALs: normalize nuh_layer_id to 0
|
||||
* - All other NALs: pass through unchanged, matching Kodi's compatibility path
|
||||
*
|
||||
* All buffers are reused across samples to minimize GC pressure on the hot path.
|
||||
*/
|
||||
class DoviConvertingTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val emitLog: ((String, String, String) -> Unit)? = null
|
||||
) : TrackOutput {
|
||||
|
||||
companion object {
|
||||
@@ -45,6 +47,12 @@ class DoviConvertingTrackOutput(
|
||||
private set
|
||||
var strippedNalCount = 0L
|
||||
private set
|
||||
var strippedRpuNalCount = 0L
|
||||
private set
|
||||
var strippedElNalCount = 0L
|
||||
private set
|
||||
var strippedInitNalCount = 0L
|
||||
private set
|
||||
var convertedRpuCount = 0L
|
||||
private set
|
||||
var rpuConversionFailureCount = 0L
|
||||
@@ -69,59 +77,54 @@ class DoviConvertingTrackOutput(
|
||||
private var rpuConversionCallCount = 0L
|
||||
private var totalRpuConversionTimeUs = 0L
|
||||
private var totalSampleProcessingTimeUs = 0L
|
||||
private var loggedSupplementalWrapper = false
|
||||
private var loggedEncryptedSupplementalPassthrough = false
|
||||
|
||||
override fun format(format: Format) {
|
||||
if (!conversionActive) {
|
||||
val codecs = format.codecs
|
||||
if (codecs != null && codecs.startsWith("dvhe.07")) {
|
||||
if (isDvProfile7Codec(codecs)) {
|
||||
val codecString = codecs ?: ""
|
||||
conversionActive = true
|
||||
Log.i(TAG, "DV Profile 7 detected ($codecs), mode=$dvMode")
|
||||
Log.i(
|
||||
TAG,
|
||||
"Original format: mime=${format.sampleMimeType}, codecs=$codecs, " +
|
||||
logInfo("DV Profile 7 detected ($codecString), mode=$dvMode")
|
||||
when (dvMode) {
|
||||
DvConversionMode.DV81 -> logInfo("DV81: Kodi-style libdovi conversion (convert RPU type 62, drop EL type 63)")
|
||||
DvConversionMode.HEVC_STRIP -> logInfo("HEVC_STRIP: Kodi-compatible strip (drop RPU type 62 and EL type 63 only)")
|
||||
else -> Unit
|
||||
}
|
||||
logInfo(
|
||||
"Original format: mime=${format.sampleMimeType}, codecs=$codecString, " +
|
||||
"initData=${format.initializationData.size} entries " +
|
||||
"(${format.initializationData.mapIndexed { i, d -> "$i:${d.size}B" }.joinToString()})"
|
||||
)
|
||||
val strippedInitializationData = stripInitializationData(format.initializationData)
|
||||
|
||||
val newFormat = when (dvMode) {
|
||||
DvConversionMode.DV81 -> {
|
||||
// Parse DV level from codec string: "dvhe.07.06" → 6
|
||||
val level = codecs.split('.').getOrNull(2)?.toIntOrNull() ?: 6
|
||||
val level = codecString.split('.').getOrNull(2)?.toIntOrNull() ?: 6
|
||||
val newCodecs = "dvhe.08.%02d".format(level)
|
||||
val dvConfigRecord = buildDv81ConfigRecord(level)
|
||||
Log.i(TAG, "DV81: rewriting to $newCodecs, config=${dvConfigRecord.size}B")
|
||||
logInfo("DV81: rewriting to $newCodecs, config=${dvConfigRecord.size}B")
|
||||
|
||||
format.buildUpon()
|
||||
.setSampleMimeType(MimeTypes.VIDEO_DOLBY_VISION)
|
||||
.setCodecs(newCodecs)
|
||||
.setInitializationData(
|
||||
if (format.initializationData.isNotEmpty()) {
|
||||
listOf(format.initializationData[0], dvConfigRecord)
|
||||
} else {
|
||||
listOf(ByteArray(0), dvConfigRecord)
|
||||
}
|
||||
)
|
||||
.setInitializationData(strippedInitializationData + dvConfigRecord)
|
||||
.build()
|
||||
}
|
||||
else -> {
|
||||
// HEVC_STRIP: present as plain HEVC
|
||||
Log.i(TAG, "HEVC_STRIP: rewriting to video/hevc")
|
||||
logInfo("HEVC_STRIP: rewriting to video/hevc")
|
||||
format.buildUpon()
|
||||
.setSampleMimeType(MimeTypes.VIDEO_H265)
|
||||
.setCodecs(null)
|
||||
.setInitializationData(
|
||||
if (format.initializationData.isNotEmpty()) {
|
||||
listOf(format.initializationData[0])
|
||||
} else {
|
||||
emptyList()
|
||||
}
|
||||
)
|
||||
.setInitializationData(strippedInitializationData)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
Log.i(
|
||||
TAG,
|
||||
logInfo(
|
||||
"Rewritten format: mime=${newFormat.sampleMimeType}, " +
|
||||
"codecs=${newFormat.codecs}, initData=${newFormat.initializationData.size} entries"
|
||||
)
|
||||
@@ -179,23 +182,24 @@ class DoviConvertingTrackOutput(
|
||||
val srcLen = sampleLen
|
||||
sampleLen = 0
|
||||
|
||||
val outLen: Int
|
||||
val outBuf: ByteArray
|
||||
val processStartNs = System.nanoTime()
|
||||
val success = try {
|
||||
processNalUnits(srcLen)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "NAL processing failed, passing raw sample", e)
|
||||
val success = 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")
|
||||
}
|
||||
false
|
||||
}
|
||||
if (success) {
|
||||
outLen = outputLen
|
||||
outBuf = outputBuf
|
||||
} else {
|
||||
outLen = srcLen
|
||||
outBuf = sampleBuf
|
||||
try {
|
||||
processSampleData(flags, srcLen)
|
||||
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) {
|
||||
recordSampleProcessing((System.nanoTime() - processStartNs) / 1_000L)
|
||||
}
|
||||
@@ -209,17 +213,76 @@ class DoviConvertingTrackOutput(
|
||||
}
|
||||
|
||||
/**
|
||||
* Process NAL units in sampleBuf[0..dataLen). Auto-detects format:
|
||||
* Process a sample, unwrapping Media3 supplemental-data framing when present.
|
||||
*
|
||||
* Samples with C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA are stored as:
|
||||
* [4-byte big-endian main sample size][main sample][supplemental data].
|
||||
* Only the main sample contains video NALs and should be rewritten.
|
||||
*/
|
||||
private fun processSampleData(flags: Int, dataLen: Int) {
|
||||
if ((flags and C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA) == 0) {
|
||||
processNalUnits(0, dataLen)
|
||||
return
|
||||
}
|
||||
|
||||
if (dataLen < 4) {
|
||||
logWarn("Bad supplemental sample: ${dataLen}B is too small")
|
||||
copyRawSample(dataLen)
|
||||
return
|
||||
}
|
||||
|
||||
val mainSampleLen = readInt32BE(sampleBuf, 0)
|
||||
if (mainSampleLen < 0 || mainSampleLen > dataLen - 4) {
|
||||
logWarn("Bad supplemental sample: mainLen=$mainSampleLen total=$dataLen")
|
||||
copyRawSample(dataLen)
|
||||
return
|
||||
}
|
||||
|
||||
val supplementalLen = dataLen - 4 - mainSampleLen
|
||||
if (!loggedSupplementalWrapper) {
|
||||
loggedSupplementalWrapper = true
|
||||
logDebug(
|
||||
"Supplemental wrapper detected: total=${dataLen}B, main=${mainSampleLen}B, " +
|
||||
"supplemental=${supplementalLen}B, innerFirstBytes=${formatBytes(sampleBuf, 4, 8)}"
|
||||
)
|
||||
}
|
||||
|
||||
processNalUnits(4, mainSampleLen)
|
||||
|
||||
val processedMainLen = outputLen
|
||||
if (processedMainLen == 0) {
|
||||
outputLen = 0
|
||||
return
|
||||
}
|
||||
|
||||
ensureOutputCapacity(4 + processedMainLen + supplementalLen)
|
||||
System.arraycopy(outputBuf, 0, outputBuf, 4, processedMainLen)
|
||||
writeInt32BE(outputBuf, 0, processedMainLen)
|
||||
if (supplementalLen > 0) {
|
||||
System.arraycopy(sampleBuf, 4 + mainSampleLen, outputBuf, 4 + processedMainLen, supplementalLen)
|
||||
}
|
||||
outputLen = 4 + processedMainLen + supplementalLen
|
||||
|
||||
if (sampleCount <= 3 || (sampleCount % 500 == 0L)) {
|
||||
logDebug(
|
||||
"Sample #$sampleCount (Supplemental): main=${mainSampleLen}B -> ${processedMainLen}B, " +
|
||||
"supplemental=${supplementalLen}B, total=${dataLen}B -> ${outputLen}B"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process NAL units in sampleBuf[dataOffset..dataOffset+dataLen). Auto-detects format:
|
||||
* - Annex B (00 00 00 01 / 00 00 01 start codes) — used by MatroskaExtractor
|
||||
* - Length-prefixed (4-byte big-endian length) — used by Mp4Extractor
|
||||
*
|
||||
* Result is written to outputBuf[0..outputLen).
|
||||
*/
|
||||
private fun processNalUnits(dataLen: Int) {
|
||||
private fun processNalUnits(dataOffset: Int, dataLen: Int) {
|
||||
outputLen = 0
|
||||
if (dataLen < 4) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
System.arraycopy(sampleBuf, 0, outputBuf, 0, dataLen)
|
||||
System.arraycopy(sampleBuf, dataOffset, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
return
|
||||
}
|
||||
@@ -227,41 +290,41 @@ class DoviConvertingTrackOutput(
|
||||
// Auto-detect: Annex B starts with 00 00 00 01 or 00 00 01
|
||||
val isAnnexB = (
|
||||
dataLen >= 4 &&
|
||||
sampleBuf[0] == 0.toByte() &&
|
||||
sampleBuf[1] == 0.toByte() &&
|
||||
sampleBuf[2] == 0.toByte() &&
|
||||
sampleBuf[3] == 1.toByte()
|
||||
sampleBuf[dataOffset] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 1] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 2] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 3] == 1.toByte()
|
||||
) ||
|
||||
(
|
||||
dataLen >= 3 &&
|
||||
sampleBuf[0] == 0.toByte() &&
|
||||
sampleBuf[1] == 0.toByte() &&
|
||||
sampleBuf[2] == 1.toByte()
|
||||
sampleBuf[dataOffset] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 1] == 0.toByte() &&
|
||||
sampleBuf[dataOffset + 2] == 1.toByte()
|
||||
)
|
||||
|
||||
if (sampleCount == 0L) {
|
||||
Log.d(
|
||||
TAG,
|
||||
logDebug(
|
||||
"NAL format detected: ${if (isAnnexB) "Annex B" else "length-prefixed"}, " +
|
||||
"first bytes: ${sampleBuf.take(8).joinToString(" ") { "%02X".format(it) }}"
|
||||
"first bytes: ${formatBytes(sampleBuf, dataOffset, 8)}"
|
||||
)
|
||||
}
|
||||
|
||||
if (isAnnexB) processAnnexBNals(dataLen) else processLengthPrefixedNals(dataLen)
|
||||
if (isAnnexB) processAnnexBNals(dataOffset, dataLen) else processLengthPrefixedNals(dataOffset, dataLen)
|
||||
}
|
||||
|
||||
/** Process Annex B formatted NAL units (MKV path). Scans inline, no list allocation. */
|
||||
private fun processAnnexBNals(dataLen: Int) {
|
||||
private fun processAnnexBNals(dataOffset: Int, dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
val dataEnd = dataOffset + dataLen
|
||||
var kept = 0
|
||||
var stripped = 0
|
||||
|
||||
// Find first start code
|
||||
var scEnd = -1
|
||||
var i = 0
|
||||
while (i < dataLen - 2) {
|
||||
var i = dataOffset
|
||||
while (i < dataEnd - 2) {
|
||||
if (sampleBuf[i] == 0.toByte() && sampleBuf[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataLen && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
|
||||
if (i + 3 < dataEnd && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
|
||||
scEnd = i + 4
|
||||
break
|
||||
} else if (sampleBuf[i + 2] == 1.toByte()) {
|
||||
@@ -274,7 +337,7 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
if (scEnd < 0) {
|
||||
// No start codes found — pass through
|
||||
System.arraycopy(sampleBuf, 0, outputBuf, 0, dataLen)
|
||||
System.arraycopy(sampleBuf, dataOffset, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
sampleCount++
|
||||
return
|
||||
@@ -282,13 +345,13 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
var nalStart = scEnd
|
||||
|
||||
while (nalStart < dataLen) {
|
||||
while (nalStart < dataEnd) {
|
||||
// Find next start code to determine end of current NAL
|
||||
var nalEnd = dataLen
|
||||
var nalEnd = dataEnd
|
||||
i = nalStart
|
||||
while (i < dataLen - 2) {
|
||||
while (i < dataEnd - 2) {
|
||||
if (sampleBuf[i] == 0.toByte() && sampleBuf[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataLen && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
|
||||
if (i + 3 < dataEnd && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
|
||||
nalEnd = i
|
||||
break
|
||||
} else if (sampleBuf[i + 2] == 1.toByte()) {
|
||||
@@ -307,7 +370,6 @@ class DoviConvertingTrackOutput(
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
System.arraycopy(sampleBuf, nalStart, outputBuf, outputLen, nalLen)
|
||||
normalizeLayerId(outputBuf, outputLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
} else if (action == NalAction.CONVERT) {
|
||||
@@ -315,23 +377,22 @@ class DoviConvertingTrackOutput(
|
||||
if (convertedLen >= 0) {
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
normalizeLayerId(outputBuf, outputLen)
|
||||
outputLen += convertedLen
|
||||
convertedRpuCount++
|
||||
kept++
|
||||
} else {
|
||||
strippedNalCount++
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
} else {
|
||||
strippedNalCount++
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
}
|
||||
|
||||
// Advance past the next start code
|
||||
if (nalEnd >= dataLen) break
|
||||
nalStart = if (nalEnd + 3 < dataLen && sampleBuf[nalEnd + 2] == 0.toByte() && sampleBuf[nalEnd + 3] == 1.toByte()) {
|
||||
if (nalEnd >= dataEnd) break
|
||||
nalStart = if (nalEnd + 3 < dataEnd && sampleBuf[nalEnd + 2] == 0.toByte() && sampleBuf[nalEnd + 3] == 1.toByte()) {
|
||||
nalEnd + 4
|
||||
} else {
|
||||
nalEnd + 3
|
||||
@@ -340,8 +401,7 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
sampleCount++
|
||||
if (sampleCount <= 3 || (sampleCount % 500 == 0L)) {
|
||||
Log.d(
|
||||
TAG,
|
||||
logDebug(
|
||||
"Sample #$sampleCount (AnnexB): ${dataLen}B -> ${outputLen}B, " +
|
||||
"kept=$kept stripped=$stripped NALs"
|
||||
)
|
||||
@@ -349,21 +409,22 @@ class DoviConvertingTrackOutput(
|
||||
}
|
||||
|
||||
/** Process length-prefixed NAL units (MP4 path). */
|
||||
private fun processLengthPrefixedNals(dataLen: Int) {
|
||||
private fun processLengthPrefixedNals(dataOffset: Int, dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
var pos = 0
|
||||
val dataEnd = dataOffset + dataLen
|
||||
var pos = dataOffset
|
||||
var kept = 0
|
||||
var stripped = 0
|
||||
|
||||
while (pos + 4 <= dataLen) {
|
||||
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)
|
||||
|
||||
if (nalLen <= 0 || pos + 4 + nalLen > dataLen) {
|
||||
if (nalLen <= 0 || pos + 4 + nalLen > dataEnd) {
|
||||
if (sampleCount < 5) {
|
||||
Log.w(TAG, "Bad NAL length $nalLen at pos $pos (data.size=$dataLen)")
|
||||
logWarn("Bad NAL length $nalLen at pos ${pos - dataOffset} (data.size=$dataLen)")
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -375,7 +436,6 @@ class DoviConvertingTrackOutput(
|
||||
writeInt32BE(outputBuf, outputLen, nalLen)
|
||||
outputLen += 4
|
||||
System.arraycopy(sampleBuf, nalStart, outputBuf, outputLen, nalLen)
|
||||
normalizeLayerId(outputBuf, outputLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
} else if (action == NalAction.CONVERT) {
|
||||
@@ -383,16 +443,15 @@ class DoviConvertingTrackOutput(
|
||||
if (convertedLen >= 0) {
|
||||
writeInt32BE(outputBuf, outputLen, convertedLen)
|
||||
outputLen += 4
|
||||
normalizeLayerId(outputBuf, outputLen)
|
||||
outputLen += convertedLen
|
||||
convertedRpuCount++
|
||||
kept++
|
||||
} else {
|
||||
strippedNalCount++
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
} else {
|
||||
strippedNalCount++
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
|
||||
@@ -401,15 +460,24 @@ class DoviConvertingTrackOutput(
|
||||
|
||||
sampleCount++
|
||||
if (sampleCount <= 3 || (sampleCount % 500 == 0L)) {
|
||||
Log.d(
|
||||
TAG,
|
||||
logDebug(
|
||||
"Sample #$sampleCount (LenPrefix): ${dataLen}B -> ${outputLen}B, " +
|
||||
"kept=$kept stripped=$stripped NALs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private enum class NalAction { KEEP, STRIP, CONVERT }
|
||||
private enum class NalAction { KEEP, STRIP_RPU, STRIP_EL, CONVERT }
|
||||
|
||||
private fun recordStrippedNal(action: NalAction) {
|
||||
strippedNalCount++
|
||||
// CONVERT reaches here only after conversion fails; raw P7 RPUs are not safe in P8.1 output.
|
||||
when (action) {
|
||||
NalAction.STRIP_RPU, NalAction.CONVERT -> strippedRpuNalCount++
|
||||
NalAction.STRIP_EL -> strippedElNalCount++
|
||||
NalAction.KEEP -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun convertRpuIntoOutput(nalStart: Int, nalLen: Int, outputOffset: Int): Int {
|
||||
ensureOutputCapacity(outputOffset + MAX_CONVERTED_RPU_SIZE)
|
||||
@@ -449,8 +517,7 @@ class DoviConvertingTrackOutput(
|
||||
private fun recordSampleProcessing(elapsedUs: Long) {
|
||||
totalSampleProcessingTimeUs += elapsedUs
|
||||
if (sampleCount <= 3 || (sampleCount > 0 && sampleCount % 500 == 0L)) {
|
||||
Log.d(
|
||||
TAG,
|
||||
logDebug(
|
||||
"Perf: avgSample=${averageSampleProcessingTimeUs}us, " +
|
||||
"avgRpu=${averageRpuConversionTimeUs}us, converted=$convertedRpuCount, " +
|
||||
"rpuFailures=$rpuConversionFailureCount, rpuTooSmall=$rpuOutputTooSmallCount"
|
||||
@@ -458,23 +525,126 @@ class DoviConvertingTrackOutput(
|
||||
}
|
||||
}
|
||||
|
||||
/** Classify a NAL at sampleBuf[offset..offset+len) without copying. */
|
||||
private fun processNalInline(offset: Int, len: Int): NalAction {
|
||||
if (len < 2) return NalAction.KEEP
|
||||
val nalType = (sampleBuf[offset].toInt() ushr 1) and 0x3F
|
||||
val nuhLayerId = ((sampleBuf[offset].toInt() and 1) shl 5) or
|
||||
((sampleBuf[offset + 1].toInt() ushr 3) and 0x1F)
|
||||
return when {
|
||||
nalType == NAL_TYPE_UNSPEC62 && dvMode == DvConversionMode.DV81 -> NalAction.CONVERT
|
||||
nalType == NAL_TYPE_UNSPEC62 || nalType == NAL_TYPE_UNSPEC63 || nuhLayerId > 0 -> NalAction.STRIP
|
||||
else -> NalAction.KEEP
|
||||
private fun stripInitializationData(initializationData: List<ByteArray>): List<ByteArray> {
|
||||
if (initializationData.isEmpty()) return emptyList()
|
||||
|
||||
val stripped = ArrayList<ByteArray>(initializationData.size)
|
||||
var beforeBytes = 0
|
||||
var afterBytes = 0
|
||||
var droppedBuffers = 0
|
||||
|
||||
for (data in initializationData) {
|
||||
beforeBytes += data.size
|
||||
val processed = stripInitializationAnnexB(data)
|
||||
if (processed == null) {
|
||||
// Media3's HEVC init data is normally Annex B. Non-AnnexB entries in
|
||||
// Dolby Vision formats are typically dvcC/dvvC records, which must not
|
||||
// be forwarded when advertising plain HEVC.
|
||||
droppedBuffers++
|
||||
continue
|
||||
}
|
||||
if (processed.isEmpty()) {
|
||||
droppedBuffers++
|
||||
continue
|
||||
}
|
||||
afterBytes += processed.size
|
||||
stripped.add(processed)
|
||||
}
|
||||
|
||||
logInfo(
|
||||
"Init data stripped: ${initializationData.size} entries/${beforeBytes}B -> " +
|
||||
"${stripped.size} entries/${afterBytes}B, strippedNals=$strippedInitNalCount, " +
|
||||
"droppedBuffers=$droppedBuffers"
|
||||
)
|
||||
|
||||
return stripped
|
||||
}
|
||||
|
||||
private fun normalizeLayerId(data: ByteArray, offset: Int) {
|
||||
if (data.size - offset >= 2) {
|
||||
data[offset] = (data[offset].toInt() and 0xFE).toByte()
|
||||
data[offset + 1] = (data[offset + 1].toInt() and 0x07).toByte()
|
||||
private fun stripInitializationAnnexB(data: ByteArray): ByteArray? {
|
||||
if (data.isEmpty()) return data
|
||||
|
||||
val firstStartCodeEnd = findStartCodeEnd(data, 0) ?: return null
|
||||
ensureOutputCapacity(data.size)
|
||||
outputLen = 0
|
||||
|
||||
var kept = 0
|
||||
var stripped = 0
|
||||
var nalStart = firstStartCodeEnd
|
||||
|
||||
while (nalStart < data.size) {
|
||||
val nalEnd = findNextStartCodeOffset(data, nalStart) ?: data.size
|
||||
val nalLen = nalEnd - nalStart
|
||||
if (nalLen > 0) {
|
||||
when (classifyNal(data, nalStart, nalLen, convertRpu = false)) {
|
||||
NalAction.KEEP -> {
|
||||
ensureOutputCapacity(outputLen + 4 + nalLen)
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
System.arraycopy(data, nalStart, outputBuf, outputLen, nalLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
}
|
||||
else -> {
|
||||
strippedInitNalCount++
|
||||
stripped++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nalEnd >= data.size) break
|
||||
nalStart = findStartCodeEnd(data, nalEnd) ?: break
|
||||
}
|
||||
|
||||
logDebug("Init data sample: ${data.size}B -> ${outputLen}B, kept=$kept stripped=$stripped NALs")
|
||||
return outputBuf.copyOf(outputLen)
|
||||
}
|
||||
|
||||
private fun findStartCodeEnd(data: ByteArray, from: Int): Int? {
|
||||
var i = from
|
||||
while (i < data.size - 2) {
|
||||
if (data[i] == 0.toByte() && data[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < data.size && data[i + 2] == 0.toByte() && data[i + 3] == 1.toByte()) {
|
||||
return i + 4
|
||||
} else if (data[i + 2] == 1.toByte()) {
|
||||
return i + 3
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findNextStartCodeOffset(data: ByteArray, from: Int): Int? {
|
||||
var i = from
|
||||
while (i < data.size - 2) {
|
||||
if (data[i] == 0.toByte() && data[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < data.size && data[i + 2] == 0.toByte() && data[i + 3] == 1.toByte()) {
|
||||
return i
|
||||
} else if (data[i + 2] == 1.toByte()) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 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 isDvProfile7Codec(codecs: String?): Boolean {
|
||||
val normalized = codecs?.lowercase() ?: return false
|
||||
return normalized.startsWith("dvhe.07") || normalized.startsWith("dvh1.07")
|
||||
}
|
||||
|
||||
private fun classifyNal(data: ByteArray, offset: Int, len: Int, convertRpu: Boolean): NalAction {
|
||||
if (len < 2) return NalAction.KEEP
|
||||
val nalType = (data[offset].toInt() ushr 1) and 0x3F
|
||||
return when {
|
||||
nalType == NAL_TYPE_UNSPEC62 && convertRpu -> NalAction.CONVERT
|
||||
nalType == NAL_TYPE_UNSPEC62 -> NalAction.STRIP_RPU
|
||||
nalType == NAL_TYPE_UNSPEC63 -> NalAction.STRIP_EL
|
||||
else -> NalAction.KEEP
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,6 +655,23 @@ class DoviConvertingTrackOutput(
|
||||
buf[offset + 3] = (value and 0xFF).toByte()
|
||||
}
|
||||
|
||||
private fun readInt32BE(buf: ByteArray, offset: Int): Int = ((buf[offset].toInt() and 0xFF) shl 24) or
|
||||
((buf[offset + 1].toInt() and 0xFF) shl 16) or
|
||||
((buf[offset + 2].toInt() and 0xFF) shl 8) or
|
||||
(buf[offset + 3].toInt() and 0xFF)
|
||||
|
||||
private fun copyRawSample(dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
System.arraycopy(sampleBuf, 0, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
}
|
||||
|
||||
private fun formatBytes(data: ByteArray, offset: Int, length: Int): String {
|
||||
val end = minOf(data.size, offset + length)
|
||||
if (offset >= end) return ""
|
||||
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))
|
||||
@@ -497,6 +684,26 @@ class DoviConvertingTrackOutput(
|
||||
}
|
||||
}
|
||||
|
||||
private fun logDebug(message: String) {
|
||||
Log.d(TAG, message)
|
||||
emitLog?.invoke("debug", "dv-convert", message)
|
||||
}
|
||||
|
||||
private fun logInfo(message: String) {
|
||||
Log.i(TAG, message)
|
||||
emitLog?.invoke("info", "dv-convert", message)
|
||||
}
|
||||
|
||||
private fun logWarn(message: String) {
|
||||
Log.w(TAG, message)
|
||||
emitLog?.invoke("warn", "dv-convert", message)
|
||||
}
|
||||
|
||||
private fun logError(message: String, throwable: Throwable) {
|
||||
Log.e(TAG, message, throwable)
|
||||
emitLog?.invoke("error", "dv-convert", "$message: ${throwable.message}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a 24-byte DOVIDecoderConfigurationRecord for DV Profile 8.1.
|
||||
*
|
||||
|
||||
@@ -16,12 +16,13 @@ import androidx.media3.extractor.TrackOutput
|
||||
class DoviExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput,
|
||||
private val dvMode: DvConversionMode,
|
||||
private val emitLog: ((String, String, String) -> Unit)?,
|
||||
private val onVideoTrackWrapped: (DoviConvertingTrackOutput) -> Unit
|
||||
) : ExtractorOutput {
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (type == C.TRACK_TYPE_VIDEO) {
|
||||
val wrapper = DoviConvertingTrackOutput(original, dvMode)
|
||||
val wrapper = DoviConvertingTrackOutput(original, dvMode, emitLog)
|
||||
onVideoTrackWrapped(wrapper)
|
||||
return wrapper
|
||||
}
|
||||
@@ -39,7 +40,8 @@ class DoviExtractorOutputWrapper(
|
||||
*/
|
||||
class DoviExtractorWrapper(
|
||||
private val delegate: Extractor,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val emitLog: ((String, String, String) -> Unit)? = null
|
||||
) : Extractor {
|
||||
|
||||
@Volatile var doviTrackOutput: DoviConvertingTrackOutput? = null
|
||||
@@ -48,7 +50,7 @@ class DoviExtractorWrapper(
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(DoviExtractorOutputWrapper(output, dvMode) { doviTrackOutput = it })
|
||||
delegate.init(DoviExtractorOutputWrapper(output, dvMode, emitLog) { doviTrackOutput = it })
|
||||
}
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int = delegate.read(input, seekPosition)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ class ExoPlayerPlugin :
|
||||
private const val TAG = "ExoPlayerPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/exo_player"
|
||||
private const val EVENT_CHANNEL = "com.plezy/exo_player/events"
|
||||
private const val MPV_FALLBACK_SWITCH_TIMEOUT_MS = 15_000L
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
@@ -36,15 +37,29 @@ class ExoPlayerPlugin :
|
||||
private var mpvCore: MpvPlayerCore? = null // MPV fallback player
|
||||
private var usingMpvFallback: Boolean = false
|
||||
private var fallbackInProgress: Boolean = false
|
||||
private var pendingMpvFallbackSwitchGeneration: Int? = null
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
|
||||
// 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 val mainHandler = Handler(Looper.getMainLooper())
|
||||
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>()
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
@@ -80,6 +95,8 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
pendingMpvProperties.clear()
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity")
|
||||
@@ -94,6 +111,7 @@ class ExoPlayerPlugin :
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
sessionGeneration++
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(TAG, "Detached from activity for config changes")
|
||||
@@ -148,7 +166,9 @@ class ExoPlayerPlugin :
|
||||
}
|
||||
"setSubtitleStyle" -> handleSetSubtitleStyle(call, result)
|
||||
"setBoxFitMode" -> handleSetBoxFitMode(call, result)
|
||||
"setVideoZoom" -> handleSetVideoZoom(call, result)
|
||||
"setDvConversionMode" -> handleSetDvConversionMode(call, result)
|
||||
"setAudioNormalization" -> handleSetAudioNormalization(call, result)
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"setMpvProperty" -> handleSetMpvProperty(call, result)
|
||||
"setLogLevel" -> {
|
||||
@@ -180,16 +200,21 @@ class ExoPlayerPlugin :
|
||||
|
||||
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
|
||||
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
|
||||
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
|
||||
configuredBufferSizeBytes = bufferSizeBytes
|
||||
|
||||
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()
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -201,6 +226,9 @@ class ExoPlayerPlugin :
|
||||
bufferSizeBytes = bufferSizeBytes,
|
||||
tunnelingEnabled = tunnelingEnabled
|
||||
) ?: false
|
||||
if (success && playerCore?.setDebugDvConversionMode(dvConversionMode) != true) {
|
||||
Log.w(TAG, "Invalid DV conversion mode during initialize: $dvConversionMode")
|
||||
}
|
||||
|
||||
// Start hidden
|
||||
playerCore?.setVisible(false)
|
||||
@@ -223,6 +251,8 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
usingMpvFallback = false
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
pendingMpvProperties.clear()
|
||||
Log.d(TAG, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
@@ -235,16 +265,19 @@ class ExoPlayerPlugin :
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
val autoPlay = call.argument<Boolean>("autoPlay") ?: true
|
||||
val isLive = call.argument<Boolean>("isLive") ?: false
|
||||
val externalSubtitles = call.argument<List<Map<String, String?>>>("externalSubtitles")
|
||||
val externalSubtitles = call.argument<List<Map<String, Any?>>>("externalSubtitles")
|
||||
|
||||
if (uri == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
|
||||
// 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) {
|
||||
clearPendingMpvFallbackSwitch()
|
||||
pendingMpvProperties.clear()
|
||||
}
|
||||
|
||||
@@ -255,6 +288,8 @@ class ExoPlayerPlugin :
|
||||
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")
|
||||
}
|
||||
@@ -496,13 +531,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)
|
||||
}
|
||||
|
||||
@@ -546,6 +582,22 @@ class ExoPlayerPlugin :
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoZoom(call: MethodCall, result: MethodChannel.Result) {
|
||||
val scale = call.argument<Number>("scale")?.toDouble()
|
||||
if (scale == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'scale'", null)
|
||||
return
|
||||
}
|
||||
if (usingMpvFallback) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
playerCore?.setVideoZoom(scale)
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetDvConversionMode(call: MethodCall, result: MethodChannel.Result) {
|
||||
val mode = call.argument<String>("mode")
|
||||
if (mode == null) {
|
||||
@@ -566,6 +618,23 @@ 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 handleSetMpvProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val value = call.argument<String>("value")
|
||||
@@ -580,6 +649,9 @@ 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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -587,7 +659,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)
|
||||
}
|
||||
@@ -635,6 +707,8 @@ class ExoPlayerPlugin :
|
||||
"audio-bitrate" to mpv.getProperty("audio-bitrate"),
|
||||
// Performance metrics
|
||||
"total-avsync-change" to mpv.getProperty("total-avsync-change"),
|
||||
"cache-used" to mpv.getProperty("cache-used"),
|
||||
"demuxer-max-bytes" to mpv.getProperty("demuxer-max-bytes"),
|
||||
"cache-speed" to mpv.getProperty("cache-speed"),
|
||||
"frame-drop-count" to mpv.getProperty("frame-drop-count"),
|
||||
"decoder-frame-drop-count" to mpv.getProperty("decoder-frame-drop-count"),
|
||||
@@ -678,17 +752,48 @@ class ExoPlayerPlugin :
|
||||
// ExoPlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = nameToId[name] ?: return
|
||||
val propId = observedProperties[name]?.id ?: return
|
||||
mainHandler.post { eventSink?.success(listOf(propId, value)) }
|
||||
}
|
||||
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
private fun eventPayload(name: String, data: Map<String, Any>? = null): Map<String, Any> {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
mainHandler.post { eventSink?.success(event) }
|
||||
return event
|
||||
}
|
||||
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
val pendingFallbackSwitch =
|
||||
name == "file-loaded" && pendingMpvFallbackSwitchGeneration == sessionGeneration && usingMpvFallback
|
||||
if (pendingFallbackSwitch) {
|
||||
clearPendingMpvFallbackSwitch()
|
||||
}
|
||||
|
||||
val event = eventPayload(name, data)
|
||||
mainHandler.post {
|
||||
eventSink?.success(event)
|
||||
if (pendingFallbackSwitch) {
|
||||
eventSink?.success(eventPayload("backend-switched"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun armPendingMpvFallbackSwitch(generation: Int) {
|
||||
pendingMpvFallbackSwitchGeneration = generation
|
||||
mainHandler.postDelayed({
|
||||
if (pendingMpvFallbackSwitchGeneration == generation && sessionGeneration == generation && usingMpvFallback) {
|
||||
Log.w(TAG, "Timed out waiting for MPV fallback file-loaded before backend-switched")
|
||||
clearPendingMpvFallbackSwitch()
|
||||
onEvent("backend-switched", null)
|
||||
}
|
||||
}, MPV_FALLBACK_SWITCH_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
private fun clearPendingMpvFallbackSwitch() {
|
||||
pendingMpvFallbackSwitchGeneration = null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -713,6 +818,91 @@ class ExoPlayerPlugin :
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 setupMpvFallback(
|
||||
core: MpvPlayerCore,
|
||||
act: Activity,
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
positionMs: Long
|
||||
) {
|
||||
// Snapshot Dart-registered state on main thread before clearing
|
||||
val pendingProps = pendingMpvProperties.toList()
|
||||
pendingMpvProperties.clear()
|
||||
val observedProps = observedProperties.toList()
|
||||
|
||||
// Compute content FD on main thread (needs contentResolver)
|
||||
val mpvUri = openContentFd(uri, act.contentResolver)
|
||||
?.let { "fdclose://$it" } ?: uri
|
||||
|
||||
// Buffer size for closure
|
||||
val bufferSize = configuredBufferSizeBytes
|
||||
|
||||
if (mpvCore !== core) {
|
||||
core.dispose()
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return
|
||||
}
|
||||
// Configure basic MPV properties for Plex playback
|
||||
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
|
||||
core.setProperty("vo", "gpu")
|
||||
core.setProperty("ao", "audiotrack")
|
||||
|
||||
// Forward user's buffer config to MPV fallback
|
||||
if (bufferSize != null && bufferSize > 0) {
|
||||
core.setProperty("demuxer-max-bytes", bufferSize.toString())
|
||||
}
|
||||
|
||||
// Apply pending MPV properties from Dart
|
||||
for ((propName, propValue) in pendingProps) {
|
||||
core.setProperty(propName, propValue)
|
||||
}
|
||||
|
||||
// Re-observe exactly what Dart registered via observeProperty, so the
|
||||
// event stream keeps flowing for every property the Dart side consumes.
|
||||
for ((propName, observed) in observedProps) {
|
||||
core.observeProperty(propName, observed.format)
|
||||
}
|
||||
|
||||
// Show the MPV surface (internally posts to UI)
|
||||
core.setVisible(true)
|
||||
|
||||
// Load media at the same position
|
||||
val startSeconds = positionMs / 1000.0
|
||||
val options = mutableListOf<String>()
|
||||
options.add("start=$startSeconds")
|
||||
headers?.forEach { (key, value) ->
|
||||
options.add("http-header-fields-append=$key: $value")
|
||||
}
|
||||
val optionsStr = options.joinToString(",")
|
||||
armPendingMpvFallbackSwitch(sessionGeneration)
|
||||
core.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
|
||||
|
||||
// On GPUs without compute shaders, MPV can't do dynamic peak detection
|
||||
// and spline tone-mapping produces dim/washed-out results with extreme
|
||||
// static HDR peak metadata. Use reinhard which handles this better.
|
||||
Thread {
|
||||
val peakDetection = core.getProperty("hdr-compute-peak")
|
||||
if (peakDetection == "no") {
|
||||
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
|
||||
core.setProperty("tone-mapping", "reinhard")
|
||||
core.setProperty("tone-mapping-param", "0.7")
|
||||
core.setProperty("tone-mapping-mode", "luma")
|
||||
}
|
||||
}.start()
|
||||
|
||||
// Request audio focus
|
||||
core.requestAudioFocus()
|
||||
|
||||
Log.i(TAG, "Successfully switched to MPV fallback")
|
||||
}
|
||||
|
||||
override fun onFormatUnsupported(
|
||||
uri: String,
|
||||
headers: Map<String, String>?,
|
||||
@@ -747,17 +937,20 @@ class ExoPlayerPlugin :
|
||||
mpvCore?.dispose()
|
||||
mpvCore = null
|
||||
usingMpvFallback = false // Clear before handoff
|
||||
clearPendingMpvFallbackSwitch()
|
||||
|
||||
val generation = sessionGeneration
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
if (generation != sessionGeneration) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return@post
|
||||
}
|
||||
val act = activity
|
||||
if (act == null) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return@post
|
||||
}
|
||||
|
||||
@@ -774,6 +967,7 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
}
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
return@initialize
|
||||
}
|
||||
if (!success) {
|
||||
@@ -782,6 +976,7 @@ class ExoPlayerPlugin :
|
||||
mpvCore = null
|
||||
}
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
Log.e(TAG, "Failed to initialize MPV fallback")
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: $errorMessage"))
|
||||
return@initialize
|
||||
@@ -790,95 +985,18 @@ 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)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
Log.e(TAG, "Failed to switch to MPV fallback", e)
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fallbackInProgress = false
|
||||
clearPendingMpvFallbackSwitch()
|
||||
Log.e(TAG, "Failed to switch to MPV fallback", e)
|
||||
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ 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.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
|
||||
@@ -17,6 +21,10 @@ 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 java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.math.abs
|
||||
@@ -27,6 +35,54 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
|
||||
val audioDelayUs = AtomicLong(0L)
|
||||
|
||||
/** Returns whether direct encoded output should be hidden so decoded PCM output can be selected. */
|
||||
var shouldBlockDirectAudioOutput: ((Format) -> Boolean)? = null
|
||||
|
||||
/** Called before Media3 reacts to an audio route/capability change. */
|
||||
var onAudioCapabilitiesChanged: (() -> Unit)? = null
|
||||
|
||||
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),
|
||||
videoDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
|
||||
override fun buildAudioSink(
|
||||
context: Context,
|
||||
enableFloatOutput: Boolean,
|
||||
@@ -51,10 +107,17 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
val defaultSink = DefaultAudioSink.Builder(context)
|
||||
.setEnableFloatOutput(enableFloatOutput)
|
||||
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
|
||||
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs))
|
||||
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs, audioDiagnosticsLogger))
|
||||
.build()
|
||||
|
||||
return PositionFixAudioSink(defaultSink, rawPositionUs, audioDelayUs)
|
||||
return PositionFixAudioSink(
|
||||
defaultSink,
|
||||
rawPositionUs,
|
||||
audioDelayUs,
|
||||
shouldBlockDirectAudioOutput,
|
||||
onAudioCapabilitiesChanged,
|
||||
audioDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +146,10 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
private class PositionFixAudioSink(
|
||||
sink: AudioSink,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val audioDelayUs: AtomicLong
|
||||
private val audioDelayUs: AtomicLong,
|
||||
private val shouldBlockDirectAudioOutput: ((Format) -> Boolean)?,
|
||||
private val onAudioCapabilitiesChanged: (() -> Unit)?,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : ForwardingAudioSink(sink) {
|
||||
|
||||
private var startMediaTimeUs = Long.MIN_VALUE
|
||||
@@ -97,12 +163,45 @@ private class PositionFixAudioSink(
|
||||
// Transient counter-offset: after seek/flush, ramp offset from 0 to full
|
||||
// over recoveryDurationUs to prevent video frame drops.
|
||||
private var recoveryDurationUs = 0L
|
||||
private val loggedDirectBlockMimeTypes = mutableSetOf<String>()
|
||||
private var loggedFirstBuffer = false
|
||||
|
||||
override fun supportsFormat(format: Format): Boolean {
|
||||
if (blocksDirectAudioOutput(format)) return false
|
||||
return super.supportsFormat(format)
|
||||
}
|
||||
|
||||
override fun getFormatSupport(format: Format): Int {
|
||||
if (blocksDirectAudioOutput(format)) return AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
return super.getFormatSupport(format)
|
||||
}
|
||||
|
||||
private fun blocksDirectAudioOutput(format: Format): Boolean {
|
||||
if (shouldBlockDirectAudioOutput?.invoke(format) != true) return false
|
||||
val mimeType = format.sampleMimeType ?: "unknown"
|
||||
if (loggedDirectBlockMimeTypes.add(mimeType)) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"audio",
|
||||
"Blocking direct $mimeType output; decoded PCM output will be preferred"
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun handleBuffer(
|
||||
buffer: ByteBuffer,
|
||||
presentationTimeUs: Long,
|
||||
encodedAccessUnitCount: Int
|
||||
): Boolean {
|
||||
if (!loggedFirstBuffer && buffer.hasRemaining()) {
|
||||
loggedFirstBuffer = true
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"audio-sink",
|
||||
"First buffer: size=${buffer.remaining()}B, pts=${presentationTimeUs}us, accessUnits=$encodedAccessUnitCount"
|
||||
)
|
||||
}
|
||||
if (startMediaTimeUs == Long.MIN_VALUE) {
|
||||
startMediaTimeUs = presentationTimeUs
|
||||
refMediaTimeUs = presentationTimeUs
|
||||
@@ -163,7 +262,10 @@ private class PositionFixAudioSink(
|
||||
override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) = listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
|
||||
override fun onOffloadBufferEmptying() = listener.onOffloadBufferEmptying()
|
||||
override fun onOffloadBufferFull() = listener.onOffloadBufferFull()
|
||||
override fun onAudioCapabilitiesChanged() = listener.onAudioCapabilitiesChanged()
|
||||
override fun onAudioCapabilitiesChanged() {
|
||||
onAudioCapabilitiesChanged?.invoke()
|
||||
listener.onAudioCapabilitiesChanged()
|
||||
}
|
||||
override fun onAudioTrackInitialized(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackInitialized(audioTrackConfig)
|
||||
override fun onAudioTrackReleased(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackReleased(audioTrackConfig)
|
||||
override fun onSilenceSkipped() = listener.onSilenceSkipped()
|
||||
@@ -225,6 +327,96 @@ 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 log: ((String, String, String) -> Unit)?
|
||||
) : MediaCodecVideoRenderer(builder) {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
private var stripHdr10PlusSei = false
|
||||
private var stripDvRpu = false
|
||||
|
||||
// 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
|
||||
@@ -235,7 +427,8 @@ internal class SubtitleDelayRenderer(
|
||||
@OptIn(UnstableApi::class)
|
||||
private class RawPositionOutputProvider(
|
||||
private val delegate: AudioOutputProvider,
|
||||
private val rawPositionUs: AtomicLong
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : AudioOutputProvider {
|
||||
|
||||
private var cachedOutput: RawPositionAudioOutput? = null
|
||||
@@ -256,7 +449,7 @@ private class RawPositionOutputProvider(
|
||||
|
||||
val realOutput = delegate.getAudioOutput(config)
|
||||
cachedConfig = config
|
||||
return RawPositionAudioOutput(realOutput, rawPositionUs, this)
|
||||
return RawPositionAudioOutput(realOutput, rawPositionUs, this, log)
|
||||
}
|
||||
|
||||
fun returnToCache(output: RawPositionAudioOutput) {
|
||||
@@ -285,9 +478,15 @@ private class RawPositionOutputProvider(
|
||||
private class RawPositionAudioOutput(
|
||||
private val delegate: AudioOutput,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val provider: RawPositionOutputProvider
|
||||
private val provider: RawPositionOutputProvider,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : AudioOutput {
|
||||
|
||||
private var loggedFirstWrite = false
|
||||
private var writeCount = 0L
|
||||
private var writtenBytes = 0L
|
||||
private var failed = false
|
||||
|
||||
override fun getPositionUs(): Long {
|
||||
val pos = delegate.getPositionUs()
|
||||
rawPositionUs.set(pos)
|
||||
@@ -298,10 +497,37 @@ private class RawPositionAudioOutput(
|
||||
override fun pause() = delegate.pause()
|
||||
|
||||
@Throws(AudioOutput.WriteException::class)
|
||||
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long) = delegate.write(buffer, size, presentationTimeUs)
|
||||
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long): Boolean {
|
||||
val before = buffer.position()
|
||||
val handled = try {
|
||||
delegate.write(buffer, size, presentationTimeUs)
|
||||
} catch (e: AudioOutput.WriteException) {
|
||||
failed = true
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
log?.invoke("warn", "audio-output", "Write failed; AudioTrack will not be reused: ${e.message}")
|
||||
throw e
|
||||
}
|
||||
val written = buffer.position() - before
|
||||
if (written > 0) {
|
||||
writeCount++
|
||||
writtenBytes += written.toLong()
|
||||
if (!loggedFirstWrite) {
|
||||
loggedFirstWrite = true
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"audio-output",
|
||||
"First write: wrote=${written}B, handled=$handled, pts=${presentationTimeUs}us, writes=$writeCount, total=${writtenBytes}B"
|
||||
)
|
||||
}
|
||||
}
|
||||
return handled
|
||||
}
|
||||
|
||||
override fun flush() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
loggedFirstWrite = false
|
||||
writeCount = 0
|
||||
writtenBytes = 0
|
||||
delegate.flush()
|
||||
}
|
||||
|
||||
@@ -309,6 +535,10 @@ private class RawPositionAudioOutput(
|
||||
|
||||
override fun release() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
if (failed) {
|
||||
delegate.release()
|
||||
return
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 25) {
|
||||
delegate.stop()
|
||||
delegate.flush()
|
||||
|
||||
@@ -7,8 +7,8 @@ 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).
|
||||
|
||||
@@ -174,7 +174,8 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
)
|
||||
frameRateManager = FrameRateManager(
|
||||
activity = activity,
|
||||
handler = handler
|
||||
handler = handler,
|
||||
log = { emitLog("info", "framerate", it) }
|
||||
)
|
||||
|
||||
// Create FrameLayout container for video
|
||||
@@ -237,6 +238,9 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
setOption("opengl-es", "yes")
|
||||
setOption("vd-lavc-film-grain", "cpu")
|
||||
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)
|
||||
}
|
||||
@@ -276,6 +280,17 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
|
||||
// Flow collectors
|
||||
|
||||
private fun emitLog(level: String, prefix: String, text: String) {
|
||||
delegate?.onEvent(
|
||||
"log-message",
|
||||
mapOf(
|
||||
"prefix" to prefix,
|
||||
"level" to level,
|
||||
"text" to text
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun collectEvents(p: MpvPlayer) {
|
||||
scope.launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
p.eventFlow.collect { event ->
|
||||
@@ -317,14 +332,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
private fun collectLogMessages(p: MpvPlayer) {
|
||||
scope.launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
p.logFlow.collect { msg ->
|
||||
delegate?.onEvent(
|
||||
"log-message",
|
||||
mapOf(
|
||||
"prefix" to msg.prefix,
|
||||
"level" to msg.level.name.lowercase(),
|
||||
"text" to msg.text
|
||||
)
|
||||
)
|
||||
emitLog(msg.level.name.lowercase(), msg.prefix, msg.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -784,7 +792,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, surfaceView?.holder?.surface, extraDelayMs) { switched ->
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs) { switched ->
|
||||
player?.let { updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") }
|
||||
onComplete(switched)
|
||||
}
|
||||
@@ -805,6 +813,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.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.os.Build
|
||||
|
||||
object DeviceQuirks {
|
||||
val isEWaste: Boolean
|
||||
get() = isGooglePixelDevice || isGoogleTensorDevice
|
||||
|
||||
private val isGooglePixelDevice: Boolean
|
||||
get() = (
|
||||
Build.MANUFACTURER.equals("Google", ignoreCase = true) ||
|
||||
Build.BRAND.equals("google", ignoreCase = true)
|
||||
) &&
|
||||
Build.MODEL.contains("Pixel", ignoreCase = true)
|
||||
|
||||
private val isGoogleTensorDevice: Boolean
|
||||
get() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
|
||||
val soc = Build.SOC_MODEL
|
||||
return soc.startsWith("Tensor", ignoreCase = true) ||
|
||||
soc.startsWith("GS", ignoreCase = true)
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,11 @@ import android.hardware.display.DisplayManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import androidx.annotation.RequiresApi
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class FrameRateManager(
|
||||
private val activity: Activity,
|
||||
@@ -19,11 +19,23 @@ class FrameRateManager(
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "FrameRateManager"
|
||||
private const val SHORT_VIDEO_LENGTH_MS = 300000L // 5 minutes
|
||||
private const val DISPLAY_SETTLE_MS = 2000L
|
||||
private const val WATCHDOG_MARGIN_MS = 3000L
|
||||
private const val RATE_TOLERANCE = 0.1f
|
||||
}
|
||||
|
||||
private data class RefreshRateMatch(
|
||||
val reason: String,
|
||||
val priority: Int,
|
||||
val error: Float
|
||||
)
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private data class DisplayModeCandidate(
|
||||
val mode: Display.Mode,
|
||||
val match: RefreshRateMatch
|
||||
)
|
||||
|
||||
private var currentVideoFps: Float = 0f
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private var pendingSettleRunnable: Runnable? = null
|
||||
@@ -32,20 +44,18 @@ class FrameRateManager(
|
||||
|
||||
private fun getDisplayManager(): DisplayManager = activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
|
||||
|
||||
// / Request a display frame-rate switch. Invokes [onComplete] once, either:
|
||||
// / - immediately with `switched=false` when no switch is needed (invalid
|
||||
// / fps, no matching mode, seamless fallback); or
|
||||
// / - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the
|
||||
// / caller's [extraDelayMs], with `switched=true`; or
|
||||
// / - via a watchdog with `switched=true` if the real event never arrives,
|
||||
// / so the caller doesn't hang.
|
||||
// /
|
||||
// / The caller is responsible for pausing playback before calling and
|
||||
// / resuming it after [onComplete] fires.
|
||||
// Request a display frame-rate switch. Invokes [onComplete] once, either:
|
||||
// - immediately with `switched=false` when no switch is needed (invalid fps,
|
||||
// no matching mode, or already matching); or
|
||||
// - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the caller's
|
||||
// [extraDelayMs], with `switched=true`; or
|
||||
// - via a watchdog if the real event never arrives, so the caller doesn't hang.
|
||||
//
|
||||
// The caller is responsible for pausing playback before calling and resuming
|
||||
// it after [onComplete] fires.
|
||||
fun setVideoFrameRate(
|
||||
fps: Float,
|
||||
videoDurationMs: Long,
|
||||
surface: Surface?,
|
||||
extraDelayMs: Long,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
@@ -56,22 +66,15 @@ class FrameRateManager(
|
||||
return
|
||||
}
|
||||
|
||||
log("fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, API=${Build.VERSION.SDK_INT}")
|
||||
log(
|
||||
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
|
||||
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
)
|
||||
|
||||
when {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
if (surface == null) {
|
||||
Log.d(TAG, "setVideoFrameRate: Surface not available")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
setFrameRateS(fps, surface, videoDurationMs, extraDelayMs, onComplete)
|
||||
}
|
||||
// API R's Surface.setFrameRate() only supports seamless switching (no
|
||||
// CHANGE_FRAME_RATE_ALWAYS), so 60→24Hz won't switch. Fall through to
|
||||
// preferredDisplayModeId which directly sets the display mode.
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> setFrameRateM(fps, extraDelayMs, onComplete)
|
||||
else -> onComplete(false)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
setDisplayMode(fps, extraDelayMs, onComplete)
|
||||
} else {
|
||||
onComplete(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,11 +119,11 @@ class FrameRateManager(
|
||||
}
|
||||
val cb = pendingCompletion ?: return
|
||||
pendingCompletion = null
|
||||
Log.d(TAG, "FrameRateManager complete ($reason, switched=$switched)")
|
||||
log("complete reason=$reason, switched=$switched, currentMode=${currentModeDescription()}")
|
||||
cb(switched)
|
||||
}
|
||||
|
||||
private fun registerDisplayListener(extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
private fun registerDisplayListener(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
// Resolve any previous pending op before starting a new one.
|
||||
firePendingCompletion("superseded", switched = false)
|
||||
pendingCompletion = onComplete
|
||||
@@ -135,7 +138,7 @@ class FrameRateManager(
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
|
||||
val settle = Runnable { firePendingCompletion("display settled", switched = true) }
|
||||
val settle = Runnable { firePendingCompletion("display settled", switched = currentRateMatch(fps) != null) }
|
||||
pendingSettleRunnable = settle
|
||||
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
|
||||
}
|
||||
@@ -145,148 +148,122 @@ class FrameRateManager(
|
||||
// Watchdog: if the TV never signals a display change (silently ignoring
|
||||
// the mode request), still complete after a bounded wait so the caller
|
||||
// doesn't hang.
|
||||
val watchdog = Runnable { firePendingCompletion("watchdog", switched = true) }
|
||||
val watchdog = Runnable { firePendingCompletion("watchdog", switched = currentRateMatch(fps) != null) }
|
||||
watchdogRunnable = watchdog
|
||||
handler.postDelayed(watchdog, DISPLAY_SETTLE_MS + extraDelayMs + WATCHDOG_MARGIN_MS)
|
||||
}
|
||||
|
||||
private fun currentRateMatchesFps(fps: Float): Boolean {
|
||||
val current = activity.display?.mode?.refreshRate ?: return false
|
||||
if (current <= 0f) return false
|
||||
// Treat "equal within a frame" and "clean multiple" as a match —
|
||||
// same tolerance the API M matcher uses below.
|
||||
if (kotlin.math.abs(current - fps) < 0.1f) return true
|
||||
val mod = current % fps
|
||||
return mod < 0.1f || (fps - mod) < 0.1f
|
||||
private fun matchRefreshRate(refreshRate: Float, fps: Float): RefreshRateMatch? {
|
||||
if (refreshRate <= 0f || fps <= 0f) return null
|
||||
|
||||
val exactError = abs(refreshRate - fps)
|
||||
if (exactError < RATE_TOLERANCE) {
|
||||
return RefreshRateMatch(reason = "exact", priority = 0, error = exactError)
|
||||
}
|
||||
|
||||
val multiple = (refreshRate / fps).roundToInt()
|
||||
if (multiple > 1) {
|
||||
val multipleError = abs(refreshRate - (fps * multiple))
|
||||
if (multipleError < RATE_TOLERANCE) {
|
||||
return RefreshRateMatch(reason = "${multiple}x", priority = 1, error = multipleError)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.S)
|
||||
private fun setFrameRateS(
|
||||
fps: Float,
|
||||
surface: Surface,
|
||||
videoDurationMs: Long,
|
||||
extraDelayMs: Long,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
Log.d(TAG, "setFrameRateS: fps=$fps, duration=${videoDurationMs}ms")
|
||||
|
||||
// If the current display rate already satisfies the video fps, issue
|
||||
// the hint for book-keeping but skip the listener — otherwise we'd
|
||||
// wait for an onDisplayChanged event that never fires and end up
|
||||
// burning the watchdog timeout for no reason.
|
||||
if (currentRateMatchesFps(fps)) {
|
||||
Log.d(TAG, "Current display rate already matches ${fps}fps, no switch needed")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (videoDurationMs < SHORT_VIDEO_LENGTH_MS) {
|
||||
Log.d(TAG, "Short video, using seamless-only switching")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
var seamless = false
|
||||
activity.display?.mode?.alternativeRefreshRates?.let { refreshRates ->
|
||||
for (rate in refreshRates) {
|
||||
if (fps.toString().startsWith(rate.toString()) ||
|
||||
rate.toString().startsWith(fps.toString()) ||
|
||||
rate % fps == 0f
|
||||
) {
|
||||
seamless = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seamless) {
|
||||
log("Seamless switch available for ${fps}fps")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener(extraDelayMs, onComplete)
|
||||
private fun currentRateMatch(fps: Float): RefreshRateMatch? {
|
||||
val current = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
currentDisplayMode()?.refreshRate
|
||||
} else {
|
||||
val userPreference = getDisplayManager().matchContentFrameRateUserPreference
|
||||
if (userPreference == DisplayManager.MATCH_CONTENT_FRAMERATE_ALWAYS) {
|
||||
Log.d(TAG, "User preference allows non-seamless switch")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ALWAYS
|
||||
)
|
||||
registerDisplayListener(extraDelayMs, onComplete)
|
||||
} else {
|
||||
Log.d(TAG, "Non-seamless switch not allowed, using seamless-only")
|
||||
surface.setFrameRate(
|
||||
fps,
|
||||
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
|
||||
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
|
||||
)
|
||||
onComplete(false)
|
||||
}
|
||||
}
|
||||
null
|
||||
} ?: return null
|
||||
return matchRefreshRate(current, fps)
|
||||
}
|
||||
|
||||
private fun currentModeDescription(): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
describeMode(currentDisplayMode())
|
||||
} else {
|
||||
"unavailable"
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setFrameRateM(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
Log.d(TAG, "setFrameRateM: fps=$fps")
|
||||
val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
|
||||
private fun currentDisplay(): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
activity.display
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val display = wm.defaultDisplay
|
||||
(activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun currentDisplayMode(): Display.Mode? = currentDisplay()?.mode
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun describeMode(mode: Display.Mode?): String {
|
||||
if (mode == null) return "unknown"
|
||||
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz"
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
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) }
|
||||
)
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
log("setDisplayMode fps=$fps")
|
||||
val display = currentDisplay()
|
||||
if (display == null) {
|
||||
log("display unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
val supportedModes = display.supportedModes
|
||||
if (supportedModes == null) {
|
||||
log("supported display modes unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
val currentMode = display.mode
|
||||
var modeToUse = currentMode
|
||||
log("supported modes=${describeSupportedModes(supportedModes)}")
|
||||
|
||||
for (mode in supportedModes) {
|
||||
if (mode.physicalHeight != currentMode.physicalHeight ||
|
||||
mode.physicalWidth != currentMode.physicalWidth
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (BigDecimal(fps.toString()).setScale(1, RoundingMode.FLOOR) ==
|
||||
BigDecimal(mode.refreshRate.toString()).setScale(1, RoundingMode.FLOOR)
|
||||
) {
|
||||
modeToUse = mode
|
||||
break
|
||||
} else if ((mode.refreshRate % fps).let { it < 0.1f || (fps - it) < 0.1f }) {
|
||||
modeToUse = mode
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (modeToUse == currentMode) {
|
||||
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes)
|
||||
if (modeMatch == null) {
|
||||
log("no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight}")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "Switching to mode ${modeToUse.modeId} (${modeToUse.refreshRate}Hz)")
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = modeToUse.modeId
|
||||
activity.window?.attributes = attrs
|
||||
val modeToUse = modeMatch.mode
|
||||
if (modeToUse.modeId == currentMode.modeId) {
|
||||
log("current mode already matches ${fps}fps (${modeMatch.match.reason}), no switch needed")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
registerDisplayListener(extraDelayMs, onComplete)
|
||||
|
||||
log(
|
||||
"switching to ${describeMode(modeToUse)} for ${fps}fps " +
|
||||
"(${modeMatch.match.reason}, error=${modeMatch.match.error})"
|
||||
)
|
||||
val window = activity.window
|
||||
if (window == null) {
|
||||
log("window unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
registerDisplayListener(fps, extraDelayMs, onComplete)
|
||||
window.attributes = window.attributes.apply { preferredDisplayModeId = modeToUse.modeId }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,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
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,28 @@ allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
if (providers.gradleProperty("localAssCore").isPresent) {
|
||||
// Opt-in A/B of a locally built libass native core: build it in the
|
||||
// libass-android fork with `./gradlew :lib_ass:publishToMavenLocal
|
||||
// -PVERSION_NAME=0.4.0-local`, then build this app with -PlocalAssCore.
|
||||
mavenLocal()
|
||||
} else {
|
||||
// Production libass native core: the -O3/NEON/asm AAR published on
|
||||
// the edde746/libass-android fork's releases (the upstream Maven
|
||||
// artifact io.github.peerless2012:ass ships un-optimized natives —
|
||||
// see the fork's pinned libass-cmake fix). Resolved as
|
||||
// <tag>/ass-<tag>.aar with no metadata probing.
|
||||
exclusiveContent {
|
||||
forRepository {
|
||||
ivy {
|
||||
url = uri("https://github.com/edde746/libass-android/releases/download")
|
||||
patternLayout { artifact("[revision]/[artifact]-[revision].[ext]") }
|
||||
metadataSources { artifact() }
|
||||
}
|
||||
}
|
||||
filter { includeModule("io.github.peerless2012", "ass") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
require 'dotenv/load'
|
||||
Dotenv.load("../../.env")
|
||||
require 'shellwords'
|
||||
|
||||
PROJECT_ROOT = File.expand_path("../..", __dir__)
|
||||
PROJECT_ROOT_ARG = Shellwords.escape(PROJECT_ROOT)
|
||||
|
||||
Dotenv.load(File.join(PROJECT_ROOT, ".env"))
|
||||
|
||||
default_platform(:android)
|
||||
|
||||
@@ -7,7 +12,7 @@ platform :android do
|
||||
desc "Build and deploy to Google Play Store"
|
||||
lane :release do
|
||||
# Get version from pubspec.yaml
|
||||
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
|
||||
pubspec_path = File.join(PROJECT_ROOT, "pubspec.yaml")
|
||||
pubspec_content = File.read(pubspec_path)
|
||||
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
|
||||
|
||||
@@ -19,11 +24,11 @@ platform :android do
|
||||
UI.user_error!("Could not extract version from pubspec.yaml")
|
||||
end
|
||||
|
||||
git_commit = `git rev-parse --short HEAD`.strip
|
||||
git_commit = `git -C #{PROJECT_ROOT_ARG} rev-parse --short HEAD`.strip
|
||||
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=play-store --obfuscate --split-debug-info=debug-info/android-aab")
|
||||
sh("cd #{ENV['PWD']}/.. && ./scripts/upload-symbols.sh android-aab")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && flutter build appbundle --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=play-store --dart-define=SENTRY_DIST=play-store --obfuscate --split-debug-info=debug-info/android-aab --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-aab/obfuscation.map.json")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=play-store ./scripts/upload-symbols.sh android-aab")
|
||||
|
||||
upload_to_play_store(
|
||||
track: "production",
|
||||
@@ -33,8 +38,8 @@ platform :android do
|
||||
)
|
||||
|
||||
# Build universal APK for Amazon Appstore (doesn't accept AABs, excludes x86 via env var)
|
||||
sh("cd #{ENV['PWD']}/.. && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=amazon --obfuscate --split-debug-info=debug-info/android-apk")
|
||||
sh("cd #{ENV['PWD']}/.. && ./scripts/upload-symbols.sh android-apk")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=amazon --dart-define=SENTRY_DIST=amazon --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=amazon ./scripts/upload-symbols.sh android-apk")
|
||||
|
||||
upload_to_amazon_appstore(
|
||||
apk_paths: [
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
# This builtInKotlin flag was added automatically by Flutter migrator
|
||||
android.builtInKotlin=false
|
||||
# This newDsl flag was added automatically by Flutter migrator
|
||||
android.newDsl=false
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// libass ASS subtitle rendering: Kotlin/JNI bindings + Media3 integration
|
||||
// (extractor, parsers, AssHandler, GL atlas overlay). The native libass core
|
||||
// (libass.so + prefab headers) comes from the Maven artifact
|
||||
// io.github.peerless2012:ass; this module compiles its JNI against it.
|
||||
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")
|
||||
if (project.hasProperty("localAssCore")) {
|
||||
// The locally published A/B core only ships device ABIs (x86 would need
|
||||
// nasm on the host); match it so prefab resolution doesn't fail.
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
|
||||
}
|
||||
}
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
// libass.so in the prefab AAR is built against c++_shared (abi.json: stl=c++_shared);
|
||||
// prefab validates consumer STL compatibility.
|
||||
arguments += listOf("-DANDROID_STL=c++_shared")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
prefab = true
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// libass.so is a prefab IMPORTED target (linked, not owned) — the app packages
|
||||
// it from the io.github.peerless2012:ass AAR; don't duplicate it here.
|
||||
excludes.add("**/libass.so")
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
version = "3.22.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// compileOnly: prefab headers + link-time libass.so come from the AAR; runtime
|
||||
// packaging of libass.so is the app's implementation dependency.
|
||||
// -PlocalAssCore swaps in a mavenLocal()-published core for A/B tests (must
|
||||
// match the app module's version so one libass.so is linked and packaged).
|
||||
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
|
||||
compileOnly("io.github.peerless2012:ass:$assCoreVersion@aar")
|
||||
|
||||
implementation("androidx.annotation:annotation:1.9.1")
|
||||
implementation("androidx.annotation:annotation-experimental:1.5.1")
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
implementation("androidx.media3:media3-ui:1.9.2")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# Constructed from JNI via FindClass/NewObject (AssKt.c).
|
||||
-keep class com.edde746.plezy.libass.AssAtlasFrame { *; }
|
||||
# JNI exports bind by name (Java_com_edde746_plezy_libass_*); keep the names stable.
|
||||
-keepclasseswithmembernames class com.edde746.plezy.libass.* {
|
||||
native <methods>;
|
||||
}
|
||||
@@ -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,436 @@
|
||||
// JNI bindings for libass. Exports use standard Java_<package>_<Class>_<method>
|
||||
// naming so no RegisterNatives/JNI_OnLoad registration is needed.
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.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) {
|
||||
return (jlong)ass_new_track((ASS_Library*)ass);
|
||||
}
|
||||
|
||||
// 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 ---
|
||||
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderInit(JNIEnv* env, jclass clazz, jlong ass) {
|
||||
ASS_Renderer* assRenderer = ass_renderer_init((ASS_Library*)ass);
|
||||
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, NULL, 1);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// (image, original-list index) pair so packing can run in height-sorted order
|
||||
// while slots stay keyed by list position (= blend order) for pass 2.
|
||||
typedef struct {
|
||||
ASS_Image* img;
|
||||
int idx;
|
||||
} PackItem;
|
||||
|
||||
static int comparePackItemsByHeightDesc(const void* a, const void* b) {
|
||||
const PackItem* ia = (const PackItem*)a;
|
||||
const PackItem* ib = (const PackItem*)b;
|
||||
return ib->img->h - ia->img->h;
|
||||
}
|
||||
|
||||
// Throttle for truncation warnings (shared across renderers; logging only).
|
||||
static int truncationLogCounter = 0;
|
||||
|
||||
// Renders a frame into the provided atlas + vertex direct ByteBuffers.
|
||||
//
|
||||
// - atlasBuf holds packed ALPHA_8 pixels with row stride atlasMaxW. Only the first
|
||||
// atlasHeight rows are written; the caller uploads that region to a texture
|
||||
// allocated once at atlasMaxW × atlasMaxH.
|
||||
// - vertexBuf holds a per-quad vertex stream (6 vertices × (2 pos + 2 uv + 4 color)
|
||||
// floats = 48 floats = 192 bytes per quad). Must match BYTES_PER_QUAD/VERTEX in
|
||||
// AssSubtitleAtlasPipeline.kt. Ready for a single glDrawArrays(GL_TRIANGLES, 0, N * 6).
|
||||
// - UVs are normalized against atlasMaxW × atlasMaxH (the allocated texture dims),
|
||||
// not the packed region, so the texture never needs reallocation.
|
||||
// - Images are packed in height-sorted rows (minimizes packed height) but vertices
|
||||
// are emitted in original list order — the list order is libass's painter order.
|
||||
//
|
||||
// Never fails on content size: images that don't fit the remaining atlas/vertex
|
||||
// capacity are dropped and counted in AssAtlasFrame.truncated, so a heavy frame
|
||||
// degrades instead of going stale. Returns NULL only for missing buffers/handles.
|
||||
// On changed == 0, returns (0, 0, 0, changed, 0) without touching the buffers —
|
||||
// caller reuses the atlas texture already on the GPU.
|
||||
JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFrameAtlas(
|
||||
JNIEnv* env, jclass clazz, jlong render, jlong track, jlong time, jobject atlasBuf, jint atlasMaxW, jint atlasMaxH,
|
||||
jobject vertexBuf) {
|
||||
if (!render || !track || !atlasBuf || !vertexBuf || atlasMaxW <= 0 || atlasMaxH <= 0) return NULL;
|
||||
|
||||
jclass atlasFrameClass = (*env)->FindClass(env, "com/edde746/plezy/libass/AssAtlasFrame");
|
||||
if (!atlasFrameClass) return NULL;
|
||||
jmethodID ctor = (*env)->GetMethodID(env, atlasFrameClass, "<init>", "(IIIII)V");
|
||||
if (!ctor) return NULL;
|
||||
|
||||
const long long t0 = nowMs();
|
||||
int changed;
|
||||
ASS_Image* image = ass_render_frame((ASS_Renderer*)render, (ASS_Track*)track, time, &changed);
|
||||
const long long tAss = nowMs();
|
||||
|
||||
if (changed == 0 || image == NULL) {
|
||||
if (tAss - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, no output)", (long long)time,
|
||||
tAss - t0, changed);
|
||||
}
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
|
||||
}
|
||||
|
||||
uint8_t* atlasPixels = (uint8_t*)(*env)->GetDirectBufferAddress(env, atlasBuf);
|
||||
jlong atlasCap = (*env)->GetDirectBufferCapacity(env, atlasBuf);
|
||||
float* vertices = (float*)(*env)->GetDirectBufferAddress(env, vertexBuf);
|
||||
jlong vertexCap = (*env)->GetDirectBufferCapacity(env, vertexBuf);
|
||||
if (!atlasPixels || !vertices) return NULL;
|
||||
if ((jlong)atlasMaxW * atlasMaxH > atlasCap) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR, LOG_TAG, "atlas buffer smaller than %dx%d (capacity %lld bytes)", atlasMaxW, atlasMaxH,
|
||||
(long long)atlasCap);
|
||||
return NULL;
|
||||
}
|
||||
// 48 floats per quad × 4 bytes = 192 bytes/quad
|
||||
const int maxQuads = (int)(vertexCap / 192);
|
||||
|
||||
int total = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) total++;
|
||||
}
|
||||
if (total == 0) {
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
|
||||
}
|
||||
|
||||
// Pass 1: assign packing slots in height-sorted order so mixed-size frames pack
|
||||
// tight rows. slotX/slotY are keyed by the image's position in the original
|
||||
// list; -1 marks images dropped for capacity.
|
||||
PackItem* items = (PackItem*)malloc(sizeof(PackItem) * (size_t)total);
|
||||
int* slotX = (int*)malloc(sizeof(int) * (size_t)total);
|
||||
int* slotY = (int*)malloc(sizeof(int) * (size_t)total);
|
||||
if (!items || !slotX || !slotY) {
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
return NULL;
|
||||
}
|
||||
int n = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) {
|
||||
items[n].img = img;
|
||||
items[n].idx = n;
|
||||
n++;
|
||||
}
|
||||
}
|
||||
qsort(items, (size_t)n, sizeof(PackItem), comparePackItemsByHeightDesc);
|
||||
|
||||
int cursorX = 0, cursorY = 0, rowH = 0;
|
||||
int truncated = 0;
|
||||
int packedH = 0;
|
||||
int accepted = 0;
|
||||
long long srcPixels = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
ASS_Image* img = items[i].img;
|
||||
srcPixels += (long long)img->w * img->h;
|
||||
int sx = -1, sy = -1;
|
||||
if (img->w <= atlasMaxW && accepted < maxQuads) {
|
||||
int cx = cursorX, cy = cursorY, rh = rowH;
|
||||
if (cx + img->w > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + img->h <= atlasMaxH) {
|
||||
sx = cx;
|
||||
sy = cy;
|
||||
cursorX = cx + img->w;
|
||||
cursorY = cy;
|
||||
rowH = (img->h > rh) ? img->h : rh;
|
||||
if (cy + img->h > packedH) packedH = cy + img->h;
|
||||
accepted++;
|
||||
}
|
||||
}
|
||||
if (sx < 0) truncated++;
|
||||
slotX[items[i].idx] = sx;
|
||||
slotY[items[i].idx] = sy;
|
||||
}
|
||||
|
||||
if (truncated > 0 && (truncationLogCounter++ & 63) == 0) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d images dropped (atlas %dx%d, %d quads max)", truncated,
|
||||
n, atlasMaxW, atlasMaxH, maxQuads);
|
||||
}
|
||||
if (accepted == 0) {
|
||||
free(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated);
|
||||
}
|
||||
|
||||
memset(atlasPixels, 0, (size_t)atlasMaxW * packedH);
|
||||
|
||||
// Pass 2: walk the original list (= libass's painter/blend order), copying each
|
||||
// accepted image into its assigned slot and emitting its quad.
|
||||
int qi = 0;
|
||||
int k = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
const int px = slotX[k];
|
||||
const int py = slotY[k];
|
||||
k++;
|
||||
if (px < 0) continue;
|
||||
|
||||
for (int y = 0; y < img->h; y++) {
|
||||
uint8_t* dst = atlasPixels + (size_t)(py + y) * atlasMaxW + px;
|
||||
const uint8_t* src = img->bitmap + (size_t)y * img->stride;
|
||||
memcpy(dst, src, (size_t)img->w);
|
||||
}
|
||||
|
||||
const float x0 = (float)img->dst_x;
|
||||
const float y0 = (float)img->dst_y;
|
||||
const float x1 = x0 + (float)img->w;
|
||||
const float y1 = y0 + (float)img->h;
|
||||
const float u0 = (float)px / (float)atlasMaxW;
|
||||
const float v0 = (float)py / (float)atlasMaxH;
|
||||
const float u1 = (float)(px + img->w) / (float)atlasMaxW;
|
||||
const float v1 = (float)(py + img->h) / (float)atlasMaxH;
|
||||
const 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(items);
|
||||
free(slotX);
|
||||
free(slotY);
|
||||
|
||||
// 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 quads=%d",
|
||||
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, packedH, qi);
|
||||
}
|
||||
|
||||
// atlasWidth is the full row stride (GLES2 can't upload with stride ≠ width);
|
||||
// atlasHeight is the packed height — the only rows worth uploading.
|
||||
return (*env)->NewObject(env, atlasFrameClass, ctor, atlasMaxW, packedH, qi, changed, truncated);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
|
||||
project("asskt")
|
||||
|
||||
# libass headers + libass.so come from the io.github.peerless2012:ass AAR via prefab.
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c)
|
||||
find_package(lib_ass REQUIRED CONFIG)
|
||||
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE
|
||||
lib_ass::ass
|
||||
log)
|
||||
@@ -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,21 @@
|
||||
package com.edde746.plezy.libass
|
||||
|
||||
/**
|
||||
* Result of a packed-atlas render. The atlas pixel data is stored in the direct ByteBuffer
|
||||
* that was passed into [AssRender.renderFrameAtlas]; the vertex stream is in the other.
|
||||
*
|
||||
* @param atlasWidth atlas row stride in pixels (= the allocated width; 0 when [changed] == 0)
|
||||
* @param atlasHeight packed atlas height in pixels — the rows worth uploading
|
||||
* @param quadCount number of quads; the vertex buffer holds [quadCount] * 6 vertices
|
||||
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
|
||||
* @param truncated images dropped because they exceeded the atlas/vertex capacity;
|
||||
* the frame is incomplete but never stale (> 0 should be rare —
|
||||
* it means even the GL-max-sized atlas couldn't fit the frame)
|
||||
*/
|
||||
class AssAtlasFrame(
|
||||
val atlasWidth: Int,
|
||||
val atlasHeight: Int,
|
||||
val quadCount: Int,
|
||||
val changed: Int,
|
||||
val truncated: Int
|
||||
)
|
||||
@@ -0,0 +1,164 @@
|
||||
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 {
|
||||
|
||||
@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)
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderFrameAtlas(
|
||||
render: Long,
|
||||
track: Long,
|
||||
time: Long,
|
||||
atlasBuf: ByteBuffer,
|
||||
atlasMaxWidth: Int,
|
||||
atlasMaxHeight: Int,
|
||||
vertexBuf: ByteBuffer
|
||||
): AssAtlasFrame?
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderDeinit(render: Long)
|
||||
}
|
||||
|
||||
private var nativeRender: Long = nativeAssRenderInit(nativeAss)
|
||||
|
||||
@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) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a frame into a packed ALPHA_8 texture atlas plus a single vertex stream
|
||||
* ready for `glDrawArrays(GL_TRIANGLES, 0, quadCount * 6)`.
|
||||
*
|
||||
* UVs are normalized against ([atlasMaxW], [atlasMaxH]) — the allocated texture
|
||||
* dims — so the caller can allocate the texture once and `glTexSubImage2D` only
|
||||
* the packed rows. Images that exceed the capacity are dropped and counted in
|
||||
* [AssAtlasFrame.truncated]; the render never fails on content size.
|
||||
*
|
||||
* @param atlasBuf direct ByteBuffer receiving the packed pixels (≥ atlasMaxW × atlasMaxH)
|
||||
* @param atlasMaxW atlas row stride in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param atlasMaxH atlas height in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
|
||||
* @param vertexBuf direct ByteBuffer receiving the vertex stream (192 bytes per quad)
|
||||
*/
|
||||
/** How long the most recent [renderFrameAtlas] waited to acquire the shared
|
||||
* libass lock (contended by track dialogue/font feeding), in milliseconds. */
|
||||
@Volatile
|
||||
var lastLockWaitMs: Long = 0
|
||||
private set
|
||||
|
||||
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
|
||||
return nativeAssRenderFrameAtlas(nativeRender, t.nativeAssTrack, time, atlasBuf, atlasMaxW, atlasMaxH, vertexBuf)
|
||||
}
|
||||
}
|
||||
|
||||
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,386 @@
|
||||
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
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
if (videoSize.isValid) render.setStorageSize(videoSize.width, videoSize.height)
|
||||
when {
|
||||
surfaceSize.isValid -> render.setFrameSize(surfaceSize.width, surfaceSize.height)
|
||||
// Fallback frame until the overlay surface reports its size.
|
||||
videoSize.isValid -> render.setFrameSize(videoSize.width, videoSize.height)
|
||||
}
|
||||
margins?.let { m -> render.setMargins(m[0], m[1], m[2], 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(width, 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(top, bottom, left, right)
|
||||
}
|
||||
|
||||
/** 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
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.edde746.plezy.libass.media
|
||||
|
||||
data class AssHandlerConfig(
|
||||
val glyphSize: Int = 10000,
|
||||
val cacheSize: Int = 128
|
||||
)
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,991 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import android.opengl.EGL14
|
||||
import android.opengl.EGLContext
|
||||
import android.opengl.EGLDisplay
|
||||
import android.opengl.EGLExt
|
||||
import android.opengl.EGLSurface
|
||||
import android.opengl.GLES20
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.util.GlProgram
|
||||
import androidx.media3.common.util.GlUtil
|
||||
import androidx.media3.common.util.Size
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* Atlas-rendering pipeline behind [AssSubtitleSurfaceView].
|
||||
* Runs libass on its own [HandlerThread] into a packed
|
||||
* ALPHA_8 texture atlas plus a single vertex stream, and a GL thread that uploads
|
||||
* both and issues one `glDrawArrays` per frame. Each swap is pinned to the video's
|
||||
* target release time via [EGLExt.eglPresentationTimeANDROID]: SurfaceFlinger holds
|
||||
* the buffer and composes it on the same vsync as the corresponding video frame.
|
||||
*/
|
||||
@UnstableApi
|
||||
internal object AssAtlasPipelineConfig {
|
||||
/** Flip to `true` for `adb logcat -s AssSurfaceGlThread:D AssLibassThread:D` traces. */
|
||||
internal const val TIMING_LOGS = false
|
||||
|
||||
/** Fallback atlas row width when GL caps are unknown (EGL init failed/slow). */
|
||||
internal const val FALLBACK_ATLAS_W = 2048
|
||||
|
||||
/** Fallback atlas height; 2048 × 4096 = 8 MB matches the long-proven default. */
|
||||
internal const val FALLBACK_ATLAS_H = 4096
|
||||
|
||||
/**
|
||||
* Pixel budget per atlas slot once GL caps are known: 4096×4096 or 2048×8192
|
||||
* (16 MB ALPHA_8). Sized so heavy typesetting (full-screen gradients/blurs)
|
||||
* fits where the old fixed 2048×4096 overflowed and dropped frames.
|
||||
*/
|
||||
internal const val ATLAS_PIXEL_BUDGET = 16 * 1024 * 1024
|
||||
|
||||
/** Preallocated vertex-stream capacity (192 bytes × 16384 = 3 MB per buffer). */
|
||||
internal const val MAX_QUADS = 16384
|
||||
|
||||
/** Must match the byte layout produced by `nativeAssRenderFrameAtlas` in AssKt.c. */
|
||||
internal const val BYTES_PER_VERTEX = 32
|
||||
internal const val BYTES_PER_QUAD = BYTES_PER_VERTEX * 6
|
||||
|
||||
/**
|
||||
* Kill switch for speculative render-ahead (see [SpecRenderEngine]) and the
|
||||
* event prefetch. With it off (or on low-RAM devices, which stay at 2 slots)
|
||||
* every request renders on-demand inside the video frame's release deadline —
|
||||
* the pre-speculation behavior.
|
||||
*
|
||||
* Only pays off when typical changed renders fit the speculation coverage
|
||||
* window (~frame interval + release budget): with the un-optimized (-O0)
|
||||
* native core's 90ms+ renders it could only add overhead; with the -O3/NEON
|
||||
* core's ~35-50ms renders it converts near-misses into on-time latches.
|
||||
*/
|
||||
internal const val SPECULATION_ENABLED = true
|
||||
}
|
||||
|
||||
/** Payload handed from the libass worker to the GL thread. */
|
||||
internal class AtlasPayload(
|
||||
val slotIndex: Int,
|
||||
val atlasBuf: ByteBuffer,
|
||||
val vertexBuf: ByteBuffer,
|
||||
var frame: AssAtlasFrame,
|
||||
var presentationTimeUs: Long,
|
||||
var releaseTimeNs: Long,
|
||||
/** Bumped on every content-changing render; lets the GL thread tell "same slot,
|
||||
* new content" apart from "same slot, same content" when deciding to re-upload. */
|
||||
var contentSeq: Long = 0L
|
||||
)
|
||||
|
||||
/** Payload slots plus the atlas dims their buffers were sized for. */
|
||||
internal class AtlasSlots(
|
||||
val payloads: Array<AtlasPayload>,
|
||||
val atlasW: Int,
|
||||
val atlasH: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* Owns both the libass worker and the GL thread. The two talk via a single-slot
|
||||
* atomic — a newer payload always replaces a pending one so the GL thread never
|
||||
* falls behind.
|
||||
*/
|
||||
@UnstableApi
|
||||
internal class AssAtlasPipeline(
|
||||
surface: Surface,
|
||||
width: Int,
|
||||
height: Int,
|
||||
assHandler: AssHandler,
|
||||
lowRamDevice: Boolean = false
|
||||
) {
|
||||
private val surfaceWidth = width
|
||||
private val surfaceHeight = height
|
||||
|
||||
// 3 slots give the render-ahead engine a writable target while one slot is
|
||||
// posted and another is in GL's hands; low-RAM devices stay at 2 slots with
|
||||
// speculation off (the legacy on-demand behavior, ~19 MB less in buffers).
|
||||
private val slotCount = if (lowRamDevice) 2 else 3
|
||||
private val speculationEnabled = AssAtlasPipelineConfig.SPECULATION_ENABLED && slotCount >= 3
|
||||
|
||||
// Atlas dims, resolved exactly once (first-wins): normally by the GL thread from
|
||||
// GL_MAX_TEXTURE_SIZE right after EGL init; by the libass thread's 1 s fallback
|
||||
// if GL never comes up. Both threads then agree on the dims, which matters
|
||||
// because the C side bakes UV denominators = these dims into the vertex stream
|
||||
// and the GL side allocates the texture once at these dims.
|
||||
private val dimsResolved = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
private val dimsLatch = java.util.concurrent.CountDownLatch(1)
|
||||
|
||||
@Volatile private var atlasW = 0
|
||||
|
||||
@Volatile private var atlasH = 0
|
||||
|
||||
private fun resolveAtlasDims(maxTextureSize: Int): Pair<Int, Int> {
|
||||
if (dimsResolved.compareAndSet(false, true)) {
|
||||
if (maxTextureSize < 4096) {
|
||||
// Query failed (or an ancient GPU): keep the long-proven fixed size.
|
||||
atlasW = AssAtlasPipelineConfig.FALLBACK_ATLAS_W
|
||||
atlasH = AssAtlasPipelineConfig.FALLBACK_ATLAS_H
|
||||
} else {
|
||||
val w = if (surfaceWidth > 2048) 4096 else 2048
|
||||
atlasW = w
|
||||
atlasH = minOf(maxTextureSize, AssAtlasPipelineConfig.ATLAS_PIXEL_BUDGET / w)
|
||||
}
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d("AssAtlasPipeline", "atlas dims ${atlasW}x$atlasH (glMaxTexture=$maxTextureSize)")
|
||||
}
|
||||
dimsLatch.countDown()
|
||||
}
|
||||
return atlasW to atlasH
|
||||
}
|
||||
|
||||
// Lazily allocated on the libass thread once atlas dims are known; ~19 MB of
|
||||
// direct buffers per slot at the full budget, so don't pay it before the
|
||||
// first actual render. Confined to the libass thread after creation.
|
||||
private var slots: AtlasSlots? = null
|
||||
|
||||
private fun acquireSlots(): AtlasSlots {
|
||||
slots?.let { return it }
|
||||
if (!dimsLatch.await(1, java.util.concurrent.TimeUnit.SECONDS)) {
|
||||
resolveAtlasDims(0) // first-wins: no-op if the GL thread resolved meanwhile
|
||||
}
|
||||
val w = atlasW
|
||||
val h = atlasH
|
||||
val payloads = Array(slotCount) { index ->
|
||||
AtlasPayload(
|
||||
slotIndex = index,
|
||||
atlasBuf = ByteBuffer.allocateDirect(w * h).order(ByteOrder.nativeOrder()),
|
||||
vertexBuf = ByteBuffer.allocateDirect(
|
||||
AssAtlasPipelineConfig.MAX_QUADS * AssAtlasPipelineConfig.BYTES_PER_QUAD
|
||||
).order(ByteOrder.nativeOrder()),
|
||||
frame = AssAtlasFrame(0, 0, 0, 0, 0),
|
||||
presentationTimeUs = 0L,
|
||||
releaseTimeNs = C.TIME_UNSET
|
||||
)
|
||||
}
|
||||
return AtlasSlots(payloads, w, h).also { slots = it }
|
||||
}
|
||||
|
||||
/** Slot index the GL thread most recently took for drawing; the libass side
|
||||
* never writes it. Written only inside [takePending] on the GL thread. */
|
||||
@Volatile private var glLastTakenSlot = -1
|
||||
|
||||
private val pendingPayload = AtomicReference<AtlasPayload?>(null)
|
||||
private val glThread = AtlasGlThread(
|
||||
surface,
|
||||
width,
|
||||
height,
|
||||
assHandler,
|
||||
takePending = {
|
||||
pendingPayload.getAndSet(null)?.also { glLastTakenSlot = it.slotIndex }
|
||||
},
|
||||
resolveAtlasDims = ::resolveAtlasDims
|
||||
)
|
||||
private val libassThread = AtlasLibassThread(
|
||||
assHandler,
|
||||
acquireSlots = ::acquireSlots,
|
||||
speculationEnabled = speculationEnabled,
|
||||
glTakenSlot = { glLastTakenSlot },
|
||||
onFrameReady = { payload ->
|
||||
pendingPayload.set(payload)
|
||||
glThread.triggerDraw()
|
||||
}
|
||||
)
|
||||
|
||||
fun start() {
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
"AssAtlasPipeline",
|
||||
"start surface=${surfaceWidth}x$surfaceHeight slots=$slotCount speculation=$speculationEnabled"
|
||||
)
|
||||
}
|
||||
glThread.start()
|
||||
libassThread.start()
|
||||
}
|
||||
|
||||
fun requestRender(presentationTimeUs: Long, releaseTimeNs: Long) {
|
||||
libassThread.enqueue(presentationTimeUs, releaseTimeNs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-renders the last requested position — for renderer state changes (margins,
|
||||
* use-margins) that must become visible while playback is paused. Safe during
|
||||
* playback: the next video frame's [requestRender] supersedes it (latest-wins).
|
||||
*/
|
||||
fun invalidate() {
|
||||
libassThread.invalidate()
|
||||
}
|
||||
|
||||
fun onSurfaceSizeChanged(width: Int, height: Int) {
|
||||
glThread.onSurfaceSizeChanged(width, height)
|
||||
}
|
||||
|
||||
/** Vsync-pinned swaps performed (excludes untimed invalidate repaints). */
|
||||
val swapCount: Long get() = glThread.swapCount
|
||||
|
||||
/** Pinned swaps that finished past the swap-time budget (possible missed vsync). */
|
||||
val lateSwapCount: Long get() = glThread.lateSwapCount
|
||||
|
||||
/** Worst observed swap lateness past the target release time, in milliseconds. */
|
||||
val maxLateMs: Long get() = glThread.maxLateMs
|
||||
|
||||
/** Total libass renders performed (one per serviced request). */
|
||||
val renderCount: Long get() = libassThread.renderCount
|
||||
|
||||
/** Renders where libass reported changed content (atlas/vertex rewritten). */
|
||||
val changedRenderCount: Long get() = libassThread.changedRenderCount
|
||||
|
||||
/** Renders that overflowed the atlas/vertex capacity (frame content incomplete). */
|
||||
val overflowCount: Long get() = libassThread.overflowCount
|
||||
|
||||
/** Duration of the most recent libass render, in milliseconds. */
|
||||
val lastLibassMs: Long get() = libassThread.lastLibassMs
|
||||
|
||||
/** Worst observed libass render duration, in milliseconds. */
|
||||
val maxLibassMs: Long get() = libassThread.maxLibassMs
|
||||
|
||||
/** Changed-render duration histogram: [≤10ms, ≤25ms, ≤42ms, ≤84ms, >84ms]. */
|
||||
val libassMsHistogram: List<Long> get() = libassThread.histogramSnapshot()
|
||||
|
||||
/** Requests served from a pre-rendered (speculative) frame — GL-only hot path. */
|
||||
val specHits: Long get() = libassThread.specHits
|
||||
|
||||
/** Requests where a speculative frame existed but didn't match (seek, state change). */
|
||||
val specMisses: Long get() = libassThread.specMisses
|
||||
|
||||
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
|
||||
val specSkips: Long get() = libassThread.specSkips
|
||||
|
||||
/** Cache-warming prefetch renders of upcoming events. */
|
||||
val prefetchCount: Long get() = libassThread.prefetchCount
|
||||
|
||||
/** Worst (minimum) lead of a changed-content pinned swap vs its target release
|
||||
* time, in ms; negative = the new content was queued after the video frame's
|
||||
* vsync. Long.MAX_VALUE until a changed pinned swap happened. */
|
||||
val minLeadChangedMs: Long get() = glThread.minLeadChangedMs
|
||||
|
||||
fun releaseAndWait() {
|
||||
libassThread.releaseAndWait()
|
||||
glThread.releaseAndWait()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a [Handler] synchronously: posts [releaseWhat] with an [Ack], waits up to 1 s
|
||||
* for the handler to invoke [onReleased] (on its own looper) and signal the latch.
|
||||
*/
|
||||
private fun postShutdownAndWait(
|
||||
handler: Handler,
|
||||
releaseWhat: Int,
|
||||
onReleased: () -> Unit
|
||||
) {
|
||||
val latch = Object()
|
||||
synchronized(latch) {
|
||||
handler.obtainMessage(releaseWhat, Ack(latch, onReleased)).sendToTarget()
|
||||
try {
|
||||
latch.wait(1_000)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Transport for [postShutdownAndWait] — the handler callback calls [release] then notifies. */
|
||||
private class Ack(val latch: Any, val release: () -> Unit)
|
||||
|
||||
/**
|
||||
* Runs libass off the GL thread into a packed atlas + vertex stream. Latest-wins:
|
||||
* older pending renders are dropped when a newer one arrives. Slot choice, the
|
||||
* changed-flag bookkeeping and speculative render-ahead live in [SpecRenderEngine];
|
||||
* this thread owns the buffers, the timing/stat accounting and the GL handoff.
|
||||
*/
|
||||
@UnstableApi
|
||||
private class AtlasLibassThread(
|
||||
private val assHandler: AssHandler,
|
||||
private val acquireSlots: () -> AtlasSlots,
|
||||
private val speculationEnabled: Boolean,
|
||||
private val glTakenSlot: () -> Int,
|
||||
private val onFrameReady: (AtlasPayload) -> Unit
|
||||
) : HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY) {
|
||||
|
||||
/** Immutable (pts, release) request — handed off through a single atomic so a
|
||||
* concurrent enqueue can neither be lost by drain's consume nor torn in half.
|
||||
* [enqueueNs] timestamps the handoff so drain can report how long the request
|
||||
* sat behind an in-flight render (the queue-wait component of subtitle lag). */
|
||||
private class PendingFrame(val ptsUs: Long, val releaseNs: Long, val enqueueNs: Long = System.nanoTime())
|
||||
|
||||
private lateinit var handler: Handler
|
||||
|
||||
private val pending = AtomicReference<PendingFrame?>(null)
|
||||
|
||||
@Volatile private var lastRequestedPtsUs = UNSET
|
||||
private var contentSeqCounter = 0L
|
||||
|
||||
// Thread-confined; created on first render so non-ASS playback never allocates.
|
||||
private var engine: SpecRenderEngine? = null
|
||||
|
||||
val specHits: Long get() = engine?.specHits ?: 0L
|
||||
val specMisses: Long get() = engine?.specMisses ?: 0L
|
||||
val specSkips: Long get() = engine?.specSkips ?: 0L
|
||||
val prefetchCount: Long get() = engine?.prefetchCount ?: 0L
|
||||
|
||||
// Telemetry; single-writer (this thread), read from the stats path.
|
||||
@Volatile var renderCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var changedRenderCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var overflowCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var lastLibassMs = 0L
|
||||
private set
|
||||
|
||||
@Volatile var maxLibassMs = 0L
|
||||
private set
|
||||
|
||||
/** Changed-render durations bucketed at ≤10 / ≤25 / ≤42 / ≤84 / >84 ms. */
|
||||
private val histogram = java.util.concurrent.atomic.AtomicLongArray(5)
|
||||
|
||||
fun histogramSnapshot(): List<Long> = List(histogram.length()) { histogram.get(it) }
|
||||
|
||||
private fun recordChangedRenderMs(ms: Long) {
|
||||
val bucket = when {
|
||||
ms <= 10 -> 0
|
||||
ms <= 25 -> 1
|
||||
ms <= 42 -> 2
|
||||
ms <= 84 -> 3
|
||||
else -> 4
|
||||
}
|
||||
histogram.incrementAndGet(bucket)
|
||||
}
|
||||
|
||||
override fun start() {
|
||||
super.start()
|
||||
handler = Handler(looper) { msg ->
|
||||
when (msg.what) {
|
||||
MSG_RENDER -> drainAndRender()
|
||||
MSG_RELEASE -> {
|
||||
val ack = msg.obj as Ack
|
||||
ack.release()
|
||||
quit()
|
||||
synchronized(ack.latch) { (ack.latch as Object).notifyAll() }
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fun enqueue(presentationTimeUs: Long, releaseTimeNs: Long) {
|
||||
if (!::handler.isInitialized) return
|
||||
val dropped = pending.getAndSet(PendingFrame(presentationTimeUs, releaseTimeNs))
|
||||
if (dropped != null && AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
// A request was coalesced away — the renderer is behind by at least one
|
||||
// frame. agedMs = how long the dropped request had been waiting.
|
||||
Log.d(
|
||||
TAG,
|
||||
"drop pts=${dropped.ptsUs / 1000}ms agedMs=${(System.nanoTime() - dropped.enqueueNs) / 1_000_000} " +
|
||||
"replacedBy=${presentationTimeUs / 1000}ms"
|
||||
)
|
||||
}
|
||||
handler.removeMessages(MSG_RENDER)
|
||||
handler.sendEmptyMessage(MSG_RENDER)
|
||||
}
|
||||
|
||||
/** Re-enqueues the last requested PTS (renderer state changed, possibly while paused). */
|
||||
fun invalidate() {
|
||||
val pts = lastRequestedPtsUs
|
||||
if (pts == UNSET) return
|
||||
// TIME_UNSET release time => the GL thread swaps immediately instead of
|
||||
// vsync-pinning to a video frame that may never come while paused.
|
||||
enqueue(pts, C.TIME_UNSET)
|
||||
}
|
||||
|
||||
private fun ensureEngine(slots: AtlasSlots): SpecRenderEngine {
|
||||
engine?.let { return it }
|
||||
return SpecRenderEngine(
|
||||
slotCount = slots.payloads.size,
|
||||
speculationEnabled = speculationEnabled,
|
||||
renderAt = { timeMs, slot -> timedRender(timeMs, slots, slot) },
|
||||
// Renderer identity in the high bits + its state generation in the low bits:
|
||||
// a recreated renderer (media item transition) can never alias a stale
|
||||
// speculation, even if the new generation counter happens to match.
|
||||
stateGeneration = {
|
||||
assHandler.render?.let {
|
||||
(System.identityHashCode(it).toLong() shl 32) or (it.stateGeneration.toLong() and 0xffffffffL)
|
||||
} ?: -1L
|
||||
},
|
||||
glTakenSlot = glTakenSlot,
|
||||
debugLog = if (AssAtlasPipelineConfig.TIMING_LOGS) ({ msg -> Log.d(TAG, msg) }) else null
|
||||
).also { engine = it }
|
||||
}
|
||||
|
||||
/** Consecutive renders that reported no content change — a static screen.
|
||||
* Reset by any changed render (dialogue flips, karaoke, animated signs). */
|
||||
private var unchangedStreak = 0
|
||||
|
||||
/** Renders into [slot]'s buffers, owning the per-render timing/stat accounting
|
||||
* for both on-demand and speculative renders. */
|
||||
private fun timedRender(timeMs: Long, slots: AtlasSlots, slot: Int): AssAtlasFrame? {
|
||||
val render = assHandler.render ?: return null
|
||||
val payload = slots.payloads[slot]
|
||||
val t0 = System.nanoTime()
|
||||
val frame = render.renderFrameAtlas(timeMs, payload.atlasBuf, slots.atlasW, slots.atlasH, payload.vertexBuf)
|
||||
?: return null
|
||||
val libassMs = (System.nanoTime() - t0) / 1_000_000
|
||||
renderCount++
|
||||
lastLibassMs = libassMs
|
||||
if (libassMs > maxLibassMs) maxLibassMs = libassMs
|
||||
if (frame.truncated > 0) overflowCount++
|
||||
if (frame.changed != 0) {
|
||||
changedRenderCount++
|
||||
recordChangedRenderMs(libassMs)
|
||||
unchangedStreak = 0
|
||||
} else {
|
||||
unchangedStreak++
|
||||
}
|
||||
return frame
|
||||
}
|
||||
|
||||
private fun drainAndRender() {
|
||||
val request = pending.getAndSet(null) ?: return
|
||||
val pts = request.ptsUs
|
||||
val releaseNs = request.releaseNs
|
||||
lastRequestedPtsUs = pts
|
||||
val tDrain = System.nanoTime()
|
||||
// How long the request sat in the handoff (behind an in-flight on-demand or
|
||||
// speculative render) — the queue-wait component of any subtitle lag.
|
||||
val waitMs = (tDrain - request.enqueueNs) / 1_000_000
|
||||
// Before any ASS render exists (SRT/VTT or no subs) do nothing — this also
|
||||
// keeps the slot buffers unallocated for non-ASS playback.
|
||||
if (assHandler.render == null) return
|
||||
val slots = acquireSlots()
|
||||
val engine = ensureEngine(slots)
|
||||
val pinned = releaseNs != C.TIME_UNSET
|
||||
// Budget left until the video frame's vsync when we START servicing.
|
||||
val budgetMs = if (pinned) (releaseNs - tDrain) / 1_000_000 else -1L
|
||||
|
||||
when (val outcome = engine.service(pts, pinned)) {
|
||||
is SpecRenderEngine.Outcome.Post -> {
|
||||
val payload = slots.payloads[outcome.slot]
|
||||
if (outcome.newContent) {
|
||||
payload.frame = outcome.frame
|
||||
payload.contentSeq = ++contentSeqCounter
|
||||
}
|
||||
payload.presentationTimeUs = pts
|
||||
payload.releaseTimeNs = releaseNs
|
||||
onFrameReady(payload)
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"render pts=${pts / 1000}ms seq=${payload.contentSeq} waitMs=$waitMs budgetMs=$budgetMs " +
|
||||
"libassMs=$lastLibassMs lockWaitMs=${assHandler.render?.lastLockWaitMs} " +
|
||||
"specHit=${outcome.specHit} changed=${payload.frame.changed} quads=${payload.frame.quadCount} " +
|
||||
"atlas=${payload.frame.atlasWidth}x${payload.frame.atlasHeight} truncated=${payload.frame.truncated}"
|
||||
)
|
||||
}
|
||||
}
|
||||
SpecRenderEngine.Outcome.Skip -> {
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(TAG, "skip pts=${pts / 1000}ms waitMs=$waitMs budgetMs=$budgetMs (no content)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-render the predicted next frame in the dead time between requests so the
|
||||
// next service is (usually) a GL-only hit. Never delays a waiting request.
|
||||
engine.speculateAfter(pts, pinned, hasPending = pending.get() != null)?.let { write ->
|
||||
val payload = slots.payloads[write.slot]
|
||||
payload.frame = write.frame
|
||||
payload.contentSeq = ++contentSeqCounter
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"spec after=${pts / 1000}ms seq=${payload.contentSeq} libassMs=$lastLibassMs " +
|
||||
"lockWaitMs=${assHandler.render?.lastLockWaitMs} slot=${write.slot} quads=${write.frame.quadCount}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
maybePrefetch(engine, slots, pts, pinned)
|
||||
}
|
||||
|
||||
/** Start time of the last event boundary we cache-warmed (libass/track ms). */
|
||||
private var lastPrefetchedStartMs = Long.MIN_VALUE
|
||||
|
||||
/** Wall time of the last prefetch render, for the cooldown. */
|
||||
private var lastPrefetchNs = Long.MIN_VALUE / 2
|
||||
|
||||
/**
|
||||
* Cache-warms the next upcoming subtitle event so heavy typesetting pays its
|
||||
* cache-cold rasterization (seconds on weak devices) before the sign appears
|
||||
* instead of at appearance.
|
||||
*
|
||||
* The render blocks this thread, and during playback a new request is never
|
||||
* more than one frame interval away — so a prefetch is only allowed when its
|
||||
* delay cannot be SEEN, not merely when the queue is momentarily empty
|
||||
* (the v1 mistake, which thrashed on densely-authored per-frame events and
|
||||
* stalled visible dialogue):
|
||||
* - the screen must be static ([unchangedStreak]): requests delayed behind
|
||||
* the prefetch re-render identical content, so their lateness is invisible;
|
||||
* - the warmed event must be the NEXT on-screen change (no other event start
|
||||
* or end before it) — this also kills dense per-frame event sections,
|
||||
* where the next change is always ≤ one frame away;
|
||||
* - a cooldown bounds the worst-case overhead to one render per window.
|
||||
*/
|
||||
private fun maybePrefetch(engine: SpecRenderEngine, slots: AtlasSlots, ptsUs: Long, pinned: Boolean) {
|
||||
if (!speculationEnabled) return
|
||||
if (!pinned) return
|
||||
if (pending.get() != null) return
|
||||
if (unchangedStreak < PREFETCH_STATIC_STREAK) return
|
||||
val now = System.nanoTime()
|
||||
if (now - lastPrefetchNs < PREFETCH_COOLDOWN_NS) return
|
||||
val track = assHandler.track ?: return
|
||||
val nowMs = ptsUs / 1000
|
||||
// Events closer than MIN_AHEAD are the regular per-frame path's business;
|
||||
// beyond HORIZON the warmed bitmaps may be evicted before they're needed.
|
||||
val targetMs = track.nextEventStartMs(nowMs + PREFETCH_MIN_AHEAD_MS)
|
||||
if (targetMs < 0 || targetMs == lastPrefetchedStartMs) return
|
||||
if (targetMs > nowMs + PREFETCH_HORIZON_MS) return
|
||||
// Invisibility gate, time-budgeted: a prefetch is invisible as long as it
|
||||
// finishes before anything on screen is due to change (the screen is static
|
||||
// per the streak gate, so requests delayed behind it re-render identical
|
||||
// content). Estimate the cost from the worst render seen this session —
|
||||
// an overestimate only skips warming; an underestimate delays one boundary
|
||||
// by the shortfall. nextEventChangeMs also sees ends, so a dialogue line
|
||||
// due to disappear inside the budget skips the prefetch.
|
||||
val nextChangeMs = track.nextEventChangeMs(nowMs)
|
||||
if (nextChangeMs in 0 until targetMs) {
|
||||
val runwayMs = nextChangeMs - nowMs
|
||||
val costEstimateMs = (maxLibassMs * 5 / 4).coerceIn(PREFETCH_COST_FLOOR_MS, PREFETCH_COST_CEIL_MS)
|
||||
if (runwayMs < costEstimateMs + PREFETCH_SAFETY_MS) return
|
||||
}
|
||||
lastPrefetchedStartMs = targetMs
|
||||
lastPrefetchNs = now
|
||||
engine.prefetch(targetMs * 1000)?.let { write ->
|
||||
val payload = slots.payloads[write.slot]
|
||||
payload.frame = write.frame
|
||||
payload.contentSeq = ++contentSeqCounter
|
||||
}
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"prefetch evt=${targetMs}ms aheadMs=${targetMs - nowMs} " +
|
||||
"tookMs=${(System.nanoTime() - now) / 1_000_000} libassMs=$lastLibassMs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun releaseAndWait() {
|
||||
if (!::handler.isInitialized) {
|
||||
quit()
|
||||
return
|
||||
}
|
||||
postShutdownAndWait(handler, MSG_RELEASE) { /* nothing thread-local to tear down */ }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AssLibassThread"
|
||||
private const val MSG_RENDER = 1
|
||||
private const val MSG_RELEASE = 2
|
||||
private const val UNSET = Long.MIN_VALUE
|
||||
|
||||
/** Don't prefetch events the per-frame speculation will reach imminently. */
|
||||
private const val PREFETCH_MIN_AHEAD_MS = 1_000L
|
||||
|
||||
/** Don't warm caches so early that the bitmaps could be evicted again. */
|
||||
private const val PREFETCH_HORIZON_MS = 15_000L
|
||||
|
||||
/** Static-screen requirement before a prefetch may block this thread. */
|
||||
private const val PREFETCH_STATIC_STREAK = 3
|
||||
|
||||
/** Minimum spacing between prefetch renders. */
|
||||
private const val PREFETCH_COOLDOWN_NS = 2_000_000_000L
|
||||
|
||||
/** Cost-estimate clamp for the time-budgeted invisibility gate: never
|
||||
* assume a prefetch cheaper than the floor (estimator may not have seen a
|
||||
* heavy frame yet) nor pointlessly demand more runway than the ceiling. */
|
||||
private const val PREFETCH_COST_FLOOR_MS = 250L
|
||||
private const val PREFETCH_COST_CEIL_MS = 1_500L
|
||||
|
||||
/** Slack added to the cost estimate when checking the static runway. */
|
||||
private const val PREFETCH_SAFETY_MS = 150L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the EGL surface, uploads the atlas + vertex stream and issues a single
|
||||
* `glDrawArrays` per frame. Swaps immediately with the swap pinned to the video's
|
||||
* target release time via [EGLExt.eglPresentationTimeANDROID]; SurfaceFlinger
|
||||
* holds the buffer until then, so the thread is never blocked waiting for a vsync.
|
||||
*/
|
||||
@UnstableApi
|
||||
private class AtlasGlThread(
|
||||
private val surface: Surface,
|
||||
@Volatile private var width: Int,
|
||||
@Volatile private var height: Int,
|
||||
private val assHandler: AssHandler,
|
||||
private val takePending: () -> AtlasPayload?,
|
||||
private val resolveAtlasDims: (maxTextureSize: Int) -> Pair<Int, Int>
|
||||
) : HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY) {
|
||||
|
||||
private lateinit var handler: Handler
|
||||
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
|
||||
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
|
||||
private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE
|
||||
|
||||
private val renderer = AtlasRenderer(assHandler)
|
||||
private var lastUploadedPayload: AtlasPayload? = null
|
||||
private var lastUploadedSeq = -1L
|
||||
private var lastSwappedSeq = -1L
|
||||
|
||||
// Lateness telemetry; single-writer (this thread), read from the stats path.
|
||||
@Volatile var swapCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var lateSwapCount = 0L
|
||||
private set
|
||||
|
||||
@Volatile var maxLateMs = 0L
|
||||
private set
|
||||
|
||||
/** Minimum lead (release target − swap completion) over changed-content pinned
|
||||
* swaps; negative = content queued after the video frame's vsync. */
|
||||
@Volatile var minLeadChangedMs = Long.MAX_VALUE
|
||||
private set
|
||||
|
||||
override fun start() {
|
||||
super.start()
|
||||
handler = Handler(looper) { msg ->
|
||||
try {
|
||||
when (msg.what) {
|
||||
MSG_INIT -> initEgl()
|
||||
MSG_DRAW -> drawAndSwap()
|
||||
MSG_SIZE_CHANGED -> sizeChanged(width, height)
|
||||
MSG_RELEASE -> {
|
||||
val ack = msg.obj as Ack
|
||||
ack.release()
|
||||
quit()
|
||||
synchronized(ack.latch) { (ack.latch as Object).notifyAll() }
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "GL thread error", e)
|
||||
releaseEgl()
|
||||
}
|
||||
true
|
||||
}
|
||||
handler.sendEmptyMessage(MSG_INIT)
|
||||
}
|
||||
|
||||
fun onSurfaceSizeChanged(width: Int, height: Int) {
|
||||
this.width = width
|
||||
this.height = height
|
||||
handler.sendEmptyMessage(MSG_SIZE_CHANGED)
|
||||
}
|
||||
|
||||
fun triggerDraw() {
|
||||
if (!::handler.isInitialized) return
|
||||
handler.removeMessages(MSG_DRAW)
|
||||
handler.sendEmptyMessage(MSG_DRAW)
|
||||
}
|
||||
|
||||
fun releaseAndWait() {
|
||||
if (!::handler.isInitialized) {
|
||||
quit()
|
||||
return
|
||||
}
|
||||
postShutdownAndWait(handler, MSG_RELEASE) { releaseEgl() }
|
||||
}
|
||||
|
||||
private fun initEgl() {
|
||||
try {
|
||||
eglDisplay = GlUtil.getDefaultEglDisplay()
|
||||
eglContext = GlUtil.createEglContext(eglDisplay)
|
||||
eglSurface = GlUtil.createEglSurface(eglDisplay, surface, C.COLOR_TRANSFER_SDR, false)
|
||||
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
|
||||
renderer.onSurfaceCreated()
|
||||
// Resolve atlas dims from real GL caps (first-wins against the libass
|
||||
// thread's fallback) and allocate the texture once at those dims — uploads
|
||||
// are glTexSubImage2D of the packed rows from then on.
|
||||
val maxTexture = IntArray(1)
|
||||
GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxTexture, 0)
|
||||
val (atlasW, atlasH) = resolveAtlasDims(maxTexture[0])
|
||||
renderer.allocateAtlasTexture(atlasW, atlasH)
|
||||
sizeChanged(width, height)
|
||||
} catch (e: GlUtil.GlException) {
|
||||
Log.e(TAG, "Failed to initialize EGL", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sizeChanged(width: Int, height: Int) {
|
||||
renderer.onSurfaceChanged(width, height)
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
|
||||
GlUtil.clearFocusedBuffers()
|
||||
EGL14.eglSwapBuffers(eglDisplay, eglSurface)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawAndSwap() {
|
||||
if (eglDisplay == EGL14.EGL_NO_DISPLAY) return
|
||||
val payload = takePending() ?: return
|
||||
|
||||
// Render immediately (GL commands queue on the GPU). Re-upload only when the
|
||||
// slot's content actually changed — identity alone is not enough because the
|
||||
// libass side rewrites slot buffers in place (contentSeq tracks the rewrites).
|
||||
val t0 = System.nanoTime()
|
||||
val reuse = payload === lastUploadedPayload && payload.contentSeq == lastUploadedSeq
|
||||
renderer.onDrawFrame(payload, reuseUploads = reuse)
|
||||
lastUploadedPayload = payload
|
||||
lastUploadedSeq = payload.contentSeq
|
||||
val t1 = System.nanoTime()
|
||||
|
||||
// Swap immediately with the presentation time set: SurfaceFlinger holds the
|
||||
// queued buffer until the video frame's target release time, so the subtitle
|
||||
// can never appear early, and the GL thread is free again within a couple of
|
||||
// milliseconds. Sleeping here until near the target vsync (as a removed
|
||||
// TextureView path once required) made this thread blind for almost a whole
|
||||
// frame interval — the single-slot latest-wins handoff would then drop an
|
||||
// intermediate subtitle state (e.g. the transition to blank), showing the
|
||||
// previous state one frame too long.
|
||||
if (payload.releaseTimeNs != C.TIME_UNSET) {
|
||||
EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, payload.releaseTimeNs)
|
||||
}
|
||||
EGL14.eglSwapBuffers(eglDisplay, eglSurface)
|
||||
val t2 = System.nanoTime()
|
||||
if (payload.releaseTimeNs != C.TIME_UNSET) {
|
||||
swapCount++
|
||||
val lateNs = t2 - payload.releaseTimeNs
|
||||
if (lateNs > LATE_THRESHOLD_NS) {
|
||||
lateSwapCount++
|
||||
val lateMs = lateNs / 1_000_000
|
||||
if (lateMs > maxLateMs) maxLateMs = lateMs
|
||||
}
|
||||
// Lead of changed-content swaps is the frame-perfection signal: ≥ 0 means
|
||||
// the new subtitle content reached the queue before the video frame's vsync.
|
||||
if (payload.contentSeq != lastSwappedSeq) {
|
||||
val leadMs = -lateNs / 1_000_000
|
||||
if (leadMs < minLeadChangedMs) minLeadChangedMs = leadMs
|
||||
}
|
||||
}
|
||||
lastSwappedSeq = payload.contentSeq
|
||||
if (AssAtlasPipelineConfig.TIMING_LOGS) {
|
||||
val pinned = payload.releaseTimeNs != C.TIME_UNSET
|
||||
// headroomMs: slack before the target vsync when GL STARTED; leadMs: slack
|
||||
// when the buffer was actually queued (negative = queued after the vsync).
|
||||
val headroomMs = if (pinned) (payload.releaseTimeNs - t0) / 1_000_000 else -1L
|
||||
val leadMs = if (pinned) (payload.releaseTimeNs - t2) / 1_000_000 else -1L
|
||||
Log.d(
|
||||
TAG,
|
||||
"swap pts=${payload.presentationTimeUs / 1000}ms seq=${payload.contentSeq} " +
|
||||
"quads=${payload.frame.quadCount} reused=$reuse drawMs=${(t1 - t0) / 1_000_000} " +
|
||||
"swapMs=${(t2 - t1) / 1_000_000} headroomMs=$headroomMs leadMs=$leadMs pinned=$pinned"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseEgl() {
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
|
||||
try {
|
||||
renderer.onSurfaceDestroyed()
|
||||
GlUtil.destroyEglSurface(eglDisplay, eglSurface)
|
||||
GlUtil.destroyEglContext(eglDisplay, eglContext)
|
||||
} catch (e: GlUtil.GlException) {
|
||||
Log.e(TAG, "Failed to release EGL", e)
|
||||
} finally {
|
||||
eglDisplay = EGL14.EGL_NO_DISPLAY
|
||||
eglContext = EGL14.EGL_NO_CONTEXT
|
||||
eglSurface = EGL14.EGL_NO_SURFACE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AssSurfaceGlThread"
|
||||
private const val MSG_INIT = 1
|
||||
private const val MSG_DRAW = 2
|
||||
private const val MSG_SIZE_CHANGED = 3
|
||||
private const val MSG_RELEASE = 4
|
||||
|
||||
/**
|
||||
* Swaps finishing this far past the target release time arrived after the
|
||||
* buffer should already have been queued and may miss the frame's vsync —
|
||||
* actual slack depends on the display's vsync offset from the release time.
|
||||
*/
|
||||
private const val LATE_THRESHOLD_NS = 4_000_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GL-side work for the atlas-based path. Maintains a single atlas texture and a
|
||||
* single vertex buffer; uploads them per frame (unless the payload identity
|
||||
* matches the last upload) and issues one `glDrawArrays` for the whole frame.
|
||||
*/
|
||||
@UnstableApi
|
||||
private class AtlasRenderer(private val assHandler: AssHandler) {
|
||||
|
||||
private val vertexShaderCode = """
|
||||
attribute vec2 a_Position;
|
||||
attribute vec2 a_TexCoord;
|
||||
attribute vec4 a_Color;
|
||||
uniform vec2 u_SurfaceSize;
|
||||
varying vec2 v_TexCoord;
|
||||
varying vec4 v_Color;
|
||||
void main() {
|
||||
vec2 clip = (a_Position / u_SurfaceSize) * 2.0 - 1.0;
|
||||
clip.y = -clip.y;
|
||||
gl_Position = vec4(clip, 0.0, 1.0);
|
||||
v_TexCoord = a_TexCoord;
|
||||
v_Color = a_Color;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val fragmentShaderCode = """
|
||||
precision mediump float;
|
||||
varying vec2 v_TexCoord;
|
||||
varying vec4 v_Color;
|
||||
uniform sampler2D u_Texture;
|
||||
void main() {
|
||||
float alpha = texture2D(u_Texture, v_TexCoord).a;
|
||||
gl_FragColor = v_Color * alpha;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private var surfaceSize = Size.ZERO
|
||||
private lateinit var glProgram: GlProgram
|
||||
|
||||
private var atlasTexId = 0
|
||||
private var vertexBufferId = 0
|
||||
|
||||
private var aPosition = 0
|
||||
private var aTexCoord = 0
|
||||
private var aColor = 0
|
||||
private var uTexture = 0
|
||||
private var uSurfaceSize = 0
|
||||
|
||||
private var atlasAllocatedW = 0
|
||||
private var atlasAllocatedH = 0
|
||||
|
||||
/**
|
||||
* Allocates the atlas texture once at the resolved dims. The C side bakes UV
|
||||
* denominators = these dims into the vertex stream, so per-frame uploads can be
|
||||
* partial ([uploadAtlas]) without ever reallocating — drivers keep one stable
|
||||
* texture allocation instead of churning on packed-height changes.
|
||||
*/
|
||||
fun allocateAtlasTexture(width: Int, height: Int) {
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, atlasTexId)
|
||||
GLES20.glTexImage2D(
|
||||
GLES20.GL_TEXTURE_2D, 0, GLES20.GL_ALPHA,
|
||||
width, height, 0,
|
||||
GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, null
|
||||
)
|
||||
atlasAllocatedW = width
|
||||
atlasAllocatedH = height
|
||||
}
|
||||
|
||||
fun onSurfaceCreated() {
|
||||
glProgram = GlProgram(vertexShaderCode, fragmentShaderCode)
|
||||
GlUtil.checkGlError()
|
||||
glProgram.use()
|
||||
|
||||
aPosition = glProgram.getAttributeArrayLocationAndEnable("a_Position")
|
||||
aTexCoord = glProgram.getAttributeArrayLocationAndEnable("a_TexCoord")
|
||||
aColor = glProgram.getAttributeArrayLocationAndEnable("a_Color")
|
||||
uTexture = glProgram.getUniformLocation("u_Texture")
|
||||
uSurfaceSize = glProgram.getUniformLocation("u_SurfaceSize")
|
||||
|
||||
val tex = IntArray(1)
|
||||
GLES20.glGenTextures(1, tex, 0)
|
||||
atlasTexId = tex[0]
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, atlasTexId)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
|
||||
GLES20.glUniform1i(uTexture, 0)
|
||||
|
||||
val buf = IntArray(1)
|
||||
GLES20.glGenBuffers(1, buf, 0)
|
||||
vertexBufferId = buf[0]
|
||||
|
||||
GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1)
|
||||
GLES20.glEnable(GLES20.GL_BLEND)
|
||||
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA)
|
||||
}
|
||||
|
||||
fun onSurfaceChanged(width: Int, height: Int) {
|
||||
surfaceSize = Size(width, height)
|
||||
assHandler.render?.setFrameSize(width, height)
|
||||
GLES20.glViewport(0, 0, width, height)
|
||||
GLES20.glUniform2f(uSurfaceSize, width.toFloat(), height.toFloat())
|
||||
}
|
||||
|
||||
fun onDrawFrame(payload: AtlasPayload, reuseUploads: Boolean) {
|
||||
GlUtil.clearFocusedBuffers()
|
||||
|
||||
val frame = payload.frame
|
||||
val quadCount = frame.quadCount
|
||||
if (quadCount == 0) return
|
||||
|
||||
if (!reuseUploads) {
|
||||
uploadAtlas(payload.atlasBuf, frame.atlasWidth, frame.atlasHeight)
|
||||
uploadVertices(payload.vertexBuf, quadCount)
|
||||
}
|
||||
|
||||
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBufferId)
|
||||
val stride = AssAtlasPipelineConfig.BYTES_PER_VERTEX
|
||||
GLES20.glVertexAttribPointer(aPosition, 2, GLES20.GL_FLOAT, false, stride, 0)
|
||||
GLES20.glVertexAttribPointer(aTexCoord, 2, GLES20.GL_FLOAT, false, stride, 8)
|
||||
GLES20.glVertexAttribPointer(aColor, 4, GLES20.GL_FLOAT, false, stride, 16)
|
||||
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, quadCount * 6)
|
||||
}
|
||||
|
||||
private fun uploadAtlas(atlasBuf: ByteBuffer, atlasW: Int, atlasH: Int) {
|
||||
atlasBuf.position(0).limit(atlasW * atlasH)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, atlasTexId)
|
||||
if (atlasW == atlasAllocatedW && atlasH <= atlasAllocatedH) {
|
||||
// Steady state: packed rows into the once-allocated texture.
|
||||
GLES20.glTexSubImage2D(
|
||||
GLES20.GL_TEXTURE_2D, 0, 0, 0, atlasW, atlasH,
|
||||
GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, atlasBuf
|
||||
)
|
||||
} else {
|
||||
// Defensive: dims disagree with the allocation (shouldn't happen — both
|
||||
// sides resolve dims through the same first-wins gate).
|
||||
Log.w("AssAtlasRenderer", "atlas upload ${atlasW}x$atlasH outside allocation ${atlasAllocatedW}x$atlasAllocatedH")
|
||||
GLES20.glTexImage2D(
|
||||
GLES20.GL_TEXTURE_2D, 0, GLES20.GL_ALPHA,
|
||||
atlasW, atlasH, 0,
|
||||
GLES20.GL_ALPHA, GLES20.GL_UNSIGNED_BYTE, atlasBuf
|
||||
)
|
||||
atlasAllocatedW = atlasW
|
||||
atlasAllocatedH = atlasH
|
||||
}
|
||||
}
|
||||
|
||||
private fun uploadVertices(vertexBuf: ByteBuffer, quadCount: Int) {
|
||||
val size = quadCount * AssAtlasPipelineConfig.BYTES_PER_QUAD
|
||||
vertexBuf.position(0).limit(size)
|
||||
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBufferId)
|
||||
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, size, vertexBuf, GLES20.GL_STREAM_DRAW)
|
||||
}
|
||||
|
||||
fun onSurfaceDestroyed() {
|
||||
if (atlasTexId != 0) {
|
||||
val tex = intArrayOf(atlasTexId)
|
||||
GLES20.glDeleteTextures(1, tex, 0)
|
||||
atlasTexId = 0
|
||||
}
|
||||
if (vertexBufferId != 0) {
|
||||
val buf = intArrayOf(vertexBufferId)
|
||||
GLES20.glDeleteBuffers(1, buf, 0)
|
||||
vertexBufferId = 0
|
||||
}
|
||||
if (::glProgram.isInitialized) glProgram.delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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
|
||||
|
||||
init {
|
||||
setZOrderMediaOverlay(true)
|
||||
holder.setFormat(PixelFormat.TRANSLUCENT)
|
||||
holder.addCallback(this)
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
/** Cache-warming prefetch renders of upcoming events. */
|
||||
val prefetchCount: Long get() = pipeline?.prefetchCount ?: 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 }
|
||||
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
val rect = holder.surfaceFrame
|
||||
assHandler.setOverlaySurfaceSize(rect.width(), rect.height())
|
||||
val lowRam = (context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)
|
||||
?.isLowRamDevice ?: false
|
||||
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam)
|
||||
.also { it.start() }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package com.edde746.plezy.libass.media.widget
|
||||
|
||||
import com.edde746.plezy.libass.AssAtlasFrame
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* Decision core of the speculative render-ahead pipeline.
|
||||
*
|
||||
* 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
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
if (specPtsUs != UNSET) {
|
||||
val eps = epsilonUs()
|
||||
val genNow = stateGeneration()
|
||||
val hit = genNow == specGen && eps > 0 && abs(ptsUs - specPtsUs) <= eps
|
||||
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=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms slot=$slot")
|
||||
return Outcome.Post(slot, frame, newContent = false, specHit = true)
|
||||
}
|
||||
specMisses++
|
||||
debugLog?.invoke(
|
||||
"miss pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms eps=${eps / 1000}ms " +
|
||||
"gen=${if (genNow == specGen) "ok" else "CHANGED"} slot=$slot frame=${frame != null}"
|
||||
)
|
||||
} else {
|
||||
debugLog?.invoke("no-spec pts=${ptsUs / 1000}ms")
|
||||
}
|
||||
|
||||
// On-demand render. Preferring libassLastSlot as the target makes changed == 0
|
||||
// unambiguous: the buffers were untouched and already hold the right content.
|
||||
val target = renderTargetSlot() ?: return Outcome.Skip
|
||||
val frame = renderAt(ptsUs / 1000, target) ?: return Outcome.Skip
|
||||
if (frame.changed == 0) {
|
||||
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(specPts / 1000, target) ?: run {
|
||||
specSkips++
|
||||
return null
|
||||
}
|
||||
specGen = gen
|
||||
specPtsUs = specPts
|
||||
if (frame.changed == 0) {
|
||||
// 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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(ptsUs / 1000, 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 epsilonUs(): Long = if (deltaValid()) minOf(medianDeltaUs() / 2, EPSILON_CAP_US) else 0L
|
||||
|
||||
private companion object {
|
||||
const val UNSET = Long.MIN_VALUE
|
||||
const val DELTA_SAMPLES = 8
|
||||
const val MIN_DELTA_SAMPLES = 4
|
||||
const val MAX_DELTA_US = 250_000L
|
||||
const val EPSILON_CAP_US = 8_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
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)
|
||||
}
|
||||
|
||||
@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 within epsilon`() {
|
||||
val h = Harness()
|
||||
val last = h.prime()
|
||||
|
||||
val outcome = h.engine.service(last + DELTA + 3_000, pinned = true)
|
||||
|
||||
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
|
||||
}
|
||||
|
||||
@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 `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 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,11 @@ 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")
|
||||
// libass subtitle module (Kotlin/JNI bindings + Media3 glue); the native libass
|
||||
// core stays the upstream Maven artifact io.github.peerless2012:ass.
|
||||
include(":libass")
|
||||
|
||||
|
After Width: | Height: | Size: 121 KiB |
@@ -1,15 +0,0 @@
|
||||
## iOS
|
||||
|
||||
| Home | Library | Media Card | Season |
|
||||
|------|---------|------------|--------|
|
||||
|  |  |  |  |
|
||||
|
||||
## macOS
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
Before Width: | Height: | Size: 3.8 MiB |
|
Before Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 2.6 MiB |
|
Before Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 4.4 MiB |
|
Before Width: | Height: | Size: 3.4 MiB |
|
Before Width: | Height: | Size: 3.0 MiB |
|
Before Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,17 @@
|
||||
targets:
|
||||
$default:
|
||||
builders:
|
||||
json_serializable:
|
||||
options:
|
||||
create_to_json: true
|
||||
explicit_to_json: true
|
||||
field_rename: none
|
||||
include_if_null: true
|
||||
checked: false
|
||||
freezed:
|
||||
options:
|
||||
copy_with: true
|
||||
equal: true
|
||||
to_string: true
|
||||
slang_build_runner:
|
||||
enabled: false
|
||||
@@ -1,128 +1,34 @@
|
||||
PODS:
|
||||
- background_downloader (0.0.1):
|
||||
- Flutter
|
||||
- connectivity_plus (0.0.1):
|
||||
- Flutter
|
||||
- cupertino_http (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- device_info_plus (0.0.1):
|
||||
- Flutter
|
||||
- file_picker (0.0.1):
|
||||
- Flutter
|
||||
- Flutter (1.0.0)
|
||||
- os_media_controls (0.2.1):
|
||||
- os_media_controls (0.2.4):
|
||||
- Flutter
|
||||
- package_info_plus (0.4.5):
|
||||
- Flutter
|
||||
- Sentry/HybridSDK (8.58.0)
|
||||
- sentry_flutter (9.16.0):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- Sentry/HybridSDK (= 8.58.0)
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqlite3 (3.52.0):
|
||||
- sqlite3/common (= 3.52.0)
|
||||
- sqlite3/common (3.52.0)
|
||||
- sqlite3/dbstatvtab (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/fts5 (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/math (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/perf-threadsafe (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/rtree (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/session (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3_flutter_libs (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqlite3 (~> 3.52.0)
|
||||
- sqlite3/dbstatvtab
|
||||
- sqlite3/fts5
|
||||
- sqlite3/math
|
||||
- sqlite3/perf-threadsafe
|
||||
- sqlite3/rtree
|
||||
- sqlite3/session
|
||||
- universal_gamepad (0.1.0):
|
||||
- Flutter
|
||||
- url_launcher_ios (0.0.1):
|
||||
- Flutter
|
||||
- wakelock_plus (0.0.1):
|
||||
- Flutter
|
||||
|
||||
DEPENDENCIES:
|
||||
- background_downloader (from `.symlinks/plugins/background_downloader/ios`)
|
||||
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
|
||||
- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)
|
||||
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
|
||||
- file_picker (from `.symlinks/plugins/file_picker/ios`)
|
||||
- Flutter (from `Flutter`)
|
||||
- os_media_controls (from `.symlinks/plugins/os_media_controls/ios`)
|
||||
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
|
||||
- sentry_flutter (from `.symlinks/plugins/sentry_flutter/ios`)
|
||||
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- sqlite3_flutter_libs (from `.symlinks/plugins/sqlite3_flutter_libs/darwin`)
|
||||
- universal_gamepad (from `.symlinks/plugins/universal_gamepad/ios`)
|
||||
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
|
||||
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- Sentry
|
||||
- sqlite3
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
background_downloader:
|
||||
:path: ".symlinks/plugins/background_downloader/ios"
|
||||
connectivity_plus:
|
||||
:path: ".symlinks/plugins/connectivity_plus/ios"
|
||||
cupertino_http:
|
||||
:path: ".symlinks/plugins/cupertino_http/darwin"
|
||||
device_info_plus:
|
||||
:path: ".symlinks/plugins/device_info_plus/ios"
|
||||
file_picker:
|
||||
:path: ".symlinks/plugins/file_picker/ios"
|
||||
Flutter:
|
||||
:path: Flutter
|
||||
os_media_controls:
|
||||
:path: ".symlinks/plugins/os_media_controls/ios"
|
||||
package_info_plus:
|
||||
:path: ".symlinks/plugins/package_info_plus/ios"
|
||||
sentry_flutter:
|
||||
:path: ".symlinks/plugins/sentry_flutter/ios"
|
||||
shared_preferences_foundation:
|
||||
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
|
||||
sqlite3_flutter_libs:
|
||||
:path: ".symlinks/plugins/sqlite3_flutter_libs/darwin"
|
||||
universal_gamepad:
|
||||
:path: ".symlinks/plugins/universal_gamepad/ios"
|
||||
url_launcher_ios:
|
||||
:path: ".symlinks/plugins/url_launcher_ios/ios"
|
||||
wakelock_plus:
|
||||
:path: ".symlinks/plugins/wakelock_plus/ios"
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
background_downloader: 50e91d979067b82081aba359d7d916b3ba5fadad
|
||||
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
|
||||
cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
|
||||
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
|
||||
file_picker: 8fc6fe5e42585a217d44d22f79ec046cb8d81140
|
||||
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
|
||||
os_media_controls: 3b06fe2dc0977dfa94f9c1dd73df7a55022d202f
|
||||
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
|
||||
Sentry: d587a8fe91ca13503ecd69a1905f3e8a0fcf61be
|
||||
sentry_flutter: 31101687061fb85211ebab09ce6eb8db4e9ba74f
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
sqlite3: a51c07cf16e023d6c48abd5e5791a61a47354921
|
||||
sqlite3_flutter_libs: b3e120efe9a82017e5552a620f696589ed4f62ab
|
||||
os_media_controls: 048eb9a75974191b2496d85575b6edcefc572d4e
|
||||
universal_gamepad: 838bbb70d37d8c7c719038aa397214f2c4c4f866
|
||||
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
|
||||
wakelock_plus: 5aaa6a7ccaf4749a96a7d8ff0721d68061ad62cf
|
||||
|
||||
PODFILE CHECKSUM: 16bb7f67e16d8aaa2bfb97666803fbfb291b6559
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */; };
|
||||
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */; };
|
||||
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */; };
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -78,6 +79,7 @@
|
||||
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>"; };
|
||||
F3553CDE70191F0FC81A782E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -93,6 +95,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
|
||||
6A8A46212EDB320D0057B88C /* MPVKit in Frameworks */,
|
||||
69E1B4BB161DC9D84D1DFC62 /* Pods_Runner.framework in Frameworks */,
|
||||
);
|
||||
@@ -147,6 +150,7 @@
|
||||
9740EEB11CF90186004384FC /* Flutter */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,
|
||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
|
||||
9740EEB21CF90195004384FC /* Debug.xcconfig */,
|
||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
|
||||
@@ -215,6 +219,9 @@
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
97C146ED1CF9000F007C117D /* Runner */ = {
|
||||
packageProductDependencies = (
|
||||
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
|
||||
);
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
|
||||
buildPhases = (
|
||||
@@ -266,6 +273,7 @@
|
||||
);
|
||||
mainGroup = 97C146E51CF9000F007C117D;
|
||||
packageReferences = (
|
||||
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */,
|
||||
6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */,
|
||||
);
|
||||
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
|
||||
@@ -781,7 +789,7 @@
|
||||
repositoryURL = "https://github.com/edde746/MPVKit";
|
||||
requirement = {
|
||||
kind = revision;
|
||||
revision = 86dcf97f04e572abb5641e74780251a1d5634ff3;
|
||||
revision = 245b69dce22156e81b79c84cfcb748358b674e47;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
@@ -792,7 +800,17 @@
|
||||
package = 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */;
|
||||
productName = MPVKit;
|
||||
};
|
||||
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = FlutterGeneratedPluginSwiftPackage;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
};
|
||||
rootObject = 97C146E61CF9000F007C117D /* Project object */;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,84 @@
|
||||
{
|
||||
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "csqlite",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/simolus3/CSQLite.git",
|
||||
"state" : {
|
||||
"revision" : "1ee46d19a4f451a7aa64ffc64fc99b4748131e62"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkcamera",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKCamera",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "5c691d11014b910aff69f960475d70e65d9dcc96"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkimagepickercontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKImagePickerController",
|
||||
"state" : {
|
||||
"branch" : "4.3.9",
|
||||
"revision" : "0bdfeacefa308545adde07bef86e349186335915"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkphotogallery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKPhotoGallery",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "mpvkit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "86dcf97f04e572abb5641e74780251a1d5634ff3"
|
||||
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sdwebimage",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/SDWebImage/SDWebImage",
|
||||
"state" : {
|
||||
"revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0",
|
||||
"version" : "5.21.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sentry-cocoa",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/getsentry/sentry-cocoa",
|
||||
"state" : {
|
||||
"revision" : "16cd512711375fa73f25ae5e373f596bdf4251ae",
|
||||
"version" : "8.58.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftygif",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/kirualex/SwiftyGif.git",
|
||||
"state" : {
|
||||
"revision" : "4430cbc148baa3907651d40562d96325426f409a",
|
||||
"version" : "5.4.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "tocropviewcontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/TimOliver/TOCropViewController",
|
||||
"state" : {
|
||||
"revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e",
|
||||
"version" : "2.8.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
"version" : 2
|
||||
}
|
||||
|
||||
@@ -5,6 +5,24 @@
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<PreActions>
|
||||
<ExecutionAction
|
||||
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
|
||||
<ActionContent
|
||||
title = "Run Prepare Flutter Framework Script"
|
||||
scriptText = "/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" prepare ">
|
||||
<EnvironmentBuildable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
|
||||
BuildableName = "Runner.app"
|
||||
BlueprintName = "Runner"
|
||||
ReferencedContainer = "container:Runner.xcodeproj">
|
||||
</BuildableReference>
|
||||
</EnvironmentBuildable>
|
||||
</ActionContent>
|
||||
</ExecutionAction>
|
||||
</PreActions>
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
|
||||
@@ -1,14 +1,84 @@
|
||||
{
|
||||
"originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "csqlite",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/simolus3/CSQLite.git",
|
||||
"state" : {
|
||||
"revision" : "1ee46d19a4f451a7aa64ffc64fc99b4748131e62"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkcamera",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKCamera",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "5c691d11014b910aff69f960475d70e65d9dcc96"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkimagepickercontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKImagePickerController",
|
||||
"state" : {
|
||||
"branch" : "4.3.9",
|
||||
"revision" : "0bdfeacefa308545adde07bef86e349186335915"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "dkphotogallery",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/zhangao0086/DKPhotoGallery",
|
||||
"state" : {
|
||||
"branch" : "master",
|
||||
"revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "mpvkit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "86dcf97f04e572abb5641e74780251a1d5634ff3"
|
||||
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sdwebimage",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/SDWebImage/SDWebImage",
|
||||
"state" : {
|
||||
"revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0",
|
||||
"version" : "5.21.7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sentry-cocoa",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/getsentry/sentry-cocoa",
|
||||
"state" : {
|
||||
"revision" : "16cd512711375fa73f25ae5e373f596bdf4251ae",
|
||||
"version" : "8.58.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftygif",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/kirualex/SwiftyGif.git",
|
||||
"state" : {
|
||||
"revision" : "4430cbc148baa3907651d40562d96325426f409a",
|
||||
"version" : "5.4.5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "tocropviewcontroller",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/TimOliver/TOCropViewController",
|
||||
"state" : {
|
||||
"revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e",
|
||||
"version" : "2.8.0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
"version" : 2
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
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]?
|
||||
@@ -29,5 +35,119 @@ import AVFoundation
|
||||
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "MpvPlayerPlugin") {
|
||||
MpvPlayerPlugin.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>
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(FLUTTER_BUILD_NUMBER)</string>
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
<false/>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
@@ -35,6 +37,10 @@
|
||||
</dict>
|
||||
<key>NSLocalNetworkUsageDescription</key>
|
||||
<string>This app needs to connect to your media servers on your local network.</string>
|
||||
<key>NSLocationWhenInUseUsageDescription</key>
|
||||
<string>Plezy uses location access when iOS requires it to detect your local network and connect to your media servers.</string>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
<string>Plezy needs photo library access so you can choose images to upload as media artwork.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>Camera is used to scan QR codes for Companion Remote pairing.</string>
|
||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||
|
||||
@@ -13,7 +13,7 @@ import UIKit
|
||||
func pipDidStop(restored: Bool)
|
||||
func pipDidFailToStart(error: Error?)
|
||||
func pipSetPlaying(_ playing: Bool)
|
||||
func pipSkip(byInterval seconds: Double)
|
||||
func pipSkip(byInterval seconds: Double, completion: @escaping () -> Void)
|
||||
var isPipPlaying: Bool { get }
|
||||
var pipDuration: Double { get }
|
||||
}
|
||||
@@ -48,7 +48,7 @@ import UIKit
|
||||
/// Forward play/pause commands from PiP overlay to mpv
|
||||
func pipSetPlaying(_ playing: Bool)
|
||||
/// Forward skip forward/backward commands from PiP overlay to mpv
|
||||
func pipSkip(byInterval seconds: Double)
|
||||
func pipSkip(byInterval seconds: Double, completion: @escaping () -> Void)
|
||||
/// Query whether mpv is currently playing
|
||||
var isPipPlaying: Bool { get }
|
||||
/// Get total duration in seconds
|
||||
@@ -99,9 +99,7 @@ import UIKit
|
||||
self.delegateHelper = helper
|
||||
pipController = AVPictureInPictureController(contentSource: contentSource)
|
||||
pipController?.delegate = helper
|
||||
if #available(iOS 14.2, *) {
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = false
|
||||
}
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = false
|
||||
}
|
||||
|
||||
/// Enable/disable system auto-PiP (starts PiP automatically on background transition)
|
||||
@@ -110,30 +108,15 @@ import UIKit
|
||||
pipController?.canStartPictureInPictureAutomaticallyFromInline = enabled
|
||||
}
|
||||
|
||||
/// Sync the layer's controlTimebase with the actual playback position.
|
||||
/// This makes the PiP progress bar show the correct time.
|
||||
/// MPVKit owns the sample-buffer layer timebase. PiP only reads it.
|
||||
func syncTimebase(currentTime: Double, isPlaying: Bool) {
|
||||
guard let timebase = sampleBufferLayer?.controlTimebase else { return }
|
||||
let cmTime = CMTime(seconds: currentTime, preferredTimescale: 1000)
|
||||
CMTimebaseSetTime(timebase, time: cmTime)
|
||||
CMTimebaseSetRate(timebase, rate: isPlaying ? 1.0 : 0.0)
|
||||
}
|
||||
|
||||
/// Ensure the layer has a timebase so the PiP progress UI can follow mpv.
|
||||
/// Ensure the layer has MPVKit's renderer-owned timebase before PiP starts.
|
||||
func warmLayer(currentTime: Double, isPlaying: Bool) {
|
||||
guard let sampleBufferLayer else { return }
|
||||
if sampleBufferLayer.controlTimebase == nil {
|
||||
var timebase: CMTimebase?
|
||||
CMTimebaseCreateWithSourceClock(
|
||||
allocator: kCFAllocatorDefault,
|
||||
sourceClock: CMClockGetHostTimeClock(),
|
||||
timebaseOut: &timebase
|
||||
)
|
||||
if let tb = timebase {
|
||||
sampleBufferLayer.controlTimebase = tb
|
||||
}
|
||||
if sampleBufferLayer?.controlTimebase == nil {
|
||||
print("[MpvPipController] Waiting for MPVKit renderer timebase before PiP")
|
||||
}
|
||||
syncTimebase(currentTime: currentTime, isPlaying: isPlaying)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
@@ -188,6 +171,7 @@ import UIKit
|
||||
|
||||
/// Invalidate the playback state so PiP updates its UI (play/pause button)
|
||||
func invalidatePlaybackState() {
|
||||
guard #available(iOS 15.0, *) else { return }
|
||||
pipController?.invalidatePlaybackState()
|
||||
}
|
||||
|
||||
@@ -310,8 +294,11 @@ import UIKit
|
||||
) {
|
||||
let seconds = CMTimeGetSeconds(skipInterval)
|
||||
print("[MpvPipController] PiP skip by \(seconds)s")
|
||||
controller?.delegate?.pipSkip(byInterval: seconds)
|
||||
completionHandler()
|
||||
guard let delegate = controller?.delegate else {
|
||||
completionHandler()
|
||||
return
|
||||
}
|
||||
delegate.pipSkip(byInterval: seconds, completion: completionHandler)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import AVFoundation
|
||||
#if os(tvOS)
|
||||
import AVKit
|
||||
#endif
|
||||
import QuartzCore
|
||||
import UIKit
|
||||
|
||||
@@ -9,9 +12,20 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
private weak var window: UIWindow?
|
||||
private var mainBlankView: UIView?
|
||||
private var isVisible = false
|
||||
private var isDisposed = false
|
||||
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")
|
||||
@@ -88,6 +102,10 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
let scale = screen.nativeScale > 0 ? screen.nativeScale : screen.scale
|
||||
videoLayer.contentsScale = scale
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
updateEDRMode(sigPeak: lastSigPeak)
|
||||
#endif
|
||||
}
|
||||
|
||||
func externalDisplayDidChange() {
|
||||
@@ -95,7 +113,7 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
}
|
||||
|
||||
private func refreshExternalDisplayAttachment() {
|
||||
guard let containerView else { return }
|
||||
guard containerView != nil else { return }
|
||||
|
||||
let externalSuperview = externalVideoSuperview
|
||||
|
||||
@@ -183,28 +201,613 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
command(["seek", "0", "relative+exact"])
|
||||
}
|
||||
|
||||
override func updateEDRMode(sigPeak: Double) {
|
||||
private func restoreVideoPresentation() {
|
||||
guard !isPipActive else { return }
|
||||
|
||||
refreshExternalDisplayAttachment()
|
||||
recoverDisplayLayerIfNeeded()
|
||||
updateEDRMode(sigPeak: lastSigPeak)
|
||||
if isPaused { forceDraw() }
|
||||
}
|
||||
|
||||
private func recoverDisplayLayerIfNeeded() {
|
||||
guard let videoLayer else { return }
|
||||
|
||||
let hdrEnabled = self.hdrEnabled
|
||||
var edrHeadroom: CGFloat = 1.0
|
||||
var requiresFlush = false
|
||||
if #available(iOS 14.0, tvOS 14.0, *) {
|
||||
requiresFlush = videoLayer.requiresFlushToResumeDecoding
|
||||
}
|
||||
let status = videoLayer.status
|
||||
guard requiresFlush || status == .failed else { return }
|
||||
|
||||
videoLayer.flush()
|
||||
}
|
||||
|
||||
override func updateEDRMode(sigPeak: Double) {
|
||||
#if os(iOS)
|
||||
if #available(iOS 17.0, *) {
|
||||
edrHeadroom = containerView?.window?.screen.potentialEDRHeadroom ?? 1.0
|
||||
guard let videoLayer else { return }
|
||||
|
||||
let shouldEnableEDR = hdrEnabled && sigPeak > 1.0
|
||||
if #available(iOS 26.0, *) {
|
||||
withoutLayerAnimations {
|
||||
videoLayer.wantsExtendedDynamicRangeContent =
|
||||
hdrEnabled && sigPeak > 1.0 && edrHeadroom > 1.0
|
||||
videoLayer.preferredDynamicRange = shouldEnableEDR ? .high : .standard
|
||||
}
|
||||
} else if #available(iOS 17.0, *) {
|
||||
withoutLayerAnimations {
|
||||
videoLayer.wantsExtendedDynamicRangeContent = shouldEnableEDR
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
let shouldEnableEDR = hdrEnabled && sigPeak > 1.0 && edrHeadroom > 1.0
|
||||
print(
|
||||
"[MpvPlayerCore] EDR mode: \(shouldEnableEDR) (hdrEnabled: \(hdrEnabled), sigPeak: \(sigPeak), headroom: \(edrHeadroom))"
|
||||
)
|
||||
}
|
||||
|
||||
func dispose() {
|
||||
@discardableResult
|
||||
override func updateDisplayCriteria(
|
||||
doviProfile: Int64,
|
||||
doviLevel: Int64,
|
||||
doviCompatibilityId: Int64?,
|
||||
fps: Double,
|
||||
width: Int32,
|
||||
height: Int32,
|
||||
sigPeak: Double,
|
||||
gamma: String?,
|
||||
primaries: String?,
|
||||
colorMatrix: String?
|
||||
) -> Bool {
|
||||
#if os(tvOS)
|
||||
lastDisplayCriteriaMutation = .skipped
|
||||
guard let window = containerView?.window ?? self.window else { return false }
|
||||
let displayManager = window.avDisplayManager
|
||||
|
||||
if width <= 0 || height <= 0 {
|
||||
clearDisplayCriteria(displayManager, reason: "no video dimensions")
|
||||
return false
|
||||
}
|
||||
|
||||
let refreshRate = Float(fps > 0 ? fps : 0)
|
||||
let sourceHasDolbyVision = doviProfile > 0
|
||||
guard
|
||||
refreshRate > 0 || sourceHasDolbyVision || sigPeak > 0 || gamma != nil || primaries != nil || colorMatrix != nil
|
||||
else {
|
||||
clearDisplayCriteria(displayManager, reason: "no display metadata")
|
||||
return false
|
||||
}
|
||||
|
||||
let sourceBaseRange = Self.resolveBaseDisplayDynamicRange(
|
||||
sigPeak: sigPeak,
|
||||
gamma: gamma,
|
||||
primaries: primaries,
|
||||
colorMatrix: colorMatrix,
|
||||
doviCompatibilityId: doviCompatibilityId
|
||||
)
|
||||
let sourceRange: DisplayDynamicRange = sourceHasDolbyVision ? .dolbyVision : sourceBaseRange
|
||||
// The HDR toggle (`hdrEnabled`) is authoritative on tvOS: when it's off,
|
||||
// drive the HDMI link in SDR regardless of the source — Dolby Vision
|
||||
// included — so turning HDR off actually leaves DV mode (issue #1262).
|
||||
// This is the only path that gates the HDMI mode on tvOS;
|
||||
// target-colorspace-hint is inert in the avfoundation VO and EDR is iOS.
|
||||
var displayRange: DisplayDynamicRange
|
||||
if !hdrEnabled {
|
||||
displayRange = .sdr
|
||||
} else if sourceHasDolbyVision {
|
||||
displayRange = .dolbyVision
|
||||
} else {
|
||||
displayRange = Self.supportedDisplayDynamicRange(for: sourceBaseRange)
|
||||
}
|
||||
guard displayManager.isDisplayCriteriaMatchingEnabled else {
|
||||
clearDisplayCriteria(displayManager, reason: "matching disabled")
|
||||
return false
|
||||
}
|
||||
guard #available(tvOS 17.0, *) else {
|
||||
clearDisplayCriteria(displayManager, reason: "display criteria unavailable")
|
||||
return false
|
||||
}
|
||||
|
||||
var formatDescription = Self.makeDisplayFormatDescription(
|
||||
dynamicRange: displayRange,
|
||||
width: width,
|
||||
height: height,
|
||||
doviProfile: doviProfile,
|
||||
doviLevel: doviLevel,
|
||||
doviCompatibilityId: doviCompatibilityId)
|
||||
if formatDescription == nil, sourceHasDolbyVision, hdrEnabled {
|
||||
displayRange = sourceBaseRange
|
||||
formatDescription = Self.makeDisplayFormatDescription(
|
||||
dynamicRange: displayRange,
|
||||
width: width,
|
||||
height: height,
|
||||
doviProfile: doviProfile,
|
||||
doviLevel: doviLevel,
|
||||
doviCompatibilityId: doviCompatibilityId)
|
||||
}
|
||||
|
||||
guard let formatDescription else {
|
||||
clearDisplayCriteria(displayManager, reason: "format description failed")
|
||||
return false
|
||||
}
|
||||
|
||||
let criteriaKey =
|
||||
"\(displayRange.rawValue)|\(refreshRate)|\(width)x\(height)|\(doviProfile)|\(doviLevel)|\(doviCompatibilityId ?? -1)"
|
||||
if Self.activeDisplayCriteriaKey == criteriaKey && displayManager.preferredDisplayCriteria != nil {
|
||||
lastDisplayCriteriaMutation = .unchanged
|
||||
return true
|
||||
}
|
||||
|
||||
let displayCriteria = AVDisplayCriteria(
|
||||
refreshRate: refreshRate,
|
||||
formatDescription: formatDescription
|
||||
)
|
||||
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
|
||||
return false
|
||||
#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"
|
||||
case hdr10 = "HDR10"
|
||||
case hlg = "HLG"
|
||||
case dolbyVision = "Dolby Vision"
|
||||
}
|
||||
|
||||
private func clearDisplayCriteria(_ displayManager: AVDisplayManager, reason: String) {
|
||||
if Self.activeDisplayCriteriaKey != nil || displayManager.preferredDisplayCriteria != nil {
|
||||
displayManager.preferredDisplayCriteria = nil
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
private static func resolveBaseDisplayDynamicRange(
|
||||
sigPeak: Double,
|
||||
gamma: String?,
|
||||
primaries: String?,
|
||||
colorMatrix: String?,
|
||||
doviCompatibilityId: Int64?
|
||||
) -> DisplayDynamicRange {
|
||||
let normalizedGamma = normalizeColorTag(gamma)
|
||||
let normalizedPrimaries = normalizeColorTag(primaries)
|
||||
let normalizedColorMatrix = normalizeColorTag(colorMatrix)
|
||||
|
||||
if normalizedGamma.contains("hlg") || normalizedGamma.contains("arib") {
|
||||
return .hlg
|
||||
}
|
||||
if normalizedGamma.contains("pq") || normalizedGamma.contains("smpte2084")
|
||||
|| normalizedGamma.contains("st2084") || sigPeak > 1.0
|
||||
|| normalizedPrimaries.contains("bt2020") || normalizedColorMatrix.contains("bt2020")
|
||||
{
|
||||
return .hdr10
|
||||
}
|
||||
switch doviCompatibilityId {
|
||||
case 1, 6:
|
||||
return .hdr10
|
||||
case 4:
|
||||
return .hlg
|
||||
case 2:
|
||||
return .sdr
|
||||
default:
|
||||
break
|
||||
}
|
||||
return .sdr
|
||||
}
|
||||
|
||||
private static func normalizeColorTag(_ value: String?) -> String {
|
||||
value?.lowercased().filter { $0.isLetter || $0.isNumber } ?? ""
|
||||
}
|
||||
|
||||
private static func supportedDisplayDynamicRange(for range: DisplayDynamicRange) -> DisplayDynamicRange {
|
||||
let availableModes = AVPlayer.availableHDRModes
|
||||
switch range {
|
||||
case .dolbyVision:
|
||||
if availableModes.contains(.dolbyVision) { return .dolbyVision }
|
||||
if availableModes.contains(.hdr10) { return .hdr10 }
|
||||
if availableModes.contains(.hlg) { return .hlg }
|
||||
return .sdr
|
||||
case .hdr10:
|
||||
return availableModes.contains(.hdr10) ? .hdr10 : .sdr
|
||||
case .hlg:
|
||||
return availableModes.contains(.hlg) ? .hlg : .sdr
|
||||
case .sdr:
|
||||
return .sdr
|
||||
}
|
||||
}
|
||||
|
||||
private static func makeDisplayFormatDescription(
|
||||
dynamicRange: DisplayDynamicRange,
|
||||
width: Int32,
|
||||
height: Int32,
|
||||
doviProfile: Int64,
|
||||
doviLevel: Int64,
|
||||
doviCompatibilityId: Int64?
|
||||
) -> CMVideoFormatDescription? {
|
||||
if dynamicRange == .dolbyVision {
|
||||
// Profile 8.x always carries a compatibility id; profile 5 has none.
|
||||
// We assume bl_signal_compatibility_id = 1 (HDR10 base) for profile 8
|
||||
// because mpv does not expose the compat id and that's by far the
|
||||
// most common case.
|
||||
let fallbackCompat: Int64 = doviProfile == 8 ? 1 : 0
|
||||
let compat = UInt8(truncatingIfNeeded: doviCompatibilityId ?? fallbackCompat)
|
||||
return makeDolbyVisionFormatDescription(
|
||||
width: width,
|
||||
height: height,
|
||||
profile: UInt8(truncatingIfNeeded: doviProfile),
|
||||
level: UInt8(truncatingIfNeeded: doviLevel),
|
||||
compatibility: compat
|
||||
)
|
||||
}
|
||||
|
||||
let extensions: [CFString: Any]
|
||||
switch dynamicRange {
|
||||
case .hdr10:
|
||||
extensions = [
|
||||
kCMFormatDescriptionExtension_ColorPrimaries:
|
||||
kCMFormatDescriptionColorPrimaries_ITU_R_2020,
|
||||
kCMFormatDescriptionExtension_TransferFunction:
|
||||
kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ,
|
||||
kCMFormatDescriptionExtension_YCbCrMatrix:
|
||||
kCMFormatDescriptionYCbCrMatrix_ITU_R_2020,
|
||||
]
|
||||
case .hlg:
|
||||
extensions = [
|
||||
kCMFormatDescriptionExtension_ColorPrimaries:
|
||||
kCMFormatDescriptionColorPrimaries_ITU_R_2020,
|
||||
kCMFormatDescriptionExtension_TransferFunction:
|
||||
kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG,
|
||||
kCMFormatDescriptionExtension_YCbCrMatrix:
|
||||
kCMFormatDescriptionYCbCrMatrix_ITU_R_2020,
|
||||
]
|
||||
case .sdr:
|
||||
extensions = [
|
||||
kCMFormatDescriptionExtension_ColorPrimaries:
|
||||
kCMFormatDescriptionColorPrimaries_ITU_R_709_2,
|
||||
kCMFormatDescriptionExtension_TransferFunction:
|
||||
kCMFormatDescriptionTransferFunction_ITU_R_709_2,
|
||||
kCMFormatDescriptionExtension_YCbCrMatrix:
|
||||
kCMFormatDescriptionYCbCrMatrix_ITU_R_709_2,
|
||||
]
|
||||
case .dolbyVision:
|
||||
return nil
|
||||
}
|
||||
|
||||
var fd: CMVideoFormatDescription?
|
||||
let status = CMVideoFormatDescriptionCreate(
|
||||
allocator: kCFAllocatorDefault,
|
||||
codecType: kCMVideoCodecType_HEVC,
|
||||
width: width,
|
||||
height: height,
|
||||
extensions: extensions as CFDictionary,
|
||||
formatDescriptionOut: &fd
|
||||
)
|
||||
return status == noErr ? fd : nil
|
||||
}
|
||||
|
||||
/// Build a synthetic 'dvh1' `CMVideoFormatDescription` from the Dolby Vision
|
||||
/// metadata mpv exposes. Used solely as a hint object for
|
||||
/// `AVDisplayCriteria(refreshRate:formatDescription:)` — it is never
|
||||
/// enqueued onto the sample-buffer layer.
|
||||
private static func makeDolbyVisionFormatDescription(
|
||||
width: Int32,
|
||||
height: Int32,
|
||||
profile: UInt8,
|
||||
level: UInt8,
|
||||
compatibility: UInt8
|
||||
) -> CMVideoFormatDescription? {
|
||||
// 24-byte Dolby Vision configuration record (dvcC ≤ profile 7, dvvC ≥ 8).
|
||||
// Layout from ETSI TS 103 572 §7.1.1 — same packing as FFmpeg's
|
||||
// videotoolbox_dovi_extradata_create (in 0002 patch):
|
||||
// [0] dv_version_major (= 1)
|
||||
// [1] dv_version_minor (= 0)
|
||||
// [2..3] big-endian uint16: profile<<9 | level<<3 | rpu<<2 | el<<1 | bl
|
||||
// [4] compatibility<<4 | md_compression<<2
|
||||
// [5..23] reserved zero
|
||||
var dovi = [UInt8](repeating: 0, count: 24)
|
||||
dovi[0] = 1
|
||||
dovi[1] = 0
|
||||
let flags: UInt16 =
|
||||
(UInt16(profile) & 0x7f) << 9
|
||||
| (UInt16(level) & 0x3f) << 3
|
||||
| (1 << 2) // rpu_present_flag
|
||||
| (1 << 0) // bl_present_flag
|
||||
dovi[2] = UInt8((flags >> 8) & 0xff)
|
||||
dovi[3] = UInt8(flags & 0xff)
|
||||
dovi[4] = (compatibility & 0x0f) << 4
|
||||
|
||||
// CoreMedia carries codec-specific boxes under
|
||||
// kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms.
|
||||
let recordKey: CFString = (profile > 7 ? "dvvC" : "dvcC") as CFString
|
||||
let atoms: [CFString: Any] = [recordKey: Data(dovi) as CFData]
|
||||
|
||||
let extensions: [CFString: Any] = [
|
||||
kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms: atoms as CFDictionary,
|
||||
kCMFormatDescriptionExtension_ColorPrimaries:
|
||||
kCMFormatDescriptionColorPrimaries_ITU_R_2020,
|
||||
kCMFormatDescriptionExtension_TransferFunction:
|
||||
kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ,
|
||||
kCMFormatDescriptionExtension_YCbCrMatrix:
|
||||
kCMFormatDescriptionYCbCrMatrix_ITU_R_2020,
|
||||
]
|
||||
|
||||
var fd: CMVideoFormatDescription?
|
||||
let status = CMVideoFormatDescriptionCreate(
|
||||
allocator: kCFAllocatorDefault,
|
||||
codecType: kCMVideoCodecType_DolbyVisionHEVC, // 'dvh1'
|
||||
width: width,
|
||||
height: height,
|
||||
extensions: extensions as CFDictionary,
|
||||
formatDescriptionOut: &fd
|
||||
)
|
||||
return status == noErr ? fd : nil
|
||||
}
|
||||
#endif
|
||||
|
||||
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.
|
||||
// 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)
|
||||
ExternalDisplayManager.shared.detach(core: self)
|
||||
@@ -218,7 +821,8 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
mainBlankView?.removeFromSuperview()
|
||||
mainBlankView = nil
|
||||
isInitialized = false
|
||||
print("[MpvPlayerCore] Disposed")
|
||||
|
||||
Self.log("Disposed")
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -226,21 +830,44 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
}
|
||||
|
||||
private func setupNotifications() {
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(enterBackground),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(enterForeground),
|
||||
name: UIApplication.willEnterForegroundNotification,
|
||||
object: nil
|
||||
)
|
||||
#if os(iOS)
|
||||
let scene = window?.windowScene
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(enterBackground),
|
||||
name: UIScene.didEnterBackgroundNotification,
|
||||
object: scene
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(enterForeground),
|
||||
name: UIScene.willEnterForegroundNotification,
|
||||
object: scene
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(sceneDidActivate),
|
||||
name: UIScene.didActivateNotification,
|
||||
object: scene
|
||||
)
|
||||
#else
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(enterBackground),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(enterForeground),
|
||||
name: UIApplication.willEnterForegroundNotification,
|
||||
object: nil
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
@objc private func enterBackground() {
|
||||
isBackgrounded = true
|
||||
if isPipActive || isPipStarting {
|
||||
print("[MpvPlayerCore] Entering background - PiP active/starting, keeping video")
|
||||
return
|
||||
@@ -251,6 +878,7 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
}
|
||||
|
||||
@objc private func enterForeground() {
|
||||
isBackgrounded = false
|
||||
if isPipActive {
|
||||
print("[MpvPlayerCore] Entering foreground - PiP active, skipping vid restore")
|
||||
return
|
||||
@@ -259,4 +887,16 @@ class MpvPlayerCore: MpvPlayerCoreBase {
|
||||
print("[MpvPlayerCore] Entering foreground - enabling video")
|
||||
setProperty("vid", value: "auto")
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@objc private func sceneDidActivate() {
|
||||
isBackgrounded = false
|
||||
if isPipActive {
|
||||
return
|
||||
}
|
||||
|
||||
setProperty("vid", value: "auto")
|
||||
restoreVideoPresentation()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
|
||||
// MpvPluginShared conformance
|
||||
var coreBase: MpvPlayerCoreBase? { playerCore }
|
||||
func setPlayerVisible(_ visible: Bool) { playerCore?.setVisible(visible) }
|
||||
func setPlayerVisible(_ visible: Bool, restoreOnWindowVisible _: Bool) { playerCore?.setVisible(visible) }
|
||||
func updatePlayerFrame() { playerCore?.updateFrame() }
|
||||
|
||||
// PiP
|
||||
@@ -72,7 +72,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
case "initialize":
|
||||
handleInitialize(result: result)
|
||||
case "dispose":
|
||||
handleDispose(result: result)
|
||||
handleDispose(call: call, result: result)
|
||||
case "setProperty":
|
||||
handleSetProperty(call: call, result: result)
|
||||
case "getProperty":
|
||||
@@ -81,6 +81,8 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
handleObserveProperty(call: call, result: result)
|
||||
case "command":
|
||||
handleCommand(call: call, result: result)
|
||||
case "setDisplayCriteria":
|
||||
handleSetDisplayCriteria(call: call, result: result)
|
||||
case "setVisible":
|
||||
handleSetVisible(call: call, result: result)
|
||||
case "isInitialized":
|
||||
@@ -186,6 +188,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
guard let playerCore = playerCore else { return nil }
|
||||
guard let pip = ensurePipController() else { return nil }
|
||||
pendingInlineRestoreAfterPip = false
|
||||
playerCore.setPipSubtitleCompositing(true)
|
||||
playerCore.isPipStarting = true
|
||||
pip.syncTimebase(currentTime: playerCore.timePos, isPlaying: !playerCore.isPaused)
|
||||
pip.invalidatePlaybackState()
|
||||
@@ -230,6 +233,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
|
||||
/// Unified cleanup for all PiP exit paths
|
||||
private func cleanupPip(notify: Bool, pause: Bool = false) {
|
||||
playerCore?.setPipSubtitleCompositing(false)
|
||||
playerCore?.isPipStarting = false
|
||||
playerCore?.isPipActive = false
|
||||
isManualPipRequest = false
|
||||
@@ -322,30 +326,32 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
}
|
||||
}
|
||||
|
||||
private func handleDispose(result: @escaping FlutterResult) {
|
||||
private func handleDispose(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
let args = call.arguments as? [String: Any]
|
||||
let preserveDisplayMode = args?["preserveDisplayMode"] as? Bool ?? false
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self else { result(nil); return }
|
||||
NSLog("[MpvPlayerPlugin] dispose preserveDisplayMode=%@", preserveDisplayMode.description)
|
||||
self.pipController?.teardown()
|
||||
self.pipController = nil
|
||||
self.autoPipEnabled = false
|
||||
self.pendingInlineRestoreAfterPip = false
|
||||
self.unregisterSceneActivationObserver()
|
||||
self.stopPipTimebaseSync()
|
||||
self.playerCore?.dispose()
|
||||
self.playerCore?.dispose(preserveDisplayCriteria: preserveDisplayMode)
|
||||
self.playerCore = nil
|
||||
result(nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleSetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
guard let args = call.arguments as? [String: Any],
|
||||
let name = args["name"] as? String,
|
||||
let value = args["value"] as? String
|
||||
else {
|
||||
result(
|
||||
FlutterError(
|
||||
code: "INVALID_ARGS", message: "Missing 'name' or 'value' argument",
|
||||
details: nil))
|
||||
func didSetPauseProperty(value: String) {
|
||||
pipController?.invalidatePlaybackState()
|
||||
if playerCore?.isPipActive == true { syncPipTimebase() }
|
||||
}
|
||||
|
||||
private func handleSetDisplayCriteria(call: FlutterMethodCall, result: @escaping FlutterResult) {
|
||||
guard let args = call.arguments as? [String: Any] else {
|
||||
result(FlutterError(code: "INVALID_ARGS", message: "Missing arguments", details: nil))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -354,13 +360,66 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
|
||||
return
|
||||
}
|
||||
|
||||
core.setPropertyAsync(name, value: value) { [weak self] _ in
|
||||
if name == "pause" {
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
if core.isPipActive == true { self?.syncPipTimebase() }
|
||||
let extraDelayMs = int64Value(args["extraDelayMs"]).map { Int(clamping: $0) } ?? 0
|
||||
guard let raw = args["criteria"] as? [String: Any] else {
|
||||
DispatchQueue.main.async {
|
||||
core.setServerDisplayCriteriaForPlayback(nil, extraDelayMs: extraDelayMs) {
|
||||
result(nil)
|
||||
}
|
||||
}
|
||||
result(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let criteria = ServerDisplayCriteria(
|
||||
doviProfile: int64Value(raw["doviProfile"]) ?? 0,
|
||||
doviLevel: int64Value(raw["doviLevel"]) ?? 0,
|
||||
doviCompatibilityId: int64Value(raw["doviCompatibilityId"]),
|
||||
fps: doubleValue(raw["fps"]) ?? 0,
|
||||
width: Int32(truncatingIfNeeded: int64Value(raw["width"]) ?? 0),
|
||||
height: Int32(truncatingIfNeeded: int64Value(raw["height"]) ?? 0),
|
||||
gamma: stringValue(raw["transfer"]),
|
||||
primaries: stringValue(raw["primaries"]),
|
||||
colorMatrix: stringValue(raw["matrix"])
|
||||
)
|
||||
DispatchQueue.main.async {
|
||||
core.setServerDisplayCriteriaForPlayback(criteria, extraDelayMs: extraDelayMs) {
|
||||
result(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func int64Value(_ value: Any?) -> Int64? {
|
||||
switch value {
|
||||
case let value as Int64:
|
||||
return value
|
||||
case let value as Int:
|
||||
return Int64(value)
|
||||
case let value as NSNumber:
|
||||
return value.int64Value
|
||||
case let value as String:
|
||||
return Int64(value)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func doubleValue(_ value: Any?) -> Double? {
|
||||
switch value {
|
||||
case let value as Double:
|
||||
return value
|
||||
case let value as NSNumber:
|
||||
return value.doubleValue
|
||||
case let value as String:
|
||||
return Double(value)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func stringValue(_ value: Any?) -> String? {
|
||||
guard let value else { return nil }
|
||||
let string = String(describing: value).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return string.isEmpty ? nil : string
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
@@ -432,13 +491,17 @@ extension MpvPlayerPlugin: MpvPipDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
func pipSkip(byInterval seconds: Double) {
|
||||
guard let playerCore = playerCore else { return }
|
||||
func pipSkip(byInterval seconds: Double, completion: @escaping () -> Void) {
|
||||
guard let playerCore = playerCore else {
|
||||
completion()
|
||||
return
|
||||
}
|
||||
let newTime = max(0, playerCore.timePos + seconds)
|
||||
playerCore.command(["seek", String(newTime), "absolute"])
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
|
||||
self?.syncPipTimebase()
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
playerCore.commandAsync(["seek", String(newTime), "absolute"]) { [weak self] _ in
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
|
||||
self?.pipController?.invalidatePlaybackState()
|
||||
completion()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
require 'dotenv/load'
|
||||
Dotenv.load("../../.env")
|
||||
require 'shellwords'
|
||||
|
||||
PROJECT_ROOT = File.expand_path("../..", __dir__)
|
||||
PROJECT_ROOT_ARG = Shellwords.escape(PROJECT_ROOT)
|
||||
|
||||
Dotenv.load(File.join(PROJECT_ROOT, ".env"))
|
||||
|
||||
default_platform(:ios)
|
||||
|
||||
platform :ios do
|
||||
desc "Build and deploy to App Store"
|
||||
lane :deploy_appstore do
|
||||
git_commit = `git rev-parse --short HEAD`.strip
|
||||
git_commit = `git -C #{PROJECT_ROOT_ARG} rev-parse --short HEAD`.strip
|
||||
|
||||
# Build the Flutter app
|
||||
sh("cd #{ENV['PWD']}/.. && flutter build ipa --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=app-store --split-debug-info=debug-info/ios")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && flutter build ipa --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=app-store --dart-define=SENTRY_DIST=app-store --split-debug-info=debug-info/ios")
|
||||
|
||||
# Upload debug symbols
|
||||
sh("cd #{ENV['PWD']}/.. && ./scripts/upload-symbols.sh ios")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=app-store ./scripts/upload-symbols.sh ios")
|
||||
|
||||
# Upload to App Store
|
||||
upload_to_app_store(
|
||||
|
||||
@@ -200,9 +200,13 @@ class JellyfinConnection extends Connection {
|
||||
@override
|
||||
final DateTime? lastAuthenticatedAt;
|
||||
|
||||
/// Server base URL, no trailing slash. e.g. `https://jellyfin.home.lan`.
|
||||
/// Active server base URL, no trailing slash. e.g. `https://jellyfin.home.lan`.
|
||||
final String baseUrl;
|
||||
|
||||
/// Candidate server URLs for this Jellyfin server, with [baseUrl] first.
|
||||
/// Existing installs only have [baseUrl]; deserialization backfills this.
|
||||
final List<String> baseUrls;
|
||||
|
||||
/// Server's reported name (System/Info).
|
||||
final String serverName;
|
||||
|
||||
@@ -230,6 +234,7 @@ class JellyfinConnection extends Connection {
|
||||
JellyfinConnection({
|
||||
required this.id,
|
||||
required this.baseUrl,
|
||||
List<String>? baseUrls,
|
||||
required this.serverName,
|
||||
required this.serverMachineId,
|
||||
required this.userId,
|
||||
@@ -240,7 +245,7 @@ class JellyfinConnection extends Connection {
|
||||
this.status = ConnectionStatus.unknown,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
});
|
||||
}) : baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
|
||||
|
||||
@override
|
||||
ConnectionKind get kind => ConnectionKind.jellyfin;
|
||||
@@ -252,16 +257,38 @@ class JellyfinConnection extends Connection {
|
||||
String get displayLabel => serverName;
|
||||
|
||||
@override
|
||||
String? get displaySubtitle => '$userName · ${_truncateUrl(baseUrl)}';
|
||||
String? get displaySubtitle {
|
||||
final extraCount = baseUrls.length - 1;
|
||||
final suffix = extraCount > 0 ? ' +$extraCount' : '';
|
||||
return '$userName · ${_truncateUrl(baseUrl)}$suffix';
|
||||
}
|
||||
|
||||
static String _truncateUrl(String url) {
|
||||
if (url.length <= 40) return url;
|
||||
return '${url.substring(0, 37)}…';
|
||||
}
|
||||
|
||||
static List<String> _normalizeBaseUrls(String activeBaseUrl, List<String>? urls) {
|
||||
final result = <String>[];
|
||||
final seen = <String>{};
|
||||
|
||||
void add(String url) {
|
||||
final trimmed = url.trim();
|
||||
if (trimmed.isEmpty || !seen.add(trimmed)) return;
|
||||
result.add(trimmed);
|
||||
}
|
||||
|
||||
add(activeBaseUrl);
|
||||
for (final url in urls ?? const <String>[]) {
|
||||
add(url);
|
||||
}
|
||||
return List.unmodifiable(result);
|
||||
}
|
||||
|
||||
JellyfinConnection copyWith({
|
||||
String? id,
|
||||
String? baseUrl,
|
||||
List<String>? baseUrls,
|
||||
String? serverName,
|
||||
String? serverMachineId,
|
||||
String? userId,
|
||||
@@ -273,9 +300,11 @@ class JellyfinConnection extends Connection {
|
||||
DateTime? createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
final nextBaseUrl = baseUrl ?? this.baseUrl;
|
||||
return JellyfinConnection(
|
||||
id: id ?? this.id,
|
||||
baseUrl: baseUrl ?? this.baseUrl,
|
||||
baseUrl: nextBaseUrl,
|
||||
baseUrls: baseUrls ?? this.baseUrls,
|
||||
serverName: serverName ?? this.serverName,
|
||||
serverMachineId: serverMachineId ?? this.serverMachineId,
|
||||
userId: userId ?? this.userId,
|
||||
@@ -293,6 +322,7 @@ class JellyfinConnection extends Connection {
|
||||
Map<String, Object?> toConfigJson() {
|
||||
return {
|
||||
'baseUrl': baseUrl,
|
||||
'baseUrls': baseUrls,
|
||||
'serverName': serverName,
|
||||
'serverMachineId': serverMachineId,
|
||||
'userId': userId,
|
||||
@@ -310,9 +340,16 @@ class JellyfinConnection extends Connection {
|
||||
required DateTime createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
final rawBaseUrls = json['baseUrls'];
|
||||
final baseUrls = rawBaseUrls is List ? rawBaseUrls.whereType<String>().toList(growable: false) : const <String>[];
|
||||
final rawBaseUrl = json['baseUrl'] as String?;
|
||||
final baseUrl = rawBaseUrl != null && rawBaseUrl.isNotEmpty
|
||||
? rawBaseUrl
|
||||
: (baseUrls.isNotEmpty ? baseUrls.first : '');
|
||||
return JellyfinConnection(
|
||||
id: id,
|
||||
baseUrl: json['baseUrl'] as String? ?? '',
|
||||
baseUrl: baseUrl,
|
||||
baseUrls: baseUrls,
|
||||
serverName: json['serverName'] as String? ?? 'Jellyfin',
|
||||
serverMachineId: json['serverMachineId'] as String? ?? '',
|
||||
userId: json['userId'] as String? ?? '',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'dart:io';
|
||||
import '../media/ids.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
@@ -60,7 +61,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase.forTesting(super.e);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 14;
|
||||
int get schemaVersion => 15;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
@@ -206,6 +207,13 @@ class AppDatabase extends _$AppDatabase {
|
||||
() => m.create(idxOfflineWatchProgressProfile),
|
||||
);
|
||||
}
|
||||
if (from < 15) {
|
||||
appLogger.i('Adding mediaSourceId column to DownloadedMedia (v15 migration)');
|
||||
await _ignoreAlreadyExists(
|
||||
'DownloadedMedia.mediaSourceId column',
|
||||
() => m.addColumn(downloadedMedia, downloadedMedia.mediaSourceId),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -251,7 +259,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
}
|
||||
|
||||
/// Get pending watch actions for a specific server
|
||||
Future<List<OfflineWatchProgressItem>> getPendingWatchActionsForServer(String serverId, {String? profileId}) {
|
||||
Future<List<OfflineWatchProgressItem>> getPendingWatchActionsForServer(ServerId serverId, {String? profileId}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
@@ -277,11 +285,57 @@ class AppDatabase extends _$AppDatabase {
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt)])
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)])
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
}
|
||||
|
||||
Future<List<OfflineWatchProgressItem>> getWatchActionsForKey(
|
||||
String globalKey, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
|
||||
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
}
|
||||
|
||||
Future<Map<String, List<OfflineWatchProgressItem>>> getWatchActionsForKeys(
|
||||
Set<String> globalKeys, {
|
||||
String? profileId,
|
||||
bool filterProfile = false,
|
||||
Map<String, String?>? clientScopeIdsByGlobalKey,
|
||||
}) async {
|
||||
if (globalKeys.isEmpty) return const {};
|
||||
final rows =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.isIn(globalKeys) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
|
||||
final result = <String, List<OfflineWatchProgressItem>>{};
|
||||
for (final action in rows) {
|
||||
if (clientScopeIdsByGlobalKey != null && clientScopeIdsByGlobalKey.containsKey(action.globalKey)) {
|
||||
final expectedScope = clientScopeIdsByGlobalKey[action.globalKey];
|
||||
if (!_clientScopeValuesMatch(action.clientScopeId, expectedScope)) continue;
|
||||
}
|
||||
result.putIfAbsent(action.globalKey, () => <OfflineWatchProgressItem>[]).add(action);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Get the latest actions for multiple items in a single query
|
||||
///
|
||||
/// Returns a map of globalKey -> latest action for each key.
|
||||
@@ -302,7 +356,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
t.globalKey.isIn(globalKeys) &
|
||||
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt)]))
|
||||
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
|
||||
.get();
|
||||
|
||||
// Group by globalKey and take the latest (first due to ordering)
|
||||
@@ -328,71 +382,75 @@ class AppDatabase extends _$AppDatabase {
|
||||
/// Insert or update a progress action (merges with existing).
|
||||
Future<void> upsertProgressAction({
|
||||
String? profileId,
|
||||
required String serverId,
|
||||
required ServerId serverId,
|
||||
String? clientScopeId,
|
||||
required String ratingKey,
|
||||
required int viewOffset,
|
||||
required int duration,
|
||||
required int? duration,
|
||||
required bool shouldMarkWatched,
|
||||
}) async {
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final globalKey = buildGlobalKey(ServerId(serverId), ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
// Check for existing progress entry
|
||||
final existing =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
_nullableTextPredicate(t.profileId, profileId) &
|
||||
_clientScopePredicate(t.clientScopeId, clientScopeId) &
|
||||
t.actionType.equals(OfflineActionType.progress.id),
|
||||
)
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
await transaction(() async {
|
||||
final existing =
|
||||
await (select(offlineWatchProgress)
|
||||
..where(
|
||||
(t) =>
|
||||
t.globalKey.equals(globalKey) &
|
||||
_nullableTextPredicate(t.profileId, profileId) &
|
||||
_clientScopePredicate(t.clientScopeId, clientScopeId) &
|
||||
t.actionType.equals(OfflineActionType.progress.id),
|
||||
)
|
||||
..orderBy([(t) => OrderingTerm.asc(t.id)]))
|
||||
.get();
|
||||
|
||||
if (existing != null) {
|
||||
// Update existing progress entry
|
||||
await (update(offlineWatchProgress)..where((t) => t.id.equals(existing.id))).write(
|
||||
OfflineWatchProgressCompanion(
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
updatedAt: Value(now),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Insert new progress entry
|
||||
await into(offlineWatchProgress).insert(
|
||||
OfflineWatchProgressCompanion.insert(
|
||||
serverId: serverId,
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
actionType: OfflineActionType.progress.id,
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
}
|
||||
final keep = existing.isEmpty ? null : existing.first;
|
||||
if (keep != null) {
|
||||
await (update(offlineWatchProgress)..where((t) => t.id.equals(keep.id))).write(
|
||||
OfflineWatchProgressCompanion(
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
updatedAt: Value(now),
|
||||
),
|
||||
);
|
||||
final duplicateIds = existing.skip(1).map((row) => row.id).toList(growable: false);
|
||||
if (duplicateIds.isNotEmpty) {
|
||||
await (delete(offlineWatchProgress)..where((t) => t.id.isIn(duplicateIds))).go();
|
||||
}
|
||||
} else {
|
||||
await into(offlineWatchProgress).insert(
|
||||
OfflineWatchProgressCompanion.insert(
|
||||
serverId: serverId,
|
||||
profileId: Value(profileId),
|
||||
clientScopeId: Value(clientScopeId),
|
||||
ratingKey: ratingKey,
|
||||
globalKey: globalKey,
|
||||
actionType: OfflineActionType.progress.id,
|
||||
viewOffset: Value(viewOffset),
|
||||
duration: Value(duration),
|
||||
shouldMarkWatched: Value(shouldMarkWatched),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Insert a manual watch action (watched or unwatched).
|
||||
/// Removes conflicting actions for the same item.
|
||||
Future<void> insertWatchAction({
|
||||
String? profileId,
|
||||
required String serverId,
|
||||
required ServerId serverId,
|
||||
String? clientScopeId,
|
||||
required String ratingKey,
|
||||
required String actionType, // 'watched' or 'unwatched'
|
||||
}) async {
|
||||
final globalKey = buildGlobalKey(serverId, ratingKey);
|
||||
final globalKey = buildGlobalKey(ServerId(serverId), ratingKey);
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
// Remove conflicting actions (opposite action type and progress)
|
||||
@@ -436,11 +494,14 @@ class AppDatabase extends _$AppDatabase {
|
||||
}
|
||||
|
||||
/// Get count of pending sync items
|
||||
Future<int> getPendingSyncCount({String? profileId}) async {
|
||||
Future<int> getPendingSyncCount({String? profileId, int? maxSyncAttempts}) async {
|
||||
final query = selectOnly(offlineWatchProgress)..addColumns([offlineWatchProgress.id.count()]);
|
||||
if (profileId != null) {
|
||||
query.where(offlineWatchProgress.profileId.equals(profileId));
|
||||
}
|
||||
if (maxSyncAttempts != null) {
|
||||
query.where(offlineWatchProgress.syncAttempts.isSmallerThanValue(maxSyncAttempts));
|
||||
}
|
||||
final count = await query.map((row) => row.read(offlineWatchProgress.id.count())).getSingle();
|
||||
return count ?? 0;
|
||||
}
|
||||
@@ -464,7 +525,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
|
||||
Future<void> insertSyncRule({
|
||||
String profileId = '',
|
||||
required String serverId,
|
||||
required ServerId serverId,
|
||||
required String ratingKey,
|
||||
required String globalKey,
|
||||
required String targetType,
|
||||
@@ -510,7 +571,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
if (profileId.isEmpty) return;
|
||||
final legacyRules = await (select(syncRules)..where((t) => t.profileId.equals(''))).get();
|
||||
for (final rule in legacyRules) {
|
||||
final scopedKey = buildProfileScopedGlobalKey(profileId, rule.serverId, rule.ratingKey);
|
||||
final scopedKey = buildProfileScopedGlobalKey(profileId, ServerId(rule.serverId), rule.ratingKey);
|
||||
final duplicate = await getSyncRule(scopedKey);
|
||||
if (duplicate != null) {
|
||||
await (delete(syncRules)..where((t) => t.id.equals(rule.id))).go();
|
||||
@@ -570,11 +631,7 @@ LazyDatabase _openConnection() {
|
||||
|
||||
// Migrate from old location on desktop (was in Documents subfolder)
|
||||
if (!Platform.isAndroid && !Platform.isIOS && !await file.exists()) {
|
||||
final oldFolder = await getApplicationDocumentsDirectory();
|
||||
final oldFile = File(p.join(oldFolder.path, 'plezy_downloads.db'));
|
||||
if (await oldFile.exists()) {
|
||||
await oldFile.rename(file.path);
|
||||
}
|
||||
await migrateLegacyDesktopDatabase(target: file);
|
||||
}
|
||||
|
||||
return NativeDatabase.createInBackground(
|
||||
@@ -589,3 +646,61 @@ LazyDatabase _openConnection() {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Move the legacy desktop DB from `Documents/` to `ApplicationSupport/`.
|
||||
/// `File.rename` only works within a single volume — Windows users with
|
||||
/// OneDrive-redirected Documents (or any cross-drive setup) hit
|
||||
/// `ERROR_NOT_SAME_DEVICE` (errno 17), and the uncaught throw used to
|
||||
/// strand the splash on "Loading servers..." forever (#1022). Falls back
|
||||
/// to copy + delete on any [FileSystemException] and swallows all errors
|
||||
/// so a failed migration never propagates fatally.
|
||||
///
|
||||
/// [sourceOverride] and [renameOverride] are test seams — production
|
||||
/// callers leave them null.
|
||||
Future<void> migrateLegacyDesktopDatabase({
|
||||
required File target,
|
||||
File? sourceOverride,
|
||||
Future<void> Function(File source, String targetPath)? renameOverride,
|
||||
}) async {
|
||||
final File oldFile;
|
||||
try {
|
||||
if (sourceOverride != null) {
|
||||
oldFile = sourceOverride;
|
||||
} else {
|
||||
final oldFolder = await getApplicationDocumentsDirectory();
|
||||
oldFile = File(p.join(oldFolder.path, 'plezy_downloads.db'));
|
||||
}
|
||||
if (!await oldFile.exists()) return;
|
||||
} catch (e, st) {
|
||||
appLogger.w('Legacy DB migration skipped before source lookup completed', error: e, stackTrace: st);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (renameOverride != null) {
|
||||
await renameOverride(oldFile, target.path);
|
||||
} else {
|
||||
await oldFile.rename(target.path);
|
||||
}
|
||||
appLogger.i('Moved legacy DB from ${oldFile.path} → ${target.path}');
|
||||
return;
|
||||
} on FileSystemException catch (e) {
|
||||
appLogger.w('Legacy DB rename failed (osError=${e.osError?.errorCode}); falling back to copy', error: e);
|
||||
}
|
||||
|
||||
try {
|
||||
await oldFile.copy(target.path);
|
||||
try {
|
||||
await oldFile.delete();
|
||||
} catch (e) {
|
||||
// Leaving the source behind is non-fatal — the new file is canonical.
|
||||
appLogger.w('Legacy DB copied but old file delete failed: $e');
|
||||
}
|
||||
appLogger.i('Copied legacy DB from ${oldFile.path} → ${target.path}');
|
||||
} catch (e, st) {
|
||||
// Copy itself failed (disk full, source locked by OneDrive sync,
|
||||
// permissions). Leave both files alone — drift will create a fresh
|
||||
// empty DB at the new location, and a future relaunch can retry.
|
||||
appLogger.e('Legacy DB migration failed entirely', error: e, stackTrace: st);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +221,17 @@ class $DownloadedMediaTable extends DownloadedMedia
|
||||
requiredDuringInsert: false,
|
||||
defaultValue: const Constant(0),
|
||||
);
|
||||
static const VerificationMeta _mediaSourceIdMeta = const VerificationMeta(
|
||||
'mediaSourceId',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<String> mediaSourceId = GeneratedColumn<String>(
|
||||
'media_source_id',
|
||||
aliasedName,
|
||||
true,
|
||||
type: DriftSqlType.string,
|
||||
requiredDuringInsert: false,
|
||||
);
|
||||
@override
|
||||
List<GeneratedColumn> get $columns => [
|
||||
id,
|
||||
@@ -242,6 +253,7 @@ class $DownloadedMediaTable extends DownloadedMedia
|
||||
retryCount,
|
||||
bgTaskId,
|
||||
mediaIndex,
|
||||
mediaSourceId,
|
||||
];
|
||||
@override
|
||||
String get aliasedName => _alias ?? actualTableName;
|
||||
@@ -397,6 +409,15 @@ class $DownloadedMediaTable extends DownloadedMedia
|
||||
mediaIndex.isAcceptableOrUnknown(data['media_index']!, _mediaIndexMeta),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('media_source_id')) {
|
||||
context.handle(
|
||||
_mediaSourceIdMeta,
|
||||
mediaSourceId.isAcceptableOrUnknown(
|
||||
data['media_source_id']!,
|
||||
_mediaSourceIdMeta,
|
||||
),
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -482,6 +503,10 @@ class $DownloadedMediaTable extends DownloadedMedia
|
||||
DriftSqlType.int,
|
||||
data['${effectivePrefix}media_index'],
|
||||
)!,
|
||||
mediaSourceId: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.string,
|
||||
data['${effectivePrefix}media_source_id'],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -512,6 +537,7 @@ class DownloadedMediaItem extends DataClass
|
||||
final int retryCount;
|
||||
final String? bgTaskId;
|
||||
final int mediaIndex;
|
||||
final String? mediaSourceId;
|
||||
const DownloadedMediaItem({
|
||||
required this.id,
|
||||
required this.serverId,
|
||||
@@ -532,6 +558,7 @@ class DownloadedMediaItem extends DataClass
|
||||
required this.retryCount,
|
||||
this.bgTaskId,
|
||||
required this.mediaIndex,
|
||||
this.mediaSourceId,
|
||||
});
|
||||
@override
|
||||
Map<String, Expression> toColumns(bool nullToAbsent) {
|
||||
@@ -573,6 +600,9 @@ class DownloadedMediaItem extends DataClass
|
||||
map['bg_task_id'] = Variable<String>(bgTaskId);
|
||||
}
|
||||
map['media_index'] = Variable<int>(mediaIndex);
|
||||
if (!nullToAbsent || mediaSourceId != null) {
|
||||
map['media_source_id'] = Variable<String>(mediaSourceId);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -615,6 +645,9 @@ class DownloadedMediaItem extends DataClass
|
||||
? const Value.absent()
|
||||
: Value(bgTaskId),
|
||||
mediaIndex: Value(mediaIndex),
|
||||
mediaSourceId: mediaSourceId == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
: Value(mediaSourceId),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -645,6 +678,7 @@ class DownloadedMediaItem extends DataClass
|
||||
retryCount: serializer.fromJson<int>(json['retryCount']),
|
||||
bgTaskId: serializer.fromJson<String?>(json['bgTaskId']),
|
||||
mediaIndex: serializer.fromJson<int>(json['mediaIndex']),
|
||||
mediaSourceId: serializer.fromJson<String?>(json['mediaSourceId']),
|
||||
);
|
||||
}
|
||||
@override
|
||||
@@ -670,6 +704,7 @@ class DownloadedMediaItem extends DataClass
|
||||
'retryCount': serializer.toJson<int>(retryCount),
|
||||
'bgTaskId': serializer.toJson<String?>(bgTaskId),
|
||||
'mediaIndex': serializer.toJson<int>(mediaIndex),
|
||||
'mediaSourceId': serializer.toJson<String?>(mediaSourceId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -693,6 +728,7 @@ class DownloadedMediaItem extends DataClass
|
||||
int? retryCount,
|
||||
Value<String?> bgTaskId = const Value.absent(),
|
||||
int? mediaIndex,
|
||||
Value<String?> mediaSourceId = const Value.absent(),
|
||||
}) => DownloadedMediaItem(
|
||||
id: id ?? this.id,
|
||||
serverId: serverId ?? this.serverId,
|
||||
@@ -721,6 +757,9 @@ class DownloadedMediaItem extends DataClass
|
||||
retryCount: retryCount ?? this.retryCount,
|
||||
bgTaskId: bgTaskId.present ? bgTaskId.value : this.bgTaskId,
|
||||
mediaIndex: mediaIndex ?? this.mediaIndex,
|
||||
mediaSourceId: mediaSourceId.present
|
||||
? mediaSourceId.value
|
||||
: this.mediaSourceId,
|
||||
);
|
||||
DownloadedMediaItem copyWithCompanion(DownloadedMediaCompanion data) {
|
||||
return DownloadedMediaItem(
|
||||
@@ -763,6 +802,9 @@ class DownloadedMediaItem extends DataClass
|
||||
mediaIndex: data.mediaIndex.present
|
||||
? data.mediaIndex.value
|
||||
: this.mediaIndex,
|
||||
mediaSourceId: data.mediaSourceId.present
|
||||
? data.mediaSourceId.value
|
||||
: this.mediaSourceId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -787,7 +829,8 @@ class DownloadedMediaItem extends DataClass
|
||||
..write('errorMessage: $errorMessage, ')
|
||||
..write('retryCount: $retryCount, ')
|
||||
..write('bgTaskId: $bgTaskId, ')
|
||||
..write('mediaIndex: $mediaIndex')
|
||||
..write('mediaIndex: $mediaIndex, ')
|
||||
..write('mediaSourceId: $mediaSourceId')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
@@ -813,6 +856,7 @@ class DownloadedMediaItem extends DataClass
|
||||
retryCount,
|
||||
bgTaskId,
|
||||
mediaIndex,
|
||||
mediaSourceId,
|
||||
);
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
@@ -836,7 +880,8 @@ class DownloadedMediaItem extends DataClass
|
||||
other.errorMessage == this.errorMessage &&
|
||||
other.retryCount == this.retryCount &&
|
||||
other.bgTaskId == this.bgTaskId &&
|
||||
other.mediaIndex == this.mediaIndex);
|
||||
other.mediaIndex == this.mediaIndex &&
|
||||
other.mediaSourceId == this.mediaSourceId);
|
||||
}
|
||||
|
||||
class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
@@ -859,6 +904,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
final Value<int> retryCount;
|
||||
final Value<String?> bgTaskId;
|
||||
final Value<int> mediaIndex;
|
||||
final Value<String?> mediaSourceId;
|
||||
const DownloadedMediaCompanion({
|
||||
this.id = const Value.absent(),
|
||||
this.serverId = const Value.absent(),
|
||||
@@ -879,6 +925,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
this.retryCount = const Value.absent(),
|
||||
this.bgTaskId = const Value.absent(),
|
||||
this.mediaIndex = const Value.absent(),
|
||||
this.mediaSourceId = const Value.absent(),
|
||||
});
|
||||
DownloadedMediaCompanion.insert({
|
||||
this.id = const Value.absent(),
|
||||
@@ -900,6 +947,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
this.retryCount = const Value.absent(),
|
||||
this.bgTaskId = const Value.absent(),
|
||||
this.mediaIndex = const Value.absent(),
|
||||
this.mediaSourceId = const Value.absent(),
|
||||
}) : serverId = Value(serverId),
|
||||
ratingKey = Value(ratingKey),
|
||||
globalKey = Value(globalKey),
|
||||
@@ -925,6 +973,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
Expression<int>? retryCount,
|
||||
Expression<String>? bgTaskId,
|
||||
Expression<int>? mediaIndex,
|
||||
Expression<String>? mediaSourceId,
|
||||
}) {
|
||||
return RawValuesInsertable({
|
||||
if (id != null) 'id': id,
|
||||
@@ -947,6 +996,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
if (retryCount != null) 'retry_count': retryCount,
|
||||
if (bgTaskId != null) 'bg_task_id': bgTaskId,
|
||||
if (mediaIndex != null) 'media_index': mediaIndex,
|
||||
if (mediaSourceId != null) 'media_source_id': mediaSourceId,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -970,6 +1020,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
Value<int>? retryCount,
|
||||
Value<String?>? bgTaskId,
|
||||
Value<int>? mediaIndex,
|
||||
Value<String?>? mediaSourceId,
|
||||
}) {
|
||||
return DownloadedMediaCompanion(
|
||||
id: id ?? this.id,
|
||||
@@ -991,6 +1042,7 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
retryCount: retryCount ?? this.retryCount,
|
||||
bgTaskId: bgTaskId ?? this.bgTaskId,
|
||||
mediaIndex: mediaIndex ?? this.mediaIndex,
|
||||
mediaSourceId: mediaSourceId ?? this.mediaSourceId,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1056,6 +1108,9 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
if (mediaIndex.present) {
|
||||
map['media_index'] = Variable<int>(mediaIndex.value);
|
||||
}
|
||||
if (mediaSourceId.present) {
|
||||
map['media_source_id'] = Variable<String>(mediaSourceId.value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -1080,7 +1135,8 @@ class DownloadedMediaCompanion extends UpdateCompanion<DownloadedMediaItem> {
|
||||
..write('errorMessage: $errorMessage, ')
|
||||
..write('retryCount: $retryCount, ')
|
||||
..write('bgTaskId: $bgTaskId, ')
|
||||
..write('mediaIndex: $mediaIndex')
|
||||
..write('mediaIndex: $mediaIndex, ')
|
||||
..write('mediaSourceId: $mediaSourceId')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
@@ -5319,6 +5375,7 @@ typedef $$DownloadedMediaTableCreateCompanionBuilder =
|
||||
Value<int> retryCount,
|
||||
Value<String?> bgTaskId,
|
||||
Value<int> mediaIndex,
|
||||
Value<String?> mediaSourceId,
|
||||
});
|
||||
typedef $$DownloadedMediaTableUpdateCompanionBuilder =
|
||||
DownloadedMediaCompanion Function({
|
||||
@@ -5341,6 +5398,7 @@ typedef $$DownloadedMediaTableUpdateCompanionBuilder =
|
||||
Value<int> retryCount,
|
||||
Value<String?> bgTaskId,
|
||||
Value<int> mediaIndex,
|
||||
Value<String?> mediaSourceId,
|
||||
});
|
||||
|
||||
class $$DownloadedMediaTableFilterComposer
|
||||
@@ -5446,6 +5504,11 @@ class $$DownloadedMediaTableFilterComposer
|
||||
column: $table.mediaIndex,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<String> get mediaSourceId => $composableBuilder(
|
||||
column: $table.mediaSourceId,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$DownloadedMediaTableOrderingComposer
|
||||
@@ -5551,6 +5614,11 @@ class $$DownloadedMediaTableOrderingComposer
|
||||
column: $table.mediaIndex,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<String> get mediaSourceId => $composableBuilder(
|
||||
column: $table.mediaSourceId,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$DownloadedMediaTableAnnotationComposer
|
||||
@@ -5638,6 +5706,11 @@ class $$DownloadedMediaTableAnnotationComposer
|
||||
column: $table.mediaIndex,
|
||||
builder: (column) => column,
|
||||
);
|
||||
|
||||
GeneratedColumn<String> get mediaSourceId => $composableBuilder(
|
||||
column: $table.mediaSourceId,
|
||||
builder: (column) => column,
|
||||
);
|
||||
}
|
||||
|
||||
class $$DownloadedMediaTableTableManager
|
||||
@@ -5696,6 +5769,7 @@ class $$DownloadedMediaTableTableManager
|
||||
Value<int> retryCount = const Value.absent(),
|
||||
Value<String?> bgTaskId = const Value.absent(),
|
||||
Value<int> mediaIndex = const Value.absent(),
|
||||
Value<String?> mediaSourceId = const Value.absent(),
|
||||
}) => DownloadedMediaCompanion(
|
||||
id: id,
|
||||
serverId: serverId,
|
||||
@@ -5716,6 +5790,7 @@ class $$DownloadedMediaTableTableManager
|
||||
retryCount: retryCount,
|
||||
bgTaskId: bgTaskId,
|
||||
mediaIndex: mediaIndex,
|
||||
mediaSourceId: mediaSourceId,
|
||||
),
|
||||
createCompanionCallback:
|
||||
({
|
||||
@@ -5738,6 +5813,7 @@ class $$DownloadedMediaTableTableManager
|
||||
Value<int> retryCount = const Value.absent(),
|
||||
Value<String?> bgTaskId = const Value.absent(),
|
||||
Value<int> mediaIndex = const Value.absent(),
|
||||
Value<String?> mediaSourceId = const Value.absent(),
|
||||
}) => DownloadedMediaCompanion.insert(
|
||||
id: id,
|
||||
serverId: serverId,
|
||||
@@ -5758,6 +5834,7 @@ class $$DownloadedMediaTableTableManager
|
||||
retryCount: retryCount,
|
||||
bgTaskId: bgTaskId,
|
||||
mediaIndex: mediaIndex,
|
||||
mediaSourceId: mediaSourceId,
|
||||
),
|
||||
withReferenceMapper: (p0) => p0
|
||||
.map((e) => (e.readTable(table), BaseReferences(db, table, e)))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import '../media/ids.dart';
|
||||
|
||||
import 'app_database.dart';
|
||||
import '../models/download_models.dart';
|
||||
@@ -76,7 +77,7 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
}
|
||||
|
||||
Future<void> insertDownload({
|
||||
required String serverId,
|
||||
required ServerId serverId,
|
||||
String? clientScopeId,
|
||||
required String ratingKey,
|
||||
required String globalKey,
|
||||
@@ -85,6 +86,7 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
String? grandparentRatingKey,
|
||||
required int status,
|
||||
int mediaIndex = 0,
|
||||
String? mediaSourceId,
|
||||
}) async {
|
||||
await into(downloadedMedia).insert(
|
||||
DownloadedMediaCompanion.insert(
|
||||
@@ -97,6 +99,7 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
grandparentRatingKey: Value(grandparentRatingKey),
|
||||
status: status,
|
||||
mediaIndex: Value(mediaIndex),
|
||||
mediaSourceId: Value(mediaSourceId),
|
||||
),
|
||||
mode: InsertMode.insertOrReplace,
|
||||
);
|
||||
@@ -145,6 +148,12 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
)..where((t) => t.globalKey.equals(globalKey))).write(DownloadedMediaCompanion(status: Value(status)));
|
||||
}
|
||||
|
||||
Future<void> updateDownloadMediaSource(String globalKey, String? mediaSourceId) async {
|
||||
await (update(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
DownloadedMediaCompanion(mediaSourceId: Value(mediaSourceId)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> updateDownloadProgress(String globalKey, int progress, int downloadedBytes, int totalBytes) async {
|
||||
await (update(downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
DownloadedMediaCompanion(
|
||||
@@ -201,14 +210,14 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
|
||||
Future<List<DownloadedMediaItem>> getEpisodesBySeason(
|
||||
String seasonKey, {
|
||||
String? serverId,
|
||||
ServerId? serverId,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(downloadedMedia)..where(
|
||||
(t) =>
|
||||
t.parentRatingKey.equals(seasonKey) &
|
||||
_optionalServerPredicate(t.serverId, serverId) &
|
||||
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
|
||||
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
|
||||
))
|
||||
.get();
|
||||
@@ -216,24 +225,24 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
|
||||
Future<List<DownloadedMediaItem>> getEpisodesByShow(
|
||||
String showKey, {
|
||||
String? serverId,
|
||||
ServerId? serverId,
|
||||
String? clientScopeId,
|
||||
bool filterClientScope = false,
|
||||
}) {
|
||||
return (select(downloadedMedia)..where(
|
||||
(t) =>
|
||||
t.grandparentRatingKey.equals(showKey) &
|
||||
_optionalServerPredicate(t.serverId, serverId) &
|
||||
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
|
||||
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
|
||||
))
|
||||
.get();
|
||||
}
|
||||
|
||||
Future<List<DownloadedMediaItem>> getDownloadsByServerId(String serverId) {
|
||||
Future<List<DownloadedMediaItem>> getDownloadsByServerId(ServerId serverId) {
|
||||
return (select(downloadedMedia)..where((t) => t.serverId.equals(serverId))).get();
|
||||
}
|
||||
|
||||
Expression<bool> _optionalServerPredicate(GeneratedColumn<String> column, String? serverId) {
|
||||
Expression<bool> _optionalServerPredicate(GeneratedColumn<String> column, ServerId? serverId) {
|
||||
return serverId == null ? const Constant(true) : column.equals(serverId);
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ class DownloadedMedia extends Table {
|
||||
IntColumn get retryCount => integer().withDefault(const Constant(0))();
|
||||
TextColumn get bgTaskId => text().nullable()();
|
||||
IntColumn get mediaIndex => integer().withDefault(const Constant(0))();
|
||||
TextColumn get mediaSourceId => text().nullable()();
|
||||
}
|
||||
|
||||
/// Profile ownership for shared physical downloads.
|
||||
|
||||
@@ -93,5 +93,12 @@ class MediaServerHttpException extends MediaServerException {
|
||||
type == MediaServerHttpErrorType.receiveTimeout;
|
||||
|
||||
@override
|
||||
String toString() => 'MediaServerHttpException(${type.name}: $message)';
|
||||
String toString() {
|
||||
final parts = <String>[type.name];
|
||||
if (statusCode != null) parts.add('HTTP $statusCode');
|
||||
if (message.isNotEmpty) parts.add(message);
|
||||
final uri = requestUri;
|
||||
if (uri != null) parts.add('${uri.host}${uri.path}');
|
||||
return 'MediaServerHttpException(${parts.join(': ')})';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'focus_theme.dart';
|
||||
|
||||
/// Exposes the focus state of an enclosing focus wrapper to a descendant
|
||||
/// [CardFocusBorder] that draws the focus border itself.
|
||||
///
|
||||
/// Wrappers ([FocusableWrapper]/[FocusBuilders.buildFocusableCard]) insert this
|
||||
/// instead of painting a border when `delegateFocusBorder` is set, so cards can
|
||||
/// put the border on the exact rect the design highlights (the poster image,
|
||||
/// not the card-plus-captions rect — issue #1278). Only the [CardFocusBorder]
|
||||
/// element registers a dependency, so a focus flip rebuilds just that border
|
||||
/// box: a stable `child:` card subtree (e.g. the TV rail's MediaCard) is not
|
||||
/// rebuilt.
|
||||
class CardFocusScope extends InheritedWidget {
|
||||
const CardFocusScope({super.key, required this.showFocus, required super.child});
|
||||
|
||||
/// Whether the enclosing wrapper currently shows focus visuals
|
||||
/// (focused while in keyboard/d-pad input mode).
|
||||
final bool showFocus;
|
||||
|
||||
/// Null when no delegating wrapper is above (touch mode skips the focus
|
||||
/// wrappers entirely) — [CardFocusBorder] then renders its child bare.
|
||||
static bool? maybeOf(BuildContext context) => context.dependOnInheritedWidgetOfExactType<CardFocusScope>()?.showFocus;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(CardFocusScope oldWidget) => showFocus != oldWidget.showFocus;
|
||||
}
|
||||
|
||||
/// Draws the focus border around its child based on the enclosing
|
||||
/// [CardFocusScope], letting the card decide which rect gets highlighted.
|
||||
///
|
||||
/// Defaults to an outside stroke so the border hugs the child exactly like the
|
||||
/// full-bleed card treatment (the child's own corner radius nests inside it).
|
||||
/// Decoration only — never affects layout. Renders the child unchanged when no
|
||||
/// scope is present.
|
||||
class CardFocusBorder extends StatelessWidget {
|
||||
const CardFocusBorder({
|
||||
super.key,
|
||||
required this.borderRadius,
|
||||
this.strokeAlign = BorderSide.strokeAlignOutside,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final double borderRadius;
|
||||
final double strokeAlign;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final showFocus = CardFocusScope.maybeOf(context);
|
||||
if (showFocus == null) return child;
|
||||
|
||||
return AnimatedContainer(
|
||||
duration: FocusTheme.getAnimationDuration(context),
|
||||
curve: Curves.easeOutCubic,
|
||||
foregroundDecoration: FocusTheme.focusDecoration(
|
||||
context,
|
||||
isFocused: showFocus,
|
||||
borderRadius: borderRadius,
|
||||
borderStrokeAlign: strokeAlign,
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,19 +5,22 @@ import 'package:flutter/services.dart';
|
||||
extension KeyEventActionable on KeyEvent {
|
||||
bool get isActionable => this is KeyDownEvent || this is KeyRepeatEvent;
|
||||
bool get isPhysicalKeyboardEvent => deviceType == ui.KeyEventDeviceType.keyboard;
|
||||
// Only true keyboard submit keys belong here. LogicalKeyboardKey.select is
|
||||
// a TV-remote / dpad-center key (Android DPAD_CENTER, tvOS UIPressTypeSelect)
|
||||
// — USB keyboards never emit it. The custom Flutter tvOS engine reports its
|
||||
// synthesized Siri Remote presses with deviceType=keyboard, so classifying
|
||||
// select-with-keyboard-deviceType as a "keyboard enter" would route center
|
||||
// dpad through TextField submit and skip the TV virtual keyboard.
|
||||
bool get isPhysicalKeyboardEnter =>
|
||||
deviceType == ui.KeyEventDeviceType.keyboard &&
|
||||
(logicalKey == LogicalKeyboardKey.enter ||
|
||||
logicalKey == LogicalKeyboardKey.numpadEnter ||
|
||||
logicalKey == LogicalKeyboardKey.select);
|
||||
(logicalKey == LogicalKeyboardKey.enter || logicalKey == LogicalKeyboardKey.numpadEnter);
|
||||
|
||||
bool get isTvSelectEvent {
|
||||
if (isPhysicalKeyboardEvent) return false;
|
||||
// Dpad-center / gamepad-A are TV-remote-only — always treat as TV select,
|
||||
// regardless of the deviceType claim from the engine.
|
||||
if (logicalKey == LogicalKeyboardKey.select || logicalKey == LogicalKeyboardKey.gameButtonA) return true;
|
||||
if (logicalKey == LogicalKeyboardKey.enter || logicalKey == LogicalKeyboardKey.numpadEnter) {
|
||||
return deviceType != ui.KeyEventDeviceType.keyboard;
|
||||
}
|
||||
return false;
|
||||
if (isPhysicalKeyboardEvent) return false;
|
||||
return logicalKey == LogicalKeyboardKey.enter || logicalKey == LogicalKeyboardKey.numpadEnter;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,35 +99,17 @@ class SelectKeyUpSuppressor {
|
||||
|
||||
/// Global helper to suppress the next BACK key-up event.
|
||||
///
|
||||
/// Use this when a modal (bottom sheet, dialog) closes to prevent
|
||||
/// the BACK key-up from propagating to the underlying screen.
|
||||
/// Armed when a modal (dialog, sheet) closes while a back key is still held —
|
||||
/// e.g. by [BackKeySuppressorObserver] when a route pops mid-press — so the
|
||||
/// in-flight key-up doesn't propagate to the underlying screen's back handler.
|
||||
class BackKeyUpSuppressor {
|
||||
static final _instance = _KeyUpSuppressor((k) => k.isBackKey);
|
||||
static bool _closedViaBackKey = false;
|
||||
|
||||
/// Mark that a modal is being closed via back key press.
|
||||
/// Call this before Navigator.pop() in back key handlers.
|
||||
static void markClosedViaBackKey() {
|
||||
_closedViaBackKey = true;
|
||||
}
|
||||
|
||||
/// Request suppression of back key-up events.
|
||||
/// Suppression is skipped if the modal was closed via back key
|
||||
/// (since the key-up already triggered the close).
|
||||
static void suppressBackUntilKeyUp() {
|
||||
if (_closedViaBackKey) {
|
||||
_closedViaBackKey = false;
|
||||
return;
|
||||
}
|
||||
_instance.suppress();
|
||||
}
|
||||
static void suppressBackUntilKeyUp() => _instance.suppress();
|
||||
|
||||
/// Clear any pending suppression. Call when opening a new modal
|
||||
/// to ensure stale suppression from previous closes doesn't affect it.
|
||||
static void clearSuppression() {
|
||||
_instance.clearSuppression();
|
||||
_closedViaBackKey = false;
|
||||
}
|
||||
static void clearSuppression() => _instance.clearSuppression();
|
||||
|
||||
static bool consumeIfSuppressed(KeyEvent event) => _instance.consumeIfSuppressed(event);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../services/device_performance.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import 'focus_theme.dart';
|
||||
|
||||
/// Renders the focus glow for a focused card in the root [Overlay] so it paints
|
||||
/// ABOVE sibling cards on all four sides.
|
||||
///
|
||||
/// The glow is an outward blur ([FocusTheme.focusGlowShadows]). When drawn
|
||||
/// in-tree behind a packed rail/grid it is occluded by later-painted neighbours
|
||||
/// on the trailing edges and only escapes on the leading (left) edge — producing
|
||||
/// a one-sided halo (issue #1231). Lifting it into an [OverlayPortal] that
|
||||
/// follows the card via [LayerLink] makes it render above every sibling, so the
|
||||
/// glow is symmetric on all sides. The crisp focus border stays in-card; only
|
||||
/// the glow moves to the overlay.
|
||||
///
|
||||
/// Only mounts the overlay/leader while the card is focused (or fading out), so
|
||||
/// there is at most one [LeaderLayer] on screen regardless of how many cards a
|
||||
/// grid builds.
|
||||
class FocusGlowOverlay extends StatefulWidget {
|
||||
const FocusGlowOverlay({
|
||||
super.key,
|
||||
required this.isFocused,
|
||||
required this.borderRadius,
|
||||
required this.color,
|
||||
required this.child,
|
||||
this.glowSize,
|
||||
});
|
||||
|
||||
/// Whether the wrapped card currently shows focus. Drives the glow.
|
||||
final bool isFocused;
|
||||
|
||||
/// Border radius of the card, used for the glow's rounded rect.
|
||||
final double borderRadius;
|
||||
|
||||
/// Glow colour, resolved from the card's theme at the call site (the overlay
|
||||
/// builds in the root Overlay's context, which may not carry a nested theme).
|
||||
final Color color;
|
||||
|
||||
/// Explicit card size. When null, falls back to [LayerLink.leaderSize] (one
|
||||
/// frame late on first show, hidden under the opacity-0 fade-in).
|
||||
final Size? glowSize;
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<FocusGlowOverlay> createState() => _FocusGlowOverlayState();
|
||||
}
|
||||
|
||||
class _FocusGlowOverlayState extends State<FocusGlowOverlay> {
|
||||
final OverlayPortalController _controller = OverlayPortalController();
|
||||
final LayerLink _link = LayerLink();
|
||||
|
||||
/// Drives the [AnimatedOpacity] target. Set false on focus loss so the glow
|
||||
/// fades out before the portal is hidden in [_handleFadeEnd].
|
||||
bool _visible = false;
|
||||
|
||||
/// Glow is skipped on the reduced effects tier (blurred shadows + fade
|
||||
/// saveLayer are too expensive on weak GPUs) and when the user turned the
|
||||
/// Focus Glow setting off (#1278). The crisp focus border remains.
|
||||
static bool get _disabled => DevicePerformance.isReduced || !SettingsService.instance.read(SettingsService.focusGlow);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.isFocused && !_disabled) {
|
||||
_visible = true;
|
||||
_controller.show();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(FocusGlowOverlay oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (_disabled) return;
|
||||
if (widget.isFocused == oldWidget.isFocused) return;
|
||||
if (widget.isFocused) {
|
||||
_controller.show();
|
||||
// Start hidden, then fade in next frame.
|
||||
_visible = false;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && widget.isFocused) setState(() => _visible = true);
|
||||
});
|
||||
} else {
|
||||
// Fade out; _handleFadeEnd hides the portal once opacity reaches 0.
|
||||
setState(() => _visible = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _handleFadeEnd() {
|
||||
if (!_visible && mounted && _controller.isShowing) {
|
||||
_controller.hide();
|
||||
setState(() {}); // drop the OverlayPortal/leader from the tree
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_disabled) return widget.child;
|
||||
|
||||
// Gate the LeaderLayer to the focused card only: when not focused and not
|
||||
// mid-fade, return the bare child (no OverlayPortal, no leader).
|
||||
if (!widget.isFocused && !_controller.isShowing) {
|
||||
return widget.child;
|
||||
}
|
||||
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
|
||||
return OverlayPortal(
|
||||
controller: _controller,
|
||||
overlayChildBuilder: (overlayContext) {
|
||||
final size = widget.glowSize ?? _link.leaderSize;
|
||||
final extent = FocusTheme.focusGlowExtent;
|
||||
|
||||
return CompositedTransformFollower(
|
||||
link: _link,
|
||||
targetAnchor: Alignment.topLeft,
|
||||
followerAnchor: Alignment.topLeft,
|
||||
offset: Offset(-extent, -extent),
|
||||
child: IgnorePointer(
|
||||
child: AnimatedOpacity(
|
||||
opacity: _visible ? 1.0 : 0.0,
|
||||
duration: duration,
|
||||
curve: Curves.easeOutCubic,
|
||||
onEnd: _handleFadeEnd,
|
||||
child: size == null
|
||||
? const SizedBox.shrink()
|
||||
: CustomPaint(
|
||||
size: Size(size.width + extent * 2, size.height + extent * 2),
|
||||
painter: _FocusGlowPainter(
|
||||
rect: Offset(extent, extent) & size,
|
||||
borderRadius: widget.borderRadius,
|
||||
shadows: FocusTheme.focusGlowShadows(widget.color),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: CompositedTransformTarget(link: _link, child: widget.child),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints [shadows] around [rect] with the rect interior clipped out, so only
|
||||
/// the outer glow shows — matching the original look where the opaque card hid
|
||||
/// the inner part of the shadow.
|
||||
class _FocusGlowPainter extends CustomPainter {
|
||||
const _FocusGlowPainter({required this.rect, required this.borderRadius, required this.shadows});
|
||||
|
||||
final Rect rect;
|
||||
final double borderRadius;
|
||||
final List<BoxShadow> shadows;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final rrect = RRect.fromRectAndRadius(rect, Radius.circular(borderRadius));
|
||||
final clip = Path.combine(PathOperation.difference, Path()..addRect(Offset.zero & size), Path()..addRRect(rrect));
|
||||
canvas.save();
|
||||
canvas.clipPath(clip);
|
||||
for (final shadow in shadows) {
|
||||
canvas.drawRRect(rrect.shift(shadow.offset).inflate(shadow.spreadRadius), shadow.toPaint());
|
||||
}
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_FocusGlowPainter oldDelegate) {
|
||||
return oldDelegate.rect != rect ||
|
||||
oldDelegate.borderRadius != borderRadius ||
|
||||
!listEquals(oldDelegate.shadows, shadows);
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,7 @@ class FocusMemoryTracker {
|
||||
final String _debugLabelPrefix;
|
||||
String? _lastFocusedKey;
|
||||
|
||||
FocusMemoryTracker({VoidCallback? onFocusChanged, String debugLabelPrefix = 'focus'})
|
||||
: _onFocusChanged = onFocusChanged,
|
||||
_debugLabelPrefix = debugLabelPrefix;
|
||||
FocusMemoryTracker({this._onFocusChanged, this._debugLabelPrefix = 'focus'});
|
||||
|
||||
/// Get or create a focus node for the given key
|
||||
FocusNode get(String key, {String? debugLabel}) {
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../services/device_performance.dart';
|
||||
import '../theme/mono_tokens.dart';
|
||||
|
||||
class FocusTheme {
|
||||
FocusTheme._();
|
||||
|
||||
static const double focusScale = 1.02;
|
||||
static const double fullCardFocusScale = 1.03;
|
||||
static const double focusBorderWidth = 2.5;
|
||||
static const double defaultBorderRadius = 8.0;
|
||||
static const double focusGlowInnerBlurRadius = 18;
|
||||
static const double focusGlowOuterBlurRadius = 34;
|
||||
static const double focusGlowSpreadRadius = 1.5;
|
||||
|
||||
static Color getFocusBorderColor(BuildContext context) {
|
||||
return Theme.of(context).colorScheme.primary;
|
||||
}
|
||||
|
||||
static Duration getAnimationDuration(BuildContext context) {
|
||||
// Reduced tier: snap focus transitions (scale/border/glow) instead of
|
||||
// animating — each animation frame re-rasterizes the focused card.
|
||||
if (DevicePerformance.isReduced) return Duration.zero;
|
||||
return Theme.of(context).extension<MonoTokens>()?.fast ?? const Duration(milliseconds: 150);
|
||||
}
|
||||
|
||||
@@ -20,16 +28,41 @@ class FocusTheme {
|
||||
BuildContext context, {
|
||||
required bool isFocused,
|
||||
double borderRadius = defaultBorderRadius,
|
||||
double borderStrokeAlign = BorderSide.strokeAlignInside,
|
||||
Color? color,
|
||||
}) {
|
||||
final focusColor = color ?? getFocusBorderColor(context);
|
||||
|
||||
return BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(borderRadius),
|
||||
border: Border.all(color: isFocused ? focusColor : Colors.transparent, width: focusBorderWidth),
|
||||
border: Border.all(
|
||||
color: isFocused ? focusColor : Colors.transparent,
|
||||
width: focusBorderWidth,
|
||||
strokeAlign: borderStrokeAlign,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The focus glow as a list of [BoxShadow]s.
|
||||
///
|
||||
/// Rendered by [FocusGlowOverlay] in the root overlay so the glow paints
|
||||
/// above sibling cards on all four sides (an in-tree background shadow is
|
||||
/// occluded by later-painted neighbours, which produced the one-sided halo).
|
||||
static List<BoxShadow> focusGlowShadows(Color color) {
|
||||
return [
|
||||
BoxShadow(
|
||||
color: color.withValues(alpha: 0.34),
|
||||
blurRadius: focusGlowInnerBlurRadius,
|
||||
spreadRadius: focusGlowSpreadRadius,
|
||||
),
|
||||
BoxShadow(color: color.withValues(alpha: 0.2), blurRadius: focusGlowOuterBlurRadius),
|
||||
];
|
||||
}
|
||||
|
||||
/// How far the focus glow visibly reaches beyond the card edge. Used to size
|
||||
/// the overlay paint area so the blur is not clipped.
|
||||
static double get focusGlowExtent => focusGlowOuterBlurRadius * 2 + focusGlowSpreadRadius;
|
||||
|
||||
/// Build focus decoration with background color instead of border.
|
||||
/// Useful for video controls where it should match the native hover style.
|
||||
static BoxDecoration focusBackgroundDecoration({required bool isFocused, double borderRadius = defaultBorderRadius}) {
|
||||
|
||||
@@ -1,26 +1,54 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../widgets/app_icon.dart';
|
||||
import '../widgets/clickable_cursor.dart';
|
||||
import 'focus_theme.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
import 'key_event_utils.dart';
|
||||
|
||||
typedef FocusableActionBuilder = Widget Function(BuildContext context, FocusableActionBuildState state);
|
||||
|
||||
class FocusableActionBuildState {
|
||||
final FocusNode focusNode;
|
||||
final bool isFocused;
|
||||
final bool showFocus;
|
||||
final bool isKeyboardMode;
|
||||
final Duration animationDuration;
|
||||
|
||||
const FocusableActionBuildState({
|
||||
required this.focusNode,
|
||||
required this.isFocused,
|
||||
required this.showFocus,
|
||||
required this.isKeyboardMode,
|
||||
required this.animationDuration,
|
||||
});
|
||||
}
|
||||
|
||||
class FocusableAction {
|
||||
final IconData icon;
|
||||
final Color? iconColor;
|
||||
final double iconFill;
|
||||
|
||||
final String? debugLabel;
|
||||
final FocusNode? focusNode;
|
||||
final bool autofocus;
|
||||
|
||||
final String? tooltip;
|
||||
final VoidCallback? onPressed;
|
||||
final Widget? child;
|
||||
final FocusableActionBuilder? builder;
|
||||
|
||||
const FocusableAction({
|
||||
this.icon = Icons.circle,
|
||||
this.iconColor,
|
||||
this.iconFill = 1.0,
|
||||
this.debugLabel,
|
||||
this.focusNode,
|
||||
this.autofocus = false,
|
||||
this.tooltip,
|
||||
this.onPressed,
|
||||
this.child,
|
||||
this.builder,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -42,6 +70,12 @@ class FocusableActionBar extends StatefulWidget {
|
||||
/// Called when the user presses the back key while an action is focused.
|
||||
final VoidCallback? onBack;
|
||||
|
||||
/// Called when any action in the row gains or loses focus.
|
||||
final ValueChanged<bool>? onFocusChange;
|
||||
|
||||
final double spacing;
|
||||
final MainAxisSize mainAxisSize;
|
||||
|
||||
const FocusableActionBar({
|
||||
super.key,
|
||||
required this.actions,
|
||||
@@ -50,6 +84,9 @@ class FocusableActionBar extends StatefulWidget {
|
||||
this.onNavigateLeft,
|
||||
this.onNavigateRight,
|
||||
this.onBack,
|
||||
this.onFocusChange,
|
||||
this.spacing = 0,
|
||||
this.mainAxisSize = MainAxisSize.min,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -58,7 +95,10 @@ class FocusableActionBar extends StatefulWidget {
|
||||
|
||||
class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
late List<FocusNode> _focusNodes;
|
||||
late List<bool> _ownsFocusNodes;
|
||||
late List<VoidCallback> _focusListeners;
|
||||
late List<bool> _focusStates;
|
||||
bool _hasAnyFocus = false;
|
||||
|
||||
FocusNode? getFocusNode(int index) => index >= 0 && index < _focusNodes.length ? _focusNodes[index] : null;
|
||||
|
||||
@@ -75,29 +115,58 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
@override
|
||||
void didUpdateWidget(FocusableActionBar oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.actions.length != widget.actions.length) {
|
||||
if (_shouldRebuildFocusNodes(oldWidget)) {
|
||||
_disposeNodes();
|
||||
_initNodes();
|
||||
}
|
||||
}
|
||||
|
||||
bool _shouldRebuildFocusNodes(FocusableActionBar oldWidget) {
|
||||
if (oldWidget.actions.length != widget.actions.length) return true;
|
||||
for (var i = 0; i < widget.actions.length; i++) {
|
||||
if (oldWidget.actions[i].focusNode != widget.actions[i].focusNode) return true;
|
||||
if (oldWidget.actions[i].debugLabel != widget.actions[i].debugLabel) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void _initNodes() {
|
||||
_focusNodes = List.generate(widget.actions.length, (i) => FocusNode(debugLabel: 'ActionBar[$i]'));
|
||||
_focusStates = List.filled(widget.actions.length, false);
|
||||
_focusNodes = List.generate(
|
||||
widget.actions.length,
|
||||
(i) => widget.actions[i].focusNode ?? FocusNode(debugLabel: widget.actions[i].debugLabel ?? 'ActionBar[$i]'),
|
||||
);
|
||||
_ownsFocusNodes = List.generate(widget.actions.length, (i) => widget.actions[i].focusNode == null);
|
||||
_focusListeners = [];
|
||||
_focusStates = List.generate(widget.actions.length, (i) => _focusNodes[i].hasFocus);
|
||||
_hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
|
||||
for (var i = 0; i < _focusNodes.length; i++) {
|
||||
final idx = i;
|
||||
_focusNodes[i].addListener(() {
|
||||
void listener() {
|
||||
final hasFocus = _focusNodes[idx].hasFocus;
|
||||
if (_focusStates[idx] != hasFocus) {
|
||||
setState(() => _focusStates[idx] = hasFocus);
|
||||
}
|
||||
});
|
||||
_notifyRowFocusIfChanged();
|
||||
}
|
||||
|
||||
_focusListeners.add(listener);
|
||||
_focusNodes[i].addListener(listener);
|
||||
}
|
||||
}
|
||||
|
||||
void _notifyRowFocusIfChanged() {
|
||||
final hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
|
||||
if (_hasAnyFocus == hasAnyFocus) return;
|
||||
_hasAnyFocus = hasAnyFocus;
|
||||
widget.onFocusChange?.call(hasAnyFocus);
|
||||
}
|
||||
|
||||
void _disposeNodes() {
|
||||
for (final node in _focusNodes) {
|
||||
node.dispose();
|
||||
for (var i = 0; i < _focusNodes.length; i++) {
|
||||
_focusNodes[i].removeListener(_focusListeners[i]);
|
||||
if (_ownsFocusNodes[i]) {
|
||||
_focusNodes[i].dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,8 +182,13 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [for (var i = 0; i < widget.actions.length; i++) _buildButton(i, isKeyboard, duration)],
|
||||
mainAxisSize: widget.mainAxisSize,
|
||||
children: [
|
||||
for (var i = 0; i < widget.actions.length; i++) ...[
|
||||
if (i > 0 && widget.spacing > 0) SizedBox(width: widget.spacing),
|
||||
_buildButton(i, isKeyboard, duration),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,8 +198,19 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
final showFocus = isFocused && isKeyboard;
|
||||
final opacity = isKeyboard && !isFocused ? 0.6 : 1.0;
|
||||
|
||||
final buildState = FocusableActionBuildState(
|
||||
focusNode: _focusNodes[index],
|
||||
isFocused: isFocused,
|
||||
showFocus: showFocus,
|
||||
isKeyboardMode: isKeyboard,
|
||||
animationDuration: duration,
|
||||
);
|
||||
final customChild = action.builder?.call(context, buildState);
|
||||
|
||||
return Focus(
|
||||
focusNode: _focusNodes[index],
|
||||
autofocus: action.autofocus,
|
||||
descendantsAreFocusable: false,
|
||||
onKeyEvent: (node, event) {
|
||||
if (widget.onBack != null) {
|
||||
final backResult = handleBackKeyAction(event, widget.onBack!);
|
||||
@@ -139,19 +224,27 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
: widget.onNavigateRight,
|
||||
onDown: widget.onNavigateDown,
|
||||
onUp: widget.onNavigateUp,
|
||||
// Consume LEFT/RIGHT at the row's first/last button when no edge
|
||||
// callback is wired, so focus can't fall off the row (#1181).
|
||||
trapHorizontalEdges: true,
|
||||
)(node, event);
|
||||
},
|
||||
child: AnimatedOpacity(
|
||||
opacity: showFocus ? 1.0 : opacity,
|
||||
duration: duration,
|
||||
child: Container(
|
||||
decoration: FocusTheme.focusBackgroundDecoration(isFocused: showFocus, borderRadius: 20),
|
||||
child: ClickableCursor(
|
||||
enabled: action.onPressed != null || action.child != null || customChild != null,
|
||||
child: AnimatedOpacity(
|
||||
opacity: showFocus ? 1.0 : opacity,
|
||||
duration: duration,
|
||||
child:
|
||||
action.child ??
|
||||
IconButton(
|
||||
icon: AppIcon(action.icon, fill: action.iconFill, color: action.iconColor),
|
||||
tooltip: action.tooltip,
|
||||
onPressed: action.onPressed,
|
||||
customChild ??
|
||||
Container(
|
||||
decoration: FocusTheme.focusBackgroundDecoration(isFocused: showFocus, borderRadius: 20),
|
||||
child:
|
||||
action.child ??
|
||||
IconButton(
|
||||
icon: AppIcon(action.icon, fill: action.iconFill, color: action.iconColor),
|
||||
tooltip: action.tooltip,
|
||||
onPressed: action.onPressed,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,16 +1,93 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../services/gamepad_service.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
import '../utils/text_input_diagnostics.dart';
|
||||
import '../widgets/tv_virtual_keyboard.dart';
|
||||
import 'dpad_navigator.dart';
|
||||
|
||||
bool _usesTvKeyboard(bool enableTvKeyboard) => enableTvKeyboard && PlatformDetector.isAppleTV();
|
||||
bool _usesTvKeyboard(bool enableTvKeyboard) => enableTvKeyboard && PlatformDetector.isTV();
|
||||
|
||||
String? _keyboardHint(InputDecoration? decoration) => decoration?.hintText ?? decoration?.labelText;
|
||||
|
||||
enum TvKeyboardAutoOpenBehavior {
|
||||
/// Open the TV virtual keyboard whenever the field receives focus.
|
||||
onFocus,
|
||||
|
||||
/// Keep initial focus on the field without opening the keyboard, then open
|
||||
/// automatically on later focus entries. Explicit tap/select still opens it.
|
||||
afterFirstFocus,
|
||||
|
||||
/// Never auto-open the TV virtual keyboard on focus. Explicit tap/select
|
||||
/// still opens it.
|
||||
never,
|
||||
}
|
||||
|
||||
String _describeTextInputKey(KeyEvent event) {
|
||||
return 'type=${event.runtimeType} logical=${event.logicalKey.keyLabel}/${event.logicalKey.keyId} '
|
||||
'physical=${event.physicalKey.usbHidUsage} deviceType=${event.deviceType} character=${event.character}';
|
||||
}
|
||||
|
||||
void _logTvTextInput(String message) {
|
||||
TextInputDiagnostics.log('FlutterTextField', message);
|
||||
}
|
||||
|
||||
class _NativeTvTextInputFocusBridge {
|
||||
static const _channel = MethodChannel('com.plezy/text_input');
|
||||
static final Set<Object> _focusedTokens = <Object>{};
|
||||
static bool _lastSentFocused = false;
|
||||
|
||||
static void setFocused(Object token, bool focused) {
|
||||
_logTvTextInput(
|
||||
'NativeFocusBridge.setFocused requested focused=$focused token=$token activeTokens=${_focusedTokens.length}',
|
||||
);
|
||||
if (focused) {
|
||||
_focusedTokens.add(token);
|
||||
} else {
|
||||
_focusedTokens.remove(token);
|
||||
}
|
||||
|
||||
if (!PlatformDetector.isTV() || PlatformDetector.isAppleTV()) {
|
||||
_logTvTextInput(
|
||||
'NativeFocusBridge clearing without platform send isTv=${PlatformDetector.isTV()} '
|
||||
'isAppleTV=${PlatformDetector.isAppleTV()}',
|
||||
);
|
||||
_focusedTokens.clear();
|
||||
_lastSentFocused = false;
|
||||
return;
|
||||
}
|
||||
|
||||
final anyFocused = _focusedTokens.isNotEmpty;
|
||||
if (_lastSentFocused == anyFocused) {
|
||||
_logTvTextInput('NativeFocusBridge no-op anyFocused=$anyFocused tokenCount=${_focusedTokens.length}');
|
||||
return;
|
||||
}
|
||||
_lastSentFocused = anyFocused;
|
||||
_logTvTextInput('NativeFocusBridge sending anyFocused=$anyFocused tokenCount=${_focusedTokens.length}');
|
||||
unawaited(GamepadService.setNativeTextInputFocused(anyFocused));
|
||||
unawaited(_sendFocused(anyFocused));
|
||||
}
|
||||
|
||||
static Future<void> _sendFocused(bool focused) async {
|
||||
try {
|
||||
await _channel.invokeMethod<void>('setNativeTextInputFocused', focused);
|
||||
_logTvTextInput('NativeFocusBridge platform send complete focused=$focused');
|
||||
} on MissingPluginException {
|
||||
_logTvTextInput('NativeFocusBridge platform send missing plugin focused=$focused');
|
||||
// Tests and non-Android embedders do not register this channel.
|
||||
} on PlatformException {
|
||||
_logTvTextInput('NativeFocusBridge platform send failed focused=$focused');
|
||||
// Focus reporting is a best-effort native routing hint.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleInputKey({
|
||||
required TextEditingController controller,
|
||||
required FocusNode node,
|
||||
required bool usesTvKeyboard,
|
||||
required bool enabled,
|
||||
required VoidCallback openKeyboard,
|
||||
@@ -31,10 +108,28 @@ KeyEventResult _handleInputKey({
|
||||
VoidCallback? onNavigateDown,
|
||||
}) {
|
||||
final key = event.logicalKey;
|
||||
KeyEventResult finish(KeyEventResult result, String reason) {
|
||||
_logTvTextInput(
|
||||
'result=$result reason=$reason key=(${_describeTextInputKey(event)}) '
|
||||
'usesTvKeyboard=$usesTvKeyboard enabled=$enabled textLength=${controller.text.length} '
|
||||
'selection=${controller.selection} onNav(up=${onNavigateUp != null},down=${onNavigateDown != null},'
|
||||
'left=${onNavigateLeft != null},right=${onNavigateRight != null}) onSelect=${onSelect != null} onBack=${onBack != null}',
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
_logTvTextInput(
|
||||
'received key=(${_describeTextInputKey(event)}) usesTvKeyboard=$usesTvKeyboard enabled=$enabled '
|
||||
'textLength=${controller.text.length} selection=${controller.selection}',
|
||||
);
|
||||
|
||||
if (_shouldPassNativeTvKeyToPlatform(usesTvKeyboard: usesTvKeyboard, enabled: enabled, event: event)) {
|
||||
return finish(KeyEventResult.skipRemainingHandlers, 'pass-native-tv-key-to-platform');
|
||||
}
|
||||
|
||||
if (usesTvKeyboard && enabled && event.isTvSelectEvent) {
|
||||
if (event is KeyDownEvent) openKeyboard();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'open-custom-tv-keyboard');
|
||||
}
|
||||
|
||||
if (usesTvKeyboard && enabled && event.isPhysicalKeyboardEvent) {
|
||||
@@ -50,12 +145,12 @@ KeyEventResult _handleInputKey({
|
||||
maxLines: maxLines,
|
||||
event: event,
|
||||
);
|
||||
if (result != KeyEventResult.ignored) return result;
|
||||
if (result != KeyEventResult.ignored) return finish(result, 'custom-tv-hardware-keyboard');
|
||||
}
|
||||
|
||||
if (onBack != null && key.isBackKey) {
|
||||
if (event is KeyDownEvent) onBack();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'onBack');
|
||||
}
|
||||
|
||||
// Enter/numpad enter are left to TextField.onSubmitted. Handle only
|
||||
@@ -64,33 +159,83 @@ KeyEventResult _handleInputKey({
|
||||
onSelect != null &&
|
||||
(key == LogicalKeyboardKey.select || key == LogicalKeyboardKey.gameButtonA)) {
|
||||
if (event is KeyDownEvent) onSelect();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'native-tv-non-text-select');
|
||||
}
|
||||
|
||||
if (!event.isActionable) return KeyEventResult.ignored;
|
||||
if (!event.isActionable) return finish(KeyEventResult.ignored, 'non-actionable');
|
||||
|
||||
if (key.isUpKey && onNavigateUp != null) {
|
||||
onNavigateUp();
|
||||
return KeyEventResult.handled;
|
||||
final isMultiline = _isMultilineTextInput(keyboardType: keyboardType, maxLines: maxLines);
|
||||
|
||||
// Directional escape: an explicit callback always wins. Otherwise, fall back
|
||||
// to the framework's geometry-based directional traversal so an un-wired
|
||||
// field moves to its nearest neighbour instead of dead-ending (the field's
|
||||
// own onKeyEvent runs before EditableText, which would otherwise swallow the
|
||||
// arrow). Single-line only for UP/DOWN — multiline falls through so
|
||||
// EditableText can move the caret between lines.
|
||||
if (key.isUpKey) {
|
||||
if (onNavigateUp != null) {
|
||||
onNavigateUp();
|
||||
return finish(KeyEventResult.handled, 'onNavigateUp');
|
||||
}
|
||||
if (!isMultiline) {
|
||||
final moved = node.focusInDirection(TraversalDirection.up);
|
||||
return finish(moved ? KeyEventResult.handled : KeyEventResult.ignored, 'focusInDirection-up');
|
||||
}
|
||||
}
|
||||
if (key.isDownKey && onNavigateDown != null) {
|
||||
onNavigateDown();
|
||||
return KeyEventResult.handled;
|
||||
if (key.isDownKey) {
|
||||
if (onNavigateDown != null) {
|
||||
onNavigateDown();
|
||||
return finish(KeyEventResult.handled, 'onNavigateDown');
|
||||
}
|
||||
if (!isMultiline) {
|
||||
final moved = node.focusInDirection(TraversalDirection.down);
|
||||
return finish(moved ? KeyEventResult.handled : KeyEventResult.ignored, 'focusInDirection-down');
|
||||
}
|
||||
}
|
||||
|
||||
final sel = controller.selection;
|
||||
if (sel.isCollapsed) {
|
||||
if (key.isLeftKey && sel.baseOffset == 0 && onNavigateLeft != null) {
|
||||
onNavigateLeft();
|
||||
return KeyEventResult.handled;
|
||||
if (key.isLeftKey && sel.baseOffset == 0) {
|
||||
if (onNavigateLeft != null) {
|
||||
onNavigateLeft();
|
||||
return finish(KeyEventResult.handled, 'onNavigateLeft-at-start');
|
||||
}
|
||||
final moved = node.focusInDirection(TraversalDirection.left);
|
||||
return finish(moved ? KeyEventResult.handled : KeyEventResult.ignored, 'focusInDirection-left-at-start');
|
||||
}
|
||||
if (key.isRightKey && sel.baseOffset == controller.text.length && onNavigateRight != null) {
|
||||
onNavigateRight();
|
||||
return KeyEventResult.handled;
|
||||
if (key.isRightKey && sel.baseOffset == controller.text.length) {
|
||||
if (onNavigateRight != null) {
|
||||
onNavigateRight();
|
||||
return finish(KeyEventResult.handled, 'onNavigateRight-at-end');
|
||||
}
|
||||
final moved = node.focusInDirection(TraversalDirection.right);
|
||||
return finish(moved ? KeyEventResult.handled : KeyEventResult.ignored, 'focusInDirection-right-at-end');
|
||||
}
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
return finish(KeyEventResult.ignored, 'fall-through');
|
||||
}
|
||||
|
||||
bool _shouldPassNativeTvKeyToPlatform({required bool usesTvKeyboard, required bool enabled, required KeyEvent event}) {
|
||||
if (!enabled || usesTvKeyboard || !PlatformDetector.isTV()) {
|
||||
_logTvTextInput(
|
||||
'native-pass=false reason=disabled-or-custom-keyboard enabled=$enabled usesTvKeyboard=$usesTvKeyboard '
|
||||
'isTv=${PlatformDetector.isTV()} key=(${_describeTextInputKey(event)})',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Android TV provides its own IME. Remote keys must reach the platform so
|
||||
// users can move around that keyboard instead of escaping the app field.
|
||||
// Some remotes (Chromecast) are reported by Flutter as keyboard events, so
|
||||
// native TV navigation cannot rely on deviceType.
|
||||
final key = event.logicalKey;
|
||||
final shouldPass = key.isDpadDirection || key.isBackKey || event.isTvSelectEvent;
|
||||
_logTvTextInput(
|
||||
'native-pass=$shouldPass reason=${shouldPass ? "remote-navigation-key" : "not-navigation-key"} '
|
||||
'key=(${_describeTextInputKey(event)})',
|
||||
);
|
||||
return shouldPass;
|
||||
}
|
||||
|
||||
KeyEventResult _handleTvHardwareKeyboardKey({
|
||||
@@ -381,6 +526,7 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
|
||||
final bool autofocus;
|
||||
final bool enabled;
|
||||
final bool enableTvKeyboard;
|
||||
final TvKeyboardAutoOpenBehavior tvKeyboardAutoOpenBehavior;
|
||||
final bool obscureText;
|
||||
final bool autocorrect;
|
||||
final bool enableSuggestions;
|
||||
@@ -413,6 +559,7 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
|
||||
this.autofocus = false,
|
||||
this.enabled = true,
|
||||
this.enableTvKeyboard = true,
|
||||
this.tvKeyboardAutoOpenBehavior = TvKeyboardAutoOpenBehavior.onFocus,
|
||||
this.obscureText = false,
|
||||
this.autocorrect = true,
|
||||
this.enableSuggestions = true,
|
||||
@@ -430,31 +577,33 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
|
||||
});
|
||||
|
||||
bool get _hasTvKeyboard => _usesTvKeyboard(enableTvKeyboard);
|
||||
bool get _usesNativeTvKeyboard => PlatformDetector.isTV() && !_hasTvKeyboard;
|
||||
|
||||
void _showTvKeyboard(BuildContext context) {
|
||||
if (!enabled) return;
|
||||
showTvVirtualKeyboard(
|
||||
context: context,
|
||||
controller: controller,
|
||||
hintText: _keyboardHint(decoration),
|
||||
keyboardType: keyboardType,
|
||||
textInputAction: textInputAction,
|
||||
inputFormatters: inputFormatters,
|
||||
obscureText: obscureText,
|
||||
maxLength: maxLength,
|
||||
maxLines: maxLines,
|
||||
onChanged: onChanged,
|
||||
onSubmitted: onSubmitted,
|
||||
onAction: onEditingComplete ?? onSelect,
|
||||
);
|
||||
VoidCallback? get _effectiveOnEditingComplete {
|
||||
if (onEditingComplete != null) return onEditingComplete;
|
||||
if (_usesNativeTvKeyboard && onSubmitted == null) return _handleTvKeyboardAction;
|
||||
return null;
|
||||
}
|
||||
|
||||
KeyEventResult _handleKey(BuildContext context, FocusNode _, KeyEvent event) {
|
||||
void _handleTvKeyboardAction() {
|
||||
if (onEditingComplete != null) {
|
||||
onEditingComplete!();
|
||||
} else if (onSelect != null) {
|
||||
onSelect!();
|
||||
} else if (onNavigateDown != null) {
|
||||
onNavigateDown!();
|
||||
} else {
|
||||
_defaultEditingComplete(textInputAction);
|
||||
}
|
||||
}
|
||||
|
||||
KeyEventResult _handleKey(BuildContext context, FocusNode node, KeyEvent event, VoidCallback openKeyboard) {
|
||||
return _handleInputKey(
|
||||
controller: controller,
|
||||
node: node,
|
||||
usesTvKeyboard: _hasTvKeyboard,
|
||||
enabled: enabled,
|
||||
openKeyboard: () => _showTvKeyboard(context),
|
||||
openKeyboard: openKeyboard,
|
||||
event: event,
|
||||
keyboardType: keyboardType,
|
||||
textInputAction: textInputAction,
|
||||
@@ -473,16 +622,263 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget buildFocusableInput(BuildContext context, Widget Function(bool usesTvKeyboard) builder) {
|
||||
final usesTvKeyboard = _hasTvKeyboard;
|
||||
return Focus(
|
||||
// This wrapper only intercepts key events bubbling from the input; the
|
||||
// real TextField/TextFormField must remain the traversable focus target.
|
||||
canRequestFocus: false,
|
||||
skipTraversal: true,
|
||||
onKeyEvent: (node, event) => _handleKey(context, node, event),
|
||||
child: builder(usesTvKeyboard),
|
||||
Widget buildFocusableInput(
|
||||
BuildContext context,
|
||||
Widget Function(bool usesTvKeyboard, FocusNode focusNode, VoidCallback openKeyboard) builder,
|
||||
) {
|
||||
return _FocusableTextInputHost(input: this, builder: builder);
|
||||
}
|
||||
}
|
||||
|
||||
class _FocusableTextInputHost extends StatefulWidget {
|
||||
final _FocusableTextInputBase input;
|
||||
final Widget Function(bool usesTvKeyboard, FocusNode focusNode, VoidCallback openKeyboard) builder;
|
||||
|
||||
const _FocusableTextInputHost({required this.input, required this.builder});
|
||||
|
||||
@override
|
||||
State<_FocusableTextInputHost> createState() => _FocusableTextInputHostState();
|
||||
}
|
||||
|
||||
class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
|
||||
FocusNode? _ownedFocusNode;
|
||||
FocusNode? _installedFocusNode;
|
||||
FocusOnKeyEventCallback? _previousOnKeyEvent;
|
||||
late final FocusOnKeyEventCallback _keyHandler = _handleKey;
|
||||
late final VoidCallback _focusListener = _handleFocusChanged;
|
||||
final Object _nativeFocusToken = Object();
|
||||
bool _reportedNativeTextInputFocused = false;
|
||||
TvVirtualKeyboardHandle? _tvKeyboardHandle;
|
||||
bool _tvKeyboardOpen = false;
|
||||
bool _tvKeyboardOpenScheduled = false;
|
||||
bool _suppressTvKeyboardAutoOpen = false;
|
||||
bool _hasSeenTvKeyboardFocus = false;
|
||||
bool _suppressTvKeyboardForCurrentFocus = false;
|
||||
|
||||
FocusNode get _effectiveFocusNode =>
|
||||
widget.input.focusNode ?? (_ownedFocusNode ??= FocusNode(debugLabel: 'FocusableTextInput'));
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_FocusableTextInputHost oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.input.focusNode != widget.input.focusNode) {
|
||||
// An open keyboard dialog intentionally survives rebuilds and focusNode
|
||||
// swaps; it is closed only when this host unmounts — see dispose.
|
||||
_restoreInstalledHandler();
|
||||
_suppressTvKeyboardAutoOpen = false;
|
||||
_tvKeyboardOpenScheduled = false;
|
||||
_hasSeenTvKeyboardFocus = false;
|
||||
_suppressTvKeyboardForCurrentFocus = false;
|
||||
}
|
||||
_handleFocusChanged();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_restoreInstalledHandler();
|
||||
// The keyboard is a navigator route — it must not outlive the field that
|
||||
// opened it (e.g. a form section swapped out while the keyboard is up).
|
||||
// Navigator mutation is unsafe during tree finalization; defer a frame.
|
||||
final keyboard = _tvKeyboardHandle;
|
||||
if (keyboard != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => keyboard.close());
|
||||
}
|
||||
_ownedFocusNode?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _handleFocusChanged() {
|
||||
_syncNativeTextInputFocus();
|
||||
_syncTvKeyboardAutoOpen();
|
||||
}
|
||||
|
||||
void _syncNativeTextInputFocus() {
|
||||
final focused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._usesNativeTvKeyboard;
|
||||
_logTvTextInput(
|
||||
'Host.syncNativeTextInputFocus focused=$focused installed=${_installedFocusNode?.debugLabel} '
|
||||
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
|
||||
'usesNativeTvKeyboard=${widget.input._usesNativeTvKeyboard}',
|
||||
);
|
||||
_setNativeTextInputFocused(focused);
|
||||
}
|
||||
|
||||
void _syncTvKeyboardAutoOpen() {
|
||||
final focused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._hasTvKeyboard;
|
||||
final visible = _canShowTvKeyboard;
|
||||
_logTvTextInput(
|
||||
'Host.syncTvKeyboardAutoOpen focused=$focused open=$_tvKeyboardOpen scheduled=$_tvKeyboardOpenScheduled '
|
||||
'suppressed=$_suppressTvKeyboardAutoOpen behavior=${widget.input.tvKeyboardAutoOpenBehavior} '
|
||||
'seenFocus=$_hasSeenTvKeyboardFocus suppressCurrent=$_suppressTvKeyboardForCurrentFocus '
|
||||
'installed=${_installedFocusNode?.debugLabel} '
|
||||
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
|
||||
'usesTvKeyboard=${widget.input._hasTvKeyboard} visible=$visible',
|
||||
);
|
||||
|
||||
if (!focused) {
|
||||
_suppressTvKeyboardForCurrentFocus = false;
|
||||
if (!_tvKeyboardOpen && !_tvKeyboardOpenScheduled) {
|
||||
_suppressTvKeyboardAutoOpen = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!visible) return;
|
||||
if (!_shouldAutoOpenTvKeyboardForCurrentFocus()) return;
|
||||
if (_suppressTvKeyboardAutoOpen || _tvKeyboardOpen || _tvKeyboardOpenScheduled) return;
|
||||
|
||||
_tvKeyboardOpenScheduled = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
_tvKeyboardOpenScheduled = false;
|
||||
final stillFocused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._hasTvKeyboard;
|
||||
if (!stillFocused || !_canShowTvKeyboard || _suppressTvKeyboardAutoOpen || _tvKeyboardOpen) return;
|
||||
_openTvKeyboard();
|
||||
});
|
||||
}
|
||||
|
||||
bool get _canShowTvKeyboard {
|
||||
final route = ModalRoute.of(context);
|
||||
return TickerMode.valuesOf(context).enabled && (route?.isCurrent ?? true);
|
||||
}
|
||||
|
||||
bool _shouldAutoOpenTvKeyboardForCurrentFocus() {
|
||||
switch (widget.input.tvKeyboardAutoOpenBehavior) {
|
||||
case TvKeyboardAutoOpenBehavior.onFocus:
|
||||
return true;
|
||||
case TvKeyboardAutoOpenBehavior.afterFirstFocus:
|
||||
if (!_hasSeenTvKeyboardFocus) {
|
||||
_hasSeenTvKeyboardFocus = true;
|
||||
_suppressTvKeyboardForCurrentFocus = true;
|
||||
return false;
|
||||
}
|
||||
return !_suppressTvKeyboardForCurrentFocus;
|
||||
case TvKeyboardAutoOpenBehavior.never:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _openTvKeyboard() {
|
||||
if (!mounted || !widget.input.enabled || !widget.input._hasTvKeyboard || !_canShowTvKeyboard || _tvKeyboardOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
_tvKeyboardOpenScheduled = false;
|
||||
_tvKeyboardOpen = true;
|
||||
_hasSeenTvKeyboardFocus = true;
|
||||
_suppressTvKeyboardForCurrentFocus = false;
|
||||
_suppressTvKeyboardAutoOpen = true;
|
||||
_logTvTextInput('Host.openTvKeyboard node=${_installedFocusNode?.debugLabel}');
|
||||
// The dialog outlives input rebuilds (e.g. a search field whose
|
||||
// onNavigateDown appears once results arrive while the keyboard is up),
|
||||
// so only static configuration may be snapshotted here — the callbacks
|
||||
// must resolve against widget.input at invoke time.
|
||||
final input = widget.input;
|
||||
final keyboard = showTvVirtualKeyboard(
|
||||
context: context,
|
||||
controller: input.controller,
|
||||
hintText: _keyboardHint(input.decoration),
|
||||
keyboardType: input.keyboardType,
|
||||
textInputAction: input.textInputAction,
|
||||
inputFormatters: input.inputFormatters,
|
||||
obscureText: input.obscureText,
|
||||
maxLength: input.maxLength,
|
||||
maxLines: input.maxLines,
|
||||
onChanged: (text) {
|
||||
if (!mounted) return;
|
||||
widget.input.onChanged?.call(text);
|
||||
},
|
||||
onSubmitted: (text) {
|
||||
if (!mounted) return;
|
||||
final current = widget.input;
|
||||
if (current.onSubmitted != null) {
|
||||
current.onSubmitted!(text);
|
||||
} else {
|
||||
current._handleTvKeyboardAction();
|
||||
}
|
||||
},
|
||||
);
|
||||
if (keyboard == null) {
|
||||
_tvKeyboardOpen = false;
|
||||
return;
|
||||
}
|
||||
_tvKeyboardHandle = keyboard;
|
||||
unawaited(
|
||||
keyboard.closed.whenComplete(() {
|
||||
_tvKeyboardHandle = null;
|
||||
if (!mounted) return;
|
||||
_tvKeyboardOpen = false;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
if (_installedFocusNode?.hasFocus != true) {
|
||||
_suppressTvKeyboardAutoOpen = false;
|
||||
}
|
||||
_syncTvKeyboardAutoOpen();
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
void _setNativeTextInputFocused(bool focused) {
|
||||
if (_reportedNativeTextInputFocused == focused) {
|
||||
_logTvTextInput('Host.setNativeTextInputFocused no-op focused=$focused');
|
||||
return;
|
||||
}
|
||||
_logTvTextInput('Host.setNativeTextInputFocused old=$_reportedNativeTextInputFocused new=$focused');
|
||||
_reportedNativeTextInputFocused = focused;
|
||||
_NativeTvTextInputFocusBridge.setFocused(_nativeFocusToken, focused);
|
||||
}
|
||||
|
||||
KeyEventResult _handleKey(FocusNode node, KeyEvent event) {
|
||||
final previous = _previousOnKeyEvent;
|
||||
if (previous != null && !identical(previous, _keyHandler)) {
|
||||
final result = previous(node, event);
|
||||
_logTvTextInput(
|
||||
'Host.previousOnKeyEvent node=${node.debugLabel} result=$result key=(${_describeTextInputKey(event)})',
|
||||
);
|
||||
if (result != KeyEventResult.ignored) return result;
|
||||
}
|
||||
return widget.input._handleKey(context, node, event, _openTvKeyboard);
|
||||
}
|
||||
|
||||
void _installKeyHandler(FocusNode node) {
|
||||
// Handle D-pad escapes on the field's own node so EditableText shortcuts
|
||||
// can't consume directions before our reusable navigation callbacks run.
|
||||
if (_installedFocusNode == node) {
|
||||
if (identical(node.onKeyEvent, _keyHandler)) return;
|
||||
_previousOnKeyEvent = node.onKeyEvent;
|
||||
node.onKeyEvent = _keyHandler;
|
||||
_logTvTextInput('Host.reinstalled key handler node=${node.debugLabel} previous=${_previousOnKeyEvent != null}');
|
||||
return;
|
||||
}
|
||||
|
||||
_restoreInstalledHandler();
|
||||
_installedFocusNode = node;
|
||||
_previousOnKeyEvent = node.onKeyEvent;
|
||||
node.onKeyEvent = _keyHandler;
|
||||
node.addListener(_focusListener);
|
||||
_logTvTextInput('Host.installed key handler node=${node.debugLabel} previous=${_previousOnKeyEvent != null}');
|
||||
}
|
||||
|
||||
void _restoreInstalledHandler() {
|
||||
_logTvTextInput('Host.restoreInstalledHandler node=${_installedFocusNode?.debugLabel}');
|
||||
_setNativeTextInputFocused(false);
|
||||
final node = _installedFocusNode;
|
||||
if (node != null) {
|
||||
node.removeListener(_focusListener);
|
||||
if (identical(node.onKeyEvent, _keyHandler)) {
|
||||
node.onKeyEvent = _previousOnKeyEvent;
|
||||
}
|
||||
}
|
||||
_installedFocusNode = null;
|
||||
_previousOnKeyEvent = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final focusNode = _effectiveFocusNode;
|
||||
_installKeyHandler(focusNode);
|
||||
_handleFocusChanged();
|
||||
return widget.builder(widget.input._hasTvKeyboard, focusNode, _openTvKeyboard);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,6 +906,7 @@ class FocusableTextField extends _FocusableTextInputBase {
|
||||
super.autofocus,
|
||||
super.enabled,
|
||||
super.enableTvKeyboard,
|
||||
super.tvKeyboardAutoOpenBehavior,
|
||||
super.obscureText,
|
||||
super.autocorrect,
|
||||
super.enableSuggestions,
|
||||
@@ -530,9 +927,9 @@ class FocusableTextField extends _FocusableTextInputBase {
|
||||
Widget build(BuildContext context) {
|
||||
return buildFocusableInput(
|
||||
context,
|
||||
(usesTvKeyboard) => TextField(
|
||||
(usesTvKeyboard, effectiveFocusNode, openKeyboard) => TextField(
|
||||
controller: controller,
|
||||
focusNode: focusNode,
|
||||
focusNode: effectiveFocusNode,
|
||||
enabled: enabled,
|
||||
decoration: decoration,
|
||||
keyboardType: usesTvKeyboard ? TextInputType.none : keyboardType,
|
||||
@@ -540,7 +937,7 @@ class FocusableTextField extends _FocusableTextInputBase {
|
||||
inputFormatters: inputFormatters,
|
||||
onChanged: onChanged,
|
||||
onSubmitted: onSubmitted,
|
||||
onEditingComplete: onEditingComplete,
|
||||
onEditingComplete: _effectiveOnEditingComplete,
|
||||
autofocus: autofocus,
|
||||
autocorrect: autocorrect,
|
||||
enableSuggestions: enableSuggestions,
|
||||
@@ -554,7 +951,7 @@ class FocusableTextField extends _FocusableTextInputBase {
|
||||
readOnly: usesTvKeyboard,
|
||||
showCursor: usesTvKeyboard ? true : null,
|
||||
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
|
||||
onTap: usesTvKeyboard ? () => _showTvKeyboard(context) : null,
|
||||
onTap: usesTvKeyboard ? openKeyboard : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -585,6 +982,7 @@ class FocusableTextFormField extends _FocusableTextInputBase {
|
||||
super.autofocus,
|
||||
super.enabled,
|
||||
super.enableTvKeyboard,
|
||||
super.tvKeyboardAutoOpenBehavior,
|
||||
super.obscureText,
|
||||
super.autocorrect,
|
||||
super.enableSuggestions,
|
||||
@@ -605,9 +1003,9 @@ class FocusableTextFormField extends _FocusableTextInputBase {
|
||||
Widget build(BuildContext context) {
|
||||
return buildFocusableInput(
|
||||
context,
|
||||
(usesTvKeyboard) => TextFormField(
|
||||
(usesTvKeyboard, effectiveFocusNode, openKeyboard) => TextFormField(
|
||||
controller: controller,
|
||||
focusNode: focusNode,
|
||||
focusNode: effectiveFocusNode,
|
||||
enabled: enabled,
|
||||
decoration: decoration,
|
||||
keyboardType: usesTvKeyboard ? TextInputType.none : keyboardType,
|
||||
@@ -615,7 +1013,7 @@ class FocusableTextFormField extends _FocusableTextInputBase {
|
||||
inputFormatters: inputFormatters,
|
||||
onChanged: onChanged,
|
||||
onFieldSubmitted: onFieldSubmitted,
|
||||
onEditingComplete: onEditingComplete,
|
||||
onEditingComplete: _effectiveOnEditingComplete,
|
||||
validator: validator,
|
||||
autovalidateMode: autovalidateMode,
|
||||
onSaved: onSaved,
|
||||
@@ -632,7 +1030,7 @@ class FocusableTextFormField extends _FocusableTextInputBase {
|
||||
readOnly: usesTvKeyboard,
|
||||
showCursor: usesTvKeyboard ? true : null,
|
||||
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
|
||||
onTap: usesTvKeyboard ? () => _showTvKeyboard(context) : null,
|
||||
onTap: usesTvKeyboard ? openKeyboard : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,25 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../widgets/clickable_cursor.dart';
|
||||
import '../utils/text_input_diagnostics.dart';
|
||||
import 'card_focus_scope.dart';
|
||||
import 'dpad_navigator.dart';
|
||||
import 'focus_glow_overlay.dart';
|
||||
import 'focus_theme.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
import 'key_event_utils.dart';
|
||||
|
||||
String _describeFocusableKey(KeyEvent event) {
|
||||
return 'type=${event.runtimeType} logical=${event.logicalKey.keyLabel}/${event.logicalKey.keyId} '
|
||||
'physical=${event.physicalKey.usbHidUsage} deviceType=${event.deviceType} character=${event.character}';
|
||||
}
|
||||
|
||||
void _logFocusableWrapper(String message) {
|
||||
TextInputDiagnostics.log('FocusableWrapper', message);
|
||||
}
|
||||
|
||||
/// A wrapper widget that makes its child focusable with D-pad navigation support.
|
||||
///
|
||||
/// Provides:
|
||||
@@ -70,7 +84,7 @@ class FocusableWrapper extends StatefulWidget {
|
||||
/// Whether the wrapper can receive focus.
|
||||
final bool canRequestFocus;
|
||||
|
||||
/// Custom key event handler. Return KeyEventResult.handled to consume the event.
|
||||
/// Custom key event handler. Return any non-ignored result to stop default handling.
|
||||
/// This is called before the default key handling.
|
||||
final KeyEventResult Function(FocusNode node, KeyEvent event)? onKeyEvent;
|
||||
|
||||
@@ -94,6 +108,17 @@ class FocusableWrapper extends StatefulWidget {
|
||||
/// Useful for elements like sliders where scaling looks odd.
|
||||
final bool disableScale;
|
||||
|
||||
/// Scale used for the focus animation.
|
||||
final double focusScale;
|
||||
|
||||
/// Whether to draw a glow around the focused widget.
|
||||
final bool useFocusGlow;
|
||||
|
||||
/// Skip drawing the focus border here and expose the focus state through a
|
||||
/// [CardFocusScope] instead, so the child places the border on the exact
|
||||
/// rect it wants highlighted (e.g. MediaCard's poster image).
|
||||
final bool delegateFocusBorder;
|
||||
|
||||
/// Whether descendants can receive focus.
|
||||
/// Set to false when the child widget has its own Focus (e.g. buttons)
|
||||
/// that would compete with this wrapper's focus handling.
|
||||
@@ -124,6 +149,9 @@ class FocusableWrapper extends StatefulWidget {
|
||||
this.useBackgroundFocus = false,
|
||||
this.focusColor,
|
||||
this.disableScale = false,
|
||||
this.focusScale = FocusTheme.focusScale,
|
||||
this.useFocusGlow = false,
|
||||
this.delegateFocusBorder = false,
|
||||
this.descendantsAreFocusable = true,
|
||||
});
|
||||
|
||||
@@ -137,7 +165,7 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
bool _isFocused = false;
|
||||
|
||||
late final AnimationController _animationController;
|
||||
late final Animation<double> _scaleAnimation;
|
||||
late Animation<double> _scaleAnimation;
|
||||
|
||||
// Long-press detection for SELECT key
|
||||
Timer? _longPressTimer;
|
||||
@@ -166,9 +194,13 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
void _initAnimations() {
|
||||
_animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 150));
|
||||
|
||||
_scaleAnimation = Tween<double>(
|
||||
_scaleAnimation = _createScaleAnimation();
|
||||
}
|
||||
|
||||
Animation<double> _createScaleAnimation() {
|
||||
return Tween<double>(
|
||||
begin: 1.0,
|
||||
end: FocusTheme.focusScale,
|
||||
end: widget.focusScale,
|
||||
).animate(CurvedAnimation(parent: _animationController, curve: Curves.easeOutCubic));
|
||||
}
|
||||
|
||||
@@ -188,6 +220,10 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
if (widget.canRequestFocus != oldWidget.canRequestFocus) {
|
||||
_focusNode.canRequestFocus = widget.canRequestFocus;
|
||||
}
|
||||
|
||||
if (widget.focusScale != oldWidget.focusScale) {
|
||||
_scaleAnimation = _createScaleAnimation();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -315,23 +351,34 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
|
||||
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
|
||||
final key = event.logicalKey;
|
||||
KeyEventResult finish(KeyEventResult result, String reason) {
|
||||
_logFocusableWrapper(
|
||||
'node=${node.debugLabel} result=$result reason=$reason key=(${_describeFocusableKey(event)}) '
|
||||
'onNav(up=${widget.onNavigateUp != null},down=${widget.onNavigateDown != null},'
|
||||
'left=${widget.onNavigateLeft != null},right=${widget.onNavigateRight != null}) '
|
||||
'onSelect=${widget.onSelect != null} onBack=${widget.onBack != null}',
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
_logFocusableWrapper('node=${node.debugLabel} received key=(${_describeFocusableKey(event)})');
|
||||
|
||||
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'select-key-up-suppressed');
|
||||
}
|
||||
|
||||
// Call custom key handler first
|
||||
if (widget.onKeyEvent != null) {
|
||||
final result = widget.onKeyEvent!(node, event);
|
||||
if (result == KeyEventResult.handled) {
|
||||
return result;
|
||||
if (result != KeyEventResult.ignored) {
|
||||
return finish(result, 'custom-onKeyEvent');
|
||||
}
|
||||
}
|
||||
|
||||
if (widget.onBack != null) {
|
||||
final backResult = handleBackKeyAction(event, widget.onBack!);
|
||||
if (backResult != KeyEventResult.ignored) {
|
||||
return backResult;
|
||||
return finish(backResult, 'onBack');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,10 +398,10 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
}
|
||||
});
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'select-long-press-down');
|
||||
} else if (event is KeyRepeatEvent) {
|
||||
// Consume repeat events to prevent system sounds
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'select-long-press-repeat');
|
||||
} else if (event is KeyUpEvent) {
|
||||
final timerWasActive = _longPressTimer?.isActive ?? false;
|
||||
_longPressTimer?.cancel();
|
||||
@@ -364,52 +411,52 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
}
|
||||
// If timer already fired, long press was triggered - do nothing on key up
|
||||
_isSelectKeyDown = false;
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'select-long-press-up');
|
||||
}
|
||||
} else if (widget.onSelect != null) {
|
||||
return handleOneShotSelect(event, widget.onSelect!);
|
||||
return finish(handleOneShotSelect(event, widget.onSelect!), 'one-shot-select');
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore key up events for other keys
|
||||
if (!event.isActionable) {
|
||||
return KeyEventResult.ignored;
|
||||
return finish(KeyEventResult.ignored, 'non-actionable');
|
||||
}
|
||||
|
||||
// Context menu key
|
||||
if (key.isContextMenuKey) {
|
||||
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
|
||||
widget.onLongPress?.call();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'context-menu');
|
||||
}
|
||||
|
||||
// UP arrow - if callback provided, navigate up
|
||||
if (key == LogicalKeyboardKey.arrowUp && widget.onNavigateUp != null) {
|
||||
widget.onNavigateUp!();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'onNavigateUp');
|
||||
}
|
||||
|
||||
// DOWN arrow - if callback provided, navigate down
|
||||
if (key == LogicalKeyboardKey.arrowDown && widget.onNavigateDown != null) {
|
||||
widget.onNavigateDown!();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'onNavigateDown');
|
||||
}
|
||||
|
||||
// LEFT arrow - if callback provided, navigate left (caller is responsible
|
||||
// for only providing this callback when the item is at the left edge)
|
||||
if (key == LogicalKeyboardKey.arrowLeft && widget.onNavigateLeft != null) {
|
||||
widget.onNavigateLeft!();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'onNavigateLeft');
|
||||
}
|
||||
|
||||
// RIGHT arrow - if callback provided, navigate right (caller is responsible
|
||||
// for only providing this callback when the item is at the right edge)
|
||||
if (key == LogicalKeyboardKey.arrowRight && widget.onNavigateRight != null) {
|
||||
widget.onNavigateRight!();
|
||||
return KeyEventResult.handled;
|
||||
return finish(KeyEventResult.handled, 'onNavigateRight');
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
return finish(KeyEventResult.ignored, 'fall-through');
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -423,16 +470,6 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
_animationController.duration = duration;
|
||||
}
|
||||
|
||||
// Choose decoration based on useBackgroundFocus
|
||||
final decoration = widget.useBackgroundFocus
|
||||
? FocusTheme.focusBackgroundDecoration(isFocused: showFocus, borderRadius: widget.borderRadius)
|
||||
: FocusTheme.focusDecoration(
|
||||
context,
|
||||
isFocused: showFocus,
|
||||
borderRadius: widget.borderRadius,
|
||||
color: widget.focusColor,
|
||||
);
|
||||
|
||||
Widget result = Focus(
|
||||
focusNode: _focusNode,
|
||||
autofocus: widget.autofocus,
|
||||
@@ -443,15 +480,36 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
animation: _scaleAnimation,
|
||||
builder: (context, child) {
|
||||
final shouldScale = showFocus && !widget.disableScale;
|
||||
return Transform.scale(
|
||||
scale: shouldScale ? _scaleAnimation.value : 1.0,
|
||||
child: AnimatedContainer(
|
||||
// The glow (full-bleed cards) is drawn in an overlay above siblings so
|
||||
// it stays symmetric; the in-card decoration only carries the border.
|
||||
Widget card;
|
||||
if (widget.delegateFocusBorder) {
|
||||
card = CardFocusScope(showFocus: showFocus, child: widget.child);
|
||||
} else {
|
||||
final focusDecoration = widget.useBackgroundFocus
|
||||
? FocusTheme.focusBackgroundDecoration(isFocused: showFocus, borderRadius: widget.borderRadius)
|
||||
: FocusTheme.focusDecoration(
|
||||
context,
|
||||
isFocused: showFocus,
|
||||
borderRadius: widget.borderRadius,
|
||||
color: widget.focusColor,
|
||||
);
|
||||
card = AnimatedContainer(
|
||||
duration: duration,
|
||||
curve: Curves.easeOutCubic,
|
||||
decoration: decoration,
|
||||
decoration: focusDecoration,
|
||||
child: widget.child,
|
||||
),
|
||||
);
|
||||
);
|
||||
}
|
||||
if (widget.useFocusGlow) {
|
||||
card = FocusGlowOverlay(
|
||||
isFocused: showFocus,
|
||||
borderRadius: widget.borderRadius,
|
||||
color: widget.focusColor ?? FocusTheme.getFocusBorderColor(context),
|
||||
child: card,
|
||||
);
|
||||
}
|
||||
return Transform.scale(scale: shouldScale ? _scaleAnimation.value : 1.0, child: card);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -461,6 +519,10 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
result = Semantics(label: widget.semanticLabel, button: widget.onSelect != null, child: result);
|
||||
}
|
||||
|
||||
if (widget.onSelect != null || widget.onLongPress != null) {
|
||||
result = ClickableCursor(child: result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
@@ -40,6 +42,13 @@ class InputModeTracker extends StatefulWidget {
|
||||
return of(context) == InputMode.keyboard;
|
||||
}
|
||||
|
||||
/// Whether system back must be blocked because the dpad key handler owns
|
||||
/// back navigation: on Android in keyboard mode (TV/gamepad), letting the
|
||||
/// system back through as well double-pops the route.
|
||||
static bool shouldBlockSystemBack(BuildContext context) {
|
||||
return Platform.isAndroid && isKeyboardMode(context);
|
||||
}
|
||||
|
||||
@override
|
||||
State<InputModeTracker> createState() => _InputModeTrackerState();
|
||||
}
|
||||
|
||||
@@ -62,17 +62,23 @@ KeyEventResult handleBackKeyAction(KeyEvent event, VoidCallback onBack) {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (PlatformDetector.isAppleTV() && event.isPhysicalKeyboardEvent && event is KeyDownEvent) {
|
||||
BackKeyCoordinator.markHandled();
|
||||
BackKeyUpSuppressor.suppressBackUntilKeyUp();
|
||||
onBack();
|
||||
// AppleTV physical-keyboard back (Siri Remote Menu via engine-synthesized
|
||||
// escape): run onBack on KeyDown only; consume KeyUp silently. The
|
||||
// suppressor-based "arm-on-KeyDown, clear-on-KeyUp" pattern leaks here
|
||||
// because onBack typically calls Navigator.pop, swapping the focus tree
|
||||
// before the matching KeyUp is dispatched — the orphaned KeyUp then never
|
||||
// reaches a consumeIfSuppressed call, pinning the suppressor armed and
|
||||
// silently swallowing the next press's KeyDown.
|
||||
if (PlatformDetector.isAppleTV() && event.isPhysicalKeyboardEvent) {
|
||||
if (event is KeyDownEvent) {
|
||||
BackKeyCoordinator.markHandled();
|
||||
onBack();
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event is KeyUpEvent) {
|
||||
BackKeyCoordinator.markHandled();
|
||||
// Mark that we're closing via back key so suppressBackUntilKeyUp() knows to skip
|
||||
BackKeyUpSuppressor.markClosedViaBackKey();
|
||||
onBack();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
@@ -112,6 +118,13 @@ KeyEventResult handleOneShotSelect(KeyEvent event, VoidCallback onActivate) {
|
||||
/// (passed through to the framework). Directions mapped to a callback
|
||||
/// automatically return [KeyEventResult.handled].
|
||||
///
|
||||
/// When [trapHorizontalEdges] is true, LEFT/RIGHT with no callback return
|
||||
/// [KeyEventResult.handled] (consumed) instead of being passed through. Use
|
||||
/// this for a self-contained horizontal group (e.g. a button row) so D-pad
|
||||
/// can't escape off the edge into an off-screen "black hole" (#1181); wire an
|
||||
/// explicit [onLeft]/[onRight] only where edge-escape into another region is
|
||||
/// intended. UP/DOWN are unaffected and always pass through when unmapped.
|
||||
///
|
||||
/// Directional keys repeat on [KeyRepeatEvent] (via [isActionable]).
|
||||
/// Select is one-shot: fires on [KeyDownEvent] only, consumes repeat and up.
|
||||
///
|
||||
@@ -132,6 +145,7 @@ FocusOnKeyEventCallback dpadKeyHandler({
|
||||
VoidCallback? onLeft,
|
||||
VoidCallback? onRight,
|
||||
VoidCallback? onSelect,
|
||||
bool trapHorizontalEdges = false,
|
||||
}) {
|
||||
return (FocusNode _, KeyEvent event) {
|
||||
// Select: one-shot activation (no repeat), must run before isActionable
|
||||
@@ -152,13 +166,19 @@ FocusOnKeyEventCallback dpadKeyHandler({
|
||||
onDown();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isLeftKey && onLeft != null) {
|
||||
onLeft();
|
||||
return KeyEventResult.handled;
|
||||
if (key.isLeftKey) {
|
||||
if (onLeft != null) {
|
||||
onLeft();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (trapHorizontalEdges) return KeyEventResult.handled;
|
||||
}
|
||||
if (key.isRightKey && onRight != null) {
|
||||
onRight();
|
||||
return KeyEventResult.handled;
|
||||
if (key.isRightKey) {
|
||||
if (onRight != null) {
|
||||
onRight();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
if (trapHorizontalEdges) return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
return KeyEventResult.ignored;
|
||||
@@ -174,6 +194,12 @@ FocusOnKeyEventCallback dpadKeyHandler({
|
||||
class BackKeySuppressorObserver extends NavigatorObserver {
|
||||
@override
|
||||
void didPop(Route route, Route? previousRoute) {
|
||||
// On AppleTV, handleBackKeyAction consumes the KeyUp silently regardless,
|
||||
// so the suppressor isn't needed and arming it would pin state across the
|
||||
// pop's focus-tree swap. (The atomic engine fix delivers KeyDown+KeyUp in
|
||||
// a single recognizer Began callback, so didPop fires squarely inside the
|
||||
// window where BackKeyPressTracker.isBackKeyDown is true.)
|
||||
if (PlatformDetector.isAppleTV()) return;
|
||||
if (BackKeyPressTracker.isBackKeyDown) {
|
||||
BackKeyUpSuppressor.suppressBackUntilKeyUp();
|
||||
}
|
||||
|
||||
@@ -26,6 +26,13 @@ class HubFocusMemory {
|
||||
return _lastColumnHint.clamp(0, itemCount - 1);
|
||||
}
|
||||
|
||||
/// Get only this hub's remembered index, without falling back to the global column hint.
|
||||
static int getForHubOnly(String hubKey, int itemCount, {int fallback = 0}) {
|
||||
if (itemCount <= 0) return 0;
|
||||
final remembered = _perHubMemory[hubKey];
|
||||
return (remembered ?? fallback).clamp(0, itemCount - 1);
|
||||
}
|
||||
|
||||
/// Clear all memory (e.g., when leaving a screen)
|
||||
static void clear() {
|
||||
_perHubMemory.clear();
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "eller",
|
||||
"connectToJellyfin": "Forbind til Jellyfin",
|
||||
"useQuickConnect": "Brug Quick Connect",
|
||||
"quickConnectCode": "Quick Connect-kode",
|
||||
"quickConnectInstructions": "Åbn Quick Connect i Jellyfin, og indtast denne kode.",
|
||||
"quickConnectWaiting": "Venter på godkendelse…",
|
||||
"quickConnectCancel": "Annullér",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "Ja",
|
||||
"no": "Nej",
|
||||
"delete": "Slet",
|
||||
"edit": "Rediger",
|
||||
"shuffle": "Bland",
|
||||
"addTo": "Tilføj til...",
|
||||
"createNew": "Opret ny",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "Indstillinger",
|
||||
"mute": "Lydløs",
|
||||
"ok": "OK",
|
||||
"off": "Fra",
|
||||
"seasonNumber": "Sæson ${number}",
|
||||
"episodeNumberTitle": "Episode ${number} - ${title}",
|
||||
"chapterNumber": "Kapitel ${number}",
|
||||
"reconnect": "Genopret forbindelse",
|
||||
"exit": "Afslut",
|
||||
"viewAll": "Vis alle",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "Gitter",
|
||||
"listView": "Liste",
|
||||
"showHeroSection": "Vis hero-sektion",
|
||||
"continueWatchingAction": "Handling for Fortsæt med at se",
|
||||
"continueWatchingPlay": "Afspil",
|
||||
"continueWatchingDetails": "Åbn detaljer",
|
||||
"useGlobalHubs": "Brug startlayout",
|
||||
"useGlobalHubsDescription": "Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.",
|
||||
"showServerNameOnHubs": "Vis servernavn på hubbe",
|
||||
@@ -125,6 +132,10 @@
|
||||
"showEpisodeNumberOnCardsDescription": "Vis sæson- og episodenummer på episodekort",
|
||||
"showSeasonPostersOnTabs": "Vis sæsonplakater på faner",
|
||||
"showSeasonPostersOnTabsDescription": "Vis hver sæsons plakat over dens fane",
|
||||
"tvFullCardLayout": "Fuldflade TV-kort",
|
||||
"tvFullCardLayoutDescription": "Brug TV-kort kun med billeder og skuespillernavne ovenpå",
|
||||
"focusGlow": "Fokusglød",
|
||||
"focusGlowDescription": "Vis en blød glød omkring det fokuserede kort",
|
||||
"hideSpoilers": "Skjul spoilere for usete episoder",
|
||||
"hideSpoilersDescription": "Slør miniaturebilleder og beskrivelser for usete episoder",
|
||||
"playerBackend": "Afspillerbackend",
|
||||
@@ -248,16 +259,30 @@
|
||||
"displaySwitchDelay": "Forsinkelse ved skærmskift",
|
||||
"tunneledPlayback": "Tunneleret afspilning",
|
||||
"tunneledPlaybackDescription": "Brug videotunneling. Slå fra, hvis HDR-afspilning viser sort video.",
|
||||
"dvConversionMode": "Dolby Vision-konvertering",
|
||||
"dvConversionModeDescription": "Vælg, hvordan ExoPlayer håndterer Dolby Vision Profile 7-filer.",
|
||||
"dvConversionAuto": "Auto",
|
||||
"dvConversionNative": "Native / deaktiveret",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "Brug enhedens kapabilitetsregistrering og normal fallbackadfærd",
|
||||
"dvConversionNativeDescription": "Tving native DV7 og undertryk forsøg på DV-konvertering",
|
||||
"dvConversionDv81Description": "Tving inline RPU-konvertering til Dolby Vision profil 8.1",
|
||||
"dvConversionHevcStripDescription": "Fjern Dolby Vision RPU/EL-lag og brug almindelig HEVC",
|
||||
"requireProfileSelectionOnOpen": "Spørg om profil ved åbning",
|
||||
"requireProfileSelectionOnOpenDescription": "Vis profilvalg hver gang appen åbnes",
|
||||
"forceTvMode": "Gennemtving TV-tilstand",
|
||||
"forceTvModeDescription": "Tving TV-layout. Til enheder, der ikke registreres automatisk. Kræver genstart.",
|
||||
"startInFullscreen": "Start i fuldskærm",
|
||||
"startInFullscreenDescription": "Åbn Plezy i fuldskærmstilstand ved opstart",
|
||||
"exitFullscreenOnPlayerClose": "Forlad fuldskærm ved lukning af afspiller",
|
||||
"exitFullscreenOnPlayerCloseDescription": "Afslut automatisk fuldskærm, når videoafspilleren lukkes",
|
||||
"autoHidePerformanceOverlay": "Skjul ydelses-overlay automatisk",
|
||||
"autoHidePerformanceOverlayDescription": "Fade ydelses-overlayet med afspilningskontrollerne",
|
||||
"showNavBarLabels": "Vis navigationsbarlabels",
|
||||
"showNavBarLabelsDescription": "Vis tekstlabels under navigationsbarikoner",
|
||||
"startupSection": "Startsektion",
|
||||
"startupSectionDescription": "Vælg hvilken sektion Plezy åbner ved start",
|
||||
"liveTvDefaultFavorites": "Standard til favoritkanaler",
|
||||
"liveTvDefaultFavoritesDescription": "Vis kun favoritkanaler ved åbning af Live TV",
|
||||
"display": "Skærm",
|
||||
@@ -279,6 +304,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Indstil genvej for ${actionName}",
|
||||
"clearShortcut": "Ryd genvej",
|
||||
"noShortcutSet": "Ingen genvej angivet",
|
||||
"currentShortcut": "Nuværende genvej:",
|
||||
"actions": {
|
||||
"playPause": "Afspil/Pause",
|
||||
"volumeUp": "Lydstyrke op",
|
||||
@@ -297,10 +324,14 @@
|
||||
"speedIncrease": "Øg hastighed",
|
||||
"speedDecrease": "Sænk hastighed",
|
||||
"speedReset": "Nulstil hastighed",
|
||||
"zoomIn": "Zoom ind",
|
||||
"zoomOut": "Zoom ud",
|
||||
"zoomReset": "Nulstil zoom",
|
||||
"subSeekNext": "Søg til næste undertekst",
|
||||
"subSeekPrev": "Søg til forrige undertekst",
|
||||
"shaderToggle": "Skift shadere",
|
||||
"skipMarker": "Spring intro/rulletekster over"
|
||||
"skipMarker": "Spring intro/rulletekster over",
|
||||
"screenshot": "Tag skærmbillede"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +365,10 @@
|
||||
"markAsWatched": "Markér som set",
|
||||
"markAsUnwatched": "Markér som uset",
|
||||
"removeFromContinueWatching": "Fjern fra Fortsæt med at se",
|
||||
"viewDetails": "Vis detaljer",
|
||||
"goToSeries": "Gå til serie",
|
||||
"goToSeason": "Gå til sæson",
|
||||
"shufflePlay": "Afspil tilfældigt",
|
||||
"shuffleNotAvailableOffline": "Bland afspilning er ikke tilgængelig offline",
|
||||
"fileInfo": "Filinfo",
|
||||
"deleteFromServer": "Slet fra server",
|
||||
"confirmDelete": "Slet dette medie og dets filer fra din server?",
|
||||
@@ -347,6 +379,19 @@
|
||||
"playFromBeginning": "Afspil fra begyndelsen",
|
||||
"playVersion": "Afspil version..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "Bedøm",
|
||||
"server": "Server",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "Angiv en score",
|
||||
"notRated": "Ikke bedømt",
|
||||
"liked": "Synes godt om",
|
||||
"notLiked": "Ikke liket",
|
||||
"saved": "Gemt",
|
||||
"notAvailable": "Intet match fundet",
|
||||
"noConnectedTrackers": "Forbind en tracker i Indstillinger for at bedømme der."
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, film",
|
||||
"mediaCardShow": "${title}, TV-serie",
|
||||
@@ -379,6 +424,10 @@
|
||||
"unlockRotation": "Lås rotation op",
|
||||
"timerActive": "Timer aktiv",
|
||||
"playbackWillPauseIn": "Afspilning pauses om ${duration}",
|
||||
"sleepTimerEndOfVideo": "Slutningen af aktuel video",
|
||||
"sleepTimerStopAtHeader": "Stop ved",
|
||||
"sleepTimerDurationHeader": "Timer",
|
||||
"playbackWillPauseAtEnd": "Afspilning pauses i slutningen af denne video",
|
||||
"stillWatching": "Ser du stadig?",
|
||||
"pausingIn": "Pauser om ${seconds}s",
|
||||
"continueWatching": "Fortsæt",
|
||||
@@ -394,7 +443,7 @@
|
||||
"nextChapterButton": "Næste kapitel",
|
||||
"muteButton": "Lydløs",
|
||||
"unmuteButton": "Slå lyd til",
|
||||
"settingsButton": "Videoindstillinger",
|
||||
"settingsButton": "Afspilningsindstillinger",
|
||||
"tracksButton": "Lyd og undertekster",
|
||||
"chaptersButton": "Kapitler",
|
||||
"versionsButton": "Videoversioner",
|
||||
@@ -420,6 +469,8 @@
|
||||
"endsAt": "Slutter kl. ${time}",
|
||||
"pipActive": "Afspiller i billede-i-billede",
|
||||
"pipFailed": "Billede-i-billede kunne ikke starte",
|
||||
"screenshotSaved": "Skærmbillede gemt",
|
||||
"zoomPercent": "Zoom ${percent}%",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Kræver Android 8.0 eller nyere",
|
||||
"iosVersion": "Kræver iOS 15.0 eller nyere",
|
||||
@@ -436,6 +487,10 @@
|
||||
"searchSubtitles": "Søg undertekster",
|
||||
"language": "Sprog",
|
||||
"noSubtitlesFound": "Ingen undertekster fundet",
|
||||
"downloadedSubtitle": "Downloadet",
|
||||
"noSubtitlesAvailable": "Ingen undertekster tilgængelige",
|
||||
"noAudioTracksAvailable": "Ingen lydspor tilgængelige",
|
||||
"noTracksAvailable": "Ingen spor tilgængelige",
|
||||
"subtitleDownloaded": "Undertekst downloadet",
|
||||
"subtitleDownloadFailed": "Kunne ikke downloade undertekst",
|
||||
"searchLanguages": "Søg sprog..."
|
||||
@@ -457,7 +512,6 @@
|
||||
"fileInfoNotAvailable": "Filinfo ikke tilgængelig",
|
||||
"errorLoadingFileInfo": "Fejl ved indlæsning af filinfo: ${error}",
|
||||
"errorLoadingSeries": "Fejl ved indlæsning af serie",
|
||||
"errorLoadingSeason": "Fejl ved indlæsning af sæson",
|
||||
"musicNotSupported": "Musikafspilning understøttes endnu ikke",
|
||||
"noDescriptionAvailable": "Ingen beskrivelse tilgængelig",
|
||||
"noProfilesAvailable": "Ingen profiler tilgængelige",
|
||||
@@ -474,8 +528,10 @@
|
||||
"metadataRefreshFailed": "Kunne ikke opdatere metadata: ${error}",
|
||||
"logoutConfirm": "Er du sikker på, at du vil logge ud?",
|
||||
"noSeasonsFound": "Ingen sæsoner fundet",
|
||||
"seasonsLoadFailed": "Kunne ikke indlæse sæsoner",
|
||||
"noEpisodesFound": "Ingen episoder fundet i første sæson",
|
||||
"noEpisodesFoundGeneral": "Ingen episoder fundet",
|
||||
"episodesLoadFailed": "Kunne ikke indlæse episoder",
|
||||
"noResultsFound": "Ingen resultater fundet",
|
||||
"sleepTimerSet": "Sove-timer indstillet til ${label}",
|
||||
"noItemsAvailable": "Ingen elementer tilgængelige",
|
||||
@@ -501,7 +557,10 @@
|
||||
"position": "Position",
|
||||
"assOverride": "ASS-tilsidesættelse",
|
||||
"bold": "Fed",
|
||||
"italic": "Kursiv"
|
||||
"italic": "Kursiv",
|
||||
"renderResolution": "Gengivelsesopløsning",
|
||||
"renderResolutionScreen": "Skærmopløsning",
|
||||
"renderResolutionVideo": "Videoopløsning"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "mpv.conf",
|
||||
@@ -579,7 +638,8 @@
|
||||
"pinProtectionOptional": "PIN-beskyttelse (valgfri)",
|
||||
"pinExplain": "4-cifret PIN kræves for at skifte profiler.",
|
||||
"continueButton": "Fortsæt",
|
||||
"pinsDontMatch": "PIN-koder matcher ikke"
|
||||
"pinsDontMatch": "PIN-koder matcher ikke",
|
||||
"initializeServicesFailed": "Kunne ikke initialisere profiltjenester"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "Forbindelser",
|
||||
@@ -588,7 +648,9 @@
|
||||
"addConnectionSubtitleScoped": "Føj til ${displayName}: Plex, Jellyfin eller en anden profilforbindelse",
|
||||
"sessionExpiredOne": "Sessionen er udløbet for ${name}",
|
||||
"sessionExpiredMany": "Sessionen er udløbet for ${count} servere",
|
||||
"signInAgain": "Log ind igen"
|
||||
"signInAgain": "Log ind igen",
|
||||
"editJellyfinTitle": "Rediger Jellyfin-forbindelse",
|
||||
"editJellyfinIntro": "Tilføj eller fjern URL'er for ${serverName}. Plezy bruger den tilgængelige URL med lavest latenstid."
|
||||
},
|
||||
"discover": {
|
||||
"title": "Opdag",
|
||||
@@ -609,7 +671,8 @@
|
||||
"rating": "Bedømmelse",
|
||||
"movie": "Film",
|
||||
"tvShow": "TV-serie",
|
||||
"minutesLeft": "${minutes} min tilbage"
|
||||
"minutesLeft": "${minutes} min tilbage",
|
||||
"moreLikeThis": "Mere som dette"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Søgning mislykkedes: ${error}",
|
||||
@@ -628,6 +691,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Biblioteker",
|
||||
"fallbackTitle": "Bibliotek",
|
||||
"scanLibraryFiles": "Scan biblioteksfiler",
|
||||
"scanLibrary": "Scan bibliotek",
|
||||
"analyze": "Analysér",
|
||||
@@ -684,15 +748,27 @@
|
||||
"genre": "Genre",
|
||||
"year": "År",
|
||||
"contentRating": "Aldersvurdering",
|
||||
"tag": "Tag"
|
||||
"tag": "Tag",
|
||||
"unwatched": "Usete"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "Titel",
|
||||
"dateAdded": "Tilføjet dato",
|
||||
"releaseDate": "Udgivelsesdato",
|
||||
"rating": "Vurdering",
|
||||
"communityRating": "Fællesskabsvurdering",
|
||||
"criticRating": "Kritikerbedømmelse",
|
||||
"userRating": "Brugerbedømmelse",
|
||||
"lastPlayed": "Sidst afspillet",
|
||||
"datePlayed": "Afspilningsdato",
|
||||
"playCount": "Antal afspilninger",
|
||||
"productionYear": "Produktionsår",
|
||||
"runtime": "Spilletid",
|
||||
"officialRating": "Officiel vurdering",
|
||||
"premiereDate": "Premieredato",
|
||||
"startDate": "Startdato",
|
||||
"airTime": "Sendetid",
|
||||
"studio": "Studie",
|
||||
"random": "Tilfældig",
|
||||
"dateShared": "Delt dato",
|
||||
"latestEpisodeAirDate": "Seneste episodes premieredato"
|
||||
@@ -739,6 +815,12 @@
|
||||
"noChannels": "Ingen kanaler tilgængelige",
|
||||
"noDvr": "Ingen DVR konfigureret på nogen server",
|
||||
"noPrograms": "Ingen programdata tilgængelig",
|
||||
"liveStreamFailed": "Livestream mislykkedes",
|
||||
"unknownProgram": "Ukendt program",
|
||||
"unknownHub": "Ukendt",
|
||||
"unknownError": "Ukendt fejl",
|
||||
"channelNumber": "Kanal ${number}",
|
||||
"unknownChannel": "Ukendt kanal",
|
||||
"live": "LIVE",
|
||||
"reloadGuide": "Genindlæs guide",
|
||||
"now": "Nu",
|
||||
@@ -917,12 +999,21 @@
|
||||
"deleteDownload": "Slet download",
|
||||
"retryDownload": "Prøv download igen",
|
||||
"downloadQueued": "Download i kø",
|
||||
"downloadResumed": "Download genoptaget",
|
||||
"serverErrorBitrate": "Serverfejl: filen overskrider muligvis grænsen for ekstern bitrate",
|
||||
"episodesQueued": "${count} episoder i downloadkø",
|
||||
"downloadDeleted": "Download slettet",
|
||||
"deleteConfirm": "Slet \"${title}\" fra denne enhed?",
|
||||
"deletingWithProgress": "Sletter ${title}... (${current} af ${total})",
|
||||
"cancelledDownloadTitle": "Annulleret download",
|
||||
"cancelledDownloadMessage": "Denne download blev annulleret. Hvad vil du gøre?",
|
||||
"allEpisodesAlreadyDownloaded": "Alle episoder er allerede downloadet",
|
||||
"resumeDownload": "Genoptag download",
|
||||
"cancelledDownload": "Annulleret download",
|
||||
"syncingFile": "${file} (synkroniserer ${status})",
|
||||
"downloadedFileClickToComplete": "${file} downloadet — klik for at fuldføre",
|
||||
"partialDownloadClickToComplete": "Delvist downloadet — klik for at fuldføre",
|
||||
"deleting": "Sletter...",
|
||||
"deletingWithProgress": "Sletter ${title}... (${current} af ${total})",
|
||||
"queuedTooltip": "I kø",
|
||||
"queuedFilesTooltip": "I kø: ${files}",
|
||||
"downloadingTooltip": "Downloader...",
|
||||
@@ -983,6 +1074,7 @@
|
||||
"companionRemote": {
|
||||
"title": "Fjernbetjening",
|
||||
"connectedTo": "Forbundet til ${name}",
|
||||
"unknownDevice": "Ukendt enhed",
|
||||
"session": {
|
||||
"startingServer": "Starter fjernserver...",
|
||||
"failedToCreate": "Kunne ikke starte fjernserver:",
|
||||
@@ -1042,11 +1134,19 @@
|
||||
"subtitles": "Undertekster",
|
||||
"audio": "Lyd",
|
||||
"searchHint": "Søg på desktop..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "Ingen netværksgrænseflade fundet",
|
||||
"authenticationFailed": "Godkendelse mislykkedes",
|
||||
"joinTimedOut": "Tidsgrænse for deltagelse i session overskredet",
|
||||
"failedToConnectAnyAddress": "Kunne ikke oprette forbindelse til nogen adresse",
|
||||
"connectionLostAfterAttempts": "Forbindelse mistet efter ${attempts} forsøg",
|
||||
"connectionLost": "Forbindelse mistet"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "Afspilningsindstillinger",
|
||||
"playbackSpeed": "Afspilningshastighed",
|
||||
"zoom": "Zoom",
|
||||
"sleepTimer": "Sove-timer",
|
||||
"audioSync": "Lydsynkronisering",
|
||||
"subtitleSync": "Undertekstsynkronisering",
|
||||
@@ -1056,6 +1156,43 @@
|
||||
"audioPassthrough": "Lyd-passthrough",
|
||||
"audioNormalization": "Normalisér lydstyrke"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "Farve",
|
||||
"performance": "Ydeevne",
|
||||
"buffer": "Buffer",
|
||||
"app": "App",
|
||||
"decoder": "Dekoder",
|
||||
"rawDecoder": "Rå dekoder",
|
||||
"tunneling": "Tunneling",
|
||||
"aspect": "Billedformat",
|
||||
"rotation": "Rotation",
|
||||
"dvSource": "DV-kilde",
|
||||
"dvPath": "DV-sti",
|
||||
"p7Conversion": "P7-konv.",
|
||||
"sampleRate": "Samplingsrate",
|
||||
"pixelFormat": "Pixelformat",
|
||||
"hwFormat": "HW-format",
|
||||
"matrix": "Matrix",
|
||||
"primaries": "Primærfarver",
|
||||
"transfer": "Transfer",
|
||||
"renderFps": "Render FPS",
|
||||
"displayFps": "Skærm-FPS",
|
||||
"avSync": "A/V-synk.",
|
||||
"dropped": "Tabte",
|
||||
"dvRpus": "DV RPU’er",
|
||||
"dvRpuAverage": "DV RPU gns.",
|
||||
"dvSampleAverage": "DV-sample gns.",
|
||||
"maxLuma": "Maks. luma",
|
||||
"minLuma": "Min. luma",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "Brugt cache",
|
||||
"cacheLimit": "Cachegrænse",
|
||||
"speed": "Hastighed",
|
||||
"player": "Afspiller",
|
||||
"memory": "Hukommelse",
|
||||
"uiFps": "UI FPS"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "Ekstern afspiller",
|
||||
"useExternalPlayer": "Brug ekstern afspiller",
|
||||
@@ -1065,6 +1202,7 @@
|
||||
"systemDefault": "Systemstandard",
|
||||
"addCustomPlayer": "Tilføj brugerdefineret afspiller",
|
||||
"playerName": "Afspillernavn",
|
||||
"playerNameHint": "Min afspiller",
|
||||
"playerCommand": "Kommando",
|
||||
"playerPackage": "Pakkenavn",
|
||||
"playerUrlScheme": "URL-skema",
|
||||
@@ -1224,9 +1362,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Tilføj Jellyfin-server",
|
||||
"jellyfinUrlIntro": "Indtast server-URL'en, f.eks. `https://jellyfin.example.com`.",
|
||||
"serverUrl": "Server-URL",
|
||||
"serverUrls": "Server-URL'er",
|
||||
"serverUrlsHelper": "Flere URL'er er tilladt, adskilt med kommaer.",
|
||||
"findServer": "Find server",
|
||||
"searchingLocalServers": "Søger efter lokale Jellyfin-servere...",
|
||||
"localServers": "Lokale Jellyfin-servere",
|
||||
"username": "Brugernavn",
|
||||
"password": "Adgangskode",
|
||||
"signIn": "Log ind",
|
||||
@@ -1236,17 +1376,12 @@
|
||||
"signInFailed": "Login mislykkedes: ${error}",
|
||||
"quickConnectFailed": "Quick Connect mislykkedes: ${error}",
|
||||
"addPlexTitle": "Log ind med Plex",
|
||||
"plexAuthIntro": "Log ind med en browser eller QR-kode.",
|
||||
"plexQRPrompt": "Scan denne QR-kode for at logge ind.",
|
||||
"waitingForPlexConfirmation": "Venter på at plex.tv bekræfter login…",
|
||||
"pinExpired": "PIN udløb før login. Prøv igen.",
|
||||
"duplicatePlexAccount": "Allerede logget ind på Plex. Log ud for at skifte konto.",
|
||||
"failedToRegisterAccount": "Kunne ikke registrere kontoen: ${error}",
|
||||
"enterJellyfinUrlError": "Angiv URL'en til din Jellyfin-server",
|
||||
"addConnectionTitle": "Tilføj forbindelse",
|
||||
"addConnectionTitleScoped": "Tilføj til ${name}",
|
||||
"addConnectionIntroGlobal": "Tilføj en anden medieserver. Plex og Jellyfin vises sammen på Hjem.",
|
||||
"addConnectionIntroScoped": "Tilføj en ny server, eller lån en fra en anden profil.",
|
||||
"signInWithPlexCard": "Log ind med Plex",
|
||||
"signInWithPlexCardSubtitle": "Godkend denne enhed. Delte servere tilføjes.",
|
||||
"signInWithPlexCardSubtitleScoped": "Godkend en Plex-konto. Home-brugere bliver profiler.",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "oder",
|
||||
"connectToJellyfin": "Mit Jellyfin verbinden",
|
||||
"useQuickConnect": "Quick Connect verwenden",
|
||||
"quickConnectCode": "Quick Connect-Code",
|
||||
"quickConnectInstructions": "Öffne Quick Connect in Jellyfin und gib diesen Code ein.",
|
||||
"quickConnectWaiting": "Warte auf Bestätigung…",
|
||||
"quickConnectCancel": "Abbrechen",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "Ja",
|
||||
"no": "Nein",
|
||||
"delete": "Löschen",
|
||||
"edit": "Bearbeiten",
|
||||
"shuffle": "Zufall",
|
||||
"addTo": "Hinzufügen zu...",
|
||||
"createNew": "Neu erstellen",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "Optionen",
|
||||
"mute": "Stumm",
|
||||
"ok": "OK",
|
||||
"off": "Aus",
|
||||
"seasonNumber": "Staffel ${number}",
|
||||
"episodeNumberTitle": "Episode ${number} - ${title}",
|
||||
"chapterNumber": "Kapitel ${number}",
|
||||
"reconnect": "Erneut verbinden",
|
||||
"exit": "Beenden",
|
||||
"viewAll": "Alle anzeigen",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "Raster",
|
||||
"listView": "Liste",
|
||||
"showHeroSection": "Hero-Bereich anzeigen",
|
||||
"continueWatchingAction": "Aktion für Weiterschauen",
|
||||
"continueWatchingPlay": "Abspielen",
|
||||
"continueWatchingDetails": "Details öffnen",
|
||||
"useGlobalHubs": "Startlayout verwenden",
|
||||
"useGlobalHubsDescription": "Einheitliche Start-Hubs anzeigen. Sonst Bibliotheksempfehlungen verwenden.",
|
||||
"showServerNameOnHubs": "Servername bei Hubs anzeigen",
|
||||
@@ -125,6 +132,10 @@
|
||||
"showEpisodeNumberOnCardsDescription": "Staffel- und Episodennummer auf Episodenkarten anzeigen",
|
||||
"showSeasonPostersOnTabs": "Staffelposter auf Tabs anzeigen",
|
||||
"showSeasonPostersOnTabsDescription": "Poster jeder Staffel über ihrem Tab anzeigen",
|
||||
"tvFullCardLayout": "Vollflächige TV-Karten",
|
||||
"tvFullCardLayoutDescription": "TV-Karten nur mit Bild verwenden und Darstellernamen einblenden",
|
||||
"focusGlow": "Fokus-Leuchten",
|
||||
"focusGlowDescription": "Sanftes Leuchten um die fokussierte Karte anzeigen",
|
||||
"hideSpoilers": "Spoiler für nicht gesehene Episoden verbergen",
|
||||
"hideSpoilersDescription": "Vorschaubilder und Beschreibungen ungesehener Episoden verwischen",
|
||||
"playerBackend": "Player-Backend",
|
||||
@@ -248,16 +259,30 @@
|
||||
"displaySwitchDelay": "Verzögerung beim Displaywechsel",
|
||||
"tunneledPlayback": "Tunnelwiedergabe",
|
||||
"tunneledPlaybackDescription": "Video-Tunneling verwenden. Deaktivieren, wenn HDR-Wiedergabe schwarzes Video zeigt.",
|
||||
"dvConversionMode": "Dolby-Vision-Konvertierung",
|
||||
"dvConversionModeDescription": "Wähle, wie ExoPlayer Dolby-Vision-Profil-7-Dateien behandelt.",
|
||||
"dvConversionAuto": "Automatisch",
|
||||
"dvConversionNative": "Nativ / deaktiviert",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "Gerätefähigkeiten erkennen und normales Fallback-Verhalten verwenden",
|
||||
"dvConversionNativeDescription": "Natives DV7 erzwingen und DV-Konvertierungsversuch unterdrücken",
|
||||
"dvConversionDv81Description": "Inline-RPU-Konvertierung zu Dolby Vision Profil 8.1 erzwingen",
|
||||
"dvConversionHevcStripDescription": "Dolby-Vision-RPU/EL-Schichten entfernen und reines HEVC ausgeben",
|
||||
"requireProfileSelectionOnOpen": "Profil beim Öffnen abfragen",
|
||||
"requireProfileSelectionOnOpenDescription": "Profilauswahl bei jedem Öffnen der App anzeigen",
|
||||
"forceTvMode": "TV-Modus erzwingen",
|
||||
"forceTvModeDescription": "TV-Layout erzwingen. Für Geräte ohne automatische Erkennung. Neustart erforderlich.",
|
||||
"startInFullscreen": "Im Vollbildmodus starten",
|
||||
"startInFullscreenDescription": "Plezy beim Start im Vollbildmodus öffnen",
|
||||
"exitFullscreenOnPlayerClose": "Vollbild beim Schließen des Players beenden",
|
||||
"exitFullscreenOnPlayerCloseDescription": "Vollbildmodus automatisch beenden, wenn der Videoplayer geschlossen wird",
|
||||
"autoHidePerformanceOverlay": "Leistungsoverlay automatisch ausblenden",
|
||||
"autoHidePerformanceOverlayDescription": "Leistungsoverlay mit den Wiedergabesteuerungen ein-/ausblenden",
|
||||
"showNavBarLabels": "Navigationsleisten-Beschriftungen anzeigen",
|
||||
"showNavBarLabelsDescription": "Textbeschriftungen unter den Symbolen der Navigationsleiste anzeigen",
|
||||
"startupSection": "Startbereich",
|
||||
"startupSectionDescription": "Legt fest, welchen Bereich Plezy beim Start öffnet",
|
||||
"liveTvDefaultFavorites": "Standardmäßig Favoritenkanäle",
|
||||
"liveTvDefaultFavoritesDescription": "Beim Öffnen von Live TV nur Favoritenkanäle anzeigen",
|
||||
"display": "Anzeige",
|
||||
@@ -279,6 +304,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Tastenkürzel festlegen für ${actionName}",
|
||||
"clearShortcut": "Kürzel löschen",
|
||||
"noShortcutSet": "Keine Tastenkombination festgelegt",
|
||||
"currentShortcut": "Aktuelle Tastenkombination:",
|
||||
"actions": {
|
||||
"playPause": "Wiedergabe/Pause",
|
||||
"volumeUp": "Lauter",
|
||||
@@ -297,10 +324,14 @@
|
||||
"speedIncrease": "Geschwindigkeit erhöhen",
|
||||
"speedDecrease": "Geschwindigkeit verringern",
|
||||
"speedReset": "Geschwindigkeit zurücksetzen",
|
||||
"zoomIn": "Vergrößern",
|
||||
"zoomOut": "Verkleinern",
|
||||
"zoomReset": "Zoom zurücksetzen",
|
||||
"subSeekNext": "Zum nächsten Untertitel springen",
|
||||
"subSeekPrev": "Zum vorherigen Untertitel springen",
|
||||
"shaderToggle": "Shader umschalten",
|
||||
"skipMarker": "Intro/Abspann überspringen"
|
||||
"skipMarker": "Intro/Abspann überspringen",
|
||||
"screenshot": "Screenshot aufnehmen"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +365,10 @@
|
||||
"markAsWatched": "Als gesehen markieren",
|
||||
"markAsUnwatched": "Als ungesehen markieren",
|
||||
"removeFromContinueWatching": "Aus ‚Weiterschauen‘ entfernen",
|
||||
"viewDetails": "Details anzeigen",
|
||||
"goToSeries": "Zur Serie",
|
||||
"goToSeason": "Zur Staffel",
|
||||
"shufflePlay": "Zufallswiedergabe",
|
||||
"shuffleNotAvailableOffline": "Zufallswiedergabe ist offline nicht verfügbar",
|
||||
"fileInfo": "Dateiinfo",
|
||||
"deleteFromServer": "Vom Server löschen",
|
||||
"confirmDelete": "Dieses Medium und seine Dateien von deinem Server löschen?",
|
||||
@@ -347,6 +379,19 @@
|
||||
"playFromBeginning": "Von Anfang an abspielen",
|
||||
"playVersion": "Version abspielen..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "Bewerten",
|
||||
"server": "Server",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "Eine Wertung festlegen",
|
||||
"notRated": "Nicht bewertet",
|
||||
"liked": "Gefällt mir",
|
||||
"notLiked": "Nicht geliket",
|
||||
"saved": "Gespeichert",
|
||||
"notAvailable": "Keine Übereinstimmung gefunden",
|
||||
"noConnectedTrackers": "Verbinde einen Tracker in den Einstellungen, um dort zu bewerten."
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, Film",
|
||||
"mediaCardShow": "${title}, Serie",
|
||||
@@ -379,6 +424,10 @@
|
||||
"unlockRotation": "Rotation entsperren",
|
||||
"timerActive": "Schlaftimer aktiv",
|
||||
"playbackWillPauseIn": "Wiedergabe wird in ${duration} pausiert",
|
||||
"sleepTimerEndOfVideo": "Ende des aktuellen Videos",
|
||||
"sleepTimerStopAtHeader": "Beenden bei",
|
||||
"sleepTimerDurationHeader": "Timer",
|
||||
"playbackWillPauseAtEnd": "Wiedergabe wird am Ende dieses Videos pausiert",
|
||||
"stillWatching": "Schaust du noch?",
|
||||
"pausingIn": "Pause in ${seconds}s",
|
||||
"continueWatching": "Weiter",
|
||||
@@ -394,7 +443,7 @@
|
||||
"nextChapterButton": "Nächstes Kapitel",
|
||||
"muteButton": "Stumm schalten",
|
||||
"unmuteButton": "Stummschaltung aufheben",
|
||||
"settingsButton": "Videoeinstellungen",
|
||||
"settingsButton": "Wiedergabeeinstellungen",
|
||||
"tracksButton": "Audio und Untertitel",
|
||||
"chaptersButton": "Kapitel",
|
||||
"versionsButton": "Videoversionen",
|
||||
@@ -420,6 +469,8 @@
|
||||
"endsAt": "Endet um ${time}",
|
||||
"pipActive": "Wiedergabe im Bild-in-Bild-Modus",
|
||||
"pipFailed": "Bild-in-Bild konnte nicht gestartet werden",
|
||||
"screenshotSaved": "Screenshot gespeichert",
|
||||
"zoomPercent": "Zoom ${percent}%",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Erfordert Android 8.0 oder neuer",
|
||||
"iosVersion": "Erfordert iOS 15.0 oder neuer",
|
||||
@@ -436,6 +487,10 @@
|
||||
"searchSubtitles": "Untertitel suchen",
|
||||
"language": "Sprache",
|
||||
"noSubtitlesFound": "Keine Untertitel gefunden",
|
||||
"downloadedSubtitle": "Heruntergeladen",
|
||||
"noSubtitlesAvailable": "Keine Untertitel verfügbar",
|
||||
"noAudioTracksAvailable": "Keine Audiospuren verfügbar",
|
||||
"noTracksAvailable": "Keine Spuren verfügbar",
|
||||
"subtitleDownloaded": "Untertitel heruntergeladen",
|
||||
"subtitleDownloadFailed": "Untertitel konnte nicht heruntergeladen werden",
|
||||
"searchLanguages": "Sprachen suchen..."
|
||||
@@ -457,7 +512,6 @@
|
||||
"fileInfoNotAvailable": "Dateiinfo nicht verfügbar",
|
||||
"errorLoadingFileInfo": "Fehler beim Laden der Dateiinfo: ${error}",
|
||||
"errorLoadingSeries": "Fehler beim Laden der Serie",
|
||||
"errorLoadingSeason": "Fehler beim Laden der Staffel",
|
||||
"musicNotSupported": "Musikwiedergabe wird noch nicht unterstützt",
|
||||
"noDescriptionAvailable": "Keine Beschreibung verfügbar",
|
||||
"noProfilesAvailable": "Keine Profile verfügbar",
|
||||
@@ -474,8 +528,10 @@
|
||||
"metadataRefreshFailed": "Metadaten konnten nicht aktualisiert werden: ${error}",
|
||||
"logoutConfirm": "Abmeldung wirklich durchführen?",
|
||||
"noSeasonsFound": "Keine Staffeln gefunden",
|
||||
"seasonsLoadFailed": "Staffeln konnten nicht geladen werden",
|
||||
"noEpisodesFound": "Keine Episoden in der ersten Staffel gefunden",
|
||||
"noEpisodesFoundGeneral": "Keine Episoden gefunden",
|
||||
"episodesLoadFailed": "Episoden konnten nicht geladen werden",
|
||||
"noResultsFound": "Keine Ergebnisse gefunden",
|
||||
"sleepTimerSet": "Sleep-Timer gesetzt auf ${label}",
|
||||
"noItemsAvailable": "Keine Elemente verfügbar",
|
||||
@@ -501,7 +557,10 @@
|
||||
"position": "Position",
|
||||
"assOverride": "ASS-Überschreibung",
|
||||
"bold": "Fett",
|
||||
"italic": "Kursiv"
|
||||
"italic": "Kursiv",
|
||||
"renderResolution": "Render-Auflösung",
|
||||
"renderResolutionScreen": "Bildschirmauflösung",
|
||||
"renderResolutionVideo": "Videoauflösung"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "mpv-Konfiguration",
|
||||
@@ -579,7 +638,8 @@
|
||||
"pinProtectionOptional": "PIN-Schutz (optional)",
|
||||
"pinExplain": "4-stellige PIN zum Profilwechsel erforderlich.",
|
||||
"continueButton": "Weiter",
|
||||
"pinsDontMatch": "PINs stimmen nicht überein"
|
||||
"pinsDontMatch": "PINs stimmen nicht überein",
|
||||
"initializeServicesFailed": "Profildienste konnten nicht initialisiert werden"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "Verbindungen",
|
||||
@@ -588,7 +648,9 @@
|
||||
"addConnectionSubtitleScoped": "Zu ${displayName} hinzufügen: Plex, Jellyfin oder eine andere Profilverbindung",
|
||||
"sessionExpiredOne": "Sitzung für ${name} abgelaufen",
|
||||
"sessionExpiredMany": "Sitzungen für ${count} Server abgelaufen",
|
||||
"signInAgain": "Erneut anmelden"
|
||||
"signInAgain": "Erneut anmelden",
|
||||
"editJellyfinTitle": "Jellyfin-Verbindung bearbeiten",
|
||||
"editJellyfinIntro": "Füge URLs für ${serverName} hinzu oder entferne sie. Plezy verwendet die erreichbare URL mit der geringsten Latenz."
|
||||
},
|
||||
"discover": {
|
||||
"title": "Entdecken",
|
||||
@@ -609,7 +671,8 @@
|
||||
"rating": "Altersfreigabe",
|
||||
"movie": "Film",
|
||||
"tvShow": "Serie",
|
||||
"minutesLeft": "${minutes} Min übrig"
|
||||
"minutesLeft": "${minutes} Min übrig",
|
||||
"moreLikeThis": "Ähnliche Inhalte"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Suche fehlgeschlagen: ${error}",
|
||||
@@ -628,6 +691,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Mediatheken",
|
||||
"fallbackTitle": "Mediathek",
|
||||
"scanLibraryFiles": "Mediatheksdateien scannen",
|
||||
"scanLibrary": "Mediathek scannen",
|
||||
"analyze": "Analysieren",
|
||||
@@ -684,15 +748,27 @@
|
||||
"genre": "Genre",
|
||||
"year": "Jahr",
|
||||
"contentRating": "Altersfreigabe",
|
||||
"tag": "Tag"
|
||||
"tag": "Tag",
|
||||
"unwatched": "Ungesehene"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "Titel",
|
||||
"dateAdded": "Hinzugefügt am",
|
||||
"releaseDate": "Erscheinungsdatum",
|
||||
"rating": "Bewertung",
|
||||
"communityRating": "Community-Bewertung",
|
||||
"criticRating": "Kritikerbewertung",
|
||||
"userRating": "Benutzerbewertung",
|
||||
"lastPlayed": "Zuletzt abgespielt",
|
||||
"datePlayed": "Wiedergabedatum",
|
||||
"playCount": "Wiedergaben",
|
||||
"productionYear": "Produktionsjahr",
|
||||
"runtime": "Laufzeit",
|
||||
"officialRating": "Offizielle Bewertung",
|
||||
"premiereDate": "Premierendatum",
|
||||
"startDate": "Startdatum",
|
||||
"airTime": "Sendezeit",
|
||||
"studio": "Studio",
|
||||
"random": "Zufällig",
|
||||
"dateShared": "Datum geteilt",
|
||||
"latestEpisodeAirDate": "Letztes Folgenausstrahlungsdatum"
|
||||
@@ -739,6 +815,12 @@
|
||||
"noChannels": "Keine Kanäle verfügbar",
|
||||
"noDvr": "Kein DVR auf einem Server konfiguriert",
|
||||
"noPrograms": "Keine Programmdaten verfügbar",
|
||||
"liveStreamFailed": "Livestream fehlgeschlagen",
|
||||
"unknownProgram": "Unbekannte Sendung",
|
||||
"unknownHub": "Unbekannt",
|
||||
"unknownError": "Unbekannter Fehler",
|
||||
"channelNumber": "Kanal ${number}",
|
||||
"unknownChannel": "Unbekannter Kanal",
|
||||
"live": "LIVE",
|
||||
"reloadGuide": "Programmführer neu laden",
|
||||
"now": "Jetzt",
|
||||
@@ -917,12 +999,21 @@
|
||||
"deleteDownload": "Download löschen",
|
||||
"retryDownload": "Download wiederholen",
|
||||
"downloadQueued": "Download in Warteschlange",
|
||||
"downloadResumed": "Download fortgesetzt",
|
||||
"serverErrorBitrate": "Serverfehler: Datei überschreitet möglicherweise das Remote-Bitrate-Limit",
|
||||
"episodesQueued": "${count} Episoden zum Download hinzugefügt",
|
||||
"downloadDeleted": "Download gelöscht",
|
||||
"deleteConfirm": "\"${title}\" von diesem Gerät löschen?",
|
||||
"deletingWithProgress": "Lösche ${title}... (${current} von ${total})",
|
||||
"cancelledDownloadTitle": "Abgebrochener Download",
|
||||
"cancelledDownloadMessage": "Dieser Download wurde abgebrochen. Was möchtest du tun?",
|
||||
"allEpisodesAlreadyDownloaded": "Alle Episoden sind bereits heruntergeladen",
|
||||
"resumeDownload": "Download fortsetzen",
|
||||
"cancelledDownload": "Abgebrochener Download",
|
||||
"syncingFile": "${file} (${status} wird synchronisiert)",
|
||||
"downloadedFileClickToComplete": "${file} heruntergeladen — zum Abschließen klicken",
|
||||
"partialDownloadClickToComplete": "Teilweise heruntergeladen — zum Abschließen klicken",
|
||||
"deleting": "Lösche...",
|
||||
"deletingWithProgress": "Lösche ${title}... (${current} von ${total})",
|
||||
"queuedTooltip": "In Warteschlange",
|
||||
"queuedFilesTooltip": "In Warteschlange: ${files}",
|
||||
"downloadingTooltip": "Lädt herunter...",
|
||||
@@ -983,6 +1074,7 @@
|
||||
"companionRemote": {
|
||||
"title": "Companion-Fernbedienung",
|
||||
"connectedTo": "Verbunden mit ${name}",
|
||||
"unknownDevice": "Unbekanntes Gerät",
|
||||
"session": {
|
||||
"startingServer": "Remote-Server wird gestartet...",
|
||||
"failedToCreate": "Remote-Server konnte nicht gestartet werden:",
|
||||
@@ -1042,11 +1134,19 @@
|
||||
"subtitles": "Untertitel",
|
||||
"audio": "Audio",
|
||||
"searchHint": "Auf Desktop suchen..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "Keine Netzwerkschnittstelle gefunden",
|
||||
"authenticationFailed": "Authentifizierung fehlgeschlagen",
|
||||
"joinTimedOut": "Zeitüberschreitung beim Beitreten zur Sitzung",
|
||||
"failedToConnectAnyAddress": "Keine Verbindung zu einer Adresse möglich",
|
||||
"connectionLostAfterAttempts": "Verbindung nach ${attempts} Versuchen verloren",
|
||||
"connectionLost": "Verbindung verloren"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "Wiedergabeeinstellungen",
|
||||
"playbackSpeed": "Wiedergabegeschwindigkeit",
|
||||
"zoom": "Zoom",
|
||||
"sleepTimer": "Schlaftimer",
|
||||
"audioSync": "Audio-Synchronisation",
|
||||
"subtitleSync": "Untertitel-Synchronisation",
|
||||
@@ -1056,6 +1156,43 @@
|
||||
"audioPassthrough": "Audio-Durchleitung",
|
||||
"audioNormalization": "Lautstärke normalisieren"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "Farbe",
|
||||
"performance": "Leistung",
|
||||
"buffer": "Puffer",
|
||||
"app": "App",
|
||||
"decoder": "Decoder",
|
||||
"rawDecoder": "Raw-Decoder",
|
||||
"tunneling": "Tunneling",
|
||||
"aspect": "Seitenverhältnis",
|
||||
"rotation": "Drehung",
|
||||
"dvSource": "DV-Quelle",
|
||||
"dvPath": "DV-Pfad",
|
||||
"p7Conversion": "P7-Konv.",
|
||||
"sampleRate": "Abtastrate",
|
||||
"pixelFormat": "Pixelformat",
|
||||
"hwFormat": "HW-Format",
|
||||
"matrix": "Matrix",
|
||||
"primaries": "Primärfarben",
|
||||
"transfer": "Transfer",
|
||||
"renderFps": "Render-FPS",
|
||||
"displayFps": "Display-FPS",
|
||||
"avSync": "A/V-Sync",
|
||||
"dropped": "Verworfen",
|
||||
"dvRpus": "DV-RPUs",
|
||||
"dvRpuAverage": "DV-RPU Ø",
|
||||
"dvSampleAverage": "DV-Sample Ø",
|
||||
"maxLuma": "Max. Luma",
|
||||
"minLuma": "Min. Luma",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "Cache genutzt",
|
||||
"cacheLimit": "Cache-Limit",
|
||||
"speed": "Geschwindigkeit",
|
||||
"player": "Player",
|
||||
"memory": "Speicher",
|
||||
"uiFps": "UI-FPS"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "Externer Player",
|
||||
"useExternalPlayer": "Externen Player verwenden",
|
||||
@@ -1065,6 +1202,7 @@
|
||||
"systemDefault": "Systemstandard",
|
||||
"addCustomPlayer": "Benutzerdefinierten Player hinzufügen",
|
||||
"playerName": "Playername",
|
||||
"playerNameHint": "Mein Player",
|
||||
"playerCommand": "Befehl",
|
||||
"playerPackage": "Paketname",
|
||||
"playerUrlScheme": "URL-Schema",
|
||||
@@ -1224,9 +1362,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Jellyfin-Server hinzufügen",
|
||||
"jellyfinUrlIntro": "Gib die Server-URL ein, z. B. `https://jellyfin.example.com`.",
|
||||
"serverUrl": "Server-URL",
|
||||
"serverUrls": "Server-URLs",
|
||||
"serverUrlsHelper": "Mehrere URLs möglich, durch Kommas getrennt.",
|
||||
"findServer": "Server finden",
|
||||
"searchingLocalServers": "Suche nach lokalen Jellyfin-Servern...",
|
||||
"localServers": "Lokale Jellyfin-Server",
|
||||
"username": "Benutzername",
|
||||
"password": "Passwort",
|
||||
"signIn": "Anmelden",
|
||||
@@ -1236,17 +1376,12 @@
|
||||
"signInFailed": "Anmeldung fehlgeschlagen: ${error}",
|
||||
"quickConnectFailed": "Quick Connect fehlgeschlagen: ${error}",
|
||||
"addPlexTitle": "Mit Plex anmelden",
|
||||
"plexAuthIntro": "Melde dich mit Browser oder QR-Code an.",
|
||||
"plexQRPrompt": "Scanne diesen QR-Code zum Anmelden.",
|
||||
"waitingForPlexConfirmation": "Warte auf Bestätigung durch plex.tv…",
|
||||
"pinExpired": "PIN ist vor der Anmeldung abgelaufen. Bitte erneut versuchen.",
|
||||
"duplicatePlexAccount": "Bereits bei Plex angemeldet. Melde dich ab, um Konten zu wechseln.",
|
||||
"failedToRegisterAccount": "Konto konnte nicht registriert werden: ${error}",
|
||||
"enterJellyfinUrlError": "Gib die URL deines Jellyfin-Servers ein",
|
||||
"addConnectionTitle": "Verbindung hinzufügen",
|
||||
"addConnectionTitleScoped": "Zu ${name} hinzufügen",
|
||||
"addConnectionIntroGlobal": "Füge einen weiteren Medienserver hinzu. Plex und Jellyfin erscheinen zusammen auf der Startseite.",
|
||||
"addConnectionIntroScoped": "Füge einen neuen Server hinzu oder leihe einen von einem anderen Profil aus.",
|
||||
"signInWithPlexCard": "Mit Plex anmelden",
|
||||
"signInWithPlexCardSubtitle": "Dieses Gerät autorisieren. Geteilte Server werden hinzugefügt.",
|
||||
"signInWithPlexCardSubtitleScoped": "Ein Plex-Konto autorisieren. Home-Benutzer werden zu Profilen.",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "or",
|
||||
"connectToJellyfin": "Connect to Jellyfin",
|
||||
"useQuickConnect": "Use Quick Connect",
|
||||
"quickConnectCode": "Quick Connect code",
|
||||
"quickConnectInstructions": "Open Quick Connect in Jellyfin and enter this code.",
|
||||
"quickConnectWaiting": "Waiting for approval…",
|
||||
"quickConnectCancel": "Cancel",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "Yes",
|
||||
"no": "No",
|
||||
"delete": "Delete",
|
||||
"edit": "Edit",
|
||||
"shuffle": "Shuffle",
|
||||
"addTo": "Add to...",
|
||||
"createNew": "Create new",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "Settings",
|
||||
"mute": "Mute",
|
||||
"ok": "OK",
|
||||
"off": "Off",
|
||||
"seasonNumber": "Season ${number}",
|
||||
"episodeNumberTitle": "Episode ${number} - ${title}",
|
||||
"chapterNumber": "Chapter ${number}",
|
||||
"reconnect": "Reconnect",
|
||||
"exit": "Exit",
|
||||
"viewAll": "View All",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "Grid",
|
||||
"listView": "List",
|
||||
"showHeroSection": "Show Hero Section",
|
||||
"continueWatchingAction": "Continue Watching Action",
|
||||
"continueWatchingPlay": "Play",
|
||||
"continueWatchingDetails": "Open Details",
|
||||
"useGlobalHubs": "Use Home Layout",
|
||||
"useGlobalHubsDescription": "Show unified home hubs. Otherwise use library recommendations.",
|
||||
"showServerNameOnHubs": "Show Server Name on Hubs",
|
||||
@@ -125,6 +132,16 @@
|
||||
"showEpisodeNumberOnCardsDescription": "Show season and episode number on episode cards",
|
||||
"showSeasonPostersOnTabs": "Show Season Posters on Tabs",
|
||||
"showSeasonPostersOnTabsDescription": "Show each season's poster above its tab",
|
||||
"tvFullCardLayout": "Full TV Cards",
|
||||
"tvFullCardLayoutDescription": "Use image-only TV cards with actor names overlaid",
|
||||
"focusGlow": "Focus Glow",
|
||||
"focusGlowDescription": "Draw a soft glow around the focused card",
|
||||
"visualEffects": "Visual Effects",
|
||||
"visualEffectsAuto": "Auto",
|
||||
"visualEffectsAutoDescription": "Reduce effects automatically on low-power devices",
|
||||
"visualEffectsFull": "Full",
|
||||
"visualEffectsReduced": "Reduced",
|
||||
"visualEffectsReducedDescription": "Fewer animations and lower-resolution artwork",
|
||||
"hideSpoilers": "Hide Spoilers for Unwatched Episodes",
|
||||
"hideSpoilersDescription": "Blur thumbnails and descriptions for unwatched episodes",
|
||||
"playerBackend": "Player Backend",
|
||||
@@ -248,16 +265,30 @@
|
||||
"displaySwitchDelay": "Display Switch Delay",
|
||||
"tunneledPlayback": "Tunneled Playback",
|
||||
"tunneledPlaybackDescription": "Use video tunneling. Disable if HDR playback shows black video.",
|
||||
"dvConversionMode": "Dolby Vision Conversion",
|
||||
"dvConversionModeDescription": "Choose how ExoPlayer handles Dolby Vision Profile 7 files.",
|
||||
"dvConversionAuto": "Auto",
|
||||
"dvConversionNative": "Native / Disabled",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "Use device capability detection and normal fallback behavior",
|
||||
"dvConversionNativeDescription": "Force native DV7 and suppress DV conversion retry",
|
||||
"dvConversionDv81Description": "Force inline RPU conversion to Dolby Vision profile 8.1",
|
||||
"dvConversionHevcStripDescription": "Strip Dolby Vision RPU/EL layers and present plain HEVC",
|
||||
"requireProfileSelectionOnOpen": "Ask for profile on app open",
|
||||
"requireProfileSelectionOnOpenDescription": "Show profile selection every time the app is opened",
|
||||
"forceTvMode": "Force TV mode",
|
||||
"forceTvModeDescription": "Force TV layout. For devices that don't auto-detect. Requires restart.",
|
||||
"startInFullscreen": "Start in fullscreen",
|
||||
"startInFullscreenDescription": "Open Plezy in fullscreen mode at launch",
|
||||
"exitFullscreenOnPlayerClose": "Exit fullscreen on player close",
|
||||
"exitFullscreenOnPlayerCloseDescription": "Automatically exit fullscreen when closing the video player",
|
||||
"autoHidePerformanceOverlay": "Auto-Hide Performance Overlay",
|
||||
"autoHidePerformanceOverlayDescription": "Fade the performance overlay with the playback controls",
|
||||
"showNavBarLabels": "Show Navigation Bar Labels",
|
||||
"showNavBarLabelsDescription": "Display text labels under navigation bar icons",
|
||||
"startupSection": "Startup Section",
|
||||
"startupSectionDescription": "Choose which section Plezy opens to when it starts",
|
||||
"liveTvDefaultFavorites": "Default to Favorite Channels",
|
||||
"liveTvDefaultFavoritesDescription": "Show only favorite channels when opening Live TV",
|
||||
"display": "Display",
|
||||
@@ -279,6 +310,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Set Shortcut for ${actionName}",
|
||||
"clearShortcut": "Clear shortcut",
|
||||
"noShortcutSet": "No shortcut set",
|
||||
"currentShortcut": "Current shortcut:",
|
||||
"actions": {
|
||||
"playPause": "Play/Pause",
|
||||
"volumeUp": "Volume Up",
|
||||
@@ -297,10 +330,14 @@
|
||||
"speedIncrease": "Increase Speed",
|
||||
"speedDecrease": "Decrease Speed",
|
||||
"speedReset": "Reset Speed",
|
||||
"zoomIn": "Zoom In",
|
||||
"zoomOut": "Zoom Out",
|
||||
"zoomReset": "Reset Zoom",
|
||||
"subSeekNext": "Seek to Next Subtitle",
|
||||
"subSeekPrev": "Seek to Previous Subtitle",
|
||||
"shaderToggle": "Toggle Shaders",
|
||||
"skipMarker": "Skip Intro/Credits"
|
||||
"skipMarker": "Skip Intro/Credits",
|
||||
"screenshot": "Take Screenshot"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +371,10 @@
|
||||
"markAsWatched": "Mark as Watched",
|
||||
"markAsUnwatched": "Mark as Unwatched",
|
||||
"removeFromContinueWatching": "Remove from Continue Watching",
|
||||
"viewDetails": "View details",
|
||||
"goToSeries": "Go to series",
|
||||
"goToSeason": "Go to season",
|
||||
"shufflePlay": "Shuffle Play",
|
||||
"shuffleNotAvailableOffline": "Shuffle not available offline",
|
||||
"fileInfo": "File Info",
|
||||
"deleteFromServer": "Delete from server",
|
||||
"confirmDelete": "Delete this media and its files from your server?",
|
||||
@@ -347,6 +385,19 @@
|
||||
"playFromBeginning": "Play from Beginning",
|
||||
"playVersion": "Play Version..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "Rate",
|
||||
"server": "Server",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "Set a score",
|
||||
"notRated": "Not rated",
|
||||
"liked": "Liked",
|
||||
"notLiked": "Not liked",
|
||||
"saved": "Saved",
|
||||
"notAvailable": "No match found",
|
||||
"noConnectedTrackers": "Connect a tracker in Settings to rate there."
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, movie",
|
||||
"mediaCardShow": "${title}, TV show",
|
||||
@@ -379,6 +430,10 @@
|
||||
"unlockRotation": "Unlock rotation",
|
||||
"timerActive": "Timer Active",
|
||||
"playbackWillPauseIn": "Playback will pause in ${duration}",
|
||||
"sleepTimerEndOfVideo": "End of current video",
|
||||
"sleepTimerStopAtHeader": "Stop at",
|
||||
"sleepTimerDurationHeader": "Timer",
|
||||
"playbackWillPauseAtEnd": "Playback will pause at the end of this video",
|
||||
"stillWatching": "Still watching?",
|
||||
"pausingIn": "Pausing in ${seconds}s",
|
||||
"continueWatching": "Continue",
|
||||
@@ -394,7 +449,7 @@
|
||||
"nextChapterButton": "Next chapter",
|
||||
"muteButton": "Mute",
|
||||
"unmuteButton": "Unmute",
|
||||
"settingsButton": "Video settings",
|
||||
"settingsButton": "Playback Settings",
|
||||
"tracksButton": "Audio & Subtitles",
|
||||
"chaptersButton": "Chapters",
|
||||
"versionsButton": "Video versions",
|
||||
@@ -420,6 +475,8 @@
|
||||
"endsAt": "Ends at ${time}",
|
||||
"pipActive": "Playing in Picture-in-Picture",
|
||||
"pipFailed": "Picture-in-picture failed to start",
|
||||
"screenshotSaved": "Screenshot saved",
|
||||
"zoomPercent": "Zoom ${percent}%",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Requires Android 8.0 or newer",
|
||||
"iosVersion": "Requires iOS 15.0 or newer",
|
||||
@@ -436,6 +493,10 @@
|
||||
"searchSubtitles": "Search Subtitles",
|
||||
"language": "Language",
|
||||
"noSubtitlesFound": "No subtitles found",
|
||||
"downloadedSubtitle": "Downloaded",
|
||||
"noSubtitlesAvailable": "No subtitles available",
|
||||
"noAudioTracksAvailable": "No audio tracks available",
|
||||
"noTracksAvailable": "No tracks available",
|
||||
"subtitleDownloaded": "Subtitle downloaded",
|
||||
"subtitleDownloadFailed": "Failed to download subtitle",
|
||||
"searchLanguages": "Search languages..."
|
||||
@@ -457,7 +518,6 @@
|
||||
"fileInfoNotAvailable": "File information not available",
|
||||
"errorLoadingFileInfo": "Error loading file info: ${error}",
|
||||
"errorLoadingSeries": "Error loading series",
|
||||
"errorLoadingSeason": "Error loading season",
|
||||
"musicNotSupported": "Music playback is not yet supported",
|
||||
"noDescriptionAvailable": "No description available",
|
||||
"noProfilesAvailable": "No profiles available",
|
||||
@@ -474,8 +534,10 @@
|
||||
"metadataRefreshFailed": "Failed to refresh metadata: ${error}",
|
||||
"logoutConfirm": "Are you sure you want to logout?",
|
||||
"noSeasonsFound": "No seasons found",
|
||||
"seasonsLoadFailed": "Couldn't load seasons",
|
||||
"noEpisodesFound": "No episodes found in first season",
|
||||
"noEpisodesFoundGeneral": "No episodes found",
|
||||
"episodesLoadFailed": "Couldn't load episodes",
|
||||
"noResultsFound": "No results found",
|
||||
"sleepTimerSet": "Sleep timer set for ${label}",
|
||||
"noItemsAvailable": "No items available",
|
||||
@@ -501,7 +563,10 @@
|
||||
"position": "Position",
|
||||
"assOverride": "ASS Override",
|
||||
"bold": "Bold",
|
||||
"italic": "Italic"
|
||||
"italic": "Italic",
|
||||
"renderResolution": "Render Resolution",
|
||||
"renderResolutionScreen": "Screen resolution",
|
||||
"renderResolutionVideo": "Video resolution"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "mpv.conf",
|
||||
@@ -579,7 +644,8 @@
|
||||
"pinProtectionOptional": "PIN protection (optional)",
|
||||
"pinExplain": "4-digit PIN required to switch profiles.",
|
||||
"continueButton": "Continue",
|
||||
"pinsDontMatch": "PINs don't match"
|
||||
"pinsDontMatch": "PINs don't match",
|
||||
"initializeServicesFailed": "Failed to initialize profile services"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "Connections",
|
||||
@@ -588,7 +654,9 @@
|
||||
"addConnectionSubtitleScoped": "Add to ${displayName}: Plex, Jellyfin, or another profile connection",
|
||||
"sessionExpiredOne": "Session expired for ${name}",
|
||||
"sessionExpiredMany": "Session expired for ${count} servers",
|
||||
"signInAgain": "Sign in again"
|
||||
"signInAgain": "Sign in again",
|
||||
"editJellyfinTitle": "Edit Jellyfin connection",
|
||||
"editJellyfinIntro": "Add or remove URLs for ${serverName}. Plezy will use the reachable URL with the lowest latency."
|
||||
},
|
||||
"discover": {
|
||||
"title": "Discover",
|
||||
@@ -609,7 +677,8 @@
|
||||
"rating": "Rating",
|
||||
"movie": "Movie",
|
||||
"tvShow": "TV Show",
|
||||
"minutesLeft": "${minutes} min left"
|
||||
"minutesLeft": "${minutes} min left",
|
||||
"moreLikeThis": "More Like This"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Search failed: ${error}",
|
||||
@@ -628,6 +697,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Libraries",
|
||||
"fallbackTitle": "Library",
|
||||
"scanLibraryFiles": "Scan Library Files",
|
||||
"scanLibrary": "Scan Library",
|
||||
"analyze": "Analyze",
|
||||
@@ -684,15 +754,27 @@
|
||||
"genre": "Genre",
|
||||
"year": "Year",
|
||||
"contentRating": "Content Rating",
|
||||
"tag": "Tag"
|
||||
"tag": "Tag",
|
||||
"unwatched": "Unwatched"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "Title",
|
||||
"dateAdded": "Date Added",
|
||||
"releaseDate": "Release Date",
|
||||
"rating": "Rating",
|
||||
"communityRating": "Community Rating",
|
||||
"criticRating": "Critic Rating",
|
||||
"userRating": "User Rating",
|
||||
"lastPlayed": "Last Played",
|
||||
"datePlayed": "Date Played",
|
||||
"playCount": "Play Count",
|
||||
"productionYear": "Production Year",
|
||||
"runtime": "Runtime",
|
||||
"officialRating": "Official Rating",
|
||||
"premiereDate": "Premiere Date",
|
||||
"startDate": "Start Date",
|
||||
"airTime": "Air Time",
|
||||
"studio": "Studio",
|
||||
"random": "Random",
|
||||
"dateShared": "Date Shared",
|
||||
"latestEpisodeAirDate": "Latest Episode Air Date"
|
||||
@@ -739,6 +821,12 @@
|
||||
"noChannels": "No channels available",
|
||||
"noDvr": "No DVR configured on any server",
|
||||
"noPrograms": "No program data available",
|
||||
"liveStreamFailed": "Live stream failed",
|
||||
"unknownProgram": "Unknown Program",
|
||||
"unknownHub": "Unknown",
|
||||
"unknownError": "Unknown error",
|
||||
"channelNumber": "Channel ${number}",
|
||||
"unknownChannel": "Unknown channel",
|
||||
"live": "LIVE",
|
||||
"reloadGuide": "Reload Guide",
|
||||
"now": "Now",
|
||||
@@ -899,7 +987,10 @@
|
||||
"participantResumed": "${name} resumed",
|
||||
"participantSeeked": "${name} seeked",
|
||||
"participantBuffering": "${name} is buffering",
|
||||
"participantNeedsUpdate": "${name} is on an older app version — sync unavailable",
|
||||
"resumingWithout": "Resuming without ${name}",
|
||||
"waitingForParticipants": "Waiting for others to load...",
|
||||
"waitingForName": "Waiting for ${name}...",
|
||||
"recentRooms": "Recent Rooms",
|
||||
"renameRoom": "Rename Room",
|
||||
"removeRoom": "Remove",
|
||||
@@ -917,10 +1008,19 @@
|
||||
"deleteDownload": "Delete download",
|
||||
"retryDownload": "Retry download",
|
||||
"downloadQueued": "Download queued",
|
||||
"downloadResumed": "Download resumed",
|
||||
"serverErrorBitrate": "Server error: file may exceed the remote bitrate limit",
|
||||
"episodesQueued": "${count} episodes queued for download",
|
||||
"downloadDeleted": "Download deleted",
|
||||
"deleteConfirm": "Delete \"${title}\" from this device?",
|
||||
"cancelledDownloadTitle": "Cancelled Download",
|
||||
"cancelledDownloadMessage": "This download was cancelled. What would you like to do?",
|
||||
"allEpisodesAlreadyDownloaded": "All episodes already downloaded",
|
||||
"resumeDownload": "Resume download",
|
||||
"cancelledDownload": "Cancelled download",
|
||||
"syncingFile": "${file} (syncing ${status})",
|
||||
"downloadedFileClickToComplete": "Downloaded ${file} - Click to complete",
|
||||
"partialDownloadClickToComplete": "Partially downloaded - Click to complete",
|
||||
"deleting": "Deleting...",
|
||||
"deletingWithProgress": "Deleting ${title}... (${current} of ${total})",
|
||||
"queuedTooltip": "Queued",
|
||||
@@ -983,6 +1083,7 @@
|
||||
"companionRemote": {
|
||||
"title": "Companion Remote",
|
||||
"connectedTo": "Connected to ${name}",
|
||||
"unknownDevice": "Unknown Device",
|
||||
"session": {
|
||||
"startingServer": "Starting remote server...",
|
||||
"failedToCreate": "Failed to start remote server:",
|
||||
@@ -1042,11 +1143,19 @@
|
||||
"subtitles": "Subtitles",
|
||||
"audio": "Audio",
|
||||
"searchHint": "Search on desktop..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "No network interface found",
|
||||
"authenticationFailed": "Authentication failed",
|
||||
"joinTimedOut": "Timed out joining session",
|
||||
"failedToConnectAnyAddress": "Failed to connect to any address",
|
||||
"connectionLostAfterAttempts": "Connection lost after ${attempts} attempts",
|
||||
"connectionLost": "Connection lost"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "Playback Settings",
|
||||
"playbackSpeed": "Playback Speed",
|
||||
"zoom": "Zoom",
|
||||
"sleepTimer": "Sleep Timer",
|
||||
"audioSync": "Audio Sync",
|
||||
"subtitleSync": "Subtitle Sync",
|
||||
@@ -1056,6 +1165,43 @@
|
||||
"audioPassthrough": "Audio Passthrough",
|
||||
"audioNormalization": "Normalize Loudness"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "Color",
|
||||
"performance": "Performance",
|
||||
"buffer": "Buffer",
|
||||
"app": "App",
|
||||
"decoder": "Decoder",
|
||||
"rawDecoder": "Raw Decoder",
|
||||
"tunneling": "Tunneling",
|
||||
"aspect": "Aspect",
|
||||
"rotation": "Rotation",
|
||||
"dvSource": "DV Source",
|
||||
"dvPath": "DV Path",
|
||||
"p7Conversion": "P7 Conv",
|
||||
"sampleRate": "Sample Rate",
|
||||
"pixelFormat": "Pixel Fmt",
|
||||
"hwFormat": "HW Fmt",
|
||||
"matrix": "Matrix",
|
||||
"primaries": "Primaries",
|
||||
"transfer": "Transfer",
|
||||
"renderFps": "Render FPS",
|
||||
"displayFps": "Display FPS",
|
||||
"avSync": "A/V Sync",
|
||||
"dropped": "Dropped",
|
||||
"dvRpus": "DV RPUs",
|
||||
"dvRpuAverage": "DV RPU Avg",
|
||||
"dvSampleAverage": "DV Sample Avg",
|
||||
"maxLuma": "Max Luma",
|
||||
"minLuma": "Min Luma",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "Cache Used",
|
||||
"cacheLimit": "Cache Limit",
|
||||
"speed": "Speed",
|
||||
"player": "Player",
|
||||
"memory": "Memory",
|
||||
"uiFps": "UI FPS"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "External Player",
|
||||
"useExternalPlayer": "Use External Player",
|
||||
@@ -1065,6 +1211,7 @@
|
||||
"systemDefault": "System Default",
|
||||
"addCustomPlayer": "Add Custom Player",
|
||||
"playerName": "Player Name",
|
||||
"playerNameHint": "My Player",
|
||||
"playerCommand": "Command",
|
||||
"playerPackage": "Package Name",
|
||||
"playerUrlScheme": "URL Scheme",
|
||||
@@ -1224,9 +1371,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Add Jellyfin server",
|
||||
"jellyfinUrlIntro": "Enter the server URL, e.g. `https://jellyfin.example.com`.",
|
||||
"serverUrl": "Server URL",
|
||||
"serverUrls": "Server URLs",
|
||||
"serverUrlsHelper": "Multiple URLs allowed, separated by commas.",
|
||||
"findServer": "Find server",
|
||||
"searchingLocalServers": "Looking for local Jellyfin servers...",
|
||||
"localServers": "Local Jellyfin servers",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"signIn": "Sign in",
|
||||
@@ -1236,17 +1385,12 @@
|
||||
"signInFailed": "Sign-in failed: ${error}",
|
||||
"quickConnectFailed": "Quick Connect failed: ${error}",
|
||||
"addPlexTitle": "Sign in with Plex",
|
||||
"plexAuthIntro": "Sign in with a browser or QR code.",
|
||||
"plexQRPrompt": "Scan this QR code to sign in.",
|
||||
"waitingForPlexConfirmation": "Waiting for plex.tv to confirm your sign-in…",
|
||||
"pinExpired": "PIN expired before sign-in. Please try again.",
|
||||
"duplicatePlexAccount": "Already signed in to Plex. Sign out to switch accounts.",
|
||||
"failedToRegisterAccount": "Failed to register account: ${error}",
|
||||
"enterJellyfinUrlError": "Enter your Jellyfin server URL",
|
||||
"addConnectionTitle": "Add connection",
|
||||
"addConnectionTitleScoped": "Add to ${name}",
|
||||
"addConnectionIntroGlobal": "Add another media server. Plex and Jellyfin appear together on Home.",
|
||||
"addConnectionIntroScoped": "Add a new server, or borrow one from another profile.",
|
||||
"signInWithPlexCard": "Sign in with Plex",
|
||||
"signInWithPlexCardSubtitle": "Authorize this device. Shared servers are added.",
|
||||
"signInWithPlexCardSubtitleScoped": "Authorize a Plex account. Home users become profiles.",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "o",
|
||||
"connectToJellyfin": "Conectar a Jellyfin",
|
||||
"useQuickConnect": "Usar Quick Connect",
|
||||
"quickConnectCode": "Código de Quick Connect",
|
||||
"quickConnectInstructions": "Abre Quick Connect en Jellyfin e introduce este código.",
|
||||
"quickConnectWaiting": "Esperando aprobación…",
|
||||
"quickConnectCancel": "Cancelar",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "Sí",
|
||||
"no": "No",
|
||||
"delete": "Eliminar",
|
||||
"edit": "Editar",
|
||||
"shuffle": "Aleatorio",
|
||||
"addTo": "Añadir a...",
|
||||
"createNew": "Crear",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "Ajustes",
|
||||
"mute": "Silencio",
|
||||
"ok": "OK",
|
||||
"off": "Desactivado",
|
||||
"seasonNumber": "Temporada ${number}",
|
||||
"episodeNumberTitle": "Episodio ${number} - ${title}",
|
||||
"chapterNumber": "Capítulo ${number}",
|
||||
"reconnect": "Reconectar",
|
||||
"exit": "Salir",
|
||||
"viewAll": "Ver todo",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "Cuadrícula",
|
||||
"listView": "Lista",
|
||||
"showHeroSection": "Mostrar Sección Destacada",
|
||||
"continueWatchingAction": "Acción de Seguir viendo",
|
||||
"continueWatchingPlay": "Reproducir",
|
||||
"continueWatchingDetails": "Abrir detalles",
|
||||
"useGlobalHubs": "Usar diseño de inicio",
|
||||
"useGlobalHubsDescription": "Mostrar hubs de inicio unificados. Si no, usar recomendaciones de biblioteca.",
|
||||
"showServerNameOnHubs": "Mostrar Nombre del Servidor en los Hubs",
|
||||
@@ -125,6 +132,10 @@
|
||||
"showEpisodeNumberOnCardsDescription": "Mostrar temporada y episodio en tarjetas de episodio",
|
||||
"showSeasonPostersOnTabs": "Mostrar pósters de temporada en las pestañas",
|
||||
"showSeasonPostersOnTabsDescription": "Mostrar el póster de cada temporada sobre su pestaña",
|
||||
"tvFullCardLayout": "Tarjetas TV completas",
|
||||
"tvFullCardLayoutDescription": "Usar tarjetas TV solo con imagen y nombres de actores superpuestos",
|
||||
"focusGlow": "Brillo de foco",
|
||||
"focusGlowDescription": "Mostrar un brillo suave alrededor de la tarjeta con foco",
|
||||
"hideSpoilers": "Ocultar spoilers de episodios no vistos",
|
||||
"hideSpoilersDescription": "Desenfocar miniaturas y descripciones de episodios no vistos",
|
||||
"playerBackend": "Reproductor",
|
||||
@@ -248,16 +259,30 @@
|
||||
"displaySwitchDelay": "Retraso de cambio de pantalla",
|
||||
"tunneledPlayback": "Reproducción tunelizada",
|
||||
"tunneledPlaybackDescription": "Usar tunelización de video. Desactívala si HDR muestra video negro.",
|
||||
"dvConversionMode": "Conversión de Dolby Vision",
|
||||
"dvConversionModeDescription": "Elige cómo ExoPlayer gestiona archivos Dolby Vision Profile 7.",
|
||||
"dvConversionAuto": "Automático",
|
||||
"dvConversionNative": "Nativo / desactivado",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "Usar detección de capacidades del dispositivo y el comportamiento de respaldo normal",
|
||||
"dvConversionNativeDescription": "Forzar DV7 nativo y suprimir el reintento de conversión DV",
|
||||
"dvConversionDv81Description": "Forzar conversión RPU en línea a Dolby Vision perfil 8.1",
|
||||
"dvConversionHevcStripDescription": "Quitar capas RPU/EL de Dolby Vision y presentar HEVC normal",
|
||||
"requireProfileSelectionOnOpen": "Pedir perfil al abrir la app",
|
||||
"requireProfileSelectionOnOpenDescription": "Mostrar selección de perfil cada vez que se abre la aplicación",
|
||||
"forceTvMode": "Forzar modo TV",
|
||||
"forceTvModeDescription": "Forzar diseño TV. Para dispositivos que no lo detectan. Requiere reinicio.",
|
||||
"startInFullscreen": "Iniciar en pantalla completa",
|
||||
"startInFullscreenDescription": "Abrir Plezy en modo pantalla completa al iniciar",
|
||||
"exitFullscreenOnPlayerClose": "Salir de pantalla completa al cerrar el reproductor",
|
||||
"exitFullscreenOnPlayerCloseDescription": "Salir automáticamente del modo de pantalla completa al cerrar el reproductor de vídeo",
|
||||
"autoHidePerformanceOverlay": "Ocultar superposición de rendimiento automáticamente",
|
||||
"autoHidePerformanceOverlayDescription": "Desvanecer la superposición de rendimiento con los controles de reproducción",
|
||||
"showNavBarLabels": "Mostrar etiquetas de la barra de navegación",
|
||||
"showNavBarLabelsDescription": "Mostrar etiquetas de texto bajo los iconos de la barra de navegación",
|
||||
"startupSection": "Sección de inicio",
|
||||
"startupSectionDescription": "Elige qué sección abre Plezy al iniciarse",
|
||||
"liveTvDefaultFavorites": "Canales favoritos por defecto",
|
||||
"liveTvDefaultFavoritesDescription": "Mostrar solo canales favoritos al abrir TV en vivo",
|
||||
"display": "Pantalla",
|
||||
@@ -279,6 +304,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Establecer atajo para ${actionName}",
|
||||
"clearShortcut": "Borrar atajo",
|
||||
"noShortcutSet": "Sin atajo asignado",
|
||||
"currentShortcut": "Atajo actual:",
|
||||
"actions": {
|
||||
"playPause": "Reproducir/Pausar",
|
||||
"volumeUp": "Subir Volumen",
|
||||
@@ -297,10 +324,14 @@
|
||||
"speedIncrease": "Aumentar Velocidad",
|
||||
"speedDecrease": "Disminuir Velocidad",
|
||||
"speedReset": "Restablecer Velocidad",
|
||||
"zoomIn": "Acercar",
|
||||
"zoomOut": "Alejar",
|
||||
"zoomReset": "Restablecer zoom",
|
||||
"subSeekNext": "Ir al Siguiente Subtítulo",
|
||||
"subSeekPrev": "Ir al Anterior Subtítulo",
|
||||
"shaderToggle": "Alternar Shaders",
|
||||
"skipMarker": "Saltar Intro/Créditos"
|
||||
"skipMarker": "Saltar Intro/Créditos",
|
||||
"screenshot": "Tomar captura de pantalla"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +365,10 @@
|
||||
"markAsWatched": "Marcar como Visto",
|
||||
"markAsUnwatched": "Marcar como No Visto",
|
||||
"removeFromContinueWatching": "Eliminar de Seguir Viendo",
|
||||
"viewDetails": "Ver detalles",
|
||||
"goToSeries": "Ir a la serie",
|
||||
"goToSeason": "Ir a la temporada",
|
||||
"shufflePlay": "Reproducción Aleatoria",
|
||||
"shuffleNotAvailableOffline": "La reproducción aleatoria no está disponible sin conexión",
|
||||
"fileInfo": "Información del Archivo",
|
||||
"deleteFromServer": "Eliminar del servidor",
|
||||
"confirmDelete": "¿Eliminar este medio y sus archivos de tu servidor?",
|
||||
@@ -347,6 +379,19 @@
|
||||
"playFromBeginning": "Reproducir desde el inicio",
|
||||
"playVersion": "Reproducir versión..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "Calificar",
|
||||
"server": "Servidor",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "Establecer puntuación",
|
||||
"notRated": "Sin calificar",
|
||||
"liked": "Me gusta",
|
||||
"notLiked": "Sin Me gusta",
|
||||
"saved": "Guardado",
|
||||
"notAvailable": "No se encontró coincidencia",
|
||||
"noConnectedTrackers": "Conecta un tracker en Ajustes para calificar allí."
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, película",
|
||||
"mediaCardShow": "${title}, serie de TV",
|
||||
@@ -379,6 +424,10 @@
|
||||
"unlockRotation": "Desbloquear rotación",
|
||||
"timerActive": "Temporizador Activo",
|
||||
"playbackWillPauseIn": "La reproducción se pausará en ${duration}",
|
||||
"sleepTimerEndOfVideo": "Fin del video actual",
|
||||
"sleepTimerStopAtHeader": "Detener en",
|
||||
"sleepTimerDurationHeader": "Temporizador",
|
||||
"playbackWillPauseAtEnd": "La reproducción se pausará al final de este video",
|
||||
"stillWatching": "¿Sigues viendo?",
|
||||
"pausingIn": "Pausa en ${seconds}s",
|
||||
"continueWatching": "Continuar",
|
||||
@@ -394,7 +443,7 @@
|
||||
"nextChapterButton": "Capítulo siguiente",
|
||||
"muteButton": "Silenciar",
|
||||
"unmuteButton": "Activar sonido",
|
||||
"settingsButton": "Ajustes de video",
|
||||
"settingsButton": "Ajustes de reproducción",
|
||||
"tracksButton": "Audio y subtítulos",
|
||||
"chaptersButton": "Capítulos",
|
||||
"versionsButton": "Versiones de video",
|
||||
@@ -420,6 +469,8 @@
|
||||
"endsAt": "Termina a las ${time}",
|
||||
"pipActive": "Reproduciendo en Imagen en Imagen",
|
||||
"pipFailed": "Error al iniciar Imagen en Imagen",
|
||||
"screenshotSaved": "Captura de pantalla guardada",
|
||||
"zoomPercent": "Zoom ${percent}%",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Requiere Android 8.0 o más reciente",
|
||||
"iosVersion": "Requiere iOS 15.0 o más reciente",
|
||||
@@ -436,6 +487,10 @@
|
||||
"searchSubtitles": "Buscar subtítulos",
|
||||
"language": "Idioma",
|
||||
"noSubtitlesFound": "No se encontraron subtítulos",
|
||||
"downloadedSubtitle": "Descargado",
|
||||
"noSubtitlesAvailable": "No hay subtítulos disponibles",
|
||||
"noAudioTracksAvailable": "No hay pistas de audio disponibles",
|
||||
"noTracksAvailable": "No hay pistas disponibles",
|
||||
"subtitleDownloaded": "Subtítulo descargado",
|
||||
"subtitleDownloadFailed": "Error al descargar subtítulo",
|
||||
"searchLanguages": "Buscar idiomas..."
|
||||
@@ -457,7 +512,6 @@
|
||||
"fileInfoNotAvailable": "Información de archivo no disponible",
|
||||
"errorLoadingFileInfo": "Error al cargar info de archivo: ${error}",
|
||||
"errorLoadingSeries": "Error al cargar la serie",
|
||||
"errorLoadingSeason": "Error al cargar la temporada",
|
||||
"musicNotSupported": "La reproducción de música aún no está soportada",
|
||||
"noDescriptionAvailable": "No hay descripción disponible",
|
||||
"noProfilesAvailable": "No hay perfiles disponibles",
|
||||
@@ -474,8 +528,10 @@
|
||||
"metadataRefreshFailed": "Error al actualizar metadatos: ${error}",
|
||||
"logoutConfirm": "¿Estás seguro de que quieres cerrar sesión?",
|
||||
"noSeasonsFound": "No se encontraron temporadas",
|
||||
"seasonsLoadFailed": "No se pudieron cargar las temporadas",
|
||||
"noEpisodesFound": "No se encontraron episodios en la primera temporada",
|
||||
"noEpisodesFoundGeneral": "No se encontraron episodios",
|
||||
"episodesLoadFailed": "No se pudieron cargar los episodios",
|
||||
"noResultsFound": "No se encontraron resultados",
|
||||
"sleepTimerSet": "Temporizador establecido en ${label}",
|
||||
"noItemsAvailable": "No hay elementos disponibles",
|
||||
@@ -501,7 +557,10 @@
|
||||
"position": "Posición",
|
||||
"assOverride": "Sobreescritura ASS",
|
||||
"bold": "Negrita",
|
||||
"italic": "Cursiva"
|
||||
"italic": "Cursiva",
|
||||
"renderResolution": "Resolución de renderizado",
|
||||
"renderResolutionScreen": "Resolución de pantalla",
|
||||
"renderResolutionVideo": "Resolución del vídeo"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "Configuración de mpv",
|
||||
@@ -579,7 +638,8 @@
|
||||
"pinProtectionOptional": "Protección con PIN (opcional)",
|
||||
"pinExplain": "Se requiere PIN de 4 dígitos para cambiar de perfil.",
|
||||
"continueButton": "Continuar",
|
||||
"pinsDontMatch": "Los PIN no coinciden"
|
||||
"pinsDontMatch": "Los PIN no coinciden",
|
||||
"initializeServicesFailed": "No se pudieron inicializar los servicios de perfil"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "Conexiones",
|
||||
@@ -588,7 +648,9 @@
|
||||
"addConnectionSubtitleScoped": "Añadir a ${displayName}: Plex, Jellyfin u otra conexión de perfil",
|
||||
"sessionExpiredOne": "Sesión caducada para ${name}",
|
||||
"sessionExpiredMany": "Sesión caducada para ${count} servidores",
|
||||
"signInAgain": "Iniciar sesión de nuevo"
|
||||
"signInAgain": "Iniciar sesión de nuevo",
|
||||
"editJellyfinTitle": "Editar conexión de Jellyfin",
|
||||
"editJellyfinIntro": "Añade o elimina URL para ${serverName}. Plezy usará la URL accesible con menor latencia."
|
||||
},
|
||||
"discover": {
|
||||
"title": "Descubrir",
|
||||
@@ -609,7 +671,8 @@
|
||||
"rating": "Calificación",
|
||||
"movie": "Película",
|
||||
"tvShow": "Serie de TV",
|
||||
"minutesLeft": "quedan ${minutes} min"
|
||||
"minutesLeft": "quedan ${minutes} min",
|
||||
"moreLikeThis": "Más como esto"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Error en la búsqueda: ${error}",
|
||||
@@ -628,6 +691,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Bibliotecas",
|
||||
"fallbackTitle": "Biblioteca",
|
||||
"scanLibraryFiles": "Escanear Archivos de la Biblioteca",
|
||||
"scanLibrary": "Escanear Biblioteca",
|
||||
"analyze": "Analizar",
|
||||
@@ -684,15 +748,27 @@
|
||||
"genre": "Género",
|
||||
"year": "Año",
|
||||
"contentRating": "Clasificación",
|
||||
"tag": "Etiqueta"
|
||||
"tag": "Etiqueta",
|
||||
"unwatched": "No vistos"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "Título",
|
||||
"dateAdded": "Fecha de adición",
|
||||
"releaseDate": "Fecha de estreno",
|
||||
"rating": "Valoración",
|
||||
"communityRating": "Calificación de comunidad",
|
||||
"criticRating": "Calificación de crítica",
|
||||
"userRating": "Calificación del usuario",
|
||||
"lastPlayed": "Última reproducción",
|
||||
"datePlayed": "Fecha de reproducción",
|
||||
"playCount": "Reproducciones",
|
||||
"productionYear": "Año de producción",
|
||||
"runtime": "Duración",
|
||||
"officialRating": "Calificación oficial",
|
||||
"premiereDate": "Fecha de estreno",
|
||||
"startDate": "Fecha de inicio",
|
||||
"airTime": "Hora de emisión",
|
||||
"studio": "Estudio",
|
||||
"random": "Aleatorio",
|
||||
"dateShared": "Fecha de compartición",
|
||||
"latestEpisodeAirDate": "Última fecha de emisión del episodio"
|
||||
@@ -739,6 +815,12 @@
|
||||
"noChannels": "No hay canales disponibles",
|
||||
"noDvr": "No hay DVR configurado en ningún servidor",
|
||||
"noPrograms": "No hay datos de programación disponibles",
|
||||
"liveStreamFailed": "Falló la transmisión en vivo",
|
||||
"unknownProgram": "Programa desconocido",
|
||||
"unknownHub": "Desconocido",
|
||||
"unknownError": "Error desconocido",
|
||||
"channelNumber": "Canal ${number}",
|
||||
"unknownChannel": "Canal desconocido",
|
||||
"live": "EN VIVO",
|
||||
"reloadGuide": "Recargar guía",
|
||||
"now": "Ahora",
|
||||
@@ -917,12 +999,21 @@
|
||||
"deleteDownload": "Eliminar descarga",
|
||||
"retryDownload": "Reintentar descarga",
|
||||
"downloadQueued": "Descarga en cola",
|
||||
"downloadResumed": "Descarga reanudada",
|
||||
"serverErrorBitrate": "Error del servidor: el archivo puede superar el límite de bitrate remoto",
|
||||
"episodesQueued": "${count} episodios en cola para descargar",
|
||||
"downloadDeleted": "Descarga eliminada",
|
||||
"deleteConfirm": "¿Eliminar \"${title}\" de este dispositivo?",
|
||||
"deletingWithProgress": "Eliminando ${title}... (${current} de ${total})",
|
||||
"cancelledDownloadTitle": "Descarga cancelada",
|
||||
"cancelledDownloadMessage": "Esta descarga se canceló. ¿Qué quieres hacer?",
|
||||
"allEpisodesAlreadyDownloaded": "Todos los episodios ya están descargados",
|
||||
"resumeDownload": "Reanudar descarga",
|
||||
"cancelledDownload": "Descarga cancelada",
|
||||
"syncingFile": "${file} (sincronizando ${status})",
|
||||
"downloadedFileClickToComplete": "${file} descargado — haz clic para completar",
|
||||
"partialDownloadClickToComplete": "Descarga parcial — haz clic para completar",
|
||||
"deleting": "Eliminando...",
|
||||
"deletingWithProgress": "Eliminando ${title}... (${current} de ${total})",
|
||||
"queuedTooltip": "En cola",
|
||||
"queuedFilesTooltip": "En cola: ${files}",
|
||||
"downloadingTooltip": "Descargando...",
|
||||
@@ -983,6 +1074,7 @@
|
||||
"companionRemote": {
|
||||
"title": "Control remoto",
|
||||
"connectedTo": "Conectado a ${name}",
|
||||
"unknownDevice": "Dispositivo desconocido",
|
||||
"session": {
|
||||
"startingServer": "Iniciando servidor remoto...",
|
||||
"failedToCreate": "Error al iniciar el servidor remoto:",
|
||||
@@ -1042,11 +1134,19 @@
|
||||
"subtitles": "Subtítulos",
|
||||
"audio": "Audio",
|
||||
"searchHint": "Buscar en escritorio..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "No se encontró ninguna interfaz de red",
|
||||
"authenticationFailed": "Autenticación fallida",
|
||||
"joinTimedOut": "Se agotó el tiempo al unirse a la sesión",
|
||||
"failedToConnectAnyAddress": "No se pudo conectar a ninguna dirección",
|
||||
"connectionLostAfterAttempts": "Conexión perdida tras ${attempts} intentos",
|
||||
"connectionLost": "Conexión perdida"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "Ajustes de reproducción",
|
||||
"playbackSpeed": "Velocidad de reproducción",
|
||||
"zoom": "Zoom",
|
||||
"sleepTimer": "Temporizador de apagado",
|
||||
"audioSync": "Sincronización de audio",
|
||||
"subtitleSync": "Sincronización de subtítulos",
|
||||
@@ -1056,6 +1156,43 @@
|
||||
"audioPassthrough": "Audio Passthrough",
|
||||
"audioNormalization": "Normalizar volumen"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "Color",
|
||||
"performance": "Rendimiento",
|
||||
"buffer": "Búfer",
|
||||
"app": "App",
|
||||
"decoder": "Decodificador",
|
||||
"rawDecoder": "Decodificador raw",
|
||||
"tunneling": "Túnel",
|
||||
"aspect": "Aspecto",
|
||||
"rotation": "Rotación",
|
||||
"dvSource": "Origen DV",
|
||||
"dvPath": "Ruta DV",
|
||||
"p7Conversion": "Conv. P7",
|
||||
"sampleRate": "Frecuencia de muestreo",
|
||||
"pixelFormat": "Formato de píxel",
|
||||
"hwFormat": "Formato HW",
|
||||
"matrix": "Matriz",
|
||||
"primaries": "Primarios",
|
||||
"transfer": "Transferencia",
|
||||
"renderFps": "FPS render",
|
||||
"displayFps": "FPS pantalla",
|
||||
"avSync": "Sincronía A/V",
|
||||
"dropped": "Descartados",
|
||||
"dvRpus": "DV RPUs",
|
||||
"dvRpuAverage": "Prom. DV RPU",
|
||||
"dvSampleAverage": "Prom. muestra DV",
|
||||
"maxLuma": "Luma máx.",
|
||||
"minLuma": "Luma mín.",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "Caché usada",
|
||||
"cacheLimit": "Límite de caché",
|
||||
"speed": "Velocidad",
|
||||
"player": "Reproductor",
|
||||
"memory": "Memoria",
|
||||
"uiFps": "FPS UI"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "Reproductor externo",
|
||||
"useExternalPlayer": "Usar reproductor externo",
|
||||
@@ -1065,6 +1202,7 @@
|
||||
"systemDefault": "Predeterminado del sistema",
|
||||
"addCustomPlayer": "Añadir reproductor personalizado",
|
||||
"playerName": "Nombre del reproductor",
|
||||
"playerNameHint": "Mi reproductor",
|
||||
"playerCommand": "Comando",
|
||||
"playerPackage": "Nombre del paquete",
|
||||
"playerUrlScheme": "Esquema URL",
|
||||
@@ -1224,9 +1362,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Añadir servidor Jellyfin",
|
||||
"jellyfinUrlIntro": "Introduce la URL del servidor, p. ej. `https://jellyfin.example.com`.",
|
||||
"serverUrl": "URL del servidor",
|
||||
"serverUrls": "URL del servidor",
|
||||
"serverUrlsHelper": "Se permiten varias URL, separadas por comas.",
|
||||
"findServer": "Buscar servidor",
|
||||
"searchingLocalServers": "Buscando servidores Jellyfin locales...",
|
||||
"localServers": "Servidores Jellyfin locales",
|
||||
"username": "Usuario",
|
||||
"password": "Contraseña",
|
||||
"signIn": "Iniciar sesión",
|
||||
@@ -1236,17 +1376,12 @@
|
||||
"signInFailed": "Error al iniciar sesión: ${error}",
|
||||
"quickConnectFailed": "Quick Connect ha fallado: ${error}",
|
||||
"addPlexTitle": "Iniciar sesión con Plex",
|
||||
"plexAuthIntro": "Inicia sesión con un navegador o código QR.",
|
||||
"plexQRPrompt": "Escanea este código QR para iniciar sesión.",
|
||||
"waitingForPlexConfirmation": "Esperando que plex.tv confirme tu inicio de sesión…",
|
||||
"pinExpired": "El PIN caducó antes de iniciar sesión. Inténtalo de nuevo.",
|
||||
"duplicatePlexAccount": "Ya iniciaste sesión en Plex. Cierra sesión para cambiar de cuenta.",
|
||||
"failedToRegisterAccount": "No se pudo registrar la cuenta: ${error}",
|
||||
"enterJellyfinUrlError": "Introduce la URL de tu servidor Jellyfin",
|
||||
"addConnectionTitle": "Añadir conexión",
|
||||
"addConnectionTitleScoped": "Añadir a ${name}",
|
||||
"addConnectionIntroGlobal": "Añade otro servidor multimedia. Plex y Jellyfin aparecen juntos en Inicio.",
|
||||
"addConnectionIntroScoped": "Añade un servidor nuevo o toma prestado uno de otro perfil.",
|
||||
"signInWithPlexCard": "Iniciar sesión con Plex",
|
||||
"signInWithPlexCardSubtitle": "Autoriza este dispositivo. Se añaden servidores compartidos.",
|
||||
"signInWithPlexCardSubtitleScoped": "Autoriza una cuenta Plex. Los usuarios de Home se convierten en perfiles.",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "ou",
|
||||
"connectToJellyfin": "Se connecter à Jellyfin",
|
||||
"useQuickConnect": "Utiliser Quick Connect",
|
||||
"quickConnectCode": "Code Quick Connect",
|
||||
"quickConnectInstructions": "Ouvrez Quick Connect dans Jellyfin et saisissez ce code.",
|
||||
"quickConnectWaiting": "En attente d'approbation…",
|
||||
"quickConnectCancel": "Annuler",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "Oui",
|
||||
"no": "Non",
|
||||
"delete": "Supprimer",
|
||||
"edit": "Modifier",
|
||||
"shuffle": "Mélanger",
|
||||
"addTo": "Ajouter à...",
|
||||
"createNew": "Créer",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "Réglages",
|
||||
"mute": "Muet",
|
||||
"ok": "OK",
|
||||
"off": "Désactivé",
|
||||
"seasonNumber": "Saison ${number}",
|
||||
"episodeNumberTitle": "Épisode ${number} - ${title}",
|
||||
"chapterNumber": "Chapitre ${number}",
|
||||
"reconnect": "Reconnecter",
|
||||
"exit": "Quitter",
|
||||
"viewAll": "Tout afficher",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "Grille",
|
||||
"listView": "Liste",
|
||||
"showHeroSection": "Afficher la section Hero",
|
||||
"continueWatchingAction": "Action Continuer à regarder",
|
||||
"continueWatchingPlay": "Lire",
|
||||
"continueWatchingDetails": "Ouvrir les détails",
|
||||
"useGlobalHubs": "Utiliser la mise en page d'accueil",
|
||||
"useGlobalHubsDescription": "Afficher des hubs d'accueil unifiés. Sinon, utiliser les recommandations de bibliothèque.",
|
||||
"showServerNameOnHubs": "Afficher le nom du serveur sur les hubs",
|
||||
@@ -125,6 +132,10 @@
|
||||
"showEpisodeNumberOnCardsDescription": "Afficher la saison et l'épisode sur les cartes d'épisode",
|
||||
"showSeasonPostersOnTabs": "Afficher les posters de saison sur les onglets",
|
||||
"showSeasonPostersOnTabsDescription": "Afficher l'affiche de chaque saison au-dessus de son onglet",
|
||||
"tvFullCardLayout": "Cartes TV pleines",
|
||||
"tvFullCardLayoutDescription": "Utiliser des cartes TV avec image seule et noms des acteurs superposés",
|
||||
"focusGlow": "Halo de sélection",
|
||||
"focusGlowDescription": "Afficher un léger halo autour de la carte sélectionnée",
|
||||
"hideSpoilers": "Masquer les spoilers des épisodes non vus",
|
||||
"hideSpoilersDescription": "Flouter les miniatures et descriptions des épisodes non vus",
|
||||
"playerBackend": "Moteur de lecture",
|
||||
@@ -248,16 +259,30 @@
|
||||
"displaySwitchDelay": "Délai de changement d'affichage",
|
||||
"tunneledPlayback": "Lecture tunnelée",
|
||||
"tunneledPlaybackDescription": "Utiliser le tunneling vidéo. Désactivez si la lecture HDR affiche un écran noir.",
|
||||
"dvConversionMode": "Conversion Dolby Vision",
|
||||
"dvConversionModeDescription": "Choisissez comment ExoPlayer gère les fichiers Dolby Vision Profile 7.",
|
||||
"dvConversionAuto": "Auto",
|
||||
"dvConversionNative": "Natif / désactivé",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "Utiliser la détection des capacités de l’appareil et le comportement de repli normal",
|
||||
"dvConversionNativeDescription": "Forcer le DV7 natif et bloquer la nouvelle tentative de conversion DV",
|
||||
"dvConversionDv81Description": "Forcer la conversion RPU intégrée vers Dolby Vision profil 8.1",
|
||||
"dvConversionHevcStripDescription": "Supprimer les couches RPU/EL Dolby Vision et présenter du HEVC simple",
|
||||
"requireProfileSelectionOnOpen": "Demander le profil à l'ouverture",
|
||||
"requireProfileSelectionOnOpenDescription": "Afficher la sélection de profil à chaque ouverture de l'application",
|
||||
"forceTvMode": "Forcer le mode TV",
|
||||
"forceTvModeDescription": "Forcer l'interface TV. Pour appareils non détectés automatiquement. Redémarrage requis.",
|
||||
"startInFullscreen": "Démarrer en plein écran",
|
||||
"startInFullscreenDescription": "Ouvrir Plezy en mode plein écran au lancement",
|
||||
"exitFullscreenOnPlayerClose": "Quitter le plein écran à la fermeture du lecteur",
|
||||
"exitFullscreenOnPlayerCloseDescription": "Quitter automatiquement le plein écran lors de la fermeture du lecteur vidéo",
|
||||
"autoHidePerformanceOverlay": "Masquer auto. superposition performances",
|
||||
"autoHidePerformanceOverlayDescription": "Faire apparaître/disparaître la superposition avec les contrôles de lecture",
|
||||
"showNavBarLabels": "Afficher les libellés de la barre de navigation",
|
||||
"showNavBarLabelsDescription": "Afficher les libellés sous les icônes de la barre de navigation",
|
||||
"startupSection": "Section de démarrage",
|
||||
"startupSectionDescription": "Choisissez la section que Plezy ouvre au démarrage",
|
||||
"liveTvDefaultFavorites": "Chaînes favorites par défaut",
|
||||
"liveTvDefaultFavoritesDescription": "Afficher uniquement les chaînes favorites à l'ouverture de la TV en direct",
|
||||
"display": "Affichage",
|
||||
@@ -279,6 +304,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Définir un raccourci pour ${actionName}",
|
||||
"clearShortcut": "Effacer le raccourci",
|
||||
"noShortcutSet": "Aucun raccourci défini",
|
||||
"currentShortcut": "Raccourci actuel :",
|
||||
"actions": {
|
||||
"playPause": "Lecture/Pause",
|
||||
"volumeUp": "Augmenter le volume",
|
||||
@@ -297,10 +324,14 @@
|
||||
"speedIncrease": "Augmenter la vitesse",
|
||||
"speedDecrease": "Réduire la vitesse",
|
||||
"speedReset": "Réinitialiser la vitesse",
|
||||
"zoomIn": "Zoom avant",
|
||||
"zoomOut": "Zoom arrière",
|
||||
"zoomReset": "Réinitialiser le zoom",
|
||||
"subSeekNext": "Rechercher le sous-titre suivant",
|
||||
"subSeekPrev": "Rechercher le sous-titre précédent",
|
||||
"shaderToggle": "Activer/désactiver les shaders",
|
||||
"skipMarker": "Passer l'intro/le générique"
|
||||
"skipMarker": "Passer l'intro/le générique",
|
||||
"screenshot": "Prendre une capture d'écran"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +365,10 @@
|
||||
"markAsWatched": "Marquer comme vu",
|
||||
"markAsUnwatched": "Marquer comme non visionné",
|
||||
"removeFromContinueWatching": "Supprimer de la liste \"Continuer à regarder\"",
|
||||
"viewDetails": "Voir les détails",
|
||||
"goToSeries": "Aller à la série",
|
||||
"goToSeason": "Aller à la saison",
|
||||
"shufflePlay": "Lecture aléatoire",
|
||||
"shuffleNotAvailableOffline": "La lecture aléatoire n’est pas disponible hors ligne",
|
||||
"fileInfo": "Informations sur le fichier",
|
||||
"deleteFromServer": "Supprimer du serveur",
|
||||
"confirmDelete": "Supprimer ce média et ses fichiers de votre serveur ?",
|
||||
@@ -347,6 +379,19 @@
|
||||
"playFromBeginning": "Lire depuis le début",
|
||||
"playVersion": "Lire la version..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "Noter",
|
||||
"server": "Serveur",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "Définir une note",
|
||||
"notRated": "Non noté",
|
||||
"liked": "Aimé",
|
||||
"notLiked": "Non aimé",
|
||||
"saved": "Enregistré",
|
||||
"notAvailable": "Aucune correspondance trouvée",
|
||||
"noConnectedTrackers": "Connectez un tracker dans Paramètres pour y noter."
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, film",
|
||||
"mediaCardShow": "${title}, show TV",
|
||||
@@ -379,6 +424,10 @@
|
||||
"unlockRotation": "Déverrouiller la rotation",
|
||||
"timerActive": "Minuterie active",
|
||||
"playbackWillPauseIn": "La lecture sera mise en pause dans ${duration}",
|
||||
"sleepTimerEndOfVideo": "Fin de la vidéo actuelle",
|
||||
"sleepTimerStopAtHeader": "Arrêter à",
|
||||
"sleepTimerDurationHeader": "Minuterie",
|
||||
"playbackWillPauseAtEnd": "La lecture sera mise en pause à la fin de cette vidéo",
|
||||
"stillWatching": "Toujours en train de regarder ?",
|
||||
"pausingIn": "Pause dans ${seconds}s",
|
||||
"continueWatching": "Continuer",
|
||||
@@ -394,7 +443,7 @@
|
||||
"nextChapterButton": "Chapitre suivant",
|
||||
"muteButton": "Mute",
|
||||
"unmuteButton": "Dé-mute",
|
||||
"settingsButton": "Paramètres vidéo",
|
||||
"settingsButton": "Paramètres de lecture",
|
||||
"tracksButton": "Audio et sous-titres",
|
||||
"chaptersButton": "Chapitres",
|
||||
"versionsButton": "Versions vidéo",
|
||||
@@ -420,6 +469,8 @@
|
||||
"endsAt": "Fin à ${time}",
|
||||
"pipActive": "Lecture en mode image dans l'image",
|
||||
"pipFailed": "Échec du démarrage du mode image dans l'image",
|
||||
"screenshotSaved": "Capture d'écran enregistrée",
|
||||
"zoomPercent": "Zoom ${percent} %",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Nécessite Android 8.0 ou plus récent",
|
||||
"iosVersion": "Nécessite iOS 15.0 ou plus récent",
|
||||
@@ -436,6 +487,10 @@
|
||||
"searchSubtitles": "Rechercher des sous-titres",
|
||||
"language": "Langue",
|
||||
"noSubtitlesFound": "Aucun sous-titre trouvé",
|
||||
"downloadedSubtitle": "Téléchargé",
|
||||
"noSubtitlesAvailable": "Aucun sous-titre disponible",
|
||||
"noAudioTracksAvailable": "Aucune piste audio disponible",
|
||||
"noTracksAvailable": "Aucune piste disponible",
|
||||
"subtitleDownloaded": "Sous-titre téléchargé",
|
||||
"subtitleDownloadFailed": "Échec du téléchargement du sous-titre",
|
||||
"searchLanguages": "Rechercher des langues..."
|
||||
@@ -457,7 +512,6 @@
|
||||
"fileInfoNotAvailable": "Informations sur le fichier non disponibles",
|
||||
"errorLoadingFileInfo": "Erreur lors du chargement des informations sur le fichier: ${error}",
|
||||
"errorLoadingSeries": "Erreur lors du chargement de la série",
|
||||
"errorLoadingSeason": "Erreur lors du chargement de la saison",
|
||||
"musicNotSupported": "La lecture de musique n'est pas encore prise en charge",
|
||||
"noDescriptionAvailable": "Aucune description disponible",
|
||||
"noProfilesAvailable": "Aucun profil disponible",
|
||||
@@ -474,8 +528,10 @@
|
||||
"metadataRefreshFailed": "Échec de l'actualisation des métadonnées: ${error}",
|
||||
"logoutConfirm": "Êtes-vous sûr de vouloir vous déconnecter ?",
|
||||
"noSeasonsFound": "Aucune saison trouvée",
|
||||
"seasonsLoadFailed": "Impossible de charger les saisons",
|
||||
"noEpisodesFound": "Aucun épisode trouvé dans la première saison",
|
||||
"noEpisodesFoundGeneral": "Aucun épisode trouvé",
|
||||
"episodesLoadFailed": "Impossible de charger les épisodes",
|
||||
"noResultsFound": "Aucun résultat trouvé",
|
||||
"sleepTimerSet": "Minuterie de mise en veille réglée sur ${label}",
|
||||
"noItemsAvailable": "Aucun élément disponible",
|
||||
@@ -501,7 +557,10 @@
|
||||
"position": "Position",
|
||||
"assOverride": "Remplacement ASS",
|
||||
"bold": "Gras",
|
||||
"italic": "Italique"
|
||||
"italic": "Italique",
|
||||
"renderResolution": "Résolution de rendu",
|
||||
"renderResolutionScreen": "Résolution de l'écran",
|
||||
"renderResolutionVideo": "Résolution de la vidéo"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "Configuration mpv",
|
||||
@@ -579,7 +638,8 @@
|
||||
"pinProtectionOptional": "Protection par PIN (optionnelle)",
|
||||
"pinExplain": "PIN à 4 chiffres requis pour changer de profil.",
|
||||
"continueButton": "Continuer",
|
||||
"pinsDontMatch": "Les PIN ne correspondent pas"
|
||||
"pinsDontMatch": "Les PIN ne correspondent pas",
|
||||
"initializeServicesFailed": "Impossible d’initialiser les services de profil"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "Connexions",
|
||||
@@ -588,7 +648,9 @@
|
||||
"addConnectionSubtitleScoped": "Ajouter à ${displayName} : Plex, Jellyfin ou une autre connexion de profil",
|
||||
"sessionExpiredOne": "Session expirée pour ${name}",
|
||||
"sessionExpiredMany": "Session expirée pour ${count} serveurs",
|
||||
"signInAgain": "Se reconnecter"
|
||||
"signInAgain": "Se reconnecter",
|
||||
"editJellyfinTitle": "Modifier la connexion Jellyfin",
|
||||
"editJellyfinIntro": "Ajoutez ou supprimez des URL pour ${serverName}. Plezy utilisera l'URL joignable avec la latence la plus faible."
|
||||
},
|
||||
"discover": {
|
||||
"title": "Découvrez",
|
||||
@@ -609,7 +671,8 @@
|
||||
"rating": "Évaluation",
|
||||
"movie": "Film",
|
||||
"tvShow": "Show TV",
|
||||
"minutesLeft": "${minutes} min restantes"
|
||||
"minutesLeft": "${minutes} min restantes",
|
||||
"moreLikeThis": "Plus de contenus similaires"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Recherche échouée: ${error}",
|
||||
@@ -628,6 +691,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Bibliothèques",
|
||||
"fallbackTitle": "Bibliothèque",
|
||||
"scanLibraryFiles": "Scanner les fichiers de la bibliothèque",
|
||||
"scanLibrary": "Scanner la bibliothèque",
|
||||
"analyze": "Analyser",
|
||||
@@ -684,15 +748,27 @@
|
||||
"genre": "Genre",
|
||||
"year": "Année",
|
||||
"contentRating": "Classification",
|
||||
"tag": "Tag"
|
||||
"tag": "Tag",
|
||||
"unwatched": "Non vus"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "Titre",
|
||||
"dateAdded": "Date d'ajout",
|
||||
"releaseDate": "Date de sortie",
|
||||
"rating": "Note",
|
||||
"communityRating": "Note communautaire",
|
||||
"criticRating": "Note critique",
|
||||
"userRating": "Note utilisateur",
|
||||
"lastPlayed": "Dernière lecture",
|
||||
"datePlayed": "Date de lecture",
|
||||
"playCount": "Lectures",
|
||||
"productionYear": "Année de production",
|
||||
"runtime": "Durée",
|
||||
"officialRating": "Classification officielle",
|
||||
"premiereDate": "Date de première",
|
||||
"startDate": "Date de début",
|
||||
"airTime": "Heure de diffusion",
|
||||
"studio": "Studio",
|
||||
"random": "Aléatoire",
|
||||
"dateShared": "Date de partage",
|
||||
"latestEpisodeAirDate": "Dernière date de diffusion"
|
||||
@@ -739,6 +815,12 @@
|
||||
"noChannels": "Aucune chaîne disponible",
|
||||
"noDvr": "Aucun DVR configuré sur les serveurs",
|
||||
"noPrograms": "Aucune donnée de programme disponible",
|
||||
"liveStreamFailed": "Échec du direct",
|
||||
"unknownProgram": "Programme inconnu",
|
||||
"unknownHub": "Inconnu",
|
||||
"unknownError": "Erreur inconnue",
|
||||
"channelNumber": "Chaîne ${number}",
|
||||
"unknownChannel": "Chaîne inconnue",
|
||||
"live": "EN DIRECT",
|
||||
"reloadGuide": "Recharger le guide",
|
||||
"now": "Maintenant",
|
||||
@@ -917,12 +999,21 @@
|
||||
"deleteDownload": "Supprimer le téléchargement",
|
||||
"retryDownload": "Réessayer le téléchargement",
|
||||
"downloadQueued": "Téléchargement en attente",
|
||||
"downloadResumed": "Téléchargement repris",
|
||||
"serverErrorBitrate": "Erreur serveur : le fichier peut dépasser la limite de bitrate distant",
|
||||
"episodesQueued": "${count} épisodes en attente de téléchargement",
|
||||
"downloadDeleted": "Télécharger supprimé",
|
||||
"deleteConfirm": "Supprimer \"${title}\" de cet appareil ?",
|
||||
"deletingWithProgress": "Suppression de ${title}... (${current} sur ${total})",
|
||||
"cancelledDownloadTitle": "Téléchargement annulé",
|
||||
"cancelledDownloadMessage": "Ce téléchargement a été annulé. Que voulez-vous faire ?",
|
||||
"allEpisodesAlreadyDownloaded": "Tous les épisodes sont déjà téléchargés",
|
||||
"resumeDownload": "Reprendre le téléchargement",
|
||||
"cancelledDownload": "Téléchargement annulé",
|
||||
"syncingFile": "${file} (synchronisation ${status})",
|
||||
"downloadedFileClickToComplete": "${file} téléchargé — cliquez pour terminer",
|
||||
"partialDownloadClickToComplete": "Téléchargement partiel — cliquez pour terminer",
|
||||
"deleting": "Suppression...",
|
||||
"deletingWithProgress": "Suppression de ${title}... (${current} sur ${total})",
|
||||
"queuedTooltip": "En attente",
|
||||
"queuedFilesTooltip": "En attente : ${files}",
|
||||
"downloadingTooltip": "Téléchargement...",
|
||||
@@ -983,6 +1074,7 @@
|
||||
"companionRemote": {
|
||||
"title": "Télécommande compagnon",
|
||||
"connectedTo": "Connecté à ${name}",
|
||||
"unknownDevice": "Appareil inconnu",
|
||||
"session": {
|
||||
"startingServer": "Démarrage du serveur distant...",
|
||||
"failedToCreate": "Échec du démarrage du serveur distant :",
|
||||
@@ -1042,11 +1134,19 @@
|
||||
"subtitles": "Sous-titres",
|
||||
"audio": "Audio",
|
||||
"searchHint": "Rechercher sur le bureau..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "Aucune interface réseau trouvée",
|
||||
"authenticationFailed": "Échec de l’authentification",
|
||||
"joinTimedOut": "Délai dépassé lors de la connexion à la session",
|
||||
"failedToConnectAnyAddress": "Impossible de se connecter à une adresse",
|
||||
"connectionLostAfterAttempts": "Connexion perdue après ${attempts} tentatives",
|
||||
"connectionLost": "Connexion perdue"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "Paramètres de lecture",
|
||||
"playbackSpeed": "Vitesse de lecture",
|
||||
"zoom": "Zoom",
|
||||
"sleepTimer": "Minuterie de mise en veille",
|
||||
"audioSync": "Synchronisation audio",
|
||||
"subtitleSync": "Synchronisation des sous-titres",
|
||||
@@ -1056,6 +1156,43 @@
|
||||
"audioPassthrough": "Audio Pass-Through",
|
||||
"audioNormalization": "Normaliser le volume"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "Couleur",
|
||||
"performance": "Performances",
|
||||
"buffer": "Tampon",
|
||||
"app": "App",
|
||||
"decoder": "Décodeur",
|
||||
"rawDecoder": "Décodeur brut",
|
||||
"tunneling": "Tunneling",
|
||||
"aspect": "Format",
|
||||
"rotation": "Rotation",
|
||||
"dvSource": "Source DV",
|
||||
"dvPath": "Chemin DV",
|
||||
"p7Conversion": "Conv. P7",
|
||||
"sampleRate": "Fréquence",
|
||||
"pixelFormat": "Fmt pixel",
|
||||
"hwFormat": "Fmt HW",
|
||||
"matrix": "Matrice",
|
||||
"primaries": "Primaires",
|
||||
"transfer": "Transfert",
|
||||
"renderFps": "FPS rendu",
|
||||
"displayFps": "FPS écran",
|
||||
"avSync": "Synchro A/V",
|
||||
"dropped": "Perdues",
|
||||
"dvRpus": "DV RPU",
|
||||
"dvRpuAverage": "Moy. DV RPU",
|
||||
"dvSampleAverage": "Moy. échant. DV",
|
||||
"maxLuma": "Luma max.",
|
||||
"minLuma": "Luma min.",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "Cache utilisé",
|
||||
"cacheLimit": "Limite du cache",
|
||||
"speed": "Vitesse",
|
||||
"player": "Lecteur",
|
||||
"memory": "Mémoire",
|
||||
"uiFps": "FPS UI"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "Lecteur externe",
|
||||
"useExternalPlayer": "Utiliser un lecteur externe",
|
||||
@@ -1065,6 +1202,7 @@
|
||||
"systemDefault": "Par défaut du système",
|
||||
"addCustomPlayer": "Ajouter un lecteur personnalisé",
|
||||
"playerName": "Nom du lecteur",
|
||||
"playerNameHint": "Mon lecteur",
|
||||
"playerCommand": "Commande",
|
||||
"playerPackage": "Nom du paquet",
|
||||
"playerUrlScheme": "Schéma URL",
|
||||
@@ -1224,9 +1362,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Ajouter un serveur Jellyfin",
|
||||
"jellyfinUrlIntro": "Saisissez l'URL du serveur, par ex. `https://jellyfin.example.com`.",
|
||||
"serverUrl": "URL du serveur",
|
||||
"serverUrls": "URL du serveur",
|
||||
"serverUrlsHelper": "Plusieurs URL possibles, séparées par des virgules.",
|
||||
"findServer": "Rechercher un serveur",
|
||||
"searchingLocalServers": "Recherche de serveurs Jellyfin locaux...",
|
||||
"localServers": "Serveurs Jellyfin locaux",
|
||||
"username": "Nom d'utilisateur",
|
||||
"password": "Mot de passe",
|
||||
"signIn": "Se connecter",
|
||||
@@ -1236,17 +1376,12 @@
|
||||
"signInFailed": "Échec de la connexion : ${error}",
|
||||
"quickConnectFailed": "Échec de Quick Connect : ${error}",
|
||||
"addPlexTitle": "Se connecter avec Plex",
|
||||
"plexAuthIntro": "Connectez-vous avec un navigateur ou un code QR.",
|
||||
"plexQRPrompt": "Scannez ce QR code pour vous connecter.",
|
||||
"waitingForPlexConfirmation": "En attente de la confirmation de plex.tv…",
|
||||
"pinExpired": "Le PIN a expiré avant la connexion. Veuillez réessayer.",
|
||||
"duplicatePlexAccount": "Déjà connecté à Plex. Déconnectez-vous pour changer de compte.",
|
||||
"failedToRegisterAccount": "Échec de l'enregistrement du compte : ${error}",
|
||||
"enterJellyfinUrlError": "Saisissez l'URL de votre serveur Jellyfin",
|
||||
"addConnectionTitle": "Ajouter une connexion",
|
||||
"addConnectionTitleScoped": "Ajouter à ${name}",
|
||||
"addConnectionIntroGlobal": "Ajoutez un autre serveur multimédia. Plex et Jellyfin apparaissent ensemble sur Accueil.",
|
||||
"addConnectionIntroScoped": "Ajoutez un nouveau serveur, ou empruntez-en un à un autre profil.",
|
||||
"signInWithPlexCard": "Se connecter avec Plex",
|
||||
"signInWithPlexCardSubtitle": "Autorisez cet appareil. Les serveurs partagés sont ajoutés.",
|
||||
"signInWithPlexCardSubtitleScoped": "Autorisez un compte Plex. Les utilisateurs Home deviennent des profils.",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "o",
|
||||
"connectToJellyfin": "Connetti a Jellyfin",
|
||||
"useQuickConnect": "Usa Quick Connect",
|
||||
"quickConnectCode": "Codice Quick Connect",
|
||||
"quickConnectInstructions": "Apri Quick Connect in Jellyfin e inserisci questo codice.",
|
||||
"quickConnectWaiting": "In attesa di approvazione…",
|
||||
"quickConnectCancel": "Annulla",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "Sì",
|
||||
"no": "No",
|
||||
"delete": "Elimina",
|
||||
"edit": "Modifica",
|
||||
"shuffle": "Casuale",
|
||||
"addTo": "Aggiungi a...",
|
||||
"createNew": "Crea",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "Opzioni",
|
||||
"mute": "Muto",
|
||||
"ok": "OK",
|
||||
"off": "Disattivato",
|
||||
"seasonNumber": "Stagione ${number}",
|
||||
"episodeNumberTitle": "Episodio ${number} - ${title}",
|
||||
"chapterNumber": "Capitolo ${number}",
|
||||
"reconnect": "Riconnetti",
|
||||
"exit": "Esci",
|
||||
"viewAll": "Mostra tutto",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "Griglia",
|
||||
"listView": "Elenco",
|
||||
"showHeroSection": "Mostra sezione principale",
|
||||
"continueWatchingAction": "Azione Continua a guardare",
|
||||
"continueWatchingPlay": "Riproduci",
|
||||
"continueWatchingDetails": "Apri dettagli",
|
||||
"useGlobalHubs": "Usa layout home",
|
||||
"useGlobalHubsDescription": "Mostra hub Home unificati. Altrimenti usa i consigli della libreria.",
|
||||
"showServerNameOnHubs": "Mostra nome server sugli hub",
|
||||
@@ -125,6 +132,10 @@
|
||||
"showEpisodeNumberOnCardsDescription": "Mostra stagione ed episodio sulle schede episodio",
|
||||
"showSeasonPostersOnTabs": "Mostra poster delle stagioni sulle schede",
|
||||
"showSeasonPostersOnTabsDescription": "Mostra il poster di ogni stagione sopra la sua scheda",
|
||||
"tvFullCardLayout": "Schede TV piene",
|
||||
"tvFullCardLayoutDescription": "Usa schede TV solo immagine con i nomi degli attori sovrapposti",
|
||||
"focusGlow": "Bagliore di selezione",
|
||||
"focusGlowDescription": "Mostra un leggero bagliore attorno alla scheda selezionata",
|
||||
"hideSpoilers": "Nascondi spoiler per episodi non visti",
|
||||
"hideSpoilersDescription": "Sfoca miniature e descrizioni degli episodi non visti",
|
||||
"playerBackend": "Motore di riproduzione",
|
||||
@@ -248,16 +259,30 @@
|
||||
"displaySwitchDelay": "Ritardo cambio display",
|
||||
"tunneledPlayback": "Riproduzione tunnelizzata",
|
||||
"tunneledPlaybackDescription": "Usa tunneling video. Disattiva se la riproduzione HDR mostra video nero.",
|
||||
"dvConversionMode": "Conversione Dolby Vision",
|
||||
"dvConversionModeDescription": "Scegli come ExoPlayer gestisce i file Dolby Vision Profile 7.",
|
||||
"dvConversionAuto": "Auto",
|
||||
"dvConversionNative": "Nativo / disattivato",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "Usa il rilevamento delle capacità del dispositivo e il normale comportamento di fallback",
|
||||
"dvConversionNativeDescription": "Forza DV7 nativo e sopprime il nuovo tentativo di conversione DV",
|
||||
"dvConversionDv81Description": "Forza la conversione RPU inline a Dolby Vision profilo 8.1",
|
||||
"dvConversionHevcStripDescription": "Rimuove i livelli RPU/EL Dolby Vision e presenta HEVC semplice",
|
||||
"requireProfileSelectionOnOpen": "Chiedi profilo all'apertura",
|
||||
"requireProfileSelectionOnOpenDescription": "Mostra la selezione del profilo ogni volta che l'app viene aperta",
|
||||
"forceTvMode": "Forza modalità TV",
|
||||
"forceTvModeDescription": "Forza layout TV. Per dispositivi non rilevati automaticamente. Richiede riavvio.",
|
||||
"startInFullscreen": "Avvia a schermo intero",
|
||||
"startInFullscreenDescription": "Apri Plezy a schermo intero all'avvio",
|
||||
"exitFullscreenOnPlayerClose": "Esci dallo schermo intero alla chiusura del player",
|
||||
"exitFullscreenOnPlayerCloseDescription": "Esci automaticamente dallo schermo intero quando il lettore video viene chiuso",
|
||||
"autoHidePerformanceOverlay": "Nascondi automaticamente overlay prestazioni",
|
||||
"autoHidePerformanceOverlayDescription": "Dissolvi l'overlay prestazioni con i controlli di riproduzione",
|
||||
"showNavBarLabels": "Mostra etichette barra di navigazione",
|
||||
"showNavBarLabelsDescription": "Mostra le etichette sotto le icone della barra di navigazione",
|
||||
"startupSection": "Sezione di avvio",
|
||||
"startupSectionDescription": "Scegli quale sezione apre Plezy all'avvio",
|
||||
"liveTvDefaultFavorites": "Canali preferiti predefiniti",
|
||||
"liveTvDefaultFavoritesDescription": "Mostra solo i canali preferiti all'apertura della TV dal vivo",
|
||||
"display": "Schermo",
|
||||
@@ -279,6 +304,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "Imposta scorciatoia per ${actionName}",
|
||||
"clearShortcut": "Elimina scorciatoia",
|
||||
"noShortcutSet": "Nessuna scorciatoia impostata",
|
||||
"currentShortcut": "Scorciatoia attuale:",
|
||||
"actions": {
|
||||
"playPause": "Riproduci/Pausa",
|
||||
"volumeUp": "Alza volume",
|
||||
@@ -297,10 +324,14 @@
|
||||
"speedIncrease": "Aumenta velocità",
|
||||
"speedDecrease": "Diminuisci velocità",
|
||||
"speedReset": "Ripristina velocità",
|
||||
"zoomIn": "Aumenta zoom",
|
||||
"zoomOut": "Riduci zoom",
|
||||
"zoomReset": "Ripristina zoom",
|
||||
"subSeekNext": "Vai al sottotitolo successivo",
|
||||
"subSeekPrev": "Vai al sottotitolo precedente",
|
||||
"shaderToggle": "Attiva/disattiva shader",
|
||||
"skipMarker": "Salta intro/titoli di coda"
|
||||
"skipMarker": "Salta intro/titoli di coda",
|
||||
"screenshot": "Cattura schermata"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +365,10 @@
|
||||
"markAsWatched": "Segna come visto",
|
||||
"markAsUnwatched": "Segna come non visto",
|
||||
"removeFromContinueWatching": "Rimuovi da Continua a guardare",
|
||||
"viewDetails": "Vedi dettagli",
|
||||
"goToSeries": "Vai alle serie",
|
||||
"goToSeason": "Vai alla stagione",
|
||||
"shufflePlay": "Riproduzione casuale",
|
||||
"shuffleNotAvailableOffline": "Riproduzione casuale non disponibile offline",
|
||||
"fileInfo": "Info sul file",
|
||||
"deleteFromServer": "Elimina dal server",
|
||||
"confirmDelete": "Eliminare questo media e i suoi file dal server?",
|
||||
@@ -347,6 +379,19 @@
|
||||
"playFromBeginning": "Riproduci dall'inizio",
|
||||
"playVersion": "Riproduci versione..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "Valuta",
|
||||
"server": "Server",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "Imposta un punteggio",
|
||||
"notRated": "Non valutato",
|
||||
"liked": "Mi piace",
|
||||
"notLiked": "Non contrassegnato con Mi piace",
|
||||
"saved": "Salvato",
|
||||
"notAvailable": "Nessuna corrispondenza trovata",
|
||||
"noConnectedTrackers": "Collega un tracker in Impostazioni per valutarlo lì."
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}, film",
|
||||
"mediaCardShow": "${title}, serie TV",
|
||||
@@ -379,6 +424,10 @@
|
||||
"unlockRotation": "Sblocca rotazione",
|
||||
"timerActive": "Timer attivo",
|
||||
"playbackWillPauseIn": "La riproduzione si interromperà tra ${duration}",
|
||||
"sleepTimerEndOfVideo": "Fine del video corrente",
|
||||
"sleepTimerStopAtHeader": "Interrompi a",
|
||||
"sleepTimerDurationHeader": "Timer",
|
||||
"playbackWillPauseAtEnd": "La riproduzione si interromperà alla fine di questo video",
|
||||
"stillWatching": "Stai ancora guardando?",
|
||||
"pausingIn": "Pausa tra ${seconds}s",
|
||||
"continueWatching": "Continua",
|
||||
@@ -394,7 +443,7 @@
|
||||
"nextChapterButton": "Capitolo successivo",
|
||||
"muteButton": "Silenzia",
|
||||
"unmuteButton": "Riattiva audio",
|
||||
"settingsButton": "Impostazioni video",
|
||||
"settingsButton": "Impostazioni di riproduzione",
|
||||
"tracksButton": "Audio e sottotitoli",
|
||||
"chaptersButton": "Capitoli",
|
||||
"versionsButton": "Versioni video",
|
||||
@@ -420,6 +469,8 @@
|
||||
"endsAt": "Finisce alle ${time}",
|
||||
"pipActive": "Riproduzione in Picture-in-Picture",
|
||||
"pipFailed": "Impossibile avviare la modalità Picture-in-Picture",
|
||||
"screenshotSaved": "Schermata salvata",
|
||||
"zoomPercent": "Zoom ${percent}%",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Richiede Android 8.0 o versioni successive",
|
||||
"iosVersion": "Richiede iOS 15.0 o versioni successive",
|
||||
@@ -436,6 +487,10 @@
|
||||
"searchSubtitles": "Cerca sottotitoli",
|
||||
"language": "Lingua",
|
||||
"noSubtitlesFound": "Nessun sottotitolo trovato",
|
||||
"downloadedSubtitle": "Scaricato",
|
||||
"noSubtitlesAvailable": "Nessun sottotitolo disponibile",
|
||||
"noAudioTracksAvailable": "Nessuna traccia audio disponibile",
|
||||
"noTracksAvailable": "Nessuna traccia disponibile",
|
||||
"subtitleDownloaded": "Sottotitolo scaricato",
|
||||
"subtitleDownloadFailed": "Impossibile scaricare il sottotitolo",
|
||||
"searchLanguages": "Cerca lingue..."
|
||||
@@ -457,7 +512,6 @@
|
||||
"fileInfoNotAvailable": "Informazioni sul file non disponibili",
|
||||
"errorLoadingFileInfo": "Errore caricamento informazioni sul file: ${error}",
|
||||
"errorLoadingSeries": "Errore caricamento serie",
|
||||
"errorLoadingSeason": "Errore caricamento stagione",
|
||||
"musicNotSupported": "La riproduzione musicale non è ancora supportata",
|
||||
"noDescriptionAvailable": "Nessuna descrizione disponibile",
|
||||
"noProfilesAvailable": "Nessun profilo disponibile",
|
||||
@@ -474,8 +528,10 @@
|
||||
"metadataRefreshFailed": "Errore aggiornamento metadati: ${error}",
|
||||
"logoutConfirm": "Sei sicuro di volerti disconnettere?",
|
||||
"noSeasonsFound": "Nessuna stagione trovata",
|
||||
"seasonsLoadFailed": "Impossibile caricare le stagioni",
|
||||
"noEpisodesFound": "Nessun episodio trovato nella prima stagione",
|
||||
"noEpisodesFoundGeneral": "Nessun episodio trovato",
|
||||
"episodesLoadFailed": "Impossibile caricare gli episodi",
|
||||
"noResultsFound": "Nessun risultato",
|
||||
"sleepTimerSet": "Imposta timer spegnimento per ${label}",
|
||||
"noItemsAvailable": "Nessun elemento disponibile",
|
||||
@@ -501,7 +557,10 @@
|
||||
"position": "Posizione",
|
||||
"assOverride": "Sovrascrittura ASS",
|
||||
"bold": "Grassetto",
|
||||
"italic": "Corsivo"
|
||||
"italic": "Corsivo",
|
||||
"renderResolution": "Risoluzione di rendering",
|
||||
"renderResolutionScreen": "Risoluzione dello schermo",
|
||||
"renderResolutionVideo": "Risoluzione del video"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "Configurazione mpv",
|
||||
@@ -579,7 +638,8 @@
|
||||
"pinProtectionOptional": "Protezione PIN (opzionale)",
|
||||
"pinExplain": "PIN a 4 cifre richiesto per cambiare profilo.",
|
||||
"continueButton": "Continua",
|
||||
"pinsDontMatch": "I PIN non corrispondono"
|
||||
"pinsDontMatch": "I PIN non corrispondono",
|
||||
"initializeServicesFailed": "Impossibile inizializzare i servizi profilo"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "Connessioni",
|
||||
@@ -588,7 +648,9 @@
|
||||
"addConnectionSubtitleScoped": "Aggiungi a ${displayName}: Plex, Jellyfin o un'altra connessione profilo",
|
||||
"sessionExpiredOne": "Sessione scaduta per ${name}",
|
||||
"sessionExpiredMany": "Sessione scaduta per ${count} server",
|
||||
"signInAgain": "Accedi di nuovo"
|
||||
"signInAgain": "Accedi di nuovo",
|
||||
"editJellyfinTitle": "Modifica connessione Jellyfin",
|
||||
"editJellyfinIntro": "Aggiungi o rimuovi URL per ${serverName}. Plezy userà l'URL raggiungibile con la latenza più bassa."
|
||||
},
|
||||
"discover": {
|
||||
"title": "Esplora",
|
||||
@@ -609,7 +671,8 @@
|
||||
"rating": "Classificazione",
|
||||
"movie": "Film",
|
||||
"tvShow": "Serie TV",
|
||||
"minutesLeft": "${minutes} minuti rimanenti"
|
||||
"minutesLeft": "${minutes} minuti rimanenti",
|
||||
"moreLikeThis": "Altri contenuti simili"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "Ricerca fallita: ${error}",
|
||||
@@ -628,6 +691,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Librerie",
|
||||
"fallbackTitle": "Libreria",
|
||||
"scanLibraryFiles": "Scansiona file libreria",
|
||||
"scanLibrary": "Scansiona libreria",
|
||||
"analyze": "Analizza",
|
||||
@@ -684,15 +748,27 @@
|
||||
"genre": "Genere",
|
||||
"year": "Anno",
|
||||
"contentRating": "Classificazione",
|
||||
"tag": "Tag"
|
||||
"tag": "Tag",
|
||||
"unwatched": "Non visti"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "Titolo",
|
||||
"dateAdded": "Data di aggiunta",
|
||||
"releaseDate": "Data di uscita",
|
||||
"rating": "Valutazione",
|
||||
"communityRating": "Valutazione della community",
|
||||
"criticRating": "Valutazione critica",
|
||||
"userRating": "Valutazione utente",
|
||||
"lastPlayed": "Ultima riproduzione",
|
||||
"datePlayed": "Data di riproduzione",
|
||||
"playCount": "Riproduzioni",
|
||||
"productionYear": "Anno di produzione",
|
||||
"runtime": "Durata",
|
||||
"officialRating": "Classificazione ufficiale",
|
||||
"premiereDate": "Data di première",
|
||||
"startDate": "Data di inizio",
|
||||
"airTime": "Orario di messa in onda",
|
||||
"studio": "Studio",
|
||||
"random": "Casuale",
|
||||
"dateShared": "Data di condivisione",
|
||||
"latestEpisodeAirDate": "Data ultima messa in onda"
|
||||
@@ -739,6 +815,12 @@
|
||||
"noChannels": "Nessun canale disponibile",
|
||||
"noDvr": "Nessun DVR configurato su nessun server",
|
||||
"noPrograms": "Nessun dato di programma disponibile",
|
||||
"liveStreamFailed": "Streaming live non riuscito",
|
||||
"unknownProgram": "Programma sconosciuto",
|
||||
"unknownHub": "Sconosciuto",
|
||||
"unknownError": "Errore sconosciuto",
|
||||
"channelNumber": "Canale ${number}",
|
||||
"unknownChannel": "Canale sconosciuto",
|
||||
"live": "IN DIRETTA",
|
||||
"reloadGuide": "Ricarica guida",
|
||||
"now": "Ora",
|
||||
@@ -917,12 +999,21 @@
|
||||
"deleteDownload": "Elimina download",
|
||||
"retryDownload": "Riprova download",
|
||||
"downloadQueued": "Download in coda",
|
||||
"downloadResumed": "Download ripreso",
|
||||
"serverErrorBitrate": "Errore server: il file può superare il limite di bitrate remoto",
|
||||
"episodesQueued": "${count} episodi in coda per il download",
|
||||
"downloadDeleted": "Download eliminato",
|
||||
"deleteConfirm": "Eliminare \"${title}\" da questo dispositivo?",
|
||||
"deletingWithProgress": "Eliminazione di ${title}... (${current} di ${total})",
|
||||
"cancelledDownloadTitle": "Download annullato",
|
||||
"cancelledDownloadMessage": "Questo download è stato annullato. Cosa vuoi fare?",
|
||||
"allEpisodesAlreadyDownloaded": "Tutti gli episodi sono già stati scaricati",
|
||||
"resumeDownload": "Riprendi download",
|
||||
"cancelledDownload": "Download annullato",
|
||||
"syncingFile": "${file} (sincronizzazione ${status})",
|
||||
"downloadedFileClickToComplete": "${file} scaricato — fai clic per completare",
|
||||
"partialDownloadClickToComplete": "Scaricato parzialmente — fai clic per completare",
|
||||
"deleting": "Eliminazione...",
|
||||
"deletingWithProgress": "Eliminazione di ${title}... (${current} di ${total})",
|
||||
"queuedTooltip": "In coda",
|
||||
"queuedFilesTooltip": "In coda: ${files}",
|
||||
"downloadingTooltip": "Download in corso...",
|
||||
@@ -983,6 +1074,7 @@
|
||||
"companionRemote": {
|
||||
"title": "Telecomando",
|
||||
"connectedTo": "Connesso a ${name}",
|
||||
"unknownDevice": "Dispositivo sconosciuto",
|
||||
"session": {
|
||||
"startingServer": "Avvio del server remoto...",
|
||||
"failedToCreate": "Impossibile avviare il server remoto:",
|
||||
@@ -1042,11 +1134,19 @@
|
||||
"subtitles": "Sottotitoli",
|
||||
"audio": "Audio",
|
||||
"searchHint": "Cerca sul desktop..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "Nessuna interfaccia di rete trovata",
|
||||
"authenticationFailed": "Autenticazione non riuscita",
|
||||
"joinTimedOut": "Tempo scaduto durante l’accesso alla sessione",
|
||||
"failedToConnectAnyAddress": "Impossibile connettersi a qualsiasi indirizzo",
|
||||
"connectionLostAfterAttempts": "Connessione persa dopo ${attempts} tentativi",
|
||||
"connectionLost": "Connessione persa"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "Impostazioni di riproduzione",
|
||||
"playbackSpeed": "Velocità di riproduzione",
|
||||
"zoom": "Zoom",
|
||||
"sleepTimer": "Timer di spegnimento",
|
||||
"audioSync": "Sincronizzazione audio",
|
||||
"subtitleSync": "Sincronizzazione sottotitoli",
|
||||
@@ -1056,6 +1156,43 @@
|
||||
"audioPassthrough": "Audio Passthrough",
|
||||
"audioNormalization": "Normalizza volume"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "Colore",
|
||||
"performance": "Prestazioni",
|
||||
"buffer": "Buffer",
|
||||
"app": "App",
|
||||
"decoder": "Decoder",
|
||||
"rawDecoder": "Decoder raw",
|
||||
"tunneling": "Tunneling",
|
||||
"aspect": "Aspetto",
|
||||
"rotation": "Rotazione",
|
||||
"dvSource": "Sorgente DV",
|
||||
"dvPath": "Percorso DV",
|
||||
"p7Conversion": "Conv. P7",
|
||||
"sampleRate": "Frequenza camp.",
|
||||
"pixelFormat": "Formato pixel",
|
||||
"hwFormat": "Formato HW",
|
||||
"matrix": "Matrice",
|
||||
"primaries": "Primari",
|
||||
"transfer": "Transfer",
|
||||
"renderFps": "FPS render",
|
||||
"displayFps": "FPS display",
|
||||
"avSync": "Sync A/V",
|
||||
"dropped": "Scartati",
|
||||
"dvRpus": "DV RPU",
|
||||
"dvRpuAverage": "Media DV RPU",
|
||||
"dvSampleAverage": "Media camp. DV",
|
||||
"maxLuma": "Luma max",
|
||||
"minLuma": "Luma min",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "Cache usata",
|
||||
"cacheLimit": "Limite cache",
|
||||
"speed": "Velocità",
|
||||
"player": "Player",
|
||||
"memory": "Memoria",
|
||||
"uiFps": "FPS UI"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "Lettore esterno",
|
||||
"useExternalPlayer": "Usa lettore esterno",
|
||||
@@ -1065,6 +1202,7 @@
|
||||
"systemDefault": "Predefinito di sistema",
|
||||
"addCustomPlayer": "Aggiungi lettore personalizzato",
|
||||
"playerName": "Nome lettore",
|
||||
"playerNameHint": "Il mio player",
|
||||
"playerCommand": "Comando",
|
||||
"playerPackage": "Nome pacchetto",
|
||||
"playerUrlScheme": "Schema URL",
|
||||
@@ -1224,9 +1362,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Aggiungi server Jellyfin",
|
||||
"jellyfinUrlIntro": "Inserisci l'URL del server, es. `https://jellyfin.example.com`.",
|
||||
"serverUrl": "URL del server",
|
||||
"serverUrls": "URL del server",
|
||||
"serverUrlsHelper": "Sono consentiti più URL, separati da virgole.",
|
||||
"findServer": "Trova server",
|
||||
"searchingLocalServers": "Ricerca server Jellyfin locali...",
|
||||
"localServers": "Server Jellyfin locali",
|
||||
"username": "Nome utente",
|
||||
"password": "Password",
|
||||
"signIn": "Accedi",
|
||||
@@ -1236,17 +1376,12 @@
|
||||
"signInFailed": "Accesso non riuscito: ${error}",
|
||||
"quickConnectFailed": "Quick Connect non riuscito: ${error}",
|
||||
"addPlexTitle": "Accedi con Plex",
|
||||
"plexAuthIntro": "Accedi con un browser o un codice QR.",
|
||||
"plexQRPrompt": "Scansiona questo QR code per accedere.",
|
||||
"waitingForPlexConfirmation": "In attesa della conferma da plex.tv…",
|
||||
"pinExpired": "PIN scaduto prima dell'accesso. Riprova.",
|
||||
"duplicatePlexAccount": "Accesso a Plex già effettuato. Esci per cambiare account.",
|
||||
"failedToRegisterAccount": "Registrazione account non riuscita: ${error}",
|
||||
"enterJellyfinUrlError": "Inserisci l'URL del tuo server Jellyfin",
|
||||
"addConnectionTitle": "Aggiungi connessione",
|
||||
"addConnectionTitleScoped": "Aggiungi a ${name}",
|
||||
"addConnectionIntroGlobal": "Aggiungi un altro server multimediale. Plex e Jellyfin appaiono insieme in Home.",
|
||||
"addConnectionIntroScoped": "Aggiungi un nuovo server, o prendine in prestito uno da un altro profilo.",
|
||||
"signInWithPlexCard": "Accedi con Plex",
|
||||
"signInWithPlexCardSubtitle": "Autorizza questo dispositivo. I server condivisi vengono aggiunti.",
|
||||
"signInWithPlexCardSubtitleScoped": "Autorizza un account Plex. Gli utenti Home diventano profili.",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"or": "または",
|
||||
"connectToJellyfin": "Jellyfinに接続",
|
||||
"useQuickConnect": "Quick Connect を使う",
|
||||
"quickConnectCode": "Quick Connect コード",
|
||||
"quickConnectInstructions": "JellyfinでQuick Connectを開き、このコードを入力してください。",
|
||||
"quickConnectWaiting": "承認を待っています…",
|
||||
"quickConnectCancel": "キャンセル",
|
||||
@@ -36,6 +35,7 @@
|
||||
"yes": "はい",
|
||||
"no": "いいえ",
|
||||
"delete": "削除",
|
||||
"edit": "編集",
|
||||
"shuffle": "シャッフル",
|
||||
"addTo": "追加...",
|
||||
"createNew": "新規作成",
|
||||
@@ -51,6 +51,10 @@
|
||||
"settings": "設定",
|
||||
"mute": "ミュート",
|
||||
"ok": "OK",
|
||||
"off": "オフ",
|
||||
"seasonNumber": "シーズン${number}",
|
||||
"episodeNumberTitle": "エピソード${number} - ${title}",
|
||||
"chapterNumber": "チャプター${number}",
|
||||
"reconnect": "再接続",
|
||||
"exit": "終了",
|
||||
"viewAll": "すべて表示",
|
||||
@@ -111,6 +115,9 @@
|
||||
"gridView": "グリッド",
|
||||
"listView": "リスト",
|
||||
"showHeroSection": "ヒーローセクションを表示",
|
||||
"continueWatchingAction": "視聴中の操作",
|
||||
"continueWatchingPlay": "再生",
|
||||
"continueWatchingDetails": "詳細を開く",
|
||||
"useGlobalHubs": "ホームレイアウトを使用",
|
||||
"useGlobalHubsDescription": "統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。",
|
||||
"showServerNameOnHubs": "ハブにサーバー名を表示",
|
||||
@@ -125,6 +132,10 @@
|
||||
"showEpisodeNumberOnCardsDescription": "エピソードカードにシーズン番号とエピソード番号を表示します",
|
||||
"showSeasonPostersOnTabs": "タブにシーズンポスターを表示",
|
||||
"showSeasonPostersOnTabsDescription": "各シーズンのポスターをタブの上に表示します",
|
||||
"tvFullCardLayout": "フルTVカード",
|
||||
"tvFullCardLayoutDescription": "TVカードを画像のみで表示し、俳優名を重ねて表示します",
|
||||
"focusGlow": "フォーカス時の光彩",
|
||||
"focusGlowDescription": "フォーカス中のカードの周りに柔らかい光彩を表示します",
|
||||
"hideSpoilers": "未視聴エピソードのネタバレを非表示",
|
||||
"hideSpoilersDescription": "未視聴エピソードのサムネイルと説明をぼかします",
|
||||
"playerBackend": "プレーヤーバックエンド",
|
||||
@@ -248,16 +259,30 @@
|
||||
"displaySwitchDelay": "ディスプレイ切り替え遅延",
|
||||
"tunneledPlayback": "トンネル再生",
|
||||
"tunneledPlaybackDescription": "動画トンネリングを使用します。HDR再生で画面が黒くなる場合は無効にしてください。",
|
||||
"dvConversionMode": "Dolby Vision 変換",
|
||||
"dvConversionModeDescription": "ExoPlayer が Dolby Vision Profile 7 ファイルを処理する方法を選択します。",
|
||||
"dvConversionAuto": "自動",
|
||||
"dvConversionNative": "ネイティブ / 無効",
|
||||
"dvConversionDv81": "P7 → P8.1",
|
||||
"dvConversionHevcStrip": "P7 → HEVC",
|
||||
"dvConversionAutoDescription": "デバイスの機能検出と通常のフォールバック動作を使用します",
|
||||
"dvConversionNativeDescription": "ネイティブ DV7 を強制し、DV 変換の再試行を抑制します",
|
||||
"dvConversionDv81Description": "Dolby Vision プロファイル 8.1 へのインライン RPU 変換を強制します",
|
||||
"dvConversionHevcStripDescription": "Dolby Vision の RPU/EL レイヤーを削除し、通常の HEVC として扱います",
|
||||
"requireProfileSelectionOnOpen": "アプリ起動時にプロフィールを確認",
|
||||
"requireProfileSelectionOnOpenDescription": "アプリを開くたびにプロフィール選択を表示",
|
||||
"forceTvMode": "TVモードを強制",
|
||||
"forceTvModeDescription": "TVレイアウトを強制します。自動検出しないデバイス向けです。再起動が必要です。",
|
||||
"startInFullscreen": "全画面表示で起動",
|
||||
"startInFullscreenDescription": "起動時にPlezyを全画面モードで開きます",
|
||||
"exitFullscreenOnPlayerClose": "プレイヤーを閉じたときに全画面を終了",
|
||||
"exitFullscreenOnPlayerCloseDescription": "ビデオプレイヤーを閉じたときに自動的に全画面モードを終了します",
|
||||
"autoHidePerformanceOverlay": "パフォーマンスオーバーレイを自動非表示",
|
||||
"autoHidePerformanceOverlayDescription": "再生コントロールと一緒にパフォーマンスオーバーレイをフェードする",
|
||||
"showNavBarLabels": "ナビゲーションバーラベルを表示",
|
||||
"showNavBarLabelsDescription": "ナビゲーションバーアイコンの下にテキストラベルを表示",
|
||||
"startupSection": "起動時のセクション",
|
||||
"startupSectionDescription": "起動時に Plezy が開くセクションを選択します",
|
||||
"liveTvDefaultFavorites": "お気に入りチャンネルをデフォルトに",
|
||||
"liveTvDefaultFavoritesDescription": "ライブTV を開いたときにお気に入りチャンネルのみ表示",
|
||||
"display": "ディスプレイ",
|
||||
@@ -279,6 +304,8 @@
|
||||
"hotkeys": {
|
||||
"setShortcutFor": "${actionName}のショートカットを設定",
|
||||
"clearShortcut": "ショートカットをクリア",
|
||||
"noShortcutSet": "ショートカット未設定",
|
||||
"currentShortcut": "現在のショートカット:",
|
||||
"actions": {
|
||||
"playPause": "再生/一時停止",
|
||||
"volumeUp": "音量を上げる",
|
||||
@@ -297,10 +324,14 @@
|
||||
"speedIncrease": "速度を上げる",
|
||||
"speedDecrease": "速度を下げる",
|
||||
"speedReset": "速度をリセット",
|
||||
"zoomIn": "ズームイン",
|
||||
"zoomOut": "ズームアウト",
|
||||
"zoomReset": "ズームをリセット",
|
||||
"subSeekNext": "次の字幕にシーク",
|
||||
"subSeekPrev": "前の字幕にシーク",
|
||||
"shaderToggle": "シェーダー切替",
|
||||
"skipMarker": "イントロ/クレジットをスキップ"
|
||||
"skipMarker": "イントロ/クレジットをスキップ",
|
||||
"screenshot": "スクリーンショットを撮る"
|
||||
}
|
||||
},
|
||||
"fileInfo": {
|
||||
@@ -334,9 +365,10 @@
|
||||
"markAsWatched": "視聴済みにする",
|
||||
"markAsUnwatched": "未視聴にする",
|
||||
"removeFromContinueWatching": "視聴中から削除",
|
||||
"viewDetails": "詳細を表示",
|
||||
"goToSeries": "シリーズへ移動",
|
||||
"goToSeason": "シーズンへ移動",
|
||||
"shufflePlay": "シャッフル再生",
|
||||
"shuffleNotAvailableOffline": "オフラインではシャッフルを利用できません",
|
||||
"fileInfo": "ファイル情報",
|
||||
"deleteFromServer": "サーバーから削除",
|
||||
"confirmDelete": "このメディアとそのファイルをサーバーから削除しますか?",
|
||||
@@ -347,6 +379,19 @@
|
||||
"playFromBeginning": "最初から再生",
|
||||
"playVersion": "バージョンを再生..."
|
||||
},
|
||||
"rateSheet": {
|
||||
"title": "評価",
|
||||
"server": "サーバー",
|
||||
"starValue": "${rating} / 5",
|
||||
"scoreValue": "${score} / 10",
|
||||
"setScore": "スコアを設定",
|
||||
"notRated": "未評価",
|
||||
"liked": "いいね済み",
|
||||
"notLiked": "いいねなし",
|
||||
"saved": "保存済み",
|
||||
"notAvailable": "一致なし",
|
||||
"noConnectedTrackers": "設定でトラッカーを接続すると、そこで評価できます。"
|
||||
},
|
||||
"accessibility": {
|
||||
"mediaCardMovie": "${title}、映画",
|
||||
"mediaCardShow": "${title}、テレビ番組",
|
||||
@@ -379,6 +424,10 @@
|
||||
"unlockRotation": "回転のロックを解除",
|
||||
"timerActive": "タイマー動作中",
|
||||
"playbackWillPauseIn": "再生は${duration}後に一時停止します",
|
||||
"sleepTimerEndOfVideo": "現在の動画の最後",
|
||||
"sleepTimerStopAtHeader": "停止のタイミング",
|
||||
"sleepTimerDurationHeader": "タイマー",
|
||||
"playbackWillPauseAtEnd": "再生はこの動画の最後に一時停止します",
|
||||
"stillWatching": "まだ視聴中ですか?",
|
||||
"pausingIn": "${seconds}秒後に一時停止",
|
||||
"continueWatching": "続ける",
|
||||
@@ -394,7 +443,7 @@
|
||||
"nextChapterButton": "次のチャプター",
|
||||
"muteButton": "ミュート",
|
||||
"unmuteButton": "ミュート解除",
|
||||
"settingsButton": "動画設定",
|
||||
"settingsButton": "再生設定",
|
||||
"tracksButton": "音声と字幕",
|
||||
"chaptersButton": "チャプター",
|
||||
"versionsButton": "動画バージョン",
|
||||
@@ -420,6 +469,8 @@
|
||||
"endsAt": "${time}に終了",
|
||||
"pipActive": "ピクチャーインピクチャーで再生中",
|
||||
"pipFailed": "ピクチャーインピクチャーの開始に失敗しました",
|
||||
"screenshotSaved": "スクリーンショットを保存しました",
|
||||
"zoomPercent": "ズーム ${percent}%",
|
||||
"pipErrors": {
|
||||
"androidVersion": "Android 8.0以降が必要です",
|
||||
"iosVersion": "iOS 15.0以降が必要です",
|
||||
@@ -436,6 +487,10 @@
|
||||
"searchSubtitles": "字幕を検索",
|
||||
"language": "言語",
|
||||
"noSubtitlesFound": "字幕が見つかりません",
|
||||
"downloadedSubtitle": "ダウンロード済み",
|
||||
"noSubtitlesAvailable": "利用可能な字幕はありません",
|
||||
"noAudioTracksAvailable": "利用可能な音声トラックはありません",
|
||||
"noTracksAvailable": "利用可能なトラックはありません",
|
||||
"subtitleDownloaded": "字幕をダウンロードしました",
|
||||
"subtitleDownloadFailed": "字幕のダウンロードに失敗しました",
|
||||
"searchLanguages": "言語を検索..."
|
||||
@@ -457,7 +512,6 @@
|
||||
"fileInfoNotAvailable": "ファイル情報が利用できません",
|
||||
"errorLoadingFileInfo": "ファイル情報の読み込みエラー: ${error}",
|
||||
"errorLoadingSeries": "シリーズの読み込みエラー",
|
||||
"errorLoadingSeason": "シーズンの読み込みエラー",
|
||||
"musicNotSupported": "音楽の再生はまだサポートされていません",
|
||||
"noDescriptionAvailable": "説明はありません",
|
||||
"noProfilesAvailable": "利用可能なプロフィールがありません",
|
||||
@@ -474,8 +528,10 @@
|
||||
"metadataRefreshFailed": "メタデータの更新に失敗しました: ${error}",
|
||||
"logoutConfirm": "ログアウトしてもよろしいですか?",
|
||||
"noSeasonsFound": "シーズンが見つかりません",
|
||||
"seasonsLoadFailed": "シーズンを読み込めませんでした",
|
||||
"noEpisodesFound": "最初のシーズンにエピソードが見つかりません",
|
||||
"noEpisodesFoundGeneral": "エピソードが見つかりません",
|
||||
"episodesLoadFailed": "エピソードを読み込めませんでした",
|
||||
"noResultsFound": "結果が見つかりません",
|
||||
"sleepTimerSet": "スリープタイマーを${label}に設定しました",
|
||||
"noItemsAvailable": "アイテムがありません",
|
||||
@@ -501,7 +557,10 @@
|
||||
"position": "位置",
|
||||
"assOverride": "ASSオーバーライド",
|
||||
"bold": "太字",
|
||||
"italic": "斜体"
|
||||
"italic": "斜体",
|
||||
"renderResolution": "レンダリング解像度",
|
||||
"renderResolutionScreen": "画面解像度",
|
||||
"renderResolutionVideo": "動画解像度"
|
||||
},
|
||||
"mpvConfig": {
|
||||
"title": "mpv.conf",
|
||||
@@ -579,7 +638,8 @@
|
||||
"pinProtectionOptional": "PIN保護(オプション)",
|
||||
"pinExplain": "プロフィール切り替えには4桁のPINが必要です。",
|
||||
"continueButton": "続ける",
|
||||
"pinsDontMatch": "PINが一致しません"
|
||||
"pinsDontMatch": "PINが一致しません",
|
||||
"initializeServicesFailed": "プロフィールサービスの初期化に失敗しました"
|
||||
},
|
||||
"connections": {
|
||||
"sectionTitle": "接続",
|
||||
@@ -588,7 +648,9 @@
|
||||
"addConnectionSubtitleScoped": "${displayName}に追加: Plex、Jellyfin、または別プロフィールの接続",
|
||||
"sessionExpiredOne": "${name} のセッションの有効期限が切れました",
|
||||
"sessionExpiredMany": "${count} 台のサーバーのセッションの有効期限が切れました",
|
||||
"signInAgain": "再度サインイン"
|
||||
"signInAgain": "再度サインイン",
|
||||
"editJellyfinTitle": "Jellyfin接続を編集",
|
||||
"editJellyfinIntro": "${serverName} のURLを追加または削除します。Plezyは到達可能なURLのうち最も低遅延のものを使用します。"
|
||||
},
|
||||
"discover": {
|
||||
"title": "探す",
|
||||
@@ -609,7 +671,8 @@
|
||||
"rating": "評価",
|
||||
"movie": "映画",
|
||||
"tvShow": "テレビ番組",
|
||||
"minutesLeft": "残り${minutes}分"
|
||||
"minutesLeft": "残り${minutes}分",
|
||||
"moreLikeThis": "似ている作品"
|
||||
},
|
||||
"errors": {
|
||||
"searchFailed": "検索に失敗しました: ${error}",
|
||||
@@ -628,6 +691,7 @@
|
||||
},
|
||||
"libraries": {
|
||||
"title": "ライブラリ",
|
||||
"fallbackTitle": "ライブラリ",
|
||||
"scanLibraryFiles": "ライブラリファイルをスキャン",
|
||||
"scanLibrary": "ライブラリをスキャン",
|
||||
"analyze": "解析",
|
||||
@@ -684,15 +748,27 @@
|
||||
"genre": "ジャンル",
|
||||
"year": "年",
|
||||
"contentRating": "視聴年齢区分",
|
||||
"tag": "タグ"
|
||||
"tag": "タグ",
|
||||
"unwatched": "未視聴"
|
||||
},
|
||||
"sortLabels": {
|
||||
"title": "タイトル",
|
||||
"dateAdded": "追加日",
|
||||
"releaseDate": "リリース日",
|
||||
"rating": "評価",
|
||||
"communityRating": "コミュニティ評価",
|
||||
"criticRating": "批評家評価",
|
||||
"userRating": "ユーザー評価",
|
||||
"lastPlayed": "最終再生",
|
||||
"datePlayed": "再生日",
|
||||
"playCount": "再生回数",
|
||||
"productionYear": "製作年",
|
||||
"runtime": "再生時間",
|
||||
"officialRating": "公式レーティング",
|
||||
"premiereDate": "プレミア日",
|
||||
"startDate": "開始日",
|
||||
"airTime": "放送時刻",
|
||||
"studio": "スタジオ",
|
||||
"random": "ランダム",
|
||||
"dateShared": "共有日",
|
||||
"latestEpisodeAirDate": "最新エピソード放送日"
|
||||
@@ -739,6 +815,12 @@
|
||||
"noChannels": "チャンネルがありません",
|
||||
"noDvr": "どのサーバーにもDVRが設定されていません",
|
||||
"noPrograms": "番組データがありません",
|
||||
"liveStreamFailed": "ライブストリームに失敗しました",
|
||||
"unknownProgram": "不明な番組",
|
||||
"unknownHub": "不明",
|
||||
"unknownError": "不明なエラー",
|
||||
"channelNumber": "チャンネル ${number}",
|
||||
"unknownChannel": "不明なチャンネル",
|
||||
"live": "ライブ",
|
||||
"reloadGuide": "番組表を再読込",
|
||||
"now": "現在",
|
||||
@@ -917,12 +999,21 @@
|
||||
"deleteDownload": "ダウンロードを削除",
|
||||
"retryDownload": "ダウンロードを再試行",
|
||||
"downloadQueued": "ダウンロードをキューに追加しました",
|
||||
"downloadResumed": "ダウンロードを再開しました",
|
||||
"serverErrorBitrate": "サーバーエラー: ファイルがリモートビットレート制限を超えている可能性があります",
|
||||
"episodesQueued": "${count}エピソードをダウンロードキューに追加しました",
|
||||
"downloadDeleted": "ダウンロードを削除しました",
|
||||
"deleteConfirm": "このデバイスから「${title}」を削除しますか?",
|
||||
"deletingWithProgress": "${title}を削除中... (${current}/${total})",
|
||||
"cancelledDownloadTitle": "キャンセルされたダウンロード",
|
||||
"cancelledDownloadMessage": "このダウンロードはキャンセルされました。どうしますか?",
|
||||
"allEpisodesAlreadyDownloaded": "すべてのエピソードはすでにダウンロード済みです",
|
||||
"resumeDownload": "ダウンロードを再開",
|
||||
"cancelledDownload": "キャンセルされたダウンロード",
|
||||
"syncingFile": "${file}(${status}を同期中)",
|
||||
"downloadedFileClickToComplete": "${file} をダウンロード済み — クリックして完了",
|
||||
"partialDownloadClickToComplete": "一部ダウンロード済み — クリックして完了",
|
||||
"deleting": "削除中...",
|
||||
"deletingWithProgress": "${title}を削除中... (${current}/${total})",
|
||||
"queuedTooltip": "キュー",
|
||||
"queuedFilesTooltip": "キュー: ${files}",
|
||||
"downloadingTooltip": "ダウンロード中...",
|
||||
@@ -983,6 +1074,7 @@
|
||||
"companionRemote": {
|
||||
"title": "コンパニオンリモート",
|
||||
"connectedTo": "${name}に接続中",
|
||||
"unknownDevice": "不明なデバイス",
|
||||
"session": {
|
||||
"startingServer": "リモートサーバーを起動中...",
|
||||
"failedToCreate": "リモートサーバーの起動に失敗しました:",
|
||||
@@ -1042,11 +1134,19 @@
|
||||
"subtitles": "字幕",
|
||||
"audio": "音声",
|
||||
"searchHint": "デスクトップで検索..."
|
||||
},
|
||||
"errors": {
|
||||
"noNetworkInterface": "ネットワークインターフェースが見つかりません",
|
||||
"authenticationFailed": "認証に失敗しました",
|
||||
"joinTimedOut": "セッション参加がタイムアウトしました",
|
||||
"failedToConnectAnyAddress": "どのアドレスにも接続できませんでした",
|
||||
"connectionLostAfterAttempts": "${attempts}回試行後に接続が切断されました",
|
||||
"connectionLost": "接続が切断されました"
|
||||
}
|
||||
},
|
||||
"videoSettings": {
|
||||
"playbackSettings": "再生設定",
|
||||
"playbackSpeed": "再生速度",
|
||||
"zoom": "ズーム",
|
||||
"sleepTimer": "スリープタイマー",
|
||||
"audioSync": "音声同期",
|
||||
"subtitleSync": "字幕同期",
|
||||
@@ -1056,6 +1156,43 @@
|
||||
"audioPassthrough": "オーディオパススルー",
|
||||
"audioNormalization": "ラウドネス正規化"
|
||||
},
|
||||
"performanceOverlay": {
|
||||
"color": "色",
|
||||
"performance": "パフォーマンス",
|
||||
"buffer": "バッファ",
|
||||
"app": "アプリ",
|
||||
"decoder": "デコーダー",
|
||||
"rawDecoder": "Raw デコーダー",
|
||||
"tunneling": "トンネリング",
|
||||
"aspect": "アスペクト",
|
||||
"rotation": "回転",
|
||||
"dvSource": "DV ソース",
|
||||
"dvPath": "DV パス",
|
||||
"p7Conversion": "P7 変換",
|
||||
"sampleRate": "サンプルレート",
|
||||
"pixelFormat": "ピクセル形式",
|
||||
"hwFormat": "HW 形式",
|
||||
"matrix": "マトリクス",
|
||||
"primaries": "プライマリ",
|
||||
"transfer": "転送",
|
||||
"renderFps": "描画 FPS",
|
||||
"displayFps": "表示 FPS",
|
||||
"avSync": "A/V 同期",
|
||||
"dropped": "ドロップ",
|
||||
"dvRpus": "DV RPU",
|
||||
"dvRpuAverage": "DV RPU 平均",
|
||||
"dvSampleAverage": "DV サンプル平均",
|
||||
"maxLuma": "最大輝度",
|
||||
"minLuma": "最小輝度",
|
||||
"maxCll": "MaxCLL",
|
||||
"maxFall": "MaxFALL",
|
||||
"cacheUsed": "使用キャッシュ",
|
||||
"cacheLimit": "キャッシュ上限",
|
||||
"speed": "速度",
|
||||
"player": "プレーヤー",
|
||||
"memory": "メモリ",
|
||||
"uiFps": "UI FPS"
|
||||
},
|
||||
"externalPlayer": {
|
||||
"title": "外部プレーヤー",
|
||||
"useExternalPlayer": "外部プレーヤーを使用",
|
||||
@@ -1065,6 +1202,7 @@
|
||||
"systemDefault": "システムデフォルト",
|
||||
"addCustomPlayer": "カスタムプレーヤーを追加",
|
||||
"playerName": "プレーヤー名",
|
||||
"playerNameHint": "マイプレーヤー",
|
||||
"playerCommand": "コマンド",
|
||||
"playerPackage": "パッケージ名",
|
||||
"playerUrlScheme": "URLスキーム",
|
||||
@@ -1224,9 +1362,11 @@
|
||||
},
|
||||
"addServer": {
|
||||
"addJellyfinTitle": "Jellyfinサーバーを追加",
|
||||
"jellyfinUrlIntro": "サーバーURLを入力してください。例: `https://jellyfin.example.com`。",
|
||||
"serverUrl": "サーバーURL",
|
||||
"serverUrls": "サーバーURL",
|
||||
"serverUrlsHelper": "複数のURLをカンマ区切りで入力できます。",
|
||||
"findServer": "サーバーを検索",
|
||||
"searchingLocalServers": "ローカル Jellyfin サーバーを検索中...",
|
||||
"localServers": "ローカル Jellyfin サーバー",
|
||||
"username": "ユーザー名",
|
||||
"password": "パスワード",
|
||||
"signIn": "サインイン",
|
||||
@@ -1236,17 +1376,12 @@
|
||||
"signInFailed": "サインインに失敗しました: ${error}",
|
||||
"quickConnectFailed": "Quick Connectに失敗しました: ${error}",
|
||||
"addPlexTitle": "Plexでサインイン",
|
||||
"plexAuthIntro": "ブラウザまたはQRコードでサインインします。",
|
||||
"plexQRPrompt": "このQRコードをスキャンしてサインインしてください。",
|
||||
"waitingForPlexConfirmation": "plex.tvがサインインを確認するのを待っています…",
|
||||
"pinExpired": "サインイン前にPINの有効期限が切れました。もう一度お試しください。",
|
||||
"duplicatePlexAccount": "すでにPlexにサインインしています。アカウントを切り替えるにはサインアウトしてください。",
|
||||
"failedToRegisterAccount": "アカウントの登録に失敗しました: ${error}",
|
||||
"enterJellyfinUrlError": "JellyfinサーバーのURLを入力してください",
|
||||
"addConnectionTitle": "接続を追加",
|
||||
"addConnectionTitleScoped": "${name}に追加",
|
||||
"addConnectionIntroGlobal": "別のメディアサーバーを追加します。PlexとJellyfinはホームに一緒に表示されます。",
|
||||
"addConnectionIntroScoped": "新しいサーバーを追加するか、別のプロファイルから借りてください。",
|
||||
"signInWithPlexCard": "Plexでサインイン",
|
||||
"signInWithPlexCardSubtitle": "このデバイスを承認します。共有サーバーが追加されます。",
|
||||
"signInWithPlexCardSubtitleScoped": "Plexアカウントを承認します。Homeユーザーはプロフィールになります。",
|
||||
|
||||