Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fed572d19e | ||
|
|
adef523894 | ||
|
|
84bc4b2618 | ||
|
|
ead637cc92 | ||
|
|
eed6071b94 | ||
|
|
6da1f83891 | ||
|
|
8b5ee4f3dd | ||
|
|
a6cca37174 | ||
|
|
fff1b3090d | ||
|
|
c3305d2919 | ||
|
|
b457290a6b | ||
|
|
a11da3fec8 | ||
|
|
99c21ce6ae | ||
|
|
5b6016d88b | ||
|
|
6aaea847a7 | ||
|
|
a615ec6b97 | ||
|
|
c4059d0ead | ||
|
|
f95465067e | ||
|
|
e6a0840fbe | ||
|
|
cb55134cef | ||
|
|
5d83d4833c | ||
|
|
f2bf43a8bc | ||
|
|
b4b36c7e18 | ||
|
|
be01631cab | ||
|
|
02a5f8ad2c | ||
|
|
0964ab8ba2 | ||
|
|
89b8af62ea | ||
|
|
5842d9c1ec | ||
|
|
07463eea04 | ||
|
|
627374d4b5 | ||
|
|
c4b043cba9 | ||
|
|
aa9118a799 | ||
|
|
fe954eef5f | ||
|
|
66d0ef054e | ||
|
|
8f13a56e1a | ||
|
|
8061c4f5f2 | ||
|
|
802d47e980 | ||
|
|
1a9d2686c9 | ||
|
|
95800d8a72 | ||
|
|
3f55cc461e | ||
|
|
c201bc2f03 | ||
|
|
75c095a5b2 | ||
|
|
974806fe80 | ||
|
|
6f64ca2952 | ||
|
|
a9a7498991 | ||
|
|
37446e2d8e | ||
|
|
72f68bdfa7 | ||
|
|
24d7681d92 | ||
|
|
595a846bb9 | ||
|
|
7652d060e2 | ||
|
|
7fc559e64b | ||
|
|
ed1d0f1b10 | ||
|
|
5591a0094d | ||
|
|
6ab46ced54 | ||
|
|
a029b1a7c8 | ||
|
|
ca7f90d1bd | ||
|
|
4fcb221643 | ||
|
|
0f5cd11c08 | ||
|
|
7d0e04bcc0 | ||
|
|
09e0b06e49 | ||
|
|
5c08862194 | ||
|
|
de91db47c7 | ||
|
|
d7422c81cb | ||
|
|
da21481ff3 | ||
|
|
e5dc9c3f89 | ||
|
|
d7500c25c1 | ||
|
|
d1ccd236fd | ||
|
|
5961bf8881 | ||
|
|
0a75e2345e | ||
|
|
70ffe8ff15 | ||
|
|
938ddc5942 | ||
|
|
ec530c6713 | ||
|
|
a53041a352 | ||
|
|
294419109b | ||
|
|
61268fab73 | ||
|
|
8b7917fcc4 | ||
|
|
2563d624ca | ||
|
|
54af977f39 | ||
|
|
21f48382bc | ||
|
|
424c14a344 | ||
|
|
fcb167e661 | ||
|
|
32b3fb64a2 | ||
|
|
71cbb83c06 | ||
|
|
33d80b6d0e | ||
|
|
a9cbb72c63 | ||
|
|
7c496413f8 | ||
|
|
04673a8c8a | ||
|
|
958c27350d | ||
|
|
591f33aa2c | ||
|
|
dcf2314d9d | ||
|
|
4c74d6a1d5 | ||
|
|
5842d30ae8 | ||
|
|
5e19d9dad4 | ||
|
|
b0b4d5d6db | ||
|
|
a55ec642b3 | ||
|
|
aedca9b416 | ||
|
|
d9a5fb034e | ||
|
|
92cc49a265 | ||
|
|
1e83e4e6c2 | ||
|
|
e71580def9 | ||
|
|
2f47ed23cd | ||
|
|
b66eec827d | ||
|
|
df0d71e6f8 | ||
|
|
088886bfb6 | ||
|
|
e0122feb2b | ||
|
|
08a3a61c2a | ||
|
|
4cc8b4c0d9 | ||
|
|
7a4cdc8b5e | ||
|
|
20896a3d48 | ||
|
|
fc96ddc1ab | ||
|
|
4522f42bbf | ||
|
|
a4b88df965 | ||
|
|
810ef002ad | ||
|
|
cb900c255a | ||
|
|
43ab083cda | ||
|
|
3fb90a4948 | ||
|
|
65713858ea | ||
|
|
744e72d76b | ||
|
|
761303de11 | ||
|
|
4a1111f435 | ||
|
|
4b6533d25b | ||
|
|
05ef93c55b | ||
|
|
8d2eca42d4 | ||
|
|
0f3d06668f | ||
|
|
7131be4cc0 | ||
|
|
436fd7d2d5 | ||
|
|
c198bab04c | ||
|
|
2a6f752860 | ||
|
|
16c0e00302 | ||
|
|
6d75e58f52 | ||
|
|
ad1a12c998 | ||
|
|
9fe6dbe9f2 | ||
|
|
304d8a5e33 | ||
|
|
986237491f | ||
|
|
35eef09f72 | ||
|
|
8461e6ba5f | ||
|
|
93d3ec65e2 | ||
|
|
35dce90ea9 | ||
|
|
483691d43a | ||
|
|
b4a84c6a28 | ||
|
|
c5e7ce648b | ||
|
|
7cfd68c491 | ||
|
|
137f2a0e95 | ||
|
|
1bdeca3b5f | ||
|
|
cff6666219 | ||
|
|
b0798cde9f | ||
|
|
417f3a5e36 | ||
|
|
d4d44e6c72 | ||
|
|
658469f954 | ||
|
|
efd33b3a4e | ||
|
|
86498547ba | ||
|
|
5fe1e6dc65 | ||
|
|
1df47ed8e1 | ||
|
|
a7527718df | ||
|
|
7cd5bb64bb | ||
|
|
b38df008ec | ||
|
|
ceab5a5b59 | ||
|
|
6eb0805f8d | ||
|
|
a33c423985 | ||
|
|
1a26b0dd08 | ||
|
|
4cc065b73a | ||
|
|
071ae8e1c2 | ||
|
|
7658587584 | ||
|
|
49fce5ace9 | ||
|
|
057ff98ec1 | ||
|
|
00a6e056b0 | ||
|
|
78fa2c29e3 | ||
|
|
0e1af9faaf | ||
|
|
99b0528623 | ||
|
|
f5c7b95b02 | ||
|
|
d78a7d925e | ||
|
|
62c25e493e | ||
|
|
e543f417ce | ||
|
|
4c2f533eef | ||
|
|
fb048097ab | ||
|
|
4eb3ab4632 | ||
|
|
a910aa95cb | ||
|
|
3703ac47c3 | ||
|
|
c390e0fb0c | ||
|
|
3665d416c4 | ||
|
|
2e1a7130fc | ||
|
|
55382deaf9 | ||
|
|
4436efea72 | ||
|
|
8e9c81fe47 | ||
|
|
093c0596f1 | ||
|
|
908b4a8dac | ||
|
|
8033a308ce | ||
|
|
68c328b469 | ||
|
|
01f04eda42 | ||
|
|
0f016e4e13 | ||
|
|
953acedcab | ||
|
|
be9197eda6 | ||
|
|
a2b3377d91 | ||
|
|
e1b488f860 | ||
|
|
a79084b0a5 | ||
|
|
75704c7a9b | ||
|
|
f2ce587a85 | ||
|
|
947fddf540 | ||
|
|
50a9365be8 | ||
|
|
06ecba5fb5 | ||
|
|
096e285ab0 | ||
|
|
aeb6108654 | ||
|
|
f622ba8efe | ||
|
|
e47b4e0a73 | ||
|
|
9dd8aa4679 | ||
|
|
3f6e4c0716 | ||
|
|
49c117db83 | ||
|
|
d77836ef22 |
+2
-2
@@ -3,5 +3,5 @@
|
||||
!.maestro/jellyfin-demo/
|
||||
!.maestro/jellyfin-demo/**
|
||||
!scripts/
|
||||
!scripts/maestro_fixtures.py
|
||||
!scripts/maestro_real_jellyfin.py
|
||||
!scripts/maestro/maestro_fixtures.py
|
||||
!scripts/maestro/maestro_real_jellyfin.py
|
||||
|
||||
@@ -77,11 +77,12 @@ body:
|
||||
id: media-server
|
||||
attributes:
|
||||
label: Media Server
|
||||
description: Are you using Jellyfin or Plex?
|
||||
description: Are you using Jellyfin, Plex or Emby?
|
||||
multiple: true
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
- Emby
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ body:
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
- Emby
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
name: Build
|
||||
run-name: ${{ inputs.release_tag != '' && format('Release {0}', inputs.release_tag) || format('Build {0}', github.sha) }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Tag for a draft release; omit to build Actions artifacts only
|
||||
default: ''
|
||||
type: string
|
||||
build_android:
|
||||
description: Build Android
|
||||
default: true
|
||||
@@ -860,7 +865,7 @@ jobs:
|
||||
|
||||
create-release:
|
||||
needs: [validate-trusted-ref, build-android, build-ios, build-macos, build-windows, package-windows, build-linux]
|
||||
if: ${{ always() && needs.validate-trusted-ref.result == 'success' && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && inputs.build_android && inputs.build_ios && inputs.build_macos && inputs.build_windows && inputs.build_linux }}
|
||||
if: ${{ always() && needs.validate-trusted-ref.result == 'success' && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && inputs.build_android && inputs.build_ios && inputs.build_macos && inputs.build_windows && inputs.build_linux && inputs.release_tag != '' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -879,6 +884,21 @@ jobs:
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "build_number=$BUILD_NUMBER" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Validate release tag
|
||||
if: ${{ inputs.release_tag != '' }}
|
||||
env:
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
if [[ ! "$RELEASE_TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Release tag must use semantic versioning: $RELEASE_TAG" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$RELEASE_TAG" != "$VERSION" ]]; then
|
||||
echo "Release tag $RELEASE_TAG does not match pubspec version $VERSION." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Download Android artifacts
|
||||
if: ${{ inputs.build_android }}
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
@@ -1043,5 +1063,8 @@ jobs:
|
||||
files: ${{ steps.release-files.outputs.files }}
|
||||
draft: true
|
||||
prerelease: false
|
||||
name: ${{ inputs.release_tag }}
|
||||
tag_name: ${{ inputs.release_tag }}
|
||||
target_commitish: ${{ github.sha }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
run: scripts/codegen.sh --check
|
||||
|
||||
- name: Verify translation hygiene
|
||||
run: python3 scripts/clean_translations.py --check --strict
|
||||
run: python3 scripts/checks/clean_translations.py --check --strict
|
||||
|
||||
- name: Verify workflow and script guards
|
||||
run: bash scripts/ci_guard_checks.sh
|
||||
@@ -75,10 +75,10 @@ jobs:
|
||||
xargs -0 -r dart format --output=none --set-exit-if-changed
|
||||
|
||||
- name: Verify icon consistency
|
||||
run: dart run scripts/check_icon_consistency.dart
|
||||
run: dart run scripts/checks/check_icon_consistency.dart
|
||||
|
||||
- name: Analyze code
|
||||
run: dart run scripts/check_analyzer.dart
|
||||
run: dart run scripts/checks/check_analyzer.dart
|
||||
|
||||
- name: Check for unused code
|
||||
run: |
|
||||
@@ -317,7 +317,8 @@ jobs:
|
||||
mpv_property_result_contract_test \
|
||||
hdr_metadata_test \
|
||||
plane_geometry_test \
|
||||
video_params_test
|
||||
video_params_test \
|
||||
plane_render_executor_test
|
||||
|
||||
- name: Run Linux native reliability tests
|
||||
run: |
|
||||
|
||||
@@ -10,7 +10,7 @@ RUN apt-get update \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /opt/plezy-demo
|
||||
COPY scripts/maestro_fixtures.py scripts/maestro_real_jellyfin.py scripts/prepare_maestro_media.py ./
|
||||
COPY scripts/maestro/maestro_fixtures.py scripts/maestro/maestro_real_jellyfin.py scripts/maestro/prepare_maestro_media.py ./
|
||||
COPY .maestro/jellyfin-demo/seed.sh ./seed.sh
|
||||
|
||||
ARG PLEZY_DEMO_MEDIA_BASE_URL=https://demo-files.plezy.app/media-samples/
|
||||
|
||||
+11
-7
@@ -16,6 +16,10 @@
|
||||
- Run `scripts/run_tests.sh` to run the test suite (same as `flutter test`, but scaled to your core count)
|
||||
- Test your changes thoroughly
|
||||
|
||||
### AI-assisted contributions
|
||||
|
||||
AI-assisted pull requests must state in the PR description which model(s) were used (e.g. Claude Sonnet 4.5, GPT-5, Gemini 3 Pro).
|
||||
|
||||
### Code Quality Checks
|
||||
|
||||
The project includes automated CI checks that run on all pull requests:
|
||||
@@ -51,22 +55,22 @@ Prerequisites: Java 17, Flutter and Android SDK/platform tools, a running Androi
|
||||
Run the suites from the repository root (`py -3` can replace `python3` on Windows):
|
||||
|
||||
```bash
|
||||
python3 scripts/run_maestro.py basic # Basic user flows
|
||||
python3 scripts/run_maestro.py catalog # Catalog and music flows
|
||||
python3 scripts/run_maestro.py media # Codec playback and track selection
|
||||
python3 scripts/maestro/run_maestro.py basic # Basic user flows
|
||||
python3 scripts/maestro/run_maestro.py catalog # Catalog and music flows
|
||||
python3 scripts/maestro/run_maestro.py media # Codec playback and track selection
|
||||
```
|
||||
|
||||
Run one flow with `--flow`:
|
||||
|
||||
```bash
|
||||
python3 scripts/run_maestro.py basic --flow .maestro/flows/04_search.yaml
|
||||
python3 scripts/maestro/run_maestro.py basic --flow .maestro/flows/04_search.yaml
|
||||
```
|
||||
|
||||
Use `--skip-build` to reuse the debug APK and `--skip-jellyfin-build` to reuse the Jellyfin image. Set
|
||||
`--device <adb-serial>` when multiple devices are connected; physical devices also require `--adb-reverse`.
|
||||
|
||||
Top-level flows live in `.maestro/flows/`, shared setup in `.maestro/subflows/`, and focused regressions in
|
||||
`.maestro/regression_flows/`. Automatic groups are declared in `scripts/run_maestro_ci.py::GROUPS`. Every top-level
|
||||
`.maestro/regression_flows/`. Automatic groups are declared in `scripts/maestro/run_maestro_ci.py::GROUPS`. Every top-level
|
||||
regression flow must be registered either there or in `DESTRUCTIVE_MANUAL_TARGETS`; reusable subflows are not
|
||||
independent tests. A manual-only classification must state why the flow cannot run automatically.
|
||||
|
||||
@@ -75,7 +79,7 @@ manual target rather than an automatic group. Run them only against the pre-seed
|
||||
emulator, using the required opt-in:
|
||||
|
||||
```bash
|
||||
python3 scripts/run_maestro_ci.py profile-regressions --disposable-emulator
|
||||
python3 scripts/maestro/run_maestro_ci.py profile-regressions --disposable-emulator
|
||||
```
|
||||
|
||||
The target refuses to start without `--disposable-emulator`. Each profile flow writes to its own Jellyfin log and
|
||||
@@ -102,7 +106,7 @@ Update a production image only through a reviewed change:
|
||||
4. Before changing the Bugs digest, exercise it with non-production configuration and a disposable volume. Review
|
||||
migrations, take a restorable `bugs_data` backup, then validate a cloned volume. A forward-only migration rolls back
|
||||
with the prior digest and pre-change backup, not by changing the image reference alone.
|
||||
5. Run `python3 scripts/check_container_image_pins.py`, `python3 scripts/test_check_container_image_pins.py`, and
|
||||
5. Run `python3 scripts/checks/check_container_image_pins.py`, `python3 scripts/checks/test_check_container_image_pins.py`, and
|
||||
`(cd server && go test ./...)`. Inspect the rendered Compose configuration and rebuilt images locally without
|
||||
exposing configuration values. Do not publish or deploy from a review checkout, and never fall back to `latest` when
|
||||
a digest is unavailable.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
cask "plezy" do
|
||||
version "2.13.0"
|
||||
sha256 "045f632883b3418a509c95170fc7767b619280873a66c8d96aa71e01cd35408d"
|
||||
version "2.16.0"
|
||||
sha256 "87568115810fd627babfd05967fbc7d1bf9f40bd38eed319cf7b404b09e47162"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
|
||||
@@ -190,7 +190,7 @@ scripts/setup_hooks.sh
|
||||
End-to-end tests (Android emulator plus a Dockerized Jellyfin fixture):
|
||||
|
||||
```bash
|
||||
python3 scripts/run_maestro.py basic
|
||||
python3 scripts/maestro/run_maestro.py basic
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -132,7 +132,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
|
||||
val aar = File(mpvDir, mpvAar)
|
||||
val manifest = File(mpvFfmpegDevelopmentDir, ".manifest")
|
||||
val abis = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
|
||||
val libraries = listOf("avcodec", "avutil", "swresample")
|
||||
val libraries = listOf("avcodec", "avformat", "avutil", "swresample")
|
||||
inputs.file(aar)
|
||||
inputs.property("ffmpegVersion", mpvFfmpegVersion)
|
||||
inputs.property("sourceUrl", mpvFfmpegSourceUrl)
|
||||
@@ -145,6 +145,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
|
||||
outputs.files(
|
||||
File(mpvFfmpegDevelopmentDir, "include/libavcodec/avcodec.h"),
|
||||
File(mpvFfmpegDevelopmentDir, "include/libavutil/avconfig.h"),
|
||||
File(mpvFfmpegDevelopmentDir, "include/libavformat/avformat.h"),
|
||||
File(mpvFfmpegDevelopmentDir, "include/libswresample/swresample.h"),
|
||||
manifest
|
||||
)
|
||||
@@ -182,7 +183,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
|
||||
} catch (error: Exception) {
|
||||
throw GradleException("Failed to extract FFmpeg $mpvFfmpegVersion headers", error)
|
||||
}
|
||||
listOf("libavcodec", "libavutil", "libswresample").forEach { library ->
|
||||
listOf("libavcodec", "libavformat", "libavutil", "libswresample").forEach { library ->
|
||||
project.copy {
|
||||
from(File(extractedSource, library)) {
|
||||
include("*.h")
|
||||
@@ -206,6 +207,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
|
||||
from(zipTree(aar)) {
|
||||
include(
|
||||
"jni/*/libavcodec.so",
|
||||
"jni/*/libavformat.so",
|
||||
"jni/*/libavutil.so",
|
||||
"jni/*/libswresample.so"
|
||||
)
|
||||
|
||||
Vendored
+10
@@ -18,3 +18,13 @@
|
||||
|
||||
# growOutputBuffer's JNI descriptor names this type, so it may not be renamed either.
|
||||
-keep class androidx.media3.decoder.SimpleDecoderOutputBuffer { *; }
|
||||
|
||||
# ffmpeg_demuxer_jni.cc resolves the AVIO input proxy's callbacks by name
|
||||
# (FindClass on the interface, GetMethodID for position/read/length). Keeping
|
||||
# the interface members pins the names on every implementation, including the
|
||||
# anonymous proxy inside FfmpegExtractor.
|
||||
-keep interface com.edde746.plezy.exoplayer.FfmpegDemuxerJni$Input {
|
||||
long position();
|
||||
int read(byte[], int);
|
||||
long length();
|
||||
}
|
||||
|
||||
Binary file not shown.
+6
-6
@@ -107,7 +107,7 @@ class TrueHdSpeedTransitionTest {
|
||||
// AudioTrackConfig is built from OutputConfig, which stays PCM16 by design; the real
|
||||
// AudioTrack format is swapped in the builder modifier. The observable carrier signature is
|
||||
// therefore the 192kHz carrier rate with no decoder instantiated.
|
||||
if (carrierEncoding != TrueHdMatPacker.CARRIER_SAMPLE_RATE || decoderBefore != null) {
|
||||
if (carrierEncoding != IecCarrier.SAMPLE_RATE || decoderBefore != null) {
|
||||
Log.i(TAG, "==== SKIPPED: device does not take the carrier (rate=$carrierEncoding) ====")
|
||||
teardown(handler, player, thread, fixture)
|
||||
return
|
||||
@@ -137,12 +137,12 @@ class TrueHdSpeedTransitionTest {
|
||||
|
||||
assertEquals(
|
||||
"returning to 1x must put TrueHD back on the carrier",
|
||||
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
|
||||
IecCarrier.SAMPLE_RATE,
|
||||
rateRestored
|
||||
)
|
||||
assertNotEquals(
|
||||
"TrueHD must leave the IEC 61937 carrier when speed leaves 1x",
|
||||
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
|
||||
IecCarrier.SAMPLE_RATE,
|
||||
encodingAfter
|
||||
)
|
||||
assertTrue("a decoder must take over the TrueHD track", decoderAfter != null)
|
||||
@@ -203,7 +203,7 @@ class TrueHdSpeedTransitionTest {
|
||||
@Test
|
||||
fun aRateFamilyMismatchFallsBackToTheDecoderInsteadOfGoingSilent() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
if (!supportsTrueHdMatCarrier()) {
|
||||
if (!supportsIecCarrier(context)) {
|
||||
Log.i(TAG, "==== MISMATCH SKIPPED: device has no carrier route ====")
|
||||
return
|
||||
}
|
||||
@@ -297,13 +297,13 @@ class TrueHdSpeedTransitionTest {
|
||||
// AudioTrack is ever opened and the rate sequence alone cannot tell the two apart.
|
||||
assertTrue(
|
||||
"the carrier must have been entered and then left at runtime, saw: $diagnostics",
|
||||
diagnostics.any { it.contains("MAT/IEC 61937 carrier") } &&
|
||||
diagnostics.any { it.contains("via IEC 61937 carrier") } &&
|
||||
diagnostics.any { it.contains("44.1kHz-family rate its container did not") }
|
||||
)
|
||||
assertTrue("a decoder must take the stream over instead of the carrier", decoder != null)
|
||||
assertNotEquals(
|
||||
"the stream must not still be riding the carrier",
|
||||
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
|
||||
IecCarrier.SAMPLE_RATE,
|
||||
rate
|
||||
)
|
||||
assertTrue("playback must keep advancing after the fallback", positionSecond > positionFirst)
|
||||
|
||||
@@ -19,20 +19,22 @@ else()
|
||||
target_link_libraries(dovi_bridge log)
|
||||
endif()
|
||||
|
||||
foreach(ffmpeg_library avcodec avutil swresample)
|
||||
foreach(ffmpeg_library avcodec avformat avutil swresample)
|
||||
add_library(${ffmpeg_library} SHARED IMPORTED)
|
||||
set_target_properties(${ffmpeg_library} PROPERTIES
|
||||
IMPORTED_LOCATION "${MPV_FFMPEG_ROOT}/native/${ANDROID_ABI}/lib${ffmpeg_library}.so")
|
||||
endforeach()
|
||||
|
||||
add_library(ffmpegJNI SHARED
|
||||
media3_ffmpeg_decoder/ffmpeg_jni.cc)
|
||||
media3_ffmpeg_decoder/ffmpeg_jni.cc
|
||||
media3_ffmpeg_demuxer/ffmpeg_demuxer_jni.cc)
|
||||
target_compile_features(ffmpegJNI PRIVATE cxx_std_17)
|
||||
target_include_directories(ffmpegJNI PRIVATE
|
||||
"${MPV_FFMPEG_ROOT}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/media3_ffmpeg_decoder")
|
||||
target_link_libraries(ffmpegJNI
|
||||
avcodec
|
||||
avformat
|
||||
avutil
|
||||
swresample
|
||||
android
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -882,7 +882,8 @@ class MainActivity : FlutterActivity() {
|
||||
} catch (e: IllegalStateException) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "not_supported"))
|
||||
} catch (e: Exception) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "unknown", "errorMessage" to (e.message ?: "Unknown error")))
|
||||
Log.w(TAG, "Failed to enter PiP", e)
|
||||
result.success(mapOf("success" to false, "errorCode" to "unknown", "errorMessage" to e.message))
|
||||
}
|
||||
}
|
||||
"setAutoPipReady" -> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioManager
|
||||
import android.media.AudioTrack
|
||||
@@ -30,6 +31,38 @@ internal fun isPassthroughAudioMimeType(mimeType: String): Boolean = when (mimeT
|
||||
|
||||
internal fun shouldBlockDirectOutputForPassthrough(mimeType: String, audioPassthroughEnabled: Boolean): Boolean = !audioPassthroughEnabled && isPassthroughAudioMimeType(mimeType)
|
||||
|
||||
/**
|
||||
* The DTS-family mimes the bundled FFmpeg decoder claims (`FfmpegLibrary` maps both to `dca`).
|
||||
*
|
||||
* DTS Express (`audio/vnd.dts.hd;profile=lbr`) and DTS:X (`audio/vnd.dts.uhd`) are deliberately
|
||||
* excluded: FFmpeg does not claim them, so hiding their platform decoders would leave those
|
||||
* streams with no decoder at all.
|
||||
*/
|
||||
internal fun isFfmpegDtsMimeType(mimeType: String): Boolean = mimeType == MimeTypes.AUDIO_DTS || mimeType == MimeTypes.AUDIO_DTS_HD
|
||||
|
||||
/**
|
||||
* Whether a DTS stream should decode in the app's FFmpeg decoder instead of a platform
|
||||
* MediaCodec decoder.
|
||||
*
|
||||
* Platform DTS decoders cannot be trusted with decode. On Amlogic-based Google TV boxes (the
|
||||
* Onn family) DTS decode is license-gated in firmware, so `c2.amlogic.audio.decoder.dtshd`
|
||||
* initialises, drains and advances the playback position while rendering silence — and collapses
|
||||
* 5.1 to stereo where it does produce sound (#1995). FFmpeg decodes the whole `dca` family to
|
||||
* full multichannel PCM everywhere, which is what mpv and Kodi ship on the same hardware.
|
||||
*
|
||||
* Scoped to streams that are actually going to decode: [directOutputBlocked] (passthrough off,
|
||||
* downmix, normalization, the AudioTrack-failure blocklist) or a route that cannot bitstream DTS
|
||||
* in any shape ([routeCanBitstreamDts] false — the Android TV default leaves passthrough on, so
|
||||
* the setting alone cannot identify the decode path). Bitstream-capable routes are left exactly
|
||||
* alone: media3 selects direct output before it ever consults the decoder list, and leaving the
|
||||
* platform decoder visible there keeps the hardware-decoder tunneling gate unchanged.
|
||||
*/
|
||||
internal fun shouldForceFfmpegDtsDecode(
|
||||
mimeType: String,
|
||||
directOutputBlocked: () -> Boolean,
|
||||
routeCanBitstreamDts: () -> Boolean
|
||||
): Boolean = isFfmpegDtsMimeType(mimeType) && (directOutputBlocked() || !routeCanBitstreamDts())
|
||||
|
||||
/**
|
||||
* Linear PCM output encodings, i.e. the sink decoded the bitstream instead of
|
||||
* passing it through. Mirrors the platform's `AudioFormat.ENCODING_PCM_*` set.
|
||||
@@ -46,13 +79,17 @@ internal fun isPcmEncoding(encoding: Int): Boolean = when (encoding) {
|
||||
/**
|
||||
* mpv `audio-spdif` codec names and the exact platform encoding a route must
|
||||
* advertise to carry that bitstream.
|
||||
*
|
||||
* Only the codecs mpv's audiotrack AO can physically carry are listed. That AO opens every
|
||||
* spdif format as a stereo `ENCODING_IEC61937` track and clamps the track rate to
|
||||
* `getNativeOutputSampleRate` (the 48kHz mixer rate), so E-AC3 (a 192kHz burst), TrueHD
|
||||
* (192kHz/8ch MAT) and DTS-HD MA (192kHz/8ch) can never leave that AO intact. Naming one
|
||||
* anyway force-passes the codec into a track that cannot carry it (#1991); those streams
|
||||
* decode to PCM instead, like every other unnamed codec.
|
||||
*/
|
||||
private val MPV_SPDIF_CODECS: List<Pair<String, Int>> = listOf(
|
||||
"ac3" to C.ENCODING_AC3,
|
||||
"eac3" to C.ENCODING_E_AC3,
|
||||
"dts" to C.ENCODING_DTS,
|
||||
"dts-hd" to C.ENCODING_DTS_HD,
|
||||
"truehd" to C.ENCODING_DOLBY_TRUEHD
|
||||
"dts" to C.ENCODING_DTS
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -61,23 +98,36 @@ private val MPV_SPDIF_CODECS: List<Pair<String, Int>> = listOf(
|
||||
* mpv force-passes through every codec named here and has no decode fallback, so an
|
||||
* unsupported name leaves the file rendering video against a dead audio output (#1703).
|
||||
*
|
||||
* The gate is the exact encoding rather than media3's passthrough probe on purpose.
|
||||
* That probe answers DTS-HD by downgrading to the DTS core (and E-AC3 JOC to E-AC3)
|
||||
* for receivers that decode only the base layer, and it also rejects channel counts
|
||||
* above the route's PCM maximum, which does not apply to an IEC 61937 carrier. mpv
|
||||
* additionally treats `dts,dts-hd` as `dts-hd` alone, so accepting the downgrade would
|
||||
* name DTS-HD MA to a core-only receiver and lose DTS as well.
|
||||
* The gate is the exact encoding rather than media3's passthrough probe on purpose. That
|
||||
* probe answers by downgrading (DTS-HD to the DTS core, E-AC3 JOC to E-AC3) and rejects
|
||||
* channel counts above the route's PCM maximum, neither of which describes what an IEC
|
||||
* 61937 track carries.
|
||||
*/
|
||||
internal fun mpvSpdifCodecs(supportsEncoding: (Int) -> Boolean): String = MPV_SPDIF_CODECS
|
||||
.filter { (_, encoding) -> supportsEncoding(encoding) }
|
||||
.joinToString(",") { (codec, _) -> codec }
|
||||
|
||||
/** [mpvSpdifCodecs] resolved against the audio route [context] is currently routed to. */
|
||||
/**
|
||||
* [mpvSpdifCodecs] resolved against the audio route [context] is currently routed to.
|
||||
*
|
||||
* Two conditions, both required:
|
||||
* - The route must accept the exact track shape mpv opens for spdif output — stereo
|
||||
* IEC 61937 at the 48kHz mixer rate ([supportsMpvIecShape]). Advertising the raw AC3/DTS
|
||||
* encodings only says the receiver decodes them, not that the HAL takes an IEC 61937
|
||||
* AudioTrack: #1991's Shield bitstreams AC3 through ExoPlayer's raw path while every mpv
|
||||
* spdif attempt strands playback on a dead audio output, leaving nothing but AAC playable.
|
||||
* - The receiver must decode the codec itself — the raw encoding on the current
|
||||
* [AudioCapabilities] — because IEC 61937 is transport, not transcoding.
|
||||
*/
|
||||
// Deprecated only in favour of an overload that also takes spatializer channel masks, which
|
||||
// do not affect bitstream routing. Same probe ExoPlayerCore's TrueHD decision uses.
|
||||
@Suppress("DEPRECATION")
|
||||
@OptIn(UnstableApi::class)
|
||||
internal fun supportedMpvSpdifCodecs(context: Context): String {
|
||||
if (!supportsMpvIecShape(context)) {
|
||||
Log.i(TAG, "Route takes no stereo IEC 61937 track; mpv will decode instead of bitstreaming")
|
||||
return ""
|
||||
}
|
||||
val audioAttributes = AudioAttributes.Builder()
|
||||
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
|
||||
.setUsage(C.USAGE_MEDIA)
|
||||
@@ -91,8 +141,29 @@ internal fun supportedMpvSpdifCodecs(context: Context): String {
|
||||
return mpvSpdifCodecs(capabilities::supportsEncoding)
|
||||
}
|
||||
|
||||
/** The track shape mpv's audiotrack AO opens for spdif output: stereo IEC 61937 at the mixer rate. */
|
||||
private const val MPV_IEC_SAMPLE_RATE = 48_000
|
||||
private const val MPV_IEC_CHANNEL_COUNT = 2
|
||||
|
||||
internal fun supportsMpvIecShape(context: Context): Boolean = iecRouteSupported(
|
||||
sdkInt = Build.VERSION.SDK_INT,
|
||||
canSizeBuffer = { canSizeIecBuffer(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO) },
|
||||
// The SDK_INT guards repeat iecRouteSupported's tiering only because lint's NewApi
|
||||
// check cannot see through the injected lambdas.
|
||||
bitstreamSupported = {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
iecBitstreamSupported(iecProbeFormat(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
|
||||
},
|
||||
directPlaybackSupported = {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
|
||||
iecDirectPlaybackSupported(iecProbeFormat(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
|
||||
},
|
||||
hdmiRouteAdvertised = { hdmiAdvertisesIecRoute(context, MPV_IEC_SAMPLE_RATE, MPV_IEC_CHANNEL_COUNT) }
|
||||
)
|
||||
|
||||
/**
|
||||
* Whether this route can carry TrueHD as MAT inside IEC 61937 (#1804).
|
||||
* Whether this route can carry a packed bitstream inside IEC 61937 at 192kHz/7.1 — TrueHD as MAT
|
||||
* (#1804) and DTS-HD MA as DTS type IV (#1988) both ride this exact tuple.
|
||||
*
|
||||
* This is Kodi's test, and deliberately not media3's. Kodi asks the AudioTrack layer whether it can
|
||||
* size a buffer for one exact tuple — `getMinBufferSize(rate, mask, encoding) > 0` — and gates the
|
||||
@@ -100,8 +171,8 @@ internal fun supportedMpvSpdifCodecs(context: Context): String {
|
||||
* layer about the encoding, which on the boxes measured for this issue answers "TrueHD is
|
||||
* offload-capable" and says nothing about whether a raw TrueHD track will ever drain.
|
||||
*
|
||||
* Both are consulted: `getMinBufferSize` proves a track can be built, and a direct-playback oracle
|
||||
* proves the route will actually bitstream it rather than silently decode or wedge. Sizing alone is
|
||||
* Both are consulted: `getMinBufferSize` proves a track can be built, and a route oracle proves
|
||||
* the route will actually bitstream it rather than silently decode or wedge. Sizing alone is
|
||||
* not sufficient — on a Shield it answers yes for this tuple and the AudioTrack then fails to
|
||||
* initialise.
|
||||
*
|
||||
@@ -112,72 +183,99 @@ internal fun supportedMpvSpdifCodecs(context: Context): String {
|
||||
* for it means the route carries the frames. Fire OS 8 (API 30) devices bitstream TrueHD this way
|
||||
* and lost passthrough entirely under an API 33 gate (#1863). A route that still lies here fails
|
||||
* AudioTrack initialisation, which the audio recovery path answers by force-decoding.
|
||||
* - Below API 29 there is no oracle at all, so the carrier is not offered and TrueHD decodes as
|
||||
* before.
|
||||
* - API 24–28: no runtime oracle exists, so the HDMI `AudioDeviceInfo` must explicitly advertise
|
||||
* IEC 61937 at 192kHz/8ch. Shield Experience 8.x is API 28, and the previous flat `false` on
|
||||
* this tier force-decoded TrueHD on routes that genuinely carry it (#1991). A route that
|
||||
* advertises and still refuses the track fails AudioTrack initialisation into the same
|
||||
* recovery path as the tier above.
|
||||
*/
|
||||
internal fun supportsTrueHdMatCarrier(): Boolean = trueHdMatCarrierSupported(
|
||||
internal fun supportsIecCarrier(context: Context): Boolean = iecRouteSupported(
|
||||
sdkInt = Build.VERSION.SDK_INT,
|
||||
canSizeCarrierBuffer = {
|
||||
try {
|
||||
AudioTrack.getMinBufferSize(
|
||||
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
|
||||
AudioFormat.CHANNEL_OUT_7POINT1_SURROUND,
|
||||
AudioFormat.ENCODING_IEC61937
|
||||
) > 0
|
||||
} catch (error: Exception) {
|
||||
false
|
||||
}
|
||||
},
|
||||
// The SDK_INT guards repeat trueHdMatCarrierSupported's tiering only because lint's NewApi
|
||||
canSizeBuffer = { canSizeIecBuffer(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND) },
|
||||
// The SDK_INT guards repeat iecRouteSupported's tiering only because lint's NewApi
|
||||
// check cannot see through the injected lambdas.
|
||||
bitstreamSupported = {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && iecCarrierBitstreamSupported()
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
iecBitstreamSupported(iecProbeFormat(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND))
|
||||
},
|
||||
directPlaybackSupported = {
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && iecCarrierDirectPlaybackSupported()
|
||||
}
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
|
||||
iecDirectPlaybackSupported(iecProbeFormat(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND))
|
||||
},
|
||||
hdmiRouteAdvertised = { hdmiAdvertisesIecRoute(context, IecCarrier.SAMPLE_RATE, IecCarrier.CHANNEL_COUNT) }
|
||||
)
|
||||
|
||||
/**
|
||||
* [supportsTrueHdMatCarrier] with the platform probes injected. Probes are only consulted on the
|
||||
* API tiers where they exist: [bitstreamSupported] (`getDirectPlaybackSupport`) on 33+ and
|
||||
* [directPlaybackSupported] (`AudioTrack.isDirectPlaybackSupported`) on 29–32.
|
||||
* [supportsIecCarrier]/[supportsMpvIecShape] with the platform probes injected. Probes are only
|
||||
* consulted on the API tiers where they exist: [bitstreamSupported] (`getDirectPlaybackSupport`)
|
||||
* on 33+, [directPlaybackSupported] (`AudioTrack.isDirectPlaybackSupported`) on 29–32, and
|
||||
* [hdmiRouteAdvertised] (explicit HDMI `AudioDeviceInfo` advertisement) on 24–28 (#1991).
|
||||
*/
|
||||
internal fun trueHdMatCarrierSupported(
|
||||
internal fun iecRouteSupported(
|
||||
sdkInt: Int,
|
||||
canSizeCarrierBuffer: () -> Boolean,
|
||||
canSizeBuffer: () -> Boolean,
|
||||
bitstreamSupported: () -> Boolean,
|
||||
directPlaybackSupported: () -> Boolean
|
||||
directPlaybackSupported: () -> Boolean,
|
||||
hdmiRouteAdvertised: () -> Boolean
|
||||
): Boolean = when {
|
||||
sdkInt < Build.VERSION_CODES.Q -> false
|
||||
!canSizeCarrierBuffer() -> false
|
||||
// ENCODING_IEC61937 itself only exists from API 24.
|
||||
sdkInt < Build.VERSION_CODES.N -> false
|
||||
!canSizeBuffer() -> false
|
||||
sdkInt >= Build.VERSION_CODES.TIRAMISU -> bitstreamSupported()
|
||||
else -> directPlaybackSupported()
|
||||
sdkInt >= Build.VERSION_CODES.Q -> directPlaybackSupported()
|
||||
else -> hdmiRouteAdvertised()
|
||||
}
|
||||
|
||||
private fun canSizeIecBuffer(sampleRate: Int, channelMask: Int): Boolean = try {
|
||||
AudioTrack.getMinBufferSize(sampleRate, channelMask, AudioFormat.ENCODING_IEC61937) > 0
|
||||
} catch (error: Exception) {
|
||||
false
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
|
||||
private fun iecCarrierBitstreamSupported(): Boolean = try {
|
||||
val support = AudioManager.getDirectPlaybackSupport(iecCarrierProbeFormat(), movieAudioAttributes())
|
||||
private fun iecBitstreamSupported(format: AudioFormat): Boolean = try {
|
||||
val support = AudioManager.getDirectPlaybackSupport(format, movieAudioAttributes())
|
||||
(support and AudioManager.DIRECT_PLAYBACK_BITSTREAM_SUPPORTED) != 0
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "IEC 61937 carrier probe failed; not offering the TrueHD carrier", error)
|
||||
Log.w(TAG, "IEC 61937 route probe failed; not offering bitstream output", error)
|
||||
false
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
@Suppress("DEPRECATION") // Deprecated in favour of the API 33 probe the tier above uses.
|
||||
private fun iecCarrierDirectPlaybackSupported(): Boolean = try {
|
||||
AudioTrack.isDirectPlaybackSupported(iecCarrierProbeFormat(), movieAudioAttributes())
|
||||
private fun iecDirectPlaybackSupported(format: AudioFormat): Boolean = try {
|
||||
AudioTrack.isDirectPlaybackSupported(format, movieAudioAttributes())
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "IEC 61937 carrier probe failed; not offering the TrueHD carrier", error)
|
||||
Log.w(TAG, "IEC 61937 route probe failed; not offering bitstream output", error)
|
||||
false
|
||||
}
|
||||
|
||||
/** The exact tuple the carrier's `AudioTrack` is built with; see [PlezyRenderersFactory]. */
|
||||
private fun iecCarrierProbeFormat(): AudioFormat = AudioFormat.Builder()
|
||||
/**
|
||||
* Whether an HDMI output *explicitly* advertises IEC 61937 at [sampleRate]/[channelCount] —
|
||||
* the only oracle below API 29 (#1991).
|
||||
*
|
||||
* Empty `AudioDeviceInfo` capability arrays mean "unspecified" and deliberately fail this
|
||||
* check: an unvouched IEC track that initialises on a route that then renders it as PCM plays
|
||||
* the carrier as full-scale noise, which the AudioTrack-init recovery path cannot catch.
|
||||
*/
|
||||
private fun hdmiAdvertisesIecRoute(context: Context, sampleRate: Int, channelCount: Int): Boolean = try {
|
||||
val manager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
manager.getDevices(AudioManager.GET_DEVICES_OUTPUTS).any { device ->
|
||||
(device.type == AudioDeviceInfo.TYPE_HDMI || device.type == AudioDeviceInfo.TYPE_HDMI_ARC) &&
|
||||
device.encodings.contains(AudioFormat.ENCODING_IEC61937) &&
|
||||
device.sampleRates.contains(sampleRate) &&
|
||||
device.channelCounts.contains(channelCount)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "HDMI route inspection failed; not offering IEC 61937 output", error)
|
||||
false
|
||||
}
|
||||
|
||||
/** The exact tuple an IEC output's `AudioTrack` is built with; see [PlezyRenderersFactory]. */
|
||||
private fun iecProbeFormat(sampleRate: Int, channelMask: Int): AudioFormat = AudioFormat.Builder()
|
||||
.setEncoding(AudioFormat.ENCODING_IEC61937)
|
||||
.setChannelMask(AudioFormat.CHANNEL_OUT_7POINT1_SURROUND)
|
||||
.setSampleRate(TrueHdMatPacker.CARRIER_SAMPLE_RATE)
|
||||
.setChannelMask(channelMask)
|
||||
.setSampleRate(sampleRate)
|
||||
.build()
|
||||
|
||||
private fun movieAudioAttributes(): android.media.AudioAttributes = AudioAttributes.Builder()
|
||||
|
||||
-169
@@ -1,169 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.PositionHolder
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.SeekPoint
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
|
||||
/**
|
||||
* Extractor wrapper that enables approximate seeking for MKV files without Cues.
|
||||
*
|
||||
* When the underlying extractor reports an [SeekMap.Unseekable] seek map (i.e. the MKV
|
||||
* has no Cues element), this wrapper replaces it with a proportional byte-position
|
||||
* estimate and scans for the nearest Cluster boundary after seeking.
|
||||
*/
|
||||
@androidx.media3.common.util.UnstableApi
|
||||
class CuelessSeekExtractorWrapper(
|
||||
private val delegate: Extractor
|
||||
) : Extractor {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "CuelessSeek"
|
||||
|
||||
// MKV Cluster element ID: 0x1F43B675 (4-byte EBML Class-D ID)
|
||||
private val CLUSTER_ID = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
|
||||
private const val SCAN_BUFFER_SIZE = 8192
|
||||
|
||||
// Max bytes to scan for a Cluster boundary before giving up
|
||||
private const val MAX_SCAN_BYTES = 1024 * 1024 // 1 MB
|
||||
}
|
||||
|
||||
private var inputLength: Long = C.LENGTH_UNSET.toLong()
|
||||
private var needsClusterResync = false
|
||||
private var isApproximateSeeking = false
|
||||
private var pendingSeekTimeUs: Long = C.TIME_UNSET
|
||||
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(SeekInterceptingOutput(output))
|
||||
}
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
if (inputLength == C.LENGTH_UNSET.toLong()) {
|
||||
inputLength = input.length
|
||||
}
|
||||
if (needsClusterResync) {
|
||||
needsClusterResync = false
|
||||
return scanForCluster(input, seekPosition)
|
||||
}
|
||||
return delegate.read(input, seekPosition)
|
||||
}
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
if (isApproximateSeeking && position > 0) {
|
||||
needsClusterResync = true
|
||||
pendingSeekTimeUs = timeUs
|
||||
}
|
||||
delegate.seek(position, timeUs)
|
||||
}
|
||||
|
||||
override fun release() = delegate.release()
|
||||
|
||||
/**
|
||||
* Scan forward from the current input position to find the next MKV Cluster
|
||||
* element ID (0x1F43B675). Returns [Extractor.RESULT_SEEK] with the Cluster's
|
||||
* byte position so ExoPlayer repositions the DataSource there.
|
||||
*/
|
||||
private fun scanForCluster(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
val buffer = ByteArray(SCAN_BUFFER_SIZE)
|
||||
var totalScanned = 0L
|
||||
// Carry over last 3 bytes across buffer boundaries to detect split IDs
|
||||
var carry = ByteArray(0)
|
||||
|
||||
while (totalScanned < MAX_SCAN_BYTES) {
|
||||
val toRead = minOf(SCAN_BUFFER_SIZE, (MAX_SCAN_BYTES - totalScanned).toInt())
|
||||
val bytesRead: Int
|
||||
try {
|
||||
bytesRead = input.read(buffer, 0, toRead)
|
||||
} catch (_: Exception) {
|
||||
break
|
||||
}
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT) break
|
||||
|
||||
// Combine carry + new data for scanning
|
||||
val scanData = if (carry.isNotEmpty()) carry + buffer.copyOf(bytesRead) else buffer.copyOf(bytesRead)
|
||||
|
||||
for (i in 0..scanData.size - 4) {
|
||||
if (scanData[i] == CLUSTER_ID[0] &&
|
||||
scanData[i + 1] == CLUSTER_ID[1] &&
|
||||
scanData[i + 2] == CLUSTER_ID[2] &&
|
||||
scanData[i + 3] == CLUSTER_ID[3]
|
||||
) {
|
||||
// Compute the absolute byte position of this Cluster
|
||||
val clusterPosition = input.position - bytesRead - carry.size + i
|
||||
Log.d(TAG, "Found Cluster at byte $clusterPosition (scanned ${totalScanned + i} bytes)")
|
||||
seekPosition.position = clusterPosition
|
||||
delegate.seek(clusterPosition, pendingSeekTimeUs)
|
||||
pendingSeekTimeUs = C.TIME_UNSET
|
||||
return Extractor.RESULT_SEEK
|
||||
}
|
||||
}
|
||||
|
||||
// Keep last 3 bytes as carry for next iteration
|
||||
carry = if (scanData.size >= 3) scanData.copyOfRange(scanData.size - 3, scanData.size) else scanData.copyOf()
|
||||
totalScanned += bytesRead
|
||||
}
|
||||
|
||||
// Failed to find a Cluster — fall back to position 0
|
||||
Log.w(TAG, "No Cluster found after scanning $totalScanned bytes, resetting to start")
|
||||
seekPosition.position = 0
|
||||
delegate.seek(0, 0)
|
||||
return Extractor.RESULT_SEEK
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that intercepts [seekMap] calls to replace
|
||||
* [SeekMap.Unseekable] with an approximate proportional SeekMap.
|
||||
*/
|
||||
private inner class SeekInterceptingOutput(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
|
||||
override fun seekMap(seekMap: SeekMap) {
|
||||
if (seekMap is SeekMap.Unseekable) {
|
||||
val durationUs = seekMap.durationUs
|
||||
if (durationUs != C.TIME_UNSET && durationUs > 0) {
|
||||
Log.i(TAG, "Replacing Unseekable with approximate SeekMap (duration=${durationUs / 1_000_000}s)")
|
||||
isApproximateSeeking = true
|
||||
delegate.seekMap(ApproximateSeekMap(durationUs))
|
||||
return
|
||||
}
|
||||
}
|
||||
// File has real Cues or unknown duration — pass through
|
||||
isApproximateSeeking = false
|
||||
delegate.seekMap(seekMap)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Approximate SeekMap that estimates byte positions proportionally.
|
||||
* Used when the MKV has no Cues but has a known duration.
|
||||
*/
|
||||
private inner class ApproximateSeekMap(
|
||||
private val durationUs: Long
|
||||
) : SeekMap {
|
||||
|
||||
override fun isSeekable(): Boolean = true
|
||||
|
||||
override fun getDurationUs(): Long = durationUs
|
||||
|
||||
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
|
||||
val length = inputLength
|
||||
if (length == C.LENGTH_UNSET.toLong() || durationUs <= 0) {
|
||||
return SeekMap.SeekPoints(SeekPoint(0, 0))
|
||||
}
|
||||
val clampedTimeUs = timeUs.coerceIn(0, durationUs)
|
||||
val position = (clampedTimeUs.toDouble() / durationUs * length).toLong().coerceIn(0, length)
|
||||
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* Packs DTS-HD (Master Audio) access units into IEC 61937 "DTS type IV" bursts (#1988).
|
||||
*
|
||||
* Some HDMI routes advertise `ENCODING_DTS_HD` but cannot actually carry Master Audio: Amazon
|
||||
* specifies the Fire TV Stick 4K Max as "DTS-HD passthrough, basic profile", and Android has one
|
||||
* ambiguous encoding constant for both profiles until API 34. Handing media3's raw path full MA
|
||||
* frames there initialises an AudioTrack that drains normally and renders silence. The same
|
||||
* devices do bitstream the 192kHz/7.1 `ENCODING_IEC61937` carrier — the split Kodi models with
|
||||
* its "AudioTrack (IEC)" sink, and the one TrueHD already rides here (#1804, #1863) — so DTS-HD
|
||||
* is packed onto that carrier instead.
|
||||
*
|
||||
* The algorithm is a port of FFmpeg's `spdif_header_dts`/`spdif_header_dts4`
|
||||
* (libavformat/spdifenc.c, n8.1) at `dtshd_rate=768000`, the rate that fills the 8-channel/192kHz
|
||||
* carrier; Kodi's `CAEBitstreamPacker::PackDTSHD` produces the same bytes.
|
||||
*
|
||||
* Output is one complete IEC 61937 burst per access unit:
|
||||
*
|
||||
* - 8-byte preamble, little endian: `Pa=0xF872 Pb=0x4E1F Pc=0x11|subtype<<8 Pd=aligned bytes`
|
||||
* - 10-byte DTS-HD start code, 16-bit big-endian payload size, then the access unit, all 16-bit
|
||||
* byte-swapped
|
||||
* - zero padding to the burst repetition period the core frame duration maps to
|
||||
* (512 samples at 48kHz — the shape of essentially all Master Audio — is 32768 bytes)
|
||||
*
|
||||
* Unlike MAT's fixed frames, a Master Audio peak can genuinely exceed the carrier. FFmpeg answers
|
||||
* by stripping such units to the always-fitting core substream and holding that for
|
||||
* `dtshd_fallback_time` (60s) so receivers do not flap between core and MA decoding; that
|
||||
* behavior is ported as-is and pinned by the golden fixture.
|
||||
*
|
||||
* Not thread safe; the sink drives it from the playback thread only.
|
||||
*/
|
||||
internal class DtsHdIecPacker : IecCarrierPacker {
|
||||
|
||||
internal companion object {
|
||||
private const val BURST_HEADER_SIZE = 8
|
||||
private const val SYNCWORD1 = 0xF872
|
||||
private const val SYNCWORD2 = 0x4E1F
|
||||
private const val IEC61937_DTSHD = 0x11
|
||||
|
||||
/** Core and extension-substream sync words, big-endian raw framing. */
|
||||
private const val SYNC_CORE = 0x7FFE8001
|
||||
private const val SYNC_EXSS = 0x64582025
|
||||
|
||||
/**
|
||||
* Little-endian and 14-bit core framings, from S/PDIF and DTS-in-WAV captures. They have no
|
||||
* period mapping here (FFmpeg's HD path refuses them too), so they latch the stream
|
||||
* unsupported and it decodes.
|
||||
*/
|
||||
private const val SYNC_CORE_LE = 0xFE7F0180.toInt()
|
||||
private const val SYNC_CORE_14B_BE = 0x1FFFE800
|
||||
private const val SYNC_CORE_14B_LE = 0xFF1F00E8.toInt()
|
||||
|
||||
/**
|
||||
* The carrier's IEC 60958 frame rate as FFmpeg's two-channel model counts it: the burst
|
||||
* repetition period is `period = 768000 * coreSamples / coreRate` IEC 60958 frames of 4 bytes,
|
||||
* which is the same byte rate as [IecCarrier]'s 8 channels at 192kHz.
|
||||
*/
|
||||
private const val CARRIER_IEC958_RATE = 768_000
|
||||
|
||||
/** Core SFREQ index to Hz (`ff_dca_sample_rates`); zero marks invalid indices. */
|
||||
private val CORE_SAMPLE_RATES = intArrayOf(
|
||||
0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0, 12000, 24000, 48000, 96000, 192000
|
||||
)
|
||||
|
||||
/** Precedes every burst payload; `spdifenc.c`'s `dtshd_start_code`. */
|
||||
private val START_CODE = byteArrayOf(0x01, 0, 0, 0, 0, 0, 0, 0, 0xFE.toByte(), 0xFE.toByte())
|
||||
|
||||
/** Seconds of core-only output after an overflow; FFmpeg's `dtshd_fallback_time` default. */
|
||||
private const val HD_STRIP_SECONDS = 60
|
||||
|
||||
/** Minimum bytes needed to read a core header through its SFREQ field. */
|
||||
private const val MIN_CORE_HEADER_LENGTH = 9
|
||||
|
||||
/** IEC 61937-11 subtype for a burst repetition period in IEC 60958 frames, or -1. */
|
||||
private fun subtypeForPeriod(period: Long): Int = when (period) {
|
||||
512L -> 0
|
||||
1024L -> 1
|
||||
2048L -> 2
|
||||
4096L -> 3
|
||||
8192L -> 4
|
||||
16384L -> 5
|
||||
else -> -1
|
||||
}
|
||||
|
||||
private fun readSyncWord(data: ByteArray, offset: Int): Int = ((data[offset].toInt() and 0xFF) shl 24) or
|
||||
((data[offset + 1].toInt() and 0xFF) shl 16) or
|
||||
((data[offset + 2].toInt() and 0xFF) shl 8) or
|
||||
(data[offset + 3].toInt() and 0xFF)
|
||||
|
||||
/** Reads [count] (≤ 24) bits big-endian starting at absolute bit [bitPosition]. */
|
||||
private fun readBits(data: ByteArray, bitPosition: Int, count: Int): Int {
|
||||
var result = 0
|
||||
var position = bitPosition
|
||||
var remaining = count
|
||||
while (remaining > 0) {
|
||||
val byte = data[position ushr 3].toInt() and 0xFF
|
||||
val bitsLeftInByte = 8 - (position and 7)
|
||||
val take = minOf(bitsLeftInByte, remaining)
|
||||
result = (result shl take) or ((byte shr (bitsLeftInByte - take)) and ((1 shl take) - 1))
|
||||
position += take
|
||||
remaining -= take
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** `NBLKS + 1`: PCM blocks of 32 samples in the core frame at [offset]. */
|
||||
private fun coreBlocks(data: ByteArray, offset: Int): Int {
|
||||
val word = ((data[offset + 4].toInt() and 0xFF) shl 8) or (data[offset + 5].toInt() and 0xFF)
|
||||
return ((word shr 2) and 0x7F) + 1
|
||||
}
|
||||
|
||||
/** `FSIZE + 1`: the core frame's byte length. */
|
||||
private fun coreFrameSize(data: ByteArray, offset: Int): Int {
|
||||
val bits = ((data[offset + 5].toInt() and 0xFF) shl 16) or
|
||||
((data[offset + 6].toInt() and 0xFF) shl 8) or
|
||||
(data[offset + 7].toInt() and 0xFF)
|
||||
return ((bits shr 4) and 0x3FFF) + 1
|
||||
}
|
||||
|
||||
/** The core `SFREQ` field mapped to Hz; 0 for reserved indices. */
|
||||
private fun coreSampleRate(data: ByteArray, offset: Int): Int = CORE_SAMPLE_RATES[((data[offset + 8].toInt() and 0xFF) shr 2) and 0x0F]
|
||||
|
||||
/**
|
||||
* Total byte length of the extension substream at [offset] (`nuBits4ExSSFsize + 1`), or 0
|
||||
* when the header does not fit in [limit].
|
||||
*
|
||||
* Header layout after the 32-bit sync: UserDefinedBits(8), nExtSSIndex(2),
|
||||
* bHeaderSizeType(1), then a header-size field of 8 or 12 bits and this size field of 16 or
|
||||
* 20 bits — at most 75 bits, so 10 bytes cover every shape.
|
||||
*/
|
||||
private fun extensionSubstreamSize(data: ByteArray, offset: Int, limit: Int): Int {
|
||||
if (offset + 10 > limit) return 0
|
||||
val base = offset shl 3
|
||||
val wide = readBits(data, base + 42, 1) == 1
|
||||
val sizeFieldPosition = base + 43 + if (wide) 12 else 8
|
||||
return readBits(data, sizeFieldPosition, if (wide) 20 else 16) + 1
|
||||
}
|
||||
}
|
||||
|
||||
/** Burst geometry learned from the stream's core framing; zero until the first unit packs. */
|
||||
private var burstBytes = 0
|
||||
|
||||
private var burstBacking = Array(2) { ByteArray(0) }
|
||||
private var burstBuffers = Array(2) { ByteBuffer.wrap(burstBacking[it]) }
|
||||
private var burstIndex = 0
|
||||
|
||||
/** Bytes each reusable buffer was dirtied to, so padding only clears what a prior burst wrote. */
|
||||
private val dirtyEnd = intArrayOf(0, 0)
|
||||
|
||||
/** Assembles start code + size + access unit before the byte swap; sized with the bursts. */
|
||||
private var payloadScratch = ByteArray(0)
|
||||
|
||||
/** Access units still to strip to their core after an overflow. */
|
||||
private var hdStripRemaining = 0
|
||||
|
||||
/**
|
||||
* Latched when a burst had to be stripped to the core substream, so the sink can log the
|
||||
* downgrade once. Cleared by [reset].
|
||||
*/
|
||||
var strippedToCore = false
|
||||
private set
|
||||
|
||||
override var unsupportedStream = false
|
||||
private set
|
||||
|
||||
override fun reset() {
|
||||
// Buffers and the learned burst geometry survive; only per-stream state drops. The flag is
|
||||
// re-learned from the next unit; leaving it latched would silence every later stream.
|
||||
hdStripRemaining = 0
|
||||
strippedToCore = false
|
||||
unsupportedStream = false
|
||||
}
|
||||
|
||||
override fun accessUnitLength(data: ByteArray, offset: Int, limit: Int): Int {
|
||||
if (offset + 4 > limit) return 0
|
||||
when (readSyncWord(data, offset)) {
|
||||
SYNC_CORE -> Unit
|
||||
SYNC_EXSS -> {
|
||||
// A stray HD frame without its core, seen at stream starts. Its size is walkable, so it
|
||||
// is consumed as a unit and dropped by packAccessUnit; FFmpeg discards these too.
|
||||
val size = extensionSubstreamSize(data, offset, limit)
|
||||
return if (size < 4 || offset + size > limit) 0 else size
|
||||
}
|
||||
SYNC_CORE_LE, SYNC_CORE_14B_BE, SYNC_CORE_14B_LE -> {
|
||||
unsupportedStream = true
|
||||
return 0
|
||||
}
|
||||
else -> return 0
|
||||
}
|
||||
|
||||
if (offset + MIN_CORE_HEADER_LENGTH > limit) return 0
|
||||
val coreSize = coreFrameSize(data, offset)
|
||||
var end = offset + coreSize
|
||||
if (coreSize < MIN_CORE_HEADER_LENGTH || end > limit) return 0
|
||||
// Master Audio glues one or more extension substreams to the core; they belong to this unit.
|
||||
while (end + 4 <= limit && readSyncWord(data, end) == SYNC_EXSS) {
|
||||
val size = extensionSubstreamSize(data, end, limit)
|
||||
if (size < 4 || end + size > limit) return 0
|
||||
end += size
|
||||
}
|
||||
return end - offset
|
||||
}
|
||||
|
||||
override fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer? {
|
||||
if (length < MIN_CORE_HEADER_LENGTH) return null
|
||||
when (readSyncWord(data, offset)) {
|
||||
SYNC_CORE -> Unit
|
||||
// The stray leading HD frame accessUnitLength admitted; there is no core to derive a
|
||||
// period from, so it is dropped rather than carried.
|
||||
SYNC_EXSS -> return null
|
||||
else -> return null
|
||||
}
|
||||
|
||||
val blocks = coreBlocks(data, offset)
|
||||
val coreSize = coreFrameSize(data, offset)
|
||||
val sampleRate = coreSampleRate(data, offset)
|
||||
if (sampleRate == 0) {
|
||||
unsupportedStream = true
|
||||
return null
|
||||
}
|
||||
|
||||
val coreSamples = blocks shl 5
|
||||
val periodProduct = CARRIER_IEC958_RATE.toLong() * coreSamples
|
||||
val period = periodProduct / sampleRate
|
||||
val newSubtype = if (periodProduct % sampleRate != 0L) -1 else subtypeForPeriod(period)
|
||||
if (newSubtype < 0) {
|
||||
// 44.1kHz-family cores and exotic frame lengths map to no IEC 61937-11 repetition period at
|
||||
// this carrier rate; FFmpeg refuses them the same way, so the stream decodes instead.
|
||||
unsupportedStream = true
|
||||
return null
|
||||
}
|
||||
setBurstGeometry((period * 4).toInt())
|
||||
|
||||
// FFmpeg's overflow answer: a Master Audio peak the carrier cannot hold strips this and the
|
||||
// next ~60 seconds of units to the always-fitting core substream, so the receiver does not
|
||||
// flap between core and MA decoding.
|
||||
if (START_CODE.size + 2 + length > burstBytes - BURST_HEADER_SIZE) {
|
||||
hdStripRemaining = sampleRate * HD_STRIP_SECONDS / coreSamples
|
||||
}
|
||||
var payloadSize = length
|
||||
if (hdStripRemaining > 0 && coreSize <= length) {
|
||||
payloadSize = coreSize
|
||||
hdStripRemaining--
|
||||
strippedToCore = true
|
||||
}
|
||||
val payloadBytes = START_CODE.size + 2 + payloadSize
|
||||
if (payloadBytes > burstBytes - BURST_HEADER_SIZE) {
|
||||
// Even the bare core overflows this period (only possible for very short core frames);
|
||||
// nothing can be carried.
|
||||
unsupportedStream = true
|
||||
return null
|
||||
}
|
||||
|
||||
START_CODE.copyInto(payloadScratch, 0)
|
||||
payloadScratch[START_CODE.size] = (payloadSize ushr 8).toByte()
|
||||
payloadScratch[START_CODE.size + 1] = (payloadSize and 0xFF).toByte()
|
||||
data.copyInto(payloadScratch, START_CODE.size + 2, offset, offset + payloadSize)
|
||||
// A final lone byte goes out MSB-aligned; its swap partner must be zero, not stale scratch.
|
||||
if (payloadBytes and 1 == 1) payloadScratch[payloadBytes] = 0
|
||||
|
||||
burstIndex = burstIndex xor 1
|
||||
val backing = burstBacking[burstIndex]
|
||||
putLittleEndianShort(backing, 0, SYNCWORD1)
|
||||
putLittleEndianShort(backing, 2, SYNCWORD2)
|
||||
putLittleEndianShort(backing, 4, IEC61937_DTSHD or (newSubtype shl 8))
|
||||
// Aligned so (Pd & 0xF) == 0x8, which some receivers reportedly require; FFmpeg and Kodi
|
||||
// both apply the same quirk.
|
||||
putLittleEndianShort(backing, 6, ((payloadBytes + 0x17) and 0x0F.inv()) - BURST_HEADER_SIZE)
|
||||
|
||||
// The carrier is a 16-bit sample stream, so the payload goes out byte-swapped per word.
|
||||
var source = 0
|
||||
var destination = BURST_HEADER_SIZE
|
||||
val swappedPayload = payloadBytes + (payloadBytes and 1)
|
||||
while (source < swappedPayload) {
|
||||
backing[destination] = payloadScratch[source + 1]
|
||||
backing[destination + 1] = payloadScratch[source]
|
||||
source += 2
|
||||
destination += 2
|
||||
}
|
||||
if (destination < dirtyEnd[burstIndex]) {
|
||||
java.util.Arrays.fill(backing, destination, dirtyEnd[burstIndex], 0)
|
||||
}
|
||||
dirtyEnd[burstIndex] = destination
|
||||
|
||||
val burst = burstBuffers[burstIndex]
|
||||
burst.limit(burstBytes)
|
||||
burst.position(0)
|
||||
return burst
|
||||
}
|
||||
|
||||
private fun setBurstGeometry(newBurstBytes: Int) {
|
||||
if (newBurstBytes == burstBytes) return
|
||||
burstBytes = newBurstBytes
|
||||
burstBacking = Array(2) { ByteArray(newBurstBytes) }
|
||||
burstBuffers = Array(2) { ByteBuffer.wrap(burstBacking[it]).order(java.nio.ByteOrder.LITTLE_ENDIAN) }
|
||||
dirtyEnd[0] = 0
|
||||
dirtyEnd[1] = 0
|
||||
payloadScratch = ByteArray(newBurstBytes)
|
||||
}
|
||||
|
||||
private fun putLittleEndianShort(target: ByteArray, offset: Int, value: Int) {
|
||||
target[offset] = (value and 0xFF).toByte()
|
||||
target[offset + 1] = ((value shr 8) and 0xFF).toByte()
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ import androidx.media3.extractor.DefaultExtractorsFactory
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
import androidx.media3.extractor.mp4.FragmentedMp4Extractor
|
||||
import androidx.media3.extractor.mp4.Mp4Extractor
|
||||
import androidx.media3.extractor.text.SubtitleTranscodingExtractorOutput
|
||||
import androidx.media3.extractor.ts.TsExtractor
|
||||
import androidx.media3.ui.AspectRatioFrameLayout
|
||||
import androidx.media3.ui.CaptionStyleCompat
|
||||
@@ -71,6 +72,7 @@ import androidx.media3.ui.SubtitleView
|
||||
import com.edde746.plezy.AndroidRuntimeDiagnostics
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
|
||||
import com.edde746.plezy.libass.media.text.AssSubtitleExtractorOutput
|
||||
import com.edde746.plezy.libass.media.widget.AssSubtitleSurfaceView
|
||||
import com.edde746.plezy.shared.AudioFocusManager
|
||||
import com.edde746.plezy.shared.DeviceQuirks
|
||||
@@ -229,6 +231,12 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
private var trackSelector: DefaultTrackSelector? = null
|
||||
private var tunnelingUserEnabled: Boolean = true
|
||||
private var tunnelingDisabledForAudioCodec: Boolean = false
|
||||
|
||||
// Tunnelled playback is driven by the audio codec's clock, so without a
|
||||
// hardware audio decoder media3 never tunnels regardless of the flag —
|
||||
// used to skip selector churn for no-op flips (see
|
||||
// updateCurrentTunnelingState). True until an evaluation says otherwise.
|
||||
private var selectedAudioHasHwDecoder: Boolean = true
|
||||
private var tunnelingDisabledForVideoCodec: Boolean = false
|
||||
private var tunnelingDisabledForDecodedPcm: Boolean = false
|
||||
private var tunnelingDisabledForAudioRecovery: Boolean = false
|
||||
@@ -314,6 +322,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
private var lastAudioRecoveryReason: String? = null
|
||||
private var lastAudioSinkError: String? = null
|
||||
private var loggedEwasteEac3Workaround: Boolean = false
|
||||
private val loggedDtsAppDecoderMimes = mutableSetOf<String>()
|
||||
private var lastTrueHdDirectOutputLogKey: String? = null
|
||||
private var loggedDecodedPcmTunnelingGuard: Boolean = false
|
||||
private var hasRenderedVideoFrameForMedia: Boolean = false
|
||||
@@ -554,6 +563,18 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
|
||||
@Volatile private var activeDoviMp4Wrapper: DoviExtractorWrapper? = null
|
||||
|
||||
// The FFmpeg extractor from the current session; getStats reads its
|
||||
// measured audio bitrate for the playing item.
|
||||
@Volatile private var activeFfmpegExtractor: FfmpegExtractor? = null
|
||||
|
||||
// Container-demuxer placement; read per media item when extractors are built.
|
||||
@Volatile private var demuxerPreference: FfmpegDemuxerPolicy.Preference = FfmpegDemuxerPolicy.Preference.FFMPEG
|
||||
|
||||
fun setDemuxerMode(mode: String) {
|
||||
demuxerPreference = FfmpegDemuxerPolicy.fromWire(mode)
|
||||
emitLog("info", "init", "demuxer mode: ${demuxerPreference.wireName}")
|
||||
}
|
||||
|
||||
private fun getConfiguredDvMode(): DvConversionMode {
|
||||
val override = debugDvModeOverride
|
||||
if (override != null) return override
|
||||
@@ -571,7 +592,10 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
// Read-ahead depth, as the wire name Dart sends. Kept a String because `LoadControlPolicy`
|
||||
// is internal and this function is not; unrecognised names resolve to Auto, which is also
|
||||
// the default (#1816).
|
||||
bufferTier: String = "auto"
|
||||
bufferTier: String = "auto",
|
||||
// Whether FFmpeg demuxes ahead of media3's extractors. Wire values from
|
||||
// [FfmpegDemuxerPolicy.Preference]; unrecognised resolves to FFmpeg.
|
||||
demuxerMode: String = "ffmpeg"
|
||||
): Boolean {
|
||||
if (isInitialized) {
|
||||
Log.d(TAG, "Already initialized")
|
||||
@@ -580,6 +604,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
|
||||
tunnelingUserEnabled = tunnelingEnabled
|
||||
this.audioPassthroughEnabled = audioPassthroughEnabled
|
||||
demuxerPreference = FfmpegDemuxerPolicy.fromWire(demuxerMode)
|
||||
this.dvMode = getConfiguredDvMode()
|
||||
DoviBridge.logSupportSummary(activity)
|
||||
Log.i(
|
||||
@@ -725,6 +750,11 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
// High-bitrate Plex DVR MPEG-TS recordings can have sparse PCR packets; the default
|
||||
// 600-packet window may leave duration unknown and seeking disabled.
|
||||
.setTsExtractorTimestampSearchBytes(TS_TIMESTAMP_SEARCH_PACKETS * TsExtractor.TS_PACKET_SIZE)
|
||||
// Raw subtitle samples from MatroskaExtractor: the external text
|
||||
// pipeline below feeds libass dialogue first and then re-adds cue
|
||||
// transcoding — with the internal wrapper enabled the dialogue bytes
|
||||
// would already be consumed before our wrapper could see them.
|
||||
.setMatroskaExtractorFlags(MatroskaExtractor.FLAG_EMIT_RAW_SUBTITLE_DATA)
|
||||
|
||||
// Inline buildWithAssSupport to retain AssHandler reference for font scale control.
|
||||
val handler = AssHandler()
|
||||
@@ -734,39 +764,61 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
// composition object and blanks palette-only fade updates (#1953).
|
||||
val subtitleParserFactory = PgsSubtitleParserFactory(AssSubtitleParserFactory(handler))
|
||||
|
||||
// Wrap extractors: replace MatroskaExtractor with ASS+DV variant,
|
||||
// wrap MP4 extractors with DV converter when enabled.
|
||||
// Reads this.dvMode each time (not captured) so DV7→8.1 retry can
|
||||
// change mode and reload without reinitializing the player.
|
||||
// Wrap extractors: FFmpeg demuxes the containers media3 is weak at
|
||||
// (primary, before the list) and anything media3 cannot sniff (catch-all,
|
||||
// behind it); give MatroskaExtractor the same libass/transcoding text
|
||||
// pipeline so the media3 fallback (ffmpeg unavailable, media3-only
|
||||
// preference) keeps ASS rendering; wrap MKV/MP4 extractors with the DV
|
||||
// converter when enabled.
|
||||
// Reads this.dvMode and this.demuxerPreference each time (not captured) so
|
||||
// DV7→8.1 retry and demuxer-mode changes can reload without
|
||||
// reinitializing the player.
|
||||
val wrappedExtractorsFactory = androidx.media3.extractor.ExtractorsFactory {
|
||||
val currentDvMode = this.dvMode
|
||||
val doviEnabled = currentDvMode != DvConversionMode.DISABLED
|
||||
extractorsFactory.createExtractors().map { extractor ->
|
||||
when {
|
||||
extractor is MatroskaExtractor -> {
|
||||
val assExtractor = ZlibMatroskaExtractor(subtitleParserFactory, handler)
|
||||
val inner = if (doviEnabled) {
|
||||
DoviExtractorWrapper(assExtractor, currentDvMode) { level, prefix, message ->
|
||||
val currentDemuxerPreference = this.demuxerPreference
|
||||
Log.i(TAG, "[init] extractors: demuxer=${currentDemuxerPreference.wireName}")
|
||||
// media3 invokes the factory once per player session and reuses the
|
||||
// extractor instances for every item, so the sniff reads the live
|
||||
// preference instead of a captured one.
|
||||
val liveDemuxerPreference = { this@ExoPlayerCore.demuxerPreference }
|
||||
val ffmpegFirst =
|
||||
listOfNotNull(
|
||||
FfmpegExtractor.create(
|
||||
liveDemuxerPreference,
|
||||
currentDvMode,
|
||||
subtitleParserFactory,
|
||||
handler
|
||||
)?.also { activeFfmpegExtractor = it }
|
||||
)
|
||||
(
|
||||
ffmpegFirst + extractorsFactory.createExtractors().map { extractor ->
|
||||
when {
|
||||
extractor is MatroskaExtractor -> {
|
||||
val withTextPipeline = OutputWrappingExtractor(extractor) { out ->
|
||||
AssSubtitleExtractorOutput(SubtitleTranscodingExtractorOutput(out, subtitleParserFactory), handler)
|
||||
}
|
||||
if (doviEnabled) {
|
||||
DoviExtractorWrapper(withTextPipeline, currentDvMode) { level, prefix, message ->
|
||||
emitLog(level, prefix, message)
|
||||
}.also {
|
||||
activeDoviMkvWrapper = it
|
||||
}
|
||||
} else {
|
||||
withTextPipeline
|
||||
}
|
||||
}
|
||||
doviEnabled && (extractor is Mp4Extractor || extractor is FragmentedMp4Extractor) -> {
|
||||
DoviExtractorWrapper(extractor, currentDvMode) { level, prefix, message ->
|
||||
emitLog(level, prefix, message)
|
||||
}.also {
|
||||
activeDoviMkvWrapper = it
|
||||
activeDoviMp4Wrapper = it
|
||||
}
|
||||
} else {
|
||||
assExtractor
|
||||
}
|
||||
// Wrap with approximate seeking for MKV files without Cues
|
||||
CuelessSeekExtractorWrapper(inner)
|
||||
else -> extractor
|
||||
}
|
||||
doviEnabled && (extractor is Mp4Extractor || extractor is FragmentedMp4Extractor) -> {
|
||||
DoviExtractorWrapper(extractor, currentDvMode) { level, prefix, message ->
|
||||
emitLog(level, prefix, message)
|
||||
}.also {
|
||||
activeDoviMp4Wrapper = it
|
||||
}
|
||||
}
|
||||
else -> extractor
|
||||
}
|
||||
}.toTypedArray()
|
||||
).toTypedArray()
|
||||
}
|
||||
|
||||
val mediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory!!, wrappedExtractorsFactory)
|
||||
@@ -2318,7 +2370,20 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
// DTS that is going to decode must not decode in a platform codec: on license-gated
|
||||
// Amlogic boxes (the Onn family) the platform decoder drains normally while rendering
|
||||
// silence (#1995). Bitstream-capable routes are untouched — media3 selects direct output
|
||||
// before consulting the decoder list, and the visible platform decoder keeps the
|
||||
// tunneling gate as it was.
|
||||
val forceDts = shouldForceFfmpegDtsDecode(
|
||||
mimeType,
|
||||
directOutputBlocked = { shouldBlockDirectAudioOutput(dtsProbeFormat(mimeType), "decoder selection") },
|
||||
routeCanBitstreamDts = { routeCanBitstreamDts(mimeType) }
|
||||
)
|
||||
if (forceDts && loggedDtsAppDecoderMimes.add(mimeType)) {
|
||||
emitLog("info", "decoder", "Using app decoder for $mimeType; the stream will decode and platform DTS decoders render silence on license-gated devices")
|
||||
}
|
||||
return forceDts
|
||||
}
|
||||
|
||||
private fun evaluateTrueHdDirectOutput(format: Format?): TrueHdDirectOutputDecision {
|
||||
@@ -2427,6 +2492,33 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the current route can bitstream [mimeType] at all: media3's raw direct path
|
||||
* ([AudioCapabilities]) or, for DTS-HD, the IEC 61937 carrier ([IecCarrierSink]). When this
|
||||
* is false the stream decodes regardless of the passthrough setting.
|
||||
*/
|
||||
private fun routeCanBitstreamDts(mimeType: String): Boolean {
|
||||
if (mimeType == MimeTypes.AUDIO_DTS_HD && supportsIecCarrier(activity)) return true
|
||||
val audioAttributes = buildMovieAudioAttributes()
|
||||
return try {
|
||||
AudioCapabilities
|
||||
.getCapabilities(activity, audioAttributes, null)
|
||||
.isPassthroughPlaybackSupported(dtsProbeFormat(mimeType), audioAttributes)
|
||||
} catch (e: Exception) {
|
||||
// An unanswerable probe biases toward FFmpeg decode. A wrong "can't bitstream" is benign
|
||||
// (bypass still wins before decoder selection); a wrong "can" leaves the silent platform
|
||||
// decode path reachable.
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** DTS selection probe at the family's common shape; decoder selection only knows the mime. */
|
||||
private fun dtsProbeFormat(mimeType: String): Format = Format.Builder()
|
||||
.setSampleMimeType(mimeType)
|
||||
.setChannelCount(6)
|
||||
.setSampleRate(48_000)
|
||||
.build()
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.Q)
|
||||
@Suppress("DEPRECATION")
|
||||
private fun isDirectPlaybackSupportedApi29(
|
||||
@@ -2658,6 +2750,18 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
|
||||
private fun updateCurrentTunnelingState(reason: String, shouldTunnel: Boolean): Boolean {
|
||||
if (shouldTunnel == currentTunneledPlayback) return false
|
||||
// A switch to "off" that the selected audio decoder could never have
|
||||
// honored anyway is transparent to media3: tunnelled playback needs a
|
||||
// tunneling-capable audio codec (it owns the AV-sync clock), so a
|
||||
// software decoder already ignored the flag. Writing the selector
|
||||
// parameter regardless forces a renderer rebuild that can tear down a
|
||||
// live codec mid-queueInputBuffer — observed as
|
||||
// "queueInputBuffer ... Released state" right after tracks arrive from
|
||||
// the ffmpeg demuxer. Record the state without the churn.
|
||||
if (!shouldTunnel && !selectedAudioHasHwDecoder) {
|
||||
currentTunneledPlayback = false
|
||||
return false
|
||||
}
|
||||
currentTunneledPlayback = shouldTunnel
|
||||
val speed = exoPlayer?.playbackParameters?.speed ?: 1f
|
||||
val audioDelayActive = (renderersFactory?.audioDelayUs?.get() ?: 0L) != 0L
|
||||
@@ -2685,6 +2789,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
|
||||
val newDisabled = !hasHardwareAudioDecoder(mimeType)
|
||||
selectedAudioHasHwDecoder = !newDisabled
|
||||
if (newDisabled != tunnelingDisabledForAudioCodec) {
|
||||
tunnelingDisabledForAudioCodec = newDisabled
|
||||
emitLog("info", "tunneling", "Audio codec ${format.codecs} ($mimeType): tunneling ${if (newDisabled) "DISABLED (no hw decoder)" else "enabled"}")
|
||||
@@ -3671,6 +3776,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
dv7RetryAttempted = override != null
|
||||
activeDoviMkvWrapper = null
|
||||
activeDoviMp4Wrapper = null
|
||||
activeFfmpegExtractor = null
|
||||
val debugMode = override?.name ?: "AUTO"
|
||||
emitLog("info", "dv-debug", "P7 DV conversion mode set to $debugMode (active=$dvMode)")
|
||||
reloadCurrentMediaForDvMode()
|
||||
@@ -3707,6 +3813,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
lastDvPlaybackInfo = null
|
||||
activeDoviMkvWrapper = null
|
||||
activeDoviMp4Wrapper = null
|
||||
activeFfmpegExtractor = null
|
||||
stopFrameWatchdog()
|
||||
cancelDecoderHangCheck()
|
||||
cancelResumeStallWatchdog()
|
||||
@@ -4070,6 +4177,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
matchResolution: Boolean,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
val mgr = frameRateManager
|
||||
@@ -4077,7 +4185,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, onComplete)
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, matchResolution, onComplete)
|
||||
}
|
||||
|
||||
override fun clearVideoFrameRate() {
|
||||
@@ -4172,7 +4280,12 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
"audioMimeType" to audioFormat?.sampleMimeType,
|
||||
"audioSampleRate" to audioFormat?.sampleRate,
|
||||
"audioChannels" to audioFormat?.channelCount,
|
||||
"audioBitrate" to audioFormat?.bitrate,
|
||||
// Container-declared bitrate when present; otherwise the FFmpeg
|
||||
// demuxer's measured value (Matroska rarely carries BPS tags — #2063).
|
||||
"audioBitrate" to (
|
||||
audioFormat?.bitrate?.takeIf { it > 0 }
|
||||
?: audioFormat?.id?.let { activeFfmpegExtractor?.measuredAudioBitrateBps(it) }
|
||||
),
|
||||
"audioDecoderName" to audioDecoderInitName,
|
||||
"audioOutputEncoding" to audioTrackConfig?.encoding,
|
||||
"audioOutputChannels" to audioTrackConfig?.channelConfig?.let { Integer.bitCount(it) },
|
||||
|
||||
@@ -258,6 +258,7 @@ class ExoPlayerPlugin :
|
||||
"setBoxFitMode" -> handleSetBoxFitMode(call, result)
|
||||
"setVideoZoom" -> handleSetVideoZoom(call, result)
|
||||
"setDvConversionMode" -> handleSetDvConversionMode(call, result)
|
||||
"setDemuxerMode" -> handleSetDemuxerMode(call, result)
|
||||
"setAudioNormalization" -> handleSetAudioNormalization(call, result)
|
||||
"setAudioPassthrough" -> handleSetAudioPassthrough(call, result)
|
||||
"setAudioDownmix" -> handleSetAudioDownmix(call, result)
|
||||
@@ -296,7 +297,7 @@ class ExoPlayerPlugin :
|
||||
// on Auto because Dart derives one for mpv's demuxer, which shares the property, and
|
||||
// the fallback replay below needs it.
|
||||
val bufferSizeAuto = call.argument<Boolean>("bufferSizeAuto") ?: false
|
||||
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
|
||||
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: false
|
||||
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
|
||||
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
|
||||
val assVideoLatencyFrames = call.argument<Int>("assVideoLatencyFrames") ?: 0
|
||||
@@ -304,6 +305,7 @@ class ExoPlayerPlugin :
|
||||
// ExoPlayer-only: mpv's read-ahead is owned by the mpv.conf editor, so there is no
|
||||
// fallback replay for this one. Resolved in the core; unrecognised means Auto (#1816).
|
||||
val bufferTier = call.argument<String>("bufferTier") ?: "auto"
|
||||
val demuxerMode = call.argument<String>("demuxerMode") ?: "ffmpeg"
|
||||
configuredBufferSizeBytes = bufferSizeBytes
|
||||
// Seed the request here rather than waiting for Dart's separate setAudioPassthrough
|
||||
// call, so a fallback raised before that arrives still derives audio-spdif correctly.
|
||||
@@ -348,7 +350,8 @@ class ExoPlayerPlugin :
|
||||
bufferSizeAuto = bufferSizeAuto,
|
||||
tunnelingEnabled = tunnelingEnabled,
|
||||
audioPassthroughEnabled = audioPassthroughEnabled,
|
||||
bufferTier = bufferTier
|
||||
bufferTier = bufferTier,
|
||||
demuxerMode = demuxerMode
|
||||
)
|
||||
if (!success) {
|
||||
if (playerCore === core) playerCore = null
|
||||
@@ -1015,14 +1018,19 @@ class ExoPlayerPlugin :
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
|
||||
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
|
||||
val matchResolution = call.argument<Boolean>("matchResolution") ?: false
|
||||
|
||||
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
|
||||
Log.d(
|
||||
TAG,
|
||||
"setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, " +
|
||||
"video=${videoWidth}x$videoHeight, matchResolution=$matchResolution"
|
||||
)
|
||||
val core = activeSurfaceCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, matchResolution) { switched ->
|
||||
result.success(switched)
|
||||
}
|
||||
}
|
||||
@@ -1136,6 +1144,18 @@ class ExoPlayerPlugin :
|
||||
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
|
||||
private fun handleSetDemuxerMode(call: MethodCall, result: MethodChannel.Result) {
|
||||
val mode = call.argument<String>("mode")
|
||||
if (mode == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'mode'", null)
|
||||
return
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
playerCore?.setDemuxerMode(mode)
|
||||
result.success(null)
|
||||
} ?: 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) {
|
||||
@@ -1312,8 +1332,10 @@ class ExoPlayerPlugin :
|
||||
val observedProps = observedProperties.toList()
|
||||
val bufferSize = configuredBufferSizeBytes
|
||||
|
||||
// vo is owned by MpvPlayerCore's init: the fallback core hardware-decodes
|
||||
// (hwdec below), so it gets the legacy gpu VO — gpu-next under mediacodec
|
||||
// fails every frame on Tegra (#2010) and reshapes no DV anyway.
|
||||
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
|
||||
core.setProperty("vo", "gpu")
|
||||
core.setProperty("ao", "audiotrack")
|
||||
|
||||
if (bufferSize != null && bufferSize > 0) {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
/**
|
||||
* JNI surface for the libavformat demuxer shim (`cpp/media3_ffmpeg_demuxer`).
|
||||
*
|
||||
* One demuxer exists per process, owned by whichever [FfmpegExtractor] is
|
||||
* currently open — Plezy plays at most one progressive source at a time, and
|
||||
* every other playback mode (HLS/DASH, music) stays on media3's own sources.
|
||||
*
|
||||
* The long[] layouts mirror the constants documented in
|
||||
* `ffmpeg_demuxer_jni.cc`; keep both sides in sync.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal object FfmpegDemuxerJni {
|
||||
/** Re-entry point for the AVIO callbacks while a native call is in flight. */
|
||||
interface Input {
|
||||
/** Current byte position of the underlying [androidx.media3.extractor.ExtractorInput]. */
|
||||
fun position(): Long
|
||||
|
||||
/**
|
||||
* Reads up to [length] bytes into [buf]. Returns the number of bytes read,
|
||||
* `0` at end of input, or `-1` after storing the failure in [lastError].
|
||||
*/
|
||||
fun read(buf: ByteArray, length: Int): Int
|
||||
|
||||
/** Total input length in bytes, or `-1` when unknown. */
|
||||
fun length(): Long
|
||||
|
||||
var lastError: String?
|
||||
}
|
||||
|
||||
// readPacket out[] indices. Deferral targets travel through
|
||||
// [nativeConsumePendingSeek], not this array.
|
||||
const val OUT_CODE = 0
|
||||
const val OUT_STREAM_INDEX = 1
|
||||
const val OUT_PTS_US = 2
|
||||
const val OUT_FLAGS = 3
|
||||
const val OUT_SIZE = 4
|
||||
const val OUT_POSITION = 5
|
||||
const val OUT_DURATION_US = 6
|
||||
const val OUT_LENGTH = 7
|
||||
|
||||
// Result codes written to out[OUT_CODE]; negative values are raw AVERRORs.
|
||||
const val CODE_PACKET = 0
|
||||
const val CODE_EOF = 1
|
||||
const val CODE_NEED_SEEK = 2
|
||||
const val CODE_GROW = 3
|
||||
const val ERR_JAVA = -102
|
||||
|
||||
// streamInfo long[] layout.
|
||||
const val INFO_TRACK_TYPE = 0
|
||||
const val INFO_WIDTH = 1
|
||||
const val INFO_HEIGHT = 2
|
||||
const val INFO_PAR_NUM = 3
|
||||
const val INFO_PAR_DEN = 4
|
||||
const val INFO_FPS_NUM = 5
|
||||
const val INFO_FPS_DEN = 6
|
||||
const val INFO_SAMPLE_RATE = 7
|
||||
const val INFO_CHANNELS = 8
|
||||
const val INFO_PCM_ENCODING = 9
|
||||
const val INFO_ROTATION = 10
|
||||
const val INFO_SELECTION_FLAGS = 11
|
||||
const val INFO_ROLE_FLAGS = 12
|
||||
const val INFO_BITRATE = 13
|
||||
const val INFO_DOVI_PROFILE = 14
|
||||
const val INFO_DOVI_LEVEL = 15
|
||||
const val INFO_LATM = 16
|
||||
const val INFO_LENGTH = 17
|
||||
|
||||
val available: Boolean = try {
|
||||
System.loadLibrary("ffmpegJNI")
|
||||
true
|
||||
} catch (_: UnsatisfiedLinkError) {
|
||||
false
|
||||
}
|
||||
|
||||
/** Probes container bytes; returns the ffmpeg short name ("avi", "asf", …) or null. */
|
||||
external fun nativeProbeFormat(header: ByteArray): String?
|
||||
|
||||
/**
|
||||
* Opens (and resumes opening) the demuxer against [input]. Returns 0 on
|
||||
* success, [CODE_NEED_SEEK] when the loader must move the input first, or a
|
||||
* negative AVERROR. The stream count is read separately via
|
||||
* [nativeStreamCount]; it must not ride the same namespace as result codes.
|
||||
*/
|
||||
external fun nativeOpen(input: Input): Int
|
||||
|
||||
external fun nativeClose()
|
||||
|
||||
external fun nativeStreamCount(): Int
|
||||
|
||||
/** Total duration in microseconds, or -1 when unknown. */
|
||||
external fun nativeDurationUs(): Long
|
||||
|
||||
/** Fills [numbers]/[strings] for [index]; false when the stream is unusable. */
|
||||
external fun nativeStreamInfo(index: Int, numbers: LongArray, strings: Array<String?>): Boolean
|
||||
|
||||
/** Codec initialization data (extradata), or null. */
|
||||
external fun nativeStreamExtradata(index: Int): ByteArray?
|
||||
|
||||
/** Number of attachment streams (embedded fonts and friends) with payloads. */
|
||||
external fun nativeAttachmentCount(): Int
|
||||
|
||||
/**
|
||||
* Fills [strings] with [filename, mimetype] for attachment [ordinal] and
|
||||
* returns the payload size in bytes, or -1 when out of range. Lets Kotlin
|
||||
* enforce font budgets before copying any bytes across the boundary.
|
||||
*/
|
||||
external fun nativeAttachmentInfo(ordinal: Int, strings: Array<String?>): Long
|
||||
|
||||
/** Attachment payload bytes, or null. */
|
||||
external fun nativeAttachmentData(ordinal: Int): ByteArray?
|
||||
|
||||
/**
|
||||
* Reads one packet into [buffer], filling [out]. See the shim header
|
||||
* comment for the result contract.
|
||||
*/
|
||||
external fun nativeReadPacket(buffer: ByteArray, out: LongArray): Int
|
||||
|
||||
/** Returns the recorded seek target, or [Long.MIN_VALUE] when none. */
|
||||
external fun nativeConsumePendingSeek(): Long
|
||||
|
||||
/** Adopts [position] as the AVIO position; the input must already be there. */
|
||||
external fun nativeResumeAfterSeek(position: Long): Int
|
||||
|
||||
/**
|
||||
* Records a presentation-time seek (media3 timeline microseconds). The next
|
||||
* [nativeReadPacket] executes it via avformat_seek_file, deferring through
|
||||
* the loader as needed; the demuxer picks the byte position itself.
|
||||
*/
|
||||
external fun nativeSeekTo(timeUs: Long)
|
||||
|
||||
/** Drops cached header blocks; called when the extractor binds a new source. */
|
||||
external fun nativeResetCache()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
/**
|
||||
* Decides whether the FFmpeg demuxer sits ahead of media3's own extractors.
|
||||
*
|
||||
* FFmpeg demuxes every progressive container by default. media3's bundled
|
||||
* extractors were weak exactly where this app kept accumulating container
|
||||
* patches — AVI (XviD packed-bitstream timestamps, missing VOL csd — issue
|
||||
* #2052), ASF/WMV (no extractor at all), MPEG-PS/VOB (no extractor), and
|
||||
* Matroska (zlib-compressed subtitles, LOAS/LATM audio as A_MS/ACM, cueless
|
||||
* seeking, font attachments) — and libavformat handles all of it natively.
|
||||
* media3's extractors stay behind FFmpeg in the list, so a container FFmpeg
|
||||
* fails to sniff still reaches media3's parsers. [Preference.MEDIA3_ONLY] is
|
||||
* the user-facing escape hatch in case a file misbehaves on the FFmpeg path.
|
||||
*/
|
||||
internal object FfmpegDemuxerPolicy {
|
||||
enum class Preference(val wireName: String) {
|
||||
FFMPEG("ffmpeg"),
|
||||
MEDIA3_ONLY("media3")
|
||||
}
|
||||
|
||||
/** Unknown wire values (including the retired "auto") resolve to FFmpeg. */
|
||||
fun fromWire(value: String?): Preference = Preference.entries.firstOrNull { it.wireName == value } ?: Preference.FFMPEG
|
||||
|
||||
/** Whether the FFmpeg extractor placed before media3's list demuxes at all. */
|
||||
fun enabled(preference: Preference): Boolean = preference == Preference.FFMPEG
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.ParserException
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.PositionHolder
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.SeekPoint
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import androidx.media3.extractor.text.SubtitleTranscodingExtractorOutput
|
||||
import com.edde746.plezy.libass.media.AssFonts
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.text.AssSubtitleExtractorOutput
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Demuxes progressive containers with libavformat and feeds the packets to
|
||||
* media3's renderers, so FFmpeg's container coverage replaces media3's on the
|
||||
* paths where it is weak (AVI/XviD timestamps and VOL csd — #2052 — ASF/WMV,
|
||||
* MPEG-PS) and where the app accumulated Matroska patches (zlib-compressed
|
||||
* subtitles, LOAS/LATM audio, cueless seeking) without giving up any of the
|
||||
* renderer-side work (passthrough carriers, DV sanitizing, libass rendering
|
||||
* with embedded fonts, subtitle latency calibration).
|
||||
*
|
||||
* Text tracks are emitted in the exact sample shape media3's
|
||||
* MatroskaExtractor writes (see [FfmpegSubtitleSamples]); the output chain
|
||||
* composed in [init] then feeds libass dialogue and transcodes cues the same
|
||||
* way the media3 Matroska path does.
|
||||
*
|
||||
* Seeking protocol: see `ffmpeg_demuxer_jni.cc`. The extractor never moves the
|
||||
* input itself; position divergences abort the native call, and Kotlin either
|
||||
* returns RESULT_SEEK or resumes in place when the loader already positioned
|
||||
* the input at the requested byte.
|
||||
*
|
||||
* The instance sits before media3's extractors and sniffs everything FFmpeg
|
||||
* can probe while [FfmpegDemuxerPolicy] enables it; media3's list behind it
|
||||
* is the fallback for anything FFmpeg cannot open.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class FfmpegExtractor private constructor(
|
||||
private val preferenceSupplier: () -> FfmpegDemuxerPolicy.Preference,
|
||||
private val dvMode: DvConversionMode,
|
||||
private val subtitleParserFactory: SubtitleParser.Factory,
|
||||
private val assHandler: AssHandler
|
||||
) : Extractor {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FfmpegExtractor"
|
||||
private const val SNIFF_BYTES = 64 * 1024
|
||||
private const val MAX_RECONCILES = 24
|
||||
|
||||
// Loader round trips (RESULT_SEEK) allowed for one item's whole open
|
||||
// phase; matroska needs ~3, avi with an end-of-file index ~4.
|
||||
private const val MAX_OPEN_LOADER_ROUND_TRIPS = 96
|
||||
private const val INITIAL_PACKET_BUFFER_BYTES = 2 * 1024 * 1024
|
||||
private const val AUDIO_INDEX_INTERVAL_US = 500_000L
|
||||
|
||||
/** Null when the native library is unavailable. */
|
||||
fun create(
|
||||
preferenceSupplier: () -> FfmpegDemuxerPolicy.Preference,
|
||||
dvMode: DvConversionMode,
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
assHandler: AssHandler
|
||||
): FfmpegExtractor? = if (FfmpegDemuxerJni.available) {
|
||||
FfmpegExtractor(preferenceSupplier, dvMode, subtitleParserFactory, assHandler)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var output: ExtractorOutput
|
||||
private var currentInput: ExtractorInput? = null
|
||||
private val inputProxy = object : FfmpegDemuxerJni.Input {
|
||||
override fun position(): Long = currentInput?.position ?: 0L
|
||||
|
||||
override fun read(buf: ByteArray, length: Int): Int {
|
||||
val input = currentInput ?: return 0
|
||||
lastError = null
|
||||
return try {
|
||||
val read = input.read(buf, 0, length)
|
||||
if (read == C.RESULT_END_OF_INPUT) 0 else read
|
||||
} catch (e: IOException) {
|
||||
lastError = e.message ?: "demuxer input failed"
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
override fun length(): Long {
|
||||
val input = currentInput ?: return -1L
|
||||
val length = input.length
|
||||
return if (length == C.LENGTH_UNSET.toLong()) -1L else length
|
||||
}
|
||||
|
||||
override var lastError: String? = null
|
||||
}
|
||||
|
||||
private var opened = false
|
||||
private var doviOutputWrapper: DoviExtractorOutputWrapper? = null
|
||||
private var durationUs = C.TIME_UNSET
|
||||
private var trackOutputs: Array<TrackOutput?> = emptyArray()
|
||||
private var primaryStreamIndex = -1
|
||||
private var primaryStreamIsAudio = false
|
||||
private var packetBytes = ByteArray(INITIAL_PACKET_BUFFER_BYTES)
|
||||
private val packetParsable = ParsableByteArray()
|
||||
private val packetOut = LongArray(FfmpegDemuxerJni.OUT_LENGTH)
|
||||
private val prefixParsable = ParsableByteArray()
|
||||
|
||||
// Per-stream text handling picked in prepareTracks; parallel to trackOutputs.
|
||||
private var subtitleKinds: Array<SubtitleKind> = emptyArray()
|
||||
private val latmOutputs = ArrayList<LatmTrackOutput>()
|
||||
|
||||
// Per-audio-stream measured bitrate, parallel to trackOutputs. Written by
|
||||
// the loader thread, read by ExoPlayerCore.getStats on another thread.
|
||||
@Volatile private var bitrateMeters: Array<StreamBitrateMeter?> = emptyArray()
|
||||
|
||||
// Seek index for the primary stream: (presentation time, input position) of
|
||||
// video keyframes or periodic audio packets. The SeekMap reads it on the
|
||||
// playback thread while the loader thread appends, hence the lock.
|
||||
private val seekIndexTimes = ArrayList<Long>()
|
||||
private val seekIndexPositions = ArrayList<Long>()
|
||||
private val seekIndexLock = Any()
|
||||
|
||||
private val sniffScratch = ByteArray(SNIFF_BYTES)
|
||||
|
||||
override fun sniff(input: ExtractorInput): Boolean {
|
||||
// media3 materializes the extractor array once per player session, so the
|
||||
// policy must be read live at sniff time — a preference captured at
|
||||
// construction would freeze for the session.
|
||||
if (!FfmpegDemuxerPolicy.enabled(preferenceSupplier())) return false
|
||||
val probed = probe(input) ?: return false
|
||||
Log.i(TAG, "sniff accepted $probed")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun probe(input: ExtractorInput): String? {
|
||||
// create() only builds instances when the native library loaded.
|
||||
input.resetPeekPosition()
|
||||
return try {
|
||||
val filled =
|
||||
input.peekFully(
|
||||
sniffScratch,
|
||||
/* offset= */
|
||||
0,
|
||||
sniffScratch.size,
|
||||
/* allowEndOfInput= */
|
||||
true
|
||||
)
|
||||
if (!filled) return null
|
||||
FfmpegDemuxerJni.nativeProbeFormat(sniffScratch)?.lowercase()
|
||||
} catch (_: Throwable) {
|
||||
// A sniffer must never take playback down: media3 escalates anything
|
||||
// that is not an IOException into a fatal loader error.
|
||||
null
|
||||
} finally {
|
||||
input.resetPeekPosition()
|
||||
}
|
||||
}
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
// media3 reuses extractor instances across sources; drop the previous
|
||||
// item's header cache so this open cannot replay stale bytes.
|
||||
FfmpegDemuxerJni.nativeResetCache()
|
||||
openLoaderRoundTrips = 0
|
||||
// Same composition as the MP4/MKV paths: DoviConvertingTrackOutput
|
||||
// inspects each video track's codecs string and passes non-DV through.
|
||||
val doviWrapped = if (dvMode != DvConversionMode.DISABLED) {
|
||||
// The wrapper forwards emitLog into each converting track output; the
|
||||
// playback-info hook stays wired to the MKV/MP4 wrappers, so nothing to
|
||||
// capture here.
|
||||
DoviExtractorOutputWrapper(
|
||||
output,
|
||||
dvMode,
|
||||
emitLog = { level, prefix, message ->
|
||||
Log.println(if (level == "error") Log.ERROR else Log.INFO, TAG, "$prefix $message")
|
||||
},
|
||||
onVideoTrackWrapped = { _ -> }
|
||||
).also { doviOutputWrapper = it }
|
||||
} else {
|
||||
doviOutputWrapper = null
|
||||
output
|
||||
}
|
||||
// Text pipeline, extractor-outward: raw media3-shape samples first hit
|
||||
// AssTrackOutput (libass dialogue feed), then the transcoding wrapper
|
||||
// parses them into cue samples. media3 does NOT wrap third-party
|
||||
// extractors' outputs; without this wrapper no text track would ever
|
||||
// reach the renderer as cues.
|
||||
this.output = AssSubtitleExtractorOutput(
|
||||
SubtitleTranscodingExtractorOutput(doviWrapped, subtitleParserFactory),
|
||||
assHandler
|
||||
)
|
||||
}
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
currentInput = input
|
||||
try {
|
||||
if (!opened && !openStreams(input, seekPosition)) return Extractor.RESULT_SEEK
|
||||
return readPacket(input, seekPosition)
|
||||
} catch (e: Throwable) {
|
||||
Log.w(TAG, "read threw at input=${input.position}", e)
|
||||
throw e
|
||||
} finally {
|
||||
currentInput = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the presentation-time target to the demuxer: the next read runs
|
||||
* avformat_seek_file, which picks the byte position and resets libavformat's
|
||||
* parse state (jumping the AVIO position under the demuxer would leave
|
||||
* demuxer-private state pointing into the old stream). The byte position
|
||||
* media3 supplies is only its SeekMap guess; the loader converges on the
|
||||
* demuxer's choice through the normal deferral round trip. The DV
|
||||
* converter's buffered NAL state resets here as well.
|
||||
*/
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
Log.i(TAG, "extractor seek position=$position timeUs=$timeUs opened=$opened")
|
||||
doviOutputWrapper?.resetTracks()
|
||||
// Buffered LOAS bytes belong to the pre-seek stream; the StreamMuxConfig
|
||||
// survives so audio resumes without waiting for the next config.
|
||||
for (latm in latmOutputs) latm.reset()
|
||||
if (opened) FfmpegDemuxerJni.nativeSeekTo(timeUs)
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
if (opened) {
|
||||
opened = false
|
||||
FfmpegDemuxerJni.nativeClose()
|
||||
}
|
||||
// media3's extractors may demux a later item while this instance keeps
|
||||
// the previous one's stream layout; a stale measurement must not leak
|
||||
// into stats.
|
||||
bitrateMeters = emptyArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Measured average bitrate (bps) of the audio stream whose index matches
|
||||
* [formatId] (this extractor sets `Format.id` to the stream index), or null
|
||||
* when this instance is not demuxing that stream. Fallback for containers
|
||||
* that declare no per-track bitrate (#2063).
|
||||
*/
|
||||
fun measuredAudioBitrateBps(formatId: String?): Int? {
|
||||
val index = formatId?.toIntOrNull() ?: return null
|
||||
return bitrateMeters.getOrNull(index)?.bitrateBps()
|
||||
}
|
||||
|
||||
// The in-call `reconciles` counter resets on every read() invocation, so it
|
||||
// cannot bound RESULT_SEEK ping-pong across loader restarts. This budget
|
||||
// spans the whole open of one item (reset in init) and turns a
|
||||
// non-converging header phase into a clean fallback instead of a hang.
|
||||
private var openLoaderRoundTrips = 0
|
||||
|
||||
/** Returns false when a loader seek was requested via [seekPosition]. */
|
||||
private fun openStreams(input: ExtractorInput, seekPosition: PositionHolder): Boolean {
|
||||
var reconciles = 0
|
||||
while (true) {
|
||||
when (val code = FfmpegDemuxerJni.nativeOpen(inputProxy)) {
|
||||
0 -> {
|
||||
prepareTracks()
|
||||
opened = true
|
||||
Log.i(TAG, "ffmpeg demuxer ready: ${trackOutputs.count { it != null }} tracks")
|
||||
return true
|
||||
}
|
||||
FfmpegDemuxerJni.CODE_NEED_SEEK -> {
|
||||
val target = FfmpegDemuxerJni.nativeConsumePendingSeek()
|
||||
Log.i(TAG, "open: NEED_SEEK target=$target inputPos=${input.position}")
|
||||
if (target == Long.MIN_VALUE || target < 0) {
|
||||
// Sticky AVIO error replayed without a fresh deferral: re-sync at
|
||||
// the loader's current position and continue (bounded below).
|
||||
if (++reconciles > MAX_RECONCILES) {
|
||||
throw malformed("demuxer produced an invalid seek target: $target")
|
||||
}
|
||||
if (FfmpegDemuxerJni.nativeResumeAfterSeek(input.position) != 0) {
|
||||
throw malformed("demuxer resync failed at ${input.position}")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (++reconciles > MAX_RECONCILES) throw malformed("too many demuxer repositions")
|
||||
if (!reconcile(input, seekPosition, target)) {
|
||||
if (++openLoaderRoundTrips > MAX_OPEN_LOADER_ROUND_TRIPS) {
|
||||
throw malformed("demuxer open did not converge after $openLoaderRoundTrips loader seeks")
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
FfmpegDemuxerJni.ERR_JAVA ->
|
||||
throw IOException(inputProxy.lastError ?: "demuxer input failed")
|
||||
else -> throw malformed("ffmpeg demuxer open failed: $code")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum class SubtitleKind { NONE, SSA, SUBRIP, VTT }
|
||||
|
||||
private fun prepareTracks() {
|
||||
val count = FfmpegDemuxerJni.nativeStreamCount()
|
||||
durationUs = FfmpegDemuxerJni.nativeDurationUs().takeIf { it >= 0 } ?: C.TIME_UNSET
|
||||
trackOutputs = arrayOfNulls(count)
|
||||
subtitleKinds = Array(count) { SubtitleKind.NONE }
|
||||
bitrateMeters = arrayOfNulls(count)
|
||||
latmOutputs.clear()
|
||||
// Fonts go in before any text track exists so AssHandler's store flushes
|
||||
// them into libass when the first ASS track is created.
|
||||
deliverFontAttachments()
|
||||
val numbers = LongArray(FfmpegDemuxerJni.INFO_LENGTH)
|
||||
val strings = arrayOfNulls<String>(3)
|
||||
var primaryVideo = -1
|
||||
var primaryAudio = -1
|
||||
|
||||
for (index in 0 until count) {
|
||||
if (!FfmpegDemuxerJni.nativeStreamInfo(index, numbers, strings)) continue
|
||||
val mime = strings[0] ?: continue
|
||||
val trackType = when (numbers[FfmpegDemuxerJni.INFO_TRACK_TYPE]) {
|
||||
0L -> C.TRACK_TYPE_VIDEO
|
||||
1L -> C.TRACK_TYPE_AUDIO
|
||||
2L -> C.TRACK_TYPE_TEXT
|
||||
else -> continue
|
||||
}
|
||||
|
||||
val builder = Format.Builder()
|
||||
.setId(index.toString())
|
||||
.setSampleMimeType(mime)
|
||||
.setLanguage(strings[1])
|
||||
.setLabel(strings[2])
|
||||
.setSelectionFlags(numbers[FfmpegDemuxerJni.INFO_SELECTION_FLAGS].toInt())
|
||||
.setRoleFlags(numbers[FfmpegDemuxerJni.INFO_ROLE_FLAGS].toInt())
|
||||
.setAverageBitrate(numbers[FfmpegDemuxerJni.INFO_BITRATE].toInt())
|
||||
|
||||
val extradata = FfmpegDemuxerJni.nativeStreamExtradata(index)
|
||||
if (extradata != null) {
|
||||
builder.setInitializationData(listOf(extradata))
|
||||
}
|
||||
|
||||
when (trackType) {
|
||||
C.TRACK_TYPE_VIDEO -> {
|
||||
// A Dolby Vision config record rides the stream as side data; the
|
||||
// codecs string is what DoviConvertingTrackOutput keys on, exactly
|
||||
// as it does for Matroska's CodecPrivate.
|
||||
val doviProfile = numbers[FfmpegDemuxerJni.INFO_DOVI_PROFILE].toInt()
|
||||
Log.i(TAG, "video track $index: doviProfile=$doviProfile mime=$mime")
|
||||
if (doviProfile >= 0) {
|
||||
val doviLevel = numbers[FfmpegDemuxerJni.INFO_DOVI_LEVEL].toInt().coerceAtLeast(0)
|
||||
builder.setCodecs("dvh1.%02d.%02d".format(doviProfile, doviLevel))
|
||||
}
|
||||
val width = numbers[FfmpegDemuxerJni.INFO_WIDTH].toInt()
|
||||
val height = numbers[FfmpegDemuxerJni.INFO_HEIGHT].toInt()
|
||||
builder
|
||||
.setWidth(width)
|
||||
.setHeight(height)
|
||||
.setRotationDegrees(numbers[FfmpegDemuxerJni.INFO_ROTATION].toInt())
|
||||
val parNum = numbers[FfmpegDemuxerJni.INFO_PAR_NUM]
|
||||
val parDen = numbers[FfmpegDemuxerJni.INFO_PAR_DEN]
|
||||
if (parNum > 0 && parDen > 0 && parNum != parDen) {
|
||||
builder.setPixelWidthHeightRatio(parNum.toFloat() / parDen.toFloat())
|
||||
}
|
||||
val fpsNum = numbers[FfmpegDemuxerJni.INFO_FPS_NUM]
|
||||
val fpsDen = numbers[FfmpegDemuxerJni.INFO_FPS_DEN]
|
||||
if (fpsNum > 0 && fpsDen > 0) {
|
||||
builder.setFrameRate(fpsNum.toFloat() / fpsDen.toFloat())
|
||||
}
|
||||
if (primaryVideo < 0) {
|
||||
primaryVideo = index
|
||||
// libass needs the storage size before the first render; the
|
||||
// Matroska path published it from the Tracks element the same way.
|
||||
if (width > 0 && height > 0) assHandler.setVideoSize(width, height)
|
||||
}
|
||||
}
|
||||
C.TRACK_TYPE_AUDIO -> {
|
||||
builder
|
||||
.setSampleRate(numbers[FfmpegDemuxerJni.INFO_SAMPLE_RATE].toInt())
|
||||
.setChannelCount(numbers[FfmpegDemuxerJni.INFO_CHANNELS].toInt())
|
||||
val pcmEncoding = numbers[FfmpegDemuxerJni.INFO_PCM_ENCODING].toInt()
|
||||
if (pcmEncoding >= 0) builder.setPcmEncoding(pcmEncoding)
|
||||
if (primaryAudio < 0) primaryAudio = index
|
||||
bitrateMeters[index] = StreamBitrateMeter()
|
||||
}
|
||||
C.TRACK_TYPE_TEXT -> {
|
||||
val kind = when (mime) {
|
||||
MimeTypes.TEXT_SSA -> SubtitleKind.SSA
|
||||
MimeTypes.APPLICATION_SUBRIP -> SubtitleKind.SUBRIP
|
||||
MimeTypes.TEXT_VTT -> SubtitleKind.VTT
|
||||
else -> SubtitleKind.NONE
|
||||
}
|
||||
subtitleKinds[index] = kind
|
||||
if (kind == SubtitleKind.SSA) {
|
||||
// Embedded ASS reaches libass as per-sample dialogue, never as a
|
||||
// whole file: AssSubtitleParserFactory keys embedded handling off
|
||||
// the Matroska container mime, and AssHeaderParser reads the
|
||||
// header from initializationData[1] — the exact layout media3's
|
||||
// MatroskaExtractor publishes.
|
||||
builder.setContainerMimeType(MimeTypes.VIDEO_MATROSKA)
|
||||
if (extradata != null) {
|
||||
builder.setInitializationData(
|
||||
listOf(FfmpegSubtitleSamples.SSA_DIALOGUE_FORMAT, extradata)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val rawOutput = output.track(index, trackType)
|
||||
val trackOutput = if (trackType == C.TRACK_TYPE_AUDIO && numbers[FfmpegDemuxerJni.INFO_LATM] == 1L) {
|
||||
// LOAS/LATM-framed AAC: unwrap to raw access units; the wrapper
|
||||
// swallows this placeholder Format and emits the real one parsed from
|
||||
// the StreamMuxConfig.
|
||||
LatmTrackOutput(rawOutput, index).also { latmOutputs.add(it) }
|
||||
} else {
|
||||
rawOutput
|
||||
}
|
||||
trackOutput.format(builder.build())
|
||||
trackOutputs[index] = trackOutput
|
||||
}
|
||||
|
||||
primaryStreamIndex = if (primaryVideo >= 0) primaryVideo else primaryAudio
|
||||
primaryStreamIsAudio = primaryVideo < 0 && primaryAudio >= 0
|
||||
synchronized(seekIndexLock) {
|
||||
seekIndexTimes.clear()
|
||||
seekIndexPositions.clear()
|
||||
}
|
||||
output.endTracks()
|
||||
output.seekMap(SeekMapImpl())
|
||||
}
|
||||
|
||||
/** Hands embedded font attachments to libass, under the shared budgets. */
|
||||
private fun deliverFontAttachments() {
|
||||
val count = FfmpegDemuxerJni.nativeAttachmentCount()
|
||||
if (count <= 0) return
|
||||
var acceptedBytes = 0L
|
||||
val meta = arrayOfNulls<String>(2)
|
||||
for (ordinal in 0 until count) {
|
||||
val size = FfmpegDemuxerJni.nativeAttachmentInfo(ordinal, meta)
|
||||
if (size <= 0) continue
|
||||
val name = meta[0] ?: continue
|
||||
val mime = meta[1] ?: continue
|
||||
if (mime !in AssFonts.fontMimeTypes) continue
|
||||
val rejectionReason = AssFonts.rejectionReason(size, acceptedBytes)
|
||||
if (rejectionReason != null) {
|
||||
Log.w(TAG, "Skipping embedded font: $rejectionReason (bytes=$size, accepted=$acceptedBytes)")
|
||||
continue
|
||||
}
|
||||
val data = FfmpegDemuxerJni.nativeAttachmentData(ordinal) ?: continue
|
||||
acceptedBytes += size
|
||||
assHandler.addFont(name, data)
|
||||
}
|
||||
}
|
||||
|
||||
private fun readPacket(input: ExtractorInput, seekPosition: PositionHolder): Int {
|
||||
var reconciles = 0
|
||||
while (true) {
|
||||
val code = FfmpegDemuxerJni.nativeReadPacket(packetBytes, packetOut)
|
||||
when (code) {
|
||||
FfmpegDemuxerJni.CODE_PACKET -> {
|
||||
val streamIndex = packetOut[FfmpegDemuxerJni.OUT_STREAM_INDEX].toInt()
|
||||
val size = packetOut[FfmpegDemuxerJni.OUT_SIZE].toInt()
|
||||
val trackOutput = trackOutputs.getOrNull(streamIndex) ?: continue
|
||||
val ptsUs = packetOut[FfmpegDemuxerJni.OUT_PTS_US]
|
||||
val isKeyframe = packetOut[FfmpegDemuxerJni.OUT_FLAGS] and 1L != 0L
|
||||
val subtitleKind = subtitleKinds.getOrNull(streamIndex) ?: SubtitleKind.NONE
|
||||
if (subtitleKind != SubtitleKind.NONE) {
|
||||
// Text samples carry their duration inside the sample text, in
|
||||
// media3's MatroskaExtractor shape; a sample without a duration
|
||||
// cannot be displayed (same skip media3 performs).
|
||||
val sampleDurationUs = packetOut[FfmpegDemuxerJni.OUT_DURATION_US]
|
||||
if (sampleDurationUs <= 0) {
|
||||
Log.w(TAG, "Skipping subtitle sample with no duration (stream=$streamIndex)")
|
||||
continue
|
||||
}
|
||||
val prefix = when (subtitleKind) {
|
||||
SubtitleKind.SSA -> FfmpegSubtitleSamples.ssaPrefix(sampleDurationUs)
|
||||
SubtitleKind.SUBRIP -> FfmpegSubtitleSamples.subripPrefix(sampleDurationUs)
|
||||
else -> FfmpegSubtitleSamples.vttPrefix(sampleDurationUs)
|
||||
}
|
||||
prefixParsable.reset(prefix, prefix.size)
|
||||
trackOutput.sampleData(prefixParsable, prefix.size)
|
||||
packetParsable.reset(packetBytes, size)
|
||||
trackOutput.sampleData(packetParsable, size)
|
||||
trackOutput.sampleMetadata(
|
||||
ptsUs,
|
||||
C.BUFFER_FLAG_KEY_FRAME,
|
||||
prefix.size + size,
|
||||
/* offset= */
|
||||
0,
|
||||
/* cryptoData= */
|
||||
null
|
||||
)
|
||||
return Extractor.RESULT_CONTINUE
|
||||
}
|
||||
packetParsable.reset(packetBytes, size)
|
||||
trackOutput.sampleData(packetParsable, size)
|
||||
// Native drops packets without any timestamp, so ptsUs is always real.
|
||||
trackOutput.sampleMetadata(
|
||||
ptsUs,
|
||||
if (isKeyframe) C.BUFFER_FLAG_KEY_FRAME else 0,
|
||||
size,
|
||||
/* offset= */
|
||||
0,
|
||||
/* cryptoData= */
|
||||
null
|
||||
)
|
||||
recordSeekPoint(streamIndex, ptsUs, packetOut[FfmpegDemuxerJni.OUT_POSITION], isKeyframe)
|
||||
bitrateMeters.getOrNull(streamIndex)?.onPacket(ptsUs, size)
|
||||
return Extractor.RESULT_CONTINUE
|
||||
}
|
||||
FfmpegDemuxerJni.CODE_EOF -> return Extractor.RESULT_END_OF_INPUT
|
||||
FfmpegDemuxerJni.CODE_NEED_SEEK -> {
|
||||
val target = FfmpegDemuxerJni.nativeConsumePendingSeek()
|
||||
if (target == Long.MIN_VALUE || target < 0) {
|
||||
// Sticky AVIO error replayed without a fresh deferral: resync in
|
||||
// place (bounded by reconciles) instead of killing the stream.
|
||||
if (++reconciles > MAX_RECONCILES || !reSync(input)) {
|
||||
throw malformed("demuxer produced an invalid seek target: $target")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (++reconciles > MAX_RECONCILES) throw malformed("too many demuxer repositions")
|
||||
if (!reconcile(input, seekPosition, target)) return Extractor.RESULT_SEEK
|
||||
}
|
||||
FfmpegDemuxerJni.CODE_GROW -> {
|
||||
val required = packetOut[FfmpegDemuxerJni.OUT_SIZE].toInt()
|
||||
packetBytes = ByteArray(required + 64 * 1024)
|
||||
}
|
||||
FfmpegDemuxerJni.ERR_JAVA ->
|
||||
throw IOException(inputProxy.lastError ?: "demuxer input failed")
|
||||
else -> throw malformed("ffmpeg demuxer read failed: $code")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-establishes the AVIO position at the loader's current input position. */
|
||||
private fun reSync(input: ExtractorInput): Boolean {
|
||||
val position = input.position
|
||||
return position >= 0 && FfmpegDemuxerJni.nativeResumeAfterSeek(position) == 0
|
||||
}
|
||||
|
||||
/** Returns true when the input is already at [target] and native resumed. */
|
||||
private fun reconcile(input: ExtractorInput, seekPosition: PositionHolder, target: Long): Boolean {
|
||||
if (target == input.position) {
|
||||
val code = FfmpegDemuxerJni.nativeResumeAfterSeek(target)
|
||||
if (code != 0) throw malformed("demuxer resume failed: $code")
|
||||
return true
|
||||
}
|
||||
seekPosition.position = target
|
||||
return false
|
||||
}
|
||||
|
||||
private fun recordSeekPoint(streamIndex: Int, timeUs: Long, position: Long, keyframe: Boolean) {
|
||||
if (streamIndex != primaryStreamIndex || position <= 0) return
|
||||
if (!primaryStreamIsAudio && !keyframe) return
|
||||
synchronized(seekIndexLock) {
|
||||
val lastIndex = seekIndexTimes.size - 1
|
||||
if (lastIndex >= 0) {
|
||||
if (timeUs <= seekIndexTimes[lastIndex]) return
|
||||
if (primaryStreamIsAudio && timeUs - seekIndexTimes[lastIndex] < AUDIO_INDEX_INTERVAL_US) {
|
||||
return
|
||||
}
|
||||
}
|
||||
seekIndexTimes.add(timeUs)
|
||||
seekIndexPositions.add(position)
|
||||
}
|
||||
}
|
||||
|
||||
private fun malformed(message: String): ParserException = ParserException.createForMalformedContainer(message, null)
|
||||
|
||||
private inner class SeekMapImpl : SeekMap {
|
||||
// Seeks are executed by the demuxer (avformat_seek_file), so seekability
|
||||
// does not depend on the sample-derived index below — that index only
|
||||
// improves the loader's initial byte guess. The timeline is published
|
||||
// from this value once, at prepare time, when the index is still empty.
|
||||
override fun isSeekable(): Boolean = this@FfmpegExtractor.durationUs != C.TIME_UNSET
|
||||
|
||||
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
|
||||
synchronized(seekIndexLock) {
|
||||
if (seekIndexTimes.isEmpty()) return SeekMap.SeekPoints(SeekPoint(0, 0))
|
||||
val index = seekIndexTimes.binarySearchFloor(timeUs)
|
||||
if (index < 0) return SeekMap.SeekPoints(SeekPoint(seekIndexTimes[0], seekIndexPositions[0]))
|
||||
val preceding = SeekPoint(seekIndexTimes[index], seekIndexPositions[index])
|
||||
if (index + 1 >= seekIndexTimes.size || seekIndexTimes[index] == timeUs) {
|
||||
return SeekMap.SeekPoints(preceding)
|
||||
}
|
||||
val following = SeekPoint(seekIndexTimes[index + 1], seekIndexPositions[index + 1])
|
||||
return SeekMap.SeekPoints(preceding, following)
|
||||
}
|
||||
}
|
||||
|
||||
// Qualified on purpose: bare `durationUs` binds to the inherited Java
|
||||
// getter as a synthetic property (this.getDurationUs()) and recurses.
|
||||
override fun getDurationUs(): Long = this@FfmpegExtractor.durationUs
|
||||
}
|
||||
}
|
||||
|
||||
/** Floor binary search over an ascending list; returns the greatest index with value <= target. */
|
||||
private fun List<Long>.binarySearchFloor(value: Long): Int {
|
||||
var low = 0
|
||||
var high = size - 1
|
||||
var result = -1
|
||||
while (low <= high) {
|
||||
val mid = (low + high) ushr 1
|
||||
if (this[mid] <= value) {
|
||||
result = mid
|
||||
low = mid + 1
|
||||
} else {
|
||||
high = mid - 1
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Builds text subtitle samples in the exact shape media3's MatroskaExtractor
|
||||
* writes, so the same downstream consumers work behind the FFmpeg demuxer:
|
||||
* the bundled SsaParser/SubripParser/WebvttParser (via
|
||||
* SubtitleTranscodingExtractorOutput) and AssTrackOutput's dialogue feed.
|
||||
*
|
||||
* MatroskaExtractor prefixes each raw payload with a synthetic header whose
|
||||
* *second* timecode carries the sample duration (BlockDuration), while the
|
||||
* first stays zero; parsers reconstruct absolute times as sampleTimeUs +
|
||||
* parsedStart. FFmpeg hands us the same raw payloads (an ASS packet is the
|
||||
* MKV block: "ReadOrder,Layer,Style,...,Text"; SubRip/WebVTT packets are the
|
||||
* bare cue text), so only the prefix needs synthesizing.
|
||||
*/
|
||||
internal object FfmpegSubtitleSamples {
|
||||
|
||||
val SSA_DIALOGUE_FORMAT: ByteArray =
|
||||
"Format: Start, End, ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
|
||||
/** `Dialogue: 0:00:00:00,H:MM:SS:CC,` — centiseconds, ':' separator (media3's SSA shape). */
|
||||
fun ssaPrefix(durationUs: Long): ByteArray = "Dialogue: 0:00:00:00,${timecode(durationUs, "%01d:%02d:%02d:%02d", 10_000)},"
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
|
||||
/** `1\n00:00:00,000 --> HH:MM:SS,mmm\n` — a complete SRT cue header. */
|
||||
fun subripPrefix(durationUs: Long): ByteArray = "1\n00:00:00,000 --> ${timecode(durationUs, "%02d:%02d:%02d,%03d", 1_000)}\n"
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
|
||||
/** `WEBVTT\n\n00:00:00.000 --> HH:MM:SS.mmm\n` — a one-cue WebVTT document header. */
|
||||
fun vttPrefix(durationUs: Long): ByteArray = "WEBVTT\n\n00:00:00.000 --> ${timecode(durationUs, "%02d:%02d:%02d.%03d", 1_000)}\n"
|
||||
.toByteArray(Charsets.UTF_8)
|
||||
|
||||
private fun timecode(timeUs: Long, format: String, lastValueDivisor: Long): String {
|
||||
val hours = timeUs / 3_600_000_000L
|
||||
var remainder = timeUs - hours * 3_600_000_000L
|
||||
val minutes = remainder / 60_000_000L
|
||||
remainder -= minutes * 60_000_000L
|
||||
val seconds = remainder / 1_000_000L
|
||||
remainder -= seconds * 1_000_000L
|
||||
val lastValue = remainder / lastValueDivisor
|
||||
return String.format(Locale.US, format, hours, minutes, seconds, lastValue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* The IEC 61937 carrier tuple every packed bitstream rides: 192kHz, 7.1, PCM-16 shaped.
|
||||
*
|
||||
* This is the high-bitrate HDMI shape Kodi uses for both TrueHD/MAT and DTS-HD Master Audio, and
|
||||
* the one [supportsIecCarrier] probes. The 44.1kHz family would need a 176.4kHz sibling, which is
|
||||
* deliberately not built; streams from that family decode instead.
|
||||
*/
|
||||
internal object IecCarrier {
|
||||
const val SAMPLE_RATE = 192_000
|
||||
const val CHANNEL_COUNT = 8
|
||||
const val BYTES_PER_FRAME = CHANNEL_COUNT * 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits one codec's bitstream into access units and packs them into IEC 61937 bursts for
|
||||
* [IecCarrierSink].
|
||||
*
|
||||
* Implementations are not thread safe; the sink drives them from the playback thread only.
|
||||
*/
|
||||
internal interface IecCarrierPacker {
|
||||
|
||||
/**
|
||||
* Length in bytes of the access unit starting at [offset], or 0 when no unit boundary is
|
||||
* recognised there. May latch [unsupportedStream] when the boundary is recognisable but names a
|
||||
* framing this carrier cannot ride.
|
||||
*/
|
||||
fun accessUnitLength(data: ByteArray, offset: Int, limit: Int): Int
|
||||
|
||||
/**
|
||||
* Packs one access unit, returning a completed burst or null when this unit did not finish one.
|
||||
*
|
||||
* Returned buffers are owned by the packer and reused, alternating between two so a burst handed
|
||||
* downstream stays valid while the next one fills. Callers must submit or copy it before the
|
||||
* second following call.
|
||||
*/
|
||||
fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer?
|
||||
|
||||
/**
|
||||
* True when the bitstream announced a shape this carrier cannot ride. The packer emits nothing
|
||||
* in that state; the sink latches the stream onto the decoder instead.
|
||||
*/
|
||||
val unsupportedStream: Boolean
|
||||
|
||||
/** Drops all carrier state. Called on flush/seek: bursts must not straddle a discontinuity. */
|
||||
fun reset()
|
||||
}
|
||||
+106
-65
@@ -16,13 +16,16 @@ import java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Routes Dolby TrueHD through a MAT/IEC 61937 carrier, and everything else through the normal sink
|
||||
* (#1804).
|
||||
* Routes Dolby TrueHD (#1804) and DTS-HD Master Audio (#1988) through an IEC 61937 carrier, and
|
||||
* everything else through the normal sink.
|
||||
*
|
||||
* Android will not bitstream raw TrueHD on the TV routes measured for this issue: the platform
|
||||
* reports `ENCODING_DOLBY_TRUEHD` as offload-only while reporting `ENCODING_IEC61937` at 192kHz/7.1
|
||||
* as bitstream-capable. Kodi models the same split and packs the carrier itself; media3 only ever
|
||||
* hands Android raw TrueHD, at the stream rate. This sink adds the missing path.
|
||||
* Android will not bitstream raw TrueHD on the TV routes measured for #1804: the platform reports
|
||||
* `ENCODING_DOLBY_TRUEHD` as offload-only while reporting `ENCODING_IEC61937` at 192kHz/7.1 as
|
||||
* bitstream-capable. Raw `ENCODING_DTS_HD` is worse on Fire OS: the route advertises it, the
|
||||
* AudioTrack initialises and drains, and the receiver hears silence, because the encoding only
|
||||
* means "basic profile" there (#1988). Kodi models the same split and packs the carrier itself;
|
||||
* media3 only ever hands Android the raw encodings, at the stream rate. This sink adds the
|
||||
* missing path, with one [IecCarrierPacker] per codec.
|
||||
*
|
||||
* **Why two delegates rather than one sink with the processors held inactive.** The carrier is a
|
||||
* bit-exact byte stream that happens to be shaped like PCM. Any sample mutation — downmix, Sonic,
|
||||
@@ -39,7 +42,7 @@ import java.util.concurrent.atomic.AtomicInteger
|
||||
* delegates so either can be activated later; per-stream calls go to the active one alone.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class TrueHdCarrierSink(
|
||||
internal class IecCarrierSink(
|
||||
private val defaultSink: AudioSink,
|
||||
private val carrierSink: AudioSink,
|
||||
/** Whether the current route can bitstream the carrier tuple. Evaluated per format. */
|
||||
@@ -49,39 +52,39 @@ internal class TrueHdCarrierSink(
|
||||
private val log: ((String, String, String) -> Unit)? = null
|
||||
) : AudioSink {
|
||||
|
||||
private companion object {
|
||||
/** One MAT frame is exactly one carrier period: 3840 frames at 192kHz. */
|
||||
const val CARRIER_BURST_DURATION_US =
|
||||
TrueHdMatPacker.MAT_PKT_OFFSET.toLong() / TrueHdMatPacker.CARRIER_BYTES_PER_FRAME *
|
||||
1_000_000L / TrueHdMatPacker.CARRIER_SAMPLE_RATE
|
||||
}
|
||||
private val matPacker = TrueHdMatPacker()
|
||||
private val dtsHdPacker = DtsHdIecPacker()
|
||||
|
||||
private val packer = TrueHdMatPacker()
|
||||
/** The packer for the configured stream; chosen by mime type in [configure]. */
|
||||
private var activePacker: IecCarrierPacker = matPacker
|
||||
|
||||
private var active: AudioSink = defaultSink
|
||||
private var carrierActive = false
|
||||
private var loggedCoreStrip = false
|
||||
|
||||
/** A burst the delegate refused; it must be placed before any further input is consumed. */
|
||||
private var pendingBurst: ByteBuffer? = null
|
||||
private var pendingBurstTimeUs: Long = 0
|
||||
|
||||
/**
|
||||
* Anchor for carrier timestamps, and how many bursts have been emitted since it.
|
||||
* Anchor for carrier timestamps, and how many carrier frames have been emitted since it.
|
||||
*
|
||||
* Each MAT frame is exactly one carrier period of audio, so timestamps are derived from the
|
||||
* cadence rather than from whichever access unit happened to close the frame. Handing the sink
|
||||
* the closing unit's own presentation time drifts against the time it derives from written
|
||||
* frames, which it reports as a discontinuity on nearly every frame.
|
||||
* Every burst is a whole number of carrier frames, so timestamps are derived from the cadence
|
||||
* rather than from whichever access unit happened to close the burst. Handing the sink the
|
||||
* closing unit's own presentation time drifts against the time it derives from written frames,
|
||||
* which it reports as a discontinuity on nearly every burst. Counting frames rather than bursts
|
||||
* keeps the arithmetic exact for burst durations that are not whole microseconds (a DTS-HD
|
||||
* burst is 10666.67us).
|
||||
*/
|
||||
private var carrierAnchorUs: Long = C.TIME_UNSET
|
||||
private var burstsSinceAnchor: Long = 0
|
||||
private var carrierFramesSinceAnchor: Long = 0
|
||||
|
||||
private var playbackParameters: PlaybackParameters = PlaybackParameters.DEFAULT
|
||||
private var sinkListener: AudioSink.Listener? = null
|
||||
|
||||
/**
|
||||
* Latched when a stream's bitstream contradicts the rate its container announced, which selection
|
||||
* was made from.
|
||||
* Latched when a stream's bitstream contradicts the shape its container announced, which
|
||||
* selection was made from.
|
||||
*
|
||||
* Deliberately outlives [flush] and [reset]: media3 resets every renderer disabled by a new
|
||||
* selection before enabling the replacement (ExoPlayerImplInternal.enableRenderers), and both
|
||||
@@ -114,11 +117,11 @@ internal class TrueHdCarrierSink(
|
||||
* [directOutputBlocked] already reports.
|
||||
*
|
||||
* The rate family is decided from the format rather than from the packer, which only learns it
|
||||
* from a major sync once buffers are already flowing — far too late for a selection that happens
|
||||
* before configure.
|
||||
* from the bitstream once buffers are already flowing — far too late for a selection that
|
||||
* happens before configure.
|
||||
*/
|
||||
private fun shouldUseCarrier(format: Format): Boolean {
|
||||
if (format.sampleMimeType != MimeTypes.AUDIO_TRUEHD) return false
|
||||
if (!isTrueHd(format) && !isDtsHd(format)) return false
|
||||
if (mismatchGeneration == mediaGeneration.get()) return false
|
||||
if (!isCarrierRateFamily(format.sampleRate)) return false
|
||||
if (playbackParameters.speed != 1f) return false
|
||||
@@ -136,15 +139,15 @@ internal class TrueHdCarrierSink(
|
||||
private fun carrierFormat(): Format = Format.Builder()
|
||||
.setSampleMimeType(MimeTypes.AUDIO_RAW)
|
||||
.setPcmEncoding(C.ENCODING_PCM_16BIT)
|
||||
.setChannelCount(TrueHdMatPacker.CARRIER_CHANNEL_COUNT)
|
||||
.setSampleRate(TrueHdMatPacker.CARRIER_SAMPLE_RATE)
|
||||
.setChannelCount(IecCarrier.CHANNEL_COUNT)
|
||||
.setSampleRate(IecCarrier.SAMPLE_RATE)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* TrueHD is deliberately binary: the carrier, or decoded PCM. Never media3's own raw TrueHD path.
|
||||
*
|
||||
* That path builds an `ENCODING_DOLBY_TRUEHD` track at the *stream* rate, which is the
|
||||
* configuration this issue is about — one box takes a single write and never advances its
|
||||
* configuration #1804 is about — one box takes a single write and never advances its
|
||||
* playback head, another freezes for ten seconds, and the third declines it and decodes anyway.
|
||||
* Even Kodi's raw fallback is a different thing: it only offers raw TrueHD after verifying it at
|
||||
* 192kHz, which media3 never requests. So when the carrier is unavailable — no IEC route, a speed
|
||||
@@ -153,15 +156,30 @@ internal class TrueHdCarrierSink(
|
||||
*/
|
||||
private fun isTrueHd(format: Format): Boolean = format.sampleMimeType == MimeTypes.AUDIO_TRUEHD
|
||||
|
||||
/**
|
||||
* DTS-HD is binary only while the carrier route exists: the carrier, or decoded PCM. Falling
|
||||
* through to media3's raw `ENCODING_DTS_HD` path on such a route would land on exactly the
|
||||
* silent configuration #1988 is about — the route that advertises the carrier and raw DTS-HD at
|
||||
* once is the one whose raw path renders silence. Without a carrier route the raw path is the
|
||||
* pre-carrier behavior and is left alone: those routes never had the carrier to lose, and some
|
||||
* of them bitstream raw DTS-HD genuinely.
|
||||
*
|
||||
* DTS Express deliberately stays off the carrier: its mime carries a `;profile=lbr` suffix, so
|
||||
* the equality below excludes it and it keeps decoding as before.
|
||||
*/
|
||||
private fun isDtsHd(format: Format): Boolean = format.sampleMimeType == MimeTypes.AUDIO_DTS_HD
|
||||
|
||||
override fun supportsFormat(format: Format): Boolean = when {
|
||||
shouldUseCarrier(format) -> true
|
||||
isTrueHd(format) -> false
|
||||
isDtsHd(format) && carrierRouteAvailable() -> false
|
||||
else -> defaultSink.supportsFormat(format)
|
||||
}
|
||||
|
||||
override fun getFormatSupport(format: Format): Int = when {
|
||||
shouldUseCarrier(format) -> AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY
|
||||
isTrueHd(format) -> AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
isDtsHd(format) && carrierRouteAvailable() -> AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
else -> defaultSink.getFormatSupport(format)
|
||||
}
|
||||
|
||||
@@ -173,16 +191,18 @@ internal class TrueHdCarrierSink(
|
||||
"info",
|
||||
"audio",
|
||||
if (useCarrier) {
|
||||
"TrueHD via MAT/IEC 61937 carrier at ${TrueHdMatPacker.CARRIER_SAMPLE_RATE}Hz/" +
|
||||
"${TrueHdMatPacker.CARRIER_CHANNEL_COUNT}ch"
|
||||
"${carrierCodecName(inputFormat)} via IEC 61937 carrier at ${IecCarrier.SAMPLE_RATE}Hz/" +
|
||||
"${IecCarrier.CHANNEL_COUNT}ch"
|
||||
} else {
|
||||
"Leaving the MAT carrier; audio returns to the normal sink"
|
||||
"Leaving the IEC 61937 carrier; audio returns to the normal sink"
|
||||
}
|
||||
)
|
||||
}
|
||||
carrierActive = useCarrier
|
||||
configuredGeneration = mediaGeneration.get()
|
||||
activePacker = if (isDtsHd(inputFormat)) dtsHdPacker else matPacker
|
||||
active = if (useCarrier) carrierSink else defaultSink
|
||||
loggedCoreStrip = false
|
||||
discardCarrierState()
|
||||
|
||||
if (useCarrier) {
|
||||
@@ -197,6 +217,8 @@ internal class TrueHdCarrierSink(
|
||||
}
|
||||
}
|
||||
|
||||
private fun carrierCodecName(format: Format): String = if (isDtsHd(format)) "DTS-HD" else "TrueHD (MAT)"
|
||||
|
||||
override fun handleBuffer(buffer: ByteBuffer, presentationTimeUs: Long, encodedAccessUnitCount: Int): Boolean {
|
||||
if (!carrierActive) return defaultSink.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
|
||||
|
||||
@@ -217,37 +239,30 @@ internal class TrueHdCarrierSink(
|
||||
|
||||
var offset = 0
|
||||
while (offset < remaining.size) {
|
||||
val length = TrueHdMatPacker.accessUnitLength(remaining, offset, remaining.size)
|
||||
val length = activePacker.accessUnitLength(remaining, offset, remaining.size)
|
||||
if (activePacker.unsupportedStream) return latchMismatch()
|
||||
if (length == 0) {
|
||||
// Not a unit boundary we recognise. Consuming the tail keeps the stream moving; trying to
|
||||
// resynchronise mid-carrier would splice a frame.
|
||||
buffer.position(buffer.limit())
|
||||
return true
|
||||
}
|
||||
val burst = packer.packAccessUnit(remaining, offset, length)
|
||||
if (packer.unsupportedRateFamily) {
|
||||
// Selection is made from Format.sampleRate, so the bitstream disagrees with its container.
|
||||
// The packer emits nothing in that state; consuming here would turn the stream into
|
||||
// silence. Leave this unit in the buffer, latch the carrier off, and ask for reselection so
|
||||
// the decoder takes over and receives it.
|
||||
if (mismatchGeneration != configuredGeneration) {
|
||||
mismatchGeneration = configuredGeneration
|
||||
log?.invoke(
|
||||
"warn",
|
||||
"audio",
|
||||
"TrueHD bitstream announced a 44.1kHz-family rate its container did not; " +
|
||||
"leaving the carrier so it decodes"
|
||||
)
|
||||
sinkListener?.onAudioCapabilitiesChanged()
|
||||
}
|
||||
return false
|
||||
}
|
||||
val burst = activePacker.packAccessUnit(remaining, offset, length)
|
||||
if (activePacker.unsupportedStream) return latchMismatch()
|
||||
offset += length
|
||||
buffer.position(buffer.position() + length)
|
||||
if (burst == null) continue
|
||||
if (activePacker === dtsHdPacker && dtsHdPacker.strippedToCore && !loggedCoreStrip) {
|
||||
loggedCoreStrip = true
|
||||
log?.invoke(
|
||||
"warn",
|
||||
"audio",
|
||||
"DTS-HD MA bitrate exceeds the IEC 61937 carrier; sending the DTS core substream for ~60s"
|
||||
)
|
||||
}
|
||||
|
||||
val burstTimeUs = carrierAnchorUs + burstsSinceAnchor * CARRIER_BURST_DURATION_US
|
||||
burstsSinceAnchor++
|
||||
val burstTimeUs = carrierAnchorUs + carrierFramesSinceAnchor * 1_000_000L / IecCarrier.SAMPLE_RATE
|
||||
carrierFramesSinceAnchor += burst.remaining().toLong() / IecCarrier.BYTES_PER_FRAME
|
||||
if (!carrierSink.handleBuffer(burst, burstTimeUs, 1)) {
|
||||
pendingBurst = burst
|
||||
pendingBurstTimeUs = burstTimeUs
|
||||
@@ -257,10 +272,35 @@ internal class TrueHdCarrierSink(
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* The bitstream announced a shape the carrier cannot ride, which selection could not see in the
|
||||
* container's Format. The packer emits nothing in that state; consuming here would turn the
|
||||
* stream into silence. Leave the unit in the buffer, latch the carrier off, and ask for
|
||||
* reselection so the decoder takes over and receives it.
|
||||
*/
|
||||
private fun latchMismatch(): Boolean {
|
||||
if (mismatchGeneration != configuredGeneration) {
|
||||
mismatchGeneration = configuredGeneration
|
||||
log?.invoke(
|
||||
"warn",
|
||||
"audio",
|
||||
if (activePacker === dtsHdPacker) {
|
||||
"DTS-HD bitstream cannot ride the 192kHz carrier (44.1kHz-family core or non-standard framing); " +
|
||||
"leaving the carrier so it decodes"
|
||||
} else {
|
||||
"TrueHD bitstream announced a 44.1kHz-family rate its container did not; " +
|
||||
"leaving the carrier so it decodes"
|
||||
}
|
||||
)
|
||||
sinkListener?.onAudioCapabilitiesChanged()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun getCurrentPositionUs(sourceEnded: Boolean): Long = active.getCurrentPositionUs(sourceEnded)
|
||||
|
||||
override fun playToEndOfStream() {
|
||||
// A partially filled MAT frame cannot be emitted; up to 20ms is dropped at the end of a stream.
|
||||
// A partially filled burst cannot be emitted; up to one burst is dropped at the end of a stream.
|
||||
active.playToEndOfStream()
|
||||
}
|
||||
|
||||
@@ -285,11 +325,12 @@ internal class TrueHdCarrierSink(
|
||||
override fun getAudioTrackBufferSizeUs(): Long = active.getAudioTrackBufferSizeUs()
|
||||
|
||||
private fun discardCarrierState() {
|
||||
packer.reset()
|
||||
matPacker.reset()
|
||||
dtsHdPacker.reset()
|
||||
pendingBurst = null
|
||||
// Re-anchor on the next burst: after a seek the carrier restarts from a new media time.
|
||||
carrierAnchorUs = C.TIME_UNSET
|
||||
burstsSinceAnchor = 0
|
||||
carrierFramesSinceAnchor = 0
|
||||
}
|
||||
|
||||
// --- Persistent state: mirrored, so either delegate can be activated later ---
|
||||
@@ -321,23 +362,23 @@ internal class TrueHdCarrierSink(
|
||||
if (isUnitSpeed) playbackParameters else PlaybackParameters.DEFAULT
|
||||
)
|
||||
|
||||
// Crossing 1x changes whether TrueHD may ride the carrier, but nothing re-asks on its own:
|
||||
// the renderer only consults the sink when capabilities are invalidated. Rebuilding the track
|
||||
// selector parameters is not enough either — DefaultTrackSelector skips invalidation when the
|
||||
// rebuilt parameters compare equal. This is the path media3 itself uses for a route change,
|
||||
// and it reaches onRendererCapabilitiesChanged, so the format is re-evaluated and TrueHD moves
|
||||
// between the carrier and the decoder.
|
||||
// Crossing 1x changes whether a bitstream may ride the carrier, but nothing re-asks on its
|
||||
// own: the renderer only consults the sink when capabilities are invalidated. Rebuilding the
|
||||
// track selector parameters is not enough either — DefaultTrackSelector skips invalidation
|
||||
// when the rebuilt parameters compare equal. This is the path media3 itself uses for a route
|
||||
// change, and it reaches onRendererCapabilitiesChanged, so the format is re-evaluated and the
|
||||
// stream moves between the carrier and the decoder.
|
||||
if (wasUnitSpeed != isUnitSpeed && (carrierActive || isUnitSpeed)) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"audio",
|
||||
"Playback speed ${if (isUnitSpeed) "returned to" else "left"} 1.0x; re-evaluating the TrueHD carrier"
|
||||
"Playback speed ${if (isUnitSpeed) "returned to" else "left"} 1.0x; re-evaluating the bitstream carrier"
|
||||
)
|
||||
sinkListener?.onAudioCapabilitiesChanged()
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether TrueHD is currently riding the carrier. Read by the core when speed changes. */
|
||||
/** Whether the configured stream is currently riding the carrier. */
|
||||
val isCarrierActive: Boolean
|
||||
get() = carrierActive
|
||||
|
||||
@@ -345,7 +386,7 @@ internal class TrueHdCarrierSink(
|
||||
* While the carrier is live the delegate is deliberately pinned to 1x, but the player polls this
|
||||
* through the media clock and adopts whatever it reads. Reporting the delegate's value would push
|
||||
* the pinned 1x back and silently undo the user's speed change, so the requested parameters are
|
||||
* reported instead; the reselection triggered above then moves TrueHD onto the decoder, which
|
||||
* reported instead; the reselection triggered above then moves the stream onto the decoder, which
|
||||
* really can apply them.
|
||||
*/
|
||||
override fun getPlaybackParameters(): PlaybackParameters = if (carrierActive) playbackParameters else active.getPlaybackParameters()
|
||||
@@ -407,7 +448,7 @@ internal class TrueHdCarrierSink(
|
||||
|
||||
/**
|
||||
* Called by the owner immediately before a new media item is set, which is the only point where
|
||||
* "this stream lied about its rate" stops being true and the carrier can be offered again.
|
||||
* "this stream lied about its shape" stops being true and the carrier can be offered again.
|
||||
*/
|
||||
fun beginMediaItem() {
|
||||
mediaGeneration.incrementAndGet()
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
|
||||
/** MKV CodecID for Microsoft ACM compatibility mode. */
|
||||
private const val CODEC_ID_ACM = "A_MS/ACM"
|
||||
|
||||
/**
|
||||
* MatroskaExtractor.init is final and extractorOutput private; subclasses swap
|
||||
* in wrapping outputs via reflection once the Segment element starts (shared
|
||||
* with ZlibMatroskaExtractor).
|
||||
*/
|
||||
internal val matroskaExtractorOutputField by lazy {
|
||||
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
|
||||
/** WAVEFORMATEX format tag for LOAS/LATM-wrapped AAC (WAVE_FORMAT_MPEG_LOAS). */
|
||||
private const val WAVE_FORMAT_MPEG_LOAS = 0x1602
|
||||
|
||||
/**
|
||||
* Returns whether a track is LOAS/LATM AAC muxed as A_MS/ACM — ffmpeg's
|
||||
* fallback mapping for aac_latm, which Matroska has no native codec ID for.
|
||||
* The WAVEFORMATEX wFormatTag is the first 2 bytes (LE) of CodecPrivate.
|
||||
*/
|
||||
fun isLoasAcmTrack(codecId: String?, codecPrivate: ByteArray?): Boolean = codecId == CODEC_ID_ACM &&
|
||||
codecPrivate != null &&
|
||||
codecPrivate.size >= 2 &&
|
||||
((codecPrivate[0].toInt() and 0xFF) or ((codecPrivate[1].toInt() and 0xFF) shl 8)) == WAVE_FORMAT_MPEG_LOAS
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps marked tracks with [LatmTrackOutput].
|
||||
* Call [markNextTrackLatm] before the parent extractor creates the track
|
||||
* (i.e. before super.endMasterElement(ID_TRACK_ENTRY)).
|
||||
*/
|
||||
class LatmExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
private var nextTrackIsLatm = false
|
||||
private val latmOutputs = mutableListOf<LatmTrackOutput>()
|
||||
|
||||
fun markNextTrackLatm() {
|
||||
nextTrackIsLatm = true
|
||||
}
|
||||
|
||||
/** Resets LATM parser state after an extractor seek. */
|
||||
fun resetTracks() {
|
||||
latmOutputs.forEach { it.reset() }
|
||||
}
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (!nextTrackIsLatm) return original
|
||||
nextTrackIsLatm = false
|
||||
return LatmTrackOutput(original, id).also { latmOutputs.add(it) }
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.PositionHolder
|
||||
|
||||
/**
|
||||
* Delegates everything to [delegate] but hands it a wrapped [ExtractorOutput].
|
||||
* Used to compose the text pipeline (libass dialogue feed + subtitle cue
|
||||
* transcoding) around media3's raw-subtitle MatroskaExtractor without
|
||||
* subclassing or reflection.
|
||||
*/
|
||||
@UnstableApi
|
||||
internal class OutputWrappingExtractor(
|
||||
private val delegate: Extractor,
|
||||
private val wrap: (ExtractorOutput) -> ExtractorOutput
|
||||
) : Extractor {
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) = delegate.init(wrap(output))
|
||||
|
||||
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int = delegate.read(input, seekPosition)
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) = delegate.seek(position, timeUs)
|
||||
|
||||
override fun release() = delegate.release()
|
||||
|
||||
override fun getUnderlyingImplementation(): Extractor = delegate.underlyingImplementation
|
||||
}
|
||||
@@ -151,14 +151,14 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
)
|
||||
}
|
||||
|
||||
private var trueHdCarrierSink: TrueHdCarrierSink? = null
|
||||
private var iecCarrierSink: IecCarrierSink? = null
|
||||
|
||||
/**
|
||||
* Clears per-stream carrier state that must survive renderer resets but not a new media item.
|
||||
* Call before setting a new source; see [TrueHdCarrierSink.beginMediaItem].
|
||||
* Call before setting a new source; see [IecCarrierSink.beginMediaItem].
|
||||
*/
|
||||
fun beginMediaItem() {
|
||||
trueHdCarrierSink?.beginMediaItem()
|
||||
iecCarrierSink?.beginMediaItem()
|
||||
}
|
||||
|
||||
override fun buildAudioSink(
|
||||
@@ -204,17 +204,17 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
audioDiagnosticsLogger
|
||||
)
|
||||
|
||||
return TrueHdCarrierSink(
|
||||
return IecCarrierSink(
|
||||
defaultSink = processedSink,
|
||||
carrierSink = buildCarrierSink(context, bufferSizeProvider),
|
||||
carrierRouteAvailable = { supportsTrueHdMatCarrier() },
|
||||
carrierRouteAvailable = { supportsIecCarrier(context) },
|
||||
directOutputBlocked = { format -> shouldBlockDirectAudioOutput?.invoke(format) == true },
|
||||
log = audioDiagnosticsLogger
|
||||
).also { trueHdCarrierSink = it }
|
||||
).also { iecCarrierSink = it }
|
||||
}
|
||||
|
||||
/**
|
||||
* The delegate that carries packed TrueHD (#1804).
|
||||
* The delegate that carries packed TrueHD and DTS-HD (#1804, #1988).
|
||||
*
|
||||
* Deliberately separate from the processed sink, and deliberately barren: an empty
|
||||
* [DefaultAudioSink.AudioProcessorChain] means no downmix, no Sonic, no silence skipping and no
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
/**
|
||||
* Rolling average bitrate of one demuxed stream, measured from packet sizes
|
||||
* over their presentation-time span — the same source of truth mpv uses for
|
||||
* its `audio-bitrate` property. It exists because containers frequently
|
||||
* declare no per-track bitrate (Matroska without BPS statistics tags), which
|
||||
* left the performance overlay with nothing to show (#2063).
|
||||
*
|
||||
* Fed from the loader thread ([onPacket]) and read from the stats path
|
||||
* ([bitrateBps]); both are synchronized. The measurement follows the demux
|
||||
* position, which runs ahead of the playhead by the buffered duration —
|
||||
* acceptable for a diagnostics overlay.
|
||||
*/
|
||||
internal class StreamBitrateMeter(private val windowUs: Long = DEFAULT_WINDOW_US) {
|
||||
|
||||
private val ptsUsQueue = ArrayDeque<Long>()
|
||||
private val sizeQueue = ArrayDeque<Int>()
|
||||
private var windowBytes = 0L
|
||||
|
||||
@Synchronized
|
||||
fun onPacket(ptsUs: Long, sizeBytes: Int) {
|
||||
if (sizeBytes <= 0) return
|
||||
// A backwards pts jump is a seek; packets on either side of it do not
|
||||
// form a contiguous span, so the window restarts.
|
||||
val last = ptsUsQueue.lastOrNull()
|
||||
if (last != null && ptsUs < last) reset()
|
||||
ptsUsQueue.addLast(ptsUs)
|
||||
sizeQueue.addLast(sizeBytes)
|
||||
windowBytes += sizeBytes
|
||||
while (ptsUsQueue.size > 1 && ptsUsQueue.last() - ptsUsQueue.first() > windowUs) {
|
||||
ptsUsQueue.removeFirst()
|
||||
windowBytes -= sizeQueue.removeFirst()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Average bitrate in bits per second over the current window, or null until
|
||||
* enough packets span a measurable interval.
|
||||
*/
|
||||
@Synchronized
|
||||
fun bitrateBps(): Int? {
|
||||
if (ptsUsQueue.size < MIN_PACKETS) return null
|
||||
val spanUs = ptsUsQueue.last() - ptsUsQueue.first()
|
||||
if (spanUs <= 0) return null
|
||||
// The pts span covers the durations of every packet except the last one,
|
||||
// whose bytes are therefore excluded — a constant-rate stream measures
|
||||
// exactly its rate.
|
||||
val bytes = windowBytes - sizeQueue.last()
|
||||
if (bytes <= 0) return null
|
||||
return (bytes * 8_000_000L / spanUs).toInt()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun reset() {
|
||||
ptsUsQueue.clear()
|
||||
sizeQueue.clear()
|
||||
windowBytes = 0L
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val DEFAULT_WINDOW_US = 10_000_000L
|
||||
private const val MIN_PACKETS = 16
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ import java.nio.ByteBuffer
|
||||
*
|
||||
* Not thread safe; the sink drives it from the playback thread only.
|
||||
*/
|
||||
internal class TrueHdMatPacker {
|
||||
internal class TrueHdMatPacker : IecCarrierPacker {
|
||||
|
||||
internal companion object {
|
||||
/** Payload bytes in one MAT frame. */
|
||||
@@ -33,11 +33,6 @@ internal class TrueHdMatPacker {
|
||||
/** Bytes from the start of one burst to the next, including preamble and trailing gap. */
|
||||
const val MAT_PKT_OFFSET = 61440
|
||||
|
||||
/** Carrier the packed stream must be played at. */
|
||||
const val CARRIER_SAMPLE_RATE = 192_000
|
||||
const val CARRIER_CHANNEL_COUNT = 8
|
||||
const val CARRIER_BYTES_PER_FRAME = CARRIER_CHANNEL_COUNT * 2
|
||||
|
||||
private const val BURST_HEADER_SIZE = 8
|
||||
private const val SYNCWORD1 = 0xF872
|
||||
private const val SYNCWORD2 = 0x4E1F
|
||||
@@ -99,7 +94,7 @@ internal class TrueHdMatPacker {
|
||||
private var samplesPerFrame = 0
|
||||
|
||||
/** Drops all carrier state. Call on flush/seek: MAT frames must not straddle a discontinuity. */
|
||||
fun reset() {
|
||||
override fun reset() {
|
||||
matBufferIndex = 0
|
||||
matBufferFilled = 0
|
||||
previousTiming = 0
|
||||
@@ -107,7 +102,7 @@ internal class TrueHdMatPacker {
|
||||
samplesPerFrame = 0
|
||||
// The family is re-learned from the next major sync. Leaving it latched here would make every
|
||||
// later stream on this packer emit nothing.
|
||||
unsupportedRateFamily = false
|
||||
unsupportedStream = false
|
||||
java.util.Arrays.fill(matBuffers[0], 0)
|
||||
java.util.Arrays.fill(matBuffers[1], 0)
|
||||
}
|
||||
@@ -119,9 +114,11 @@ internal class TrueHdMatPacker {
|
||||
* whole path is built around. Rather than carry a second carrier configuration for a combination
|
||||
* that is essentially absent from real media, the sink reads this and falls back to decoding.
|
||||
*/
|
||||
var unsupportedRateFamily: Boolean = false
|
||||
override var unsupportedStream: Boolean = false
|
||||
private set
|
||||
|
||||
override fun accessUnitLength(data: ByteArray, offset: Int, limit: Int): Int = Companion.accessUnitLength(data, offset, limit)
|
||||
|
||||
/**
|
||||
* Packs one access unit, returning a completed burst when this unit finished a MAT frame.
|
||||
*
|
||||
@@ -137,7 +134,7 @@ internal class TrueHdMatPacker {
|
||||
* At most one burst can complete per access unit: padding is bounded below half a MAT frame and
|
||||
* an access unit is far smaller, so a single unit cannot span two frame boundaries.
|
||||
*/
|
||||
fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer? {
|
||||
override fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer? {
|
||||
if (length < MIN_ACCESS_UNIT_LENGTH) return null
|
||||
|
||||
if (hasMajorSync(data, offset, offset + length)) {
|
||||
@@ -148,11 +145,11 @@ internal class TrueHdMatPacker {
|
||||
else -> return null
|
||||
}
|
||||
// Bit 3 selects the 44.1kHz family, which rides a 176.4kHz carrier we do not build.
|
||||
unsupportedRateFamily = (rateBits and 8) != 0
|
||||
if (unsupportedRateFamily) return null
|
||||
unsupportedStream = (rateBits and 8) != 0
|
||||
if (unsupportedStream) return null
|
||||
samplesPerFrame = 40 shl (rateBits and 3)
|
||||
}
|
||||
if (unsupportedRateFamily || samplesPerFrame == 0) return null
|
||||
if (unsupportedStream || samplesPerFrame == 0) return null
|
||||
|
||||
val inputTiming = ((data[offset + 2].toInt() and 0xFF) shl 8) or (data[offset + 3].toInt() and 0xFF)
|
||||
var paddingRemaining = 0
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.ParserException
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.util.zip.DataFormatException
|
||||
import java.util.zip.Inflater
|
||||
|
||||
/**
|
||||
* TrackOutput wrapper that inflates zlib-compressed sample data (MKV ContentCompAlgo 0).
|
||||
* Each MKV block is independently zlib-compressed; this wrapper decompresses per-sample
|
||||
* between sampleData() and sampleMetadata() calls.
|
||||
*
|
||||
* All buffers are reused across samples to minimize GC pressure on the hot path.
|
||||
*/
|
||||
class ZlibInflatingTrackOutput(
|
||||
delegate: TrackOutput
|
||||
) : BufferedTransformingTrackOutput(
|
||||
delegate,
|
||||
INITIAL_BUFFER_SIZE,
|
||||
INFLATE_CHUNK,
|
||||
MAX_COMPRESSED_SAMPLE_SIZE
|
||||
) {
|
||||
|
||||
companion object {
|
||||
private const val INITIAL_BUFFER_SIZE = 256 * 1024
|
||||
private const val INFLATE_CHUNK = 64 * 1024
|
||||
private const val MAX_COMPRESSED_SAMPLE_SIZE = 16 * 1024 * 1024
|
||||
private const val MAX_INFLATED_SAMPLE_SIZE = 16 * 1024 * 1024
|
||||
private const val MAX_COMPRESSION_RATIO = 1024L
|
||||
private const val MIN_RATIO_ALLOWANCE = 1024L * 1024
|
||||
}
|
||||
|
||||
var active = false
|
||||
|
||||
private val inflater = Inflater()
|
||||
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private val overflowProbe = ByteArray(1)
|
||||
|
||||
override val transformEnabled: Boolean
|
||||
get() = active
|
||||
|
||||
override val transformedBuffer: ByteArray
|
||||
get() = inflateBuf
|
||||
|
||||
override fun transformSample(inputLength: Int, flags: Int): Int {
|
||||
inflater.reset()
|
||||
inflater.setInput(inputBuffer, 0, inputLength)
|
||||
var written = 0
|
||||
val ratioBound = maxOf(MIN_RATIO_ALLOWANCE, inputLength.toLong() * MAX_COMPRESSION_RATIO)
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
if (written == inflateBuf.size) {
|
||||
if (inflateBuf.size < MAX_INFLATED_SAMPLE_SIZE) {
|
||||
val nextSize = minOf(MAX_INFLATED_SAMPLE_SIZE, inflateBuf.size * 2)
|
||||
inflateBuf = inflateBuf.copyOf(nextSize)
|
||||
} else {
|
||||
val overflow = inflater.inflate(overflowProbe, 0, 1)
|
||||
if (overflow > 0) {
|
||||
throw malformed("Inflated sample exceeds the maximum size")
|
||||
}
|
||||
if (inflater.finished()) return written
|
||||
throw stalledInflate()
|
||||
}
|
||||
}
|
||||
|
||||
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
|
||||
written += count
|
||||
if (written.toLong() > ratioBound) {
|
||||
throw malformed("Inflated sample exceeds the maximum compression ratio")
|
||||
}
|
||||
if (inflater.finished()) return written
|
||||
if (count == 0) throw stalledInflate()
|
||||
}
|
||||
} catch (_: DataFormatException) {
|
||||
// Preserve playback for corrupt subtitle blocks; the raw sample remains bounded
|
||||
// by MAX_COMPRESSED_SAMPLE_SIZE and matches the pre-hardening fallback.
|
||||
if (inflateBuf.size < inputLength) inflateBuf = inflateBuf.copyOf(inputLength)
|
||||
inputBuffer.copyInto(inflateBuf, endIndex = inputLength)
|
||||
return inputLength
|
||||
}
|
||||
}
|
||||
|
||||
private fun stalledInflate(): ParserException = when {
|
||||
inflater.needsDictionary() -> malformed("Zlib-compressed sample requires a dictionary")
|
||||
inflater.needsInput() -> malformed("Truncated zlib-compressed sample")
|
||||
else -> malformed("Zlib decompressor made no progress")
|
||||
}
|
||||
|
||||
private fun malformed(message: String, cause: Throwable? = null): ParserException = ParserException.createForMalformedContainer(message, cause)
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
|
||||
|
||||
/**
|
||||
* Extends AssMatroskaExtractor to add support for MKV quirks media3 rejects:
|
||||
*
|
||||
* ContentCompAlgo 0 (zlib) — media3 only supports ContentCompAlgo 3 (header
|
||||
* stripping). This subclass intercepts the compression algorithm during track
|
||||
* header parsing:
|
||||
* - Tells the parent it's header stripping (algo 3) to avoid the ParserException
|
||||
* - Wraps TrackOutputs with ZlibInflatingTrackOutput to decompress per-sample data
|
||||
* - Skips ContentCompSettings for zlib tracks (not applicable)
|
||||
*
|
||||
* LOAS/LATM AAC as A_MS/ACM — media3 sets audio/x-unknown for non-PCM ACM
|
||||
* tracks (silent playback). Detected tracks are wrapped with LatmTrackOutput,
|
||||
* which unwraps LOAS frames to raw AAC for direct-playing Matroska files.
|
||||
*/
|
||||
class ZlibMatroskaExtractor(
|
||||
subtitleParserFactory: SubtitleParser.Factory,
|
||||
assHandler: AssHandler
|
||||
) : AssMatroskaExtractor(subtitleParserFactory, assHandler) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ZlibMkvExtractor"
|
||||
|
||||
// Matroska EBML element IDs
|
||||
private const val ID_SEGMENT = 0x18538067
|
||||
private const val ID_TRACK_ENTRY = 0xAE
|
||||
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
|
||||
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
|
||||
}
|
||||
|
||||
private var zlibOutput: ZlibExtractorOutputWrapper? = null
|
||||
private var latmOutput: LatmExtractorOutputWrapper? = null
|
||||
private var currentTrackUsesZlib = false
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
|
||||
// After super installs AssSubtitleExtractorOutput, wrap it with our zlib +
|
||||
// LATM layers (zlib outermost so inflation runs before LATM parsing).
|
||||
if (id == ID_SEGMENT && zlibOutput == null) {
|
||||
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
|
||||
val latmWrapper = LatmExtractorOutputWrapper(currentOutput)
|
||||
latmOutput = latmWrapper
|
||||
val wrapper = ZlibExtractorOutputWrapper(latmWrapper)
|
||||
zlibOutput = wrapper
|
||||
matroskaExtractorOutputField.set(this, wrapper)
|
||||
Log.d(TAG, "Installed zlib+LATM ExtractorOutput wrapper")
|
||||
}
|
||||
}
|
||||
|
||||
override fun integerElement(id: Int, value: Long) {
|
||||
if (id == ID_CONTENT_COMPRESSION_ALGORITHM && value == 0L) {
|
||||
currentTrackUsesZlib = true
|
||||
Log.i(TAG, "Track uses ContentCompAlgo 0 (zlib), will inflate samples")
|
||||
// Tell parent it's header stripping (algo 3) to avoid ParserException
|
||||
super.integerElement(id, 3)
|
||||
return
|
||||
}
|
||||
super.integerElement(id, value)
|
||||
}
|
||||
|
||||
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
|
||||
if (id == ID_CONTENT_COMPRESSION_SETTINGS && currentTrackUsesZlib) {
|
||||
// Skip ContentCompSettings for zlib tracks — parent would store these as
|
||||
// sampleStrippedBytes and prepend them to every sample, corrupting output.
|
||||
input.skipFully(contentSize)
|
||||
return
|
||||
}
|
||||
super.binaryElement(id, contentSize, input)
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
if (id == ID_TRACK_ENTRY) {
|
||||
// Must mark before super — the track output is created inside super's
|
||||
// endMasterElement, and the x-unknown format must never reach the queue.
|
||||
val track = getCurrentTrack(id)
|
||||
if (isLoasAcmTrack(track.codecId, track.codecPrivate)) {
|
||||
Log.i(TAG, "Track ${track.number} is LOAS/LATM AAC, unwrapping to raw AAC")
|
||||
latmOutput?.markNextTrackLatm()
|
||||
}
|
||||
}
|
||||
|
||||
val wasZlib = currentTrackUsesZlib
|
||||
super.endMasterElement(id)
|
||||
|
||||
if (id == ID_TRACK_ENTRY && wasZlib) {
|
||||
zlibOutput?.activateLast()
|
||||
currentTrackUsesZlib = false
|
||||
Log.i(TAG, "Activated zlib inflation for track")
|
||||
}
|
||||
}
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
latmOutput?.resetTracks()
|
||||
zlibOutput?.resetTracks()
|
||||
super.seek(position, timeUs)
|
||||
}
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
|
||||
* Tracks are created inactive; activateLast() enables inflation for the most recently
|
||||
* created track (called when we know a track uses zlib compression).
|
||||
*/
|
||||
private class ZlibExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
private var lastCreatedWrapper: ZlibInflatingTrackOutput? = null
|
||||
private val trackOutputs = mutableListOf<ZlibInflatingTrackOutput>()
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
return ZlibInflatingTrackOutput(original).also {
|
||||
trackOutputs.add(it)
|
||||
lastCreatedWrapper = it
|
||||
}
|
||||
}
|
||||
|
||||
fun activateLast() {
|
||||
lastCreatedWrapper?.active = true
|
||||
}
|
||||
|
||||
fun resetTracks() {
|
||||
trackOutputs.forEach { it.resetBufferedData() }
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
}
|
||||
@@ -39,20 +39,48 @@ import kotlinx.coroutines.sync.withLock
|
||||
class MpvPlayerCore private constructor(
|
||||
private val context: Context,
|
||||
private val audioOnly: Boolean,
|
||||
private val hardwareDecoding: Boolean,
|
||||
private val propertyWriterOverride: (suspend (String, String) -> Unit)?,
|
||||
initializedForTesting: Boolean
|
||||
) : SurfaceHolder.Callback,
|
||||
SurfacePlayerCore {
|
||||
constructor(context: Context, audioOnly: Boolean = false) : this(context, audioOnly, null, false)
|
||||
constructor(
|
||||
context: Context,
|
||||
audioOnly: Boolean = false,
|
||||
hardwareDecoding: Boolean = true
|
||||
) : this(context, audioOnly, hardwareDecoding, null, false)
|
||||
|
||||
internal constructor(
|
||||
context: Context,
|
||||
audioOnly: Boolean,
|
||||
propertyWriter: (suspend (String, String) -> Unit)?
|
||||
) : this(context, audioOnly, propertyWriter, true)
|
||||
) : this(context, audioOnly, true, propertyWriter, true)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MpvPlayerCore"
|
||||
|
||||
/**
|
||||
* The initial `vo` chain, decided by whether this session will hardware-
|
||||
* decode.
|
||||
*
|
||||
* gpu-next (libplacebo) is the only Android path that applies Dolby Vision
|
||||
* RPU reshaping (#1902), but reshaping only ever happens under software
|
||||
* decode: FFmpeg's mediacodec wrapper exports no DOVI side data, so a
|
||||
* hardware-decoded stream renders the untouched base layer on any VO.
|
||||
* Hardware decode is also where gpu-next breaks: it samples the decoder
|
||||
* output as a samplerExternalOES that libplacebo declares in both shader
|
||||
* stages, and the Tegra GLES linker rejects that pair ("struct type
|
||||
* mismatch between shaders for uniform"), failing every frame — a solid
|
||||
* blue screen with audio on the Shield (#2010). The in-chain gpu fallback
|
||||
* cannot catch it because gpu-next initializes fine and only fails
|
||||
* per-frame renders.
|
||||
*
|
||||
* So gpu-next is offered exactly where it can help — sessions that will
|
||||
* software-decode — and hardware sessions keep the legacy gpu VO. A
|
||||
* mid-session hwdec fallback to software stays on vo=gpu, which renders
|
||||
* software frames correctly (the pre-2.15.0 behavior for every session).
|
||||
*/
|
||||
internal fun initialVideoOutput(hardwareDecoding: Boolean): String = if (hardwareDecoding) "gpu" else "gpu-next,gpu"
|
||||
}
|
||||
|
||||
/** Video-only paths. The plugin always constructs video cores with the
|
||||
@@ -293,10 +321,12 @@ class MpvPlayerCore private constructor(
|
||||
setOption("audio-display", "no")
|
||||
setOption("gapless-audio", "weak")
|
||||
} else {
|
||||
setOption("vo", "gpu")
|
||||
// vo choice is decode-path-dependent; rationale on
|
||||
// initialVideoOutput. Film grain is left on its `auto` default:
|
||||
// applied by the VO under gpu-next, by the decoder under gpu.
|
||||
setOption("vo", initialVideoOutput(hardwareDecoding))
|
||||
setOption("gpu-context", "android")
|
||||
setOption("opengl-es", "yes")
|
||||
setOption("vd-lavc-film-grain", "cpu")
|
||||
if (displayFpsOverride != null) {
|
||||
setOption("display-fps-override", displayFpsOverride)
|
||||
}
|
||||
@@ -1038,9 +1068,13 @@ class MpvPlayerCore private constructor(
|
||||
"estimated-vf-fps" to getProperty("estimated-vf-fps"),
|
||||
"video-bitrate" to getProperty("video-bitrate"),
|
||||
"hwdec-current" to getProperty("hwdec-current"),
|
||||
"current-vo" to getProperty("current-vo"),
|
||||
"audio-codec-name" to getProperty("audio-codec-name"),
|
||||
"audio-params/samplerate" to getProperty("audio-params/samplerate"),
|
||||
"audio-params/hr-channels" to getProperty("audio-params/hr-channels"),
|
||||
"audio-params/format" to getProperty("audio-params/format"),
|
||||
"current-tracks/audio/demux-samplerate" to getProperty("current-tracks/audio/demux-samplerate"),
|
||||
"current-tracks/audio/demux-channel-count" to getProperty("current-tracks/audio/demux-channel-count"),
|
||||
"audio-bitrate" to getProperty("audio-bitrate"),
|
||||
"total-avsync-change" to getProperty("total-avsync-change"),
|
||||
"cache-used" to getProperty("cache-used"),
|
||||
@@ -1171,6 +1205,7 @@ class MpvPlayerCore private constructor(
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
matchResolution: Boolean,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
val mgr = frameRateManager
|
||||
@@ -1178,7 +1213,7 @@ class MpvPlayerCore private constructor(
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight) { switched ->
|
||||
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, matchResolution) { switched ->
|
||||
player?.let {
|
||||
updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") {
|
||||
onComplete(switched)
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import com.edde746.plezy.exoplayer.supportedMpvSpdifCodecs
|
||||
import com.edde746.plezy.shared.PlayerChannelBinding
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
@@ -147,7 +148,7 @@ open class MpvPlayerPlugin(
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"initialize" -> handleInitialize(result)
|
||||
"initialize" -> handleInitialize(call, result)
|
||||
"dispose" -> handleDispose(result)
|
||||
"setProperty" -> handleSetProperty(call, result)
|
||||
"getProperty" -> handleGetProperty(call, result)
|
||||
@@ -159,6 +160,7 @@ open class MpvPlayerPlugin(
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"getAudioSpdifCodecs" -> handleGetAudioSpdifCodecs(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"openContentFd" -> handleOpenContentFd(call, result)
|
||||
"closeContentFd" -> handleCloseContentFd(call, result)
|
||||
@@ -168,7 +170,21 @@ open class MpvPlayerPlugin(
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleInitialize(result: MethodChannel.Result) {
|
||||
/**
|
||||
* Derives the `audio-spdif` value for the current audio route. mpv force-passthroughs
|
||||
* every codec named there with no decode fallback, so with no context to inspect the
|
||||
* route the conservative answer is the empty list — decode everything (#1703, #1991).
|
||||
*/
|
||||
private fun handleGetAudioSpdifCodecs(result: MethodChannel.Result) {
|
||||
val context: Context? = activity ?: applicationContext
|
||||
result.success(context?.let(::supportedMpvSpdifCodecs) ?: "")
|
||||
}
|
||||
|
||||
private fun handleInitialize(call: MethodCall, result: MethodChannel.Result) {
|
||||
// Whether the session will hardware-decode; decides the initial vo chain
|
||||
// (MpvPlayerCore.initialVideoOutput). Absent on the audio-only core and
|
||||
// from older callers; hardware decode is the setting's default.
|
||||
val hardwareDecoding = call.argument<Boolean>("hardwareDecoding") ?: true
|
||||
// Video cores need the Activity (surface/view hierarchy); the audio-only
|
||||
// core is built on the application context so it can outlive it.
|
||||
val coreContext: Context? = if (audioOnly) applicationContext else activity
|
||||
@@ -227,7 +243,7 @@ open class MpvPlayerPlugin(
|
||||
}
|
||||
|
||||
gen = ++sessionGeneration
|
||||
core = MpvPlayerCore(coreContext, audioOnly).apply {
|
||||
core = MpvPlayerCore(coreContext, audioOnly, hardwareDecoding).apply {
|
||||
delegate = this@MpvPlayerPlugin
|
||||
}
|
||||
playerCore = core
|
||||
@@ -448,14 +464,19 @@ open class MpvPlayerPlugin(
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
|
||||
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
|
||||
val matchResolution = call.argument<Boolean>("matchResolution") ?: false
|
||||
|
||||
Log.d(tag, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
|
||||
Log.d(
|
||||
tag,
|
||||
"setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, " +
|
||||
"video=${videoWidth}x$videoHeight, matchResolution=$matchResolution"
|
||||
)
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, matchResolution) { switched ->
|
||||
result.success(switched)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Pure display-mode selection policy for content-adaptive display switching.
|
||||
* Extracted from [FrameRateManager] so the policy is unit-testable on the
|
||||
* JVM, where android.view.Display.Mode cannot be instantiated.
|
||||
*/
|
||||
object DisplayModeSelector {
|
||||
const val RATE_TOLERANCE = 0.1f
|
||||
|
||||
/** JVM-testable mirror of android.view.Display.Mode. */
|
||||
data class ModeInfo(val modeId: Int, val width: Int, val height: Int, val refreshRate: Float) {
|
||||
val area: Long get() = width.toLong() * height
|
||||
}
|
||||
|
||||
data class RefreshRateMatch(val reason: String, val priority: Int, val error: Float)
|
||||
|
||||
data class Selection(val mode: ModeInfo, val reason: String)
|
||||
|
||||
private data class Candidate(val mode: ModeInfo, val match: RefreshRateMatch)
|
||||
|
||||
/** How well [refreshRate] presents [fps] content: exact, an integer multiple, or not at all. */
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the display mode for the video, or null when no switch target exists.
|
||||
* The caller compares the result against the current mode to decide whether
|
||||
* an actual switch is needed.
|
||||
*
|
||||
* With [matchResolution] and known video dimensions, resolution wins over
|
||||
* cadence: the target is the smallest mode that still contains the video
|
||||
* (never downscaling it), rate-matched within that resolution when [fps] is
|
||||
* known. Otherwise the cadence-only policy applies and requires [fps] > 0.
|
||||
*/
|
||||
fun findBestMode(
|
||||
fps: Float,
|
||||
currentMode: ModeInfo,
|
||||
supportedModes: List<ModeInfo>,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
matchResolution: Boolean
|
||||
): Selection? {
|
||||
if (matchResolution && videoWidth > 0 && videoHeight > 0) {
|
||||
resolutionMatch(fps, currentMode, supportedModes, videoWidth, videoHeight)?.let { return it }
|
||||
// No mode can contain the video (source larger than the panel):
|
||||
// fall back to the cadence-only policy below.
|
||||
}
|
||||
return cadenceMatch(fps, currentMode, supportedModes, videoWidth, videoHeight)
|
||||
}
|
||||
|
||||
private fun resolutionMatch(
|
||||
fps: Float,
|
||||
currentMode: ModeInfo,
|
||||
supportedModes: List<ModeInfo>,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int
|
||||
): Selection? {
|
||||
val candidates = supportedModes.filter { it.width >= videoWidth && it.height >= videoHeight }
|
||||
if (candidates.isEmpty()) return null
|
||||
|
||||
// Native target: the smallest resolution that still contains the video,
|
||||
// so the display (not the device) performs the upscale.
|
||||
val targetArea = candidates.minOf { it.area }
|
||||
val bucket = candidates.filter { it.area == targetArea }
|
||||
|
||||
// Rate-match within the target resolution when requested. Resolution
|
||||
// wins over cadence: a missing rate match here deliberately does not
|
||||
// widen back out to other resolutions.
|
||||
if (fps > 0f) {
|
||||
bucket
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { Candidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<Candidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
?.let { return Selection(it.mode, "resolution + ${it.match.reason} rate, error=${it.match.error}") }
|
||||
}
|
||||
|
||||
// Resolution-only request, or no cadence match at the target resolution:
|
||||
// stay as close to the current refresh rate as possible so the switch
|
||||
// renegotiates only what it has to.
|
||||
val fallback = bucket.minWithOrNull(
|
||||
compareBy<ModeInfo> { abs(it.refreshRate - currentMode.refreshRate) }.thenByDescending { it.refreshRate }
|
||||
)
|
||||
return fallback?.let { Selection(it, "resolution only") }
|
||||
}
|
||||
|
||||
private fun cadenceMatch(
|
||||
fps: Float,
|
||||
currentMode: ModeInfo,
|
||||
supportedModes: List<ModeInfo>,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int
|
||||
): Selection? {
|
||||
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
|
||||
// switch, the least disruptive (no resolution/HDMI renegotiation).
|
||||
supportedModes.asSequence()
|
||||
.filter { it.width == currentMode.width && it.height == currentMode.height }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { Candidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<Candidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
?.let { return Selection(it.mode, "${it.match.reason}, error=${it.match.error}") }
|
||||
|
||||
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
|
||||
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
|
||||
// that downscales the video below its native size (trading detail for cadence).
|
||||
// Requires known video dimensions; without them keep Tier-1-only behaviour.
|
||||
if (videoWidth <= 0 || videoHeight <= 0) return null
|
||||
return supportedModes.asSequence()
|
||||
.filter { it.width >= videoWidth && it.height >= videoHeight }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { Candidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
// Prefer the resolution closest to the panel's current one (least change,
|
||||
// keeps panel-native res when a high-res match exists), then refresh match.
|
||||
compareBy<Candidate> { abs(it.mode.area - currentMode.area) }
|
||||
.thenBy { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
)
|
||||
?.let { Selection(it.mode, "${it.match.reason}, error=${it.match.error}") }
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,6 @@ import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import androidx.annotation.RequiresApi
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class FrameRateManager(
|
||||
private val activity: Activity,
|
||||
@@ -21,24 +19,12 @@ class FrameRateManager(
|
||||
private const val TAG = "FrameRateManager"
|
||||
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 currentVideoWidth: Int = 0
|
||||
private var currentVideoHeight: Int = 0
|
||||
private var currentMatchResolution: Boolean = false
|
||||
private var displayListener: DisplayManager.DisplayListener? = null
|
||||
private var pendingSettleRunnable: Runnable? = null
|
||||
private var watchdogRunnable: Runnable? = null
|
||||
@@ -46,13 +32,17 @@ 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, or already matching); or
|
||||
// Request a display mode switch for the video's frame rate and/or, with
|
||||
// [matchResolution], its native resolution. Invokes [onComplete] once, either:
|
||||
// - immediately with `switched=false` when no switch is needed (no usable
|
||||
// fps/resolution target, 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.
|
||||
//
|
||||
// fps <= 0 with [matchResolution] requests a resolution-only switch that
|
||||
// keeps the refresh rate as close to the current one as possible.
|
||||
//
|
||||
// The caller is responsible for pausing playback before calling and resuming
|
||||
// it after [onComplete] fires.
|
||||
fun setVideoFrameRate(
|
||||
@@ -61,20 +51,24 @@ class FrameRateManager(
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int = 0,
|
||||
videoHeight: Int = 0,
|
||||
matchResolution: Boolean = false,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
currentVideoFps = fps
|
||||
currentVideoWidth = videoWidth
|
||||
currentVideoHeight = videoHeight
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
currentMatchResolution = matchResolution
|
||||
val hasResolutionTarget = matchResolution && videoWidth > 0 && videoHeight > 0
|
||||
if (fps <= 0f && !hasResolutionTarget) {
|
||||
Log.d(TAG, "setVideoFrameRate: no usable target (fps=$fps, video=${videoWidth}x$videoHeight), skipping")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
log(
|
||||
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
|
||||
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
"video=${videoWidth}x$videoHeight, matchResolution=$matchResolution, " +
|
||||
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
@@ -129,7 +123,12 @@ class FrameRateManager(
|
||||
cb(switched)
|
||||
}
|
||||
|
||||
private fun registerDisplayListener(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
private fun registerDisplayListener(
|
||||
fps: Float,
|
||||
targetModeId: Int,
|
||||
extraDelayMs: Long,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
// Resolve any previous pending op before starting a new one.
|
||||
firePendingCompletion("superseded", switched = false)
|
||||
pendingCompletion = onComplete
|
||||
@@ -144,7 +143,9 @@ class FrameRateManager(
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
|
||||
val settle = Runnable { firePendingCompletion("display settled", switched = currentRateMatch(fps) != null) }
|
||||
val settle = Runnable {
|
||||
firePendingCompletion("display settled", switched = currentMatchesRequest(fps, targetModeId))
|
||||
}
|
||||
pendingSettleRunnable = settle
|
||||
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
|
||||
}
|
||||
@@ -154,37 +155,20 @@ 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 = currentRateMatch(fps) != null) }
|
||||
val watchdog = Runnable { firePendingCompletion("watchdog", switched = currentMatchesRequest(fps, targetModeId)) }
|
||||
watchdogRunnable = watchdog
|
||||
handler.postDelayed(watchdog, DISPLAY_SETTLE_MS + extraDelayMs + WATCHDOG_MARGIN_MS)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
private fun currentRateMatch(fps: Float): RefreshRateMatch? {
|
||||
val current = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
currentDisplayMode()?.refreshRate
|
||||
} else {
|
||||
null
|
||||
} ?: return null
|
||||
return matchRefreshRate(current, fps)
|
||||
// Whether the display landed on the requested mode: the exact target, or —
|
||||
// for a rate request — any mode whose refresh presents [fps] (a TV may pick
|
||||
// a different-but-equivalent mode). A resolution-only request (fps <= 0)
|
||||
// only counts the exact target.
|
||||
private fun currentMatchesRequest(fps: Float, targetModeId: Int): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false
|
||||
val current = currentDisplayMode() ?: return false
|
||||
if (current.modeId == targetModeId) return true
|
||||
return DisplayModeSelector.matchRefreshRate(current.refreshRate, fps) != null
|
||||
}
|
||||
|
||||
private fun currentModeDescription(): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
@@ -214,46 +198,11 @@ class FrameRateManager(
|
||||
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun findBestModeMatch(
|
||||
fps: Float,
|
||||
currentMode: Display.Mode,
|
||||
supportedModes: Array<Display.Mode>,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int
|
||||
): DisplayModeCandidate? {
|
||||
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
|
||||
// switch, the least disruptive (no resolution/HDMI renegotiation).
|
||||
supportedModes.asSequence()
|
||||
.filter { it.physicalHeight == currentMode.physicalHeight && it.physicalWidth == currentMode.physicalWidth }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<DisplayModeCandidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
?.let { return it }
|
||||
|
||||
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
|
||||
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
|
||||
// that downscales the video below its native size (trading detail for cadence).
|
||||
// Requires known video dimensions; without them keep Tier-1-only behaviour.
|
||||
if (videoWidth <= 0 || videoHeight <= 0) return null
|
||||
val currentArea = currentMode.physicalWidth.toLong() * currentMode.physicalHeight
|
||||
return supportedModes.asSequence()
|
||||
.filter { it.physicalWidth >= videoWidth && it.physicalHeight >= videoHeight }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
// Prefer the resolution closest to the panel's current one (least change,
|
||||
// keeps panel-native res when a high-res match exists), then refresh match.
|
||||
compareBy<DisplayModeCandidate> { abs(it.mode.physicalWidth.toLong() * it.mode.physicalHeight - currentArea) }
|
||||
.thenBy { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
)
|
||||
}
|
||||
private fun Display.Mode.toModeInfo(): DisplayModeSelector.ModeInfo = DisplayModeSelector.ModeInfo(modeId, physicalWidth, physicalHeight, refreshRate)
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
log("setDisplayMode fps=$fps")
|
||||
log("setDisplayMode fps=$fps, matchResolution=$currentMatchResolution")
|
||||
val display = currentDisplay()
|
||||
if (display == null) {
|
||||
log("display unavailable")
|
||||
@@ -270,34 +219,43 @@ class FrameRateManager(
|
||||
val currentMode = display.mode
|
||||
log("supported modes=${describeSupportedModes(supportedModes)}")
|
||||
|
||||
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes, currentVideoWidth, currentVideoHeight)
|
||||
if (modeMatch == null) {
|
||||
val selection = DisplayModeSelector.findBestMode(
|
||||
fps,
|
||||
currentMode.toModeInfo(),
|
||||
supportedModes.map { it.toModeInfo() },
|
||||
currentVideoWidth,
|
||||
currentVideoHeight,
|
||||
currentMatchResolution
|
||||
)
|
||||
if (selection == null) {
|
||||
log(
|
||||
"no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight} " +
|
||||
"(video=${currentVideoWidth}x$currentVideoHeight)"
|
||||
"(video=${currentVideoWidth}x$currentVideoHeight, matchResolution=$currentMatchResolution)"
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
val modeToUse = modeMatch.mode
|
||||
val modeToUse = supportedModes.firstOrNull { it.modeId == selection.mode.modeId }
|
||||
if (modeToUse == null) {
|
||||
log("selected mode #${selection.mode.modeId} disappeared from supported modes")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
if (modeToUse.modeId == currentMode.modeId) {
|
||||
log("current mode already matches ${fps}fps (${modeMatch.match.reason}), no switch needed")
|
||||
log("current mode already matches ${fps}fps (${selection.reason}), no switch needed")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
log(
|
||||
"switching to ${describeMode(modeToUse)} for ${fps}fps " +
|
||||
"(${modeMatch.match.reason}, error=${modeMatch.match.error})"
|
||||
)
|
||||
log("switching to ${describeMode(modeToUse)} for ${fps}fps (${selection.reason})")
|
||||
val window = activity.window
|
||||
if (window == null) {
|
||||
log("window unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
registerDisplayListener(fps, extraDelayMs, onComplete)
|
||||
registerDisplayListener(fps, modeToUse.modeId, extraDelayMs, onComplete)
|
||||
window.attributes = window.attributes.apply { preferredDisplayModeId = modeToUse.modeId }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ interface SurfacePlayerCore {
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
matchResolution: Boolean,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
)
|
||||
}
|
||||
|
||||
@@ -48,34 +48,65 @@ class AudioOutputPolicyTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spdifListNamesEveryCodecAnUnrestrictedRouteAdvertises() {
|
||||
assertEquals("ac3,eac3,dts,dts-hd,truehd", mpvSpdifCodecs { true })
|
||||
fun dtsDecodeIsForcedToFfmpegWhenDirectOutputIsBlocked() {
|
||||
// Passthrough disabled (the #1995 report), downmix, normalization, or a failure block:
|
||||
// the stream decodes, and platform DTS decoders render silence on license-gated devices.
|
||||
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts", { true }, { true }))
|
||||
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd", { true }, { true }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dtsDecodeIsForcedToFfmpegWhenTheRouteCannotBitstream() {
|
||||
// Onn 4K Plus over HDMI to a Dolby-only TV: passthrough enabled (the Android TV default)
|
||||
// still decodes because the route carries no DTS shape (#1995).
|
||||
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts", { false }, { false }))
|
||||
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd", { false }, { false }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bitstreamCapableDtsRoutesKeepThePlatformDecoderVisible() {
|
||||
// A bitstreaming session never engages a decoder; leaving the platform decoder visible
|
||||
// keeps the hardware-decoder tunneling gate exactly as it was.
|
||||
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts", { false }, { true }))
|
||||
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd", { false }, { true }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dtsVariantsFfmpegCannotClaimAreLeftAlone() {
|
||||
// DTS Express and DTS:X are not in FfmpegLibrary's mime map; hiding their platform
|
||||
// decoders would leave those streams with no decoder at all.
|
||||
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd;profile=lbr", { true }, { false }))
|
||||
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts.uhd", { true }, { false }))
|
||||
assertFalse(shouldForceFfmpegDtsDecode(MimeTypes.AUDIO_TRUEHD, { true }, { false }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nonDtsMimesNeverConsultTheDtsProbes() {
|
||||
// Decoder selection runs this predicate for every mime, video included; the probes make
|
||||
// binder calls and must stay behind the mime gate.
|
||||
assertFalse(
|
||||
shouldForceFfmpegDtsDecode(
|
||||
MimeTypes.VIDEO_H265,
|
||||
{ throw AssertionError("directOutputBlocked consulted for a non-DTS mime") },
|
||||
{ throw AssertionError("routeCanBitstreamDts consulted for a non-DTS mime") }
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spdifListNamesOnlyCodecsMpvsStereoIecTrackCanCarry() {
|
||||
// eac3 (a 192kHz burst), truehd and dts-hd (192kHz/8ch) never survive mpv's audiotrack
|
||||
// AO, which opens every spdif format as a stereo IEC 61937 track at the mixer rate;
|
||||
// naming them strands playback on a dead audio output (#1991).
|
||||
assertEquals("ac3,dts", mpvSpdifCodecs { true })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spdifListDropsCodecsTheRouteCannotBitstream() {
|
||||
// Google TV Streamer over HDMI to a Dolby-only sink: AC3/E-AC3 bitstream,
|
||||
// TrueHD and DTS do not (#1703).
|
||||
// Google TV Streamer over HDMI to a Dolby-only sink: AC3 bitstreams, DTS does not (#1703).
|
||||
val dolbyOnlyRoute = setOf(C.ENCODING_AC3, C.ENCODING_E_AC3)
|
||||
|
||||
assertEquals("ac3,eac3", mpvSpdifCodecs { encoding -> encoding in dolbyOnlyRoute })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spdifListOmitsDtsHdOnDtsCoreOnlyRoutes() {
|
||||
// media3's passthrough probe would answer yes for DTS-HD here by downgrading to the
|
||||
// DTS core. mpv reads `dts,dts-hd` as `dts-hd` alone and force-passes DTS-HD MA, so
|
||||
// accepting that downgrade would break DTS too.
|
||||
val dtsCoreOnlyRoute = setOf(C.ENCODING_DTS)
|
||||
|
||||
assertEquals("dts", mpvSpdifCodecs { encoding -> encoding in dtsCoreOnlyRoute })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun spdifListKeepsDtsHdWhenTheRouteAdvertisesIt() {
|
||||
val dtsHdRoute = setOf(C.ENCODING_DTS, C.ENCODING_DTS_HD)
|
||||
|
||||
assertEquals("dts,dts-hd", mpvSpdifCodecs { encoding -> encoding in dtsHdRoute })
|
||||
assertEquals("ac3", mpvSpdifCodecs { encoding -> encoding in dolbyOnlyRoute })
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,47 +115,51 @@ class AudioOutputPolicyTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun carrierIsNeverOfferedBelowApi29() {
|
||||
// No direct-playback oracle exists there, and getMinBufferSize alone is known to lie
|
||||
// (a Shield sizes the tuple, then the AudioTrack fails to initialise).
|
||||
fun iecRouteIsNeverOfferedBelowApi24() {
|
||||
// ENCODING_IEC61937 does not exist there.
|
||||
assertFalse(
|
||||
trueHdMatCarrierSupported(
|
||||
sdkInt = 28,
|
||||
canSizeCarrierBuffer = { true },
|
||||
iecRouteSupported(
|
||||
sdkInt = 23,
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { true },
|
||||
directPlaybackSupported = { true }
|
||||
directPlaybackSupported = { true },
|
||||
hdmiRouteAdvertised = { true }
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun carrierRequiresASizableBufferOnEveryTier() {
|
||||
for (sdkInt in intArrayOf(29, 30, 32, 33, 34)) {
|
||||
fun iecRouteRequiresASizableBufferOnEveryTier() {
|
||||
for (sdkInt in intArrayOf(25, 28, 29, 30, 32, 33, 34)) {
|
||||
assertFalse(
|
||||
"api $sdkInt",
|
||||
trueHdMatCarrierSupported(
|
||||
iecRouteSupported(
|
||||
sdkInt = sdkInt,
|
||||
canSizeCarrierBuffer = { false },
|
||||
canSizeBuffer = { false },
|
||||
bitstreamSupported = { true },
|
||||
directPlaybackSupported = { true }
|
||||
directPlaybackSupported = { true },
|
||||
hdmiRouteAdvertised = { true }
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun carrierOnApi29To32FollowsTheDirectPlaybackProbe() {
|
||||
// Fire OS 8 (API 30) bitstreams TrueHD over this route; an API 33 gate force-decoded it (#1863).
|
||||
fun routeOnApi24To28FollowsTheHdmiAdvertisement() {
|
||||
// No runtime oracle exists below API 29; only an HDMI AudioDeviceInfo that explicitly
|
||||
// advertises the IEC tuple can vouch for it. Shield Experience 8.x is API 28, and a flat
|
||||
// `false` on this tier force-decoded TrueHD on routes that genuinely carry it (#1991).
|
||||
for (supported in booleanArrayOf(true, false)) {
|
||||
for (sdkInt in intArrayOf(29, 30, 32)) {
|
||||
for (sdkInt in intArrayOf(25, 28)) {
|
||||
assertEquals(
|
||||
"api $sdkInt supported=$supported",
|
||||
supported,
|
||||
trueHdMatCarrierSupported(
|
||||
iecRouteSupported(
|
||||
sdkInt = sdkInt,
|
||||
canSizeCarrierBuffer = { true },
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { throw AssertionError("getDirectPlaybackSupport does not exist below API 33") },
|
||||
directPlaybackSupported = { supported }
|
||||
directPlaybackSupported = { throw AssertionError("isDirectPlaybackSupported does not exist below API 29") },
|
||||
hdmiRouteAdvertised = { supported }
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -132,18 +167,39 @@ class AudioOutputPolicyTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun carrierOnApi33UsesTheBitstreamProbe() {
|
||||
fun routeOnApi29To32FollowsTheDirectPlaybackProbe() {
|
||||
// Fire OS 8 (API 30) bitstreams TrueHD over this route; an API 33 gate force-decoded it (#1863).
|
||||
for (supported in booleanArrayOf(true, false)) {
|
||||
for (sdkInt in intArrayOf(29, 30, 32)) {
|
||||
assertEquals(
|
||||
"api $sdkInt supported=$supported",
|
||||
supported,
|
||||
iecRouteSupported(
|
||||
sdkInt = sdkInt,
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { throw AssertionError("getDirectPlaybackSupport does not exist below API 33") },
|
||||
directPlaybackSupported = { supported },
|
||||
hdmiRouteAdvertised = { throw AssertionError("the HDMI advertisement must not shadow the runtime probe") }
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routeOnApi33UsesTheBitstreamProbe() {
|
||||
// getDirectPlaybackSupport distinguishes bitstream from offload-only; the coarser API 29
|
||||
// probe must not shadow it where the platform can answer precisely.
|
||||
for (supported in booleanArrayOf(true, false)) {
|
||||
assertEquals(
|
||||
"supported=$supported",
|
||||
supported,
|
||||
trueHdMatCarrierSupported(
|
||||
iecRouteSupported(
|
||||
sdkInt = 33,
|
||||
canSizeCarrierBuffer = { true },
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { supported },
|
||||
directPlaybackSupported = { throw AssertionError("API 29 probe must not be consulted on API 33+") }
|
||||
directPlaybackSupported = { throw AssertionError("API 29 probe must not be consulted on API 33+") },
|
||||
hdmiRouteAdvertised = { throw AssertionError("the HDMI advertisement must not shadow the runtime probe") }
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Pins the DTS-HD -> IEC 61937 "DTS type IV" carrier against FFmpeg (#1988).
|
||||
*
|
||||
* The carrier is fed straight to an `ENCODING_IEC61937` AudioTrack, so a wrong byte is not a subtle
|
||||
* defect: the receiver either drops sync or renders the carrier as full-scale noise. The only
|
||||
* defensible bar is byte-for-byte agreement with a reference implementation, so the fixtures are
|
||||
* FFmpeg's own input and output at the 768kHz HD rate that fills the 192kHz/7.1 carrier.
|
||||
*
|
||||
* FFmpeg cannot encode Master Audio, so the access units are synthesized — real `dca` core frames,
|
||||
* each glued to a hand-built extension substream — by `dtshd_fixture_generator.py` beside the
|
||||
* fixtures; the golden is then FFmpeg's own packing:
|
||||
*
|
||||
* ```
|
||||
* ffmpeg -f dts -i dtshd_ma_access_units.bin -c:a copy -f spdif -dtshd_rate 768000 \
|
||||
* dtshd_ma_iec61937_golden.bin
|
||||
* ```
|
||||
*
|
||||
* One mid-stream unit is oversized on purpose, so the fixtures also pin FFmpeg's overflow answer:
|
||||
* strip to the core substream and hold that for ~60s.
|
||||
*/
|
||||
class DtsHdIecPackerTest {
|
||||
|
||||
private fun resource(name: String): ByteArray = checkNotNull(javaClass.classLoader?.getResourceAsStream(name)) { "missing fixture $name" }
|
||||
.use { it.readBytes() }
|
||||
|
||||
private val accessUnits by lazy { resource("dtshd_ma_access_units.bin") }
|
||||
private val golden by lazy { resource("dtshd_ma_iec61937_golden.bin") }
|
||||
|
||||
/** 512 samples at the fixture's 48kHz core rate on the 768kHz carrier model, in bytes. */
|
||||
private val burstSize = 32768
|
||||
|
||||
/** The whole point: our carrier and FFmpeg's are the same bytes. */
|
||||
@Test
|
||||
fun packedCarrierMatchesFfmpegByteForByte() {
|
||||
val packed = packAll(accessUnits)
|
||||
|
||||
assertEquals(
|
||||
"burst count differs from FFmpeg",
|
||||
golden.size / burstSize,
|
||||
packed.size / burstSize
|
||||
)
|
||||
// Compare per burst so a failure names the burst rather than dumping 480KB.
|
||||
for (index in 0 until packed.size / burstSize) {
|
||||
val from = index * burstSize
|
||||
val to = from + burstSize
|
||||
assertArrayEquals(
|
||||
"burst $index differs from FFmpeg",
|
||||
golden.copyOfRange(from, to),
|
||||
packed.copyOfRange(from, to)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Each burst is a full IEC 61937 frame: preamble, then payload, then zero padding. */
|
||||
@Test
|
||||
fun everyBurstCarriesTheDtsHdPreamble() {
|
||||
val packed = packAll(accessUnits)
|
||||
|
||||
for (index in 0 until packed.size / burstSize) {
|
||||
val at = index * burstSize
|
||||
assertEquals("burst $index Pa", 0xF872, readLittleEndianShort(packed, at))
|
||||
assertEquals("burst $index Pb", 0x4E1F, readLittleEndianShort(packed, at + 2))
|
||||
// Data type 0x11 with subtype 4: an 8192 IEC 60958 frame repetition period.
|
||||
assertEquals("burst $index Pc (IEC61937_DTSHD)", 0x0411, readLittleEndianShort(packed, at + 4))
|
||||
val payloadSize = 10 + 2 + burstAccessUnitSize(packed, at)
|
||||
assertEquals(
|
||||
"burst $index Pd must carry FFmpeg's (length & 0xf) == 0x8 alignment",
|
||||
((payloadSize + 0x17) and 0x0F.inv()) - 8,
|
||||
readLittleEndianShort(packed, at + 6)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Master Audio peak the carrier cannot hold is stripped to the always-fitting core substream,
|
||||
* and stays stripped for ~60s so the receiver does not flap between core and MA decoding. The
|
||||
* fixture's fifth unit is oversized on purpose; everything after it is core-only.
|
||||
*/
|
||||
@Test
|
||||
fun anOversizedUnitStripsToTheCoreAndHolds() {
|
||||
val packer = DtsHdIecPacker()
|
||||
val packed = packAll(accessUnits, packer)
|
||||
|
||||
val fullUnit = 3904
|
||||
val coreOnly = 1884
|
||||
for (index in 0 until packed.size / burstSize) {
|
||||
val expected = if (index < 4) fullUnit else coreOnly
|
||||
assertEquals("burst $index payload size", expected, burstAccessUnitSize(packed, index * burstSize))
|
||||
}
|
||||
assertTrue("the strip must be observable for logging", packer.strippedToCore)
|
||||
assertFalse("stripping is a downgrade, not an unsupported stream", packer.unsupportedStream)
|
||||
}
|
||||
|
||||
/** Core frames and their glued extension substreams split as one access unit each. */
|
||||
@Test
|
||||
fun accessUnitsSpanTheCoreAndItsExtensionSubstreams() {
|
||||
val packer = DtsHdIecPacker()
|
||||
var units = 0
|
||||
var offset = 0
|
||||
while (offset < accessUnits.size) {
|
||||
val length = packer.accessUnitLength(accessUnits, offset, accessUnits.size)
|
||||
if (length == 0) break
|
||||
units++
|
||||
offset += length
|
||||
}
|
||||
assertEquals("every byte of the fixture belongs to a unit", accessUnits.size, offset)
|
||||
assertEquals(golden.size / burstSize, units)
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams with core sometimes open with a stray HD frame that has no core (FFmpeg discards
|
||||
* these). It must be consumed as a unit so the stream keeps moving, but never carried: there is
|
||||
* no core to derive the burst period from.
|
||||
*/
|
||||
@Test
|
||||
fun aStrayLeadingExtensionSubstreamIsConsumedButNotCarried() {
|
||||
val packer = DtsHdIecPacker()
|
||||
val firstUnit = packer.accessUnitLength(accessUnits, 0, accessUnits.size)
|
||||
val exssSize = 2020
|
||||
val stray = accessUnits.copyOfRange(firstUnit - exssSize, firstUnit)
|
||||
|
||||
val length = packer.accessUnitLength(stray, 0, stray.size)
|
||||
|
||||
assertEquals("the stray frame's own size field walks it", exssSize, length)
|
||||
assertNull("a coreless frame cannot ride the carrier", packer.packAccessUnit(stray, 0, length))
|
||||
assertFalse("a stray frame is dropped, not latched", packer.unsupportedStream)
|
||||
}
|
||||
|
||||
/** The wide (bHeaderSizeType=1) extension-substream header carries 20-bit size fields. */
|
||||
@Test
|
||||
fun wideHeaderExtensionSubstreamSizesAreParsed() {
|
||||
val packer = DtsHdIecPacker()
|
||||
val core = accessUnits.copyOfRange(0, 1884)
|
||||
val exssSize = 4100
|
||||
val unit = core + wideHeaderExtensionSubstream(exssSize)
|
||||
|
||||
assertEquals(1884 + exssSize, packer.accessUnitLength(unit, 0, unit.size))
|
||||
}
|
||||
|
||||
/**
|
||||
* Little-endian and 14-bit core framings (S/PDIF and DTS-in-WAV captures) have no period mapping
|
||||
* on this carrier; they must latch the stream unsupported so the sink hands it to the decoder,
|
||||
* not silently consume it.
|
||||
*/
|
||||
@Test
|
||||
fun nonBigEndianCoreFramingLatchesTheStreamUnsupported() {
|
||||
for (sync in listOf(
|
||||
byteArrayOf(0xFE.toByte(), 0x7F, 0x01, 0x80.toByte()),
|
||||
byteArrayOf(0x1F, 0xFF.toByte(), 0xE8.toByte(), 0x00),
|
||||
byteArrayOf(0xFF.toByte(), 0x1F, 0x00, 0xE8.toByte())
|
||||
)) {
|
||||
val packer = DtsHdIecPacker()
|
||||
val buffer = sync + ByteArray(64)
|
||||
|
||||
assertEquals(0, packer.accessUnitLength(buffer, 0, buffer.size))
|
||||
assertTrue("sync ${sync.joinToString { "%02x".format(it) }}", packer.unsupportedStream)
|
||||
}
|
||||
}
|
||||
|
||||
/** A 44.1kHz-family core maps to no IEC 61937-11 repetition period at 192kHz; it must decode. */
|
||||
@Test
|
||||
fun aFortyFourFamilyCoreLatchesTheStreamUnsupported() {
|
||||
val packer = DtsHdIecPacker()
|
||||
val unit = accessUnits.copyOfRange(0, 1884)
|
||||
// SFREQ sits in bits [5:2] of byte 8; index 8 is 44100Hz.
|
||||
unit[8] = ((unit[8].toInt() and 0b11000011) or (8 shl 2)).toByte()
|
||||
|
||||
assertNull(packer.packAccessUnit(unit, 0, unit.size))
|
||||
assertTrue(packer.unsupportedStream)
|
||||
}
|
||||
|
||||
/**
|
||||
* The flags gate every later call, so leaving them latched across a reset would make a packer
|
||||
* that once saw a bad stream emit nothing (or log strips) for the rest of its life.
|
||||
*/
|
||||
@Test
|
||||
fun resetClearsTheLatchesAndReproducesTheStream() {
|
||||
val packer = DtsHdIecPacker()
|
||||
val leSync = byteArrayOf(0xFE.toByte(), 0x7F, 0x01, 0x80.toByte()) + ByteArray(64)
|
||||
packer.accessUnitLength(leSync, 0, leSync.size)
|
||||
assertTrue(packer.unsupportedStream)
|
||||
|
||||
packer.reset()
|
||||
|
||||
assertFalse("reset must clear the unsupported latch", packer.unsupportedStream)
|
||||
assertFalse("reset must clear the strip latch", packer.strippedToCore)
|
||||
assertArrayEquals(
|
||||
"a clean packer must reproduce the stream after a poisoned one",
|
||||
golden,
|
||||
packAll(accessUnits, packer)
|
||||
)
|
||||
}
|
||||
|
||||
/** The packer must not allocate a burst per unit; buffers alternate and are reused. */
|
||||
@Test
|
||||
fun burstBuffersAreReusedRatherThanAllocated() {
|
||||
val packer = DtsHdIecPacker()
|
||||
val seen = java.util.IdentityHashMap<java.nio.ByteBuffer, Boolean>()
|
||||
var bursts = 0
|
||||
var offset = 0
|
||||
while (offset < accessUnits.size) {
|
||||
val length = packer.accessUnitLength(accessUnits, offset, accessUnits.size)
|
||||
if (length == 0) break
|
||||
packer.packAccessUnit(accessUnits, offset, length)?.let {
|
||||
seen[it] = true
|
||||
bursts++
|
||||
}
|
||||
offset += length
|
||||
}
|
||||
assertTrue("expected multiple bursts", bursts > 2)
|
||||
assertEquals("buffers must alternate between exactly two", 2, seen.size)
|
||||
}
|
||||
|
||||
private fun packAll(units: ByteArray, packer: DtsHdIecPacker = DtsHdIecPacker()): ByteArray {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
var offset = 0
|
||||
while (offset < units.size) {
|
||||
val length = packer.accessUnitLength(units, offset, units.size)
|
||||
if (length == 0) break
|
||||
packer.packAccessUnit(units, offset, length)?.let { burst ->
|
||||
val copy = ByteArray(burst.remaining())
|
||||
burst.duplicate().get(copy)
|
||||
out.write(copy)
|
||||
}
|
||||
offset += length
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/** The 16-bit big-endian size field after the start code, read from the byte-swapped burst. */
|
||||
private fun burstAccessUnitSize(packed: ByteArray, burstOffset: Int): Int {
|
||||
// Payload bytes 10 and 11 land swapped within their 16-bit word: 10 -> +19, 11 -> +18.
|
||||
val high = packed[burstOffset + 8 + 11].toInt() and 0xFF
|
||||
val low = packed[burstOffset + 8 + 10].toInt() and 0xFF
|
||||
return (high shl 8) or low
|
||||
}
|
||||
|
||||
/** An extension substream whose header uses the wide 12/20-bit size fields. */
|
||||
private fun wideHeaderExtensionSubstream(size: Int): ByteArray {
|
||||
val frame = ByteArray(size)
|
||||
frame[0] = 0x64
|
||||
frame[1] = 0x58
|
||||
frame[2] = 0x20
|
||||
frame[3] = 0x25
|
||||
// After UserDefinedBits(8): nExtSSIndex(2)=0, bHeaderSizeType(1)=1, then 12 header-size bits
|
||||
// and 20 frame-size bits, all values stored minus one.
|
||||
var bits = 0L
|
||||
bits = (bits shl 2) or 0L
|
||||
bits = (bits shl 1) or 1L
|
||||
bits = (bits shl 12) or (32L - 1)
|
||||
bits = (bits shl 20) or (size.toLong() - 1)
|
||||
// 35 bits, MSB-aligned into bytes 5..9.
|
||||
val aligned = bits shl (40 - 35)
|
||||
for (i in 0 until 5) {
|
||||
frame[5 + i] = ((aligned shr (32 - 8 * i)) and 0xFF).toByte()
|
||||
}
|
||||
return frame
|
||||
}
|
||||
|
||||
private fun readLittleEndianShort(data: ByteArray, offset: Int): Int = (data[offset].toInt() and 0xFF) or ((data[offset + 1].toInt() and 0xFF) shl 8)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class FfmpegDemuxerPolicyTest {
|
||||
@Test
|
||||
fun wireValuesRoundTrip() {
|
||||
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire("ffmpeg"))
|
||||
assertEquals(FfmpegDemuxerPolicy.Preference.MEDIA3_ONLY, FfmpegDemuxerPolicy.fromWire("media3"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownWireValuesResolveToFfmpeg() {
|
||||
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire(null))
|
||||
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire(""))
|
||||
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire("bogus"))
|
||||
// Retired wire value from the container-list era maps to the default.
|
||||
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire("auto"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ffmpegDemuxesByDefaultAndMedia3OnlyDisables() {
|
||||
assertTrue(FfmpegDemuxerPolicy.enabled(FfmpegDemuxerPolicy.Preference.FFMPEG))
|
||||
assertFalse(FfmpegDemuxerPolicy.enabled(FfmpegDemuxerPolicy.Preference.MEDIA3_ONLY))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Byte-exact spec for the media3-shaped subtitle sample prefixes. The shapes
|
||||
* mirror media3 1.11.0 MatroskaExtractor's SSA_PREFIX/SUBRIP_PREFIX/VTT_PREFIX
|
||||
* with the duration patched into the second timecode; SsaParser,
|
||||
* SubripParser, WebvttParser, and AssTrackOutput all parse these exact bytes.
|
||||
*/
|
||||
class FfmpegSubtitleSamplesTest {
|
||||
|
||||
private fun string(bytes: ByteArray): String = bytes.toString(Charsets.UTF_8)
|
||||
|
||||
@Test
|
||||
fun ssaPrefixMatchesMatroskaExtractorShape() {
|
||||
// 1h 2m 3s 450ms -> centiseconds, ':' separator, single-digit hour.
|
||||
assertEquals(
|
||||
"Dialogue: 0:00:00:00,1:02:03:45,",
|
||||
string(FfmpegSubtitleSamples.ssaPrefix(3_723_450_000L))
|
||||
)
|
||||
assertEquals("Dialogue: 0:00:00:00,0:00:05:00,", string(FfmpegSubtitleSamples.ssaPrefix(5_000_000L)))
|
||||
// Sub-centisecond remainders truncate, matching integer division.
|
||||
assertEquals("Dialogue: 0:00:00:00,0:00:00:99,", string(FfmpegSubtitleSamples.ssaPrefix(999_999L)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun subripPrefixIsACompleteCueHeader() {
|
||||
assertEquals(
|
||||
"1\n00:00:00,000 --> 01:02:03,450\n",
|
||||
string(FfmpegSubtitleSamples.subripPrefix(3_723_450_000L))
|
||||
)
|
||||
assertEquals("1\n00:00:00,000 --> 00:00:05,000\n", string(FfmpegSubtitleSamples.subripPrefix(5_000_000L)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun vttPrefixIsAOneCueDocumentHeader() {
|
||||
assertEquals(
|
||||
"WEBVTT\n\n00:00:00.000 --> 01:02:03.450\n",
|
||||
string(FfmpegSubtitleSamples.vttPrefix(3_723_450_000L))
|
||||
)
|
||||
assertEquals("WEBVTT\n\n00:00:00.000 --> 00:00:05.000\n", string(FfmpegSubtitleSamples.vttPrefix(5_000_000L)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ssaDialogueFormatMatchesMedia3Constant() {
|
||||
assertEquals(
|
||||
"Format: Start, End, ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
|
||||
string(FfmpegSubtitleSamples.SSA_DIALOGUE_FORMAT)
|
||||
)
|
||||
}
|
||||
}
|
||||
+176
-16
@@ -24,13 +24,14 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Routing and back-pressure contract for the TrueHD MAT carrier (#1804).
|
||||
* Routing and back-pressure contract for the IEC 61937 carrier: TrueHD/MAT (#1804) and DTS-HD
|
||||
* (#1988).
|
||||
*
|
||||
* The carrier is bit-exact, so the two failure modes that matter here are losing bytes and letting
|
||||
* the wrong sink handle TrueHD.
|
||||
* the wrong sink handle a carrier codec.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class TrueHdCarrierSinkTest {
|
||||
class IecCarrierSinkTest {
|
||||
|
||||
private val accessUnits: ByteArray =
|
||||
checkNotNull(javaClass.classLoader?.getResourceAsStream("truehd_access_units.bin"))
|
||||
@@ -40,12 +41,28 @@ class TrueHdCarrierSinkTest {
|
||||
checkNotNull(javaClass.classLoader?.getResourceAsStream("truehd_iec61937_golden.bin"))
|
||||
.use { it.readBytes() }
|
||||
|
||||
private val dtsHdAccessUnits: ByteArray by lazy {
|
||||
checkNotNull(javaClass.classLoader?.getResourceAsStream("dtshd_ma_access_units.bin"))
|
||||
.use { it.readBytes() }
|
||||
}
|
||||
|
||||
private val dtsHdGolden: ByteArray by lazy {
|
||||
checkNotNull(javaClass.classLoader?.getResourceAsStream("dtshd_ma_iec61937_golden.bin"))
|
||||
.use { it.readBytes() }
|
||||
}
|
||||
|
||||
private fun trueHdFormat(sampleRate: Int = 48_000): Format = Format.Builder()
|
||||
.setSampleMimeType(MimeTypes.AUDIO_TRUEHD)
|
||||
.setChannelCount(6)
|
||||
.setSampleRate(sampleRate)
|
||||
.build()
|
||||
|
||||
private fun dtsHdFormat(sampleRate: Int = 48_000): Format = Format.Builder()
|
||||
.setSampleMimeType(MimeTypes.AUDIO_DTS_HD)
|
||||
.setChannelCount(6)
|
||||
.setSampleRate(sampleRate)
|
||||
.build()
|
||||
|
||||
private fun audioSinkConfig(format: Format = trueHdFormat()) = AudioSink.AudioSinkConfig.Builder(format).build()
|
||||
|
||||
private fun sink(
|
||||
@@ -53,7 +70,7 @@ class TrueHdCarrierSinkTest {
|
||||
normal: FakeSink = FakeSink(),
|
||||
routeAvailable: Boolean = true,
|
||||
blocked: Boolean = false
|
||||
) = TrueHdCarrierSink(normal, carrier, { routeAvailable }, { blocked })
|
||||
) = IecCarrierSink(normal, carrier, { routeAvailable }, { blocked })
|
||||
|
||||
/**
|
||||
* TrueHD is the carrier or it is decoded. Falling through to the normal sink would hand media3
|
||||
@@ -75,6 +92,54 @@ class TrueHdCarrierSinkTest {
|
||||
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(trueHdFormat()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dtsHdWithACarrierRouteIsSupportedDirectly() {
|
||||
val carrierSink = sink()
|
||||
assertTrue(carrierSink.supportsFormat(dtsHdFormat()))
|
||||
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(dtsHdFormat()))
|
||||
}
|
||||
|
||||
/**
|
||||
* The route that advertises the carrier and raw `ENCODING_DTS_HD` at once is the one whose raw
|
||||
* path renders silence (#1988), so while the carrier route exists DTS-HD is the carrier or it is
|
||||
* decoded — never the normal sink's raw path, even when policy declines the carrier.
|
||||
*/
|
||||
@Test
|
||||
fun dtsHdOnACarrierRouteNeverFallsThroughToTheRawPath() {
|
||||
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
|
||||
val blockedSink = sink(normal = normal, blocked = true)
|
||||
|
||||
assertFalse(blockedSink.supportsFormat(dtsHdFormat()))
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, blockedSink.getFormatSupport(dtsHdFormat()))
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes without the IEC carrier never had it to lose, and some of them bitstream raw DTS-HD
|
||||
* genuinely; the pre-carrier behavior is preserved there.
|
||||
*/
|
||||
@Test
|
||||
fun dtsHdWithoutACarrierRouteFallsThroughToTheNormalSink() {
|
||||
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
|
||||
val carrierSink = sink(normal = normal, routeAvailable = false)
|
||||
|
||||
assertTrue(carrierSink.supportsFormat(dtsHdFormat()))
|
||||
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(dtsHdFormat()))
|
||||
}
|
||||
|
||||
/** DTS Express shares the DTS-HD mime prefix but carries `;profile=lbr`; it keeps decoding. */
|
||||
@Test
|
||||
fun dtsExpressIsLeftToTheNormalSink() {
|
||||
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
|
||||
val carrierSink = sink(normal = normal)
|
||||
val express = Format.Builder()
|
||||
.setSampleMimeType(MimeTypes.AUDIO_DTS_EXPRESS)
|
||||
.setSampleRate(48_000)
|
||||
.build()
|
||||
|
||||
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(express))
|
||||
assertTrue(carrierSink.supportsFormat(express))
|
||||
}
|
||||
|
||||
/** Downmix and normalization already force decoding; the carrier must not override that. */
|
||||
@Test
|
||||
fun blockedDirectOutputDeclinesTheCarrier() {
|
||||
@@ -83,8 +148,8 @@ class TrueHdCarrierSinkTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* 44.1kHz-family TrueHD rides a 176.4kHz carrier this path does not build. It has to be decided
|
||||
* from the format: the packer only learns the rate from a major sync, long after selection, and
|
||||
* 44.1kHz-family streams ride a 176.4kHz carrier this path does not build. It has to be decided
|
||||
* from the format: the packer only learns the rate from the bitstream, long after selection, and
|
||||
* selecting the carrier for it would produce silence.
|
||||
*/
|
||||
@Test
|
||||
@@ -92,6 +157,8 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink()
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(trueHdFormat(sampleRate = 44_100)))
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(trueHdFormat(sampleRate = 176_400)))
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(dtsHdFormat(sampleRate = 44_100)))
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(dtsHdFormat(sampleRate = 88_200)))
|
||||
}
|
||||
|
||||
/** A bitstream cannot be resampled, so any speed other than 1.0x decodes. */
|
||||
@@ -100,6 +167,7 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink()
|
||||
carrierSink.setPlaybackParameters(PlaybackParameters(1.5f))
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(trueHdFormat()))
|
||||
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(dtsHdFormat()))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -183,6 +251,33 @@ class TrueHdCarrierSinkTest {
|
||||
assertEquals("nothing may reach the carrier delegate", 0, carrier.written.size())
|
||||
}
|
||||
|
||||
/**
|
||||
* The DTS-HD equivalent: a bitstream whose framing the carrier cannot ride (an S/PDIF-style
|
||||
* little-endian capture) must latch onto the decoder, and the offending unit must survive.
|
||||
*/
|
||||
@Test
|
||||
fun aDtsHdFramingMismatchLeavesTheCarrierInsteadOfGoingSilent() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
val listener = RecordingSinkListener()
|
||||
carrierSink.setListener(listener)
|
||||
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
|
||||
|
||||
val littleEndianCapture = byteArrayOf(0xFE.toByte(), 0x7F, 0x01, 0x80.toByte()) + ByteArray(64)
|
||||
val buffer = ByteBuffer.wrap(littleEndianCapture)
|
||||
val accepted = carrierSink.handleBuffer(buffer, 0L, 1)
|
||||
|
||||
assertFalse("a mismatch must apply back pressure, not report success", accepted)
|
||||
assertEquals("the offending unit must stay in the buffer", 0, buffer.position())
|
||||
assertEquals("the renderer must be asked to reselect", 1, listener.capabilityInvalidations)
|
||||
assertEquals(
|
||||
"DTS-HD must now decode rather than ride the carrier or the raw path",
|
||||
AudioSink.SINK_FORMAT_UNSUPPORTED,
|
||||
carrierSink.getFormatSupport(dtsHdFormat())
|
||||
)
|
||||
assertEquals("nothing may reach the carrier delegate", 0, carrier.written.size())
|
||||
}
|
||||
|
||||
/**
|
||||
* media3 resets every renderer disabled by a new selection before enabling the replacement, and
|
||||
* both audio renderers share this sink. That reset lands mid-handover, so a latch cleared there
|
||||
@@ -278,7 +373,7 @@ class TrueHdCarrierSinkTest {
|
||||
)
|
||||
}
|
||||
|
||||
/** Everything that is not TrueHD keeps going to the existing processed sink. */
|
||||
/** Everything that is not a carrier codec keeps going to the existing processed sink. */
|
||||
@Test
|
||||
fun otherFormatsAreLeftToTheNormalSink() {
|
||||
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
|
||||
@@ -303,7 +398,7 @@ class TrueHdCarrierSinkTest {
|
||||
// Refuse every third burst once, so rejections land inside samples rather than between them.
|
||||
carrier.refuseEveryNth = 3
|
||||
|
||||
val produced = feedWholeStream(carrierSink)
|
||||
val produced = feedWholeStream(carrierSink, accessUnits)
|
||||
assertArrayEquals("carrier output must survive back pressure unchanged", golden, produced)
|
||||
assertTrue("the fake must actually have exercised the refusal path", carrier.refusals > 0)
|
||||
}
|
||||
@@ -315,7 +410,53 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
|
||||
assertArrayEquals(golden, feedWholeStream(carrierSink))
|
||||
assertArrayEquals(golden, feedWholeStream(carrierSink, accessUnits))
|
||||
}
|
||||
|
||||
/** A DTS-HD stream must select the DTS packer and come out matching FFmpeg's bytes. */
|
||||
@Test
|
||||
fun theDtsHdCarrierOutputMatchesTheGoldenStream() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
|
||||
|
||||
assertArrayEquals(dtsHdGolden, feedWholeStream(carrierSink, dtsHdAccessUnits))
|
||||
}
|
||||
|
||||
/** Back pressure must not cost DTS-HD units either; bursts and units are one-to-one there. */
|
||||
@Test
|
||||
fun aRefusedDtsHdBurstLosesNoAccessUnits() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
|
||||
carrier.refuseEveryNth = 3
|
||||
|
||||
val produced = feedWholeStream(carrierSink, dtsHdAccessUnits)
|
||||
assertArrayEquals(dtsHdGolden, produced)
|
||||
assertTrue(carrier.refusals > 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Burst timestamps come from the carrier cadence, not the closing access unit. A DTS-HD burst is
|
||||
* 10666.67us of carrier — not a whole number — so the cadence must be derived from cumulative
|
||||
* carrier frames; per-burst rounding would drift ~62ms over a movie.
|
||||
*/
|
||||
@Test
|
||||
fun dtsHdBurstTimestampsFollowTheExactCarrierCadence() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
|
||||
|
||||
feedWholeStream(carrierSink, dtsHdAccessUnits)
|
||||
|
||||
val framesPerBurst = 32768L / IecCarrier.BYTES_PER_FRAME
|
||||
carrier.bufferTimesUs.forEachIndexed { index, timeUs ->
|
||||
assertEquals(
|
||||
"burst $index timestamp",
|
||||
index * framesPerBurst * 1_000_000L / IecCarrier.SAMPLE_RATE,
|
||||
timeUs
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A refused burst must be re-offered before any further input is taken. */
|
||||
@@ -380,8 +521,23 @@ class TrueHdCarrierSinkTest {
|
||||
assertEquals(inputConfig.mediaPeriodId, configured.mediaPeriodId)
|
||||
assertEquals(MimeTypes.AUDIO_RAW, configured.format.sampleMimeType)
|
||||
assertEquals(C.ENCODING_PCM_16BIT, configured.format.pcmEncoding)
|
||||
assertEquals(TrueHdMatPacker.CARRIER_SAMPLE_RATE, configured.format.sampleRate)
|
||||
assertEquals(TrueHdMatPacker.CARRIER_CHANNEL_COUNT, configured.format.channelCount)
|
||||
assertEquals(IecCarrier.SAMPLE_RATE, configured.format.sampleRate)
|
||||
assertEquals(IecCarrier.CHANNEL_COUNT, configured.format.channelCount)
|
||||
}
|
||||
|
||||
/** DTS-HD rides the same PCM-shaped carrier tuple TrueHD does. */
|
||||
@Test
|
||||
fun theDtsHdCarrierDelegateIsConfiguredAsAFixedRatePcmCarrier() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
|
||||
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
|
||||
|
||||
val configured = checkNotNull(carrier.configuredConfig)
|
||||
assertEquals(MimeTypes.AUDIO_RAW, configured.format.sampleMimeType)
|
||||
assertEquals(C.ENCODING_PCM_16BIT, configured.format.pcmEncoding)
|
||||
assertEquals(IecCarrier.SAMPLE_RATE, configured.format.sampleRate)
|
||||
assertEquals(IecCarrier.CHANNEL_COUNT, configured.format.channelCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -399,18 +555,20 @@ class TrueHdCarrierSinkTest {
|
||||
assertEquals(null, carrier.configuredConfig)
|
||||
}
|
||||
|
||||
private fun feedWholeStream(carrierSink: TrueHdCarrierSink): ByteArray {
|
||||
val buffer = ByteBuffer.wrap(accessUnits)
|
||||
private fun feedWholeStream(carrierSink: IecCarrierSink, units: ByteArray): ByteArray {
|
||||
val buffer = ByteBuffer.wrap(units)
|
||||
var guard = 0
|
||||
while (buffer.hasRemaining() && guard++ < 10_000) {
|
||||
// media3 retries handleBuffer until it returns true, even once the buffer is fully consumed;
|
||||
// a refusal of the stream's final burst leaves it pending with nothing remaining to read.
|
||||
while ((buffer.hasRemaining() || carrierSink.hasPendingData()) && guard++ < 10_000) {
|
||||
carrierSink.handleBuffer(buffer, 0L, 1)
|
||||
}
|
||||
val carrier = carrierSinkDelegate(carrierSink)
|
||||
return carrier.written.toByteArray()
|
||||
}
|
||||
|
||||
private fun carrierSinkDelegate(sink: TrueHdCarrierSink): FakeSink {
|
||||
val field = TrueHdCarrierSink::class.java.getDeclaredField("carrierSink")
|
||||
private fun carrierSinkDelegate(sink: IecCarrierSink): FakeSink {
|
||||
val field = IecCarrierSink::class.java.getDeclaredField("carrierSink")
|
||||
field.isAccessible = true
|
||||
return field.get(sink) as FakeSink
|
||||
}
|
||||
@@ -430,6 +588,7 @@ class TrueHdCarrierSinkTest {
|
||||
/** Minimal AudioSink that records what it was handed and can apply back pressure. */
|
||||
private class FakeSink : AudioSink {
|
||||
val written = ByteArrayOutputStream()
|
||||
val bufferTimesUs = mutableListOf<Long>()
|
||||
var configuredConfig: AudioSink.AudioSinkConfig? = null
|
||||
var formatSupport: Int = AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
var lastVolume: Float = -1f
|
||||
@@ -454,6 +613,7 @@ class TrueHdCarrierSinkTest {
|
||||
val copy = ByteArray(buffer.remaining())
|
||||
buffer.duplicate().get(copy)
|
||||
written.write(copy)
|
||||
bufferTimesUs.add(presentationTimeUs)
|
||||
buffer.position(buffer.limit())
|
||||
return true
|
||||
}
|
||||
+33
-82
@@ -5,14 +5,7 @@ import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.DefaultExtractorInput
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.PositionHolder
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
|
||||
import java.io.EOFException
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
@@ -24,16 +17,17 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* Extracts the committed fixture (1s 440Hz sine, AAC-LC 48kHz stereo, LATM/LOAS
|
||||
* muxed into MKV as A_MS/ACM tag 0x1602) and verifies direct Matroska playback
|
||||
* unwraps LOAS frames to raw AAC with a synthesized AudioSpecificConfig.
|
||||
* Drives LatmTrackOutput with LOAS frames from the committed fixture (1s 440Hz
|
||||
* sine, AAC-LC 48kHz stereo, LATM/LOAS) and verifies it unwraps them to raw
|
||||
* AAC with a synthesized AudioSpecificConfig. Both demuxer paths deliver LOAS
|
||||
* this way: the FFmpeg extractor wraps aac_latm tracks directly.
|
||||
*
|
||||
* Robolectric provides real android.util.* implementations — MatroskaExtractor
|
||||
* stores tracks in a SparseArray, which is a no-op stub on plain JVM.
|
||||
* Robolectric provides real android.util.* implementations for media3's
|
||||
* internals.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class MatroskaLatmSupportTest {
|
||||
class LatmTrackOutputTest {
|
||||
|
||||
private class CapturedSample(val timeUs: Long, val flags: Int, val data: ByteArray)
|
||||
|
||||
@@ -71,14 +65,6 @@ class MatroskaLatmSupportTest {
|
||||
}
|
||||
}
|
||||
|
||||
private class FakeExtractorOutput : ExtractorOutput {
|
||||
val tracks = mutableMapOf<Int, FakeTrackOutput>()
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput = tracks.getOrPut(id) { FakeTrackOutput() }
|
||||
override fun endTracks() {}
|
||||
override fun seekMap(seekMap: SeekMap) {}
|
||||
}
|
||||
|
||||
private class ByteArrayDataReader(private val data: ByteArray) : DataReader {
|
||||
var position = 0L
|
||||
|
||||
@@ -118,76 +104,46 @@ class MatroskaLatmSupportTest {
|
||||
return frames
|
||||
}
|
||||
|
||||
private fun extractFixture(): FakeExtractorOutput {
|
||||
val data = fixtureData()
|
||||
|
||||
val assHandler = AssHandler()
|
||||
val extractor = ZlibMatroskaExtractor(AssSubtitleParserFactory(assHandler), assHandler)
|
||||
val output = FakeExtractorOutput()
|
||||
extractor.init(output)
|
||||
|
||||
val reader = ByteArrayDataReader(data)
|
||||
var input = DefaultExtractorInput(reader, 0, data.size.toLong())
|
||||
val seekPosition = PositionHolder()
|
||||
while (true) {
|
||||
when (extractor.read(input, seekPosition)) {
|
||||
Extractor.RESULT_END_OF_INPUT -> return output
|
||||
Extractor.RESULT_SEEK -> {
|
||||
reader.position = seekPosition.position
|
||||
input = DefaultExtractorInput(reader, seekPosition.position, data.size.toLong())
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun placeholderFormat(): Format = Format.Builder()
|
||||
.setId("1")
|
||||
.setSampleMimeType(MimeTypes.AUDIO_AAC)
|
||||
.setLabel("LATM track")
|
||||
.setLanguage("eng")
|
||||
.build()
|
||||
|
||||
@Test
|
||||
fun unwrapsLoasAcmTrackToRawAac() {
|
||||
val output = extractFixture()
|
||||
fun unwrapsLoasFramesToRawAac() {
|
||||
val delegate = FakeTrackOutput()
|
||||
val output = LatmTrackOutput(delegate, 1)
|
||||
output.format(placeholderFormat())
|
||||
|
||||
assertEquals(1, output.tracks.size)
|
||||
val track = output.tracks.values.first()
|
||||
val frames = loasFrames(40)
|
||||
var timeUs = 0L
|
||||
for (frame in frames) {
|
||||
output.sampleData(ParsableByteArray(frame), frame.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(timeUs, C.BUFFER_FLAG_KEY_FRAME, frame.size, 0, null)
|
||||
timeUs += 21_333
|
||||
}
|
||||
|
||||
// No audio/x-unknown format may reach the queue; the LATM-derived AAC
|
||||
// format must carry the AudioSpecificConfig for MediaCodec.
|
||||
assertFalse(track.formats.any { it.sampleMimeType == MimeTypes.AUDIO_UNKNOWN })
|
||||
val format = track.formats.last()
|
||||
// The placeholder format must be swallowed; the LATM-derived AAC format
|
||||
// carries the AudioSpecificConfig and the original track metadata.
|
||||
val format = delegate.formats.last()
|
||||
assertEquals(MimeTypes.AUDIO_AAC, format.sampleMimeType)
|
||||
assertEquals(48000, format.sampleRate)
|
||||
assertEquals(2, format.channelCount)
|
||||
assertEquals("1", format.id)
|
||||
assertEquals("LATM track", format.label)
|
||||
assertTrue(format.initializationData.isNotEmpty())
|
||||
assertTrue(format.initializationData[0].isNotEmpty())
|
||||
|
||||
// 1s at 48kHz / 1024 samples per AAC frame ≈ 47 frames
|
||||
assertTrue("expected ~47 samples, got ${track.samples.size}", track.samples.size in 40..55)
|
||||
|
||||
// Raw AAC payloads: smaller than the LOAS wrapping, no LOAS syncword,
|
||||
// keyframe-flagged, monotonic timestamps spanning ~1s.
|
||||
var prevTimeUs = Long.MIN_VALUE
|
||||
for (sample in track.samples) {
|
||||
assertTrue("expected ~40 samples, got ${delegate.samples.size}", delegate.samples.size in 35..40)
|
||||
for (sample in delegate.samples) {
|
||||
assertTrue(sample.data.isNotEmpty())
|
||||
val isLoasSync = sample.data.size >= 2 &&
|
||||
(sample.data[0].toInt() and 0xFF) == 0x56 &&
|
||||
(sample.data[1].toInt() and 0xE0) == 0xE0
|
||||
assertFalse("sample still LOAS-framed", isLoasSync)
|
||||
assertEquals(C.BUFFER_FLAG_KEY_FRAME, sample.flags and C.BUFFER_FLAG_KEY_FRAME)
|
||||
assertTrue(sample.timeUs >= prevTimeUs)
|
||||
prevTimeUs = sample.timeUs
|
||||
}
|
||||
val spanUs = track.samples.last().timeUs - track.samples.first().timeUs
|
||||
assertTrue("expected ~1s span, got ${spanUs}us", spanUs in 800_000..1_200_000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detectsLoasAcmCodecPrivate() {
|
||||
val loas = byteArrayOf(0x02, 0x16, 0, 0, 0, 0)
|
||||
assertTrue(isLoasAcmTrack("A_MS/ACM", loas))
|
||||
// Wrong tag (PCM), wrong codec, or missing private data must not match
|
||||
assertFalse(isLoasAcmTrack("A_MS/ACM", byteArrayOf(0x01, 0x00, 0, 0)))
|
||||
assertFalse(isLoasAcmTrack("A_AAC", loas))
|
||||
assertFalse(isLoasAcmTrack("A_MS/ACM", null))
|
||||
assertFalse(isLoasAcmTrack("A_MS/ACM", byteArrayOf(0x02)))
|
||||
assertFalse(isLoasAcmTrack(null, loas))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -205,19 +161,14 @@ class MatroskaLatmSupportTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesStreamMuxConfigAcrossExtractorSeek() {
|
||||
fun preservesStreamMuxConfigAcrossReset() {
|
||||
val frames = loasFrames(2)
|
||||
assertEquals(0, frames[0][3].toInt() and 0x80)
|
||||
assertEquals(0x80, frames[1][3].toInt() and 0x80)
|
||||
|
||||
val delegate = FakeTrackOutput()
|
||||
val output = LatmTrackOutput(delegate, 1)
|
||||
output.format(
|
||||
Format.Builder()
|
||||
.setId("1")
|
||||
.setSampleMimeType(MimeTypes.AUDIO_UNKNOWN)
|
||||
.build()
|
||||
)
|
||||
output.format(placeholderFormat())
|
||||
|
||||
output.sampleData(ParsableByteArray(frames[0]), frames[0].size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(0, C.BUFFER_FLAG_KEY_FRAME, frames[0].size, 0, null)
|
||||
@@ -1,105 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.DefaultExtractorInput
|
||||
import androidx.media3.extractor.Extractor
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.PositionHolder
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/** Regression coverage for Matroska files whose SeekHead references Tracks after the Clusters. */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class MatroskaLateTracksTest {
|
||||
|
||||
private class CapturedTrack(val type: Int) : TrackOutput {
|
||||
var format: Format? = null
|
||||
var sampleCount = 0
|
||||
|
||||
override fun format(format: Format) {
|
||||
this.format = format
|
||||
}
|
||||
|
||||
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int = input.read(ByteArray(length), 0, length)
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
data.skipBytes(length)
|
||||
}
|
||||
|
||||
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
|
||||
sampleCount++
|
||||
}
|
||||
}
|
||||
|
||||
private class CapturingExtractorOutput : ExtractorOutput {
|
||||
val tracks = mutableMapOf<Int, CapturedTrack>()
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput = tracks.getOrPut(id) { CapturedTrack(type) }
|
||||
override fun endTracks() = Unit
|
||||
override fun seekMap(seekMap: SeekMap) = Unit
|
||||
}
|
||||
|
||||
private class ByteArrayDataReader(private val data: ByteArray) : DataReader {
|
||||
var position = 0L
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (position >= data.size) return C.RESULT_END_OF_INPUT
|
||||
val bytesRead = minOf(length, data.size - position.toInt())
|
||||
data.copyInto(buffer, offset, position.toInt(), position.toInt() + bytesRead)
|
||||
position += bytesRead
|
||||
return bytesRead
|
||||
}
|
||||
}
|
||||
|
||||
private fun fixtureData(): ByteArray = checkNotNull(javaClass.getResourceAsStream("/matroska_tracks_at_end.mkv")) {
|
||||
"fixture matroska_tracks_at_end.mkv missing from test resources"
|
||||
}.use { it.readBytes() }
|
||||
|
||||
private fun extractFixture(): CapturingExtractorOutput {
|
||||
val data = fixtureData()
|
||||
val assHandler = AssHandler()
|
||||
val extractor = ZlibMatroskaExtractor(AssSubtitleParserFactory(assHandler), assHandler)
|
||||
val output = CapturingExtractorOutput()
|
||||
extractor.init(output)
|
||||
|
||||
val reader = ByteArrayDataReader(data)
|
||||
var input: ExtractorInput = DefaultExtractorInput(reader, 0, data.size.toLong())
|
||||
val seekPosition = PositionHolder()
|
||||
repeat(100_000) {
|
||||
when (extractor.read(input, seekPosition)) {
|
||||
Extractor.RESULT_END_OF_INPUT -> return output
|
||||
Extractor.RESULT_SEEK -> {
|
||||
reader.position = seekPosition.position
|
||||
input = DefaultExtractorInput(reader, seekPosition.position, data.size.toLong())
|
||||
}
|
||||
}
|
||||
}
|
||||
error("extractor did not reach end of input")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun extractsSamplesWhenSeekHeadReferencesTracksAfterClusters() {
|
||||
val output = extractFixture()
|
||||
|
||||
assertEquals(2, output.tracks.size)
|
||||
assertEquals(setOf(C.TRACK_TYPE_VIDEO, C.TRACK_TYPE_AUDIO), output.tracks.values.map { it.type }.toSet())
|
||||
output.tracks.values.forEach { track ->
|
||||
assertNotNull(track.format)
|
||||
assertTrue("expected extracted samples for track type ${track.type}", track.sampleCount > 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class StreamBitrateMeterTest {
|
||||
|
||||
/** Feeds [count] packets of [sizeBytes] every [intervalUs], starting at [startUs]. */
|
||||
private fun StreamBitrateMeter.feed(count: Int, sizeBytes: Int, intervalUs: Long, startUs: Long = 0L) {
|
||||
for (i in 0 until count) onPacket(startUs + i * intervalUs, sizeBytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `constant packet stream measures its bitrate`() {
|
||||
val meter = StreamBitrateMeter()
|
||||
// 1200-byte packets every 32 ms: 1200 * 8 / 0.032 = 300 kbps.
|
||||
meter.feed(count = 32, sizeBytes = 1200, intervalUs = 32_000)
|
||||
assertEquals(300_000, meter.bitrateBps())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `too few packets report nothing`() {
|
||||
val meter = StreamBitrateMeter()
|
||||
meter.feed(count = 15, sizeBytes = 1200, intervalUs = 32_000)
|
||||
assertNull(meter.bitrateBps())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `zero pts span reports nothing`() {
|
||||
val meter = StreamBitrateMeter()
|
||||
repeat(32) { meter.onPacket(0L, 1200) }
|
||||
assertNull(meter.bitrateBps())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `window drops old packets so a bitrate change is followed`() {
|
||||
val meter = StreamBitrateMeter(windowUs = 1_000_000)
|
||||
meter.feed(count = 100, sizeBytes = 1200, intervalUs = 32_000)
|
||||
// Continue at four times the packet size; after well over a window of
|
||||
// new packets, only the new rate remains.
|
||||
meter.feed(count = 100, sizeBytes = 4800, intervalUs = 32_000, startUs = 100 * 32_000L)
|
||||
assertEquals(1_200_000, meter.bitrateBps())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `backwards pts jump resets the window`() {
|
||||
val meter = StreamBitrateMeter()
|
||||
meter.feed(count = 32, sizeBytes = 1200, intervalUs = 32_000)
|
||||
// Seek back: the single post-seek packet must not combine with the
|
||||
// pre-seek span.
|
||||
meter.onPacket(0L, 1200)
|
||||
assertNull(meter.bitrateBps())
|
||||
meter.feed(count = 31, sizeBytes = 1200, intervalUs = 32_000, startUs = 32_000)
|
||||
assertEquals(300_000, meter.bitrateBps())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty packets are ignored`() {
|
||||
val meter = StreamBitrateMeter()
|
||||
meter.feed(count = 32, sizeBytes = 1200, intervalUs = 32_000)
|
||||
meter.onPacket(32 * 32_000L, 0)
|
||||
assertEquals(300_000, meter.bitrateBps())
|
||||
}
|
||||
}
|
||||
@@ -67,8 +67,8 @@ class TrueHdMatPackerTest {
|
||||
/** A burst is exactly 20ms of carrier, which is what makes the PCM-domain accounting downstream correct. */
|
||||
@Test
|
||||
fun aBurstIsTwentyMillisecondsOfCarrier() {
|
||||
val framesPerBurst = TrueHdMatPacker.MAT_PKT_OFFSET / TrueHdMatPacker.CARRIER_BYTES_PER_FRAME
|
||||
val durationUs = framesPerBurst * 1_000_000L / TrueHdMatPacker.CARRIER_SAMPLE_RATE
|
||||
val framesPerBurst = TrueHdMatPacker.MAT_PKT_OFFSET / IecCarrier.BYTES_PER_FRAME
|
||||
val durationUs = framesPerBurst * 1_000_000L / IecCarrier.SAMPLE_RATE
|
||||
assertEquals(20_000L, durationUs)
|
||||
}
|
||||
|
||||
@@ -166,11 +166,11 @@ class TrueHdMatPackerTest {
|
||||
|
||||
val length = TrueHdMatPacker.accessUnitLength(units, 0, units.size)
|
||||
packer.packAccessUnit(units, 0, length)
|
||||
assertTrue("the fixture must actually announce the 44.1kHz family", packer.unsupportedRateFamily)
|
||||
assertTrue("the fixture must actually announce the 44.1kHz family", packer.unsupportedStream)
|
||||
|
||||
packer.reset()
|
||||
|
||||
assertFalse("reset must clear the flag", packer.unsupportedRateFamily)
|
||||
assertFalse("reset must clear the flag", packer.unsupportedStream)
|
||||
assertArrayEquals(
|
||||
"a clean packer must reproduce the stream after a poisoned one",
|
||||
golden,
|
||||
|
||||
-248
@@ -1,248 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.ParserException
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.Deflater
|
||||
import java.util.zip.DeflaterOutputStream
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class ZlibInflatingTrackOutputTest {
|
||||
@Before
|
||||
fun enableMedia3TestBoundsChecks() {
|
||||
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(true)
|
||||
}
|
||||
|
||||
@After
|
||||
fun resetMedia3TestBoundsChecks() {
|
||||
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeTransformInflatesChunkedSampleAndPreservesMetadata() {
|
||||
val original = ByteArray(512 * 1024) { (it % 251).toByte() }
|
||||
val compressed = deflate(original)
|
||||
val delegate = RecordingTrackOutput(retainBytes = true)
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
val split = compressed.size / 2
|
||||
|
||||
output.sampleData(
|
||||
ParsableByteArray(compressed.copyOfRange(0, split)),
|
||||
split,
|
||||
TrackOutput.SAMPLE_DATA_PART_MAIN
|
||||
)
|
||||
output.sampleData(
|
||||
ParsableByteArray(compressed.copyOfRange(split, compressed.size)),
|
||||
compressed.size - split,
|
||||
TrackOutput.SAMPLE_DATA_PART_MAIN
|
||||
)
|
||||
output.sampleMetadata(42L, C.BUFFER_FLAG_KEY_FRAME, compressed.size, 0, null)
|
||||
|
||||
assertArrayEquals(original, delegate.retained.toByteArray())
|
||||
assertEquals(42L, delegate.timeUs)
|
||||
assertEquals(C.BUFFER_FLAG_KEY_FRAME, delegate.flags)
|
||||
assertEquals(original.size, delegate.sampleSize)
|
||||
assertEquals(0, delegate.offset)
|
||||
assertEquals(1, delegate.metadataCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeTransformUsesMetadataBoundariesForBufferedSamples() {
|
||||
val first = ByteArray(4096) { (it % 19).toByte() }
|
||||
val second = ByteArray(2048) { (it % 23).toByte() }
|
||||
val firstCompressed = deflate(first)
|
||||
val secondCompressed = deflate(second)
|
||||
val combined = firstCompressed + secondCompressed
|
||||
val delegate = RecordingTrackOutput(retainBytes = true)
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
|
||||
output.sampleData(ParsableByteArray(combined), combined.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(1, 0, firstCompressed.size, secondCompressed.size, null)
|
||||
output.sampleMetadata(2, 0, secondCompressed.size, 0, null)
|
||||
|
||||
assertArrayEquals(first + second, delegate.retained.toByteArray())
|
||||
assertEquals(2, delegate.metadataCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exactlySixteenMiBInflatedSampleIsAccepted() {
|
||||
val size = 16 * 1024 * 1024
|
||||
val compressed = deflateRepeated(size)
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
|
||||
feed(output, compressed)
|
||||
|
||||
assertEquals(size, delegate.byteCount)
|
||||
assertEquals(size, delegate.sampleSize)
|
||||
assertEquals(1, delegate.metadataCount)
|
||||
assertTrue(compressed.size < 64 * 1024)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oneByteOverInflatedLimitFailsBeforeDelegation() {
|
||||
val compressed = deflateRepeated(16 * 1024 * 1024 + 1)
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
|
||||
assertThrows(ParserException::class.java) { feed(output, compressed) }
|
||||
|
||||
assertEquals(0, delegate.byteCount)
|
||||
assertEquals(0, delegate.metadataCount)
|
||||
assertTrue(compressed.size < 64 * 1024)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun excessiveCompressionRatioFailsBeforeInflatedSizeLimit() {
|
||||
val compressed = deflate(ByteArray(8 * 1024 * 1024))
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
|
||||
assertThrows(ParserException::class.java) { feed(output, compressed) }
|
||||
|
||||
assertEquals(0, delegate.byteCount)
|
||||
assertEquals(0, delegate.metadataCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corruptStreamPassesTheBoundedSampleThroughUnchanged() {
|
||||
val corrupt = byteArrayOf(0, 1, 2, 3)
|
||||
val delegate = RecordingTrackOutput(retainBytes = true)
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
|
||||
feed(output, corrupt)
|
||||
|
||||
assertArrayEquals(corrupt, delegate.retained.toByteArray())
|
||||
assertEquals(corrupt.size, delegate.sampleSize)
|
||||
assertEquals(1, delegate.metadataCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun truncatedAndDictionaryStreamsFailClosed() {
|
||||
val valid = deflate(ByteArray(4096) { 7 })
|
||||
val dictionary = "shared-zlib-dictionary".toByteArray()
|
||||
val cases = listOf(
|
||||
valid.copyOf(valid.size - 2),
|
||||
deflate(ByteArray(4096) { 3 }, dictionary)
|
||||
)
|
||||
|
||||
for (compressed in cases) {
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
|
||||
|
||||
assertThrows(ParserException::class.java) { feed(output, compressed) }
|
||||
assertEquals(0, delegate.byteCount)
|
||||
assertEquals(0, delegate.metadataCount)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inactiveWrapperDelegatesBytesAndMetadataUnchanged() {
|
||||
val bytes = byteArrayOf(9, 8, 7, 6)
|
||||
val trailing = byteArrayOf(5, 4)
|
||||
val allBytes = bytes + trailing
|
||||
val delegate = RecordingTrackOutput(retainBytes = true)
|
||||
val output = ZlibInflatingTrackOutput(delegate)
|
||||
|
||||
output.sampleData(ParsableByteArray(allBytes), allBytes.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(99L, 3, bytes.size, trailing.size, null)
|
||||
|
||||
assertArrayEquals(allBytes, delegate.retained.toByteArray())
|
||||
assertEquals(bytes.size, delegate.sampleSize)
|
||||
assertEquals(trailing.size, delegate.offset)
|
||||
assertEquals(99L, delegate.timeUs)
|
||||
}
|
||||
|
||||
private fun feed(output: ZlibInflatingTrackOutput, compressed: ByteArray) {
|
||||
output.sampleData(
|
||||
ParsableByteArray(compressed),
|
||||
compressed.size,
|
||||
TrackOutput.SAMPLE_DATA_PART_MAIN
|
||||
)
|
||||
output.sampleMetadata(1L, C.BUFFER_FLAG_KEY_FRAME, compressed.size, 0, null)
|
||||
}
|
||||
|
||||
private fun deflate(bytes: ByteArray, dictionary: ByteArray? = null): ByteArray {
|
||||
val target = ByteArrayOutputStream()
|
||||
val deflater = Deflater().apply {
|
||||
if (dictionary != null) setDictionary(dictionary)
|
||||
}
|
||||
DeflaterOutputStream(target, deflater).use { it.write(bytes) }
|
||||
return target.toByteArray()
|
||||
}
|
||||
|
||||
private fun deflateRepeated(size: Int): ByteArray {
|
||||
val target = ByteArrayOutputStream()
|
||||
val chunk = ByteArray(8192) { (it % 7).toByte() }
|
||||
DeflaterOutputStream(target).use { stream ->
|
||||
var remaining = size
|
||||
while (remaining > 0) {
|
||||
val count = minOf(remaining, chunk.size)
|
||||
stream.write(chunk, 0, count)
|
||||
remaining -= count
|
||||
}
|
||||
}
|
||||
return target.toByteArray()
|
||||
}
|
||||
|
||||
private class RecordingTrackOutput(
|
||||
private val retainBytes: Boolean = false
|
||||
) : TrackOutput {
|
||||
val retained = ByteArrayOutputStream()
|
||||
var byteCount = 0
|
||||
var metadataCount = 0
|
||||
var timeUs = C.TIME_UNSET
|
||||
var flags = 0
|
||||
var sampleSize = -1
|
||||
var offset = -1
|
||||
|
||||
override fun format(format: Format) = Unit
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
val buffer = ByteArray(length)
|
||||
val read = input.read(buffer, 0, length)
|
||||
if (read > 0) record(buffer, read)
|
||||
return read
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
val buffer = ByteArray(length)
|
||||
data.readBytes(buffer, 0, length)
|
||||
record(buffer, length)
|
||||
}
|
||||
|
||||
private fun record(buffer: ByteArray, length: Int) {
|
||||
byteCount += length
|
||||
if (retainBytes) retained.write(buffer, 0, length)
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
metadataCount++
|
||||
this.timeUs = timeUs
|
||||
this.flags = flags
|
||||
sampleSize = size
|
||||
this.offset = offset
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,30 @@ class MpvPlayerPluginTest {
|
||||
assertNull(result.successValue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun audioSpdifCodecsWithoutContextAnswersEmptySoMpvDecodes() {
|
||||
// mpv force-passthroughs every codec named in audio-spdif with no decode fallback, so
|
||||
// with no context to inspect the audio route the only safe answer is "" (#1703, #1991).
|
||||
val result = RecordingResult()
|
||||
|
||||
MpvPlayerPlugin().onMethodCall(MethodCall("getAudioSpdifCodecs", null), result)
|
||||
|
||||
assertEquals("", result.successValue)
|
||||
assertNull(result.errorCode)
|
||||
assertEquals(1, result.completionCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hardwareDecodeSessionsKeepTheLegacyGpuVo() {
|
||||
// gpu-next under hwdec=mediacodec fails every frame on Tegra (the
|
||||
// cross-stage samplerExternalOES linker bug): solid blue screen with
|
||||
// audio on the Shield (#2010). DV reshaping — the reason gpu-next exists
|
||||
// on Android (#1902) — only happens under software decode anyway, so
|
||||
// gpu-next is offered exactly there and nowhere else.
|
||||
assertEquals("gpu", MpvPlayerCore.initialVideoOutput(hardwareDecoding = true))
|
||||
assertEquals("gpu-next,gpu", MpvPlayerCore.initialVideoOutput(hardwareDecoding = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun setPropertyWithoutCoreReportsNotInitializedForVideoAndAudio() {
|
||||
for (plugin in listOf(MpvPlayerPlugin(), MpvAudioPlayerPlugin())) {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import com.edde746.plezy.shared.DisplayModeSelector.ModeInfo
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class DisplayModeSelectorTest {
|
||||
|
||||
// A typical 4K TV: panel-native modes plus lower-resolution HDMI modes.
|
||||
private val uhd60 = ModeInfo(1, 3840, 2160, 60f)
|
||||
private val uhd50 = ModeInfo(2, 3840, 2160, 50f)
|
||||
private val uhd24 = ModeInfo(3, 3840, 2160, 23.976f)
|
||||
private val fhd60 = ModeInfo(4, 1920, 1080, 60f)
|
||||
private val fhd50 = ModeInfo(5, 1920, 1080, 50f)
|
||||
private val fhd24 = ModeInfo(6, 1920, 1080, 23.976f)
|
||||
private val hd60 = ModeInfo(7, 1280, 720, 60f)
|
||||
private val sd60 = ModeInfo(8, 720, 480, 60f)
|
||||
private val allModes = listOf(uhd60, uhd50, uhd24, fhd60, fhd50, fhd24, hd60, sd60)
|
||||
|
||||
private fun select(
|
||||
fps: Float,
|
||||
current: ModeInfo = uhd60,
|
||||
modes: List<ModeInfo> = allModes,
|
||||
videoWidth: Int = 0,
|
||||
videoHeight: Int = 0,
|
||||
matchResolution: Boolean = false
|
||||
) = DisplayModeSelector.findBestMode(fps, current, modes, videoWidth, videoHeight, matchResolution)
|
||||
|
||||
// --- Resolution matching ---
|
||||
|
||||
@Test
|
||||
fun resolutionMatchingPicksNativeResolutionAndRate() {
|
||||
val selection = select(23.976f, videoWidth = 1920, videoHeight = 1080, matchResolution = true)
|
||||
assertEquals(fhd24, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolutionOnlyRequestKeepsCurrentRefreshRate() {
|
||||
val selection = select(0f, videoWidth = 1920, videoHeight = 1080, matchResolution = true)
|
||||
assertEquals(fhd60, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolutionMatchingNeverDownscalesTheVideo() {
|
||||
// 1080p-class anamorphic content is wider than 720p even though shorter:
|
||||
// the smallest containing mode is 1080p, not 720p.
|
||||
val selection = select(0f, videoWidth = 1920, videoHeight = 800, matchResolution = true)
|
||||
assertEquals(fhd60, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolutionWinsOverCadenceWhenNativeResolutionHasNoMatchingRate() {
|
||||
// No 720p24 mode exists; the 720p video still lands on 720p (TV upscales)
|
||||
// instead of widening back out to a 24 Hz mode at another resolution.
|
||||
val selection = select(23.976f, videoWidth = 1280, videoHeight = 720, matchResolution = true)
|
||||
assertEquals(hd60, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun panelNativeContentStaysAtPanelResolution() {
|
||||
val selection = select(23.976f, videoWidth = 3840, videoHeight = 2160, matchResolution = true)
|
||||
assertEquals(uhd24, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun panelNativeResolutionOnlyRequestNeedsNoSwitch() {
|
||||
val selection = select(0f, videoWidth = 3840, videoHeight = 2160, matchResolution = true)
|
||||
assertEquals(uhd60, selection?.mode) // caller sees modeId == current and skips
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sourceLargerThanPanelFallsBackToCadencePolicy() {
|
||||
val selection = select(23.976f, videoWidth = 7680, videoHeight = 4320, matchResolution = true)
|
||||
assertEquals(uhd24, selection?.mode) // Tier-1 refresh-only switch
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sourceLargerThanPanelWithoutFpsHasNoTarget() {
|
||||
assertNull(select(0f, videoWidth = 7680, videoHeight = 4320, matchResolution = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolutionMatchingWithoutDimensionsBehavesLikeCadenceOnly() {
|
||||
val selection = select(23.976f, matchResolution = true)
|
||||
assertEquals(uhd24, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resolutionOnlyPrefersRateClosestToCurrent() {
|
||||
// From a 50 Hz current mode, a resolution-only switch keeps 50 Hz.
|
||||
val selection = select(0f, current = uhd50, videoWidth = 1920, videoHeight = 1080, matchResolution = true)
|
||||
assertEquals(fhd50, selection?.mode)
|
||||
}
|
||||
|
||||
// --- Cadence-only policy (matchResolution off): pre-existing behaviour ---
|
||||
|
||||
@Test
|
||||
fun cadenceMatchingStaysAtCurrentResolution() {
|
||||
val selection = select(23.976f, videoWidth = 1920, videoHeight = 1080)
|
||||
assertEquals(uhd24, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cadenceTierTwoAllowsResolutionChangeButNeverBelowVideo() {
|
||||
// Panel has no 4K@24; only 1080p@24 remains for 1080p content.
|
||||
val modes = listOf(uhd60, uhd50, fhd60, fhd24, hd60)
|
||||
val selection = select(23.976f, modes = modes, videoWidth = 1920, videoHeight = 1080)
|
||||
assertEquals(fhd24, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cadenceTierTwoRequiresKnownDimensions() {
|
||||
val modes = listOf(uhd60, uhd50, fhd60, fhd24, hd60)
|
||||
assertNull(select(23.976f, modes = modes))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidFpsWithoutResolutionRequestHasNoTarget() {
|
||||
assertNull(select(0f, videoWidth = 1920, videoHeight = 1080))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multipleRateCountsAsCadenceMatch() {
|
||||
// 30 fps on a 60 Hz mode is a clean 2x pulldown; current 60 Hz mode wins.
|
||||
val selection = select(29.97f, current = uhd60, modes = listOf(uhd60, uhd50))
|
||||
assertNotNull(selection)
|
||||
assertEquals(uhd60, selection?.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exactRateBeatsMultipleRate() {
|
||||
val uhd30 = ModeInfo(9, 3840, 2160, 29.97f)
|
||||
val selection = select(29.97f, modes = allModes + uhd30)
|
||||
assertEquals(uhd30, selection?.mode)
|
||||
}
|
||||
|
||||
// --- matchRefreshRate ---
|
||||
|
||||
@Test
|
||||
fun refreshRateMatchClassifiesExactMultipleAndMiss() {
|
||||
assertEquals(0, DisplayModeSelector.matchRefreshRate(23.976f, 23.976f)?.priority)
|
||||
assertEquals(1, DisplayModeSelector.matchRefreshRate(59.94f, 29.97f)?.priority)
|
||||
assertNull(DisplayModeSelector.matchRefreshRate(60f, 23.976f))
|
||||
assertNull(DisplayModeSelector.matchRefreshRate(60f, 0f))
|
||||
assertNull(DisplayModeSelector.matchRefreshRate(0f, 24f))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerates the DTS-HD MA packer fixtures (#1988).
|
||||
|
||||
FFmpeg has no DTS-HD MA encoder, so the access-unit fixture is synthesized: real
|
||||
DTS core frames from FFmpeg's `dca` encoder, each followed by a hand-built
|
||||
extension substream (EXSS) whose header fields are coherent enough for FFmpeg's
|
||||
DCA parser to glue core+EXSS into one access unit. The IEC 61937 wrapping never
|
||||
inspects EXSS payload bytes, only the sync word and size fields, so this pins
|
||||
the same wire format genuine Master Audio does.
|
||||
|
||||
One mid-stream access unit is oversized so `ffmpeg -f spdif` overflows the
|
||||
burst and strips to core-only for `dtshd_fallback_time` (60s, i.e. the rest of
|
||||
the fixture) — the golden therefore also pins the strip-and-hold behavior.
|
||||
|
||||
Usage (from this directory):
|
||||
ffmpeg -y -f lavfi -i "aevalsrc=0.3*sin(2*PI*440*t)|0.3*sin(2*PI*554*t)|0.3*sin(2*PI*659*t)|0.2*sin(2*PI*220*t)|0.25*sin(2*PI*330*t)|0.25*sin(2*PI*392*t):s=48000:d=0.15" \
|
||||
-c:a dca -strict experimental -f dts /tmp/dts_core.dts
|
||||
python3 dtshd_fixture_generator.py /tmp/dts_core.dts
|
||||
ffmpeg -y -f dts -i dtshd_ma_access_units.bin -c:a copy \
|
||||
-f spdif -dtshd_rate 768000 dtshd_ma_iec61937_golden.bin
|
||||
"""
|
||||
|
||||
import struct
|
||||
import sys
|
||||
|
||||
CORE_SYNC = 0x7FFE8001
|
||||
EXSS_SYNC = 0x64582025
|
||||
|
||||
# Payload bytes past which a 32768-byte burst (512 samples at 48kHz on the
|
||||
# 768kHz HBR carrier) overflows: 32768 - 8 preamble - 12 start code/length.
|
||||
BURST_CAPACITY = 32768 - 8 - 12
|
||||
NORMAL_EXSS_SIZE = 2020
|
||||
# Large enough that core (1884) + EXSS exceeds the burst capacity.
|
||||
OVERSIZED_EXSS_SIZE = BURST_CAPACITY
|
||||
OVERSIZED_AU_INDEX = 4
|
||||
|
||||
|
||||
def build_exss(size: int) -> bytes:
|
||||
"""A minimal EXSS frame: sync, then the narrow (bHeaderSizeType=0) header.
|
||||
|
||||
Bit layout after the 32-bit sync: UserDefinedBits(8), nExtSSIndex(2),
|
||||
bHeaderSizeType(1), nuBits4Header(8) = header bytes - 1,
|
||||
nuBits4ExSSFsize(16) = frame bytes - 1. Everything else is padding the
|
||||
parser and packer never read.
|
||||
"""
|
||||
header_size = 16
|
||||
bits = 0
|
||||
bits = (bits << 8) | 0 # UserDefinedBits
|
||||
bits = (bits << 2) | 0 # nExtSSIndex
|
||||
bits = (bits << 1) | 0 # bHeaderSizeType
|
||||
bits = (bits << 8) | (header_size - 1)
|
||||
bits = (bits << 16) | (size - 1)
|
||||
packed = bits.to_bytes(5, "big") # 35 bits, left-aligned below
|
||||
body = bytearray(size)
|
||||
struct.pack_into(">I", body, 0, EXSS_SYNC)
|
||||
shifted = int.from_bytes(packed, "big") << (40 - 35)
|
||||
body[4:9] = shifted.to_bytes(5, "big")
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
core = open(sys.argv[1], "rb").read()
|
||||
out = bytearray()
|
||||
offset = 0
|
||||
index = 0
|
||||
while offset + 9 <= len(core):
|
||||
sync = struct.unpack_from(">I", core, offset)[0]
|
||||
assert sync == CORE_SYNC, hex(sync)
|
||||
b24 = (core[offset + 5] << 16) | (core[offset + 6] << 8) | core[offset + 7]
|
||||
fsize = ((b24 >> 4) & 0x3FFF) + 1
|
||||
out += core[offset : offset + fsize]
|
||||
exss_size = OVERSIZED_EXSS_SIZE if index == OVERSIZED_AU_INDEX else NORMAL_EXSS_SIZE
|
||||
out += build_exss(exss_size)
|
||||
offset += fsize
|
||||
index += 1
|
||||
open("dtshd_ma_access_units.bin", "wb").write(out)
|
||||
print(f"{index} access units, {len(out)} bytes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -58,4 +58,6 @@ dependencies {
|
||||
implementation("androidx.media3:media3-ui:1.11.0")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
// media3 Format/MimeTypes touch android.util in static initializers.
|
||||
testImplementation("org.robolectric:robolectric:4.16.1")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.edde746.plezy.libass.media
|
||||
|
||||
/**
|
||||
* Shared policy for embedded font attachments delivered to libass: which
|
||||
* attachment mime types are fonts, and the per-font/aggregate byte budgets
|
||||
* that keep a hostile container from ballooning the font store.
|
||||
*/
|
||||
object AssFonts {
|
||||
const val MAX_FONT_BYTES = 16L * 1024 * 1024
|
||||
const val MAX_TOTAL_FONT_BYTES = 32L * 1024 * 1024
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
/** Null to accept the font, or a human-readable rejection reason. */
|
||||
fun rejectionReason(size: Long, acceptedBytes: Long): String? = when {
|
||||
size > MAX_FONT_BYTES -> "per-font limit"
|
||||
size > MAX_TOTAL_FONT_BYTES - acceptedBytes -> "aggregate limit"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
-169
@@ -1,169 +0,0 @@
|
||||
package com.edde746.plezy.libass.media.extractor
|
||||
|
||||
import android.util.Log
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.ParserException
|
||||
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 var acceptedFontBytes = 0L
|
||||
private set
|
||||
|
||||
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 -> {
|
||||
if (contentSize < 0) {
|
||||
throw ParserException.createForMalformedContainer(
|
||||
"Negative Matroska attachment size",
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
val attachmentName = requireNotNull(currentAttachmentName)
|
||||
val attachmentMime = requireNotNull(currentAttachmentMime)
|
||||
if (attachmentMime !in fontMimeTypes) {
|
||||
input.skipFully(contentSize)
|
||||
return
|
||||
}
|
||||
if (contentSize == 0) {
|
||||
input.skipFully(0)
|
||||
return
|
||||
}
|
||||
|
||||
val size = contentSize.toLong()
|
||||
val rejectionReason = when {
|
||||
size > MAX_FONT_BYTES -> "per-font limit"
|
||||
size > MAX_TOTAL_FONT_BYTES - acceptedFontBytes -> "aggregate limit"
|
||||
else -> null
|
||||
}
|
||||
if (rejectionReason != null) {
|
||||
onFontRejected(contentSize, acceptedFontBytes, rejectionReason)
|
||||
input.skipFully(contentSize)
|
||||
return
|
||||
}
|
||||
|
||||
val data = ByteArray(contentSize)
|
||||
input.readFully(data, 0, contentSize)
|
||||
acceptedFontBytes += size
|
||||
assHandler.addFont(attachmentName, data)
|
||||
}
|
||||
else -> super.binaryElement(id, contentSize, input)
|
||||
}
|
||||
}
|
||||
|
||||
protected open fun onFontRejected(
|
||||
contentSize: Int,
|
||||
acceptedBytes: Long,
|
||||
reason: String
|
||||
) {
|
||||
Log.w(
|
||||
TAG,
|
||||
"Skipping embedded font: $reason (bytes=$contentSize, accepted=$acceptedBytes)"
|
||||
)
|
||||
}
|
||||
|
||||
private fun clearAttachment() {
|
||||
currentAttachmentName = null
|
||||
currentAttachmentMime = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AssMatroskaExtractor"
|
||||
internal const val MAX_FONT_BYTES = 16L * 1024 * 1024
|
||||
internal const val MAX_TOTAL_FONT_BYTES = 32L * 1024 * 1024
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -5,21 +5,22 @@ 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.
|
||||
* Wraps every text track with [AssTrackOutput] so embedded ASS dialogue
|
||||
* reaches libass. Install it on the raw-subtitle side of the output chain —
|
||||
* between the extractor and the SubtitleTranscodingExtractorOutput — so the
|
||||
* dialogue bytes are still unparsed when they pass through.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssSubtitleExtractorOutput(
|
||||
private val delegate: ExtractorOutput,
|
||||
private val assHandler: AssHandler,
|
||||
private val extractor: AssMatroskaExtractor
|
||||
private val assHandler: AssHandler
|
||||
) : 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)
|
||||
// We can't know at this time if the subtitle track is ASS or another
|
||||
// format, so we wrap every subtitle track; non-ASS tracks pass through.
|
||||
AssTrackOutput(delegate.track(id, type), assHandler::readTrackDialogue)
|
||||
} else {
|
||||
delegate.track(id, type)
|
||||
}
|
||||
|
||||
+98
-30
@@ -1,29 +1,50 @@
|
||||
package com.edde746.plezy.libass.media.text
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.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.io.EOFException
|
||||
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.
|
||||
* Feeds embedded ASS dialogue to libass while forwarding every sample
|
||||
* unchanged. Only used by the overlay renderer, which needs the start time and
|
||||
* duration of each dialogue line.
|
||||
*
|
||||
* Samples must arrive in the media3 MatroskaExtractor subtitle shape
|
||||
* `Dialogue: 0:00:00:00,<duration timecode>,<ReadOrder,Layer,Style,...>` — the
|
||||
* second field carries the sample *duration* (MatroskaExtractor patches
|
||||
* BlockDuration into it; the FFmpeg extractor writes the packet duration).
|
||||
* The extractor beneath must therefore emit raw subtitle samples: media3's
|
||||
* MatroskaExtractor with FLAG_EMIT_RAW_SUBTITLE_DATA, or the FFmpeg demuxer
|
||||
* path. Cue transcoding happens downstream of this wrapper.
|
||||
*/
|
||||
@UnstableApi
|
||||
class AssTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val assHandler: AssHandler,
|
||||
private val extractor: AssMatroskaExtractor
|
||||
) : TrackOutput by delegate {
|
||||
private val dialogueSink: DialogueSink
|
||||
) : TrackOutput {
|
||||
|
||||
/** Receives one dialogue line; mirrors AssHandler.readTrackDialogue. */
|
||||
fun interface DialogueSink {
|
||||
fun onDialogue(trackId: String?, startMs: Long, durationMs: Long, data: ByteArray, offset: Int, length: Int)
|
||||
}
|
||||
|
||||
private var isAss = false
|
||||
|
||||
private var trackId: String? = null
|
||||
|
||||
// Sample bytes buffered between sampleData and sampleMetadata; only
|
||||
// populated for ASS tracks.
|
||||
private var buf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var bufLen = 0
|
||||
private var readBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private val forwardParsable = ParsableByteArray()
|
||||
|
||||
override fun format(format: Format) {
|
||||
if (format.sampleMimeType == MimeTypes.TEXT_SSA || format.codecs == MimeTypes.TEXT_SSA) {
|
||||
isAss = true
|
||||
@@ -32,6 +53,34 @@ class AssTrackOutput(
|
||||
delegate.format(format)
|
||||
}
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (!isAss) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
if (readBuf.size < length) readBuf = ByteArray(length)
|
||||
val bytesRead = input.read(readBuf, 0, length)
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT) {
|
||||
if (!allowEndOfInput) throw EOFException()
|
||||
return C.RESULT_END_OF_INPUT
|
||||
}
|
||||
append(readBuf, bytesRead)
|
||||
forwardParsable.reset(readBuf, bytesRead)
|
||||
delegate.sampleData(forwardParsable, bytesRead, sampleDataPart)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (isAss) {
|
||||
ensureCapacity(bufLen + length)
|
||||
System.arraycopy(data.data, data.position, buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
@@ -39,26 +88,37 @@ class AssTrackOutput(
|
||||
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
|
||||
)
|
||||
if (isAss) {
|
||||
// offset counts bytes buffered after this sample; the slice math matches
|
||||
// media3's TrackOutput contract even though subtitle samples are
|
||||
// normally delivered one at a time with offset 0.
|
||||
val start = bufLen - offset - size
|
||||
if (timeUs != C.TIME_UNSET && start >= 0) {
|
||||
feedDialogue(timeUs, start, size)
|
||||
}
|
||||
if (offset == 0) bufLen = 0
|
||||
}
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
}
|
||||
|
||||
private fun feedDialogue(timeUs: Long, start: Int, size: Int) {
|
||||
val end = start + size
|
||||
val durationIndex = findTokenIndex(start, end, 1)
|
||||
val lineIndex = findTokenIndex(start, end, 2)
|
||||
if (durationIndex <= start || lineIndex <= durationIndex) return
|
||||
val rawDuration = buf.decodeToString(durationIndex, lineIndex - 1)
|
||||
val durationUs = parseTimecodeUs(rawDuration)
|
||||
if (durationUs == C.TIME_UNSET) return
|
||||
dialogueSink.onDialogue(
|
||||
trackId,
|
||||
timeUs / 1000,
|
||||
durationUs / 1000,
|
||||
buf,
|
||||
lineIndex,
|
||||
end - lineIndex
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseTimecodeUs(timeString: String): Long {
|
||||
val matcher = SSA_TIMECODE_PATTERN.matcher(timeString.trim { it <= ' ' })
|
||||
if (!matcher.matches()) {
|
||||
@@ -72,24 +132,32 @@ class AssTrackOutput(
|
||||
return timestampUs
|
||||
}
|
||||
|
||||
private fun findTokenIndex(array: ByteArray, tokenNumber: Int): Int {
|
||||
if (tokenNumber == 0) return 0
|
||||
/** Index just past the [tokenNumber]th comma inside [from, to), or [from]. */
|
||||
private fun findTokenIndex(from: Int, to: Int, tokenNumber: Int): Int {
|
||||
var tokensFound = 0
|
||||
array.forEachIndexed { index, byte ->
|
||||
if (byte == COMMA && ++tokensFound == tokenNumber) {
|
||||
for (index in from until to) {
|
||||
if (buf[index] == COMMA && ++tokensFound == tokenNumber) {
|
||||
return index + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
return from
|
||||
}
|
||||
|
||||
private val Long.isValidTs
|
||||
get() = this != C.TIME_UNSET
|
||||
private fun append(src: ByteArray, length: Int) {
|
||||
ensureCapacity(bufLen + length)
|
||||
System.arraycopy(src, 0, buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
private fun ensureCapacity(needed: Int) {
|
||||
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val SSA_TIMECODE_PATTERN: Pattern =
|
||||
Pattern.compile("""(?:(\d+):)?(\d+):(\d+)[:.](\d+)""")
|
||||
|
||||
const val COMMA = ','.code.toByte()
|
||||
const val INITIAL_BUFFER_SIZE = 1024
|
||||
}
|
||||
}
|
||||
|
||||
-156
@@ -1,156 +0,0 @@
|
||||
package com.edde746.plezy.libass.media.extractor
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.ParserException
|
||||
import androidx.media3.extractor.DefaultExtractorInput
|
||||
import androidx.media3.extractor.ExtractorInput
|
||||
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
|
||||
import com.edde746.plezy.libass.media.AssHandler
|
||||
import java.io.EOFException
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class AssMatroskaExtractorTest {
|
||||
|
||||
@Test
|
||||
fun smallFontIsDeliveredAndNonFontDoesNotConsumeBudget() {
|
||||
val handler = AssHandler()
|
||||
val extractor = extractor(handler)
|
||||
|
||||
attachment(extractor, "font/ttf")
|
||||
extractor.fileData(4, input(4, seed = 11))
|
||||
attachment(extractor, "application/octet-stream")
|
||||
extractor.fileData(9, input(9, seed = 22))
|
||||
|
||||
val pending = handler.fontStore.pendingSnapshot()
|
||||
assertEquals(1, pending.size)
|
||||
assertEquals("fixture-font", pending.single().first)
|
||||
assertArrayEquals(byteArrayOf(11, 12, 13, 14), pending.single().second)
|
||||
assertEquals(4L, extractor.acceptedFontBytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun perFontLimitAcceptsExactBoundaryAndSkipsOneByteOver() {
|
||||
val handler = AssHandler()
|
||||
val extractor = extractor(handler)
|
||||
val limit = AssMatroskaExtractor.MAX_FONT_BYTES.toInt()
|
||||
|
||||
attachment(extractor, "font/otf")
|
||||
extractor.fileData(limit, input(limit))
|
||||
attachment(extractor, "font/otf")
|
||||
extractor.fileData(limit + 1, input(limit + 1))
|
||||
|
||||
assertEquals(limit.toLong(), extractor.acceptedFontBytes)
|
||||
assertEquals(1, handler.fontStore.pendingSnapshot().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aggregateLimitIsDeterministicAcrossAttachmentEntries() {
|
||||
val handler = AssHandler()
|
||||
val extractor = extractor(handler)
|
||||
val perFont = AssMatroskaExtractor.MAX_FONT_BYTES.toInt()
|
||||
|
||||
repeat(2) {
|
||||
attachment(extractor, "font/ttf")
|
||||
extractor.fileData(perFont, input(perFont, seed = it))
|
||||
extractor.endAttachment()
|
||||
}
|
||||
attachment(extractor, "font/ttf")
|
||||
extractor.fileData(1, input(1))
|
||||
|
||||
assertEquals(AssMatroskaExtractor.MAX_TOTAL_FONT_BYTES, extractor.acceptedFontBytes)
|
||||
assertEquals(2, handler.fontStore.pendingSnapshot().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun negativeAndZeroSizesAllocateAndDeliverNothing() {
|
||||
val handler = AssHandler()
|
||||
val extractor = extractor(handler)
|
||||
attachment(extractor, "font/woff2")
|
||||
|
||||
assertThrows(ParserException::class.java) {
|
||||
extractor.fileData(-1, input(0))
|
||||
}
|
||||
attachment(extractor, "font/woff2")
|
||||
extractor.fileData(0, input(0))
|
||||
|
||||
assertEquals(0L, extractor.acceptedFontBytes)
|
||||
assertEquals(0, handler.fontStore.pendingSnapshot().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedReadDoesNotChargeAggregateBudgetOrDeliverPartialFont() {
|
||||
val handler = AssHandler()
|
||||
val extractor = extractor(handler)
|
||||
attachment(extractor, "font/ttf")
|
||||
|
||||
assertThrows(EOFException::class.java) {
|
||||
extractor.fileData(1024, input(1024, available = 4))
|
||||
}
|
||||
assertEquals(0L, extractor.acceptedFontBytes)
|
||||
assertEquals(0, handler.fontStore.pendingSnapshot().size)
|
||||
|
||||
attachment(extractor, "font/ttf")
|
||||
extractor.fileData(1024, input(1024))
|
||||
assertEquals(1024L, extractor.acceptedFontBytes)
|
||||
assertEquals(1, handler.fontStore.pendingSnapshot().size)
|
||||
}
|
||||
|
||||
private fun extractor(handler: AssHandler) = TestExtractor(handler)
|
||||
|
||||
private fun attachment(extractor: TestExtractor, mime: String) {
|
||||
extractor.setAttachment(mime)
|
||||
}
|
||||
|
||||
private class TestExtractor(handler: AssHandler) :
|
||||
AssMatroskaExtractor(
|
||||
DefaultSubtitleParserFactory(),
|
||||
handler
|
||||
) {
|
||||
fun setAttachment(mime: String) {
|
||||
startMasterElement(ID_ATTACHED_FILE, 0, 0)
|
||||
stringElement(ID_FILE_NAME, "fixture-font")
|
||||
stringElement(ID_FILE_MIME_TYPE, mime)
|
||||
}
|
||||
|
||||
fun fileData(contentSize: Int, input: ExtractorInput) {
|
||||
binaryElement(ID_FILE_DATA, contentSize, input)
|
||||
}
|
||||
|
||||
fun endAttachment() {
|
||||
endMasterElement(ID_ATTACHED_FILE)
|
||||
}
|
||||
|
||||
override fun onFontRejected(contentSize: Int, acceptedBytes: Long, reason: String) = Unit
|
||||
}
|
||||
|
||||
private fun input(
|
||||
declared: Int,
|
||||
available: Int = declared,
|
||||
seed: Int = 0
|
||||
): ExtractorInput = DefaultExtractorInput(
|
||||
PatternDataReader(available, seed),
|
||||
0,
|
||||
declared.toLong()
|
||||
)
|
||||
|
||||
private class PatternDataReader(
|
||||
private val size: Int,
|
||||
private val seed: Int
|
||||
) : DataReader {
|
||||
private var position = 0
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (position >= size) return C.RESULT_END_OF_INPUT
|
||||
val count = minOf(length, size - position)
|
||||
for (index in 0 until count) {
|
||||
buffer[offset + index] = ((seed + position + index) and 0xFF).toByte()
|
||||
}
|
||||
position += count
|
||||
return count
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
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.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* Spec for the dialogue feed both demuxer paths rely on: samples arrive in
|
||||
* media3's MatroskaExtractor shape ("Dialogue: 0:00:00:00,<duration>,<rest>")
|
||||
* and the sink must receive the sample start, the parsed duration, and the
|
||||
* payload after the second comma — while every byte is still forwarded
|
||||
* unchanged to the delegate.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class AssTrackOutputTest {
|
||||
|
||||
private class CapturedDialogue(val trackId: String?, val startMs: Long, val durationMs: Long, val line: ByteArray)
|
||||
|
||||
private class RecordingSink : AssTrackOutput.DialogueSink {
|
||||
val dialogues = mutableListOf<CapturedDialogue>()
|
||||
|
||||
override fun onDialogue(trackId: String?, startMs: Long, durationMs: Long, data: ByteArray, offset: Int, length: Int) {
|
||||
dialogues.add(CapturedDialogue(trackId, startMs, durationMs, data.copyOfRange(offset, offset + length)))
|
||||
}
|
||||
}
|
||||
|
||||
private class RecordingTrackOutput : TrackOutput {
|
||||
val formats = mutableListOf<Format>()
|
||||
val samples = mutableListOf<ByteArray>()
|
||||
val sampleTimes = mutableListOf<Long>()
|
||||
private var buf = ByteArray(1024)
|
||||
private var bufLen = 0
|
||||
|
||||
override fun format(format: Format) {
|
||||
formats.add(format)
|
||||
}
|
||||
|
||||
override fun sampleData(input: androidx.media3.common.DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {
|
||||
if (buf.size < bufLen + length) buf = buf.copyOf(bufLen + length)
|
||||
val read = input.read(buf, bufLen, length)
|
||||
if (read > 0) bufLen += read
|
||||
return read
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (buf.size < bufLen + length) buf = buf.copyOf(bufLen + length)
|
||||
data.readBytes(buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
|
||||
val start = bufLen - offset - size
|
||||
samples.add(buf.copyOfRange(start, start + size))
|
||||
sampleTimes.add(timeUs)
|
||||
if (offset == 0) bufLen = 0
|
||||
}
|
||||
}
|
||||
|
||||
private fun ssaFormat(id: String = "3"): Format = Format.Builder()
|
||||
.setId(id)
|
||||
.setSampleMimeType(MimeTypes.TEXT_SSA)
|
||||
.build()
|
||||
|
||||
private fun deliver(output: AssTrackOutput, sample: String, timeUs: Long) {
|
||||
val bytes = sample.toByteArray(Charsets.UTF_8)
|
||||
output.sampleData(ParsableByteArray(bytes), bytes.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
output.sampleMetadata(timeUs, C.BUFFER_FLAG_KEY_FRAME, bytes.size, 0, null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun feedsDialogueAndForwardsSampleUnchanged() {
|
||||
val sink = RecordingSink()
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = AssTrackOutput(delegate, sink)
|
||||
output.format(ssaFormat())
|
||||
|
||||
val sample = "Dialogue: 0:00:00:00,0:00:05:00,7,0,Default,,0,0,0,,Hello, world"
|
||||
deliver(output, sample, 90_000_000L)
|
||||
|
||||
assertEquals(1, sink.dialogues.size)
|
||||
val dialogue = sink.dialogues.first()
|
||||
assertEquals("3", dialogue.trackId)
|
||||
assertEquals(90_000L, dialogue.startMs)
|
||||
assertEquals(5_000L, dialogue.durationMs)
|
||||
// Payload after the second comma: the raw MKV/FFmpeg block, commas in the
|
||||
// text field intact.
|
||||
assertEquals("7,0,Default,,0,0,0,,Hello, world", dialogue.line.toString(Charsets.UTF_8))
|
||||
|
||||
// The delegate still receives the full untouched sample.
|
||||
assertEquals(1, delegate.samples.size)
|
||||
assertArrayEquals(sample.toByteArray(Charsets.UTF_8), delegate.samples.first())
|
||||
assertEquals(90_000_000L, delegate.sampleTimes.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ignoresNonAssTracksAndMalformedSamples() {
|
||||
val sink = RecordingSink()
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = AssTrackOutput(delegate, sink)
|
||||
|
||||
// SubRip track: forwarded, never fed to libass.
|
||||
output.format(Format.Builder().setId("1").setSampleMimeType(MimeTypes.APPLICATION_SUBRIP).build())
|
||||
deliver(output, "1\n00:00:00,000 --> 00:00:05,000\nplain text", 1_000_000L)
|
||||
assertTrue(sink.dialogues.isEmpty())
|
||||
assertEquals(1, delegate.samples.size)
|
||||
|
||||
// ASS track with an unparseable duration: forwarded, not fed.
|
||||
val assOutput = AssTrackOutput(RecordingTrackOutput(), sink)
|
||||
assOutput.format(ssaFormat())
|
||||
deliver(assOutput, "Dialogue: bogus", 1_000_000L)
|
||||
assertTrue(sink.dialogues.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handlesChunkedSampleDataAndDataReaderPath() {
|
||||
val sink = RecordingSink()
|
||||
val delegate = RecordingTrackOutput()
|
||||
val output = AssTrackOutput(delegate, sink)
|
||||
output.format(ssaFormat("0"))
|
||||
|
||||
val sample = "Dialogue: 0:00:00:00,0:00:01:50,1,0,Style,,0,0,0,,Line"
|
||||
val bytes = sample.toByteArray(Charsets.UTF_8)
|
||||
val split = bytes.size / 2
|
||||
output.sampleData(ParsableByteArray(bytes.copyOfRange(0, split)), split, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
val rest = bytes.copyOfRange(split, bytes.size)
|
||||
var consumed = 0
|
||||
val reader = androidx.media3.common.DataReader { buffer, offset, length ->
|
||||
if (consumed >= rest.size) {
|
||||
C.RESULT_END_OF_INPUT
|
||||
} else {
|
||||
val toRead = minOf(length, rest.size - consumed)
|
||||
System.arraycopy(rest, consumed, buffer, offset, toRead)
|
||||
consumed += toRead
|
||||
toRead
|
||||
}
|
||||
}
|
||||
while (consumed < rest.size) {
|
||||
output.sampleData(reader, rest.size - consumed, false, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
}
|
||||
output.sampleMetadata(0L, C.BUFFER_FLAG_KEY_FRAME, bytes.size, 0, null)
|
||||
|
||||
assertEquals(1, sink.dialogues.size)
|
||||
assertEquals(1_500L, sink.dialogues.first().durationMs)
|
||||
assertEquals("1,0,Style,,0,0,0,,Line", sink.dialogues.first().line.toString(Charsets.UTF_8))
|
||||
assertArrayEquals(bytes, delegate.samples.first())
|
||||
}
|
||||
}
|
||||
@@ -797,8 +797,8 @@
|
||||
isa = XCRemoteSwiftPackageReference;
|
||||
repositoryURL = "https://github.com/edde746/MPVKit";
|
||||
requirement = {
|
||||
kind = exactVersion;
|
||||
version = 1.0.21;
|
||||
kind = revision;
|
||||
revision = 0097fea015fe9b59bcfed866e61acb5896454bd4;
|
||||
};
|
||||
};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
|
||||
@@ -32,8 +32,7 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "1b8e5b2ba83f0b62c0eab6e90f36fa3dc5b4038f",
|
||||
"version" : "1.0.21"
|
||||
"revision" : "0097fea015fe9b59bcfed866e61acb5896454bd4"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -32,8 +32,7 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/edde746/MPVKit",
|
||||
"state" : {
|
||||
"revision" : "1b8e5b2ba83f0b62c0eab6e90f36fa3dc5b4038f",
|
||||
"version" : "1.0.21"
|
||||
"revision" : "0097fea015fe9b59bcfed866e61acb5896454bd4"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -5,50 +5,6 @@ import '../services/plex_auth_service.dart';
|
||||
import '../utils/json_utils.dart';
|
||||
import '../utils/url_utils.dart';
|
||||
|
||||
/// Identifier of a backend kind a [Connection] points at. Lighter-weight than
|
||||
/// [MediaBackend] for places that only care about persistence/auth shape
|
||||
/// (e.g. database column values).
|
||||
enum ConnectionKind {
|
||||
plex,
|
||||
jellyfin,
|
||||
emby;
|
||||
|
||||
String get id => switch (this) {
|
||||
ConnectionKind.plex => 'plex',
|
||||
ConnectionKind.jellyfin => 'jellyfin',
|
||||
ConnectionKind.emby => 'emby',
|
||||
};
|
||||
|
||||
static ConnectionKind fromId(String id) => switch (id) {
|
||||
'plex' => ConnectionKind.plex,
|
||||
'jellyfin' => ConnectionKind.jellyfin,
|
||||
'emby' => ConnectionKind.emby,
|
||||
_ => throw ArgumentError('Unknown ConnectionKind id: $id'),
|
||||
};
|
||||
|
||||
MediaBackend get backend => switch (this) {
|
||||
ConnectionKind.plex => MediaBackend.plex,
|
||||
ConnectionKind.jellyfin => MediaBackend.jellyfin,
|
||||
ConnectionKind.emby => MediaBackend.emby,
|
||||
};
|
||||
|
||||
/// The MediaBrowser dialect this kind speaks, or `null` for Plex.
|
||||
MediaBrowserDialect? get dialect => switch (this) {
|
||||
ConnectionKind.plex => null,
|
||||
ConnectionKind.jellyfin => MediaBrowserDialect.jellyfin,
|
||||
ConnectionKind.emby => MediaBrowserDialect.emby,
|
||||
};
|
||||
|
||||
static ConnectionKind fromDialect(MediaBrowserDialect dialect) => switch (dialect) {
|
||||
MediaBrowserDialect.jellyfin => ConnectionKind.jellyfin,
|
||||
MediaBrowserDialect.emby => ConnectionKind.emby,
|
||||
};
|
||||
}
|
||||
|
||||
/// Health snapshot for a connection. Updated by the orchestrator each time a
|
||||
/// session is established or refreshed.
|
||||
enum ConnectionStatus { unknown, online, offline, authError, disabled }
|
||||
|
||||
/// A media server connection — a unit of authentication the user added.
|
||||
///
|
||||
/// A `PlexAccountConnection` carries one Plex account + its discovered servers + an
|
||||
@@ -56,15 +12,14 @@ enum ConnectionStatus { unknown, online, offline, authError, disabled }
|
||||
/// user. Most users only ever add one connection.
|
||||
sealed class Connection {
|
||||
String get id;
|
||||
ConnectionKind get kind;
|
||||
MediaBackend get kind;
|
||||
String get displayName;
|
||||
ConnectionStatus get status;
|
||||
DateTime get createdAt;
|
||||
DateTime? get lastAuthenticatedAt;
|
||||
|
||||
/// Backend kind as a [MediaBackend] — for UI that branches on backend
|
||||
/// (badges, etc.). Just a passthrough to [kind.backend].
|
||||
MediaBackend get backend => kind.backend;
|
||||
/// Alias for [kind] kept for UI call sites that read "backend"
|
||||
/// (badges, etc.).
|
||||
MediaBackend get backend => kind;
|
||||
|
||||
/// Primary label shown in connection-list UIs. Plex shows the active
|
||||
/// profile/account name; Jellyfin shows the server name.
|
||||
@@ -90,9 +45,6 @@ class PlexAccountConnection extends Connection {
|
||||
@override
|
||||
final String id;
|
||||
|
||||
@override
|
||||
final ConnectionStatus status;
|
||||
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
|
||||
@@ -123,13 +75,12 @@ class PlexAccountConnection extends Connection {
|
||||
required this.accountLabel,
|
||||
this.activeProfile,
|
||||
this.servers = const [],
|
||||
this.status = ConnectionStatus.unknown,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
});
|
||||
|
||||
@override
|
||||
ConnectionKind get kind => ConnectionKind.plex;
|
||||
MediaBackend get kind => MediaBackend.plex;
|
||||
|
||||
@override
|
||||
String get displayName => activeProfile != null && activeProfile!.title.isNotEmpty
|
||||
@@ -150,7 +101,6 @@ class PlexAccountConnection extends Connection {
|
||||
PlexHomeUser? activeProfile,
|
||||
bool clearActiveProfile = false,
|
||||
List<PlexServer>? servers,
|
||||
ConnectionStatus? status,
|
||||
DateTime? createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
@@ -161,7 +111,6 @@ class PlexAccountConnection extends Connection {
|
||||
accountLabel: accountLabel ?? this.accountLabel,
|
||||
activeProfile: clearActiveProfile ? null : (activeProfile ?? this.activeProfile),
|
||||
servers: servers ?? this.servers,
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt ?? this.lastAuthenticatedAt,
|
||||
);
|
||||
@@ -181,7 +130,6 @@ class PlexAccountConnection extends Connection {
|
||||
factory PlexAccountConnection.fromConfigJson({
|
||||
required String id,
|
||||
required Map<String, Object?> json,
|
||||
required ConnectionStatus status,
|
||||
required DateTime createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
@@ -198,7 +146,6 @@ class PlexAccountConnection extends Connection {
|
||||
accountLabel: json['accountLabel'] as String? ?? 'Plex',
|
||||
activeProfile: activeProfile,
|
||||
servers: servers,
|
||||
status: status,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt,
|
||||
);
|
||||
@@ -212,9 +159,6 @@ class JellyfinConnection extends Connection {
|
||||
@override
|
||||
final String id;
|
||||
|
||||
@override
|
||||
final ConnectionStatus status;
|
||||
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
|
||||
@@ -276,14 +220,13 @@ class JellyfinConnection extends Connection {
|
||||
this.dialect = MediaBrowserDialect.jellyfin,
|
||||
this.isAdministrator = false,
|
||||
this.primaryImageTag,
|
||||
this.status = ConnectionStatus.unknown,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
}) : baseUrl = canonicalizeBaseUrl(baseUrl),
|
||||
baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
|
||||
|
||||
@override
|
||||
ConnectionKind get kind => ConnectionKind.fromDialect(dialect);
|
||||
MediaBackend get kind => dialect.backend;
|
||||
|
||||
@override
|
||||
String get displayName => '$userName · $serverName';
|
||||
@@ -338,7 +281,6 @@ class JellyfinConnection extends Connection {
|
||||
/// a refresh must be able to null the cached value — a bare
|
||||
/// `primaryImageTag: null` is indistinguishable from "unchanged".
|
||||
bool clearPrimaryImageTag = false,
|
||||
ConnectionStatus? status,
|
||||
DateTime? createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
}) {
|
||||
@@ -356,7 +298,6 @@ class JellyfinConnection extends Connection {
|
||||
dialect: dialect ?? this.dialect,
|
||||
isAdministrator: isAdministrator ?? this.isAdministrator,
|
||||
primaryImageTag: clearPrimaryImageTag ? null : (primaryImageTag ?? this.primaryImageTag),
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt ?? this.lastAuthenticatedAt,
|
||||
);
|
||||
@@ -384,7 +325,6 @@ class JellyfinConnection extends Connection {
|
||||
factory JellyfinConnection.fromConfigJson({
|
||||
required String id,
|
||||
required Map<String, Object?> json,
|
||||
required ConnectionStatus status,
|
||||
required DateTime createdAt,
|
||||
DateTime? lastAuthenticatedAt,
|
||||
MediaBrowserDialect dialect = MediaBrowserDialect.jellyfin,
|
||||
@@ -408,7 +348,6 @@ class JellyfinConnection extends Connection {
|
||||
deviceId: json['deviceId'] as String? ?? '',
|
||||
isAdministrator: json['isAdministrator'] as bool? ?? false,
|
||||
primaryImageTag: normalizePrimaryImageTag(json['primaryImageTag']),
|
||||
status: status,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt,
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import '../services/storage_service.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'connection.dart';
|
||||
import 'connection_registry.dart';
|
||||
import 'plex_account_setup.dart';
|
||||
|
||||
/// One-shot helpers that bridge between the legacy single-Plex-account
|
||||
/// SharedPreferences state (`StorageService.plexToken` +
|
||||
@@ -97,25 +98,12 @@ class ConnectionBootstrap {
|
||||
if (existing.whereType<PlexAccountConnection>().isNotEmpty) return;
|
||||
|
||||
try {
|
||||
final auth = await PlexAuthService.create();
|
||||
try {
|
||||
final info = await auth.getUserInfo(devToken);
|
||||
final servers = await auth.fetchServers(devToken);
|
||||
final clientId = await storage.getOrCreateClientIdentifier();
|
||||
final conn = PlexAccountConnection(
|
||||
id: 'plex.$clientId',
|
||||
accountToken: devToken,
|
||||
clientIdentifier: clientId,
|
||||
accountLabel: (info['username'] as String?) ?? (info['email'] as String?) ?? 'Plex',
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
);
|
||||
await connectionRegistry.upsert(conn);
|
||||
appLogger.i('Seeded Plex account from PLEX_TOKEN dart-define as ${conn.id}');
|
||||
} finally {
|
||||
auth.dispose();
|
||||
}
|
||||
// The dev seed always keys its row by the device client id and aborts
|
||||
// on an identity-lookup failure — a bad PLEX_TOKEN must not seed a
|
||||
// mislabelled row.
|
||||
final build = await buildPlexAccountConnection(devToken, keyByAccountUuid: false, tolerateUserInfoFailure: false);
|
||||
await connectionRegistry.upsert(build.connection);
|
||||
appLogger.i('Seeded Plex account from PLEX_TOKEN dart-define as ${build.connection.id}');
|
||||
} catch (e, st) {
|
||||
appLogger.w('PLEX_TOKEN seed failed', error: e, stackTrace: st);
|
||||
}
|
||||
@@ -138,31 +126,17 @@ class ConnectionBootstrap {
|
||||
}
|
||||
|
||||
try {
|
||||
final clientId = await storage.getOrCreateClientIdentifier();
|
||||
final servers = await serverRegistry.getServers();
|
||||
|
||||
String accountLabel = 'Plex';
|
||||
String accountUuid = '';
|
||||
try {
|
||||
final info = await _plexUserInfoFetcher(token);
|
||||
accountLabel = (info['username'] as String?) ?? (info['email'] as String?) ?? 'Plex';
|
||||
accountUuid = (info['uuid'] as String?)?.trim() ?? '';
|
||||
} catch (e) {
|
||||
appLogger.d('Plex migration: account label lookup failed (using fallback): $e');
|
||||
}
|
||||
|
||||
final conn = PlexAccountConnection(
|
||||
id: 'plex.${accountUuid.isNotEmpty ? accountUuid : clientId}',
|
||||
accountToken: token,
|
||||
clientIdentifier: clientId,
|
||||
accountLabel: accountLabel,
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
final build = await buildPlexAccountConnection(
|
||||
token,
|
||||
clientIdentifier: await storage.getOrCreateClientIdentifier(),
|
||||
fetchUserInfo: _plexUserInfoFetcher,
|
||||
// The migration wraps the cached legacy server list; a network server
|
||||
// fetch could fail exactly when the migration must succeed offline.
|
||||
fetchServers: (_) => serverRegistry.getServers(),
|
||||
);
|
||||
await connectionRegistry.upsert(conn);
|
||||
appLogger.i('Migrated legacy Plex account into ConnectionRegistry as ${conn.id}');
|
||||
return conn;
|
||||
await connectionRegistry.upsert(build.connection);
|
||||
appLogger.i('Migrated legacy Plex account into ConnectionRegistry as ${build.connection.id}');
|
||||
return build.connection;
|
||||
} catch (e, st) {
|
||||
appLogger.w('Plex account migration failed', error: e, stackTrace: st);
|
||||
return null;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
|
||||
import '../database/app_database.dart';
|
||||
import '../media/media_backend.dart';
|
||||
import '../services/credential_vault.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'connection.dart';
|
||||
@@ -11,13 +13,23 @@ import 'connection.dart';
|
||||
/// CRUD over the persisted [Connections] table. The registry is the source
|
||||
/// of truth for which connections the user has added; the runtime
|
||||
/// `MultiServerManager` populates per-server clients from these records.
|
||||
///
|
||||
/// Single-connection users get a default automatically — power users with
|
||||
/// multiple connections can override it via [setDefault].
|
||||
class ConnectionRegistry {
|
||||
ConnectionRegistry(this._db);
|
||||
|
||||
final AppDatabase _db;
|
||||
static const DeepCollectionEquality _configEquality = DeepCollectionEquality();
|
||||
|
||||
final Expando<Map<String, Object?>> _decryptedConfigs = Expando<Map<String, Object?>>(
|
||||
'ConnectionRegistry.decryptedConfigs',
|
||||
);
|
||||
|
||||
/// Compares the decrypted persisted config projections retained while rows
|
||||
/// are decoded. The fallback covers models supplied outside this registry.
|
||||
bool hasSameConfig(Connection a, Connection b) {
|
||||
final aConfig = _decryptedConfigs[a] ??= a.toConfigJson();
|
||||
final bConfig = _decryptedConfigs[b] ??= b.toConfigJson();
|
||||
return _configEquality.equals(aConfig, bConfig);
|
||||
}
|
||||
|
||||
/// Emits the current set of connections after every mutation. Drift's
|
||||
/// `watch()` provides this for free.
|
||||
@@ -40,33 +52,19 @@ class ConnectionRegistry {
|
||||
return _rowToConnection(row);
|
||||
}
|
||||
|
||||
/// Insert or replace [connection]. If this is the first stored connection
|
||||
/// it is automatically marked default; re-upserting an existing row keeps
|
||||
/// the row's current `isDefault` and `createdAt` (so token/metadata
|
||||
/// refreshes don't clear the default flag or restamp creation order).
|
||||
/// Insert or replace [connection]. Re-upserting an existing row keeps the
|
||||
/// row's current `createdAt` (so token/metadata refreshes don't restamp
|
||||
/// creation order).
|
||||
///
|
||||
/// Creation order is behaviour, not bookkeeping: it decides which
|
||||
/// connection lends a profile its picture, and `remove` promotes the oldest
|
||||
/// remaining row to default. Re-authenticating rebuilds the model with
|
||||
/// `DateTime.now()` and reuses the same stable id, so without this the
|
||||
/// originally-first connection would jump to last on every re-sign-in.
|
||||
/// connection lends a profile its picture. Re-authenticating rebuilds the
|
||||
/// model with `DateTime.now()` and reuses the same stable id, so without
|
||||
/// this the originally-first connection would jump to last on every
|
||||
/// re-sign-in.
|
||||
Future<void> upsert(Connection connection) async {
|
||||
await _db.runIdentityMutation(() async {
|
||||
final existing = await (_db.select(_db.connections)..where((t) => t.id.equals(connection.id))).getSingleOrNull();
|
||||
final bool isDefault;
|
||||
final int createdAt;
|
||||
if (existing != null) {
|
||||
isDefault = existing.isDefault;
|
||||
createdAt = existing.createdAt;
|
||||
} else {
|
||||
final any =
|
||||
await (_db.selectOnly(_db.connections)
|
||||
..addColumns([_db.connections.id])
|
||||
..limit(1))
|
||||
.getSingleOrNull();
|
||||
isDefault = any == null;
|
||||
createdAt = connection.createdAt.millisecondsSinceEpoch;
|
||||
}
|
||||
final createdAt = existing?.createdAt ?? connection.createdAt.millisecondsSinceEpoch;
|
||||
final protectedConfig = await CredentialVault.protectConnectionConfig(
|
||||
connection.kind.id,
|
||||
connection.toConfigJson(),
|
||||
@@ -76,7 +74,6 @@ class ConnectionRegistry {
|
||||
kind: Value(connection.kind.id),
|
||||
displayName: Value(connection.displayName),
|
||||
configJson: Value(jsonEncode(protectedConfig)),
|
||||
isDefault: Value(isDefault),
|
||||
createdAt: Value(createdAt),
|
||||
lastAuthenticatedAt: Value(connection.lastAuthenticatedAt?.millisecondsSinceEpoch),
|
||||
);
|
||||
@@ -85,44 +82,14 @@ class ConnectionRegistry {
|
||||
appLogger.d('ConnectionRegistry: upserted ${connection.kind.id}/${connection.id}');
|
||||
}
|
||||
|
||||
/// Remove a stored connection. If the removed row was the default, the
|
||||
/// oldest remaining connection (if any) becomes default.
|
||||
/// Remove a stored connection.
|
||||
Future<void> remove(String id) async {
|
||||
await _db.runIdentityMutation(() async {
|
||||
await (_db.delete(_db.connections)..where((t) => t.id.equals(id))).go();
|
||||
final remaining = await (_db.select(_db.connections)..orderBy([(t) => OrderingTerm.asc(t.createdAt)])).get();
|
||||
if (remaining.isNotEmpty && !remaining.any((r) => r.isDefault)) {
|
||||
await (_db.update(
|
||||
_db.connections,
|
||||
)..where((t) => t.id.equals(remaining.first.id))).write(const ConnectionsCompanion(isDefault: Value(true)));
|
||||
}
|
||||
});
|
||||
appLogger.d('ConnectionRegistry: removed $id');
|
||||
}
|
||||
|
||||
/// Set [id] as the default connection. Clears the flag on all others.
|
||||
Future<void> setDefault(String id) async {
|
||||
await _db.runIdentityMutation(() async {
|
||||
await _db.transaction(() async {
|
||||
await _db.update(_db.connections).write(const ConnectionsCompanion(isDefault: Value(false)));
|
||||
await (_db.update(
|
||||
_db.connections,
|
||||
)..where((t) => t.id.equals(id))).write(const ConnectionsCompanion(isDefault: Value(true)));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Update only the auth-related metadata on an existing row (token,
|
||||
/// `lastAuthenticatedAt`). Used by the auth flow after a successful
|
||||
/// silent refresh without touching the rest of the config.
|
||||
Future<void> recordAuthSuccess(String id, DateTime at) async {
|
||||
await _db.runIdentityMutation(() async {
|
||||
await (_db.update(_db.connections)..where((t) => t.id.equals(id))).write(
|
||||
ConnectionsCompanion(lastAuthenticatedAt: Value(at.millisecondsSinceEpoch)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
await _db.runIdentityMutation(() async {
|
||||
await _db.delete(_db.connections).go();
|
||||
@@ -147,29 +114,28 @@ class ConnectionRegistry {
|
||||
Future<Connection?> _rowToConnection(ConnectionRow row) async {
|
||||
try {
|
||||
final json = jsonDecode(row.configJson) as Map<String, dynamic>;
|
||||
final kind = ConnectionKind.fromId(row.kind);
|
||||
final kind = MediaBackend.fromId(row.kind);
|
||||
final revealed = await CredentialVault.revealConnectionConfig(kind.id, json);
|
||||
final createdAt = DateTime.fromMillisecondsSinceEpoch(row.createdAt);
|
||||
final lastAuth = row.lastAuthenticatedAt == null
|
||||
? null
|
||||
: DateTime.fromMillisecondsSinceEpoch(row.lastAuthenticatedAt!);
|
||||
final connection = switch (kind) {
|
||||
ConnectionKind.plex => PlexAccountConnection.fromConfigJson(
|
||||
MediaBackend.plex => PlexAccountConnection.fromConfigJson(
|
||||
id: row.id,
|
||||
json: revealed.config,
|
||||
status: ConnectionStatus.unknown,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuth,
|
||||
),
|
||||
ConnectionKind.jellyfin || ConnectionKind.emby => JellyfinConnection.fromConfigJson(
|
||||
MediaBackend.jellyfin || MediaBackend.emby => JellyfinConnection.fromConfigJson(
|
||||
id: row.id,
|
||||
json: revealed.config,
|
||||
status: ConnectionStatus.unknown,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuth,
|
||||
dialect: kind.dialect!,
|
||||
),
|
||||
};
|
||||
_decryptedConfigs[connection] = revealed.config;
|
||||
if (revealed.migrated) {
|
||||
await upsert(connection);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,77 @@ typedef PlexAccountRegistration = ({
|
||||
String email,
|
||||
});
|
||||
|
||||
/// Result of [buildPlexAccountConnection]: the assembled connection plus the
|
||||
/// raw identity fields callers fold into their own records and dedup scans.
|
||||
typedef PlexAccountBuild = ({PlexAccountConnection connection, String username, String email, String accountUuid});
|
||||
|
||||
/// Shared token → [PlexAccountConnection] pipeline: resolve the plex.tv
|
||||
/// account identity, list the account's servers, and assemble a connection
|
||||
/// row stamped "now". [registerPlexAccountFromToken] and both
|
||||
/// [ConnectionBootstrap] entry points (the PLEX_TOKEN dev seed and the
|
||||
/// legacy-token migration) funnel through here so the id/label policy can't
|
||||
/// drift. Each caller keeps its delta via the knobs:
|
||||
///
|
||||
/// - [clientIdentifier] is persisted on the row and keys it when the account
|
||||
/// uuid is unavailable. `null` uses the short-lived [PlexAuthService]'s own
|
||||
/// per-device id (the same [StorageService]-backed value).
|
||||
/// - [fetchUserInfo]/[fetchServers] override the identity/server sources —
|
||||
/// the legacy migration injects a test seam and the cached legacy server
|
||||
/// list. When both are given (and [clientIdentifier] is set) no
|
||||
/// [PlexAuthService] is created at all.
|
||||
/// - [keyByAccountUuid]: the dev seed keys its row by client id even when
|
||||
/// the account uuid is known.
|
||||
/// - [tolerateUserInfoFailure]: sign-in and migration fall back to a
|
||||
/// client-id-keyed row when the identity lookup fails; the dev seed aborts
|
||||
/// instead of seeding a mislabelled row.
|
||||
Future<PlexAccountBuild> buildPlexAccountConnection(
|
||||
String token, {
|
||||
String? clientIdentifier,
|
||||
Future<Map<String, dynamic>> Function(String token)? fetchUserInfo,
|
||||
Future<List<PlexServer>> Function(String token)? fetchServers,
|
||||
bool keyByAccountUuid = true,
|
||||
bool tolerateUserInfoFailure = true,
|
||||
}) async {
|
||||
PlexAuthService? auth;
|
||||
try {
|
||||
if (clientIdentifier == null || fetchUserInfo == null || fetchServers == null) {
|
||||
auth = await PlexAuthService.create();
|
||||
}
|
||||
// Account identity from plex.tv — the uuid is what makes multi-account
|
||||
// work (the clientIdentifier is per-device and identical for every Plex
|
||||
// account on this install). Falls back to the client identifier only
|
||||
// when the user-info call fails outright; a later successful sign-in
|
||||
// migrates that legacy row via [_migrateLegacyClientIdRow].
|
||||
String username = '';
|
||||
String email = '';
|
||||
String accountUuid = '';
|
||||
try {
|
||||
final info = await (fetchUserInfo ?? auth!.getUserInfo)(token);
|
||||
username = (info['username'] as String?) ?? '';
|
||||
email = (info['email'] as String?) ?? '';
|
||||
accountUuid = (info['uuid'] as String?)?.trim() ?? '';
|
||||
} catch (e) {
|
||||
if (!tolerateUserInfoFailure) rethrow;
|
||||
appLogger.d('Plex user-info lookup failed (using fallback identity): $e');
|
||||
}
|
||||
|
||||
final servers = await (fetchServers ?? auth!.fetchServers)(token);
|
||||
final clientId = clientIdentifier ?? auth!.clientIdentifier;
|
||||
final connection = PlexAccountConnection(
|
||||
id: 'plex.${keyByAccountUuid && accountUuid.isNotEmpty ? accountUuid : clientId}',
|
||||
accountToken: token,
|
||||
clientIdentifier: clientId,
|
||||
accountLabel: username.isNotEmpty ? username : (email.isNotEmpty ? email : 'Plex'),
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
);
|
||||
return (connection: connection, username: username, email: email, accountUuid: accountUuid);
|
||||
} finally {
|
||||
auth?.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared post-auth pipeline for a fresh plex.tv [token]: resolve the
|
||||
/// account identity, persist the [PlexAccountConnection] (folding in a
|
||||
/// legacy client-id-keyed row from an earlier failed identity lookup), and
|
||||
@@ -31,66 +102,36 @@ Future<PlexAccountRegistration> registerPlexAccountFromToken({
|
||||
required StorageService storage,
|
||||
required PlexHomeService plexHome,
|
||||
}) async {
|
||||
final auth = await PlexAuthService.create();
|
||||
try {
|
||||
// Account identity from plex.tv — the uuid is what makes multi-account
|
||||
// work (the clientIdentifier is per-device and identical for every Plex
|
||||
// account on this install). Falls back to the client identifier only
|
||||
// when the user-info call fails outright; a later successful sign-in
|
||||
// migrates that legacy row below.
|
||||
String username = '';
|
||||
String email = '';
|
||||
String accountUuid = '';
|
||||
try {
|
||||
final info = await auth.getUserInfo(token);
|
||||
username = (info['username'] as String?) ?? '';
|
||||
email = (info['email'] as String?) ?? '';
|
||||
accountUuid = (info['uuid'] as String?)?.trim() ?? '';
|
||||
} catch (e) {
|
||||
appLogger.d('getUserInfo after Plex sign-in failed (using fallback identity): $e');
|
||||
}
|
||||
final build = await buildPlexAccountConnection(token);
|
||||
final connection = build.connection;
|
||||
final legacyId = 'plex.${connection.clientIdentifier}';
|
||||
final existedBefore =
|
||||
await connections.get(connection.id) != null ||
|
||||
(build.accountUuid.isNotEmpty &&
|
||||
legacyId != connection.id &&
|
||||
await connections.get(legacyId) is PlexAccountConnection);
|
||||
await connections.upsert(connection);
|
||||
|
||||
final servers = await auth.fetchServers(token);
|
||||
final connection = PlexAccountConnection(
|
||||
id: 'plex.${accountUuid.isNotEmpty ? accountUuid : auth.clientIdentifier}',
|
||||
accountToken: token,
|
||||
clientIdentifier: auth.clientIdentifier,
|
||||
accountLabel: username.isNotEmpty ? username : (email.isNotEmpty ? email : 'Plex'),
|
||||
servers: servers,
|
||||
createdAt: DateTime.now(),
|
||||
lastAuthenticatedAt: DateTime.now(),
|
||||
if (build.accountUuid.isNotEmpty) {
|
||||
await _migrateLegacyClientIdRow(
|
||||
replacement: connection,
|
||||
clientIdentifier: connection.clientIdentifier,
|
||||
connections: connections,
|
||||
profileConnections: profileConnections,
|
||||
storage: storage,
|
||||
);
|
||||
final legacyId = 'plex.${auth.clientIdentifier}';
|
||||
final existedBefore =
|
||||
await connections.get(connection.id) != null ||
|
||||
(accountUuid.isNotEmpty &&
|
||||
legacyId != connection.id &&
|
||||
await connections.get(legacyId) is PlexAccountConnection);
|
||||
await connections.upsert(connection);
|
||||
|
||||
if (accountUuid.isNotEmpty) {
|
||||
await _migrateLegacyClientIdRow(
|
||||
replacement: connection,
|
||||
clientIdentifier: auth.clientIdentifier,
|
||||
connections: connections,
|
||||
profileConnections: profileConnections,
|
||||
storage: storage,
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch home users now so pickers surface the account's virtual
|
||||
// profiles immediately.
|
||||
final homeUsersFetched = await plexHome.refresh(connection);
|
||||
return (
|
||||
connection: connection,
|
||||
homeUsersFetched: homeUsersFetched,
|
||||
existedBefore: existedBefore,
|
||||
username: username,
|
||||
email: email,
|
||||
);
|
||||
} finally {
|
||||
auth.dispose();
|
||||
}
|
||||
|
||||
// Fetch home users now so pickers surface the account's virtual
|
||||
// profiles immediately.
|
||||
final homeUsersFetched = await plexHome.refresh(connection);
|
||||
return (
|
||||
connection: connection,
|
||||
homeUsersFetched: homeUsersFetched,
|
||||
existedBefore: existedBefore,
|
||||
username: build.username,
|
||||
email: build.email,
|
||||
);
|
||||
}
|
||||
|
||||
/// A row keyed by the per-device client identifier (created when an earlier
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Dense BMP ranks per DUCET (Unicode 13.0) + pinned CLDR CJK radical-stroke.
|
||||
/// Each code unit stores rank + 1; zero means absent.
|
||||
/// Katakana sorts before hiragana (CLDR root tailoring).
|
||||
/// Generated by scripts/generate_ducet_ranks.dart — do not edit.
|
||||
/// Generated by scripts/codegen/generate_ducet_ranks.dart — do not edit.
|
||||
library;
|
||||
|
||||
const String _ducetRanks =
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by dart run scripts/generate_hid_key_labels.dart from scripts/data/hid_key_labels.json; do not edit by hand.
|
||||
// Generated by dart run scripts/codegen/generate_hid_key_labels.dart from scripts/codegen/data/hid_key_labels.json; do not edit by hand.
|
||||
|
||||
/// Human-readable labels for physical keyboard keys, keyed by USB HID usage code.
|
||||
const hidKeyLabels = <int, String>{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by dart run scripts/generate_iso_639_data.dart from scripts/data/iso_639_codes.json; do not edit by hand.
|
||||
// Generated by dart run scripts/codegen/generate_iso_639_data.dart from scripts/codegen/data/iso_639_codes.json; do not edit by hand.
|
||||
|
||||
class LanguageEntry {
|
||||
final String code1;
|
||||
|
||||
@@ -37,15 +37,6 @@ enum OfflineActionType {
|
||||
OfflineActionType.watched => 'watched',
|
||||
OfflineActionType.unwatched => 'unwatched',
|
||||
};
|
||||
|
||||
/// Inverse of [id]. Throws on unknown so a typo in production doesn't
|
||||
/// silently fall back to the wrong action.
|
||||
static OfflineActionType fromId(String id) => switch (id) {
|
||||
'progress' => OfflineActionType.progress,
|
||||
'watched' => OfflineActionType.watched,
|
||||
'unwatched' => OfflineActionType.unwatched,
|
||||
_ => throw ArgumentError('Unknown OfflineActionType id: $id'),
|
||||
};
|
||||
}
|
||||
|
||||
final class AppDatabaseBootstrap {
|
||||
@@ -81,7 +72,6 @@ class AppDatabase extends _$AppDatabase {
|
||||
AppDatabase._withRecovery(super.e, this._recoveryStore);
|
||||
|
||||
final TvosDatabaseRecoveryStore? _recoveryStore;
|
||||
final SerialFutureQueue _durabilityQueue = SerialFutureQueue();
|
||||
static final Object _durabilityZoneKey = Object();
|
||||
static final SerialFutureQueue _tvosRecoveryQueue = SerialFutureQueue();
|
||||
|
||||
@@ -156,12 +146,10 @@ class AppDatabase extends _$AppDatabase {
|
||||
final store = _recoveryStore;
|
||||
if (store == null || !store.isTvos) return Future<void>.value();
|
||||
|
||||
return _durabilityQueue.run(
|
||||
() => _tvosRecoveryQueue.run(
|
||||
() => store.acknowledgeRecoveryRequired(
|
||||
readIdentity: _readProtectedIdentityRecoveryRows,
|
||||
readPending: _readPendingRecoveryRows,
|
||||
),
|
||||
return _tvosRecoveryQueue.run(
|
||||
() => store.acknowledgeRecoveryRequired(
|
||||
readIdentity: _readProtectedIdentityRecoveryRows,
|
||||
readPending: _readPendingRecoveryRows,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -175,17 +163,15 @@ class AppDatabase extends _$AppDatabase {
|
||||
if (store == null || !store.isTvos) return mutation();
|
||||
if (Zone.current[_durabilityZoneKey] == this) return mutation();
|
||||
|
||||
return _durabilityQueue.run(
|
||||
() => _tvosRecoveryQueue.run(
|
||||
() => runZoned(
|
||||
() => store.runDurableMutation(
|
||||
group: group,
|
||||
mutation: mutation,
|
||||
readIdentity: _readProtectedIdentityRecoveryRows,
|
||||
readPending: _readPendingRecoveryRows,
|
||||
),
|
||||
zoneValues: {_durabilityZoneKey: this},
|
||||
return _tvosRecoveryQueue.run(
|
||||
() => runZoned(
|
||||
() => store.runDurableMutation(
|
||||
group: group,
|
||||
mutation: mutation,
|
||||
readIdentity: _readProtectedIdentityRecoveryRows,
|
||||
readPending: _readPendingRecoveryRows,
|
||||
),
|
||||
zoneValues: {_durabilityZoneKey: this},
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -324,6 +310,14 @@ class AppDatabase extends _$AppDatabase {
|
||||
});
|
||||
}
|
||||
|
||||
/// Columns that once existed in a snapshotted table and may still appear in
|
||||
/// committed recovery images written by older builds. They are stripped
|
||||
/// before the strict round-trip check in [_decodeRecoveryRow] so retiring a
|
||||
/// column does not brick restore on devices holding a pre-retirement image.
|
||||
static const Map<String, Set<String>> _retiredRecoveryColumns = {
|
||||
'connections': {'isDefault'},
|
||||
};
|
||||
|
||||
static List<T> _decodeRecoveryRows<T extends DataClass>(
|
||||
Map<String, Object?> group,
|
||||
String key,
|
||||
@@ -331,9 +325,21 @@ class AppDatabase extends _$AppDatabase {
|
||||
) {
|
||||
final value = group[key];
|
||||
if (value is! List) throw _invalidRecoveryImage;
|
||||
final retired = _retiredRecoveryColumns[key];
|
||||
return [
|
||||
for (final row in value)
|
||||
if (row is Map<String, dynamic>) _decodeRecoveryRow(row, fromJson) else throw _invalidRecoveryImage,
|
||||
if (row is Map<String, dynamic>)
|
||||
_decodeRecoveryRow(
|
||||
retired == null
|
||||
? row
|
||||
: {
|
||||
for (final entry in row.entries)
|
||||
if (!retired.contains(entry.key)) entry.key: entry.value,
|
||||
},
|
||||
fromJson,
|
||||
)
|
||||
else
|
||||
throw _invalidRecoveryImage,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -359,7 +365,7 @@ class AppDatabase extends _$AppDatabase {
|
||||
static const FormatException _invalidRecoveryImage = FormatException('Invalid tvOS database recovery image');
|
||||
|
||||
@override
|
||||
int get schemaVersion => 20;
|
||||
int get schemaVersion => 21;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
@@ -725,6 +731,10 @@ class AppDatabase extends _$AppDatabase {
|
||||
() => m.create(idxSyncRuleDownloadsProfileKey),
|
||||
);
|
||||
}
|
||||
if (from < 21) {
|
||||
appLogger.i('Dropping unused Connections.isDefault column (v21 migration)');
|
||||
await m.alterTable(TableMigration(connections));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1057,25 +1067,6 @@ class AppDatabase extends _$AppDatabase {
|
||||
});
|
||||
}
|
||||
|
||||
/// Delete a specific watch action outside a snapshotted replay.
|
||||
Future<void> deleteWatchAction(int id) {
|
||||
return _runPendingMutation(() async {
|
||||
await (delete(offlineWatchProgress)..where((t) => t.id.equals(id))).go();
|
||||
});
|
||||
}
|
||||
|
||||
/// Update retry state outside a snapshotted replay.
|
||||
Future<void> updateSyncAttempt(int id, String? errorMessage) {
|
||||
return _runPendingMutation(() async {
|
||||
final existing = await (select(offlineWatchProgress)..where((t) => t.id.equals(id))).getSingleOrNull();
|
||||
if (existing == null) return;
|
||||
|
||||
await (update(offlineWatchProgress)..where((t) => t.id.equals(id))).write(
|
||||
OfflineWatchProgressCompanion(syncAttempts: Value(existing.syncAttempts + 1), lastError: Value(errorMessage)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Get count of pending sync items
|
||||
Future<int> getPendingSyncCount({String? profileId, int? maxSyncAttempts}) async {
|
||||
final query = selectOnly(offlineWatchProgress)..addColumns([offlineWatchProgress.id.count()]);
|
||||
@@ -1275,9 +1266,6 @@ class AppDatabase extends _$AppDatabase {
|
||||
Future<void> updateSyncRuleEnabled(String globalKey, bool enabled) =>
|
||||
_writeSyncRule(globalKey, SyncRulesCompanion(enabled: Value(enabled)));
|
||||
|
||||
Future<void> updateSyncRuleLastExecuted(String globalKey) =>
|
||||
_writeSyncRule(globalKey, SyncRulesCompanion(lastExecutedAt: Value(DateTime.now().millisecondsSinceEpoch)));
|
||||
|
||||
Future<void> completeSyncRuleExecution(String globalKey) {
|
||||
return (update(syncRules)..where((t) => t.globalKey.equals(globalKey))).write(
|
||||
SyncRulesCompanion(
|
||||
|
||||
@@ -2023,6 +2023,18 @@ class $ApiCacheTable extends ApiCache
|
||||
type: DriftSqlType.string,
|
||||
requiredDuringInsert: true,
|
||||
);
|
||||
static const VerificationMeta _cachedAtMeta = const VerificationMeta(
|
||||
'cachedAt',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<DateTime> cachedAt = GeneratedColumn<DateTime>(
|
||||
'cached_at',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.dateTime,
|
||||
requiredDuringInsert: false,
|
||||
defaultValue: currentDateAndTime,
|
||||
);
|
||||
static const VerificationMeta _pinnedMeta = const VerificationMeta('pinned');
|
||||
@override
|
||||
late final GeneratedColumn<bool> pinned = GeneratedColumn<bool>(
|
||||
@@ -2036,20 +2048,8 @@ class $ApiCacheTable extends ApiCache
|
||||
),
|
||||
defaultValue: const Constant(false),
|
||||
);
|
||||
static const VerificationMeta _cachedAtMeta = const VerificationMeta(
|
||||
'cachedAt',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<DateTime> cachedAt = GeneratedColumn<DateTime>(
|
||||
'cached_at',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.dateTime,
|
||||
requiredDuringInsert: false,
|
||||
defaultValue: currentDateAndTime,
|
||||
);
|
||||
@override
|
||||
List<GeneratedColumn> get $columns => [cacheKey, data, pinned, cachedAt];
|
||||
List<GeneratedColumn> get $columns => [cacheKey, data, cachedAt, pinned];
|
||||
@override
|
||||
String get aliasedName => _alias ?? actualTableName;
|
||||
@override
|
||||
@@ -2078,18 +2078,18 @@ class $ApiCacheTable extends ApiCache
|
||||
} else if (isInserting) {
|
||||
context.missing(_dataMeta);
|
||||
}
|
||||
if (data.containsKey('pinned')) {
|
||||
context.handle(
|
||||
_pinnedMeta,
|
||||
pinned.isAcceptableOrUnknown(data['pinned']!, _pinnedMeta),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('cached_at')) {
|
||||
context.handle(
|
||||
_cachedAtMeta,
|
||||
cachedAt.isAcceptableOrUnknown(data['cached_at']!, _cachedAtMeta),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('pinned')) {
|
||||
context.handle(
|
||||
_pinnedMeta,
|
||||
pinned.isAcceptableOrUnknown(data['pinned']!, _pinnedMeta),
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -2107,14 +2107,14 @@ class $ApiCacheTable extends ApiCache
|
||||
DriftSqlType.string,
|
||||
data['${effectivePrefix}data'],
|
||||
)!,
|
||||
pinned: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}pinned'],
|
||||
)!,
|
||||
cachedAt: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.dateTime,
|
||||
data['${effectivePrefix}cached_at'],
|
||||
)!,
|
||||
pinned: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}pinned'],
|
||||
)!,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2130,24 +2130,26 @@ class ApiCacheData extends DataClass implements Insertable<ApiCacheData> {
|
||||
final String cacheKey;
|
||||
final String data;
|
||||
|
||||
/// When the row was last written ([ApiCacheSingleton.put] stamps it on
|
||||
/// every store). Read by the fresh-cache-first playback metadata gate,
|
||||
/// [ApiCacheSingleton.getIfFresh].
|
||||
final DateTime cachedAt;
|
||||
|
||||
/// Whether this item is pinned for offline access
|
||||
final bool pinned;
|
||||
|
||||
/// Timestamp for cache invalidation (optional future use)
|
||||
final DateTime cachedAt;
|
||||
const ApiCacheData({
|
||||
required this.cacheKey,
|
||||
required this.data,
|
||||
required this.pinned,
|
||||
required this.cachedAt,
|
||||
required this.pinned,
|
||||
});
|
||||
@override
|
||||
Map<String, Expression> toColumns(bool nullToAbsent) {
|
||||
final map = <String, Expression>{};
|
||||
map['cache_key'] = Variable<String>(cacheKey);
|
||||
map['data'] = Variable<String>(data);
|
||||
map['pinned'] = Variable<bool>(pinned);
|
||||
map['cached_at'] = Variable<DateTime>(cachedAt);
|
||||
map['pinned'] = Variable<bool>(pinned);
|
||||
return map;
|
||||
}
|
||||
|
||||
@@ -2155,8 +2157,8 @@ class ApiCacheData extends DataClass implements Insertable<ApiCacheData> {
|
||||
return ApiCacheCompanion(
|
||||
cacheKey: Value(cacheKey),
|
||||
data: Value(data),
|
||||
pinned: Value(pinned),
|
||||
cachedAt: Value(cachedAt),
|
||||
pinned: Value(pinned),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2168,8 +2170,8 @@ class ApiCacheData extends DataClass implements Insertable<ApiCacheData> {
|
||||
return ApiCacheData(
|
||||
cacheKey: serializer.fromJson<String>(json['cacheKey']),
|
||||
data: serializer.fromJson<String>(json['data']),
|
||||
pinned: serializer.fromJson<bool>(json['pinned']),
|
||||
cachedAt: serializer.fromJson<DateTime>(json['cachedAt']),
|
||||
pinned: serializer.fromJson<bool>(json['pinned']),
|
||||
);
|
||||
}
|
||||
@override
|
||||
@@ -2178,28 +2180,28 @@ class ApiCacheData extends DataClass implements Insertable<ApiCacheData> {
|
||||
return <String, dynamic>{
|
||||
'cacheKey': serializer.toJson<String>(cacheKey),
|
||||
'data': serializer.toJson<String>(data),
|
||||
'pinned': serializer.toJson<bool>(pinned),
|
||||
'cachedAt': serializer.toJson<DateTime>(cachedAt),
|
||||
'pinned': serializer.toJson<bool>(pinned),
|
||||
};
|
||||
}
|
||||
|
||||
ApiCacheData copyWith({
|
||||
String? cacheKey,
|
||||
String? data,
|
||||
bool? pinned,
|
||||
DateTime? cachedAt,
|
||||
bool? pinned,
|
||||
}) => ApiCacheData(
|
||||
cacheKey: cacheKey ?? this.cacheKey,
|
||||
data: data ?? this.data,
|
||||
pinned: pinned ?? this.pinned,
|
||||
cachedAt: cachedAt ?? this.cachedAt,
|
||||
pinned: pinned ?? this.pinned,
|
||||
);
|
||||
ApiCacheData copyWithCompanion(ApiCacheCompanion data) {
|
||||
return ApiCacheData(
|
||||
cacheKey: data.cacheKey.present ? data.cacheKey.value : this.cacheKey,
|
||||
data: data.data.present ? data.data.value : this.data,
|
||||
pinned: data.pinned.present ? data.pinned.value : this.pinned,
|
||||
cachedAt: data.cachedAt.present ? data.cachedAt.value : this.cachedAt,
|
||||
pinned: data.pinned.present ? data.pinned.value : this.pinned,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2208,57 +2210,57 @@ class ApiCacheData extends DataClass implements Insertable<ApiCacheData> {
|
||||
return (StringBuffer('ApiCacheData(')
|
||||
..write('cacheKey: $cacheKey, ')
|
||||
..write('data: $data, ')
|
||||
..write('pinned: $pinned, ')
|
||||
..write('cachedAt: $cachedAt')
|
||||
..write('cachedAt: $cachedAt, ')
|
||||
..write('pinned: $pinned')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(cacheKey, data, pinned, cachedAt);
|
||||
int get hashCode => Object.hash(cacheKey, data, cachedAt, pinned);
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
(other is ApiCacheData &&
|
||||
other.cacheKey == this.cacheKey &&
|
||||
other.data == this.data &&
|
||||
other.pinned == this.pinned &&
|
||||
other.cachedAt == this.cachedAt);
|
||||
other.cachedAt == this.cachedAt &&
|
||||
other.pinned == this.pinned);
|
||||
}
|
||||
|
||||
class ApiCacheCompanion extends UpdateCompanion<ApiCacheData> {
|
||||
final Value<String> cacheKey;
|
||||
final Value<String> data;
|
||||
final Value<bool> pinned;
|
||||
final Value<DateTime> cachedAt;
|
||||
final Value<bool> pinned;
|
||||
final Value<int> rowid;
|
||||
const ApiCacheCompanion({
|
||||
this.cacheKey = const Value.absent(),
|
||||
this.data = const Value.absent(),
|
||||
this.pinned = const Value.absent(),
|
||||
this.cachedAt = const Value.absent(),
|
||||
this.pinned = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
});
|
||||
ApiCacheCompanion.insert({
|
||||
required String cacheKey,
|
||||
required String data,
|
||||
this.pinned = const Value.absent(),
|
||||
this.cachedAt = const Value.absent(),
|
||||
this.pinned = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
}) : cacheKey = Value(cacheKey),
|
||||
data = Value(data);
|
||||
static Insertable<ApiCacheData> custom({
|
||||
Expression<String>? cacheKey,
|
||||
Expression<String>? data,
|
||||
Expression<bool>? pinned,
|
||||
Expression<DateTime>? cachedAt,
|
||||
Expression<bool>? pinned,
|
||||
Expression<int>? rowid,
|
||||
}) {
|
||||
return RawValuesInsertable({
|
||||
if (cacheKey != null) 'cache_key': cacheKey,
|
||||
if (data != null) 'data': data,
|
||||
if (pinned != null) 'pinned': pinned,
|
||||
if (cachedAt != null) 'cached_at': cachedAt,
|
||||
if (pinned != null) 'pinned': pinned,
|
||||
if (rowid != null) 'rowid': rowid,
|
||||
});
|
||||
}
|
||||
@@ -2266,15 +2268,15 @@ class ApiCacheCompanion extends UpdateCompanion<ApiCacheData> {
|
||||
ApiCacheCompanion copyWith({
|
||||
Value<String>? cacheKey,
|
||||
Value<String>? data,
|
||||
Value<bool>? pinned,
|
||||
Value<DateTime>? cachedAt,
|
||||
Value<bool>? pinned,
|
||||
Value<int>? rowid,
|
||||
}) {
|
||||
return ApiCacheCompanion(
|
||||
cacheKey: cacheKey ?? this.cacheKey,
|
||||
data: data ?? this.data,
|
||||
pinned: pinned ?? this.pinned,
|
||||
cachedAt: cachedAt ?? this.cachedAt,
|
||||
pinned: pinned ?? this.pinned,
|
||||
rowid: rowid ?? this.rowid,
|
||||
);
|
||||
}
|
||||
@@ -2288,12 +2290,12 @@ class ApiCacheCompanion extends UpdateCompanion<ApiCacheData> {
|
||||
if (data.present) {
|
||||
map['data'] = Variable<String>(data.value);
|
||||
}
|
||||
if (pinned.present) {
|
||||
map['pinned'] = Variable<bool>(pinned.value);
|
||||
}
|
||||
if (cachedAt.present) {
|
||||
map['cached_at'] = Variable<DateTime>(cachedAt.value);
|
||||
}
|
||||
if (pinned.present) {
|
||||
map['pinned'] = Variable<bool>(pinned.value);
|
||||
}
|
||||
if (rowid.present) {
|
||||
map['rowid'] = Variable<int>(rowid.value);
|
||||
}
|
||||
@@ -2305,8 +2307,8 @@ class ApiCacheCompanion extends UpdateCompanion<ApiCacheData> {
|
||||
return (StringBuffer('ApiCacheCompanion(')
|
||||
..write('cacheKey: $cacheKey, ')
|
||||
..write('data: $data, ')
|
||||
..write('pinned: $pinned, ')
|
||||
..write('cachedAt: $cachedAt, ')
|
||||
..write('pinned: $pinned, ')
|
||||
..write('rowid: $rowid')
|
||||
..write(')'))
|
||||
.toString();
|
||||
@@ -4333,21 +4335,6 @@ class $ConnectionsTable extends Connections
|
||||
type: DriftSqlType.string,
|
||||
requiredDuringInsert: true,
|
||||
);
|
||||
static const VerificationMeta _isDefaultMeta = const VerificationMeta(
|
||||
'isDefault',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<bool> isDefault = GeneratedColumn<bool>(
|
||||
'is_default',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.bool,
|
||||
requiredDuringInsert: false,
|
||||
defaultConstraints: GeneratedColumn.constraintIsAlways(
|
||||
'CHECK ("is_default" IN (0, 1))',
|
||||
),
|
||||
defaultValue: const Constant(false),
|
||||
);
|
||||
static const VerificationMeta _createdAtMeta = const VerificationMeta(
|
||||
'createdAt',
|
||||
);
|
||||
@@ -4375,7 +4362,6 @@ class $ConnectionsTable extends Connections
|
||||
kind,
|
||||
displayName,
|
||||
configJson,
|
||||
isDefault,
|
||||
createdAt,
|
||||
lastAuthenticatedAt,
|
||||
];
|
||||
@@ -4423,12 +4409,6 @@ class $ConnectionsTable extends Connections
|
||||
} else if (isInserting) {
|
||||
context.missing(_configJsonMeta);
|
||||
}
|
||||
if (data.containsKey('is_default')) {
|
||||
context.handle(
|
||||
_isDefaultMeta,
|
||||
isDefault.isAcceptableOrUnknown(data['is_default']!, _isDefaultMeta),
|
||||
);
|
||||
}
|
||||
if (data.containsKey('created_at')) {
|
||||
context.handle(
|
||||
_createdAtMeta,
|
||||
@@ -4471,10 +4451,6 @@ class $ConnectionsTable extends Connections
|
||||
DriftSqlType.string,
|
||||
data['${effectivePrefix}config_json'],
|
||||
)!,
|
||||
isDefault: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.bool,
|
||||
data['${effectivePrefix}is_default'],
|
||||
)!,
|
||||
createdAt: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.int,
|
||||
data['${effectivePrefix}created_at'],
|
||||
@@ -4506,10 +4482,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
/// Backend-specific config payload (token, baseUrl, profile id, …).
|
||||
final String configJson;
|
||||
|
||||
/// Whether this is the default connection used at app launch when only
|
||||
/// one connection is present.
|
||||
final bool isDefault;
|
||||
|
||||
/// Timestamp this connection was added (milliseconds since epoch).
|
||||
final int createdAt;
|
||||
|
||||
@@ -4521,7 +4493,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
required this.kind,
|
||||
required this.displayName,
|
||||
required this.configJson,
|
||||
required this.isDefault,
|
||||
required this.createdAt,
|
||||
this.lastAuthenticatedAt,
|
||||
});
|
||||
@@ -4532,7 +4503,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
map['kind'] = Variable<String>(kind);
|
||||
map['display_name'] = Variable<String>(displayName);
|
||||
map['config_json'] = Variable<String>(configJson);
|
||||
map['is_default'] = Variable<bool>(isDefault);
|
||||
map['created_at'] = Variable<int>(createdAt);
|
||||
if (!nullToAbsent || lastAuthenticatedAt != null) {
|
||||
map['last_authenticated_at'] = Variable<int>(lastAuthenticatedAt);
|
||||
@@ -4546,7 +4516,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
kind: Value(kind),
|
||||
displayName: Value(displayName),
|
||||
configJson: Value(configJson),
|
||||
isDefault: Value(isDefault),
|
||||
createdAt: Value(createdAt),
|
||||
lastAuthenticatedAt: lastAuthenticatedAt == null && nullToAbsent
|
||||
? const Value.absent()
|
||||
@@ -4564,7 +4533,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
kind: serializer.fromJson<String>(json['kind']),
|
||||
displayName: serializer.fromJson<String>(json['displayName']),
|
||||
configJson: serializer.fromJson<String>(json['configJson']),
|
||||
isDefault: serializer.fromJson<bool>(json['isDefault']),
|
||||
createdAt: serializer.fromJson<int>(json['createdAt']),
|
||||
lastAuthenticatedAt: serializer.fromJson<int?>(
|
||||
json['lastAuthenticatedAt'],
|
||||
@@ -4579,7 +4547,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
'kind': serializer.toJson<String>(kind),
|
||||
'displayName': serializer.toJson<String>(displayName),
|
||||
'configJson': serializer.toJson<String>(configJson),
|
||||
'isDefault': serializer.toJson<bool>(isDefault),
|
||||
'createdAt': serializer.toJson<int>(createdAt),
|
||||
'lastAuthenticatedAt': serializer.toJson<int?>(lastAuthenticatedAt),
|
||||
};
|
||||
@@ -4590,7 +4557,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
String? kind,
|
||||
String? displayName,
|
||||
String? configJson,
|
||||
bool? isDefault,
|
||||
int? createdAt,
|
||||
Value<int?> lastAuthenticatedAt = const Value.absent(),
|
||||
}) => ConnectionRow(
|
||||
@@ -4598,7 +4564,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
kind: kind ?? this.kind,
|
||||
displayName: displayName ?? this.displayName,
|
||||
configJson: configJson ?? this.configJson,
|
||||
isDefault: isDefault ?? this.isDefault,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt.present
|
||||
? lastAuthenticatedAt.value
|
||||
@@ -4614,7 +4579,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
configJson: data.configJson.present
|
||||
? data.configJson.value
|
||||
: this.configJson,
|
||||
isDefault: data.isDefault.present ? data.isDefault.value : this.isDefault,
|
||||
createdAt: data.createdAt.present ? data.createdAt.value : this.createdAt,
|
||||
lastAuthenticatedAt: data.lastAuthenticatedAt.present
|
||||
? data.lastAuthenticatedAt.value
|
||||
@@ -4629,7 +4593,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
..write('kind: $kind, ')
|
||||
..write('displayName: $displayName, ')
|
||||
..write('configJson: $configJson, ')
|
||||
..write('isDefault: $isDefault, ')
|
||||
..write('createdAt: $createdAt, ')
|
||||
..write('lastAuthenticatedAt: $lastAuthenticatedAt')
|
||||
..write(')'))
|
||||
@@ -4642,7 +4605,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
kind,
|
||||
displayName,
|
||||
configJson,
|
||||
isDefault,
|
||||
createdAt,
|
||||
lastAuthenticatedAt,
|
||||
);
|
||||
@@ -4654,7 +4616,6 @@ class ConnectionRow extends DataClass implements Insertable<ConnectionRow> {
|
||||
other.kind == this.kind &&
|
||||
other.displayName == this.displayName &&
|
||||
other.configJson == this.configJson &&
|
||||
other.isDefault == this.isDefault &&
|
||||
other.createdAt == this.createdAt &&
|
||||
other.lastAuthenticatedAt == this.lastAuthenticatedAt);
|
||||
}
|
||||
@@ -4664,7 +4625,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
final Value<String> kind;
|
||||
final Value<String> displayName;
|
||||
final Value<String> configJson;
|
||||
final Value<bool> isDefault;
|
||||
final Value<int> createdAt;
|
||||
final Value<int?> lastAuthenticatedAt;
|
||||
final Value<int> rowid;
|
||||
@@ -4673,7 +4633,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
this.kind = const Value.absent(),
|
||||
this.displayName = const Value.absent(),
|
||||
this.configJson = const Value.absent(),
|
||||
this.isDefault = const Value.absent(),
|
||||
this.createdAt = const Value.absent(),
|
||||
this.lastAuthenticatedAt = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
@@ -4683,7 +4642,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
required String kind,
|
||||
required String displayName,
|
||||
required String configJson,
|
||||
this.isDefault = const Value.absent(),
|
||||
required int createdAt,
|
||||
this.lastAuthenticatedAt = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
@@ -4697,7 +4655,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
Expression<String>? kind,
|
||||
Expression<String>? displayName,
|
||||
Expression<String>? configJson,
|
||||
Expression<bool>? isDefault,
|
||||
Expression<int>? createdAt,
|
||||
Expression<int>? lastAuthenticatedAt,
|
||||
Expression<int>? rowid,
|
||||
@@ -4707,7 +4664,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
if (kind != null) 'kind': kind,
|
||||
if (displayName != null) 'display_name': displayName,
|
||||
if (configJson != null) 'config_json': configJson,
|
||||
if (isDefault != null) 'is_default': isDefault,
|
||||
if (createdAt != null) 'created_at': createdAt,
|
||||
if (lastAuthenticatedAt != null)
|
||||
'last_authenticated_at': lastAuthenticatedAt,
|
||||
@@ -4720,7 +4676,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
Value<String>? kind,
|
||||
Value<String>? displayName,
|
||||
Value<String>? configJson,
|
||||
Value<bool>? isDefault,
|
||||
Value<int>? createdAt,
|
||||
Value<int?>? lastAuthenticatedAt,
|
||||
Value<int>? rowid,
|
||||
@@ -4730,7 +4685,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
kind: kind ?? this.kind,
|
||||
displayName: displayName ?? this.displayName,
|
||||
configJson: configJson ?? this.configJson,
|
||||
isDefault: isDefault ?? this.isDefault,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt ?? this.lastAuthenticatedAt,
|
||||
rowid: rowid ?? this.rowid,
|
||||
@@ -4752,9 +4706,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
if (configJson.present) {
|
||||
map['config_json'] = Variable<String>(configJson.value);
|
||||
}
|
||||
if (isDefault.present) {
|
||||
map['is_default'] = Variable<bool>(isDefault.value);
|
||||
}
|
||||
if (createdAt.present) {
|
||||
map['created_at'] = Variable<int>(createdAt.value);
|
||||
}
|
||||
@@ -4774,7 +4725,6 @@ class ConnectionsCompanion extends UpdateCompanion<ConnectionRow> {
|
||||
..write('kind: $kind, ')
|
||||
..write('displayName: $displayName, ')
|
||||
..write('configJson: $configJson, ')
|
||||
..write('isDefault: $isDefault, ')
|
||||
..write('createdAt: $createdAt, ')
|
||||
..write('lastAuthenticatedAt: $lastAuthenticatedAt, ')
|
||||
..write('rowid: $rowid')
|
||||
@@ -6909,16 +6859,16 @@ typedef $$ApiCacheTableCreateCompanionBuilder =
|
||||
ApiCacheCompanion Function({
|
||||
required String cacheKey,
|
||||
required String data,
|
||||
Value<bool> pinned,
|
||||
Value<DateTime> cachedAt,
|
||||
Value<bool> pinned,
|
||||
Value<int> rowid,
|
||||
});
|
||||
typedef $$ApiCacheTableUpdateCompanionBuilder =
|
||||
ApiCacheCompanion Function({
|
||||
Value<String> cacheKey,
|
||||
Value<String> data,
|
||||
Value<bool> pinned,
|
||||
Value<DateTime> cachedAt,
|
||||
Value<bool> pinned,
|
||||
Value<int> rowid,
|
||||
});
|
||||
|
||||
@@ -6941,13 +6891,13 @@ class $$ApiCacheTableFilterComposer
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<bool> get pinned => $composableBuilder(
|
||||
column: $table.pinned,
|
||||
ColumnFilters<DateTime> get cachedAt => $composableBuilder(
|
||||
column: $table.cachedAt,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<DateTime> get cachedAt => $composableBuilder(
|
||||
column: $table.cachedAt,
|
||||
ColumnFilters<bool> get pinned => $composableBuilder(
|
||||
column: $table.pinned,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
}
|
||||
@@ -6971,13 +6921,13 @@ class $$ApiCacheTableOrderingComposer
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<bool> get pinned => $composableBuilder(
|
||||
column: $table.pinned,
|
||||
ColumnOrderings<DateTime> get cachedAt => $composableBuilder(
|
||||
column: $table.cachedAt,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<DateTime> get cachedAt => $composableBuilder(
|
||||
column: $table.cachedAt,
|
||||
ColumnOrderings<bool> get pinned => $composableBuilder(
|
||||
column: $table.pinned,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
}
|
||||
@@ -6997,11 +6947,11 @@ class $$ApiCacheTableAnnotationComposer
|
||||
GeneratedColumn<String> get data =>
|
||||
$composableBuilder(column: $table.data, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<bool> get pinned =>
|
||||
$composableBuilder(column: $table.pinned, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<DateTime> get cachedAt =>
|
||||
$composableBuilder(column: $table.cachedAt, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<bool> get pinned =>
|
||||
$composableBuilder(column: $table.pinned, builder: (column) => column);
|
||||
}
|
||||
|
||||
class $$ApiCacheTableTableManager
|
||||
@@ -7037,28 +6987,28 @@ class $$ApiCacheTableTableManager
|
||||
({
|
||||
Value<String> cacheKey = const Value.absent(),
|
||||
Value<String> data = const Value.absent(),
|
||||
Value<bool> pinned = const Value.absent(),
|
||||
Value<DateTime> cachedAt = const Value.absent(),
|
||||
Value<bool> pinned = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
}) => ApiCacheCompanion(
|
||||
cacheKey: cacheKey,
|
||||
data: data,
|
||||
pinned: pinned,
|
||||
cachedAt: cachedAt,
|
||||
pinned: pinned,
|
||||
rowid: rowid,
|
||||
),
|
||||
createCompanionCallback:
|
||||
({
|
||||
required String cacheKey,
|
||||
required String data,
|
||||
Value<bool> pinned = const Value.absent(),
|
||||
Value<DateTime> cachedAt = const Value.absent(),
|
||||
Value<bool> pinned = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
}) => ApiCacheCompanion.insert(
|
||||
cacheKey: cacheKey,
|
||||
data: data,
|
||||
pinned: pinned,
|
||||
cachedAt: cachedAt,
|
||||
pinned: pinned,
|
||||
rowid: rowid,
|
||||
),
|
||||
withReferenceMapper: (p0) => p0
|
||||
@@ -8269,7 +8219,6 @@ typedef $$ConnectionsTableCreateCompanionBuilder =
|
||||
required String kind,
|
||||
required String displayName,
|
||||
required String configJson,
|
||||
Value<bool> isDefault,
|
||||
required int createdAt,
|
||||
Value<int?> lastAuthenticatedAt,
|
||||
Value<int> rowid,
|
||||
@@ -8280,7 +8229,6 @@ typedef $$ConnectionsTableUpdateCompanionBuilder =
|
||||
Value<String> kind,
|
||||
Value<String> displayName,
|
||||
Value<String> configJson,
|
||||
Value<bool> isDefault,
|
||||
Value<int> createdAt,
|
||||
Value<int?> lastAuthenticatedAt,
|
||||
Value<int> rowid,
|
||||
@@ -8344,11 +8292,6 @@ class $$ConnectionsTableFilterComposer
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<bool> get isDefault => $composableBuilder(
|
||||
column: $table.isDefault,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<int> get createdAt => $composableBuilder(
|
||||
column: $table.createdAt,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
@@ -8414,11 +8357,6 @@ class $$ConnectionsTableOrderingComposer
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<bool> get isDefault => $composableBuilder(
|
||||
column: $table.isDefault,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<int> get createdAt => $composableBuilder(
|
||||
column: $table.createdAt,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
@@ -8455,9 +8393,6 @@ class $$ConnectionsTableAnnotationComposer
|
||||
builder: (column) => column,
|
||||
);
|
||||
|
||||
GeneratedColumn<bool> get isDefault =>
|
||||
$composableBuilder(column: $table.isDefault, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<int> get createdAt =>
|
||||
$composableBuilder(column: $table.createdAt, builder: (column) => column);
|
||||
|
||||
@@ -8525,7 +8460,6 @@ class $$ConnectionsTableTableManager
|
||||
Value<String> kind = const Value.absent(),
|
||||
Value<String> displayName = const Value.absent(),
|
||||
Value<String> configJson = const Value.absent(),
|
||||
Value<bool> isDefault = const Value.absent(),
|
||||
Value<int> createdAt = const Value.absent(),
|
||||
Value<int?> lastAuthenticatedAt = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
@@ -8534,7 +8468,6 @@ class $$ConnectionsTableTableManager
|
||||
kind: kind,
|
||||
displayName: displayName,
|
||||
configJson: configJson,
|
||||
isDefault: isDefault,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt,
|
||||
rowid: rowid,
|
||||
@@ -8545,7 +8478,6 @@ class $$ConnectionsTableTableManager
|
||||
required String kind,
|
||||
required String displayName,
|
||||
required String configJson,
|
||||
Value<bool> isDefault = const Value.absent(),
|
||||
required int createdAt,
|
||||
Value<int?> lastAuthenticatedAt = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
@@ -8554,7 +8486,6 @@ class $$ConnectionsTableTableManager
|
||||
kind: kind,
|
||||
displayName: displayName,
|
||||
configJson: configJson,
|
||||
isDefault: isDefault,
|
||||
createdAt: createdAt,
|
||||
lastAuthenticatedAt: lastAuthenticatedAt,
|
||||
rowid: rowid,
|
||||
|
||||
@@ -145,10 +145,6 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> getDownloadOwnerCount(String globalKey) async {
|
||||
return (await _validDownloadOwnerRows(globalKey)).length;
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
Future<bool> hasDownloadOwner(String globalKey, {String? excludingProfileId}) async {
|
||||
final rows = await _validDownloadOwnerRows(globalKey, excludingProfileId: excludingProfileId);
|
||||
@@ -190,8 +186,8 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
/// inherit them.
|
||||
///
|
||||
/// Runs on every profile switch — validity context is computed once and
|
||||
/// applied in memory instead of the per-download full-table rescan
|
||||
/// `getDownloadOwnerCount` would do.
|
||||
/// applied in memory instead of a per-download full-table rescan through
|
||||
/// `_validDownloadOwnerRows`.
|
||||
Future<void> adoptLegacyDownloadsForProfile(String profileId, {bool Function()? isStillActive}) async {
|
||||
if (profileId.isEmpty) return;
|
||||
if (isStillActive != null && !isStillActive()) return;
|
||||
@@ -437,14 +433,20 @@ extension DownloadDatabaseOperations on AppDatabase {
|
||||
}
|
||||
|
||||
/// Get next item from queue (highest priority, oldest first)
|
||||
/// Only returns items that are not paused
|
||||
Future<DownloadQueueItem?> getNextQueueItem() async {
|
||||
/// Only returns items that are not paused.
|
||||
///
|
||||
/// [excludedGlobalKeys] filters out heads the caller already tried and could
|
||||
/// not resolve, so one stale row cannot starve the rest of the queue.
|
||||
Future<DownloadQueueItem?> getNextQueueItem({Set<String> excludedGlobalKeys = const {}}) async {
|
||||
final query = select(
|
||||
downloadQueue,
|
||||
).join([innerJoin(downloadedMedia, downloadedMedia.globalKey.equalsExp(downloadQueue.mediaGlobalKey))]);
|
||||
|
||||
query.where(downloadedMedia.status.equals(DownloadStatus.queued.index));
|
||||
if (excludedGlobalKeys.isNotEmpty) {
|
||||
query.where(downloadQueue.mediaGlobalKey.isNotIn(excludedGlobalKeys.toList(growable: false)));
|
||||
}
|
||||
query
|
||||
..where(downloadedMedia.status.equals(DownloadStatus.queued.index))
|
||||
..orderBy([
|
||||
OrderingTerm(expression: downloadQueue.priority, mode: OrderingMode.desc),
|
||||
OrderingTerm(expression: downloadQueue.addedAt),
|
||||
|
||||
@@ -9,12 +9,14 @@ class ApiCache extends Table {
|
||||
|
||||
TextColumn get data => text()();
|
||||
|
||||
/// When the row was last written ([ApiCacheSingleton.put] stamps it on
|
||||
/// every store). Read by the fresh-cache-first playback metadata gate,
|
||||
/// [ApiCacheSingleton.getIfFresh].
|
||||
DateTimeColumn get cachedAt => dateTime().withDefault(currentDateAndTime)();
|
||||
|
||||
/// Whether this item is pinned for offline access
|
||||
BoolColumn get pinned => boolean().withDefault(const Constant(false))();
|
||||
|
||||
/// Timestamp for cache invalidation (optional future use)
|
||||
DateTimeColumn get cachedAt => dateTime().withDefault(currentDateAndTime)();
|
||||
|
||||
@override
|
||||
Set<Column> get primaryKey => {cacheKey};
|
||||
}
|
||||
@@ -150,10 +152,6 @@ class Connections extends Table {
|
||||
/// Backend-specific config payload (token, baseUrl, profile id, …).
|
||||
TextColumn get configJson => text()();
|
||||
|
||||
/// Whether this is the default connection used at app launch when only
|
||||
/// one connection is present.
|
||||
BoolColumn get isDefault => boolean().withDefault(const Constant(false))();
|
||||
|
||||
/// Timestamp this connection was added (milliseconds since epoch).
|
||||
IntColumn get createdAt => integer()();
|
||||
|
||||
|
||||
@@ -119,6 +119,17 @@ class MediaServerHttpException extends MediaServerException {
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend already has a recording scheduled for the requested airing.
|
||||
///
|
||||
/// Plex signals duplicates with a bare 409, which UI maps by status code.
|
||||
/// Jellyfin/Emby answer `POST /LiveTv/Timers` duplicates with a 400 that is
|
||||
/// indistinguishable from a malformed request by status alone — only the DVR
|
||||
/// adapter knows that call site's semantics, so it rethrows this type and UI
|
||||
/// maps it to the "already scheduled" outcome without a backend check.
|
||||
class RecordingConflictException extends MediaServerException {
|
||||
const RecordingConflictException(super.message, {super.display});
|
||||
}
|
||||
|
||||
/// The server explicitly terminated the client's playback session (admin
|
||||
/// "stop stream", paused-too-long auto-termination, concurrent-stream limit).
|
||||
///
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -70,29 +71,73 @@ extension DpadKeyExtension on LogicalKeyboardKey {
|
||||
bool get isDownKey => this == LogicalKeyboardKey.arrowDown;
|
||||
}
|
||||
|
||||
/// Base class for suppressing key-up events after a key category triggers an
|
||||
/// action (e.g. opening a sheet). While suppressed, all events for the matched
|
||||
/// key category are consumed; suppression auto-clears on [KeyUpEvent].
|
||||
/// Base class for suppressing key events after a key category triggers an
|
||||
/// action (e.g. opening a sheet). While suppressed, every event of the matched
|
||||
/// key category is consumed — including a [KeyDownEvent] when
|
||||
/// [consumeKeyDowns] is set, because an armer running in the
|
||||
/// [HardwareKeyboard] handler phase (the hotkey recorder) arms against the
|
||||
/// very KeyDown that is then re-dispatched through the focus tree.
|
||||
///
|
||||
/// Suppression ends with the physical press: a global [HardwareKeyboard]
|
||||
/// observer watches for the matching [KeyUpEvent] and clears the armed state
|
||||
/// in a microtask — after that KeyUp's own synchronous focus dispatch, so
|
||||
/// focus-phase consumers still swallow it — which guarantees a stale armed
|
||||
/// state (a KeyUp delivered to a focus chain that never consulted us) can
|
||||
/// never swallow the next press.
|
||||
///
|
||||
/// Armers that target an in-flight KeyUp ([consumeKeyDowns] unset) treat a
|
||||
/// matching [KeyDownEvent] as proof the suppressed press already ended without
|
||||
/// its KeyUp reaching us (e.g. a closing TV IME session ate it): the armed
|
||||
/// state is cleared and the fresh press passes through unconsumed.
|
||||
class _KeyUpSuppressor {
|
||||
final bool Function(LogicalKeyboardKey) _keyMatcher;
|
||||
|
||||
_KeyUpSuppressor(this._keyMatcher);
|
||||
/// Whether a matching [KeyDownEvent] is consumed while armed. See the class
|
||||
/// documentation for why armers targeting an in-flight KeyUp must unset it.
|
||||
final bool consumeKeyDowns;
|
||||
|
||||
_KeyUpSuppressor(this._keyMatcher, {this.consumeKeyDowns = true});
|
||||
|
||||
bool _suppressed = false;
|
||||
|
||||
void suppress() => _suppressed = true;
|
||||
void suppress() {
|
||||
// Re-registered on every arm because flutter_test's HardwareKeyboard
|
||||
// clearState() drops handlers between tests; remove-then-add keeps exactly
|
||||
// one live registration. The observer only reads state and returns false,
|
||||
// so it can never consume an event, and it is intentionally never removed
|
||||
// outside re-registration.
|
||||
HardwareKeyboard.instance
|
||||
..removeHandler(_observeKeyUp)
|
||||
..addHandler(_observeKeyUp);
|
||||
_suppressed = true;
|
||||
}
|
||||
|
||||
bool _observeKeyUp(KeyEvent event) {
|
||||
if (_suppressed && event is KeyUpEvent && _keyMatcher(event.logicalKey)) {
|
||||
// The hardware phase runs before the same event's focus dispatch;
|
||||
// clearing in a microtask keeps the armed state visible to the KeyUp's
|
||||
// focus-phase consumers while ending it before any later event.
|
||||
scheduleMicrotask(clearSuppression);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void clearSuppression() => _suppressed = false;
|
||||
|
||||
/// Returns `true` (consumed) when the event belongs to the matched key
|
||||
/// category and suppression is active. Clears suppression on [KeyUpEvent].
|
||||
/// category and suppression is active. Clears suppression on [KeyUpEvent],
|
||||
/// and on a stale [KeyDownEvent] when [consumeKeyDowns] is unset.
|
||||
bool consumeIfSuppressed(KeyEvent event) {
|
||||
if (!_suppressed) return false;
|
||||
if (_keyMatcher(event.logicalKey)) {
|
||||
if (event is KeyUpEvent) _suppressed = false;
|
||||
return true;
|
||||
if (!_keyMatcher(event.logicalKey)) return false;
|
||||
if (event is KeyUpEvent) _suppressed = false;
|
||||
if (event is KeyDownEvent && !consumeKeyDowns) {
|
||||
// The in-flight KeyUp never arrived; this is a fresh press, not the
|
||||
// suppressed one. Clear and let it through.
|
||||
_suppressed = false;
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,10 +153,13 @@ class SelectKeyUpSuppressor {
|
||||
/// Global helper to suppress the next BACK key-up event.
|
||||
///
|
||||
/// 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.
|
||||
/// e.g. by [BackKeySuppressorObserver] when a route pops mid-press — or when a
|
||||
/// down-only back handler moves focus before the matching KeyUp is dispatched.
|
||||
/// A matching KeyDown while armed clears the arming instead of consuming: it
|
||||
/// can only mean the suppressed press's KeyUp was swallowed off-app, so the
|
||||
/// fresh press must act normally.
|
||||
class BackKeyUpSuppressor {
|
||||
static final _instance = _KeyUpSuppressor((k) => k.isBackKey);
|
||||
static final _instance = _KeyUpSuppressor((k) => k.isBackKey, consumeKeyDowns: false);
|
||||
|
||||
static void suppressBackUntilKeyUp() => _instance.suppress();
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ Widget buildFocusChrome(
|
||||
bool useBackgroundFocus = false,
|
||||
bool useFocusGlow = false,
|
||||
bool delegateFocusBorder = false,
|
||||
bool? showGlow,
|
||||
Size? glowSize,
|
||||
required Widget child,
|
||||
}) {
|
||||
@@ -44,10 +45,12 @@ Widget buildFocusChrome(
|
||||
}
|
||||
|
||||
// Glow (full-bleed cards) renders in an overlay above siblings so it stays
|
||||
// symmetric; the in-card decoration only carries the border.
|
||||
// symmetric; the in-card decoration only carries the border. [showGlow] lets
|
||||
// callers hold back just the glow (e.g. while a viewport scroll animates)
|
||||
// without touching the border or scale chrome.
|
||||
if (useFocusGlow) {
|
||||
card = FocusGlowOverlay(
|
||||
isFocused: showFocus,
|
||||
isFocused: showGlow ?? showFocus,
|
||||
borderRadius: borderRadius,
|
||||
color: focusColor ?? FocusTheme.getFocusBorderColor(context),
|
||||
glowSize: glowSize,
|
||||
|
||||
@@ -57,6 +57,12 @@ class _FocusGlowOverlayState extends State<FocusGlowOverlay> {
|
||||
/// fades out before the portal is hidden in [_handleFadeEnd].
|
||||
bool _visible = false;
|
||||
|
||||
/// Whether the previous [build] mounted the [OverlayPortal] — i.e. whether
|
||||
/// [_controller] is attached. An attached controller's show()/hide() assert
|
||||
/// when called during build, so [didUpdateWidget] must defer; a detached
|
||||
/// controller's show() merely records pending state and is build-safe.
|
||||
bool _portalInTree = 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.
|
||||
@@ -77,12 +83,25 @@ class _FocusGlowOverlayState extends State<FocusGlowOverlay> {
|
||||
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);
|
||||
});
|
||||
if (_portalInTree) {
|
||||
// The portal from a previous glow session is still attached (mid
|
||||
// fade-out, or the rail held the glow back during a vertical scroll):
|
||||
// show() would assert during build, so defer it out of the frame and
|
||||
// fade back in from wherever the fade-out got to.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || !widget.isFocused) return;
|
||||
if (!_controller.isShowing) _controller.show();
|
||||
setState(() => _visible = true);
|
||||
});
|
||||
} else {
|
||||
// Detached: a build-time show() only records pending state, applied
|
||||
// when this build mounts the portal. Start hidden, fade in next frame.
|
||||
_controller.show();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && widget.isFocused) setState(() => _visible = true);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Fade out; _handleFadeEnd hides the portal once opacity reaches 0.
|
||||
setState(() => _visible = false);
|
||||
@@ -98,13 +117,18 @@ class _FocusGlowOverlayState extends State<FocusGlowOverlay> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_disabled) return widget.child;
|
||||
if (_disabled) {
|
||||
_portalInTree = false;
|
||||
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) {
|
||||
_portalInTree = false;
|
||||
return widget.child;
|
||||
}
|
||||
_portalInTree = true;
|
||||
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
|
||||
|
||||
@@ -11,19 +11,10 @@ import 'owned_focus_node_binding.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,
|
||||
});
|
||||
const FocusableActionBuildState({required this.showFocus, required this.animationDuration});
|
||||
}
|
||||
|
||||
class FocusableAction {
|
||||
@@ -41,6 +32,12 @@ class FocusableAction {
|
||||
final Widget? child;
|
||||
final FocusableActionBuilder? builder;
|
||||
|
||||
/// Row gap between this action and the one before it, overriding the bar's
|
||||
/// uniform [FocusableActionBar.spacing]. Lets visually joined pairs (the
|
||||
/// detail screen's split Play button) sit tighter than the rest of the row.
|
||||
/// Ignored on the first action.
|
||||
final double? spacingBefore;
|
||||
|
||||
const FocusableAction({
|
||||
this.icon = Symbols.circle_rounded,
|
||||
this.iconColor,
|
||||
@@ -53,6 +50,7 @@ class FocusableAction {
|
||||
this.onPressed,
|
||||
this.child,
|
||||
this.builder,
|
||||
this.spacingBefore,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,7 +76,6 @@ class FocusableActionBar extends StatefulWidget {
|
||||
final ValueChanged<bool>? onFocusChange;
|
||||
|
||||
final double spacing;
|
||||
final MainAxisSize mainAxisSize;
|
||||
|
||||
const FocusableActionBar({
|
||||
super.key,
|
||||
@@ -90,7 +87,6 @@ class FocusableActionBar extends StatefulWidget {
|
||||
this.onBack,
|
||||
this.onFocusChange,
|
||||
this.spacing = 0,
|
||||
this.mainAxisSize = MainAxisSize.min,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -134,8 +130,7 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
void didUpdateWidget(FocusableActionBar oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (_shouldRebuildFocusNodes(oldWidget)) {
|
||||
_disposeNodes();
|
||||
_initNodes();
|
||||
_rebindNodes(oldWidget.actions);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,31 +143,120 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
return false;
|
||||
}
|
||||
|
||||
void _initNodes() {
|
||||
_focusBindings = [];
|
||||
_focusNodes = [];
|
||||
_focusStates = List<bool>.filled(widget.actions.length, false);
|
||||
for (var i = 0; i < widget.actions.length; i++) {
|
||||
final index = i;
|
||||
final binding = OwnedFocusNodeBinding();
|
||||
binding.bind(
|
||||
externalNode: widget.actions[i].focusNode,
|
||||
debugLabel: widget.actions[i].debugLabel ?? 'ActionBar[$i]',
|
||||
listener: () {
|
||||
final hasFocus = _focusNodes[index].hasFocus;
|
||||
if (_focusStates[index] != hasFocus) {
|
||||
setState(() => _focusStates[index] = hasFocus);
|
||||
}
|
||||
_notifyRowFocusIfChanged();
|
||||
},
|
||||
);
|
||||
_focusBindings.add(binding);
|
||||
_focusNodes.add(binding.node);
|
||||
_focusStates[i] = binding.node.hasFocus;
|
||||
/// Stable identity for matching an action across list changes: the supplied
|
||||
/// [FocusableAction.focusNode] first, else [FocusableAction.debugLabel].
|
||||
/// Unlabeled actions have no identity and only ever match positionally.
|
||||
static Object? _actionIdentity(FocusableAction action) => action.focusNode ?? action.debugLabel;
|
||||
|
||||
/// Whether the action-list shape is unchanged: same length and every
|
||||
/// labeled identity present in both lists sits at the index it had. Only
|
||||
/// then does an unlabeled action's position provably still refer to the
|
||||
/// same conceptual action.
|
||||
bool _unlabeledPositionsStable(List<FocusableAction> oldActions) {
|
||||
if (oldActions.length != widget.actions.length) return false;
|
||||
for (var i = 0; i < oldActions.length; i++) {
|
||||
final identity = _actionIdentity(oldActions[i]);
|
||||
if (identity == null) continue;
|
||||
for (var j = 0; j < widget.actions.length; j++) {
|
||||
if (j != i && _actionIdentity(widget.actions[j]) == identity) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
OwnedFocusNodeBinding _createBinding(FocusableAction action, int index) {
|
||||
final binding = OwnedFocusNodeBinding();
|
||||
binding.bind(
|
||||
externalNode: action.focusNode,
|
||||
debugLabel: action.debugLabel ?? 'ActionBar[$index]',
|
||||
listener: () => _handleBindingFocusChange(binding),
|
||||
);
|
||||
return binding;
|
||||
}
|
||||
|
||||
/// Index resolved at call time: a binding survives action-list changes, so
|
||||
/// a listener must not capture the slot it was created for.
|
||||
void _handleBindingFocusChange(OwnedFocusNodeBinding binding) {
|
||||
final index = _focusBindings.indexOf(binding);
|
||||
if (index != -1) {
|
||||
final hasFocus = binding.node.hasFocus;
|
||||
if (_focusStates[index] != hasFocus) {
|
||||
setState(() => _focusStates[index] = hasFocus);
|
||||
}
|
||||
}
|
||||
_notifyRowFocusIfChanged();
|
||||
}
|
||||
|
||||
void _initNodes() {
|
||||
_focusBindings = [for (var i = 0; i < widget.actions.length; i++) _createBinding(widget.actions[i], i)];
|
||||
_focusNodes = [for (final binding in _focusBindings) binding.node];
|
||||
_focusStates = [for (final node in _focusNodes) node.hasFocus];
|
||||
_hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
|
||||
}
|
||||
|
||||
/// Rebind on an action-list change, reusing the binding of every action
|
||||
/// whose identity survives so its focus node is not disposed out from under
|
||||
/// the user (media detail's watchlist action arrives asynchronously and
|
||||
/// used to drop D-pad focus with the wholesale rebuild). A removed focused
|
||||
/// action is disposed with its listener already detached, so the genuine
|
||||
/// row-focus loss is reported through [_notifyRowFocusIfChanged] here.
|
||||
void _rebindNodes(List<FocusableAction> oldActions) {
|
||||
final oldBindings = _focusBindings;
|
||||
final focusedOldIndex = _focusNodes.indexWhere((node) => node.hasFocus);
|
||||
|
||||
final claimed = List<bool>.filled(oldBindings.length, false);
|
||||
final unlabeledPositionsStable = _unlabeledPositionsStable(oldActions);
|
||||
int? matchOldIndex(int newIndex) {
|
||||
final identity = _actionIdentity(widget.actions[newIndex]);
|
||||
if (identity != null) {
|
||||
for (var i = 0; i < oldActions.length; i++) {
|
||||
if (!claimed[i] && _actionIdentity(oldActions[i]) == identity) return i;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// Positional reuse is the only option for an unlabeled action, but it
|
||||
// is only provably correct while the list shape is unchanged; across an
|
||||
// insertion/removal its successor is unknowable, so fall through to a
|
||||
// fresh binding — genuinely dropping focus beats silently retargeting
|
||||
// the focused binding (and its next Select) onto a different action.
|
||||
if (unlabeledPositionsStable && !claimed[newIndex] && _actionIdentity(oldActions[newIndex]) == null) {
|
||||
return newIndex;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
var focusedNewIndex = -1;
|
||||
final newBindings = <OwnedFocusNodeBinding>[];
|
||||
for (var i = 0; i < widget.actions.length; i++) {
|
||||
final oldIndex = matchOldIndex(i);
|
||||
if (oldIndex == null) {
|
||||
newBindings.add(_createBinding(widget.actions[i], i));
|
||||
continue;
|
||||
}
|
||||
claimed[oldIndex] = true;
|
||||
if (oldIndex == focusedOldIndex) focusedNewIndex = i;
|
||||
newBindings.add(oldBindings[oldIndex]);
|
||||
}
|
||||
|
||||
_focusBindings = newBindings;
|
||||
_focusNodes = [for (final binding in newBindings) binding.node];
|
||||
_focusStates = [for (final node in _focusNodes) node.hasFocus];
|
||||
|
||||
for (var i = 0; i < oldBindings.length; i++) {
|
||||
if (!claimed[i]) oldBindings[i].dispose();
|
||||
}
|
||||
|
||||
// The focused action survived: keep focus on it. The keyed row keeps its
|
||||
// Focus element attached across reorders, so this only re-requests focus
|
||||
// if the framework unfocused the node during widget churn.
|
||||
if (focusedNewIndex != -1 &&
|
||||
widget.actions[focusedNewIndex].onPressed != null &&
|
||||
!_focusNodes[focusedNewIndex].hasFocus) {
|
||||
_focusNodes[focusedNewIndex].requestFocus();
|
||||
}
|
||||
_notifyRowFocusIfChanged();
|
||||
}
|
||||
|
||||
void _notifyRowFocusIfChanged() {
|
||||
final hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
|
||||
if (_hasAnyFocus == hasAnyFocus) return;
|
||||
@@ -198,10 +282,10 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
final duration = FocusTheme.getAnimationDuration(context);
|
||||
|
||||
final row = Row(
|
||||
mainAxisSize: widget.mainAxisSize,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (var i = 0; i < widget.actions.length; i++) ...[
|
||||
if (i > 0 && widget.spacing > 0) SizedBox(width: widget.spacing),
|
||||
if (i > 0 && _gapBefore(i) > 0) SizedBox(width: _gapBefore(i)),
|
||||
_buildButton(i, isKeyboard, duration),
|
||||
],
|
||||
],
|
||||
@@ -215,22 +299,21 @@ class FocusableActionBarState extends State<FocusableActionBar> {
|
||||
return AnimatedOpacity(opacity: isKeyboard && !_hasAnyFocus ? 0.6 : 1.0, duration: duration, child: row);
|
||||
}
|
||||
|
||||
double _gapBefore(int index) => widget.actions[index].spacingBefore ?? widget.spacing;
|
||||
|
||||
Widget _buildButton(int index, bool isKeyboard, Duration duration) {
|
||||
final action = widget.actions[index];
|
||||
final enabled = action.onPressed != null;
|
||||
final isFocused = _focusStates[index];
|
||||
final showFocus = isFocused && isKeyboard;
|
||||
final opacity = isKeyboard && _hasAnyFocus && !isFocused ? 0.6 : 1.0;
|
||||
final buildState = FocusableActionBuildState(
|
||||
focusNode: _focusNodes[index],
|
||||
isFocused: isFocused,
|
||||
showFocus: showFocus,
|
||||
isKeyboardMode: isKeyboard,
|
||||
animationDuration: duration,
|
||||
);
|
||||
final buildState = FocusableActionBuildState(showFocus: showFocus, animationDuration: duration);
|
||||
final customChild = action.builder?.call(context, buildState);
|
||||
|
||||
return Focus(
|
||||
// Keyed on the binding so an insertion moves the element with its node
|
||||
// instead of detaching (and thereby unfocusing) it slot by slot.
|
||||
key: ObjectKey(_focusBindings[index]),
|
||||
focusNode: _focusNodes[index],
|
||||
canRequestFocus: enabled,
|
||||
autofocus: action.autofocus && enabled,
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
|
||||
|
||||
import '../utils/scroll_utils.dart';
|
||||
import 'owned_focus_node_binding.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
import 'dpad_navigator.dart';
|
||||
import 'dpad_select_long_press_controller.dart';
|
||||
import 'key_event_utils.dart';
|
||||
@@ -92,8 +93,12 @@ mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
|
||||
}
|
||||
// Same convention as FocusableTileStateMixin: a chip inside a
|
||||
// scrollable strip (TabChipStrip, filter bars) reveals itself on
|
||||
// focus; a no-op when no ancestor scrollable exists.
|
||||
if (focusNode.hasFocus) scrollContextToCenter(context);
|
||||
// focus; a no-op when no ancestor scrollable exists. Keyboard/D-pad
|
||||
// sessions only — pointer-mode focus is programmatic and invisible,
|
||||
// so revealing it would yank the strip (issue #2031).
|
||||
if (focusNode.hasFocus && InputModeTracker.currentMode == InputMode.keyboard) {
|
||||
scrollContextToCenter(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,25 +38,14 @@ bool _usesTvKeyboard({required TvTextInputPresentation presentation, TextInputTy
|
||||
String? _keyboardHint(InputDecoration? decoration) => decoration?.hintText ?? decoration?.labelText;
|
||||
|
||||
enum TvTextInputAutoOpenBehavior {
|
||||
/// Resolve per presentation: [onFirstFocus] for the native tvOS keyboard —
|
||||
/// arriving at a field opens it once, but returning to it during D-pad
|
||||
/// traversal does not, since it is a modal full-screen surface and
|
||||
/// re-raising it on every pass makes a form untraversable. [onFocus] for the
|
||||
/// in-app Flutter overlay, which is cheap, non-modal, and involves no UIKit
|
||||
/// first responder.
|
||||
/// Resolve per presentation: open-on-first-focus for the native tvOS
|
||||
/// keyboard — arriving at a field opens it once, but returning to it during
|
||||
/// D-pad traversal does not, since it is a modal full-screen surface and
|
||||
/// re-raising it on every pass makes a form untraversable. Open-on-focus for
|
||||
/// the in-app Flutter overlay, which is cheap, non-modal, and involves no
|
||||
/// UIKit first responder.
|
||||
automatic,
|
||||
|
||||
/// Open the selected TV text input presentation whenever the field receives
|
||||
/// focus. On Apple TV this raises the system keyboard on every focus entry,
|
||||
/// including plain D-pad traversal — prefer [automatic] unless the field is
|
||||
/// the sole purpose of its screen.
|
||||
onFocus,
|
||||
|
||||
/// Open on the field's first focus, then stay closed on later focus entries.
|
||||
/// Explicit tap/select still opens it, as does the first focus after a
|
||||
/// focus-node or presentation change.
|
||||
onFirstFocus,
|
||||
|
||||
/// Keep initial focus on the field without opening text input, then open it
|
||||
/// automatically on later focus entries. Explicit tap/select still opens it.
|
||||
afterFirstFocus,
|
||||
@@ -238,9 +227,32 @@ KeyEventResult _handleInputKey({
|
||||
if (result != KeyEventResult.ignored) return finish(result, 'custom-tv-hardware-keyboard');
|
||||
}
|
||||
|
||||
if (onBack != null && key.isBackKey) {
|
||||
if (event is KeyDownEvent) onBack();
|
||||
return finish(KeyEventResult.handled, 'onBack');
|
||||
if (onBack != null && event.logicalKey.isBackKey) {
|
||||
// On TV the native text-input path can swallow the matching KeyUp (the
|
||||
// closing IME session eats it), so back fires on KeyDown — the same
|
||||
// down-only shape as [handleBackKeyAction]'s Apple TV branch, coordinator
|
||||
// mark included so a parallel back dispatch still dedupes. Elsewhere the
|
||||
// shared handler's KeyUp semantics apply.
|
||||
if (PlatformDetector.isTV()) {
|
||||
if (BackKeyUpSuppressor.consumeIfSuppressed(event)) return finish(KeyEventResult.handled, 'onBack');
|
||||
if (event is KeyDownEvent) {
|
||||
BackKeyCoordinator.markHandled();
|
||||
onBack();
|
||||
// onBack may move focus (empty search field -> sidebar); the matching
|
||||
// KeyUp is then delivered to the NEW focus chain, whose shared
|
||||
// handlers act on KeyUp — a second back action. Arm the suppressor
|
||||
// (after onBack, so a modal opened by it cannot clear the arming) so
|
||||
// whichever chain receives the KeyUp swallows it. This cannot pin:
|
||||
// the suppressor's hardware observer clears the armed state once the
|
||||
// physical press ends, and if the IME swallows that KeyUp entirely,
|
||||
// the next back KeyDown is treated as stale arming and passes
|
||||
// through — see _KeyUpSuppressor.
|
||||
BackKeyUpSuppressor.suppressBackUntilKeyUp();
|
||||
}
|
||||
return finish(KeyEventResult.handled, 'onBack');
|
||||
}
|
||||
final backResult = handleBackKeyAction(event, onBack);
|
||||
if (backResult != KeyEventResult.ignored) return finish(backResult, 'onBack');
|
||||
}
|
||||
|
||||
// Enter/numpad enter are left to TextField.onSubmitted. Handle only
|
||||
@@ -906,21 +918,13 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
|
||||
// field should still open it — otherwise typing always costs two
|
||||
// presses — but re-raising it every time D-pad traversal passes back
|
||||
// over the field makes a multi-field form unusable, so `automatic`
|
||||
// resolves to `onFirstFocus` there. Android TV's native IME is a docked
|
||||
// opens only on first focus there. Android TV's native IME is a docked
|
||||
// soft keyboard that does not take over the screen, so it keeps the
|
||||
// historical auto-open. Explicit modes stay literal on both: a caller
|
||||
// that asks for onFocus gets onFocus.
|
||||
// historical auto-open.
|
||||
case TvTextInputAutoOpenBehavior.automatic:
|
||||
if (PlatformDetector.isAppleTV() && _hasSeenNativeTextInputFocus) return;
|
||||
_hasSeenNativeTextInputFocus = true;
|
||||
_setNativeTextInputActivated(true);
|
||||
case TvTextInputAutoOpenBehavior.onFirstFocus:
|
||||
if (_hasSeenNativeTextInputFocus) return;
|
||||
_hasSeenNativeTextInputFocus = true;
|
||||
_setNativeTextInputActivated(true);
|
||||
case TvTextInputAutoOpenBehavior.onFocus:
|
||||
_hasSeenNativeTextInputFocus = true;
|
||||
_setNativeTextInputActivated(true);
|
||||
case TvTextInputAutoOpenBehavior.afterFirstFocus:
|
||||
if (!_hasSeenNativeTextInputFocus) {
|
||||
_hasSeenNativeTextInputFocus = true;
|
||||
@@ -1052,11 +1056,6 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
|
||||
// The Flutter overlay is an in-app, non-modal widget with no UIKit first
|
||||
// responder behind it, so opening it on focus costs nothing.
|
||||
case TvTextInputAutoOpenBehavior.automatic:
|
||||
case TvTextInputAutoOpenBehavior.onFocus:
|
||||
return true;
|
||||
case TvTextInputAutoOpenBehavior.onFirstFocus:
|
||||
if (_hasSeenTvKeyboardFocus) return false;
|
||||
_hasSeenTvKeyboardFocus = true;
|
||||
return true;
|
||||
case TvTextInputAutoOpenBehavior.afterFirstFocus:
|
||||
if (!_hasSeenTvKeyboardFocus) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../utils/scroll_utils.dart';
|
||||
import 'input_mode_tracker.dart';
|
||||
import 'owned_focus_node_binding.dart';
|
||||
|
||||
/// Manages the internal/external FocusNode lifecycle for list-tile widgets and
|
||||
@@ -39,7 +40,10 @@ mixin FocusableTileStateMixin<T extends StatefulWidget> on State<T> {
|
||||
}
|
||||
|
||||
void _onFocusChange() {
|
||||
if (effectiveFocusNode.hasFocus) {
|
||||
// Reveal on focus is keyboard/D-pad-only: pointer-mode focus is
|
||||
// programmatic and invisible, so revealing it would yank the scroll view
|
||||
// (issue #2031).
|
||||
if (effectiveFocusNode.hasFocus && InputModeTracker.currentMode == InputMode.keyboard) {
|
||||
scrollContextToCenter(context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,9 +161,6 @@ class FocusableWrapper extends StatefulWidget {
|
||||
/// Short press triggers [onSelect].
|
||||
final bool enableLongPress;
|
||||
|
||||
/// Duration for long-press detection.
|
||||
final Duration longPressDuration;
|
||||
|
||||
/// Whether to use background color instead of border for focus indicator.
|
||||
/// Useful for video controls where outline doesn't look good.
|
||||
final bool useBackgroundFocus;
|
||||
@@ -223,7 +220,6 @@ class FocusableWrapper extends StatefulWidget {
|
||||
this.canRequestFocus = true,
|
||||
this.onKeyEvent,
|
||||
this.enableLongPress = false,
|
||||
this.longPressDuration = const Duration(milliseconds: 500),
|
||||
this.useBackgroundFocus = false,
|
||||
this.focusColor,
|
||||
this.disableScale = false,
|
||||
@@ -323,8 +319,12 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
_animationController?.reverse();
|
||||
}
|
||||
|
||||
// Auto-scroll into view
|
||||
if (hasFocus && widget.autoScroll) {
|
||||
// Auto-scroll into view. Keyboard/D-pad sessions only: pointer-mode
|
||||
// focus is invisible and only ever parked or restored programmatically
|
||||
// (entry focus targets, a context menu re-focusing its trigger on
|
||||
// close), so revealing it would yank the viewport away from wherever
|
||||
// the user scrolled (issue #2031).
|
||||
if (hasFocus && widget.autoScroll && InputModeTracker.currentMode == InputMode.keyboard) {
|
||||
_scrollIntoView();
|
||||
}
|
||||
|
||||
@@ -458,7 +458,6 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
|
||||
if (widget.enableLongPress) {
|
||||
final result = _selectLongPress.handleKeyEvent(
|
||||
event,
|
||||
duration: widget.longPressDuration,
|
||||
isOwnerActive: () => mounted,
|
||||
onShortPress: () => widget.onSelect?.call(),
|
||||
onLongPress: () => widget.onLongPress?.call(),
|
||||
|
||||
@@ -47,6 +47,19 @@ class InputModeTracker extends StatefulWidget {
|
||||
return of(context, listen: listen) == InputMode.keyboard;
|
||||
}
|
||||
|
||||
/// Live input mode, readable without a [BuildContext].
|
||||
///
|
||||
/// Focus-change listeners fire during key dispatch, before the inherited
|
||||
/// provider has rebuilt for a mode flip, so a context read through [of]
|
||||
/// is one frame stale on the first navigation key of a keyboard session.
|
||||
/// The tracker's own state is updated synchronously by its
|
||||
/// [HardwareKeyboard] handler, which runs before focus traversal moves
|
||||
/// focus. Falls back to the platform default when no tracker is mounted.
|
||||
static InputMode get currentMode => _instance?._mode ?? _defaultMode;
|
||||
|
||||
/// Keyboard/D-pad on TV, pointer everywhere else.
|
||||
static InputMode get _defaultMode => PlatformDetector.isTV() ? InputMode.keyboard : InputMode.pointer;
|
||||
|
||||
/// 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.
|
||||
@@ -74,8 +87,7 @@ class InputModeTracker extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _InputModeTrackerState extends State<InputModeTracker> {
|
||||
// Default to keyboard mode on Android TV, pointer mode elsewhere
|
||||
InputMode _mode = TvDetectionService.isTVSync() ? InputMode.keyboard : InputMode.pointer;
|
||||
InputMode _mode = InputModeTracker._defaultMode;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -134,7 +146,7 @@ class _InputModeTrackerState extends State<InputModeTracker> {
|
||||
Widget build(BuildContext context) {
|
||||
// Non-desktop TVs keep keyboard mode across synthetic pointer events, but
|
||||
// their controls remain pointer-reachable for engine-generated taps.
|
||||
if (TvDetectionService.isTVSync() && !PlatformDetector.isDesktopOS()) {
|
||||
if (PlatformDetector.isTV() && !PlatformDetector.isDesktopOS()) {
|
||||
return _InputModeProvider(mode: _mode, child: widget.child);
|
||||
}
|
||||
|
||||
|
||||
@@ -76,11 +76,10 @@ KeyEventResult handleBackKeyAction(KeyEvent event, VoidCallback onBack) {
|
||||
// AppleTV back (Siri Remote Menu via engine-synthesized escape): run onBack
|
||||
// on KeyDown only; consume KeyUp silently. Some engine paths report Menu as
|
||||
// a non-keyboard device, but the same down-only handling is still required.
|
||||
// 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.
|
||||
// No suppressor arming is needed here: onBack typically calls
|
||||
// Navigator.pop, swapping the focus tree before the matching KeyUp is
|
||||
// dispatched — but the orphaned KeyUp lands on the new chain, where this
|
||||
// same branch consumes it silently.
|
||||
if (PlatformDetector.isAppleTV()) {
|
||||
if (event is KeyDownEvent) {
|
||||
BackKeyCoordinator.markHandled();
|
||||
@@ -246,10 +245,10 @@ 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.)
|
||||
// so the suppressor isn't needed. (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();
|
||||
|
||||
@@ -32,4 +32,12 @@ class HubFocusMemory {
|
||||
final remembered = _perHubMemory[hubKey];
|
||||
return (remembered ?? fallback).clamp(0, itemCount - 1);
|
||||
}
|
||||
|
||||
/// Rewrite a hub's remembered index in place after its content reordered
|
||||
/// underneath it (a Continue Watching refresh, not user navigation). Unlike
|
||||
/// [setForHub] this never moves the cross-hub column hint, and it is a no-op
|
||||
/// for hubs without memory.
|
||||
void remapForHub(String hubKey, int index) {
|
||||
if (_perHubMemory.containsKey(hubKey)) _perHubMemory[hubKey] = index;
|
||||
}
|
||||
}
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Film",
|
||||
"show": "Serial",
|
||||
"season": "Sezon",
|
||||
"episode": "Epizod",
|
||||
"artist": "İfaçı",
|
||||
"album": "Albom",
|
||||
"track": "Mahnı",
|
||||
"collection": "Kolleksiya",
|
||||
"playlist": "Pleylist",
|
||||
"clip": "Klip",
|
||||
"photo": "Şəkil",
|
||||
"folder": "Qovluq"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Lisenziyalar",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Epizod dəyişəndə cari seçimi köçürmək əvəzinə serverdə seçilmiş səs və altyazını tətbiq et",
|
||||
"showChapterMarkersOnTimeline": "Zaman çubuğunda hissə işarələrini göstər",
|
||||
"showChapterMarkersOnTimelineDescription": "Zaman çubuğunu hissə sərhədlərinə böl",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Xüsusi bölmələr epizod sırasına görə",
|
||||
"specialsOrderingDescription": "Xüsusi bölmələrin serialın izləmə sırasındakı yeri",
|
||||
"specialsOrderingServer": "Server sırasını izlə",
|
||||
"specialsOrderingAirDate": "Yayım tarixinə görə qarışdır",
|
||||
"specialsOrderingLast": "Adi mövsümlərdən sonra",
|
||||
"clickVideoTogglesPlayback": "Oynat/fasilə üçün videoya toxun",
|
||||
"clickVideoTogglesPlaybackDescription": "İdarəetməni göstərmək əvəzinə oynatmaq/fasilə etmək üçün videoya toxun.",
|
||||
"videoPlayerControls": "Video oynadıcı idarəetmələri",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Oynatma zamanı tətbiqdən çıxdıqda avtomatik PiP rejiminə keç",
|
||||
"matchContentFrameRate": "Kadr tezliyini uyğunlaşdır",
|
||||
"matchContentFrameRateDescription": "Ekran yenilənmə tezliyini video məzmununa uyğunlaşdır",
|
||||
"matchContentResolution": "Məzmunun görüntü keyfiyyətinə uyğunlaş",
|
||||
"matchContentResolutionDescription": "Ekranı videonun öz görüntü keyfiyyətinə keçirir ki, miqyaslandırmanı televizorunuz etsin. Oxutma zamanı menyular və altyazılar da miqyaslandırılır",
|
||||
"matchRefreshRate": "Yenilənmə tezliyini uyğunlaşdır",
|
||||
"matchRefreshRateDescription": "Tam ekranda ekran yenilənmə tezliyini uyğunlaşdır",
|
||||
"matchDynamicRange": "Dinamik diapazonu uyğunlaşdır",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Daxili DV7-ni məcburi et",
|
||||
"dvConversionDv81Description": "Dolby Vision profile 8.1-ə çevrilməni məcburi et",
|
||||
"dvConversionHevcStripDescription": "Dolby Vision təbəqələrini sil və sadə HEVC kimi təqdim et",
|
||||
"demuxer": "Konteyner demukseri",
|
||||
"demuxerDescription": "Birbaşa oxudulan faylları hansı demukserin təhlil edəcəyi. Fayl düzgün işləmirsə, media3-ə keçin.",
|
||||
"demuxerFfmpeg": "FFmpeg (Tövsiyə olunan)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Açılışda profil soruş",
|
||||
"requireProfileSelectionOnOpenDescription": "Tətbiq hər dəfə açıldıqda profil seçimini göstər",
|
||||
"forceTvMode": "TV rejimini məcburi et",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Altyazılar və konfiqurasiya",
|
||||
"seekAndTiming": "Sarğı və vaxt tənzimləməsi",
|
||||
"behavior": "Davranış",
|
||||
"rememberPlayerChanges": "Pleyer dəyişikliklərini yadda saxla",
|
||||
"rememberPlayerChangesDescription": "Oxutma zamanı edilən dəyişikliklərin harada saxlanacağı və yenidən tətbiq ediləcəyi",
|
||||
"scopePlaybackSpeed": "Oxutma sürəti",
|
||||
"scopeShaderPreset": "Şader ön ayarı",
|
||||
"scopeAspectRatio": "Tərəf nisbəti",
|
||||
"scopeSyncOffsets": "Audio və subtitr sinxronizasiyası",
|
||||
"playerScopeOff": "Saxlama",
|
||||
"playerScopeGlobal": "Hər yerdə",
|
||||
"playerScopeLibrary": "Kitabxana üzrə",
|
||||
"playerScopeTitle": "Serial və ya film üzrə",
|
||||
"exportDialogTitle": "Plezy tənzimləmələrini ixrac et"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Səs",
|
||||
"subtitlesLabel": "Altyazı",
|
||||
"resetToZero": "0ms-yə sıfırla",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} sonra oynadılır",
|
||||
"playsEarlier": "${label} əvvəl oynadılır",
|
||||
"noOffset": "Ofset yoxdur",
|
||||
"letterbox": "Geniş ekran (Letterbox)",
|
||||
"fillScreen": "Ekrana doldur",
|
||||
"stretch": "Gərmək",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Cihaz PiP rejimini dəstəkləmir",
|
||||
"voSwitchFailed": "PiP üçün video çıxışı dəyişdirilə bilmədi",
|
||||
"failed": "PiP rejimi başladılarkən xəta",
|
||||
"prepareFailed": "PiP rejimi hazırlana bilmədi",
|
||||
"unknown": "Xəta baş verdi: ${error}"
|
||||
},
|
||||
"chapters": "Hissələr",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "${username} (${email}) üçün server tapılmadı",
|
||||
"failedToLoadServers": "Serverlər yüklənə bilmədi: ${error}"
|
||||
"failedToLoadServers": "Serverlər yüklənə bilmədi: ${error}",
|
||||
"noValidServers": "Bu hesabda istifadəyə yararlı server tapılmadı"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Başlıq",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} populyar",
|
||||
"rankAiring": "#${n} yayımlanır",
|
||||
"rankRated": "#${n} qiymətləndirilib",
|
||||
"rankFavorited": "#${n} favorit",
|
||||
"rankTrending": "#${n} trenddə",
|
||||
"rankSeasonal": "${season} üçün #${n}",
|
||||
"watchingNow": "${n} izləyir",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Bələdçi yenilənməsi tələb olundu",
|
||||
"rulesProcessRequested": "Qaydaların yenidən qiymətləndirilməsi tələb olundu",
|
||||
"recordShow": "Şounu yaz",
|
||||
"recordSettings": {
|
||||
"startEarly": "Erkən başla (saniyə)",
|
||||
"endLate": "Gec bitir (saniyə)",
|
||||
"newOnly": "Yalnız yeni epizodlar",
|
||||
"anyChannel": "İstənilən kanalda yaz",
|
||||
"anyTime": "İstənilən vaxt yaz",
|
||||
"skipInLibrary": "Kitabxanada artıq olan epizodları ötür",
|
||||
"keepUpTo": "Saxlanılacaq epizodlar",
|
||||
"keepUpToHint": "0 bütün epizodları saxlayır"
|
||||
},
|
||||
"startingInMinutes": "${minutes} dəq sonra başlayır",
|
||||
"dayAtTime": "${day}, saat ${time}",
|
||||
"invalidPlaybackData": "${product} etibarsız Canlı TV oynatma məlumatı qaytardı",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Hamısını təkrarla",
|
||||
"repeatOne": "Birini təkrarla",
|
||||
"instantMixNoServer": "Ani miks üçün heç bir server mövcud deyil",
|
||||
"noAudioUrl": "${track} üçün səs URL-i mövcud deyil"
|
||||
"noAudioUrl": "${track} üçün səs URL-i mövcud deyil",
|
||||
"discography": {
|
||||
"singlesAndEps": "Single-lar və EP-lər",
|
||||
"live": "Canlı",
|
||||
"compilations": "Kompilyasiyalar"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Birlikdə İzlə",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Sil",
|
||||
"guestSwitchUnavailable": "Keçid etmək olmadı — eyniləşdirmə üçün server əlçatan deyil",
|
||||
"guestSwitchFailed": "Keçid etmək olmadı — məzmun tapılmadı",
|
||||
"defaultDisplayName": "İstifadəçi"
|
||||
"defaultDisplayName": "İstifadəçi",
|
||||
"errors": {
|
||||
"timedOut": "Rele serveri vaxtında cavab vermədi",
|
||||
"connectionLost": "Bağlantı seans hazır olmamış kəsildi",
|
||||
"invalidRelayResponse": "Rele serveri gözlənilməz cavab göndərdi",
|
||||
"sessionEnded": "Təşkilatçı seansı bitirdi"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Yükləmələr",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Bu tətbiqi idarə etmək üçün mobil cihazınızı istifadə edin",
|
||||
"startServer": "Serveri başlat",
|
||||
"stopServer": "Serveri dayandır",
|
||||
"minimize": "Yığ"
|
||||
"minimize": "Yığ",
|
||||
"manualAddressHint": "Əl ilə bağlantı ünvanı:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Eyni Plex hesabına sahib Plezy cihazları burada görünür",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Çözücü",
|
||||
"rawDecoder": "Xam çözücü",
|
||||
"tunneling": "Tünelləmə",
|
||||
"passthrough": "Birbaşa ötürmə",
|
||||
"aspect": "Nisbət",
|
||||
"rotation": "Dönmə",
|
||||
"dvSource": "DV mənbəyi",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Prodüser",
|
||||
"country": "Ölkə",
|
||||
"collection": "Kolleksiya",
|
||||
"label": "Etiket",
|
||||
"style": "Stil",
|
||||
"mood": "Əhval-ruhiyyə"
|
||||
"label": "Etiket"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Uyğunlaşdır...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Hissəvi əlçatandır",
|
||||
"statusRequested": "Sorğu göndərildi",
|
||||
"statusProcessing": "Emal edilir",
|
||||
"statusBlocklisted": "Bloklanmış",
|
||||
"couldNotReach": "${url} ünvanına çatmaq olmadı: ${error}",
|
||||
"noInstanceAtUrl": "${url} ünvanında Seerr instansiyası yoxdur (HTTP ${status})",
|
||||
"notInitialized": "Bu Seerr instansiyasının ilkin quraşdırılması tamamlanmayıb",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Başqa profilin qoşulmasını yenidən istifadə edin.",
|
||||
"invalidCredentials": "İstifadəçi adı və ya şifrə yanlışdır",
|
||||
"authResponseNotJson": "Autentifikasiya cavabı etibarlı JSON deyildi",
|
||||
"authResponseIncomplete": "Serverin giriş cavabı natamam idi",
|
||||
"quickConnectRejected": "Quick Connect server tərəfindən rədd edildi",
|
||||
"quickConnectNotJson": "Quick Connect cavabı etibarlı JSON deyildi",
|
||||
"quickConnectMissingFields": "Quick Connect cavabında kod və ya məxfi açar yoxdur",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "Н/Д",
|
||||
"url": "URL",
|
||||
"letterKeys": "АБВ"
|
||||
"letterKeys": "АБВ",
|
||||
"mediaKind": {
|
||||
"movie": "Филм",
|
||||
"show": "Сериал",
|
||||
"season": "Сезон",
|
||||
"episode": "Епизод",
|
||||
"artist": "Изпълнител",
|
||||
"album": "Албум",
|
||||
"track": "Песен",
|
||||
"collection": "Колекция",
|
||||
"playlist": "Плейлист",
|
||||
"clip": "Клип",
|
||||
"photo": "Снимка",
|
||||
"folder": "Папка"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Лицензи",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "При смяна на епизода прилагай избраните на сървъра аудио и субтитри, вместо да се пренася текущият избор",
|
||||
"showChapterMarkersOnTimeline": "Показвай маркери на глави върху времевата линия",
|
||||
"showChapterMarkersOnTimelineDescription": "Разделяй времевата линия на сегменти по границите на главите",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Специални епизоди в реда на епизодите",
|
||||
"specialsOrderingDescription": "Къде се възпроизвеждат специалните епизоди в реда за гледане на сериала",
|
||||
"specialsOrderingServer": "Следвай реда на сървъра",
|
||||
"specialsOrderingAirDate": "Подреждай по дата на излъчване",
|
||||
"specialsOrderingLast": "След редовните сезони",
|
||||
"clickVideoTogglesPlayback": "Клик върху видеото превключва възпроизвеждане/пауза",
|
||||
"clickVideoTogglesPlaybackDescription": "Клик върху видеото пуска/паузира вместо да показва контролите.",
|
||||
"videoPlayerControls": "Контроли на видео плейъра",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Автоматично включвай режима картина в картината при излизане от приложението по време на възпроизвеждане",
|
||||
"matchContentFrameRate": "Напасване към кадровата честота на съдържанието",
|
||||
"matchContentFrameRateDescription": "Напасни честотата на опресняване на дисплея към видео съдържанието",
|
||||
"matchContentResolution": "Съобразяване с разделителната способност на съдържанието",
|
||||
"matchContentResolutionDescription": "Превключва дисплея към собствената разделителна способност на видеото, за да се погрижи телевизорът за мащабирането. По време на възпроизвеждане менютата и субтитрите също се мащабират",
|
||||
"matchRefreshRate": "Напасване на честотата на опресняване",
|
||||
"matchRefreshRateDescription": "Напасни честотата на опресняване на дисплея при цял екран",
|
||||
"matchDynamicRange": "Напасване на динамичния диапазон",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Принуждава директно възпроизвеждане на DV7 и изключва повторния опит за преобразуване",
|
||||
"dvConversionDv81Description": "Принуждава директно преобразуване на RPU към Dolby Vision Profile 8.1",
|
||||
"dvConversionHevcStripDescription": "Премахва слоевете Dolby Vision RPU/EL и подава обикновен HEVC поток",
|
||||
"demuxer": "Демултиплексор на контейнера",
|
||||
"demuxerDescription": "Кой демултиплексор анализира файловете при директно възпроизвеждане. Превключете на media3, ако даден файл създава проблеми.",
|
||||
"demuxerFfmpeg": "FFmpeg (препоръчително)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Питай за профил при отваряне на приложението",
|
||||
"requireProfileSelectionOnOpenDescription": "Показвай избор на профил всеки път при отваряне на приложението",
|
||||
"forceTvMode": "Принуди TV режим",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Субтитри и конфигурация",
|
||||
"seekAndTiming": "Търсене и време",
|
||||
"behavior": "Поведение",
|
||||
"rememberPlayerChanges": "Запомняне на промените в плейъра",
|
||||
"rememberPlayerChangesDescription": "Къде се записва и откъде се прилага отново промяна, направена по време на възпроизвеждане",
|
||||
"scopePlaybackSpeed": "Скорост на възпроизвеждане",
|
||||
"scopeShaderPreset": "Предварителна настройка на шейдъра",
|
||||
"scopeAspectRatio": "Съотношение на страните",
|
||||
"scopeSyncOffsets": "Синхронизация на аудио и субтитри",
|
||||
"playerScopeOff": "Не запазвай",
|
||||
"playerScopeGlobal": "Навсякъде",
|
||||
"playerScopeLibrary": "По библиотека",
|
||||
"playerScopeTitle": "По сериал или филм",
|
||||
"exportDialogTitle": "Експортиране на настройките на Plezy"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Аудио",
|
||||
"subtitlesLabel": "Субтитри",
|
||||
"resetToZero": "Нулирай до 0ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} се възпроизвежда по-късно",
|
||||
"playsEarlier": "${label} се възпроизвежда по-рано",
|
||||
"noOffset": "Без отместване",
|
||||
"letterbox": "Черни ленти",
|
||||
"fillScreen": "Запълни екрана",
|
||||
"stretch": "Разтегни",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Устройството не поддържа режим картина в картината",
|
||||
"voSwitchFailed": "Неуспешна смяна на видео изхода за режим картина в картината",
|
||||
"failed": "Режимът картина в картината не успя да стартира",
|
||||
"prepareFailed": "Режимът картина в картината не можа да бъде подготвен",
|
||||
"unknown": "Възникна грешка: ${error}"
|
||||
},
|
||||
"chapters": "Глави",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "Не са намерени сървъри за ${username} (${email})",
|
||||
"failedToLoadServers": "Неуспешно зареждане на сървъри: ${error}"
|
||||
"failedToLoadServers": "Неуспешно зареждане на сървъри: ${error}",
|
||||
"noValidServers": "Не бяха намерени използваеми сървъри в този акаунт"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Заглавие",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} популярен",
|
||||
"rankAiring": "#${n} в ефир",
|
||||
"rankRated": "#${n} оценен",
|
||||
"rankFavorited": "#${n} най-харесван",
|
||||
"rankTrending": "#${n} в тенденция",
|
||||
"rankSeasonal": "#${n} през ${season}",
|
||||
"watchingNow": "${n} гледат",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Заявено е опресняване на ТВ програмата",
|
||||
"rulesProcessRequested": "Заявена е преоценка на правилата",
|
||||
"recordShow": "Запиши предаването",
|
||||
"recordSettings": {
|
||||
"startEarly": "Започване по-рано (секунди)",
|
||||
"endLate": "Приключване по-късно (секунди)",
|
||||
"newOnly": "Само нови епизоди",
|
||||
"anyChannel": "Записване от всеки канал",
|
||||
"anyTime": "Записване по всяко време",
|
||||
"skipInLibrary": "Пропускане на епизоди, които вече са в библиотеката",
|
||||
"keepUpTo": "Епизоди за запазване",
|
||||
"keepUpToHint": "0 запазва всички епизоди"
|
||||
},
|
||||
"startingInMinutes": "Започва след ${minutes} мин",
|
||||
"dayAtTime": "${day} в ${time}",
|
||||
"invalidPlaybackData": "${product} върна невалидни данни за възпроизвеждане на телевизия на живо",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Повтаряне на всички",
|
||||
"repeatOne": "Повтаряне на една",
|
||||
"instantMixNoServer": "Няма наличен сървър за незабавен микс",
|
||||
"noAudioUrl": "Няма наличен URL за аудиото на ${track}"
|
||||
"noAudioUrl": "Няма наличен URL за аудиото на ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Сингли и EP",
|
||||
"live": "Концертни",
|
||||
"compilations": "Компилации"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Гледане заедно",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Премахни",
|
||||
"guestSwitchUnavailable": "Превключването не е възможно — сървърът е недостъпен за синхронизация",
|
||||
"guestSwitchFailed": "Превключването не е възможно — съдържанието не е намерено на този сървър",
|
||||
"defaultDisplayName": "Потребител"
|
||||
"defaultDisplayName": "Потребител",
|
||||
"errors": {
|
||||
"timedOut": "Релейният сървър не отговори навреме",
|
||||
"connectionLost": "Връзката се затвори, преди сесията да е готова",
|
||||
"invalidRelayResponse": "Релейният сървър изпрати неочакван отговор",
|
||||
"sessionEnded": "Организаторът прекрати сесията"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Изтегляния",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Използвайте мобилното си устройство, за да управлявате това приложение",
|
||||
"startServer": "Стартирай сървър",
|
||||
"stopServer": "Спри сървър",
|
||||
"minimize": "Минимизирай"
|
||||
"minimize": "Минимизирай",
|
||||
"manualAddressHint": "Ръчен адрес за връзка:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Plezy устройства със същия Plex акаунт се показват тук",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Декодер",
|
||||
"rawDecoder": "Суров декодер",
|
||||
"tunneling": "Тунелиране",
|
||||
"passthrough": "Директно предаване",
|
||||
"aspect": "Съотношение",
|
||||
"rotation": "Завъртане",
|
||||
"dvSource": "DV източник",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Продуцент",
|
||||
"country": "Държава",
|
||||
"collection": "Колекция",
|
||||
"label": "Етикет",
|
||||
"style": "Стил",
|
||||
"mood": "Настроение"
|
||||
"label": "Етикет"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Съпостави...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Частично налично",
|
||||
"statusRequested": "Заявено",
|
||||
"statusProcessing": "Обработва се",
|
||||
"statusBlocklisted": "В списъка с блокирани",
|
||||
"couldNotReach": "Неуспешна връзка с ${url}: ${error}",
|
||||
"noInstanceAtUrl": "На ${url} няма инстанция на Seerr (HTTP ${status})",
|
||||
"notInitialized": "Тази инстанция на Seerr не е завършила първоначалната настройка",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Използвай връзка от друг профил. PIN-защитените профили изискват PIN.",
|
||||
"invalidCredentials": "Невалидно потребителско име или парола",
|
||||
"authResponseNotJson": "Отговорът при удостоверяване не беше валиден JSON",
|
||||
"authResponseIncomplete": "Отговорът за вход от сървъра беше непълен",
|
||||
"quickConnectRejected": "Quick Connect беше отхвърлен от сървъра",
|
||||
"quickConnectNotJson": "Отговорът на Quick Connect не беше валиден JSON",
|
||||
"quickConnectMissingFields": "В отговора на Quick Connect липсва код или таен ключ",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Film",
|
||||
"show": "Serie",
|
||||
"season": "Sæson",
|
||||
"episode": "Afsnit",
|
||||
"artist": "Kunstner",
|
||||
"album": "Album",
|
||||
"track": "Nummer",
|
||||
"collection": "Samling",
|
||||
"playlist": "Afspilningsliste",
|
||||
"clip": "Klip",
|
||||
"photo": "Foto",
|
||||
"folder": "Mappe"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licenser",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Ved afsnitsskift anvendes lyden og underteksterne valgt på serveren i stedet for at videreføre det aktuelle valg",
|
||||
"showChapterMarkersOnTimeline": "Vis kapitelmarkører på tidslinjen",
|
||||
"showChapterMarkersOnTimelineDescription": "Opdel tidslinjen ved kapitelgrænser",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Specialafsnit i episoderekkefølge",
|
||||
"specialsOrderingDescription": "Hvor specialafsnit afspilles i seriens visningsrækkefølge",
|
||||
"specialsOrderingServer": "Følg serverrækkefølgen",
|
||||
"specialsOrderingAirDate": "Indflet efter udsendelsesdato",
|
||||
"specialsOrderingLast": "Efter almindelige sæsoner",
|
||||
"clickVideoTogglesPlayback": "Klik på videoen for at skifte mellem afspilning og pause",
|
||||
"clickVideoTogglesPlaybackDescription": "Klik på videoen for at afspille eller sætte på pause i stedet for at vise betjeningsknapperne.",
|
||||
"videoPlayerControls": "Videoafspillerkontroller",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Skift automatisk til billede-i-billede, når du forlader appen under afspilning",
|
||||
"matchContentFrameRate": "Tilpas billedhastigheden til indholdet",
|
||||
"matchContentFrameRateDescription": "Tilpas skærmens opdateringsfrekvens til videoindhold",
|
||||
"matchContentResolution": "Tilpas til indholdets opløsning",
|
||||
"matchContentResolutionDescription": "Skifter skærmen til videoens oprindelige opløsning, så dit tv står for opskaleringen. Menuer og undertekster opskaleres også under afspilning",
|
||||
"matchRefreshRate": "Tilpas opdateringsfrekvensen",
|
||||
"matchRefreshRateDescription": "Tilpas skærmens opdateringsfrekvens i fuld skærm",
|
||||
"matchDynamicRange": "Tilpas dynamikområdet",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Gennemtving indbygget DV7-understøttelse, og undlad at forsøge DV-konvertering igen",
|
||||
"dvConversionDv81Description": "Tving inline RPU-konvertering til Dolby Vision profil 8.1",
|
||||
"dvConversionHevcStripDescription": "Fjern Dolby Vision RPU/EL-lag og brug almindelig HEVC",
|
||||
"demuxer": "Container-demuxer",
|
||||
"demuxerDescription": "Hvilken demuxer der læser direkte afspillede filer. Skift til media3, hvis en fil driller.",
|
||||
"demuxerFfmpeg": "FFmpeg (anbefalet)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Spørg om profil ved åbning",
|
||||
"requireProfileSelectionOnOpenDescription": "Vis profilvalg hver gang appen åbnes",
|
||||
"forceTvMode": "Gennemtving TV-tilstand",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Undertekster og konfiguration",
|
||||
"seekAndTiming": "Søgning og timing",
|
||||
"behavior": "Adfærd",
|
||||
"rememberPlayerChanges": "Husk afspillerændringer",
|
||||
"rememberPlayerChangesDescription": "Hvor en ændring under afspilning gemmes og anvendes igen",
|
||||
"scopePlaybackSpeed": "Afspilningshastighed",
|
||||
"scopeShaderPreset": "Shader-forudindstilling",
|
||||
"scopeAspectRatio": "Billedformat",
|
||||
"scopeSyncOffsets": "Synkronisering af lyd og undertekster",
|
||||
"playerScopeOff": "Gem ikke",
|
||||
"playerScopeGlobal": "Overalt",
|
||||
"playerScopeLibrary": "Pr. bibliotek",
|
||||
"playerScopeTitle": "Pr. serie eller film",
|
||||
"exportDialogTitle": "Eksportér Plezy-indstillinger"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Lyd",
|
||||
"subtitlesLabel": "Undertekster",
|
||||
"resetToZero": "Nulstil til 0ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} afspilles senere",
|
||||
"playsEarlier": "${label} afspilles tidligere",
|
||||
"noOffset": "Ingen forskydning",
|
||||
"letterbox": "Letterbox",
|
||||
"fillScreen": "Fyld skærm",
|
||||
"stretch": "Stræk",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Enheden understøtter ikke billede-i-billede",
|
||||
"voSwitchFailed": "Kunne ikke skifte videooutput til billede-i-billede",
|
||||
"failed": "Billede-i-billede kunne ikke starte",
|
||||
"prepareFailed": "Billede-i-billede kunne ikke forberedes",
|
||||
"unknown": "Der opstod en fejl: ${error}"
|
||||
},
|
||||
"chapters": "Kapitler",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "Ingen servere fundet for ${username} (${email})",
|
||||
"failedToLoadServers": "Kunne ikke indlæse servere: ${error}"
|
||||
"failedToLoadServers": "Kunne ikke indlæse servere: ${error}",
|
||||
"noValidServers": "Der blev ikke fundet nogen brugbare servere på denne konto"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Titel",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} populær",
|
||||
"rankAiring": "#${n} på luften",
|
||||
"rankRated": "#${n} bedømt",
|
||||
"rankFavorited": "#${n} favorit",
|
||||
"rankTrending": "#${n} populær lige nu",
|
||||
"rankSeasonal": "#${n} i ${season}",
|
||||
"watchingNow": "${n} ser med",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Der er anmodet om en opdatering af guiden",
|
||||
"rulesProcessRequested": "Der er anmodet om en ny evaluering af reglerne",
|
||||
"recordShow": "Optag program",
|
||||
"recordSettings": {
|
||||
"startEarly": "Start tidligere (sekunder)",
|
||||
"endLate": "Slut senere (sekunder)",
|
||||
"newOnly": "Kun nye afsnit",
|
||||
"anyChannel": "Optag på alle kanaler",
|
||||
"anyTime": "Optag på alle tidspunkter",
|
||||
"skipInLibrary": "Spring afsnit over, der allerede er i biblioteket",
|
||||
"keepUpTo": "Afsnit der skal beholdes",
|
||||
"keepUpToHint": "0 beholder alle afsnit"
|
||||
},
|
||||
"startingInMinutes": "Starter om ${minutes} min",
|
||||
"dayAtTime": "${day} kl. ${time}",
|
||||
"invalidPlaybackData": "${product} returnerede ugyldige afspilningsdata for Live TV",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Gentag alle",
|
||||
"repeatOne": "Gentag ét nummer",
|
||||
"instantMixNoServer": "Ingen server er tilgængelig til et øjeblikkeligt mix",
|
||||
"noAudioUrl": "Ingen lyd-URL er tilgængelig for ${track}"
|
||||
"noAudioUrl": "Ingen lyd-URL er tilgængelig for ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Singler og EP'er",
|
||||
"live": "Live",
|
||||
"compilations": "Opsamlinger"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Se sammen",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Fjern",
|
||||
"guestSwitchUnavailable": "Kunne ikke skifte — server ikke tilgængelig for synkronisering",
|
||||
"guestSwitchFailed": "Kunne ikke skifte — indhold blev ikke fundet på denne server",
|
||||
"defaultDisplayName": "Bruger"
|
||||
"defaultDisplayName": "Bruger",
|
||||
"errors": {
|
||||
"timedOut": "Relayserveren svarede ikke i tide",
|
||||
"connectionLost": "Forbindelsen blev lukket, før sessionen var klar",
|
||||
"invalidRelayResponse": "Relayserveren sendte et uventet svar",
|
||||
"sessionEnded": "Værten afsluttede sessionen"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Downloads",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Brug din mobilenhed til at styre denne app",
|
||||
"startServer": "Start serveren",
|
||||
"stopServer": "Stop serveren",
|
||||
"minimize": "Minimér"
|
||||
"minimize": "Minimér",
|
||||
"manualAddressHint": "Manuel forbindelsesadresse:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Plezy-enheder med samme Plex-konto vises her",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Dekoder",
|
||||
"rawDecoder": "Rå dekoder",
|
||||
"tunneling": "Tunneling",
|
||||
"passthrough": "Passthrough",
|
||||
"aspect": "Billedformat",
|
||||
"rotation": "Rotation",
|
||||
"dvSource": "DV-kilde",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Producer",
|
||||
"country": "Land",
|
||||
"collection": "Samling",
|
||||
"label": "Etiket",
|
||||
"style": "Stil",
|
||||
"mood": "Stemning"
|
||||
"label": "Etiket"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Match...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Delvist tilgængelig",
|
||||
"statusRequested": "Anmodet",
|
||||
"statusProcessing": "Behandler",
|
||||
"statusBlocklisted": "På blokeringslisten",
|
||||
"couldNotReach": "Kunne ikke nå ${url}: ${error}",
|
||||
"noInstanceAtUrl": "Ingen Seerr-instans på ${url} (HTTP ${status})",
|
||||
"notInitialized": "Denne Seerr-instans har ikke fuldført førstegangsopsætningen",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Genbrug en anden profils forbindelse. PIN-beskyttede profiler kræver en PIN.",
|
||||
"invalidCredentials": "Ugyldigt brugernavn eller ugyldig adgangskode",
|
||||
"authResponseNotJson": "Godkendelsessvaret var ikke gyldig JSON",
|
||||
"authResponseIncomplete": "Loginsvaret fra serveren var ufuldstændigt",
|
||||
"quickConnectRejected": "Quick Connect blev afvist af serveren",
|
||||
"quickConnectNotJson": "Quick Connect-svaret var ikke gyldig JSON",
|
||||
"quickConnectMissingFields": "Quick Connect-svaret mangler en kode eller hemmelighed",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N. v.",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Film",
|
||||
"show": "Serie",
|
||||
"season": "Staffel",
|
||||
"episode": "Episode",
|
||||
"artist": "Interpret",
|
||||
"album": "Album",
|
||||
"track": "Titel",
|
||||
"collection": "Sammlung",
|
||||
"playlist": "Wiedergabeliste",
|
||||
"clip": "Clip",
|
||||
"photo": "Foto",
|
||||
"folder": "Ordner"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Lizenzen",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Beim Episodenwechsel die auf dem Server ausgewählten Audio- und Untertitelspuren übernehmen, statt die aktuelle Auswahl zu übertragen",
|
||||
"showChapterMarkersOnTimeline": "Kapitelmarkierungen auf der Suchleiste anzeigen",
|
||||
"showChapterMarkersOnTimelineDescription": "Die Suchleiste an Kapitelgrenzen unterteilen",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Specials in Episodenreihenfolge",
|
||||
"specialsOrderingDescription": "Wo Specials in der Wiedergabereihenfolge einer Serie abgespielt werden",
|
||||
"specialsOrderingServer": "Serverreihenfolge folgen",
|
||||
"specialsOrderingAirDate": "Nach Ausstrahlungsdatum einfügen",
|
||||
"specialsOrderingLast": "Nach den regulären Staffeln",
|
||||
"clickVideoTogglesPlayback": "Video zum Abspielen oder Pausieren anklicken",
|
||||
"clickVideoTogglesPlaybackDescription": "Video zum Abspielen oder Pausieren anklicken, statt die Steuerung anzuzeigen.",
|
||||
"videoPlayerControls": "Videoplayer-Steuerung",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Beim Verlassen der App während der Wiedergabe automatisch Bild-in-Bild starten",
|
||||
"matchContentFrameRate": "Inhalts-Bildrate anpassen",
|
||||
"matchContentFrameRateDescription": "Bildwiederholrate des Displays an Videoinhalt anpassen",
|
||||
"matchContentResolution": "An Auflösung des Inhalts anpassen",
|
||||
"matchContentResolutionDescription": "Wechselt die Anzeige auf die native Auflösung des Videos, damit dein Fernseher das Hochskalieren übernimmt. Menüs und Untertitel werden während der Wiedergabe ebenfalls hochskaliert",
|
||||
"matchRefreshRate": "Bildwiederholrate anpassen",
|
||||
"matchRefreshRateDescription": "Bildwiederholrate im Vollbild anpassen",
|
||||
"matchDynamicRange": "Dynamikumfang anpassen",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Natives DV7 erzwingen und einen erneuten DV-Konvertierungsversuch unterdrücken",
|
||||
"dvConversionDv81Description": "Inline-RPU-Konvertierung in Dolby-Vision-Profil 8.1 erzwingen",
|
||||
"dvConversionHevcStripDescription": "Dolby-Vision-RPU/EL-Schichten entfernen und reines HEVC ausgeben",
|
||||
"demuxer": "Container-Demuxer",
|
||||
"demuxerDescription": "Welcher Demuxer direkt abgespielte Dateien einliest. Wechsle zu media3, wenn eine Datei Probleme macht.",
|
||||
"demuxerFfmpeg": "FFmpeg (empfohlen)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Profil beim Öffnen abfragen",
|
||||
"requireProfileSelectionOnOpenDescription": "Profilauswahl bei jedem Öffnen der App anzeigen",
|
||||
"forceTvMode": "TV-Modus erzwingen",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Untertitel und Konfiguration",
|
||||
"seekAndTiming": "Spulen & Timing",
|
||||
"behavior": "Verhalten",
|
||||
"rememberPlayerChanges": "Playeränderungen merken",
|
||||
"rememberPlayerChangesDescription": "Wo eine während der Wiedergabe vorgenommene Änderung gespeichert und erneut angewendet wird",
|
||||
"scopePlaybackSpeed": "Wiedergabegeschwindigkeit",
|
||||
"scopeShaderPreset": "Shader-Voreinstellung",
|
||||
"scopeAspectRatio": "Seitenverhältnis",
|
||||
"scopeSyncOffsets": "Audio- und Untertitelsynchronisierung",
|
||||
"playerScopeOff": "Nicht speichern",
|
||||
"playerScopeGlobal": "Überall",
|
||||
"playerScopeLibrary": "Pro Bibliothek",
|
||||
"playerScopeTitle": "Pro Serie oder Film",
|
||||
"exportDialogTitle": "Plezy-Einstellungen exportieren"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Audio",
|
||||
"subtitlesLabel": "Untertitel",
|
||||
"resetToZero": "Auf 0 ms zurücksetzen",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} spielt später",
|
||||
"playsEarlier": "${label} spielt früher",
|
||||
"noOffset": "Kein Offset",
|
||||
"letterbox": "Letterbox",
|
||||
"fillScreen": "Bild füllen",
|
||||
"stretch": "Strecken",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Dieses Gerät unterstützt den Bild-in-Bild-Modus nicht",
|
||||
"voSwitchFailed": "Videoausgabe für Bild-in-Bild konnte nicht umgeschaltet werden",
|
||||
"failed": "Bild-in-Bild konnte nicht gestartet werden",
|
||||
"prepareFailed": "Bild-in-Bild konnte nicht vorbereitet werden",
|
||||
"unknown": "Ein Fehler ist aufgetreten: ${error}"
|
||||
},
|
||||
"chapters": "Kapitel",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "Keine Server gefunden für ${username} (${email})",
|
||||
"failedToLoadServers": "Server konnten nicht geladen werden: ${error}"
|
||||
"failedToLoadServers": "Server konnten nicht geladen werden: ${error}",
|
||||
"noValidServers": "Für dieses Konto wurden keine nutzbaren Server gefunden"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Titel",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} beliebt",
|
||||
"rankAiring": "#${n} derzeit ausgestrahlt",
|
||||
"rankRated": "#${n} bewertet",
|
||||
"rankFavorited": "#${n} favorisiert",
|
||||
"rankTrending": "#${n} angesagt",
|
||||
"rankSeasonal": "#${n} in ${season}",
|
||||
"watchingNow": "${n} schauen gerade",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Aktualisierung des TV-Programms angefordert",
|
||||
"rulesProcessRequested": "Regelauswertung angefordert",
|
||||
"recordShow": "Sendung aufnehmen",
|
||||
"recordSettings": {
|
||||
"startEarly": "Früher starten (Sekunden)",
|
||||
"endLate": "Später beenden (Sekunden)",
|
||||
"newOnly": "Nur neue Episoden",
|
||||
"anyChannel": "Auf jedem Sender aufnehmen",
|
||||
"anyTime": "Zu jeder Zeit aufnehmen",
|
||||
"skipInLibrary": "Episoden überspringen, die schon in der Bibliothek sind",
|
||||
"keepUpTo": "Zu behaltende Episoden",
|
||||
"keepUpToHint": "0 behält alle Episoden"
|
||||
},
|
||||
"startingInMinutes": "Beginnt in ${minutes} Min.",
|
||||
"dayAtTime": "${day} um ${time}",
|
||||
"invalidPlaybackData": "${product} hat ungültige Live-TV-Wiedergabedaten zurückgegeben",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Alle wiederholen",
|
||||
"repeatOne": "Titel wiederholen",
|
||||
"instantMixNoServer": "Für einen Instant Mix ist kein Server verfügbar",
|
||||
"noAudioUrl": "Für ${track} ist keine Audio-URL verfügbar"
|
||||
"noAudioUrl": "Für ${track} ist keine Audio-URL verfügbar",
|
||||
"discography": {
|
||||
"singlesAndEps": "Singles & EPs",
|
||||
"live": "Live",
|
||||
"compilations": "Kompilationen"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Gemeinsam Schauen",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Entfernen",
|
||||
"guestSwitchUnavailable": "Wechsel fehlgeschlagen — Server nicht für Synchronisierung verfügbar",
|
||||
"guestSwitchFailed": "Wechsel fehlgeschlagen — Inhalt auf diesem Server nicht gefunden",
|
||||
"defaultDisplayName": "Benutzer"
|
||||
"defaultDisplayName": "Benutzer",
|
||||
"errors": {
|
||||
"timedOut": "Der Relay-Server hat nicht rechtzeitig geantwortet",
|
||||
"connectionLost": "Die Verbindung wurde geschlossen, bevor die Sitzung bereit war",
|
||||
"invalidRelayResponse": "Der Relay-Server hat eine unerwartete Antwort gesendet",
|
||||
"sessionEnded": "Der Host hat die Sitzung beendet"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Downloads",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Verwende dein Mobilgerät, um diese App zu steuern",
|
||||
"startServer": "Server starten",
|
||||
"stopServer": "Server stoppen",
|
||||
"minimize": "Minimieren"
|
||||
"minimize": "Minimieren",
|
||||
"manualAddressHint": "Manuelle Verbindungsadresse:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Plezy-Geräte mit demselben Plex-Konto erscheinen hier",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Decoder",
|
||||
"rawDecoder": "Raw-Decoder",
|
||||
"tunneling": "Tunneling",
|
||||
"passthrough": "Durchleitung",
|
||||
"aspect": "Seitenverhältnis",
|
||||
"rotation": "Drehung",
|
||||
"dvSource": "DV-Quelle",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Produzent",
|
||||
"country": "Land",
|
||||
"collection": "Sammlung",
|
||||
"label": "Label",
|
||||
"style": "Stil",
|
||||
"mood": "Stimmung"
|
||||
"label": "Label"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Zuordnen...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Teilweise verfügbar",
|
||||
"statusRequested": "Angefragt",
|
||||
"statusProcessing": "Wird verarbeitet",
|
||||
"statusBlocklisted": "Auf der Sperrliste",
|
||||
"couldNotReach": "${url} nicht erreichbar: ${error}",
|
||||
"noInstanceAtUrl": "Keine Seerr-Instanz unter ${url} (HTTP ${status})",
|
||||
"notInitialized": "Die Ersteinrichtung dieser Seerr-Instanz wurde noch nicht abgeschlossen",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Verbindung eines anderen Profils wiederverwenden. PIN-geschützte Profile erfordern eine PIN.",
|
||||
"invalidCredentials": "Ungültiger Benutzername oder ungültiges Passwort",
|
||||
"authResponseNotJson": "Die Authentifizierungsantwort war kein gültiges JSON",
|
||||
"authResponseIncomplete": "Die Anmeldeantwort des Servers war unvollständig",
|
||||
"quickConnectRejected": "Quick Connect wurde vom Server abgelehnt",
|
||||
"quickConnectNotJson": "Die Quick Connect-Antwort war kein gültiges JSON",
|
||||
"quickConnectMissingFields": "In der Quick Connect-Antwort fehlt ein Code oder Geheimnis",
|
||||
|
||||
+63
-14
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Movie",
|
||||
"show": "Show",
|
||||
"season": "Season",
|
||||
"episode": "Episode",
|
||||
"artist": "Artist",
|
||||
"album": "Album",
|
||||
"track": "Track",
|
||||
"collection": "Collection",
|
||||
"playlist": "Playlist",
|
||||
"clip": "Clip",
|
||||
"photo": "Photo",
|
||||
"folder": "Folder"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licenses",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Automatically enter picture-in-picture when you leave the app during playback",
|
||||
"matchContentFrameRate": "Match Content Frame Rate",
|
||||
"matchContentFrameRateDescription": "Match display refresh rate to video content",
|
||||
"matchContentResolution": "Match Content Resolution",
|
||||
"matchContentResolutionDescription": "Switch the display to the video's native resolution so your TV handles upscaling. Menus and subtitles are upscaled too during playback",
|
||||
"matchRefreshRate": "Match Refresh Rate",
|
||||
"matchRefreshRateDescription": "Match display refresh rate in fullscreen",
|
||||
"matchDynamicRange": "Match Dynamic Range",
|
||||
@@ -319,6 +335,10 @@
|
||||
"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",
|
||||
"demuxer": "Container Demuxer",
|
||||
"demuxerDescription": "Which demuxer parses direct-played files. Switch to media3 if a file misbehaves.",
|
||||
"demuxerFfmpeg": "FFmpeg (Recommended)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Ask for profile on app open",
|
||||
"requireProfileSelectionOnOpenDescription": "Show profile selection every time the app is opened",
|
||||
"forceTvMode": "Force TV mode",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Subtitles & Configuration",
|
||||
"seekAndTiming": "Seek & Timing",
|
||||
"behavior": "Behavior",
|
||||
"rememberPlayerChanges": "Remember Player Changes",
|
||||
"rememberPlayerChangesDescription": "Where a change made during playback is saved and reapplied from",
|
||||
"scopePlaybackSpeed": "Playback Speed",
|
||||
"scopeShaderPreset": "Shader Preset",
|
||||
"scopeAspectRatio": "Aspect Ratio",
|
||||
"scopeSyncOffsets": "Audio & Subtitle Sync",
|
||||
"playerScopeOff": "Don't save",
|
||||
"playerScopeGlobal": "Everywhere",
|
||||
"playerScopeLibrary": "Per library",
|
||||
"playerScopeTitle": "Per show or movie",
|
||||
"exportDialogTitle": "Export Plezy settings"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Audio",
|
||||
"subtitlesLabel": "Subtitles",
|
||||
"resetToZero": "Reset to 0ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} plays later",
|
||||
"playsEarlier": "${label} plays earlier",
|
||||
"noOffset": "No offset",
|
||||
"letterbox": "Letterbox",
|
||||
"fillScreen": "Fill screen",
|
||||
"stretch": "Stretch",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Device doesn't support picture-in-picture mode",
|
||||
"voSwitchFailed": "Failed to switch video output for picture-in-picture",
|
||||
"failed": "Picture-in-picture failed to start",
|
||||
"prepareFailed": "Picture-in-picture could not be prepared",
|
||||
"unknown": "An error occurred: ${error}"
|
||||
},
|
||||
"chapters": "Chapters",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "No servers found for ${username} (${email})",
|
||||
"failedToLoadServers": "Failed to load servers: ${error}"
|
||||
"failedToLoadServers": "Failed to load servers: ${error}",
|
||||
"noValidServers": "No usable servers were found on this account"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Title",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} popular",
|
||||
"rankAiring": "#${n} airing",
|
||||
"rankRated": "#${n} rated",
|
||||
"rankFavorited": "#${n} favorited",
|
||||
"rankTrending": "#${n} trending",
|
||||
"rankSeasonal": "#${n} in ${season}",
|
||||
"watchingNow": "${n} watching",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Guide refresh requested",
|
||||
"rulesProcessRequested": "Rule re-evaluation requested",
|
||||
"recordShow": "Record show",
|
||||
"recordSettings": {
|
||||
"startEarly": "Start early (seconds)",
|
||||
"endLate": "End late (seconds)",
|
||||
"newOnly": "Only new episodes",
|
||||
"anyChannel": "Record on any channel",
|
||||
"anyTime": "Record at any time",
|
||||
"skipInLibrary": "Skip episodes already in the library",
|
||||
"keepUpTo": "Episodes to keep",
|
||||
"keepUpToHint": "0 keeps every episode"
|
||||
},
|
||||
"startingInMinutes": "Starting in ${minutes} min",
|
||||
"dayAtTime": "${day} at ${time}",
|
||||
"invalidPlaybackData": "${product} returned invalid Live TV playback data",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Repeat all",
|
||||
"repeatOne": "Repeat one",
|
||||
"instantMixNoServer": "No server is available for an instant mix",
|
||||
"noAudioUrl": "No audio URL is available for ${track}"
|
||||
"noAudioUrl": "No audio URL is available for ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Singles & EPs",
|
||||
"live": "Live",
|
||||
"compilations": "Compilations"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Watch Together",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Remove",
|
||||
"guestSwitchUnavailable": "Couldn't switch — server unavailable for sync",
|
||||
"guestSwitchFailed": "Couldn't switch — content not found on this server",
|
||||
"defaultDisplayName": "User"
|
||||
"defaultDisplayName": "User",
|
||||
"errors": {
|
||||
"timedOut": "The relay did not respond in time",
|
||||
"connectionLost": "The connection closed before the session was ready",
|
||||
"invalidRelayResponse": "The relay sent an unexpected response",
|
||||
"sessionEnded": "The host ended the session"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Downloads",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Use your mobile device to control this app",
|
||||
"startServer": "Start Server",
|
||||
"stopServer": "Stop Server",
|
||||
"minimize": "Minimize"
|
||||
"minimize": "Minimize",
|
||||
"manualAddressHint": "Manual connection address:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Plezy devices with the same Plex account appear here",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Decoder",
|
||||
"rawDecoder": "Raw Decoder",
|
||||
"tunneling": "Tunneling",
|
||||
"passthrough": "Passthrough",
|
||||
"aspect": "Aspect",
|
||||
"rotation": "Rotation",
|
||||
"dvSource": "DV Source",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Producer",
|
||||
"country": "Country",
|
||||
"collection": "Collection",
|
||||
"label": "Label",
|
||||
"style": "Style",
|
||||
"mood": "Mood"
|
||||
"label": "Label"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Match...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Partially available",
|
||||
"statusRequested": "Requested",
|
||||
"statusProcessing": "Processing",
|
||||
"statusBlocklisted": "Blocklisted",
|
||||
"couldNotReach": "Could not reach ${url}: ${error}",
|
||||
"noInstanceAtUrl": "No Seerr instance at ${url} (HTTP ${status})",
|
||||
"notInitialized": "This Seerr instance has not completed first-run setup",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Reuse another profile's connection. PIN-protected profiles require a PIN.",
|
||||
"invalidCredentials": "Invalid username or password",
|
||||
"authResponseNotJson": "The authentication response was not valid JSON",
|
||||
"authResponseIncomplete": "The sign-in response from the server was incomplete",
|
||||
"quickConnectRejected": "Quick Connect was rejected by the server",
|
||||
"quickConnectNotJson": "The Quick Connect response was not valid JSON",
|
||||
"quickConnectMissingFields": "The Quick Connect response is missing a code or secret",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/D",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Película",
|
||||
"show": "Serie",
|
||||
"season": "Temporada",
|
||||
"episode": "Episodio",
|
||||
"artist": "Artista",
|
||||
"album": "Álbum",
|
||||
"track": "Pista",
|
||||
"collection": "Colección",
|
||||
"playlist": "Lista de reproducción",
|
||||
"clip": "Clip",
|
||||
"photo": "Foto",
|
||||
"folder": "Carpeta"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licencias",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Al cambiar de episodio, aplicar el audio y los subtítulos seleccionados en el servidor en lugar de mantener la elección actual",
|
||||
"showChapterMarkersOnTimeline": "Mostrar marcadores de capítulos en la barra de progreso",
|
||||
"showChapterMarkersOnTimelineDescription": "Dividir la barra de progreso en los límites de capítulos",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Especiales en orden de episodios",
|
||||
"specialsOrderingDescription": "Dónde se reproducen los especiales en el orden de visualización de una serie",
|
||||
"specialsOrderingServer": "Seguir orden del servidor",
|
||||
"specialsOrderingAirDate": "Intercalar por fecha de emisión",
|
||||
"specialsOrderingLast": "Después de las temporadas normales",
|
||||
"clickVideoTogglesPlayback": "Clic en el video para reproducir/pausar",
|
||||
"clickVideoTogglesPlaybackDescription": "Haz clic en el video para reproducir/pausar en vez de mostrar controles.",
|
||||
"videoPlayerControls": "Controles del reproductor de video",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Activar automáticamente el modo de imagen en imagen al salir de la aplicación durante la reproducción",
|
||||
"matchContentFrameRate": "Ajustar frecuencia de actualización",
|
||||
"matchContentFrameRateDescription": "Ajustar la frecuencia de pantalla al contenido de video",
|
||||
"matchContentResolution": "Ajustar a la resolución del contenido",
|
||||
"matchContentResolutionDescription": "Cambia la pantalla a la resolución nativa del vídeo para que tu televisor se encargue del escalado. Los menús y los subtítulos también se escalan durante la reproducción",
|
||||
"matchRefreshRate": "Ajustar frecuencia de refresco",
|
||||
"matchRefreshRateDescription": "Ajustar la frecuencia de pantalla en pantalla completa",
|
||||
"matchDynamicRange": "Ajustar rango dinámico",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Forzar DV7 nativo y suprimir el reintento de conversión DV",
|
||||
"dvConversionDv81Description": "Forzar la conversión de RPU en línea al perfil 8.1 de Dolby Vision",
|
||||
"dvConversionHevcStripDescription": "Eliminar las capas RPU/EL de Dolby Vision y presentar HEVC convencional",
|
||||
"demuxer": "Demultiplexor de contenedor",
|
||||
"demuxerDescription": "Qué demultiplexor analiza los archivos de reproducción directa. Cambia a media3 si un archivo da problemas.",
|
||||
"demuxerFfmpeg": "FFmpeg (recomendado)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Pedir perfil al abrir la aplicación",
|
||||
"requireProfileSelectionOnOpenDescription": "Mostrar selección de perfil cada vez que se abre la aplicación",
|
||||
"forceTvMode": "Forzar modo TV",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Subtítulos y configuración",
|
||||
"seekAndTiming": "Desplazamiento y tiempos",
|
||||
"behavior": "Comportamiento",
|
||||
"rememberPlayerChanges": "Recordar cambios del reproductor",
|
||||
"rememberPlayerChangesDescription": "Dónde se guarda y se vuelve a aplicar un cambio realizado durante la reproducción",
|
||||
"scopePlaybackSpeed": "Velocidad de reproducción",
|
||||
"scopeShaderPreset": "Preajuste de sombreado",
|
||||
"scopeAspectRatio": "Relación de aspecto",
|
||||
"scopeSyncOffsets": "Sincronización de audio y subtítulos",
|
||||
"playerScopeOff": "No guardar",
|
||||
"playerScopeGlobal": "En todas partes",
|
||||
"playerScopeLibrary": "Por biblioteca",
|
||||
"playerScopeTitle": "Por serie o película",
|
||||
"exportDialogTitle": "Exportar ajustes de Plezy"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Audio",
|
||||
"subtitlesLabel": "Subtítulos",
|
||||
"resetToZero": "Restablecer a 0ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} se reproduce más tarde",
|
||||
"playsEarlier": "${label} se reproduce antes",
|
||||
"noOffset": "Sin desfase",
|
||||
"letterbox": "Con bandas negras",
|
||||
"fillScreen": "Llenar pantalla",
|
||||
"stretch": "Estirar",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "El dispositivo no admite el modo de imagen en imagen",
|
||||
"voSwitchFailed": "No se pudo cambiar la salida de video para el modo de imagen en imagen",
|
||||
"failed": "No se pudo iniciar el modo de imagen en imagen",
|
||||
"prepareFailed": "No se pudo preparar el modo de imagen en imagen",
|
||||
"unknown": "Ocurrió un error: ${error}"
|
||||
},
|
||||
"chapters": "Capítulos",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "No se encontraron servidores para ${username} (${email})",
|
||||
"failedToLoadServers": "Error al cargar servidores: ${error}"
|
||||
"failedToLoadServers": "Error al cargar servidores: ${error}",
|
||||
"noValidServers": "No se encontraron servidores utilizables en esta cuenta"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Título",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} popular",
|
||||
"rankAiring": "#${n} en emisión",
|
||||
"rankRated": "#${n} puntuado",
|
||||
"rankFavorited": "#${n} favorito",
|
||||
"rankTrending": "#${n} en tendencia",
|
||||
"rankSeasonal": "#${n} en ${season}",
|
||||
"watchingNow": "${n} viendo",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Solicitada actualización de la guía",
|
||||
"rulesProcessRequested": "Solicitada reevaluación de reglas",
|
||||
"recordShow": "Grabar programa",
|
||||
"recordSettings": {
|
||||
"startEarly": "Empezar antes (segundos)",
|
||||
"endLate": "Terminar después (segundos)",
|
||||
"newOnly": "Solo episodios nuevos",
|
||||
"anyChannel": "Grabar en cualquier canal",
|
||||
"anyTime": "Grabar a cualquier hora",
|
||||
"skipInLibrary": "Omitir episodios que ya están en la biblioteca",
|
||||
"keepUpTo": "Episodios que conservar",
|
||||
"keepUpToHint": "0 conserva todos los episodios"
|
||||
},
|
||||
"startingInMinutes": "Empieza en ${minutes} min",
|
||||
"dayAtTime": "${day} a las ${time}",
|
||||
"invalidPlaybackData": "${product} devolvió datos de reproducción de TV en vivo no válidos",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Repetir todo",
|
||||
"repeatOne": "Repetir una",
|
||||
"instantMixNoServer": "No hay ningún servidor disponible para una mezcla instantánea",
|
||||
"noAudioUrl": "No hay ninguna URL de audio disponible para ${track}"
|
||||
"noAudioUrl": "No hay ninguna URL de audio disponible para ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Sencillos y EP",
|
||||
"live": "En directo",
|
||||
"compilations": "Recopilaciones"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Ver juntos",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Eliminar",
|
||||
"guestSwitchUnavailable": "No se pudo cambiar — servidor no disponible para sincronización",
|
||||
"guestSwitchFailed": "No se pudo cambiar — contenido no encontrado en este servidor",
|
||||
"defaultDisplayName": "Usuario"
|
||||
"defaultDisplayName": "Usuario",
|
||||
"errors": {
|
||||
"timedOut": "El servidor de retransmisión no respondió a tiempo",
|
||||
"connectionLost": "La conexión se cerró antes de que la sesión estuviera lista",
|
||||
"invalidRelayResponse": "El servidor de retransmisión envió una respuesta inesperada",
|
||||
"sessionEnded": "El anfitrión finalizó la sesión"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Descargas",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Usa tu dispositivo móvil para controlar esta aplicación",
|
||||
"startServer": "Iniciar servidor",
|
||||
"stopServer": "Detener servidor",
|
||||
"minimize": "Minimizar"
|
||||
"minimize": "Minimizar",
|
||||
"manualAddressHint": "Dirección de conexión manual:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Los dispositivos Plezy con la misma cuenta Plex aparecen aquí",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Decodificador",
|
||||
"rawDecoder": "Decodificador sin procesar",
|
||||
"tunneling": "Túnel",
|
||||
"passthrough": "Transferencia directa",
|
||||
"aspect": "Aspecto",
|
||||
"rotation": "Rotación",
|
||||
"dvSource": "Origen DV",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Productor",
|
||||
"country": "País",
|
||||
"collection": "Colección",
|
||||
"label": "Etiqueta",
|
||||
"style": "Estilo",
|
||||
"mood": "Estado de ánimo"
|
||||
"label": "Etiqueta"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Asociar...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Parcialmente disponible",
|
||||
"statusRequested": "Solicitado",
|
||||
"statusProcessing": "Procesando",
|
||||
"statusBlocklisted": "En la lista de bloqueo",
|
||||
"couldNotReach": "No se pudo conectar con ${url}: ${error}",
|
||||
"noInstanceAtUrl": "No hay ninguna instancia de Seerr en ${url} (HTTP ${status})",
|
||||
"notInitialized": "Esta instancia de Seerr no ha completado la configuración inicial",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Reutiliza la conexión de otro perfil. Los perfiles protegidos con PIN requieren un PIN.",
|
||||
"invalidCredentials": "Usuario o contraseña no válidos",
|
||||
"authResponseNotJson": "La respuesta de autenticación no era un JSON válido",
|
||||
"authResponseIncomplete": "La respuesta de inicio de sesión del servidor estaba incompleta",
|
||||
"quickConnectRejected": "Quick Connect fue rechazado por el servidor",
|
||||
"quickConnectNotJson": "La respuesta de Quick Connect no era un JSON válido",
|
||||
"quickConnectMissingFields": "La respuesta de Quick Connect no incluye el código o el secreto",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Film",
|
||||
"show": "Série",
|
||||
"season": "Saison",
|
||||
"episode": "Épisode",
|
||||
"artist": "Artiste",
|
||||
"album": "Album",
|
||||
"track": "Titre",
|
||||
"collection": "Collection",
|
||||
"playlist": "Playlist",
|
||||
"clip": "Clip",
|
||||
"photo": "Photo",
|
||||
"folder": "Dossier"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licences",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Au changement d'épisode, appliquer l'audio et les sous-titres sélectionnés sur le serveur au lieu de conserver le choix en cours",
|
||||
"showChapterMarkersOnTimeline": "Afficher les marqueurs de chapitres sur la barre de lecture",
|
||||
"showChapterMarkersOnTimelineDescription": "Segmenter la barre de lecture aux limites des chapitres",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Épisodes spéciaux dans l’ordre des épisodes",
|
||||
"specialsOrderingDescription": "Position des épisodes spéciaux dans l’ordre de visionnage d’une série",
|
||||
"specialsOrderingServer": "Suivre l’ordre du serveur",
|
||||
"specialsOrderingAirDate": "Intercaler selon la date de diffusion",
|
||||
"specialsOrderingLast": "Après les saisons normales",
|
||||
"clickVideoTogglesPlayback": "Cliquer sur la vidéo pour alterner entre lecture et pause",
|
||||
"clickVideoTogglesPlaybackDescription": "Cliquer sur la vidéo pour lire ou mettre en pause plutôt que d’afficher les commandes",
|
||||
"videoPlayerControls": "Commandes du lecteur vidéo",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Passer en mode image dans l’image si vous quittez l’application pendant la lecture",
|
||||
"matchContentFrameRate": "Adapter la fréquence d’images au contenu",
|
||||
"matchContentFrameRateDescription": "Adapter la fréquence de rafraîchissement de l’écran au contenu vidéo",
|
||||
"matchContentResolution": "Adapter à la résolution du contenu",
|
||||
"matchContentResolutionDescription": "Bascule l’affichage sur la résolution native de la vidéo pour que votre téléviseur gère la mise à l’échelle. Les menus et les sous-titres sont eux aussi mis à l’échelle pendant la lecture",
|
||||
"matchRefreshRate": "Adapter la fréquence de rafraîchissement",
|
||||
"matchRefreshRateDescription": "Adapter la fréquence d'affichage en plein écran",
|
||||
"matchDynamicRange": "Adapter la plage dynamique",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Forcer le DV7 natif et bloquer la nouvelle tentative de conversion DV",
|
||||
"dvConversionDv81Description": "Forcer la conversion RPU intégrée vers le profil 8.1 de Dolby Vision",
|
||||
"dvConversionHevcStripDescription": "Supprimer les couches RPU/EL Dolby Vision et présenter du HEVC simple",
|
||||
"demuxer": "Démultiplexeur de conteneur",
|
||||
"demuxerDescription": "Quel démultiplexeur analyse les fichiers lus en direct. Passez à media3 si un fichier pose problème.",
|
||||
"demuxerFfmpeg": "FFmpeg (recommandé)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Demander le profil à l'ouverture",
|
||||
"requireProfileSelectionOnOpenDescription": "Afficher la sélection de profil à chaque ouverture de l'application",
|
||||
"forceTvMode": "Forcer le mode TV",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Sous-titres et configuration",
|
||||
"seekAndTiming": "Déplacement et minutage",
|
||||
"behavior": "Comportement",
|
||||
"rememberPlayerChanges": "Mémoriser les modifications du lecteur",
|
||||
"rememberPlayerChangesDescription": "Où une modification effectuée pendant la lecture est enregistrée et réappliquée",
|
||||
"scopePlaybackSpeed": "Vitesse de lecture",
|
||||
"scopeShaderPreset": "Préréglage du shader",
|
||||
"scopeAspectRatio": "Format d’image",
|
||||
"scopeSyncOffsets": "Synchronisation audio et sous-titres",
|
||||
"playerScopeOff": "Ne pas enregistrer",
|
||||
"playerScopeGlobal": "Partout",
|
||||
"playerScopeLibrary": "Par bibliothèque",
|
||||
"playerScopeTitle": "Par série ou film",
|
||||
"exportDialogTitle": "Exporter les paramètres de Plezy"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Audio",
|
||||
"subtitlesLabel": "Sous-titres",
|
||||
"resetToZero": "Réinitialiser à 0 ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} : lecture retardée",
|
||||
"playsEarlier": "${label} : lecture avancée",
|
||||
"noOffset": "Pas de décalage",
|
||||
"letterbox": "Format letterbox",
|
||||
"fillScreen": "Remplir l’écran",
|
||||
"stretch": "Étirer",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Cet appareil ne prend pas en charge le mode image dans l'image",
|
||||
"voSwitchFailed": "Échec du changement de sortie vidéo pour l'image dans l'image",
|
||||
"failed": "Échec du démarrage du mode image dans l'image",
|
||||
"prepareFailed": "Impossible de préparer le mode image dans l'image",
|
||||
"unknown": "Une erreur s'est produite : ${error}"
|
||||
},
|
||||
"chapters": "Chapitres",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "Aucun serveur trouvé pour ${username} (${email})",
|
||||
"failedToLoadServers": "Échec du chargement des serveurs : ${error}"
|
||||
"failedToLoadServers": "Échec du chargement des serveurs : ${error}",
|
||||
"noValidServers": "Aucun serveur utilisable n’a été trouvé sur ce compte"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Titre",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} populaire",
|
||||
"rankAiring": "#${n} en diffusion",
|
||||
"rankRated": "#${n} mieux noté",
|
||||
"rankFavorited": "#${n} favoris",
|
||||
"rankTrending": "#${n} tendance",
|
||||
"rankSeasonal": "#${n} de ${season}",
|
||||
"watchingNow": "${n} regardent",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Mise à jour du guide demandée",
|
||||
"rulesProcessRequested": "Réévaluation des règles demandée",
|
||||
"recordShow": "Enregistrer l'émission",
|
||||
"recordSettings": {
|
||||
"startEarly": "Démarrer en avance (secondes)",
|
||||
"endLate": "Terminer en retard (secondes)",
|
||||
"newOnly": "Uniquement les nouveaux épisodes",
|
||||
"anyChannel": "Enregistrer sur n’importe quelle chaîne",
|
||||
"anyTime": "Enregistrer à n’importe quelle heure",
|
||||
"skipInLibrary": "Ignorer les épisodes déjà présents dans la bibliothèque",
|
||||
"keepUpTo": "Épisodes à conserver",
|
||||
"keepUpToHint": "0 conserve tous les épisodes"
|
||||
},
|
||||
"startingInMinutes": "Commence dans ${minutes} min",
|
||||
"dayAtTime": "${day} à ${time}",
|
||||
"invalidPlaybackData": "${product} a renvoyé des données de lecture de TV en direct non valides",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Tout répéter",
|
||||
"repeatOne": "Répéter le titre",
|
||||
"instantMixNoServer": "Aucun serveur n’est disponible pour créer un mix instantané",
|
||||
"noAudioUrl": "Aucune URL audio n’est disponible pour ${track}"
|
||||
"noAudioUrl": "Aucune URL audio n’est disponible pour ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Singles et EP",
|
||||
"live": "Live",
|
||||
"compilations": "Compilations"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Regarder ensemble",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Supprimer",
|
||||
"guestSwitchUnavailable": "Impossible de changer — serveur indisponible pour la synchronisation",
|
||||
"guestSwitchFailed": "Impossible de changer — contenu introuvable sur ce serveur",
|
||||
"defaultDisplayName": "Utilisateur"
|
||||
"defaultDisplayName": "Utilisateur",
|
||||
"errors": {
|
||||
"timedOut": "Le serveur relais n’a pas répondu à temps",
|
||||
"connectionLost": "La connexion s’est fermée avant que la session ne soit prête",
|
||||
"invalidRelayResponse": "Le serveur relais a renvoyé une réponse inattendue",
|
||||
"sessionEnded": "L’hôte a mis fin à la session"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Téléchargements",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Utilisez votre appareil mobile pour contrôler cette application",
|
||||
"startServer": "Démarrer le serveur",
|
||||
"stopServer": "Arrêter le serveur",
|
||||
"minimize": "Réduire"
|
||||
"minimize": "Réduire",
|
||||
"manualAddressHint": "Adresse de connexion manuelle :"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Les appareils Plezy avec le même compte Plex apparaissent ici",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Décodeur",
|
||||
"rawDecoder": "Décodeur brut",
|
||||
"tunneling": "Tunnel",
|
||||
"passthrough": "Transmission directe",
|
||||
"aspect": "Format",
|
||||
"rotation": "Rotation",
|
||||
"dvSource": "Source DV",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Producteur",
|
||||
"country": "Pays",
|
||||
"collection": "Collection",
|
||||
"label": "Label",
|
||||
"style": "Style",
|
||||
"mood": "Ambiance"
|
||||
"label": "Label"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Associer...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Partiellement disponible",
|
||||
"statusRequested": "Demandé",
|
||||
"statusProcessing": "En cours de traitement",
|
||||
"statusBlocklisted": "Sur la liste de blocage",
|
||||
"couldNotReach": "Impossible de joindre ${url} : ${error}",
|
||||
"noInstanceAtUrl": "Aucune instance Seerr à l’adresse ${url} (HTTP ${status})",
|
||||
"notInitialized": "La configuration initiale de cette instance Seerr n’est pas terminée",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Réutiliser la connexion d'un autre profil. Les profils protégés par PIN exigent un PIN.",
|
||||
"invalidCredentials": "Nom d’utilisateur ou mot de passe incorrect",
|
||||
"authResponseNotJson": "La réponse d’authentification n’était pas au format JSON valide",
|
||||
"authResponseIncomplete": "La réponse de connexion du serveur était incomplète",
|
||||
"quickConnectRejected": "Quick Connect a été refusé par le serveur",
|
||||
"quickConnectNotJson": "La réponse de Quick Connect n’était pas au format JSON valide",
|
||||
"quickConnectMissingFields": "Il manque un code ou un secret dans la réponse de Quick Connect",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Film",
|
||||
"show": "Sorozat",
|
||||
"season": "Évad",
|
||||
"episode": "Epizód",
|
||||
"artist": "Előadó",
|
||||
"album": "Album",
|
||||
"track": "Szám",
|
||||
"collection": "Gyűjtemény",
|
||||
"playlist": "Lejátszási lista",
|
||||
"clip": "Klip",
|
||||
"photo": "Fénykép",
|
||||
"folder": "Mappa"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licencek",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Epizódváltáskor a szerveren kiválasztott hang és felirat lép életbe az aktuális választás átvitele helyett",
|
||||
"showChapterMarkersOnTimeline": "Fejezetjelölők megjelenítése az idősávon",
|
||||
"showChapterMarkersOnTimelineDescription": "Az idősáv felosztása a fejezetek határainál",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Különkiadások epizódsorrendben",
|
||||
"specialsOrderingDescription": "A különkiadások helye a sorozat lejátszási sorrendjében",
|
||||
"specialsOrderingServer": "Szerver szerinti sorrend",
|
||||
"specialsOrderingAirDate": "Adás dátuma szerint közbeszúrva",
|
||||
"specialsOrderingLast": "A normál évadok után",
|
||||
"clickVideoTogglesPlayback": "Kattintás a videóra a lejátszás/szünet váltásához",
|
||||
"clickVideoTogglesPlaybackDescription": "A videóra kattintva vált a lejátszás/szünet, a vezérlők megjelenítése helyett.",
|
||||
"videoPlayerControls": "Videólejátszó vezérlői",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Lejátszás közben az alkalmazás elhagyásakor automatikusan kép a képben módra vált",
|
||||
"matchContentFrameRate": "Képkockasebesség illesztése a tartalomhoz",
|
||||
"matchContentFrameRateDescription": "A kijelző frissítési frekvenciájának igazítása a videóhoz",
|
||||
"matchContentResolution": "Igazítás a tartalom felbontásához",
|
||||
"matchContentResolutionDescription": "A kijelzőt a videó natív felbontására váltja, hogy a felskálázást a tévé végezze. Lejátszás közben a menük és a feliratok is felskálázódnak",
|
||||
"matchRefreshRate": "Frissítési frekvencia illesztése",
|
||||
"matchRefreshRateDescription": "A kijelző frissítési frekvenciájának igazítása teljes képernyőn",
|
||||
"matchDynamicRange": "Dinamikatartomány illesztése",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "A natív DV7 kényszerítése és a DV-átalakítási újrapróbálkozás letiltása",
|
||||
"dvConversionDv81Description": "A közvetlen RPU-átalakítás kényszerítése Dolby Vision Profile 8.1-re",
|
||||
"dvConversionHevcStripDescription": "A Dolby Vision RPU/EL-rétegek eltávolítása és egyszerű HEVC-ként való megjelenítés",
|
||||
"demuxer": "Konténer-demuxer",
|
||||
"demuxerDescription": "Melyik demuxer dolgozza fel a közvetlenül lejátszott fájlokat. Válts media3-ra, ha egy fájl hibásan viselkedik.",
|
||||
"demuxerFfmpeg": "FFmpeg (ajánlott)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Profil kérése az alkalmazás megnyitásakor",
|
||||
"requireProfileSelectionOnOpenDescription": "Profilválasztó megjelenítése minden alkalommal, amikor az alkalmazást megnyitod",
|
||||
"forceTvMode": "TV-mód kényszerítése",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Feliratok és konfiguráció",
|
||||
"seekAndTiming": "Tekerés és időzítés",
|
||||
"behavior": "Viselkedés",
|
||||
"rememberPlayerChanges": "Lejátszó módosításainak megjegyzése",
|
||||
"rememberPlayerChangesDescription": "A lejátszás közben végzett módosítások mentési és újbóli alkalmazási helye",
|
||||
"scopePlaybackSpeed": "Lejátszási sebesség",
|
||||
"scopeShaderPreset": "Shader-előbeállítás",
|
||||
"scopeAspectRatio": "Képarány",
|
||||
"scopeSyncOffsets": "Hang- és feliratszinkronizálás",
|
||||
"playerScopeOff": "Ne mentse",
|
||||
"playerScopeGlobal": "Mindenhol",
|
||||
"playerScopeLibrary": "Könyvtáronként",
|
||||
"playerScopeTitle": "Sorozatonként vagy filmenként",
|
||||
"exportDialogTitle": "Plezy-beállítások exportálása"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Hang",
|
||||
"subtitlesLabel": "Feliratok",
|
||||
"resetToZero": "Visszaállítás 0 ms-ra",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label}: későbbre állítva",
|
||||
"playsEarlier": "${label}: korábbra állítva",
|
||||
"noOffset": "Nincs eltolás",
|
||||
"letterbox": "Fekete sávok",
|
||||
"fillScreen": "Képernyő kitöltése",
|
||||
"stretch": "Nyújtás",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Az eszköz nem támogatja a kép a képben módot",
|
||||
"voSwitchFailed": "Nem sikerült átváltani a videókimenetet a kép a képben módhoz",
|
||||
"failed": "Nem sikerült elindítani a kép a képben módot",
|
||||
"prepareFailed": "Nem sikerült előkészíteni a kép a képben módot",
|
||||
"unknown": "Hiba történt: ${error}"
|
||||
},
|
||||
"chapters": "Fejezetek",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "Nem találhatók szerverek ehhez a fiókhoz: ${username} (${email})",
|
||||
"failedToLoadServers": "Nem sikerült a szerverek betöltése: ${error}"
|
||||
"failedToLoadServers": "Nem sikerült a szerverek betöltése: ${error}",
|
||||
"noValidServers": "Nem található használható szerver ehhez a fiókhoz"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Cím",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} népszerű",
|
||||
"rankAiring": "#${n} adásban",
|
||||
"rankRated": "#${n} értékelt",
|
||||
"rankFavorited": "#${n} kedvenc",
|
||||
"rankTrending": "#${n} felkapott",
|
||||
"rankSeasonal": "#${n} a(z) ${season} évadban",
|
||||
"watchingNow": "${n} nézi",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Műsorújság frissítése kérve",
|
||||
"rulesProcessRequested": "Szabályok újraértékelése kérve",
|
||||
"recordShow": "Műsor rögzítése",
|
||||
"recordSettings": {
|
||||
"startEarly": "Korábbi kezdés (másodperc)",
|
||||
"endLate": "Későbbi befejezés (másodperc)",
|
||||
"newOnly": "Csak új epizódok",
|
||||
"anyChannel": "Felvétel bármelyik csatornáról",
|
||||
"anyTime": "Felvétel bármikor",
|
||||
"skipInLibrary": "A könyvtárban már meglévő epizódok kihagyása",
|
||||
"keepUpTo": "Megtartandó epizódok",
|
||||
"keepUpToHint": "A 0 minden epizódot megtart"
|
||||
},
|
||||
"startingInMinutes": "${minutes} perc múlva kezdődik",
|
||||
"dayAtTime": "${day}, ${time}",
|
||||
"invalidPlaybackData": "A(z) ${product} érvénytelen Élő TV-lejátszási adatokat adott vissza",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Összes ismétlése",
|
||||
"repeatOne": "Egy szám ismétlése",
|
||||
"instantMixNoServer": "Nem érhető el szerver az azonnali mixhez",
|
||||
"noAudioUrl": "Nem érhető el hang-URL ehhez: ${track}"
|
||||
"noAudioUrl": "Nem érhető el hang-URL ehhez: ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Kislemezek és EP-k",
|
||||
"live": "Élő",
|
||||
"compilations": "Válogatások"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Watch Together (Közös nézés)",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Eltávolítás",
|
||||
"guestSwitchUnavailable": "Nem sikerült a váltás — a szerver nem érhető el szinkronizáláshoz",
|
||||
"guestSwitchFailed": "Nem sikerült a váltás — a tartalom nem található ezen a szerveren",
|
||||
"defaultDisplayName": "Felhasználó"
|
||||
"defaultDisplayName": "Felhasználó",
|
||||
"errors": {
|
||||
"timedOut": "A relészerver nem válaszolt időben",
|
||||
"connectionLost": "A kapcsolat lezárult, mielőtt a munkamenet elkészült volna",
|
||||
"invalidRelayResponse": "A relészerver váratlan választ küldött",
|
||||
"sessionEnded": "A házigazda befejezte a munkamenetet"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Letöltések",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Használd a mobileszközödet az alkalmazás vezérléséhez",
|
||||
"startServer": "Szerver indítása",
|
||||
"stopServer": "Szerver leállítása",
|
||||
"minimize": "Kis méret"
|
||||
"minimize": "Kis méret",
|
||||
"manualAddressHint": "Kézi kapcsolódási cím:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Az azonos Plex-fiókot használó Plezy-eszközök itt jelennek meg",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Dekóder",
|
||||
"rawDecoder": "Nyers dekóder",
|
||||
"tunneling": "Alagutazás",
|
||||
"passthrough": "Passthrough",
|
||||
"aspect": "Méretarány",
|
||||
"rotation": "Forgatás",
|
||||
"dvSource": "DV-forrás",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Producer",
|
||||
"country": "Ország",
|
||||
"collection": "Gyűjtemény",
|
||||
"label": "Kiadó",
|
||||
"style": "Stílus",
|
||||
"mood": "Hangulat"
|
||||
"label": "Kiadó"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Párosítás...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Részben elérhető",
|
||||
"statusRequested": "Igényelve",
|
||||
"statusProcessing": "Feldolgozás alatt",
|
||||
"statusBlocklisted": "Tiltólistán",
|
||||
"couldNotReach": "Nem sikerült elérni ezt: ${url}: ${error}",
|
||||
"noInstanceAtUrl": "Nem található Seerr-példány ezen a címen: ${url} (HTTP ${status})",
|
||||
"notInitialized": "Ennek a Seerr-példánynak a kezdeti beállítása még nem fejeződött be",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Egy másik profil kapcsolatának használata. A PIN-kóddal védett profilokhoz PIN-kód szükséges.",
|
||||
"invalidCredentials": "Érvénytelen felhasználónév vagy jelszó",
|
||||
"authResponseNotJson": "A hitelesítési válasz nem érvényes JSON",
|
||||
"authResponseIncomplete": "A szerver bejelentkezési válasza hiányos volt",
|
||||
"quickConnectRejected": "A szerver elutasította a Quick Connect-kérést",
|
||||
"quickConnectNotJson": "A Quick Connect válasza nem érvényes JSON",
|
||||
"quickConnectMissingFields": "A Quick Connect válaszából hiányzik a kód vagy a titkos kulcs",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/D",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Film",
|
||||
"show": "Serie",
|
||||
"season": "Stagione",
|
||||
"episode": "Episodio",
|
||||
"artist": "Artista",
|
||||
"album": "Album",
|
||||
"track": "Traccia",
|
||||
"collection": "Raccolta",
|
||||
"playlist": "Playlist",
|
||||
"clip": "Clip",
|
||||
"photo": "Foto",
|
||||
"folder": "Cartella"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Licenze",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Al cambio di episodio applica l'audio e i sottotitoli selezionati sul server invece di mantenere la scelta corrente",
|
||||
"showChapterMarkersOnTimeline": "Mostra i marcatori dei capitoli sulla barra di avanzamento",
|
||||
"showChapterMarkersOnTimelineDescription": "Segmenta la barra di avanzamento ai confini dei capitoli",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Speciali nell'ordine degli episodi",
|
||||
"specialsOrderingDescription": "Dove vengono riprodotti gli speciali nell'ordine di visione di una serie",
|
||||
"specialsOrderingServer": "Segui l'ordine del server",
|
||||
"specialsOrderingAirDate": "Intercalati per data di trasmissione",
|
||||
"specialsOrderingLast": "Dopo le stagioni normali",
|
||||
"clickVideoTogglesPlayback": "Fai clic sul video per alternare riproduzione e pausa",
|
||||
"clickVideoTogglesPlaybackDescription": "Fai clic sul video per riprodurre o mettere in pausa anziché mostrare i controlli.",
|
||||
"videoPlayerControls": "Controlli del lettore video",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Attiva automaticamente la modalità Picture-in-Picture quando esci dall'app durante la riproduzione",
|
||||
"matchContentFrameRate": "Adatta la frequenza dei fotogrammi",
|
||||
"matchContentFrameRateDescription": "Adatta la frequenza di aggiornamento dello schermo al contenuto video",
|
||||
"matchContentResolution": "Adatta alla risoluzione del contenuto",
|
||||
"matchContentResolutionDescription": "Passa lo schermo alla risoluzione nativa del video, così è la TV a occuparsi dell'upscaling. Durante la riproduzione vengono ridimensionati anche menu e sottotitoli",
|
||||
"matchRefreshRate": "Adatta la frequenza di aggiornamento",
|
||||
"matchRefreshRateDescription": "Adatta la frequenza di aggiornamento dello schermo in modalità a schermo intero",
|
||||
"matchDynamicRange": "Adatta la gamma dinamica",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Forza il DV7 nativo e impedisce nuovi tentativi di conversione DV",
|
||||
"dvConversionDv81Description": "Forza la conversione RPU diretta al profilo Dolby Vision 8.1",
|
||||
"dvConversionHevcStripDescription": "Rimuove i livelli RPU/EL di Dolby Vision e riproduce il video come semplice HEVC",
|
||||
"demuxer": "Demuxer del contenitore",
|
||||
"demuxerDescription": "Quale demuxer analizza i file riprodotti in diretta. Passa a media3 se un file dà problemi.",
|
||||
"demuxerFfmpeg": "FFmpeg (consigliato)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Chiedi di scegliere il profilo all'apertura",
|
||||
"requireProfileSelectionOnOpenDescription": "Mostra la selezione del profilo ogni volta che l'app viene aperta",
|
||||
"forceTvMode": "Forza modalità TV",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Sottotitoli e impostazioni",
|
||||
"seekAndTiming": "Avanzamento e tempi",
|
||||
"behavior": "Comportamento",
|
||||
"rememberPlayerChanges": "Ricorda le modifiche del lettore",
|
||||
"rememberPlayerChangesDescription": "Dove viene salvata e riapplicata una modifica effettuata durante la riproduzione",
|
||||
"scopePlaybackSpeed": "Velocità di riproduzione",
|
||||
"scopeShaderPreset": "Preimpostazione shader",
|
||||
"scopeAspectRatio": "Proporzioni",
|
||||
"scopeSyncOffsets": "Sincronizzazione audio e sottotitoli",
|
||||
"playerScopeOff": "Non salvare",
|
||||
"playerScopeGlobal": "Ovunque",
|
||||
"playerScopeLibrary": "Per libreria",
|
||||
"playerScopeTitle": "Per serie o film",
|
||||
"exportDialogTitle": "Esporta le impostazioni di Plezy"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Audio",
|
||||
"subtitlesLabel": "Sottotitoli",
|
||||
"resetToZero": "Ripristina a 0 ms",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label}: riproduzione ritardata",
|
||||
"playsEarlier": "${label}: riproduzione anticipata",
|
||||
"noOffset": "Nessun ritardo",
|
||||
"letterbox": "Letterbox",
|
||||
"fillScreen": "Riempi lo schermo",
|
||||
"stretch": "Allunga",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Questo dispositivo non supporta la modalità Picture-in-Picture",
|
||||
"voSwitchFailed": "Impossibile cambiare l'uscita video per Picture-in-Picture",
|
||||
"failed": "Impossibile avviare la modalità Picture-in-Picture",
|
||||
"prepareFailed": "Impossibile preparare la modalità Picture-in-Picture",
|
||||
"unknown": "Si è verificato un errore: ${error}"
|
||||
},
|
||||
"chapters": "Capitoli",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "Nessun server trovato per ${username} (${email})",
|
||||
"failedToLoadServers": "Impossibile caricare i server: ${error}"
|
||||
"failedToLoadServers": "Impossibile caricare i server: ${error}",
|
||||
"noValidServers": "Nessun server utilizzabile trovato per questo account"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Titolo",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} popolari",
|
||||
"rankAiring": "#${n} in onda",
|
||||
"rankRated": "#${n} valutati",
|
||||
"rankFavorited": "#${n} preferiti",
|
||||
"rankTrending": "#${n} di tendenza",
|
||||
"rankSeasonal": "#${n} in ${season}",
|
||||
"watchingNow": "${n} in visione",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Aggiornamento della guida richiesto",
|
||||
"rulesProcessRequested": "Rielaborazione delle regole richiesta",
|
||||
"recordShow": "Registra programma",
|
||||
"recordSettings": {
|
||||
"startEarly": "Inizia in anticipo (secondi)",
|
||||
"endLate": "Termina in ritardo (secondi)",
|
||||
"newOnly": "Solo nuovi episodi",
|
||||
"anyChannel": "Registra su qualsiasi canale",
|
||||
"anyTime": "Registra a qualsiasi ora",
|
||||
"skipInLibrary": "Salta gli episodi già presenti nella libreria",
|
||||
"keepUpTo": "Episodi da conservare",
|
||||
"keepUpToHint": "0 conserva tutti gli episodi"
|
||||
},
|
||||
"startingInMinutes": "Inizia tra ${minutes} min",
|
||||
"dayAtTime": "${day} alle ${time}",
|
||||
"invalidPlaybackData": "${product} ha restituito dati di riproduzione della TV in diretta non validi",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Ripeti tutto",
|
||||
"repeatOne": "Ripeti il brano",
|
||||
"instantMixNoServer": "Nessun server disponibile per un mix istantaneo",
|
||||
"noAudioUrl": "Nessun URL audio disponibile per ${track}"
|
||||
"noAudioUrl": "Nessun URL audio disponibile per ${track}",
|
||||
"discography": {
|
||||
"singlesAndEps": "Singoli ed EP",
|
||||
"live": "Dal vivo",
|
||||
"compilations": "Compilation"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Guarda insieme",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Rimuovi",
|
||||
"guestSwitchUnavailable": "Impossibile cambiare — server non disponibile per la sincronizzazione",
|
||||
"guestSwitchFailed": "Impossibile cambiare — contenuto non trovato su questo server",
|
||||
"defaultDisplayName": "Utente"
|
||||
"defaultDisplayName": "Utente",
|
||||
"errors": {
|
||||
"timedOut": "Il server relay non ha risposto in tempo",
|
||||
"connectionLost": "La connessione si è chiusa prima che la sessione fosse pronta",
|
||||
"invalidRelayResponse": "Il server relay ha inviato una risposta imprevista",
|
||||
"sessionEnded": "L’host ha terminato la sessione"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Download",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Usa il tuo dispositivo mobile per controllare questa app",
|
||||
"startServer": "Avvia server",
|
||||
"stopServer": "Arresta server",
|
||||
"minimize": "Riduci"
|
||||
"minimize": "Riduci",
|
||||
"manualAddressHint": "Indirizzo di connessione manuale:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "I dispositivi Plezy con lo stesso account Plex appaiono qui",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Decoder",
|
||||
"rawDecoder": "Decoder raw",
|
||||
"tunneling": "Tunneling",
|
||||
"passthrough": "Passthrough",
|
||||
"aspect": "Proporzioni",
|
||||
"rotation": "Rotazione",
|
||||
"dvSource": "Sorgente DV",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Produttore",
|
||||
"country": "Paese",
|
||||
"collection": "Raccolta",
|
||||
"label": "Etichetta",
|
||||
"style": "Stile",
|
||||
"mood": "Atmosfera"
|
||||
"label": "Etichetta"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Abbina...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Disponibile in parte",
|
||||
"statusRequested": "Richiesto",
|
||||
"statusProcessing": "In elaborazione",
|
||||
"statusBlocklisted": "Nella lista di blocco",
|
||||
"couldNotReach": "Impossibile raggiungere ${url}: ${error}",
|
||||
"noInstanceAtUrl": "Nessuna istanza Seerr all'indirizzo ${url} (HTTP ${status})",
|
||||
"notInitialized": "Questa istanza Seerr non ha completato la configurazione iniziale",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Riutilizza la connessione di un altro profilo. I profili protetti da PIN richiedono un PIN.",
|
||||
"invalidCredentials": "Nome utente o password non validi",
|
||||
"authResponseNotJson": "La risposta di autenticazione non era un JSON valido",
|
||||
"authResponseIncomplete": "La risposta di accesso del server era incompleta",
|
||||
"quickConnectRejected": "Quick Connect è stato rifiutato dal server",
|
||||
"quickConnectNotJson": "La risposta di Quick Connect non era un JSON valido",
|
||||
"quickConnectMissingFields": "Nella risposta di Quick Connect manca un codice o un segreto",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "映画",
|
||||
"show": "テレビ番組",
|
||||
"season": "シーズン",
|
||||
"episode": "エピソード",
|
||||
"artist": "アーティスト",
|
||||
"album": "アルバム",
|
||||
"track": "曲",
|
||||
"collection": "コレクション",
|
||||
"playlist": "プレイリスト",
|
||||
"clip": "クリップ",
|
||||
"photo": "写真",
|
||||
"folder": "フォルダ"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "ライセンス",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "エピソード切り替え時に、現在の選択を引き継ぐ代わりにサーバーで選択された音声と字幕を適用します",
|
||||
"showChapterMarkersOnTimeline": "シークバーにチャプターマーカーを表示",
|
||||
"showChapterMarkersOnTimelineDescription": "チャプターの境界でシークバーを区切る",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "エピソード順にスペシャルを表示",
|
||||
"specialsOrderingDescription": "シリーズの視聴順でスペシャルを再生する位置",
|
||||
"specialsOrderingServer": "サーバーの順序に従う",
|
||||
"specialsOrderingAirDate": "放送日順に挿入",
|
||||
"specialsOrderingLast": "通常シーズンの後",
|
||||
"clickVideoTogglesPlayback": "動画クリックで再生/一時停止を切替",
|
||||
"clickVideoTogglesPlaybackDescription": "コントロール表示ではなく、動画クリックで再生/一時停止します。",
|
||||
"videoPlayerControls": "動画プレーヤーコントロール",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "再生中にアプリを離れると、自動的にピクチャーインピクチャーに切り替えます",
|
||||
"matchContentFrameRate": "コンテンツのフレームレートに合わせる",
|
||||
"matchContentFrameRateDescription": "表示のリフレッシュレートを動画コンテンツに合わせます",
|
||||
"matchContentResolution": "コンテンツの解像度に合わせる",
|
||||
"matchContentResolutionDescription": "テレビ側でアップスケーリングを処理できるよう、ディスプレイを映像本来の解像度に切り替えます。再生中はメニューや字幕もアップスケールされます",
|
||||
"matchRefreshRate": "リフレッシュレートを合わせる",
|
||||
"matchRefreshRateDescription": "全画面時に表示のリフレッシュレートを合わせます",
|
||||
"matchDynamicRange": "ダイナミックレンジを合わせる",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "ネイティブ DV7 を強制し、DV 変換の再試行を抑制します",
|
||||
"dvConversionDv81Description": "Dolby Vision プロファイル 8.1 へのインライン RPU 変換を強制します",
|
||||
"dvConversionHevcStripDescription": "Dolby Vision の RPU/EL レイヤーを削除し、通常の HEVC として扱います",
|
||||
"demuxer": "コンテナデマルチプレクサ",
|
||||
"demuxerDescription": "ダイレクト再生のファイルを解析するデマルチプレクサ。ファイルの再生に問題がある場合は media3 に切り替えてください。",
|
||||
"demuxerFfmpeg": "FFmpeg(推奨)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "アプリ起動時にプロフィールを確認",
|
||||
"requireProfileSelectionOnOpenDescription": "アプリを開くたびにプロフィール選択を表示",
|
||||
"forceTvMode": "TVモードを強制",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "字幕と設定",
|
||||
"seekAndTiming": "シークとタイミング",
|
||||
"behavior": "動作",
|
||||
"rememberPlayerChanges": "プレーヤーの変更を記憶",
|
||||
"rememberPlayerChangesDescription": "再生中に行った変更を保存し、再適用する場所",
|
||||
"scopePlaybackSpeed": "再生速度",
|
||||
"scopeShaderPreset": "シェーダープリセット",
|
||||
"scopeAspectRatio": "アスペクト比",
|
||||
"scopeSyncOffsets": "音声と字幕の同期",
|
||||
"playerScopeOff": "保存しない",
|
||||
"playerScopeGlobal": "すべて",
|
||||
"playerScopeLibrary": "ライブラリごと",
|
||||
"playerScopeTitle": "作品ごと",
|
||||
"exportDialogTitle": "Plezyの設定をエクスポート"
|
||||
},
|
||||
"search": {
|
||||
@@ -596,12 +626,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "音声",
|
||||
"subtitlesLabel": "字幕",
|
||||
"resetToZero": "0msにリセット",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label}を遅らせる",
|
||||
"playsEarlier": "${label}を早める",
|
||||
"noOffset": "オフセットなし",
|
||||
"letterbox": "レターボックス",
|
||||
"fillScreen": "画面を埋める",
|
||||
"stretch": "引き延ばす",
|
||||
@@ -667,6 +692,7 @@
|
||||
"notSupported": "デバイスはピクチャーインピクチャーモードをサポートしていません",
|
||||
"voSwitchFailed": "ピクチャーインピクチャーの映像出力切替に失敗しました",
|
||||
"failed": "ピクチャーインピクチャーの開始に失敗しました",
|
||||
"prepareFailed": "ピクチャーインピクチャーを準備できませんでした",
|
||||
"unknown": "エラーが発生しました: ${error}"
|
||||
},
|
||||
"chapters": "チャプター",
|
||||
@@ -1022,7 +1048,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "${username} (${email})のサーバーが見つかりません",
|
||||
"failedToLoadServers": "サーバーの読み込みに失敗しました: ${error}"
|
||||
"failedToLoadServers": "サーバーの読み込みに失敗しました: ${error}",
|
||||
"noValidServers": "このアカウントで利用可能なサーバーが見つかりませんでした"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "タイトル",
|
||||
@@ -1129,7 +1156,6 @@
|
||||
"rankPopular": "人気 #${n}",
|
||||
"rankAiring": "放送中 #${n}",
|
||||
"rankRated": "評価 #${n}",
|
||||
"rankFavorited": "お気に入り #${n}",
|
||||
"rankTrending": "急上昇 #${n}",
|
||||
"rankSeasonal": "#${n}(${season})",
|
||||
"watchingNow": "${n}人視聴中",
|
||||
@@ -1324,6 +1350,16 @@
|
||||
"guideReloadRequested": "番組表の更新をリクエストしました",
|
||||
"rulesProcessRequested": "録画ルールの再評価をリクエストしました",
|
||||
"recordShow": "番組を録画",
|
||||
"recordSettings": {
|
||||
"startEarly": "早めに開始(秒)",
|
||||
"endLate": "遅めに終了(秒)",
|
||||
"newOnly": "新しいエピソードのみ",
|
||||
"anyChannel": "すべてのチャンネルで録画",
|
||||
"anyTime": "すべての時間帯で録画",
|
||||
"skipInLibrary": "ライブラリにあるエピソードをスキップ",
|
||||
"keepUpTo": "保持するエピソード数",
|
||||
"keepUpToHint": "0 ですべてのエピソードを保持"
|
||||
},
|
||||
"startingInMinutes": "${minutes}分後に開始",
|
||||
"dayAtTime": "${day} ${time}",
|
||||
"invalidPlaybackData": "${product}から無効なライブTV再生データが返されました",
|
||||
@@ -1406,7 +1442,12 @@
|
||||
"repeatAll": "全曲リピート",
|
||||
"repeatOne": "1曲リピート",
|
||||
"instantMixNoServer": "インスタントミックスに利用できるサーバーがありません",
|
||||
"noAudioUrl": "${track}で利用可能な音声URLがありません"
|
||||
"noAudioUrl": "${track}で利用可能な音声URLがありません",
|
||||
"discography": {
|
||||
"singlesAndEps": "シングル・EP",
|
||||
"live": "ライブ",
|
||||
"compilations": "コンピレーション"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "一緒に見る",
|
||||
@@ -1474,7 +1515,13 @@
|
||||
"removeRoom": "削除",
|
||||
"guestSwitchUnavailable": "切り替えられません — 同期に必要なサーバーを利用できません",
|
||||
"guestSwitchFailed": "切り替えられません — このサーバーにコンテンツが見つかりません",
|
||||
"defaultDisplayName": "ユーザー"
|
||||
"defaultDisplayName": "ユーザー",
|
||||
"errors": {
|
||||
"timedOut": "リレーサーバーが時間内に応答しませんでした",
|
||||
"connectionLost": "セッションの準備が整う前に接続が閉じられました",
|
||||
"invalidRelayResponse": "リレーサーバーから予期しない応答が返されました",
|
||||
"sessionEnded": "ホストがセッションを終了しました"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "ダウンロード",
|
||||
@@ -1622,7 +1669,8 @@
|
||||
"usePhoneToControl": "モバイルデバイスでこのアプリを操作できます",
|
||||
"startServer": "サーバーを起動",
|
||||
"stopServer": "サーバーを停止",
|
||||
"minimize": "最小化"
|
||||
"minimize": "最小化",
|
||||
"manualAddressHint": "手動接続アドレス:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "同じPlexアカウントを使用しているPlezyデバイスがここに表示されます",
|
||||
@@ -1716,6 +1764,7 @@
|
||||
"decoder": "デコーダー",
|
||||
"rawDecoder": "Raw デコーダー",
|
||||
"tunneling": "トンネリング",
|
||||
"passthrough": "パススルー",
|
||||
"aspect": "アスペクト",
|
||||
"rotation": "回転",
|
||||
"dvSource": "DV ソース",
|
||||
@@ -1847,9 +1896,7 @@
|
||||
"producer": "プロデューサー",
|
||||
"country": "国",
|
||||
"collection": "コレクション",
|
||||
"label": "ラベル",
|
||||
"style": "スタイル",
|
||||
"mood": "ムード"
|
||||
"label": "ラベル"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "照合…",
|
||||
@@ -1912,6 +1959,7 @@
|
||||
"statusPartiallyAvailable": "一部利用可能",
|
||||
"statusRequested": "リクエスト済み",
|
||||
"statusProcessing": "処理中",
|
||||
"statusBlocklisted": "ブロックリスト登録済み",
|
||||
"couldNotReach": "${url}に接続できませんでした: ${error}",
|
||||
"noInstanceAtUrl": "${url}にSeerrインスタンスがありません(HTTP ${status})",
|
||||
"notInitialized": "このSeerrインスタンスでは初回セットアップが完了していません",
|
||||
@@ -2003,6 +2051,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "別のプロフィールの接続を再利用します。PINで保護されたプロフィールにはPINが必要です。",
|
||||
"invalidCredentials": "ユーザー名またはパスワードが正しくありません",
|
||||
"authResponseNotJson": "認証レスポンスが有効なJSONではありません",
|
||||
"authResponseIncomplete": "サーバーからのサインイン応答が不完全です",
|
||||
"quickConnectRejected": "Quick Connectがサーバーに拒否されました",
|
||||
"quickConnectNotJson": "Quick Connectのレスポンスが有効なJSONではありません",
|
||||
"quickConnectMissingFields": "Quick Connectのレスポンスにコードまたはシークレットがありません",
|
||||
|
||||
+68
-19
@@ -81,7 +81,21 @@
|
||||
},
|
||||
"notAvailable": "N/A",
|
||||
"url": "URL",
|
||||
"letterKeys": "ABC"
|
||||
"letterKeys": "ABC",
|
||||
"mediaKind": {
|
||||
"movie": "Фильм",
|
||||
"show": "Сериал",
|
||||
"season": "Маусым",
|
||||
"episode": "Эпизод",
|
||||
"artist": "Орындаушы",
|
||||
"album": "Альбом",
|
||||
"track": "Трек",
|
||||
"collection": "Жинақ",
|
||||
"playlist": "Ойнату тізімі",
|
||||
"clip": "Клип",
|
||||
"photo": "Фото",
|
||||
"folder": "Қалта"
|
||||
}
|
||||
},
|
||||
"screens": {
|
||||
"licenses": "Лицензиялар",
|
||||
@@ -195,11 +209,11 @@
|
||||
"followServerTrackSelectionsDescription": "Бөлім ауысқанда ағымдағы таңдауды көшірудің орнына серверде таңдалған дыбыс пен субтитрлерді қолдану",
|
||||
"showChapterMarkersOnTimeline": "Уақыт шкаласында бөлім белгілерін көрсету",
|
||||
"showChapterMarkersOnTimelineDescription": "Уақыт шкаласын бөлімдерге бөлу",
|
||||
"specialsOrdering": "",
|
||||
"specialsOrderingDescription": "",
|
||||
"specialsOrderingServer": "",
|
||||
"specialsOrderingAirDate": "",
|
||||
"specialsOrderingLast": "",
|
||||
"specialsOrdering": "Арнайы бөлімдер эпизодтар ретімен",
|
||||
"specialsOrderingDescription": "Арнайы бөлімдер сериалдың көру ретінің қай жерінде ойнатылады",
|
||||
"specialsOrderingServer": "Сервер ретін сақтау",
|
||||
"specialsOrderingAirDate": "Эфир күні бойынша араластыру",
|
||||
"specialsOrderingLast": "Қалыпты маусымдардан кейін",
|
||||
"clickVideoTogglesPlayback": "Ойнату/кідірту үшін видеоны басу",
|
||||
"clickVideoTogglesPlaybackDescription": "Басқару элементтерін көрсету орнына ойнату немесе кідірту",
|
||||
"videoPlayerControls": "Видео ойнатқыш басқару элементтері",
|
||||
@@ -291,6 +305,8 @@
|
||||
"autoPipDescription": "Видео ойнап жатқанда қолданбадан шыққанда авто-PiP режиміне өту",
|
||||
"matchContentFrameRate": "Кадр жиілігін сәйкестендіру",
|
||||
"matchContentFrameRateDescription": "Экран жиілігін видео мазмұнына сәйкестендіру",
|
||||
"matchContentResolution": "Мазмұнның ажыратымдылығына бейімдеу",
|
||||
"matchContentResolutionDescription": "Масштабтауды теледидар орындауы үшін экранды бейненің өз ажыратымдылығына ауыстырады. Ойнату кезінде мәзірлер мен субтитрлер де масштабталады",
|
||||
"matchRefreshRate": "Жаңарту жиілігін сәйкестендіру",
|
||||
"matchRefreshRateDescription": "Толық экранда экран жаңарту жиілігін сәйкестендіру",
|
||||
"matchDynamicRange": "Динамикалық диапазонды сәйкестендіру",
|
||||
@@ -319,6 +335,10 @@
|
||||
"dvConversionNativeDescription": "Ішкі DV7 режимін мәжбүрлеу",
|
||||
"dvConversionDv81Description": "Dolby Vision profile 8.1 форматына түрлендіру",
|
||||
"dvConversionHevcStripDescription": "Dolby Vision қабаттарын алып тастап, HEVC ретінде көрсету",
|
||||
"demuxer": "Контейнер демультиплексоры",
|
||||
"demuxerDescription": "Тікелей ойнатылатын файлдарды қай демультиплексор талдайды. Файл дұрыс ойнатылмаса, media3-ке ауысыңыз.",
|
||||
"demuxerFfmpeg": "FFmpeg (ұсынылады)",
|
||||
"demuxerMedia3": "media3",
|
||||
"requireProfileSelectionOnOpen": "Ашқанда профильді сұрау",
|
||||
"requireProfileSelectionOnOpenDescription": "Қолданба ашылған сайын профильді таңдауды көрсету",
|
||||
"forceTvMode": "TV режимін мәжбүрлеу",
|
||||
@@ -345,6 +365,16 @@
|
||||
"subtitlesAndConfig": "Субтитрлер мен конфигурация",
|
||||
"seekAndTiming": "Айналдыру және уақытты реттеу",
|
||||
"behavior": "Мінез-құлық",
|
||||
"rememberPlayerChanges": "Ойнатқыш өзгерістерін есте сақтау",
|
||||
"rememberPlayerChangesDescription": "Ойнату кезінде жасалған өзгеріс сақталатын және қайта қолданылатын орын",
|
||||
"scopePlaybackSpeed": "Ойнату жылдамдығы",
|
||||
"scopeShaderPreset": "Шейдер алдын ала орнатымы",
|
||||
"scopeAspectRatio": "Кадр пішімі",
|
||||
"scopeSyncOffsets": "Аудио және субтитр синхрондауы",
|
||||
"playerScopeOff": "Сақтамау",
|
||||
"playerScopeGlobal": "Барлық жерде",
|
||||
"playerScopeLibrary": "Кітапхана бойынша",
|
||||
"playerScopeTitle": "Сериал немесе фильм бойынша",
|
||||
"exportDialogTitle": "Plezy параметрлерін экспорттау"
|
||||
},
|
||||
"search": {
|
||||
@@ -599,12 +629,7 @@
|
||||
"videoControls": {
|
||||
"audioLabel": "Дыбыс",
|
||||
"subtitlesLabel": "Субтитр",
|
||||
"resetToZero": "0мс-қа қалпына келтіру",
|
||||
"addTime": "+${amount}${unit}",
|
||||
"minusTime": "-${amount}${unit}",
|
||||
"playsLater": "${label} кейін ойнатылады",
|
||||
"playsEarlier": "${label} бұрын ойнатылады",
|
||||
"noOffset": "Ығысусыз",
|
||||
"letterbox": "Кең экран (Letterbox)",
|
||||
"fillScreen": "Экранды толтыру",
|
||||
"stretch": "Созу",
|
||||
@@ -670,6 +695,7 @@
|
||||
"notSupported": "Құрылғы PiP режимін қолдамайды",
|
||||
"voSwitchFailed": "PiP үшін видео шығысын ауыстыру мүмкін болмады",
|
||||
"failed": "PiP режимін іске қосу қатесі",
|
||||
"prepareFailed": "PiP режимін дайындау мүмкін болмады",
|
||||
"unknown": "Қате орын алды: ${error}"
|
||||
},
|
||||
"chapters": "Бөлімдер",
|
||||
@@ -1027,7 +1053,8 @@
|
||||
},
|
||||
"serverSelection": {
|
||||
"noServersFoundForAccount": "${username} (${email}) үшін серверлер табылмады",
|
||||
"failedToLoadServers": "Серверлерді жүктеу қатесі: ${error}"
|
||||
"failedToLoadServers": "Серверлерді жүктеу қатесі: ${error}",
|
||||
"noValidServers": "Бұл тіркелгіде жарамды сервер табылмады"
|
||||
},
|
||||
"hubDetail": {
|
||||
"title": "Атауы",
|
||||
@@ -1135,7 +1162,6 @@
|
||||
"rankPopular": "#${n} танымал",
|
||||
"rankAiring": "#${n} эфирде",
|
||||
"rankRated": "#${n} бағаланған",
|
||||
"rankFavorited": "#${n} таңдаулы",
|
||||
"rankTrending": "#${n} трендте",
|
||||
"rankSeasonal": "#${n} — ${season}",
|
||||
"watchingNow": "${n} қарауда",
|
||||
@@ -1333,6 +1359,16 @@
|
||||
"guideReloadRequested": "Бағдарламаны жаңарту сұралды",
|
||||
"rulesProcessRequested": "Ережелерді қайта бағалау сұралды",
|
||||
"recordShow": "Шоуды жазу",
|
||||
"recordSettings": {
|
||||
"startEarly": "Ертерек бастау (секунд)",
|
||||
"endLate": "Кешірек аяқтау (секунд)",
|
||||
"newOnly": "Тек жаңа эпизодтар",
|
||||
"anyChannel": "Кез келген арнадан жазу",
|
||||
"anyTime": "Кез келген уақытта жазу",
|
||||
"skipInLibrary": "Кітапханада бар эпизодтарды өткізіп жіберу",
|
||||
"keepUpTo": "Сақталатын эпизодтар",
|
||||
"keepUpToHint": "0 барлық эпизодты сақтайды"
|
||||
},
|
||||
"startingInMinutes": "${minutes} мин кейін басталады",
|
||||
"dayAtTime": "${day}, ${time}",
|
||||
"invalidPlaybackData": "${product} жарамсыз тікелей TV ойнату деректерін қайтарды",
|
||||
@@ -1416,7 +1452,12 @@
|
||||
"repeatAll": "Барлығын қайталау",
|
||||
"repeatOne": "Біреуін қайталау",
|
||||
"instantMixNoServer": "Жедел микс үшін қолжетімді сервер жоқ",
|
||||
"noAudioUrl": "${track} үшін аудио URL-і қолжетімді емес"
|
||||
"noAudioUrl": "${track} үшін аудио URL-і қолжетімді емес",
|
||||
"discography": {
|
||||
"singlesAndEps": "Синглдер және EP",
|
||||
"live": "Жанды",
|
||||
"compilations": "Жинақтар"
|
||||
}
|
||||
},
|
||||
"watchTogether": {
|
||||
"title": "Бірге көру",
|
||||
@@ -1484,7 +1525,13 @@
|
||||
"removeRoom": "Өшіру",
|
||||
"guestSwitchUnavailable": "Ауысу мүмкін болмады",
|
||||
"guestSwitchFailed": "Ауысу мүмкін болмады — мазмұн табылмады",
|
||||
"defaultDisplayName": "Пайдаланушы"
|
||||
"defaultDisplayName": "Пайдаланушы",
|
||||
"errors": {
|
||||
"timedOut": "Реле сервері уақытында жауап бермеді",
|
||||
"connectionLost": "Сеанс дайын болмай тұрып байланыс үзілді",
|
||||
"invalidRelayResponse": "Реле сервері күтпеген жауап жіберді",
|
||||
"sessionEnded": "Ұйымдастырушы сеансты аяқтады"
|
||||
}
|
||||
},
|
||||
"downloads": {
|
||||
"title": "Жүктеулер",
|
||||
@@ -1632,7 +1679,8 @@
|
||||
"usePhoneToControl": "Осы қолданбаны басқару үшін телефоныңызды пайдаланыңыз",
|
||||
"startServer": "Серверді іске қосу",
|
||||
"stopServer": "Серверді тоқтату",
|
||||
"minimize": "Жию"
|
||||
"minimize": "Жию",
|
||||
"manualAddressHint": "Қолмен қосылу мекенжайы:"
|
||||
},
|
||||
"pairing": {
|
||||
"discoveryDescription": "Бірдей Plex тіркелгісіндегі Plezy құрылғылары мұнда көрінеді",
|
||||
@@ -1726,6 +1774,7 @@
|
||||
"decoder": "Декодер",
|
||||
"rawDecoder": "Өңделмеген декодер",
|
||||
"tunneling": "Туннельдеу",
|
||||
"passthrough": "Тікелей өткізу",
|
||||
"aspect": "Қатынас",
|
||||
"rotation": "Бұрылыс",
|
||||
"dvSource": "DV дереккөзі",
|
||||
@@ -1857,9 +1906,7 @@
|
||||
"producer": "Продюсер",
|
||||
"country": "Ел",
|
||||
"collection": "Топтама",
|
||||
"label": "Белгі",
|
||||
"style": "Стиль",
|
||||
"mood": "Көңіл-күй"
|
||||
"label": "Белгі"
|
||||
},
|
||||
"matchScreen": {
|
||||
"match": "Сәйкестендіру...",
|
||||
@@ -1922,6 +1969,7 @@
|
||||
"statusPartiallyAvailable": "Жартылай қолжетімді",
|
||||
"statusRequested": "Сұралды",
|
||||
"statusProcessing": "Өңделуде",
|
||||
"statusBlocklisted": "Бұғаттау тізімінде",
|
||||
"couldNotReach": "${url} мекенжайына қосылу мүмкін болмады: ${error}",
|
||||
"noInstanceAtUrl": "${url} мекенжайында Seerr данасы жоқ (HTTP ${status})",
|
||||
"notInitialized": "Бұл Seerr данасының бастапқы баптауы аяқталмаған",
|
||||
@@ -2013,6 +2061,7 @@
|
||||
"borrowFromAnotherProfileSubtitle": "Басқа профильдің қосылымын қайта пайдалану.",
|
||||
"invalidCredentials": "Пайдаланушы аты немесе құпия сөз қате",
|
||||
"authResponseNotJson": "Аутентификация жауабы жарамды JSON болмады",
|
||||
"authResponseIncomplete": "Сервердің кіру жауабы толық емес",
|
||||
"quickConnectRejected": "Сервер Quick Connect сұрауын қабылдамады",
|
||||
"quickConnectNotJson": "Quick Connect жауабы жарамды JSON болмады",
|
||||
"quickConnectMissingFields": "Quick Connect жауабында код немесе құпия кілт жоқ",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user