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 | ||
|
|
92b0524edb | ||
|
|
bb95d54bac | ||
|
|
36b2549506 | ||
|
|
9c6fcd2625 | ||
|
|
24f63a63c5 | ||
|
|
364cdea59b | ||
|
|
ab199b04cd | ||
|
|
ef2ab13abd | ||
|
|
fc061dc38d | ||
|
|
58b510a6c4 | ||
|
|
ec605fd8b7 | ||
|
|
25b2939f0a | ||
|
|
a7354cd3b6 | ||
|
|
eaccef33dc | ||
|
|
2ff3b350ae | ||
|
|
bb642fce03 | ||
|
|
8069683bd3 | ||
|
|
d1d393eec0 | ||
|
|
972b62f6fa | ||
|
|
ea528b5213 | ||
|
|
5a0b595466 | ||
|
|
35b3e97730 | ||
|
|
2f0a6a6bf5 | ||
|
|
d623c2164f | ||
|
|
8383c7b73b | ||
|
|
be863a0c1c | ||
|
|
fe3460ad12 | ||
|
|
ae001d9ff3 | ||
|
|
18c9f710bb | ||
|
|
7937a7e30a | ||
|
|
991184b451 | ||
|
|
c3dbbf6479 | ||
|
|
f56264dcce | ||
|
|
9cdfe7591e | ||
|
|
48f365ab30 | ||
|
|
093109ae09 | ||
|
|
14cae85931 | ||
|
|
9090ad6283 | ||
|
|
8f9ffc76eb | ||
|
|
12d9865a41 | ||
|
|
688bfdacb4 | ||
|
|
cd4432f27c | ||
|
|
5f6d9dc610 | ||
|
|
ce151a91e8 | ||
|
|
922789c014 | ||
|
|
a49f506a0b | ||
|
|
8cdf04122f | ||
|
|
3e1481c238 | ||
|
|
0d24240af4 | ||
|
|
9769c4e092 | ||
|
|
f291425f20 | ||
|
|
1c1bba7e27 | ||
|
|
26e98e898d | ||
|
|
6663353895 | ||
|
|
83c50d93a2 | ||
|
|
3a704a2b9b | ||
|
|
aff6b6576f | ||
|
|
d19ec625cd | ||
|
|
c2bd1d28fd | ||
|
|
ea356a6112 | ||
|
|
69fadc220d | ||
|
|
5611c6785a | ||
|
|
01279e5fbb | ||
|
|
369c6279d6 | ||
|
|
3177290083 | ||
|
|
a0269c6feb | ||
|
|
f2ef15806a |
+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
|
||||
@@ -36,7 +41,7 @@ env:
|
||||
libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev
|
||||
libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev
|
||||
libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev
|
||||
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
|
||||
libdisplay-info-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
|
||||
ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
|
||||
jobs:
|
||||
@@ -271,13 +276,11 @@ jobs:
|
||||
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
run: |
|
||||
# Create temporary keychain
|
||||
KEYCHAIN_PATH=$RUNNER_TEMP/build.keychain
|
||||
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
||||
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
|
||||
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
||||
|
||||
# Import certificate to keychain
|
||||
CERTIFICATE_PATH=$RUNNER_TEMP/certificate.p12
|
||||
echo "$MACOS_CERTIFICATE_BASE64" | base64 --decode -o $CERTIFICATE_PATH
|
||||
security import $CERTIFICATE_PATH -k $KEYCHAIN_PATH -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
|
||||
@@ -494,6 +497,11 @@ jobs:
|
||||
"data/app.so"
|
||||
"data/icudtl.dat"
|
||||
"data/flutter_assets/NativeAssetsManifest.json"
|
||||
# MSVC runtime bundled by InstallRequiredSystemLibraries in
|
||||
# windows/CMakeLists.txt; without it the app crashes at startup on
|
||||
# machines whose system-wide redist is older than the CI toolset.
|
||||
"msvcp140.dll"
|
||||
"vcruntime140.dll"
|
||||
)
|
||||
$forbiddenFiles = @(
|
||||
"plezy.lib"
|
||||
@@ -857,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
|
||||
@@ -876,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
|
||||
@@ -1040,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: |
|
||||
@@ -657,7 +658,7 @@ jobs:
|
||||
libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev \
|
||||
libharfbuzz-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev \
|
||||
libva-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev \
|
||||
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev \
|
||||
libdisplay-info-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev \
|
||||
liblua5.2-dev rpm libarchive-tools imagemagick ruby-dev build-essential
|
||||
sudo gem install fpm --version 1.17.0 --no-document
|
||||
|
||||
|
||||
+1
-3
@@ -18,9 +18,7 @@ migrate_working_dir/
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
# Keep .vscode/ available for contributors' local configuration.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
|
||||
@@ -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/
|
||||
|
||||
@@ -22,8 +22,8 @@ tags:
|
||||
- pressKey: "Remote Dpad Up"
|
||||
- pressKey: "Remote Dpad Right"
|
||||
- pressKey: "Remote Dpad Right"
|
||||
# The grid row must be matchable before the sort sheet opens, otherwise the
|
||||
# occlusion assertion below would pass for the wrong reason.
|
||||
# Wait for the row before opening the sheet so occlusion is tested against the
|
||||
# grid, not an absent or stale match.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s).*Alpha Archive.*"
|
||||
timeout: 15000
|
||||
@@ -31,9 +31,8 @@ tags:
|
||||
- extendedWaitUntil:
|
||||
visible: "Title"
|
||||
timeout: 10000
|
||||
# The host renders the grid, the barrier, and the sheet in one Stack and never
|
||||
# unmounts the grid, so before 8e1904dd wrapped the barrier in BlockSemantics
|
||||
# an occluded row still read as visible to accessibility and to Maestro.
|
||||
# The grid remains mounted under the Stack; BlockSemantics is required for
|
||||
# occluded rows to disappear from Maestro's accessibility tree.
|
||||
- assertNotVisible: "(?s).*Alpha Archive.*"
|
||||
- pressKey: "Remote Dpad Center"
|
||||
- pressKey: "Remote Dpad Left"
|
||||
|
||||
@@ -16,13 +16,9 @@ tags:
|
||||
visible: "(?s)^(Play|Resume).*$"
|
||||
commands:
|
||||
- pressKey: "Remote Dpad Center"
|
||||
# The TV player opens with its chrome down so the OSD and timebar never sit
|
||||
# over the opening seconds of the picture (#1765), so the Pause button can no
|
||||
# longer stand in for "the player has finished loading". Wait for the detail
|
||||
# screen to go first: the labelled spinner is necessarily up the moment the
|
||||
# player route owns the frame, and it only clears once playback reports its
|
||||
# first frame or gives up, so this can never advance before the media opens.
|
||||
# A give-up lands on the transport assertions below, which is where it belongs.
|
||||
# TV playback starts with chrome hidden (#1765), so wait for its loading label
|
||||
# rather than treating the Pause button as readiness. A failed open reaches the
|
||||
# transport assertions below.
|
||||
- extendedWaitUntil:
|
||||
notVisible: "Overview"
|
||||
timeout: 30000
|
||||
@@ -30,18 +26,14 @@ tags:
|
||||
notVisible: "Loading video"
|
||||
timeout: 30000
|
||||
- assertNotVisible: "(?s)^(Play|Pause)$"
|
||||
# Hardware transport keys drive playback without raising the chrome (#1676):
|
||||
# the player answers with a centred disc (pause) or a side readout (seek), never the
|
||||
# full chrome, so subtitles stay readable.
|
||||
# Pause first — it also freezes the clip, so the seek assertions below cannot
|
||||
# race the end of a short fixture item.
|
||||
# Transport keys keep chrome hidden (#1676); pause first so seeks cannot race
|
||||
# the end of this short fixture.
|
||||
- pressKey: "Remote Media Play Pause"
|
||||
- extendedWaitUntil:
|
||||
visible: "Paused"
|
||||
timeout: 10000
|
||||
- assertNotVisible: "(?s)^Play$"
|
||||
# D-pad seeking reports through the skip badge, never the scrub bar, and
|
||||
# consecutive presses in one direction stack into a running total.
|
||||
# D-pad seeks use the cumulative skip badge, not the scrub bar.
|
||||
- pressKey: "Remote Dpad Right"
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^Seek forward 10 seconds$"
|
||||
@@ -56,7 +48,7 @@ tags:
|
||||
visible: "Playing"
|
||||
timeout: 10000
|
||||
- assertNotVisible: "(?s)^Pause$"
|
||||
# Select stays the deliberate way to bring the chrome back.
|
||||
# Select is the explicit way to restore the chrome.
|
||||
- pressKey: "Remote Dpad Center"
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^(Play|Pause)$"
|
||||
|
||||
@@ -7,10 +7,8 @@ tags:
|
||||
- playback
|
||||
---
|
||||
- runFlow: ../subflows/onboard_jellyfin_tv.yaml
|
||||
# Reach Search with the D-pad, the way 10_tv_settings_navigation.yaml does. A
|
||||
# tap here flips InputModeTracker into pointer mode, which collapses the rail
|
||||
# to icons and leaves no "Search" label to hit — and a percentage coordinate
|
||||
# does not survive the jump from a phone in forced TV mode to a 4K television.
|
||||
# Reach Search by D-pad: taps switch to pointer mode and hide the TV rail label,
|
||||
# while percentage coordinates are not portable across TV sizes.
|
||||
- pressKey: "Remote Dpad Left"
|
||||
- extendedWaitUntil:
|
||||
visible: "Search"
|
||||
@@ -38,11 +36,8 @@ tags:
|
||||
- waitForAnimationToEnd:
|
||||
timeout: 5000
|
||||
- tapOn: "(?s)^Play S1E1$"
|
||||
# The TV player opens with its chrome down (#1765), so the Pause button can no
|
||||
# longer stand in for "the player has finished loading". Wait for the detail
|
||||
# screen to go first: the labelled spinner is necessarily up the moment the
|
||||
# player route owns the frame, and it only clears once playback reports its
|
||||
# first frame or gives up, so this can never advance before the media opens.
|
||||
# The player starts with chrome hidden (#1765); wait for its loading label
|
||||
# rather than using Pause as readiness.
|
||||
- extendedWaitUntil:
|
||||
notVisible: "(?s)^Play S1E1$"
|
||||
timeout: 30000
|
||||
@@ -51,9 +46,7 @@ tags:
|
||||
timeout: 30000
|
||||
- pressKey: "Remote Media Fast Forward"
|
||||
- pressKey: "Remote Media Fast Forward"
|
||||
# Gate on the prompt's own Cancel action, the label the iOS branch below taps.
|
||||
# "Next Episode" is the credits skip button at this point in the episode, so
|
||||
# waiting on it would let Back fire before the prompt ever opened.
|
||||
# Wait for Cancel, not Next Episode (the credits-skip action), before pressing Back.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^Cancel$"
|
||||
timeout: 20000
|
||||
|
||||
@@ -8,10 +8,8 @@ tags:
|
||||
---
|
||||
- runFlow: ../subflows/onboard_jellyfin.yaml
|
||||
- tapOn: "(?s)^Libraries.*"
|
||||
# Every seeded alphabet title carries the same dateadded, so which of them the
|
||||
# "Recently Added" rail returns is not stable across scans. This flow only
|
||||
# needs some playable movie, so accept any of them rather than pinning one and
|
||||
# failing whenever the tie-break lands elsewhere.
|
||||
# All seeded titles share dateadded, so accept any playable Recently Added movie
|
||||
# instead of relying on an unstable tie-break.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s).*(?:Alpha Archive|Bravo Beacon|Charlie Circuit|Delta Drive|Echo Engine|Foxtrot Frame|Gamma Garden|Hotel Horizon|India Index|Juliet Junction|Kilo Key|Lima Loop|Mike Matrix|November Node|Oscar Orbit|Papa Pipeline|Quebec Queue|Romeo Relay|Sierra Signal|Tango Track|Uniform Update|Victor View|Whiskey Widget|Xray XML|Yankee Yield|Zulu Zone).*, movie, .*"
|
||||
timeout: 15000
|
||||
|
||||
@@ -7,20 +7,9 @@ tags:
|
||||
- settings
|
||||
- sheets
|
||||
---
|
||||
# Guards 8e1904dd and c48cbf70 together.
|
||||
#
|
||||
# On a phone, Settings is a pushed route. Before c48cbf70 it carried no
|
||||
# OverlaySheetHost, so Manage Libraries fell back to showModalBottomSheet and a
|
||||
# single Back tore down the sheet *and* Settings. Before 8e1904dd the host
|
||||
# answered the platform pop with a TV-only dedup marker that could already be
|
||||
# spent, stranding the sheet open with no way out. Either defect fails the
|
||||
# "Manage Libraries is still there after one Back" assertion below.
|
||||
#
|
||||
# The same commit blocks semantics behind the barrier, so the occlusion
|
||||
# assertions pin that an open sheet actually hides the rows underneath.
|
||||
# Pristine state on purpose. The TV regressions in the same CI group leave
|
||||
# "Force TV mode" enabled, and this flow asserts the handheld Settings route,
|
||||
# so it must not inherit whichever layout the previous flow left behind.
|
||||
# Guards 8e1904dd and c48cbf70: phone Settings must host the sheet so one Back
|
||||
# dismisses only the sheet, while BlockSemantics hides rows behind the barrier.
|
||||
# Start clean because preceding TV flows may leave Force TV mode enabled.
|
||||
- runFlow: ../subflows/onboard_jellyfin.yaml
|
||||
- runFlow: ../subflows/open_settings.yaml
|
||||
- assertVisible: "(?s)^Services.*"
|
||||
@@ -29,10 +18,8 @@ tags:
|
||||
- extendedWaitUntil:
|
||||
visible: "Maestro Movies"
|
||||
timeout: 15000
|
||||
# The barrier swallows every pointer event, so the rows behind it must leave
|
||||
# the semantics tree too. Without BlockSemantics an occluded row still reads as
|
||||
# visible and a tap on it lands on the barrier instead. "Manage Libraries" is
|
||||
# excluded on purpose: it is also the sheet's own title.
|
||||
# The barrier removes covered rows from semantics; the sheet title remains
|
||||
# visible because it belongs to the sheet.
|
||||
- assertNotVisible: "(?s)^Services.*"
|
||||
- assertNotVisible: "(?s)^Video Playback.*"
|
||||
- assertNotVisible: "(?s)^Appearance.*"
|
||||
@@ -41,15 +28,13 @@ tags:
|
||||
- waitForAnimationToEnd:
|
||||
timeout: 3000
|
||||
- assertNotVisible: "Maestro Movies"
|
||||
# One Back closed only the sheet: Settings is still the current route.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^Manage Libraries.*"
|
||||
timeout: 10000
|
||||
- assertVisible: "(?s)^Services.*"
|
||||
- assertVisible: "(?s)^Video Playback.*"
|
||||
- assertNotVisible: "Discover"
|
||||
# Reopening proves the host did not strand the one-shot dedup marker: a second
|
||||
# dismissal has to work exactly like the first.
|
||||
# Reopening verifies the one-shot pop deduplication marker was not stranded.
|
||||
- tapOn: "(?s)^Manage Libraries.*"
|
||||
- extendedWaitUntil:
|
||||
visible: "Maestro Movies"
|
||||
|
||||
@@ -7,20 +7,10 @@ tags:
|
||||
- playback
|
||||
- subtitles
|
||||
---
|
||||
# Guards 468d6804. When a source advertises tracks the native list has not
|
||||
# produced yet, TrackManager arms an automatic selection pass with a 5s first
|
||||
# attempt and a 25s deadline. A user pick made inside that window used to only
|
||||
# persist the preference, leaving the pass armed, so the choice snapped back to
|
||||
# the server/profile preferred track up to ~30s later. The pick now retires the
|
||||
# pending pass, and the wait below is long enough to outlive both timers.
|
||||
#
|
||||
# Fixture: Codec H264 EAC3 Multisub advertises three E-AC-3 audio streams
|
||||
# (Hindi and Japanese flagged default, English not) and 36 SRT subtitle
|
||||
# streams, so both picks below are genuine changes away from the automatic one.
|
||||
# Pristine state on purpose, for two reasons: the TV regressions in the same
|
||||
# CI group leave "Force TV mode" enabled, and a remembered track selection
|
||||
# from an earlier run would pre-select the very rows this flow picks, making
|
||||
# every assertion below vacuous.
|
||||
# Guards 468d6804: a user pick must retire TrackManager's pending automatic
|
||||
# selection pass, or the server preference can overwrite it up to 30s later.
|
||||
# The codec fixture supplies non-default audio and subtitle choices, and clean
|
||||
# state prevents remembered selections from making the assertions vacuous.
|
||||
- runFlow: ../subflows/onboard_jellyfin.yaml
|
||||
- runFlow:
|
||||
file: ../subflows/open_codec_sample.yaml
|
||||
|
||||
@@ -7,16 +7,9 @@ tags:
|
||||
- settings
|
||||
- i18n
|
||||
---
|
||||
# Guards 7677d159 and 100d7729. AppLocale is switched over exhaustively in
|
||||
# appearance_settings_screen.dart, so a missing arm is a compile error, but a
|
||||
# locale whose JSON never reached the generator ships a picker entry that falls
|
||||
# back to English. Selecting Turkish and reading root-level navigation labels
|
||||
# proves the generated locale is wired end to end.
|
||||
#
|
||||
# This flow mutates a persisted pref, and the app language decides every
|
||||
# selector after the tap, so it starts from a cleared install rather than
|
||||
# ensure_onboarded: a run that dies mid-flow must not leave the next flow
|
||||
# hunting for English strings in a Turkish tree.
|
||||
# Guards 7677d159 and 100d7729: selecting Turkish and reading root navigation
|
||||
# labels proves the generated locale is wired end to end. Start clean because
|
||||
# the language preference persists and affects every later selector.
|
||||
- runFlow: ../subflows/onboard_jellyfin.yaml
|
||||
- runFlow: ../subflows/open_settings.yaml
|
||||
- tapOn: "(?s)^Appearance.*"
|
||||
@@ -54,9 +47,7 @@ tags:
|
||||
- assertVisible: "Keşfet"
|
||||
- assertNotVisible: "(?s)^Libraries.*"
|
||||
- assertNotVisible: "Discover"
|
||||
# Walk back through the Turkish tree and restore English. The pref outlives a
|
||||
# plain launchApp, so leaving the device in Turkish would break every later
|
||||
# flow in the suite.
|
||||
# Restore English before leaving the device; the locale preference outlives launchApp.
|
||||
- repeat:
|
||||
times: 3
|
||||
while:
|
||||
|
||||
@@ -7,21 +7,11 @@ tags:
|
||||
- tv
|
||||
- settings
|
||||
---
|
||||
# Guards ef310459 and the Apple-only gates touched by 6c14049e, and pins TV
|
||||
# settings navigation generally.
|
||||
#
|
||||
# It deliberately does NOT guard the 15b54e2e density change. That commit took
|
||||
# every settings row from ~80dp to ~61dp, but the rows below the fold stay in
|
||||
# the semantics tree either way, so this flow passes identically on both sides
|
||||
# of it — measured, not assumed. A real guard would need a pixel `height`
|
||||
# assertion, and Maestro has no DPR-relative form, so pinning one here would
|
||||
# only hold for the box it was written on. Row geometry belongs to
|
||||
# test/widgets/setting_tile_test.dart.
|
||||
#
|
||||
# Every step uses D-pad keys, never taps. InputModeTracker flips to pointer
|
||||
# mode on the first touch event and the TV number spinner only builds in
|
||||
# keyboard mode, so a single tapOn anywhere above would silently swap the
|
||||
# spinner for a plain text field.
|
||||
# Guards ef310459 and the Apple-only gates touched by 6c14049e.
|
||||
# This flow intentionally does not pin 15b54e2e's row density: semantics stay
|
||||
# stable across that change, and Maestro has no DPR-relative height assertion.
|
||||
# Use D-pad only; a tap switches InputModeTracker to pointer mode and removes
|
||||
# the TV number spinner.
|
||||
- runFlow: ../subflows/onboard_jellyfin_tv_device.yaml
|
||||
- pressKey: "Remote Dpad Left"
|
||||
- extendedWaitUntil:
|
||||
|
||||
@@ -1,20 +1,10 @@
|
||||
appId: com.edde746.plezy
|
||||
---
|
||||
# Reach a signed-in Home without paying for onboarding that already happened.
|
||||
#
|
||||
# `onboard_jellyfin.yaml` clears app state and retypes the server URL and
|
||||
# credentials, which measures ~59s per flow on a Pixel 7 and dominates every
|
||||
# flow that only needs "signed in, on Home". A plain `launchApp` keeps stored
|
||||
# data and cold-starts straight back to Home, which measures ~16s.
|
||||
#
|
||||
# The guard keeps each flow runnable on its own: when no session is stored --
|
||||
# a fresh install, or a run after the logout flow -- "Discover" is absent and
|
||||
# this falls through to the real onboarding. Flows that must prove onboarding
|
||||
# itself, or that need pristine state, keep calling onboard_jellyfin.yaml.
|
||||
# Reach a signed-in Home without repeating onboarding. A plain launch preserves
|
||||
# stored state (~16s versus ~59s for retyping credentials); fall back to full
|
||||
# onboarding when no session exists so each flow remains runnable alone.
|
||||
- launchApp
|
||||
# Settle on a known screen first. Branching straight off `launchApp` races the
|
||||
# splash: "Discover" has not rendered yet, the guard reads it as absent, and
|
||||
# every flow pays for a full re-onboarding it did not need.
|
||||
# Wait for the splash to resolve before deciding whether onboarding is needed.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^(?:Discover|Sign in with Plex|Connect to Jellyfin|Wait).*"
|
||||
timeout: 30000
|
||||
|
||||
@@ -10,10 +10,8 @@ appId: com.edde746.plezy
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^(?:Connect to Jellyfin|Wait).*"
|
||||
timeout: 30000
|
||||
# A miss on `tapOn ... optional: true` still runs Maestro's full element
|
||||
# search before giving up, which measured 3s here and 7.8s for "Sign in"
|
||||
# on every onboarding. These taps normally find nothing, so gate them on
|
||||
# a single visibility check instead.
|
||||
# Optional taps still pay Maestro's full search cost when they miss; guard them
|
||||
# with one visibility check instead.
|
||||
- runFlow:
|
||||
when:
|
||||
visible: "Wait"
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
appId: com.edde746.plezy
|
||||
---
|
||||
# Onboarding for a device that already reports itself as a TV.
|
||||
#
|
||||
# `onboard_jellyfin_tv.yaml` exists for the phone emulator CI runs on: it
|
||||
# onboards through the handheld layout and then walks Settings to flip
|
||||
# "Force TV mode". A real Android TV box takes the TV layout from the first
|
||||
# frame, so that walk has no handheld chrome to tap and the toggle would only
|
||||
# re-assert what PlatformDetector already reports.
|
||||
# Onboard a device that reports itself as a TV; unlike the phone flow, it starts
|
||||
# in TV layout and needs no Force TV mode walk.
|
||||
- retry:
|
||||
maxRetries: 1
|
||||
commands:
|
||||
@@ -32,9 +27,8 @@ appId: com.edde746.plezy
|
||||
- tapOn: "(?s)Server URLs.*"
|
||||
- inputText: ${JELLYFIN_URL}
|
||||
- tapOn: "Find server"
|
||||
# A TV-sized layout offers Quick Connect first because typing on a remote is
|
||||
# slow. The code path needs a second device to approve, so fall back to the
|
||||
# username form the phone flow already uses.
|
||||
# Quick Connect is awkward on a remote and needs another device, so use the
|
||||
# username form as fallback.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^(?:Username|Cancel)$"
|
||||
timeout: 30000
|
||||
|
||||
@@ -17,10 +17,8 @@ appId: com.edde746.plezy
|
||||
platform: Android
|
||||
commands:
|
||||
- hideKeyboard
|
||||
# A card announces its watch state three ways, and the codec samples keep a
|
||||
# resume position on the server once any earlier flow has played them, so the
|
||||
# partial form has to be accepted for this subflow to be re-runnable against a
|
||||
# fixture container that is not thrown away between suites.
|
||||
# Codec cards retain watch state and resume position between flows, so accept
|
||||
# any valid watch-state label to keep this subflow rerunnable.
|
||||
- extendedWaitUntil:
|
||||
visible: "(?s)^${SAMPLE_TITLE}, movie, (?:watched|unwatched|[0-9]+ percent watched)$"
|
||||
timeout: 15000
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
appId: com.edde746.plezy
|
||||
---
|
||||
# Reach Settings from a signed-in Home on a phone layout.
|
||||
#
|
||||
# The profile menu is itself an overlay sheet on the MainScreen host, so a tap
|
||||
# issued while the previous route is still settling opens nothing. The guarded
|
||||
# repeat re-opens the menu instead of failing the flow, matching the pattern
|
||||
# already used by flows/07_profiles_settings.yaml.
|
||||
# Reach phone Settings from signed-in Home. The profile menu is an overlay
|
||||
# sheet; retry while the previous route settles.
|
||||
- extendedWaitUntil:
|
||||
visible: "Discover"
|
||||
timeout: 30000
|
||||
|
||||
+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.12.1"
|
||||
sha256 "7a5e30d125d5a379108bf691ae8ce5e2af0a1acf98ee40897909a9576ebe3ef9"
|
||||
version "2.16.0"
|
||||
sha256 "87568115810fd627babfd05967fbc7d1bf9f40bd38eed319cf7b404b09e47162"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
|
||||
@@ -38,9 +38,9 @@ Package managers:
|
||||
brew tap edde746/plezy https://github.com/edde746/plezy
|
||||
brew install --cask plezy
|
||||
```
|
||||
- [AUR](https://aur.archlinux.org/packages/plezy-bin) (Arch Linux) - Community maintained by [@jianglai](https://github.com/jianglai):
|
||||
- [Pacman](https://archlinux.org/packages/extra/x86_64/plezy/) (Arch Linux) - Official package:
|
||||
```bash
|
||||
yay -S plezy-bin
|
||||
sudo pacman -S plezy
|
||||
```
|
||||
- **WinGet** (Windows):
|
||||
```bash
|
||||
@@ -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
|
||||
|
||||
@@ -15,8 +15,7 @@ linter:
|
||||
prefer_final_in_for_each: true
|
||||
avoid_print: true
|
||||
|
||||
# Do not register DCL as an analyzer plugin: its analyzer 10 integration crashes
|
||||
# on Linux. CI invokes the supported check-unused commands explicitly.
|
||||
# DCL's analyzer 10 plugin crashes on Linux; CI runs check-unused commands directly.
|
||||
dart_code_linter:
|
||||
rules-exclude:
|
||||
- "test/**"
|
||||
@@ -27,7 +26,7 @@ dart_code_linter:
|
||||
- package:dart_code_linter/presets/recommended.yaml
|
||||
|
||||
rules:
|
||||
# --- Flutter rules (on top of recommended) ---
|
||||
# Flutter-specific rules.
|
||||
- avoid-border-all
|
||||
- avoid-shrink-wrap-in-lists
|
||||
- avoid-expanded-as-spacer
|
||||
@@ -37,7 +36,7 @@ dart_code_linter:
|
||||
- prefer-define-hero-tag
|
||||
- use-setstate-synchronously
|
||||
|
||||
# --- Additional useful Dart rules ---
|
||||
# Additional Dart rules.
|
||||
- avoid-cascade-after-if-null
|
||||
- avoid-collection-methods-with-unrelated-types
|
||||
- avoid-unnecessary-type-assertions
|
||||
@@ -48,7 +47,7 @@ dart_code_linter:
|
||||
- prefer-enums-by-name
|
||||
- prefer-commenting-analyzer-ignores
|
||||
|
||||
# --- Disable noisy rules from recommended preset ---
|
||||
# Disabled noisy rules.
|
||||
- no-magic-number: false
|
||||
- avoid-dynamic: false
|
||||
- format-comment: false
|
||||
|
||||
@@ -64,7 +64,7 @@ val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile
|
||||
val mpvAar = "libmpv-release.aar"
|
||||
val mpvUrl = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
|
||||
|
||||
val media3Version = "1.10.1"
|
||||
val media3Version = "1.11.0"
|
||||
val mpvFfmpegVersion = "8.0.1"
|
||||
val mpvFfmpegSourceSha256 = "05ee0b03119b45c0bdb4df654b96802e909e0a752f72e4fe3794f487229e5a41"
|
||||
val mpvFfmpegSourceUrl = "https://ffmpeg.org/releases/ffmpeg-$mpvFfmpegVersion.tar.xz"
|
||||
@@ -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"
|
||||
)
|
||||
@@ -336,8 +338,6 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.edde746.plezy"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
@@ -518,8 +518,10 @@ dependencies {
|
||||
// Android TV Watch Next integration
|
||||
implementation("androidx.tvprovider:tvprovider:1.1.0")
|
||||
|
||||
// Periodic Watch Next background refresh (ShelfRefreshWorker). Same version
|
||||
// background_downloader pins, so the merged classpath stays coherent.
|
||||
// Only used to cancel the legacy periodic shelf refresh job (2.13.0's
|
||||
// removed ShelfRefreshWorker) that WorkManager persisted on updated
|
||||
// devices. Same version background_downloader pins, so the merged
|
||||
// classpath stays coherent.
|
||||
implementation("androidx.work:work-runtime-ktx:2.11.0")
|
||||
|
||||
// Media3 ExoPlayer for Android
|
||||
|
||||
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(context)) {
|
||||
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)
|
||||
|
||||
@@ -9,17 +9,14 @@
|
||||
<!-- Allow minSdk=25 despite libmpv-android declaring minSdk=26 -->
|
||||
<uses-sdk tools:overrideLibrary="dev.jdtech.mpv" />
|
||||
|
||||
<!-- Internet access permissions -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
|
||||
|
||||
|
||||
<!-- PIP and media session foreground service permissions -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
|
||||
<uses-permission android:name="android.permission.REORDER_TASKS"/>
|
||||
|
||||
<!-- Background download notifications and foreground service -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
|
||||
|
||||
@@ -30,15 +27,11 @@
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
|
||||
|
||||
<!-- Android TV support (not required, but allow detection) -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
<!-- Android TV Watch Next integration -->
|
||||
<uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA"/>
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
<!-- Touchscreen not required for TV -->
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
|
||||
<!-- Android Automotive OS support -->
|
||||
<uses-feature android:name="android.hardware.type.automotive" android:required="false" />
|
||||
|
||||
<application
|
||||
@@ -63,10 +56,6 @@
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|navigation|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<!-- Specifies an Android theme to apply to this Activity as soon as
|
||||
the Android process has started. This theme is visible to the user
|
||||
while the Flutter UI initializes. After that, this theme continues
|
||||
to determine the Window background behind the Flutter UI. -->
|
||||
<meta-data
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"
|
||||
@@ -77,7 +66,6 @@
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
<!-- Allow app to appear in Android TV launcher -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER"/>
|
||||
</intent-filter>
|
||||
<!-- Deep link handler for Watch Next items -->
|
||||
@@ -88,7 +76,6 @@
|
||||
<data android:scheme="plezy" android:host="play"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!-- FileProvider for sharing downloaded files with external players -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="com.edde746.plezy.fileprovider"
|
||||
|
||||
@@ -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
@@ -119,7 +119,6 @@ class MainActivity : FlutterActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
// Auto PiP state
|
||||
private var autoPipReady = false
|
||||
private var autoPipWidth: Int = 16
|
||||
private var autoPipHeight: Int = 9
|
||||
@@ -883,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" -> {
|
||||
|
||||
@@ -202,14 +202,31 @@ class CarRestrictionsMonitor(
|
||||
Log.w(TAG, "Car service is ready but has no UX restrictions manager")
|
||||
return
|
||||
}
|
||||
manager = uxManager
|
||||
// Register before reading, per the platform's own guidance: registration subscribes to future
|
||||
// changes only, it does not replay the current one. Reading first would drop a transition that
|
||||
// lands between the two binder calls, and publishing the stale "parked" afterwards would then
|
||||
// override lifecycle gating and permit audio for the whole drive.
|
||||
uxManager.registerListener { restrictions: CarUxRestrictions -> publish(restrictions.isRequiresDistractionOptimization) }
|
||||
supported = true
|
||||
publish(uxManager.currentCarUxRestrictions?.isRequiresDistractionOptimization ?: true)
|
||||
//
|
||||
// Identity-guarded because a retry re-enters bind() with the same manager instance (Car caches
|
||||
// managers until the service dies): a second registration is at best redundant and at worst a
|
||||
// platform refusal. `manager` is assigned after the listener sticks, so it only ever names a
|
||||
// manager that is actually observing the vehicle.
|
||||
if (manager !== uxManager) {
|
||||
uxManager.registerListener { restrictions: CarUxRestrictions -> adoptVerdict(restrictions.isRequiresDistractionOptimization) }
|
||||
manager = uxManager
|
||||
}
|
||||
val current = uxManager.currentCarUxRestrictions
|
||||
if (current == null) {
|
||||
// The service holds no restrictions for this display (yet). Claiming a verdict here would
|
||||
// publish the restricted default with `supported = true`, and on a car that then stays
|
||||
// parked no transition ever arrives to correct it — playback would refuse to start for the
|
||||
// whole session. Stay pending instead: Dart keeps lifecycle gating (parked, foregrounded
|
||||
// video plays; while driving the platform blocks the activity), the listener above adopts
|
||||
// the first real verdict, and every later getState retries this read.
|
||||
Log.w(TAG, "Car service has no UX restrictions for this display; keeping lifecycle gating until it answers")
|
||||
return
|
||||
}
|
||||
adoptVerdict(current.isRequiresDistractionOptimization)
|
||||
} catch (error: Throwable) {
|
||||
// Registration is the failure the caller's retry is meant to survive, so keep the connection
|
||||
// owned (it is in `car`) and report nothing rather than half-observing the vehicle.
|
||||
@@ -219,6 +236,12 @@ class CarRestrictionsMonitor(
|
||||
}
|
||||
}
|
||||
|
||||
/** A real verdict from the vehicle: only now may callers trust [requiresDistractionOptimization]. */
|
||||
private fun adoptVerdict(restricted: Boolean) {
|
||||
supported = true
|
||||
publish(restricted)
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops a dead car service. The [Car] itself is kept: its `BIND_AUTO_CREATE` binding is what
|
||||
* reconnects, and disconnecting would end that for good.
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
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
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MimeTypes
|
||||
@@ -29,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.
|
||||
@@ -45,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
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -60,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)
|
||||
@@ -90,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
|
||||
@@ -99,41 +171,115 @@ 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, where the API exists,
|
||||
* `getDirectPlaybackSupport` proves the route will actually bitstream it rather than silently
|
||||
* decode or wedge.
|
||||
* 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.
|
||||
*
|
||||
* The oracle is tiered by what the platform offers:
|
||||
* - API 33+: `getDirectPlaybackSupport`, whose bitstream flag also rules out offload-only answers.
|
||||
* - API 29–32: `AudioTrack.isDirectPlaybackSupported` for the same tuple. Coarser — it cannot tell
|
||||
* bitstream from offload — but an IEC 61937 track is PCM-shaped by definition, so direct support
|
||||
* 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.
|
||||
* - 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(context: Context): Boolean {
|
||||
// getMinBufferSize alone is not sufficient. On a Shield it answers yes for the 192kHz/7.1 IEC
|
||||
// tuple and the AudioTrack then fails to initialise; it reports that a buffer can be sized, not
|
||||
// that the route will carry the format. Without getDirectPlaybackSupport there is no way to tell
|
||||
// the two apart, so below API 33 the carrier is not offered and TrueHD decodes as before.
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return false
|
||||
internal fun supportsIecCarrier(context: Context): Boolean = iecRouteSupported(
|
||||
sdkInt = Build.VERSION.SDK_INT,
|
||||
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 &&
|
||||
iecBitstreamSupported(iecProbeFormat(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND))
|
||||
},
|
||||
directPlaybackSupported = {
|
||||
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) }
|
||||
)
|
||||
|
||||
val rate = TrueHdMatPacker.CARRIER_SAMPLE_RATE
|
||||
val mask = AudioFormat.CHANNEL_OUT_7POINT1_SURROUND
|
||||
val sizedOk = try {
|
||||
AudioTrack.getMinBufferSize(rate, mask, AudioFormat.ENCODING_IEC61937) > 0
|
||||
} catch (error: Exception) {
|
||||
false
|
||||
}
|
||||
if (!sizedOk) return false
|
||||
|
||||
return try {
|
||||
val audioAttributes = AudioAttributes.Builder()
|
||||
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
|
||||
.setUsage(C.USAGE_MEDIA)
|
||||
.build()
|
||||
.getPlatformAudioAttributes()
|
||||
val probe = AudioFormat.Builder()
|
||||
.setEncoding(AudioFormat.ENCODING_IEC61937)
|
||||
.setChannelMask(mask)
|
||||
.setSampleRate(rate)
|
||||
.build()
|
||||
val support = AudioManager.getDirectPlaybackSupport(probe, audioAttributes)
|
||||
(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)
|
||||
false
|
||||
}
|
||||
/**
|
||||
* [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 iecRouteSupported(
|
||||
sdkInt: Int,
|
||||
canSizeBuffer: () -> Boolean,
|
||||
bitstreamSupported: () -> Boolean,
|
||||
directPlaybackSupported: () -> Boolean,
|
||||
hdmiRouteAdvertised: () -> Boolean
|
||||
): Boolean = when {
|
||||
// ENCODING_IEC61937 itself only exists from API 24.
|
||||
sdkInt < Build.VERSION_CODES.N -> false
|
||||
!canSizeBuffer() -> false
|
||||
sdkInt >= Build.VERSION_CODES.TIRAMISU -> bitstreamSupported()
|
||||
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 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 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 iecDirectPlaybackSupported(format: AudioFormat): Boolean = try {
|
||||
AudioTrack.isDirectPlaybackSupported(format, movieAudioAttributes())
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "IEC 61937 route probe failed; not offering bitstream output", error)
|
||||
false
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(channelMask)
|
||||
.setSampleRate(sampleRate)
|
||||
.build()
|
||||
|
||||
private fun movieAudioAttributes(): android.media.AudioAttributes = AudioAttributes.Builder()
|
||||
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
|
||||
.setUsage(C.USAGE_MEDIA)
|
||||
.build()
|
||||
.getPlatformAudioAttributes()
|
||||
|
||||
-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
|
||||
@@ -218,6 +220,9 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
private var subtitleAnchorToScreen: Boolean = false
|
||||
private var lastSubtitleCues: List<Cue> = emptyList()
|
||||
|
||||
// Retain the inferred composition-plane aspect across empty cue groups.
|
||||
private var bitmapSubtitlePlaneAspect: Float? = null
|
||||
|
||||
// Tracks whether a text track was selected on the previous onTracksChanged so we
|
||||
// can detect the transition to "no subtitle" and clear the painted overlays (#1387).
|
||||
private var hadSelectedTextTrack: Boolean = false
|
||||
@@ -226,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
|
||||
@@ -311,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
|
||||
@@ -551,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
|
||||
@@ -568,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")
|
||||
@@ -577,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(
|
||||
@@ -722,50 +750,79 @@ 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()
|
||||
assHandler = handler
|
||||
|
||||
val assParserFactory = AssSubtitleParserFactory(handler)
|
||||
// PGS goes through PgsCompositionParser; media3's parser drops all but one
|
||||
// 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(assParserFactory, 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)
|
||||
.setSubtitleParserFactory(assParserFactory)
|
||||
.setSubtitleParserFactory(subtitleParserFactory)
|
||||
playbackMediaSourceFactory = mediaSourceFactory
|
||||
|
||||
// Wrap text renderers with subtitle delay support
|
||||
@@ -1110,11 +1167,31 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
private fun renderSubtitleCues(cues: List<Cue>) {
|
||||
val textCues = cues.filter { it.bitmap == null }
|
||||
val bitmapCues = cues.filter { it.bitmap != null }
|
||||
updateBitmapSubtitlePlaneAspect(bitmapCues)
|
||||
val outgoing = SubtitleCueLayout.layout(textCues, subtitlePositionPercent, subtitleFontSize)
|
||||
subtitleView?.setCues(outgoing)
|
||||
bitmapSubtitleView?.setCues(bitmapCues)
|
||||
}
|
||||
|
||||
private fun updateBitmapSubtitlePlaneAspect(bitmapCues: List<Cue>) {
|
||||
val inferredAspect = bitmapCues.firstNotNullOfOrNull { cue ->
|
||||
val bitmap = cue.bitmap ?: return@firstNotNullOfOrNull null
|
||||
SubtitleViewLayout.bitmapPlaneAspect(
|
||||
bitmap.width,
|
||||
bitmap.height,
|
||||
cue.size,
|
||||
cue.bitmapHeight
|
||||
)
|
||||
} ?: return
|
||||
val previousAspect = bitmapSubtitlePlaneAspect
|
||||
if (previousAspect != null && kotlin.math.abs(inferredAspect / previousAspect - 1f) <= 0.001f) return
|
||||
|
||||
bitmapSubtitlePlaneAspect = inferredAspect
|
||||
lastVideoSize?.let {
|
||||
updateSubtitleViewSize(it.width, it.height, it.pixelWidthHeightRatio)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleIsPlayingChanged(isPlaying: Boolean) {
|
||||
Log.d(TAG, "onIsPlayingChanged: $isPlaying")
|
||||
// A pause/resume can occur entirely between watchdog polls while the
|
||||
@@ -1230,12 +1307,13 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
}
|
||||
}
|
||||
|
||||
// Disabling the text track produces no trailing empty CueGroup, and no new
|
||||
// video frame re-renders the libass overlay while paused, so the last SRT/VTT
|
||||
// cue stays painted on the SubtitleViews and the last ASS frame stays on the
|
||||
// overlay. AssHandler (registered before this listener) has already nulled the
|
||||
// libass track by now, so re-rendering the last position clears it. Gate on the
|
||||
// transition to avoid redundant clears on every track change. (#1387)
|
||||
// Disabling the text track produces no trailing empty CueGroup, so the last
|
||||
// SRT/VTT cue stays painted on the SubtitleViews. AssHandler (registered
|
||||
// before this listener) has already nulled the libass track by now, so the
|
||||
// invalidate pushes one request through the atlas pipeline, which swaps an
|
||||
// explicit blank frame for a trackless render — required while paused, where
|
||||
// no video frame triggers one. Gate on the transition to avoid redundant
|
||||
// clears on every track change. (#1387, #1884)
|
||||
val hasSelectedText = hasSelectedTextTrack(tracks)
|
||||
if (!hasSelectedText && hadSelectedTextTrack) {
|
||||
lastSubtitleCues = emptyList()
|
||||
@@ -1767,8 +1845,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
videoWidth,
|
||||
videoHeight,
|
||||
pixelRatio,
|
||||
resizeMode,
|
||||
videoZoomScale
|
||||
bitmapSubtitlePlaneAspect
|
||||
)
|
||||
|
||||
activity.runOnUiThread {
|
||||
@@ -2293,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 {
|
||||
@@ -2402,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(
|
||||
@@ -2633,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
|
||||
@@ -2660,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"}")
|
||||
@@ -3381,6 +3511,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
externalSubtitleUris.clear()
|
||||
externalSubtitleContainerUris.clear()
|
||||
lastSubtitleCues = emptyList()
|
||||
bitmapSubtitlePlaneAspect = null
|
||||
hadSelectedTextTrack = false
|
||||
audioTrackGroupMap.clear()
|
||||
subtitleTrackGroupMap.clear()
|
||||
@@ -3645,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()
|
||||
@@ -3681,6 +3813,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
lastDvPlaybackInfo = null
|
||||
activeDoviMkvWrapper = null
|
||||
activeDoviMp4Wrapper = null
|
||||
activeFfmpegExtractor = null
|
||||
stopFrameWatchdog()
|
||||
cancelDecoderHangCheck()
|
||||
cancelResumeStallWatchdog()
|
||||
@@ -4044,6 +4177,7 @@ class ExoPlayerCore(private val activity: Activity) :
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
matchResolution: Boolean,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
val mgr = frameRateManager
|
||||
@@ -4051,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() {
|
||||
@@ -4146,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()
|
||||
}
|
||||
+114
-71
@@ -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
|
||||
@@ -106,8 +109,6 @@ internal class TrueHdCarrierSink(
|
||||
@Volatile
|
||||
private var mismatchGeneration = -1
|
||||
|
||||
// --- Selection ---
|
||||
|
||||
/**
|
||||
* True when this format should ride the carrier.
|
||||
*
|
||||
@@ -116,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
|
||||
@@ -138,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
|
||||
@@ -155,45 +156,68 @@ 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)
|
||||
}
|
||||
|
||||
override fun configure(inputFormat: Format, specifiedBufferSize: Int, outputChannels: IntArray?) {
|
||||
override fun configure(audioSinkConfig: AudioSink.AudioSinkConfig) {
|
||||
val inputFormat = audioSinkConfig.format
|
||||
val useCarrier = shouldUseCarrier(inputFormat)
|
||||
if (useCarrier != carrierActive) {
|
||||
log?.invoke(
|
||||
"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) {
|
||||
carrierSink.configure(carrierFormat(), specifiedBufferSize, null)
|
||||
val carrierConfig = AudioSink.AudioSinkConfig.Builder(carrierFormat())
|
||||
.setPreferredBufferSizeOverride(audioSinkConfig.preferredBufferSizeOverride)
|
||||
.setTimeline(audioSinkConfig.timeline)
|
||||
.setMediaPeriodId(audioSinkConfig.mediaPeriodId)
|
||||
.build()
|
||||
carrierSink.configure(carrierConfig)
|
||||
} else {
|
||||
defaultSink.configure(inputFormat, specifiedBufferSize, outputChannels)
|
||||
defaultSink.configure(audioSinkConfig)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Stream path: active delegate only ---
|
||||
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)
|
||||
@@ -215,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
|
||||
@@ -255,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()
|
||||
}
|
||||
|
||||
@@ -283,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 ---
|
||||
@@ -319,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
|
||||
|
||||
@@ -343,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()
|
||||
@@ -405,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
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.text.Cue
|
||||
import androidx.media3.common.util.Consumer
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.common.util.Util
|
||||
import androidx.media3.extractor.text.CuesWithTiming
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import java.util.zip.Inflater
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Delegates to [delegate] for every subtitle format except PGS, which is handled by
|
||||
* [PgsCompositionParser] because media3's PgsParser drops all but one composition object (#1953).
|
||||
*/
|
||||
@UnstableApi
|
||||
class PgsSubtitleParserFactory(private val delegate: SubtitleParser.Factory) : SubtitleParser.Factory {
|
||||
override fun supportsFormat(format: Format): Boolean = delegate.supportsFormat(format)
|
||||
|
||||
override fun getCueReplacementBehavior(format: Format): Int = delegate.getCueReplacementBehavior(format)
|
||||
|
||||
override fun create(format: Format): SubtitleParser = if (format.sampleMimeType == MimeTypes.APPLICATION_PGS) PgsCompositionParser() else delegate.create(format)
|
||||
}
|
||||
|
||||
/**
|
||||
* PGS subtitle parser that renders every composition object in a display set.
|
||||
*
|
||||
* media3's PgsParser keeps one bitmap buffer and only the first composition object's
|
||||
* coordinates, so a display set with two simultaneous images (dialogue plus a sign or
|
||||
* song caption) draws the last object at the first object's position and loses the rest.
|
||||
* It is also stateless across display sets, so Normal-state sets that only update the
|
||||
* palette (fades) or reuse cached objects blank the screen.
|
||||
*
|
||||
* This parser follows FFmpeg's pgssubdec model, which Kodi/mpv/VLC share: objects and
|
||||
* palettes are cached per epoch keyed by id, any non-Normal composition state releases
|
||||
* the caches, palette sections update entries in place, and the display-end section
|
||||
* composes one cue per object reference in the presentation. Colors use limited-range
|
||||
* BT.709 for HD planes and BT.601 otherwise, matching FFmpeg output.
|
||||
*/
|
||||
@UnstableApi
|
||||
class PgsCompositionParser : SubtitleParser {
|
||||
|
||||
companion object {
|
||||
private const val SECTION_TYPE_PALETTE = 0x14
|
||||
private const val SECTION_TYPE_OBJECT = 0x15
|
||||
private const val SECTION_TYPE_PRESENTATION = 0x16
|
||||
private const val SECTION_TYPE_END = 0x80
|
||||
|
||||
// Blu-ray spec limits, as enforced by FFmpeg's pgssubdec.
|
||||
private const val MAX_OBJECT_REFS = 2
|
||||
private const val MAX_EPOCH_OBJECTS = 64
|
||||
private const val MAX_EPOCH_PALETTES = 8
|
||||
|
||||
// Bounds object dimensions when a damaged stream declares them before any
|
||||
// presentation section has established the composition plane.
|
||||
private const val MAX_PLANE_DIMENSION = 4096
|
||||
}
|
||||
|
||||
private class PgsObject {
|
||||
var width = 0
|
||||
var height = 0
|
||||
var rle = ByteArray(0)
|
||||
var received = 0
|
||||
|
||||
val complete: Boolean
|
||||
get() = rle.isNotEmpty() && received == rle.size
|
||||
}
|
||||
|
||||
private class ObjectRef(val objectId: Int, val x: Int, val y: Int)
|
||||
|
||||
private val buffer = ParsableByteArray()
|
||||
private val inflatedBuffer = ParsableByteArray()
|
||||
private var inflater: Inflater? = null
|
||||
|
||||
// Epoch state: objects and palettes persist across display sets until a
|
||||
// non-Normal composition state starts a new epoch or [reset] follows a seek.
|
||||
private val objects = HashMap<Int, PgsObject>()
|
||||
private val palettes = HashMap<Int, IntArray>()
|
||||
|
||||
// Latest presentation composition.
|
||||
private var planeWidth = 0
|
||||
private var planeHeight = 0
|
||||
private var paletteId = 0
|
||||
private var objectRefs = emptyList<ObjectRef>()
|
||||
|
||||
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
|
||||
|
||||
override fun reset() {
|
||||
objects.clear()
|
||||
palettes.clear()
|
||||
objectRefs = emptyList()
|
||||
planeWidth = 0
|
||||
planeHeight = 0
|
||||
paletteId = 0
|
||||
}
|
||||
|
||||
override fun parse(
|
||||
data: ByteArray,
|
||||
offset: Int,
|
||||
length: Int,
|
||||
outputOptions: SubtitleParser.OutputOptions,
|
||||
output: Consumer<CuesWithTiming>
|
||||
) {
|
||||
buffer.reset(data, offset + length)
|
||||
buffer.setPosition(offset)
|
||||
val inflater = this.inflater ?: Inflater().also { this.inflater = it }
|
||||
if (Util.maybeInflate(buffer, inflatedBuffer, inflater)) {
|
||||
buffer.reset(inflatedBuffer.data, inflatedBuffer.limit())
|
||||
}
|
||||
val cues = ArrayList<Cue>()
|
||||
while (buffer.bytesLeft() >= 3) {
|
||||
readNextSection(cues)
|
||||
}
|
||||
output.accept(
|
||||
CuesWithTiming(
|
||||
cues,
|
||||
C.TIME_UNSET, // startTimeUs
|
||||
C.TIME_UNSET // durationUs
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun readNextSection(cues: MutableList<Cue>) {
|
||||
val sectionType = buffer.readUnsignedByte()
|
||||
val sectionLength = buffer.readUnsignedShort()
|
||||
val nextSectionPosition = buffer.position + sectionLength
|
||||
if (nextSectionPosition > buffer.limit()) {
|
||||
buffer.setPosition(buffer.limit())
|
||||
return
|
||||
}
|
||||
when (sectionType) {
|
||||
SECTION_TYPE_PALETTE -> parsePalette(sectionLength)
|
||||
SECTION_TYPE_OBJECT -> parseObject(sectionLength)
|
||||
SECTION_TYPE_PRESENTATION -> parsePresentation(sectionLength)
|
||||
SECTION_TYPE_END -> composeCues(cues)
|
||||
// Window sections (0x17) carry no information the composition needs.
|
||||
}
|
||||
buffer.setPosition(nextSectionPosition)
|
||||
}
|
||||
|
||||
private fun parsePresentation(sectionLength: Int) {
|
||||
if (sectionLength < 11) return
|
||||
planeWidth = buffer.readUnsignedShort()
|
||||
planeHeight = buffer.readUnsignedShort()
|
||||
buffer.skipBytes(3) // Frame rate (1), composition number (2).
|
||||
val compositionState = buffer.readUnsignedByte()
|
||||
if (compositionState and 0xC0 != 0) {
|
||||
// Epoch start/acquisition point display sets carry complete data; previous
|
||||
// epoch objects and palettes are released.
|
||||
objects.clear()
|
||||
palettes.clear()
|
||||
}
|
||||
buffer.skipBytes(1) // Palette update flag.
|
||||
paletteId = buffer.readUnsignedByte()
|
||||
val objectCount = buffer.readUnsignedByte()
|
||||
var remaining = sectionLength - 11
|
||||
val refs = ArrayList<ObjectRef>(min(objectCount, MAX_OBJECT_REFS))
|
||||
for (i in 0 until min(objectCount, MAX_OBJECT_REFS)) {
|
||||
if (remaining < 8) break
|
||||
val objectId = buffer.readUnsignedShort()
|
||||
buffer.skipBytes(1) // Window id.
|
||||
val flags = buffer.readUnsignedByte()
|
||||
val x = buffer.readUnsignedShort()
|
||||
val y = buffer.readUnsignedShort()
|
||||
remaining -= 8
|
||||
if (flags and 0x80 != 0) {
|
||||
// Cropped object: skip the crop rectangle. Like FFmpeg, the crop itself
|
||||
// is not applied, but the following reference must parse correctly.
|
||||
if (remaining < 8) break
|
||||
buffer.skipBytes(8)
|
||||
remaining -= 8
|
||||
}
|
||||
refs.add(ObjectRef(objectId, x, y))
|
||||
}
|
||||
objectRefs = refs
|
||||
}
|
||||
|
||||
private fun parsePalette(sectionLength: Int) {
|
||||
if (sectionLength % 5 != 2) return
|
||||
val id = buffer.readUnsignedByte()
|
||||
buffer.skipBytes(1) // Palette version.
|
||||
if (palettes.size >= MAX_EPOCH_PALETTES && id !in palettes) return
|
||||
// Entries update in place: fade ramps resend only the entries that changed.
|
||||
val palette = palettes.getOrPut(id) { IntArray(256) }
|
||||
val bt709 = planeHeight <= 0 || planeHeight > 576
|
||||
repeat(sectionLength / 5) {
|
||||
val index = buffer.readUnsignedByte()
|
||||
val y = buffer.readUnsignedByte()
|
||||
val cr = buffer.readUnsignedByte()
|
||||
val cb = buffer.readUnsignedByte()
|
||||
val alpha = buffer.readUnsignedByte()
|
||||
palette[index] = argbColor(y, cb, cr, alpha, bt709)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseObject(sectionLength: Int) {
|
||||
if (sectionLength < 4) return
|
||||
val id = buffer.readUnsignedShort()
|
||||
if (objects.size >= MAX_EPOCH_OBJECTS && id !in objects) return
|
||||
buffer.skipBytes(1) // Object version.
|
||||
val isFirstFragment = buffer.readUnsignedByte() and 0x80 != 0
|
||||
var remaining = sectionLength - 4
|
||||
val obj = objects.getOrPut(id) { PgsObject() }
|
||||
if (isFirstFragment) {
|
||||
if (remaining < 7) return
|
||||
val rleLength = buffer.readUnsignedInt24() - 4 // Length includes the width/height fields.
|
||||
val width = buffer.readUnsignedShort()
|
||||
val height = buffer.readUnsignedShort()
|
||||
remaining -= 7
|
||||
val maxWidth = if (planeWidth > 0) planeWidth else MAX_PLANE_DIMENSION
|
||||
val maxHeight = if (planeHeight > 0) planeHeight else MAX_PLANE_DIMENSION
|
||||
if (rleLength <= 0 || width !in 1..maxWidth || height !in 1..maxHeight) {
|
||||
obj.rle = ByteArray(0)
|
||||
obj.received = 0
|
||||
return
|
||||
}
|
||||
obj.width = width
|
||||
obj.height = height
|
||||
obj.rle = ByteArray(rleLength)
|
||||
obj.received = 0
|
||||
}
|
||||
val bytesToRead = min(remaining, obj.rle.size - obj.received)
|
||||
if (bytesToRead > 0) {
|
||||
buffer.readBytes(obj.rle, obj.received, bytesToRead)
|
||||
obj.received += bytesToRead
|
||||
}
|
||||
}
|
||||
|
||||
private fun composeCues(cues: MutableList<Cue>) {
|
||||
if (planeWidth <= 0 || planeHeight <= 0) return
|
||||
val palette = palettes[paletteId] ?: return
|
||||
for (ref in objectRefs) {
|
||||
// Skip references to missing or incomplete objects (damaged stream, or a
|
||||
// post-seek Normal set whose epoch data was never observed).
|
||||
val obj = objects[ref.objectId] ?: continue
|
||||
if (!obj.complete) continue
|
||||
cues.add(
|
||||
Cue.Builder()
|
||||
.setBitmap(decodeBitmap(obj, palette))
|
||||
.setPosition(ref.x.toFloat() / planeWidth)
|
||||
.setPositionAnchor(Cue.ANCHOR_TYPE_START)
|
||||
.setLine(ref.y.toFloat() / planeHeight, Cue.LINE_TYPE_FRACTION)
|
||||
.setLineAnchor(Cue.ANCHOR_TYPE_START)
|
||||
.setSize(obj.width.toFloat() / planeWidth)
|
||||
.setBitmapHeight(obj.height.toFloat() / planeHeight)
|
||||
.build()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeBitmap(obj: PgsObject, palette: IntArray): Bitmap {
|
||||
val pixels = IntArray(obj.width * obj.height)
|
||||
val rle = obj.rle
|
||||
var input = 0
|
||||
var output = 0
|
||||
while (input < rle.size && output < pixels.size) {
|
||||
val first = rle[input++].toInt() and 0xFF
|
||||
if (first != 0) {
|
||||
pixels[output++] = palette[first]
|
||||
continue
|
||||
}
|
||||
if (input >= rle.size) break
|
||||
val flags = rle[input++].toInt() and 0xFF
|
||||
if (flags == 0) continue // End-of-line marker.
|
||||
var run = flags and 0x3F
|
||||
if (flags and 0x40 != 0) {
|
||||
if (input >= rle.size) break
|
||||
run = run shl 8 or (rle[input++].toInt() and 0xFF)
|
||||
}
|
||||
val color = if (flags and 0x80 != 0) {
|
||||
if (input >= rle.size) break
|
||||
palette[rle[input++].toInt() and 0xFF]
|
||||
} else {
|
||||
palette[0]
|
||||
}
|
||||
val end = min(output + run, pixels.size)
|
||||
pixels.fill(color, output, end)
|
||||
output = end
|
||||
}
|
||||
return Bitmap.createBitmap(pixels, obj.width, obj.height, Bitmap.Config.ARGB_8888)
|
||||
}
|
||||
|
||||
private fun argbColor(y: Int, cb: Int, cr: Int, alpha: Int, bt709: Boolean): Int {
|
||||
val yc = (y - 16) * (255f / 219f)
|
||||
val cbc = (cb - 128) * (255f / 224f)
|
||||
val crc = (cr - 128) * (255f / 224f)
|
||||
val r: Float
|
||||
val g: Float
|
||||
val b: Float
|
||||
if (bt709) {
|
||||
r = yc + 1.5747f * crc
|
||||
g = yc - 0.1873f * cbc - 0.4682f * crc
|
||||
b = yc + 1.8556f * cbc
|
||||
} else {
|
||||
r = yc + 1.402f * crc
|
||||
g = yc - 0.34414f * cbc - 0.71414f * crc
|
||||
b = yc + 1.772f * cbc
|
||||
}
|
||||
return (alpha shl 24) or
|
||||
(r.roundToInt().coerceIn(0, 255) shl 16) or
|
||||
(g.roundToInt().coerceIn(0, 255) shl 8) or
|
||||
b.roundToInt().coerceIn(0, 255)
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
@@ -166,16 +166,15 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
enableFloatOutput: Boolean,
|
||||
enableAudioOutputPlaybackParams: Boolean
|
||||
): AudioSink {
|
||||
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
|
||||
|
||||
// Media3 1.11's replacement is fixed at 500ms; preserve the dynamic 500–1000ms PCM policy.
|
||||
@Suppress("DEPRECATION")
|
||||
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
|
||||
.setMinPcmBufferDurationUs(500_000)
|
||||
.setMaxPcmBufferDurationUs(1_000_000)
|
||||
.setPcmBufferMultiplicationFactor(4)
|
||||
// media3 defaults passthrough to 250ms, which the AC3 factor doubles to 500ms — 40000
|
||||
// bytes at 640 kbps. Some HDMI routes reject a buffer that short outright and the only
|
||||
// retry media3 1.10.1 has is to keep halving it (#1790). Ask for a second up front;
|
||||
// upstream adopted the same 1s floor as its last-resort retry in #3207.
|
||||
// Media3 defaults passthrough to 250ms, which the AC3 factor doubles to 500ms. Some
|
||||
// HDMI routes reject a buffer that short (#1790). Ask for a second up front; Media3 1.11
|
||||
// now uses the same one-second floor for its last-resort retry (#3207).
|
||||
.setPassthroughBufferDurationUs(500_000)
|
||||
.build()
|
||||
|
||||
@@ -205,17 +204,17 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
|
||||
audioDiagnosticsLogger
|
||||
)
|
||||
|
||||
return TrueHdCarrierSink(
|
||||
return IecCarrierSink(
|
||||
defaultSink = processedSink,
|
||||
carrierSink = buildCarrierSink(context, bufferSizeProvider),
|
||||
carrierRouteAvailable = { supportsTrueHdMatCarrier(context) },
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -42,16 +42,35 @@ internal object SubtitleViewLayout {
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
pixelRatio: Float,
|
||||
resizeMode: Int,
|
||||
zoomScale: Float
|
||||
planeAspect: Float?
|
||||
): SubtitleViewDimensions? {
|
||||
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
|
||||
if (containerWidth <= 0 || containerHeight <= 0) return null
|
||||
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
|
||||
val visibleVideoBounds = fit(containerWidth, containerHeight, videoAspect)
|
||||
val layoutAspect = planeAspect?.takeIf { it.isFinite() && it > 0f }
|
||||
?: return visibleVideoBounds
|
||||
|
||||
// PGS/VOB cues are authored in video coordinates, but users expect them to
|
||||
// remain readable and fully visible when the video is cropped or zoomed.
|
||||
// Fit to the visible container instead of following the cropped video rect.
|
||||
return fit(containerWidth, containerHeight, videoAspect)
|
||||
// Media3 expresses bitmap cue positions and dimensions relative to the
|
||||
// subtitle composition plane, which can differ from a cropped video's
|
||||
// dimensions. Fit that plane inside the visible video bounds so cues keep
|
||||
// their authored geometry without entering the letterbox bars.
|
||||
return fit(visibleVideoBounds.width, visibleVideoBounds.height, layoutAspect)
|
||||
}
|
||||
|
||||
fun bitmapPlaneAspect(
|
||||
bitmapWidth: Int,
|
||||
bitmapHeight: Int,
|
||||
cueWidthFraction: Float,
|
||||
cueHeightFraction: Float
|
||||
): Float? {
|
||||
if (bitmapWidth <= 0 || bitmapHeight <= 0) return null
|
||||
if (!cueWidthFraction.isFinite() || cueWidthFraction <= 0f) return null
|
||||
if (!cueHeightFraction.isFinite() || cueHeightFraction <= 0f) return null
|
||||
|
||||
// cueWidth = bitmapWidth / planeWidth and cueHeight = bitmapHeight / planeHeight.
|
||||
val aspect = bitmapWidth.toDouble() * cueHeightFraction.toDouble() /
|
||||
(bitmapHeight.toDouble() * cueWidthFraction.toDouble())
|
||||
return aspect.toFloat().takeIf { it.isFinite() && it > 0f }
|
||||
}
|
||||
|
||||
private fun videoAspect(videoWidth: Int, videoHeight: Int, pixelRatio: Float): Float? {
|
||||
|
||||
@@ -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
|
||||
@@ -96,7 +124,6 @@ class MpvPlayerCore private constructor(
|
||||
// output (#1482).
|
||||
private val mpvWriteDispatcher = Dispatchers.IO.limitedParallelism(1)
|
||||
|
||||
// Frame rate matching
|
||||
private var frameRateManager: FrameRateManager? = null
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
@@ -110,7 +137,6 @@ class MpvPlayerCore private constructor(
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post(block)
|
||||
}
|
||||
|
||||
// Audio focus
|
||||
private var audioFocusManager: AudioFocusManager? = null
|
||||
|
||||
@Volatile private var cachedPaused: Boolean = true
|
||||
@@ -275,7 +301,6 @@ class MpvPlayerCore private constructor(
|
||||
Log.d(TAG, "SurfaceView added to content view")
|
||||
}
|
||||
|
||||
// Create MpvPlayer on background thread via coroutine
|
||||
scope.launch {
|
||||
try {
|
||||
if (disposing) {
|
||||
@@ -296,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)
|
||||
}
|
||||
@@ -1041,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"),
|
||||
@@ -1174,6 +1205,7 @@ class MpvPlayerCore private constructor(
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
matchResolution: Boolean,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
val mgr = frameRateManager
|
||||
@@ -1181,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
|
||||
@@ -74,8 +75,6 @@ open class MpvPlayerPlugin(
|
||||
private var initAttemptCounter = 0
|
||||
private var activeInitAttempt: Int? = null
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
applicationContext = binding.applicationContext
|
||||
channels.attach(binding)
|
||||
@@ -104,8 +103,6 @@ open class MpvPlayerPlugin(
|
||||
takeCoreForTeardown()?.dispose()
|
||||
}
|
||||
|
||||
// ActivityAware
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
@@ -141,8 +138,6 @@ open class MpvPlayerPlugin(
|
||||
Log.d(tag, "Detached from activity for config changes")
|
||||
}
|
||||
|
||||
// EventChannel.StreamHandler
|
||||
|
||||
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
|
||||
channels.listen(events)
|
||||
}
|
||||
@@ -151,11 +146,9 @@ open class MpvPlayerPlugin(
|
||||
channels.cancel()
|
||||
}
|
||||
|
||||
// MethodChannel.MethodCallHandler
|
||||
|
||||
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)
|
||||
@@ -167,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)
|
||||
@@ -176,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
|
||||
@@ -235,7 +243,7 @@ open class MpvPlayerPlugin(
|
||||
}
|
||||
|
||||
gen = ++sessionGeneration
|
||||
core = MpvPlayerCore(coreContext, audioOnly).apply {
|
||||
core = MpvPlayerCore(coreContext, audioOnly, hardwareDecoding).apply {
|
||||
delegate = this@MpvPlayerPlugin
|
||||
}
|
||||
playerCore = core
|
||||
@@ -456,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
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
package com.edde746.plezy.watchnext
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.PeriodicWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import io.flutter.FlutterInjector
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.embedding.engine.dart.DartExecutor
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* Owns the WorkManager registration for the periodic launcher-shelf refresh.
|
||||
*
|
||||
* Registration is best-effort by design: it runs inside the plugin's sync/clear
|
||||
* result path, and a WorkManager failure must not turn a committed shelf write
|
||||
* into a channel error.
|
||||
*/
|
||||
internal object ShelfRefreshScheduler {
|
||||
private const val TAG = "ShelfRefreshScheduler"
|
||||
internal const val WORK_NAME = "plezy_shelf_refresh"
|
||||
private const val REFRESH_INTERVAL_HOURS = 6L
|
||||
|
||||
fun schedule(context: Context) {
|
||||
try {
|
||||
val request = PeriodicWorkRequestBuilder<ShelfRefreshWorker>(REFRESH_INTERVAL_HOURS, TimeUnit.HOURS)
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.build()
|
||||
WorkManager.getInstance(context.applicationContext)
|
||||
.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, request)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to schedule shelf refresh work", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel(context: Context) {
|
||||
try {
|
||||
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(WORK_NAME)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to cancel shelf refresh work", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes the Android TV Watch Next row while the app is not running.
|
||||
*
|
||||
* Boots a headless [FlutterEngine], runs the Dart `systemShelfBackgroundMain`
|
||||
* entrypoint (`lib/services/system_shelf_background.dart`), and resolves with
|
||||
* the bool that isolate reports through the `backgroundSyncComplete` method on
|
||||
* `com.plezy/watch_next`. The run is hard-capped at [RUN_TIMEOUT_MS]; the
|
||||
* engine is always destroyed on the main thread, timeout included.
|
||||
*/
|
||||
class ShelfRefreshWorker(
|
||||
appContext: Context,
|
||||
params: WorkerParameters
|
||||
) : CoroutineWorker(appContext, params) {
|
||||
companion object {
|
||||
private const val TAG = "ShelfRefreshWorker"
|
||||
internal const val RUN_TIMEOUT_MS = 90_000L
|
||||
|
||||
/** Test seam: replaces the headless Flutter launch so tests never boot an engine. */
|
||||
@Volatile
|
||||
@VisibleForTesting
|
||||
internal var engineLauncherOverride: (suspend (Context) -> Boolean)? = null
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
val context = applicationContext
|
||||
// Same support gate as WatchNextPlugin.handleIsSupported: no leanback
|
||||
// launcher, no Watch Next row worth refreshing.
|
||||
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) return Result.success()
|
||||
// A live engine (the foreground app) owns the shelf and keeps it fresh
|
||||
// itself; a concurrent headless engine would only fight it for ownership.
|
||||
if (SystemShelfLifecycle.hasLiveLease()) return Result.success()
|
||||
|
||||
val launcher = engineLauncherOverride ?: ::runHeadlessShelfSync
|
||||
val success = try {
|
||||
withTimeoutOrNull(RUN_TIMEOUT_MS) { launcher(context) } ?: false
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Background shelf refresh failed", e)
|
||||
false
|
||||
}
|
||||
return if (success) Result.success() else Result.retry()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun runHeadlessShelfSync(context: Context): Boolean {
|
||||
val appContext = context.applicationContext
|
||||
val completion = CompletableDeferred<Boolean>()
|
||||
val engine = withContext(Dispatchers.Main) {
|
||||
val loader = FlutterInjector.instance().flutterLoader()
|
||||
if (!loader.initialized()) {
|
||||
loader.startInitialization(appContext)
|
||||
}
|
||||
loader.ensureInitializationComplete(appContext, null)
|
||||
// The engine constructor auto-registers GeneratedPluginRegistrant plugins
|
||||
// (shared_preferences, path_provider, connectivity, sqlite, ...);
|
||||
// WatchNextPlugin is app-local and must be added explicitly.
|
||||
val engine = FlutterEngine(appContext)
|
||||
try {
|
||||
WatchNextPlugin.backgroundSyncCompletionListener = { success ->
|
||||
completion.complete(success)
|
||||
}
|
||||
engine.plugins.add(WatchNextPlugin())
|
||||
engine.dartExecutor.executeDartEntrypoint(
|
||||
DartExecutor.DartEntrypoint(
|
||||
loader.findAppBundlePath(),
|
||||
"package:plezy/services/system_shelf_background.dart",
|
||||
"systemShelfBackgroundMain"
|
||||
)
|
||||
)
|
||||
} catch (e: Throwable) {
|
||||
WatchNextPlugin.backgroundSyncCompletionListener = null
|
||||
engine.destroy()
|
||||
throw e
|
||||
}
|
||||
engine
|
||||
}
|
||||
return try {
|
||||
completion.await()
|
||||
} finally {
|
||||
withContext(NonCancellable + Dispatchers.Main) {
|
||||
WatchNextPlugin.backgroundSyncCompletionListener = null
|
||||
engine.destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
-7
@@ -3,6 +3,8 @@ package com.edde746.plezy.watchnext
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.work.WorkManager
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
@@ -15,6 +17,19 @@ class SystemShelfUpdateReceiver private constructor(
|
||||
constructor() : this(Executors.newSingleThreadExecutor(), true)
|
||||
internal constructor(executor: Executor) : this(executor, false)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SystemShelfUpdateReceiver"
|
||||
|
||||
/**
|
||||
* Unique name of the periodic ShelfRefreshWorker job 2.13.0 shipped and
|
||||
* enqueued (KEEP, persisted by WorkManager). The worker is gone, so on an
|
||||
* updated device the persisted job would wake the process once more, fail
|
||||
* to instantiate the deleted class, and linger as a permanently failed
|
||||
* record; cancel it on the first update instead.
|
||||
*/
|
||||
internal const val LEGACY_SHELF_REFRESH_WORK = "plezy_shelf_refresh"
|
||||
}
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val action = intent.action
|
||||
if (action != Intent.ACTION_MY_PACKAGE_REPLACED && action != Intent.ACTION_BOOT_COMPLETED) return
|
||||
@@ -22,22 +37,25 @@ class SystemShelfUpdateReceiver private constructor(
|
||||
executor.execute {
|
||||
try {
|
||||
val provider = WatchNextProvider.forMaintenance(context.applicationContext)
|
||||
// Snapshot before maintenance: restoreReadGrants() re-commits the
|
||||
// granted-URI key even when no sync ever wrote it.
|
||||
val hadPriorSync = provider.hasPersistedShelfState()
|
||||
if (action == Intent.ACTION_MY_PACKAGE_REPLACED) {
|
||||
cancelLegacyShelfRefreshWork(context.applicationContext)
|
||||
provider.migrateShelfSchema()
|
||||
} else {
|
||||
provider.restoreReadGrants()
|
||||
}
|
||||
// WorkManager normally survives reboots on its own; re-arming here
|
||||
// covers force-stop and update edge cases, and only for devices whose
|
||||
// persisted state says a shelf was actually synced before.
|
||||
if (hadPriorSync) ShelfRefreshScheduler.schedule(context.applicationContext)
|
||||
} finally {
|
||||
pending?.finish()
|
||||
if (ownsExecutor) (executor as ExecutorService).shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Best-effort by design: shelf maintenance must not die on a WorkManager failure. */
|
||||
private fun cancelLegacyShelfRefreshWork(context: Context) {
|
||||
try {
|
||||
WorkManager.getInstance(context).cancelUniqueWork(LEGACY_SHELF_REFRESH_WORK)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to cancel legacy shelf refresh work", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,13 +27,6 @@ class WatchNextPlugin() :
|
||||
internal const val SCHEMA_VERSION = 3
|
||||
private var pendingDeepLink: String? = null
|
||||
|
||||
// Resolves ShelfRefreshWorker's headless run. The worker installs it
|
||||
// before launching the background engine and clears it on engine destroy;
|
||||
// a foreground engine never sets it, so its own channel calls are unaffected.
|
||||
@Volatile
|
||||
@JvmStatic
|
||||
var backgroundSyncCompletionListener: ((Boolean) -> Unit)? = null
|
||||
|
||||
fun handleIntent(intent: Intent?): String? {
|
||||
val data = intent?.data ?: return null
|
||||
return if (data.scheme == "plezy" && data.authority == "play") {
|
||||
@@ -111,7 +104,6 @@ class WatchNextPlugin() :
|
||||
"clear" -> handleClear(call, result)
|
||||
"remove" -> handleRemove(call, result)
|
||||
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
|
||||
"backgroundSyncComplete" -> handleBackgroundSyncComplete(call, result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
@@ -144,12 +136,7 @@ class WatchNextPlugin() :
|
||||
val provider = session.provider ?: return@executeOnIo false
|
||||
val ownership = provider.claimOwnership(owner, generation) ?: return@executeOnIo false
|
||||
if (!session.isOpen()) return@executeOnIo false
|
||||
val synced = provider.syncWatchNextPrograms(owner, generation, items, ownership, session::isOpen)
|
||||
// Only a committed shelf warrants the periodic background refresh; KEEP
|
||||
// makes re-arming from every foreground sync (and the headless worker's
|
||||
// own sync) idempotent.
|
||||
if (synced) ShelfRefreshScheduler.schedule(session.context)
|
||||
synced
|
||||
provider.syncWatchNextPrograms(owner, generation, items, ownership, session::isOpen)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,10 +150,7 @@ class WatchNextPlugin() :
|
||||
val provider = session.provider ?: return@executeOnIo false
|
||||
val ownership = provider.claimOwnership(owner, generation) ?: return@executeOnIo false
|
||||
if (!session.isOpen()) return@executeOnIo false
|
||||
val cleared = provider.clearAll(owner, generation, ownership, session::isOpen)
|
||||
// A cleared shelf has nothing to refresh; the next successful sync re-arms.
|
||||
if (cleared) ShelfRefreshScheduler.cancel(session.context)
|
||||
cleared
|
||||
provider.clearAll(owner, generation, ownership, session::isOpen)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,12 +192,6 @@ class WatchNextPlugin() :
|
||||
result.success(contentId)
|
||||
}
|
||||
|
||||
private fun handleBackgroundSyncComplete(call: MethodCall, result: MethodChannel.Result) {
|
||||
val success = call.arguments as? Boolean ?: false
|
||||
backgroundSyncCompletionListener?.invoke(success)
|
||||
result.success(true)
|
||||
}
|
||||
|
||||
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
|
||||
val contentId = (data["contentId"] as? String)?.takeIf(String::isNotBlank) ?: return null
|
||||
val title = data["title"] as? String ?: return null
|
||||
|
||||
@@ -25,7 +25,6 @@ internal object SystemShelfLifecycle {
|
||||
private var claimToken = 0L
|
||||
private var currentOwner = ""
|
||||
private var currentGeneration = 0L
|
||||
private var leaseHeld = false
|
||||
|
||||
fun acquire(): Lease = acquireIf { true }!!
|
||||
|
||||
@@ -36,7 +35,6 @@ internal object SystemShelfLifecycle {
|
||||
claimToken += 1
|
||||
currentOwner = ""
|
||||
currentGeneration = 0
|
||||
leaseHeld = true
|
||||
Lease(token)
|
||||
}
|
||||
}
|
||||
@@ -47,19 +45,11 @@ internal object SystemShelfLifecycle {
|
||||
if (token == lease.token) {
|
||||
token += 1
|
||||
claimToken += 1
|
||||
leaseHeld = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True while the most recently acquired engine lease has not been
|
||||
* invalidated — i.e. a live engine (normally the UI) currently owns the
|
||||
* shelf. ShelfRefreshWorker checks this before booting a headless engine.
|
||||
*/
|
||||
fun hasLiveLease(): Boolean = synchronized(lock) { leaseHeld }
|
||||
|
||||
fun claim(lease: Lease, ownerId: String, generation: Long): Ownership? = synchronized(operationLock) {
|
||||
synchronized(lock) {
|
||||
if (
|
||||
@@ -140,13 +130,6 @@ class WatchNextProvider internal constructor(
|
||||
|
||||
internal fun claimOwnership(ownerId: String, generation: Long): SystemShelfLifecycle.Ownership? = lifecycleLease?.let { SystemShelfLifecycle.claim(it, ownerId, generation) }
|
||||
|
||||
/**
|
||||
* Whether a prior sync's committed state is still on disk. Cleared rows
|
||||
* ([clearAll]) and schema-migration wipes remove the granted-URI key, so
|
||||
* this distinguishes "user had a shelf" from "never synced / cleared".
|
||||
*/
|
||||
internal fun hasPersistedShelfState(): Boolean = prefs.contains(GRANTED_URIS)
|
||||
|
||||
internal fun syncWatchNextPrograms(
|
||||
ownerId: String,
|
||||
generation: Long,
|
||||
|
||||
@@ -48,38 +48,160 @@ 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
|
||||
fun spdifListIsEmptyForPcmOnlyRoutes() {
|
||||
assertEquals("", mpvSpdifCodecs { false })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun iecRouteIsNeverOfferedBelowApi24() {
|
||||
// ENCODING_IEC61937 does not exist there.
|
||||
assertFalse(
|
||||
iecRouteSupported(
|
||||
sdkInt = 23,
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { true },
|
||||
directPlaybackSupported = { true },
|
||||
hdmiRouteAdvertised = { true }
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun iecRouteRequiresASizableBufferOnEveryTier() {
|
||||
for (sdkInt in intArrayOf(25, 28, 29, 30, 32, 33, 34)) {
|
||||
assertFalse(
|
||||
"api $sdkInt",
|
||||
iecRouteSupported(
|
||||
sdkInt = sdkInt,
|
||||
canSizeBuffer = { false },
|
||||
bitstreamSupported = { true },
|
||||
directPlaybackSupported = { true },
|
||||
hdmiRouteAdvertised = { true }
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
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(25, 28)) {
|
||||
assertEquals(
|
||||
"api $sdkInt supported=$supported",
|
||||
supported,
|
||||
iecRouteSupported(
|
||||
sdkInt = sdkInt,
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { throw AssertionError("getDirectPlaybackSupport does not exist below API 33") },
|
||||
directPlaybackSupported = { throw AssertionError("isDirectPlaybackSupported does not exist below API 29") },
|
||||
hdmiRouteAdvertised = { supported }
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
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,
|
||||
iecRouteSupported(
|
||||
sdkInt = 33,
|
||||
canSizeBuffer = { true },
|
||||
bitstreamSupported = { supported },
|
||||
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") }
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -8,12 +8,23 @@ import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.EOFException
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class BufferedTransformingTrackOutputTest {
|
||||
@Before
|
||||
fun enableMedia3TestBoundsChecks() {
|
||||
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(true)
|
||||
}
|
||||
|
||||
@After
|
||||
fun resetMedia3TestBoundsChecks() {
|
||||
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeTransformBuffersChunksAndEmitsOneNormalizedSample() {
|
||||
|
||||
@@ -28,8 +28,6 @@ class BufferingStallPolicyTest {
|
||||
loading = loading
|
||||
)
|
||||
|
||||
// The loader's own state, for the case media3 never answers
|
||||
|
||||
@Test
|
||||
fun aLoaderThatStoppedAskingForDataCountsAsEnoughBuffer() {
|
||||
// The #1790 shape on a high bitrate stream: the byte cap is full at a couple of seconds, the
|
||||
@@ -51,8 +49,6 @@ class BufferingStallPolicyTest {
|
||||
assertEquals(Verdict.STALLED, evaluate(bufferedAheadMs = 2_000L, loading = false, loadControlReady = false))
|
||||
}
|
||||
|
||||
// The load control's own verdict
|
||||
|
||||
@Test
|
||||
fun aByteCappedBufferBelowTheDurationBarIsStillIndicted() {
|
||||
// The real failure this watchdog exists for, on a high bitrate stream: media3 released playback
|
||||
@@ -83,8 +79,6 @@ class BufferingStallPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
// Playback speed
|
||||
|
||||
@Test
|
||||
fun aFastForwardNeedsProportionallyMoreMediaBeforeItIsIndicted() {
|
||||
// Enough media to start at 1x, but the load control measures its bar in playout time, so at 2x
|
||||
@@ -107,8 +101,6 @@ class BufferingStallPolicyTest {
|
||||
assertEquals(Verdict.STALLED, evaluate(playbackSpeed = -1f))
|
||||
}
|
||||
|
||||
// Progress
|
||||
|
||||
@Test
|
||||
fun advancingPositionIsHealthy() {
|
||||
assertEquals(
|
||||
@@ -138,8 +130,6 @@ class BufferingStallPolicyTest {
|
||||
assertEquals(Verdict.STALLED, evaluate(currentPositionMs = position - 5_000))
|
||||
}
|
||||
|
||||
// Timeout
|
||||
|
||||
@Test
|
||||
fun frozenPositionWaitsOutTheTimeout() {
|
||||
assertEquals(Verdict.WAITING, evaluate(elapsedMs = BufferingStallPolicy.STALL_TIMEOUT_MS - 1))
|
||||
@@ -151,8 +141,6 @@ class BufferingStallPolicyTest {
|
||||
assertEquals(Verdict.STALLED, evaluate())
|
||||
}
|
||||
|
||||
// Starvation — the loader's problem, not the renderer's
|
||||
|
||||
@Test
|
||||
fun emptyBufferIsStarved() {
|
||||
assertEquals(Verdict.STARVED, evaluate(bufferedAheadMs = 0))
|
||||
@@ -203,8 +191,6 @@ class BufferingStallPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
// Stall clock ownership
|
||||
|
||||
@Test
|
||||
fun starvationAndProgressBothRestartTheStallClock() {
|
||||
assertTrue(BufferingStallPolicy.resetsStallClock(Verdict.STARVED))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -10,8 +10,6 @@ class DvBitstreamSanitizerTest {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
// --- HDR10+ SEI stripping (native DV codec path) ---
|
||||
|
||||
@Test
|
||||
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
|
||||
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
|
||||
@@ -85,8 +83,6 @@ class DvBitstreamSanitizerTest {
|
||||
assertArrayEquals(original, remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- DV RPU/EL stripping (HEVC fallback path) ---
|
||||
|
||||
@Test
|
||||
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
|
||||
val vcl = annexBNal(1, byteArrayOf(0x01))
|
||||
@@ -111,8 +107,6 @@ class DvBitstreamSanitizerTest {
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- Buffer handling ---
|
||||
|
||||
@Test
|
||||
fun respectsPositionAndRestoresIt() {
|
||||
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
|
||||
@@ -245,8 +239,6 @@ class DvBitstreamSanitizerTest {
|
||||
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
/** Builds an HEVC NAL unit: start code + 2-byte NAL header encoding [nalUnitType] + payload. */
|
||||
private fun annexBNal(nalUnitType: Int, payload: ByteArray, startCodeLen: Int = 4): ByteArray {
|
||||
val startCode = if (startCodeLen == 3) byteArrayOf(0, 0, 1) else byteArrayOf(0, 0, 0, 1)
|
||||
|
||||
@@ -24,8 +24,6 @@ class EndOfStreamPolicyTest {
|
||||
frameStallMs = frameStallMs
|
||||
)
|
||||
|
||||
// isFinishedFile
|
||||
|
||||
@Test
|
||||
fun stuckPastDurationWithNoPictureIsTheEndOfTheFile() {
|
||||
// The reported failure: the clock ran a minute past the last frame.
|
||||
@@ -65,8 +63,6 @@ class EndOfStreamPolicyTest {
|
||||
assertFalse(isFinishedFile(hasPlaybackOutput = false))
|
||||
}
|
||||
|
||||
// fallbackStartPositionMs
|
||||
|
||||
@Test
|
||||
fun fallbackResumesStrictlyInsideTheMedia() {
|
||||
// The observed hand-off asked MPV to start 59_816ms past the end.
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
}
|
||||
+211
-45
@@ -8,10 +8,12 @@ import androidx.media3.common.C
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.PlaybackParameters
|
||||
import androidx.media3.common.Timeline
|
||||
import androidx.media3.common.util.Clock
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.analytics.PlayerId
|
||||
import androidx.media3.exoplayer.audio.AudioSink
|
||||
import androidx.media3.exoplayer.source.MediaSource
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
@@ -22,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"))
|
||||
@@ -38,20 +41,36 @@ 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(
|
||||
carrier: FakeSink = FakeSink(),
|
||||
normal: FakeSink = FakeSink(),
|
||||
routeAvailable: Boolean = true,
|
||||
blocked: Boolean = false
|
||||
) = TrueHdCarrierSink(normal, carrier, { routeAvailable }, { blocked })
|
||||
|
||||
// --- Selection ---
|
||||
) = IecCarrierSink(normal, carrier, { routeAvailable }, { blocked })
|
||||
|
||||
/**
|
||||
* TrueHD is the carrier or it is decoded. Falling through to the normal sink would hand media3
|
||||
@@ -73,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() {
|
||||
@@ -81,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
|
||||
@@ -90,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. */
|
||||
@@ -98,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()))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,7 +181,7 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
val listener = RecordingSinkListener()
|
||||
carrierSink.setListener(listener)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
assertTrue("carrier should be live before the speed change", carrierSink.isCarrierActive)
|
||||
|
||||
carrierSink.setPlaybackParameters(PlaybackParameters(1.5f))
|
||||
@@ -132,7 +202,7 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink()
|
||||
val listener = RecordingSinkListener()
|
||||
carrierSink.setListener(listener)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
|
||||
carrierSink.setPlaybackParameters(PlaybackParameters(1.5f))
|
||||
carrierSink.setPlaybackParameters(PlaybackParameters(1f))
|
||||
@@ -147,15 +217,13 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink()
|
||||
val listener = RecordingSinkListener()
|
||||
carrierSink.setListener(listener)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
|
||||
carrierSink.setPlaybackParameters(PlaybackParameters(1f))
|
||||
|
||||
assertEquals(0, listener.capabilityInvalidations)
|
||||
}
|
||||
|
||||
// --- Rate-family mismatch discovered mid-stream ---
|
||||
|
||||
/**
|
||||
* Selection reads Format.sampleRate; the rate family is only certain once a major sync is parsed.
|
||||
* When they disagree the packer emits nothing, so consuming the input would turn the stream into
|
||||
@@ -167,7 +235,7 @@ class TrueHdCarrierSinkTest {
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
val listener = RecordingSinkListener()
|
||||
carrierSink.setListener(listener)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
|
||||
val buffer = ByteBuffer.wrap(fortyFourFamilyAccessUnits())
|
||||
val accepted = carrierSink.handleBuffer(buffer, 0L, 1)
|
||||
@@ -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
|
||||
@@ -192,7 +287,7 @@ class TrueHdCarrierSinkTest {
|
||||
fun theMismatchLatchSurvivesTheResetThatAccompaniesTheHandover() {
|
||||
val carrierSink = sink()
|
||||
carrierSink.setListener(RecordingSinkListener())
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
carrierSink.handleBuffer(ByteBuffer.wrap(fortyFourFamilyAccessUnits()), 0L, 1)
|
||||
|
||||
carrierSink.flush()
|
||||
@@ -210,7 +305,7 @@ class TrueHdCarrierSinkTest {
|
||||
fun releasingTheSinkClearsTheMismatchLatch() {
|
||||
val carrierSink = sink()
|
||||
carrierSink.setListener(RecordingSinkListener())
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
carrierSink.handleBuffer(ByteBuffer.wrap(fortyFourFamilyAccessUnits()), 0L, 1)
|
||||
|
||||
carrierSink.release()
|
||||
@@ -240,7 +335,7 @@ class TrueHdCarrierSinkTest {
|
||||
fun aNewMediaItemClearsTheMismatchLatch() {
|
||||
val carrierSink = sink()
|
||||
carrierSink.setListener(RecordingSinkListener())
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
carrierSink.handleBuffer(ByteBuffer.wrap(fortyFourFamilyAccessUnits()), 0L, 1)
|
||||
assertEquals(
|
||||
AudioSink.SINK_FORMAT_UNSUPPORTED,
|
||||
@@ -265,7 +360,7 @@ class TrueHdCarrierSinkTest {
|
||||
fun aLateMismatchFromThePreviousItemDoesNotPoisonTheNewOne() {
|
||||
val carrierSink = sink()
|
||||
carrierSink.setListener(RecordingSinkListener())
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
|
||||
// The new item starts before the outgoing stream's last buffer is handled.
|
||||
carrierSink.beginMediaItem()
|
||||
@@ -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 }
|
||||
@@ -289,8 +384,6 @@ class TrueHdCarrierSinkTest {
|
||||
assertTrue(carrierSink.supportsFormat(ac3))
|
||||
}
|
||||
|
||||
// --- Back pressure ---
|
||||
|
||||
/**
|
||||
* The regression this exists for: a delegate that refuses a burst part-way through a sample must
|
||||
* not cost the access units behind it. media3 re-delivers the same buffer after a false return,
|
||||
@@ -300,12 +393,12 @@ class TrueHdCarrierSinkTest {
|
||||
fun aRefusedBurstMidSampleLosesNoAccessUnits() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
|
||||
// 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,9 +408,55 @@ class TrueHdCarrierSinkTest {
|
||||
fun theCarrierOutputMatchesTheGoldenStream() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
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. */
|
||||
@@ -325,7 +464,7 @@ class TrueHdCarrierSinkTest {
|
||||
fun aPendingBurstIsPlacedBeforeMoreInputIsConsumed() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(audioSinkConfig())
|
||||
carrier.refuseNext = true
|
||||
|
||||
val buffer = ByteBuffer.wrap(accessUnits)
|
||||
@@ -336,8 +475,6 @@ class TrueHdCarrierSinkTest {
|
||||
assertTrue(carrierSink.hasPendingData())
|
||||
}
|
||||
|
||||
// --- Routing of controls ---
|
||||
|
||||
@Test
|
||||
fun persistentControlsReachBothDelegates() {
|
||||
val carrier = FakeSink()
|
||||
@@ -370,14 +507,37 @@ class TrueHdCarrierSinkTest {
|
||||
fun theCarrierDelegateIsConfiguredAsAFixedRatePcmCarrier() {
|
||||
val carrier = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier)
|
||||
val inputConfig = AudioSink.AudioSinkConfig.Builder(trueHdFormat())
|
||||
.setPreferredBufferSizeOverride(4_096)
|
||||
.setTimeline(Timeline.EMPTY)
|
||||
.setMediaPeriodId(MediaSource.MediaPeriodId("period"))
|
||||
.build()
|
||||
|
||||
carrierSink.configure(trueHdFormat(), 0, null)
|
||||
carrierSink.configure(inputConfig)
|
||||
|
||||
val configured = checkNotNull(carrier.configuredFormat)
|
||||
assertEquals(MimeTypes.AUDIO_RAW, configured.sampleMimeType)
|
||||
assertEquals(C.ENCODING_PCM_16BIT, configured.pcmEncoding)
|
||||
assertEquals(TrueHdMatPacker.CARRIER_SAMPLE_RATE, configured.sampleRate)
|
||||
assertEquals(TrueHdMatPacker.CARRIER_CHANNEL_COUNT, configured.channelCount)
|
||||
val configured = checkNotNull(carrier.configuredConfig)
|
||||
assertEquals(inputConfig.preferredBufferSizeOverride, configured.preferredBufferSizeOverride)
|
||||
assertSame(inputConfig.timeline, configured.timeline)
|
||||
assertEquals(inputConfig.mediaPeriodId, configured.mediaPeriodId)
|
||||
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)
|
||||
}
|
||||
|
||||
/** 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
|
||||
@@ -386,25 +546,29 @@ class TrueHdCarrierSinkTest {
|
||||
val normal = FakeSink()
|
||||
val carrierSink = sink(carrier = carrier, normal = normal)
|
||||
val ac3 = Format.Builder().setSampleMimeType(MimeTypes.AUDIO_AC3).setSampleRate(48_000).build()
|
||||
val config = audioSinkConfig(ac3)
|
||||
|
||||
carrierSink.configure(ac3, 0, null)
|
||||
carrierSink.configure(config)
|
||||
|
||||
assertSame(ac3, normal.configuredFormat)
|
||||
assertEquals(null, carrier.configuredFormat)
|
||||
assertSame(config, normal.configuredConfig)
|
||||
assertSame(ac3, normal.configuredConfig?.format)
|
||||
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
|
||||
}
|
||||
@@ -424,7 +588,8 @@ class TrueHdCarrierSinkTest {
|
||||
/** Minimal AudioSink that records what it was handed and can apply back pressure. */
|
||||
private class FakeSink : AudioSink {
|
||||
val written = ByteArrayOutputStream()
|
||||
var configuredFormat: Format? = null
|
||||
val bufferTimesUs = mutableListOf<Long>()
|
||||
var configuredConfig: AudioSink.AudioSinkConfig? = null
|
||||
var formatSupport: Int = AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
var lastVolume: Float = -1f
|
||||
var sessionId: Int = -1
|
||||
@@ -448,12 +613,13 @@ class TrueHdCarrierSinkTest {
|
||||
val copy = ByteArray(buffer.remaining())
|
||||
buffer.duplicate().get(copy)
|
||||
written.write(copy)
|
||||
bufferTimesUs.add(presentationTimeUs)
|
||||
buffer.position(buffer.limit())
|
||||
return true
|
||||
}
|
||||
|
||||
override fun configure(inputFormat: Format, specifiedBufferSize: Int, outputChannels: IntArray?) {
|
||||
configuredFormat = inputFormat
|
||||
override fun configure(audioSinkConfig: AudioSink.AudioSinkConfig) {
|
||||
configuredConfig = audioSinkConfig
|
||||
}
|
||||
|
||||
override fun supportsFormat(format: Format) = formatSupport == AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY
|
||||
+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)
|
||||
@@ -9,8 +9,6 @@ private const val MIB = 1024 * 1024
|
||||
|
||||
class LoadControlPolicyTest {
|
||||
|
||||
// autoTargetBufferBytes
|
||||
|
||||
@Test
|
||||
fun neverExceedsMedia3sOwnTargetEvenWithHugeMemory() {
|
||||
assertEquals(
|
||||
@@ -64,8 +62,6 @@ class LoadControlPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
// readAheadSeconds
|
||||
|
||||
@Test
|
||||
fun readAheadReportsSecondsAtAKnownBitrate() {
|
||||
// 64MiB of the #1618 stream (103_341 kbps) is ~5.2s — under the 15s minBufferMs, so the
|
||||
@@ -86,8 +82,6 @@ class LoadControlPolicyTest {
|
||||
assertNull(LoadControlPolicy.readAheadSeconds(64 * MIB, -1L))
|
||||
}
|
||||
|
||||
// bufferDurations
|
||||
|
||||
/**
|
||||
* media3 validates the ordering with Guava `Preconditions`, which is a plain throw rather than
|
||||
* a JVM assert, so a bad pair takes down `DefaultLoadControl.Builder.build()` in release too.
|
||||
@@ -172,8 +166,6 @@ class LoadControlPolicyTest {
|
||||
}
|
||||
}
|
||||
|
||||
// BufferTier.fromWire
|
||||
|
||||
@Test
|
||||
fun theWireNamesMatchTheDartNativeValues() {
|
||||
assertEquals(LoadControlPolicy.BufferTier.LARGE, LoadControlPolicy.BufferTier.fromWire("large"))
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.text.Cue
|
||||
import androidx.media3.extractor.text.CuesWithTiming
|
||||
import androidx.media3.extractor.text.SubtitleParser
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.Deflater
|
||||
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
|
||||
|
||||
/**
|
||||
* Regression coverage for #1953: display sets with several composition objects must
|
||||
* produce one cue per object, and Normal-state display sets (palette-only fades,
|
||||
* cached-object reuse) must keep the composition instead of blanking it.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class PgsCompositionParserTest {
|
||||
|
||||
private companion object {
|
||||
const val WHITE = 0xFFFFFFFF.toInt()
|
||||
const val FADED_WHITE = 0x80FFFFFF.toInt()
|
||||
const val YELLOW = 0xFFFFF000.toInt()
|
||||
const val GREEN_BT709 = 0xFF00D800.toInt()
|
||||
const val GREEN_BT601 = 0xFF00FF01.toInt()
|
||||
|
||||
val WHITE_ENTRY = intArrayOf(1, 235, 128, 128, 255)
|
||||
val YELLOW_ENTRY = intArrayOf(2, 210, 146, 16, 255)
|
||||
|
||||
const val STATE_NORMAL = 0x00
|
||||
const val STATE_EPOCH_START = 0x80
|
||||
}
|
||||
|
||||
private class Buf {
|
||||
private val out = ByteArrayOutputStream()
|
||||
|
||||
fun u8(value: Int) = apply { out.write(value) }
|
||||
|
||||
fun u16(value: Int) = apply {
|
||||
out.write(value ushr 8)
|
||||
out.write(value)
|
||||
}
|
||||
|
||||
fun u24(value: Int) = apply {
|
||||
out.write(value ushr 16)
|
||||
out.write(value ushr 8)
|
||||
out.write(value)
|
||||
}
|
||||
|
||||
fun raw(bytes: ByteArray) = apply { out.write(bytes) }
|
||||
|
||||
fun build(): ByteArray = out.toByteArray()
|
||||
}
|
||||
|
||||
private fun segment(type: Int, payload: ByteArray): ByteArray = Buf().u8(type).u16(payload.size).raw(payload).build()
|
||||
|
||||
private fun objectRef(id: Int, x: Int, y: Int, cropped: Boolean = false): ByteArray = Buf()
|
||||
.u16(id)
|
||||
.u8(0) // Window id.
|
||||
.u8(if (cropped) 0x80 else 0)
|
||||
.u16(x)
|
||||
.u16(y)
|
||||
.raw(if (cropped) ByteArray(8) else ByteArray(0)) // Crop rectangle.
|
||||
.build()
|
||||
|
||||
private fun pcs(planeWidth: Int, planeHeight: Int, state: Int, vararg refs: ByteArray): ByteArray {
|
||||
val payload = Buf()
|
||||
.u16(planeWidth)
|
||||
.u16(planeHeight)
|
||||
.u8(0x10) // Frame rate.
|
||||
.u16(0) // Composition number.
|
||||
.u8(state)
|
||||
.u8(0) // Palette update flag.
|
||||
.u8(0) // Palette id.
|
||||
.u8(refs.size)
|
||||
refs.forEach { payload.raw(it) }
|
||||
return segment(0x16, payload.build())
|
||||
}
|
||||
|
||||
private fun pds(vararg entries: IntArray): ByteArray {
|
||||
val payload = Buf().u8(0).u8(0) // Palette id, version.
|
||||
entries.forEach { e -> payload.u8(e[0]).u8(e[1]).u8(e[2]).u8(e[3]).u8(e[4]) }
|
||||
return segment(0x14, payload.build())
|
||||
}
|
||||
|
||||
private fun ods(id: Int, width: Int, height: Int, rle: ByteArray): ByteArray = segment(
|
||||
0x15,
|
||||
Buf().u16(id).u8(0).u8(0xC0).u24(rle.size + 4).u16(width).u16(height).raw(rle).build()
|
||||
)
|
||||
|
||||
/** RLE for a solid bitmap: one literal palette-index byte per pixel. */
|
||||
private fun solidRle(width: Int, height: Int, colorIndex: Int): ByteArray = ByteArray(width * height) { colorIndex.toByte() }
|
||||
|
||||
private fun end(): ByteArray = segment(0x80, ByteArray(0))
|
||||
|
||||
private fun displaySet(vararg segments: ByteArray): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
segments.forEach { out.write(it) }
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun parseCues(parser: PgsCompositionParser, sample: ByteArray): List<Cue> {
|
||||
val outputs = mutableListOf<CuesWithTiming>()
|
||||
parser.parse(sample, SubtitleParser.OutputOptions.allCues()) { outputs.add(it) }
|
||||
assertEquals(1, outputs.size)
|
||||
return outputs[0].cues
|
||||
}
|
||||
|
||||
/** Epoch-start display set: white 4x2 object at (100, 900) and yellow 6x3 object at (200, 100). */
|
||||
private fun twoObjectEpochStart(): ByteArray = displaySet(
|
||||
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 100, 900), objectRef(2, 200, 100)),
|
||||
pds(WHITE_ENTRY, YELLOW_ENTRY),
|
||||
ods(1, 4, 2, solidRle(4, 2, 1)),
|
||||
ods(2, 6, 3, solidRle(6, 3, 2)),
|
||||
end()
|
||||
)
|
||||
|
||||
@Test
|
||||
fun twoCompositionObjectsProduceIndependentlyPositionedCues() {
|
||||
val cues = parseCues(PgsCompositionParser(), twoObjectEpochStart())
|
||||
|
||||
assertEquals(2, cues.size)
|
||||
val (dialogue, sign) = cues
|
||||
assertEquals(100f / 1920f, dialogue.position, 1e-6f)
|
||||
assertEquals(900f / 1080f, dialogue.line, 1e-6f)
|
||||
assertEquals(4f / 1920f, dialogue.size, 1e-6f)
|
||||
assertEquals(2f / 1080f, dialogue.bitmapHeight, 1e-6f)
|
||||
assertEquals(WHITE, dialogue.bitmap!!.getPixel(0, 0))
|
||||
assertEquals(200f / 1920f, sign.position, 1e-6f)
|
||||
assertEquals(100f / 1080f, sign.line, 1e-6f)
|
||||
assertEquals(6, sign.bitmap!!.width)
|
||||
assertEquals(3, sign.bitmap!!.height)
|
||||
assertEquals(YELLOW, sign.bitmap!!.getPixel(5, 2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun paletteOnlyFadeUpdateKeepsBothObjectsAndPreservesUnsentEntries() {
|
||||
val parser = PgsCompositionParser()
|
||||
parseCues(parser, twoObjectEpochStart())
|
||||
|
||||
// Normal-state fade step: same references, only the white entry's alpha changes.
|
||||
val cues = parseCues(
|
||||
parser,
|
||||
displaySet(
|
||||
pcs(1920, 1080, STATE_NORMAL, objectRef(1, 100, 900), objectRef(2, 200, 100)),
|
||||
pds(intArrayOf(1, 235, 128, 128, 128)),
|
||||
end()
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(2, cues.size)
|
||||
assertEquals(FADED_WHITE, cues[0].bitmap!!.getPixel(0, 0))
|
||||
// The yellow entry was not resent; an in-place palette update must preserve it.
|
||||
assertEquals(YELLOW, cues[1].bitmap!!.getPixel(0, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun zeroObjectDisplaySetClearsTheComposition() {
|
||||
val parser = PgsCompositionParser()
|
||||
parseCues(parser, twoObjectEpochStart())
|
||||
|
||||
val cues = parseCues(parser, displaySet(pcs(1920, 1080, STATE_NORMAL), end()))
|
||||
|
||||
assertTrue(cues.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun epochStartReleasesCachedObjects() {
|
||||
val parser = PgsCompositionParser()
|
||||
parseCues(parser, twoObjectEpochStart())
|
||||
|
||||
// New epoch referencing an object it never defines: nothing may leak across.
|
||||
val cues = parseCues(
|
||||
parser,
|
||||
displaySet(pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 100, 900)), end())
|
||||
)
|
||||
|
||||
assertTrue(cues.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resetDropsEpochState() {
|
||||
val parser = PgsCompositionParser()
|
||||
parseCues(parser, twoObjectEpochStart())
|
||||
|
||||
parser.reset()
|
||||
val cues = parseCues(
|
||||
parser,
|
||||
displaySet(pcs(1920, 1080, STATE_NORMAL, objectRef(1, 100, 900)), end())
|
||||
)
|
||||
|
||||
assertTrue(cues.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fragmentedObjectReassembles() {
|
||||
val rle = solidRle(4, 2, 1)
|
||||
val first = segment(
|
||||
0x15,
|
||||
Buf().u16(1).u8(0).u8(0x80).u24(rle.size + 4).u16(4).u16(2).raw(rle.copyOfRange(0, 3)).build()
|
||||
)
|
||||
val continuation = segment(
|
||||
0x15,
|
||||
Buf().u16(1).u8(0).u8(0x40).raw(rle.copyOfRange(3, rle.size)).build()
|
||||
)
|
||||
|
||||
val cues = parseCues(
|
||||
PgsCompositionParser(),
|
||||
displaySet(pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 0, 0)), pds(WHITE_ENTRY), first, continuation, end())
|
||||
)
|
||||
|
||||
assertEquals(1, cues.size)
|
||||
assertEquals(WHITE, cues[0].bitmap!!.getPixel(3, 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun croppedFirstReferenceDoesNotCorruptTheSecond() {
|
||||
val cues = parseCues(
|
||||
PgsCompositionParser(),
|
||||
displaySet(
|
||||
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 100, 900, cropped = true), objectRef(2, 200, 100)),
|
||||
pds(WHITE_ENTRY, YELLOW_ENTRY),
|
||||
ods(1, 4, 2, solidRle(4, 2, 1)),
|
||||
ods(2, 6, 3, solidRle(6, 3, 2)),
|
||||
end()
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(2, cues.size)
|
||||
assertEquals(200f / 1920f, cues[1].position, 1e-6f)
|
||||
assertEquals(100f / 1080f, cues[1].line, 1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun runLengthEncodedBitmapsDecode() {
|
||||
// Short-form color run (16 white pixels), then a long-form run (100 pixels).
|
||||
val shortRun = byteArrayOf(0x00, 0x90.toByte(), 0x01)
|
||||
val longRun = byteArrayOf(0x00, 0xC0.toByte(), 0x64, 0x01)
|
||||
|
||||
val cues = parseCues(
|
||||
PgsCompositionParser(),
|
||||
displaySet(
|
||||
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 0, 0), objectRef(2, 0, 200)),
|
||||
pds(WHITE_ENTRY),
|
||||
ods(1, 16, 1, shortRun),
|
||||
ods(2, 100, 1, longRun),
|
||||
end()
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(2, cues.size)
|
||||
assertEquals(WHITE, cues[0].bitmap!!.getPixel(15, 0))
|
||||
assertEquals(WHITE, cues[1].bitmap!!.getPixel(99, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun zlibCompressedSampleParses() {
|
||||
val deflater = Deflater()
|
||||
deflater.setInput(twoObjectEpochStart())
|
||||
deflater.finish()
|
||||
val compressed = ByteArray(4096)
|
||||
val length = deflater.deflate(compressed)
|
||||
deflater.end()
|
||||
|
||||
val cues = parseCues(PgsCompositionParser(), compressed.copyOf(length))
|
||||
|
||||
assertEquals(2, cues.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun paletteMatrixFollowsPlaneHeight() {
|
||||
val greenEntry = intArrayOf(1, 145, 34, 54, 255)
|
||||
|
||||
val hdCues = parseCues(
|
||||
PgsCompositionParser(),
|
||||
displaySet(
|
||||
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 0, 0)),
|
||||
pds(greenEntry),
|
||||
ods(1, 1, 1, solidRle(1, 1, 1)),
|
||||
end()
|
||||
)
|
||||
)
|
||||
val sdCues = parseCues(
|
||||
PgsCompositionParser(),
|
||||
displaySet(
|
||||
pcs(720, 576, STATE_EPOCH_START, objectRef(1, 0, 0)),
|
||||
pds(greenEntry),
|
||||
ods(1, 1, 1, solidRle(1, 1, 1)),
|
||||
end()
|
||||
)
|
||||
)
|
||||
|
||||
assertEquals(GREEN_BT709, hdCues[0].bitmap!!.getPixel(0, 0))
|
||||
assertEquals(GREEN_BT601, sdCues[0].bitmap!!.getPixel(0, 0))
|
||||
}
|
||||
}
|
||||
@@ -52,8 +52,6 @@ class RawPositionAudioOutputTest {
|
||||
return output to listener
|
||||
}
|
||||
|
||||
// Release reporting
|
||||
|
||||
/**
|
||||
* A parked track is never going to release, so its flush has to be answered at once. Deferring
|
||||
* until the eviction would hold `DefaultAudioSink`'s process-wide pending-release count above
|
||||
@@ -116,8 +114,6 @@ class RawPositionAudioOutputTest {
|
||||
assertEquals(1, listener.releasedCount)
|
||||
}
|
||||
|
||||
// Reuse
|
||||
|
||||
@Test
|
||||
fun aParkedOutputIsHandedBackForAnIdenticalConfig() {
|
||||
val delegate = FakeOutputProvider()
|
||||
@@ -178,8 +174,6 @@ class RawPositionAudioOutputTest {
|
||||
assertEquals(1, secondListener.underrunCount)
|
||||
}
|
||||
|
||||
// Eviction — the overlap media3 itself tolerates, kept tolerable
|
||||
|
||||
/**
|
||||
* The replacement is deliberately built while the evicted track is still going away. Refusing
|
||||
* until it confirms looks safer, but the refusal reaches media3 as an init failure with no
|
||||
@@ -221,8 +215,6 @@ class RawPositionAudioOutputTest {
|
||||
assertEquals(1, listener.releasedCount)
|
||||
}
|
||||
|
||||
// Fakes
|
||||
|
||||
private class RecordingListener : AudioOutput.Listener {
|
||||
var releasedCount = 0
|
||||
var underrunCount = 0
|
||||
|
||||
@@ -7,8 +7,6 @@ import org.junit.Test
|
||||
|
||||
class ResumeStallPolicyTest {
|
||||
|
||||
// checkWindowMs
|
||||
|
||||
@Test
|
||||
fun windowFloorsAtDefaultForNormalFrameRates() {
|
||||
// 24fps → 4 × 42ms = 168ms, floored to 1000ms
|
||||
@@ -39,8 +37,6 @@ class ResumeStallPolicyTest {
|
||||
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = null, detectedFps = null, speed = 1f))
|
||||
}
|
||||
|
||||
// evaluate
|
||||
|
||||
@Test
|
||||
fun advancingFramesAreHealthy() {
|
||||
assertEquals(
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -9,16 +9,39 @@ class SubtitleViewLayoutTest {
|
||||
@Test
|
||||
fun letterboxUsesVisibleVideoRectForTextAndBitmapSubtitles() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
|
||||
val bitmap = bitmapDimensions()
|
||||
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun croppedVideoUsesBitmapCompositionPlaneAspect() {
|
||||
// #1945: 3840x1604 video with a 1920x1080 PGS plane in a 2400x1080 container.
|
||||
val planeAspect = SubtitleViewLayout.bitmapPlaneAspect(
|
||||
bitmapWidth = 480,
|
||||
bitmapHeight = 100,
|
||||
cueWidthFraction = 480f / 1920f,
|
||||
cueHeightFraction = 100f / 1080f
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
SubtitleViewDimensions(1781, 1002),
|
||||
SubtitleViewLayout.bitmapDimensions(
|
||||
containerWidth = 2400,
|
||||
containerHeight = 1080,
|
||||
videoWidth = 3840,
|
||||
videoHeight = 1604,
|
||||
pixelRatio = 1f,
|
||||
planeAspect = planeAspect
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coverKeepsTextOnScreenAndBitmapSubtitlesFullyVisible() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
|
||||
val bitmap = bitmapDimensions()
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
@@ -28,7 +51,7 @@ class SubtitleViewLayoutTest {
|
||||
@Test
|
||||
fun manualZoomKeepsBitmapSubtitlesFullyVisible() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, zoomScale = 1.5f)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, zoomScale = 1.5f)
|
||||
val bitmap = bitmapDimensions()
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
@@ -38,7 +61,7 @@ class SubtitleViewLayoutTest {
|
||||
@Test
|
||||
fun stretchDoesNotStretchBitmapSubtitlesToScreenAspect() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
|
||||
val bitmap = bitmapDimensions()
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
@@ -48,7 +71,7 @@ class SubtitleViewLayoutTest {
|
||||
@Test
|
||||
fun anchorToScreenSizesTextToContainerAndKeepsBitmapOnVideoRect() {
|
||||
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, anchorToScreen = true)
|
||||
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
|
||||
val bitmap = bitmapDimensions()
|
||||
|
||||
assertEquals(SubtitleViewDimensions(2424, 1080), text)
|
||||
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
|
||||
@@ -99,17 +122,13 @@ class SubtitleViewLayoutTest {
|
||||
anchorToScreen = anchorToScreen
|
||||
)
|
||||
|
||||
private fun bitmapDimensions(
|
||||
resizeMode: Int,
|
||||
zoomScale: Float = 1f
|
||||
): SubtitleViewDimensions? = SubtitleViewLayout.bitmapDimensions(
|
||||
private fun bitmapDimensions(): SubtitleViewDimensions? = SubtitleViewLayout.bitmapDimensions(
|
||||
containerWidth = 2424,
|
||||
containerHeight = 1080,
|
||||
videoWidth = 1920,
|
||||
videoHeight = 1080,
|
||||
pixelRatio = 1f,
|
||||
resizeMode = resizeMode,
|
||||
zoomScale = zoomScale
|
||||
planeAspect = null
|
||||
)
|
||||
|
||||
private fun assertAspectCloseTo16By9(dimensions: SubtitleViewDimensions) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
-237
@@ -1,237 +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.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ZlibInflatingTrackOutputTest {
|
||||
|
||||
@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))
|
||||
}
|
||||
}
|
||||
@@ -1,286 +0,0 @@
|
||||
package com.edde746.plezy.watchnext
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.database.Cursor
|
||||
import android.database.MatrixCursor
|
||||
import android.net.Uri
|
||||
import androidx.tvprovider.media.tv.TvContractCompat
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.testing.TestListenableWorkerBuilder
|
||||
import androidx.work.testing.WorkManagerTestInitHelper
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.lang.reflect.Proxy
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.RuntimeEnvironment
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.shadows.ShadowContentResolver
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ShelfRefreshWorkerTest {
|
||||
private val context: Context get() = RuntimeEnvironment.getApplication()
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
context.getSharedPreferences("system_shelf_state", 0).edit().clear().commit()
|
||||
context.cacheDir.resolve("system_shelf_artwork").deleteRecursively()
|
||||
ShadowContentResolver.registerProviderInternal(TvContractCompat.AUTHORITY, StubTvProvider())
|
||||
WorkManagerTestInitHelper.initializeTestWorkManager(context)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
ShelfRefreshWorker.engineLauncherOverride = null
|
||||
// Leave no live lease behind for the next test in this sandbox.
|
||||
SystemShelfLifecycle.invalidate(SystemShelfLifecycle.acquire())
|
||||
context.cacheDir.resolve("system_shelf_artwork").deleteRecursively()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun successfulSyncSchedulesUniquePeriodicRefreshWithKeepAndNetworkConstraint() {
|
||||
val plugin = WatchNextPlugin()
|
||||
val binding = pluginBinding()
|
||||
plugin.onAttachedToEngine(binding)
|
||||
try {
|
||||
val first = ShelfRecordingResult()
|
||||
plugin.onMethodCall(syncCall(generation = 1), first)
|
||||
awaitResult(first)
|
||||
assertEquals(true, first.successValue)
|
||||
|
||||
val infos = uniqueWorkInfos()
|
||||
assertEquals(1, infos.size)
|
||||
val info = infos.single()
|
||||
assertEquals(WorkInfo.State.ENQUEUED, info.state)
|
||||
assertEquals(NetworkType.CONNECTED, info.constraints.requiredNetworkType)
|
||||
assertEquals(TimeUnit.HOURS.toMillis(6), info.periodicityInfo?.repeatIntervalMillis)
|
||||
|
||||
// KEEP: a second successful sync must not replace the pending request.
|
||||
val second = ShelfRecordingResult()
|
||||
plugin.onMethodCall(syncCall(generation = 2), second)
|
||||
awaitResult(second)
|
||||
assertEquals(true, second.successValue)
|
||||
assertEquals(info.id, uniqueWorkInfos().single().id)
|
||||
} finally {
|
||||
plugin.onDetachedFromEngine(binding)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearCancelsScheduledRefresh() {
|
||||
val plugin = WatchNextPlugin()
|
||||
val binding = pluginBinding()
|
||||
plugin.onAttachedToEngine(binding)
|
||||
try {
|
||||
val sync = ShelfRecordingResult()
|
||||
plugin.onMethodCall(syncCall(generation = 1), sync)
|
||||
awaitResult(sync)
|
||||
assertEquals(true, sync.successValue)
|
||||
assertEquals(WorkInfo.State.ENQUEUED, uniqueWorkInfos().single().state)
|
||||
|
||||
val clear = ShelfRecordingResult()
|
||||
plugin.onMethodCall(
|
||||
MethodCall("clear", mapOf("schemaVersion" to 3, "ownerId" to "owner-a", "generation" to 2L)),
|
||||
clear
|
||||
)
|
||||
awaitResult(clear)
|
||||
assertEquals(true, clear.successValue)
|
||||
assertEquals(WorkInfo.State.CANCELLED, uniqueWorkInfos().single().state)
|
||||
} finally {
|
||||
plugin.onDetachedFromEngine(binding)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun receiverDoesNotArmRefreshWithoutPersistedShelfState() {
|
||||
SystemShelfUpdateReceiver(directExecutor).onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
|
||||
assertTrue(uniqueWorkInfos().isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun receiverRearmsRefreshOnBootWhenShelfStateIsPersisted() {
|
||||
// granted_uris is only written by a committed sync (clear removes it), so
|
||||
// its presence — even as an empty set — marks a prior sync.
|
||||
context.getSharedPreferences("system_shelf_state", 0).edit()
|
||||
.putStringSet("granted_uris", emptySet())
|
||||
.putInt("shelf_schema_version", 1)
|
||||
.commit()
|
||||
SystemShelfUpdateReceiver(directExecutor).onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
|
||||
assertEquals(WorkInfo.State.ENQUEUED, uniqueWorkInfos().single().state)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun receiverRearmsRefreshOnPackageReplacedWhenShelfStateIsPersisted() {
|
||||
context.getSharedPreferences("system_shelf_state", 0).edit()
|
||||
.putStringSet("granted_uris", emptySet())
|
||||
.putInt("shelf_schema_version", 1)
|
||||
.commit()
|
||||
SystemShelfUpdateReceiver(directExecutor).onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))
|
||||
assertEquals(WorkInfo.State.ENQUEUED, uniqueWorkInfos().single().state)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun workerSkipsWithoutLaunchingEngineWhenLiveEngineHoldsLease() {
|
||||
shadowOf(context.packageManager).setSystemFeature(PackageManager.FEATURE_LEANBACK, true)
|
||||
val launched = AtomicBoolean(false)
|
||||
ShelfRefreshWorker.engineLauncherOverride = {
|
||||
launched.set(true)
|
||||
true
|
||||
}
|
||||
val lease = SystemShelfLifecycle.acquire()
|
||||
try {
|
||||
val result = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
|
||||
assertEquals(androidx.work.ListenableWorker.Result.success(), result)
|
||||
assertFalse(launched.get())
|
||||
} finally {
|
||||
SystemShelfLifecycle.invalidate(lease)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun workerSkipsWithoutLaunchingEngineOnNonLeanbackDevices() {
|
||||
val launched = AtomicBoolean(false)
|
||||
ShelfRefreshWorker.engineLauncherOverride = {
|
||||
launched.set(true)
|
||||
true
|
||||
}
|
||||
val result = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
|
||||
assertEquals(androidx.work.ListenableWorker.Result.success(), result)
|
||||
assertFalse(launched.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unattendedWorkerRunsInjectedLauncherAndMapsCompletionToResult() {
|
||||
shadowOf(context.packageManager).setSystemFeature(PackageManager.FEATURE_LEANBACK, true)
|
||||
val launched = AtomicBoolean(false)
|
||||
ShelfRefreshWorker.engineLauncherOverride = {
|
||||
launched.set(true)
|
||||
true
|
||||
}
|
||||
val success = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
|
||||
assertEquals(androidx.work.ListenableWorker.Result.success(), success)
|
||||
assertTrue(launched.get())
|
||||
|
||||
ShelfRefreshWorker.engineLauncherOverride = { false }
|
||||
val failure = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
|
||||
assertEquals(androidx.work.ListenableWorker.Result.retry(), failure)
|
||||
}
|
||||
|
||||
private val directExecutor = Executor { it.run() }
|
||||
|
||||
private fun uniqueWorkInfos(): List<WorkInfo> = WorkManager.getInstance(context).getWorkInfosForUniqueWork(ShelfRefreshScheduler.WORK_NAME).get()
|
||||
|
||||
private fun syncCall(generation: Long) = MethodCall(
|
||||
"sync",
|
||||
mapOf(
|
||||
"schemaVersion" to 3,
|
||||
"ownerId" to "owner-a",
|
||||
"generation" to generation,
|
||||
"items" to emptyList<Map<String, Any?>>()
|
||||
)
|
||||
)
|
||||
|
||||
private fun awaitResult(result: ShelfRecordingResult) {
|
||||
repeat(100) {
|
||||
shadowOf(android.os.Looper.getMainLooper()).idle()
|
||||
if (result.completed.await(10, TimeUnit.MILLISECONDS)) return
|
||||
}
|
||||
assertTrue("Watch Next result never completed", false)
|
||||
}
|
||||
|
||||
private fun pluginBinding(): FlutterPlugin.FlutterPluginBinding {
|
||||
val messenger = Proxy.newProxyInstance(
|
||||
BinaryMessenger::class.java.classLoader,
|
||||
arrayOf(BinaryMessenger::class.java)
|
||||
) { _, _, _ -> null } as BinaryMessenger
|
||||
val constructor = FlutterPlugin.FlutterPluginBinding::class.java.constructors.single()
|
||||
val arguments = constructor.parameterTypes.map { type ->
|
||||
when {
|
||||
Context::class.java.isAssignableFrom(type) -> context
|
||||
BinaryMessenger::class.java.isAssignableFrom(type) -> messenger
|
||||
else -> null
|
||||
}
|
||||
}.toTypedArray()
|
||||
return constructor.newInstance(*arguments) as FlutterPlugin.FlutterPluginBinding
|
||||
}
|
||||
}
|
||||
|
||||
/** Just enough TV provider for an empty-items sync/clear to commit. */
|
||||
private class StubTvProvider : ContentProvider() {
|
||||
private val inserted = mutableListOf<ContentValues>()
|
||||
private var nextRowId = 1L
|
||||
|
||||
override fun onCreate(): Boolean = true
|
||||
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri {
|
||||
inserted += ContentValues(values)
|
||||
return uri.buildUpon().appendPath((nextRowId++).toString()).build()
|
||||
}
|
||||
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
|
||||
val deleted = inserted.size
|
||||
inserted.clear()
|
||||
return deleted
|
||||
}
|
||||
|
||||
override fun query(
|
||||
uri: Uri,
|
||||
projection: Array<out String>?,
|
||||
selection: String?,
|
||||
selectionArgs: Array<out String>?,
|
||||
sortOrder: String?
|
||||
): Cursor = MatrixCursor(
|
||||
projection ?: arrayOf(
|
||||
TvContractCompat.WatchNextPrograms._ID,
|
||||
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID,
|
||||
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_DATA,
|
||||
TvContractCompat.WatchNextPrograms.COLUMN_INTENT_URI,
|
||||
TvContractCompat.PreviewPrograms.COLUMN_POSTER_ART_URI
|
||||
)
|
||||
)
|
||||
|
||||
override fun getType(uri: Uri): String? = null
|
||||
|
||||
override fun update(
|
||||
uri: Uri,
|
||||
values: ContentValues?,
|
||||
selection: String?,
|
||||
selectionArgs: Array<out String>?
|
||||
): Int = 0
|
||||
}
|
||||
|
||||
private class ShelfRecordingResult : MethodChannel.Result {
|
||||
val completed = CountDownLatch(1)
|
||||
var successValue: Any? = null
|
||||
|
||||
override fun success(result: Any?) {
|
||||
successValue = result
|
||||
completed.countDown()
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
|
||||
completed.countDown()
|
||||
}
|
||||
|
||||
override fun notImplemented() {
|
||||
completed.countDown()
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,13 @@ import android.database.MatrixCursor
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor.AutoCloseInputStream
|
||||
import androidx.tvprovider.media.tv.TvContractCompat
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.PeriodicWorkRequestBuilder
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.Worker
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.testing.WorkManagerTestInitHelper
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
@@ -720,6 +727,26 @@ class WatchNextProviderTest {
|
||||
assertFalse(context.cacheDir.resolve("system_shelf_artwork").exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun packageUpdateCancelsLegacyShelfRefreshWork() {
|
||||
WorkManagerTestInitHelper.initializeTestWorkManager(context)
|
||||
val workManager = WorkManager.getInstance(context)
|
||||
workManager.enqueueUniquePeriodicWork(
|
||||
SystemShelfUpdateReceiver.LEGACY_SHELF_REFRESH_WORK,
|
||||
ExistingPeriodicWorkPolicy.KEEP,
|
||||
PeriodicWorkRequestBuilder<LegacyShelfRefreshStandIn>(6, TimeUnit.HOURS).build()
|
||||
).result.get()
|
||||
|
||||
SystemShelfUpdateReceiver(Executor { command -> command.run() })
|
||||
.onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))
|
||||
|
||||
val states = workManager
|
||||
.getWorkInfosForUniqueWork(SystemShelfUpdateReceiver.LEGACY_SHELF_REFRESH_WORK)
|
||||
.get()
|
||||
.map { it.state }
|
||||
assertEquals(listOf(WorkInfo.State.CANCELLED), states)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun providerFailureDeletesNewArtworkAndPreservesCommittedArtwork() {
|
||||
ScriptedHttpServer(
|
||||
@@ -1605,3 +1632,15 @@ private class ManualExecutorService : AbstractExecutorService() {
|
||||
tasks.removeFirst().run()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stands in for the removed ShelfRefreshWorker so the legacy periodic job can
|
||||
* be enqueued. Public because WorkManager's default factory instantiates
|
||||
* workers reflectively and cannot access a package-private class.
|
||||
*/
|
||||
class LegacyShelfRefreshStandIn(
|
||||
context: Context,
|
||||
params: WorkerParameters
|
||||
) : Worker(context, params) {
|
||||
override fun doWork(): Result = Result.success()
|
||||
}
|
||||
|
||||
@@ -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.
Binary file not shown.
@@ -11,7 +11,6 @@ default_platform(:android)
|
||||
platform :android do
|
||||
desc "Build and deploy to Google Play Store"
|
||||
lane :release do
|
||||
# Get version from pubspec.yaml
|
||||
pubspec_path = File.join(PROJECT_ROOT, "pubspec.yaml")
|
||||
pubspec_content = File.read(pubspec_path)
|
||||
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
|
||||
@@ -26,7 +25,6 @@ platform :android do
|
||||
|
||||
git_commit = `git -C #{PROJECT_ROOT_ARG} rev-parse --short HEAD`.strip
|
||||
|
||||
# Build the Flutter app
|
||||
sh("cd #{PROJECT_ROOT_ARG} && flutter build appbundle --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=play-store --dart-define=SENTRY_DIST=play-store --obfuscate --split-debug-info=debug-info/android-aab --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-aab/obfuscation.map.json")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=play-store ./scripts/upload-symbols.sh android-aab")
|
||||
|
||||
@@ -37,7 +35,6 @@ platform :android do
|
||||
aab: "../build/app/outputs/bundle/release/app-release.aab"
|
||||
)
|
||||
|
||||
# Build universal APK for Amazon Appstore (doesn't accept AABs, excludes x86 via env var)
|
||||
sh("cd #{PROJECT_ROOT_ARG} && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=amazon --dart-define=SENTRY_DIST=amazon --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json")
|
||||
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=amazon ./scripts/upload-symbols.sh android-apk")
|
||||
|
||||
|
||||
@@ -54,8 +54,10 @@ kotlin {
|
||||
dependencies {
|
||||
implementation("androidx.annotation:annotation:1.10.0")
|
||||
implementation("androidx.annotation:annotation-experimental:1.6.0")
|
||||
implementation("androidx.media3:media3-exoplayer:1.10.1")
|
||||
implementation("androidx.media3:media3-ui:1.10.1")
|
||||
implementation("androidx.media3:media3-exoplayer:1.11.0")
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ static inline long long nowMs(void) {
|
||||
return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
#include "AssPack.h"
|
||||
#include "ass/ass.h"
|
||||
|
||||
#define LOG_TAG "SubtitleRenderer"
|
||||
@@ -243,35 +244,8 @@ Java_com_edde746_plezy_libass_AssRender_nativeAssRenderDeinit(JNIEnv* env, jclas
|
||||
}
|
||||
}
|
||||
|
||||
// Hard cap on atlas pages (see the packing comment below). 4 pages of a GL-max
|
||||
// texture is far above the worst real frame measured (a 4K-rendered full-screen
|
||||
// typeset letter needs 3); beyond it tiles are dropped and counted in truncated.
|
||||
#define MAX_ATLAS_PAGES 4
|
||||
|
||||
// A tile is a <= atlasMaxW x atlasMaxH sub-rect of an ASS_Image. A single image
|
||||
// can exceed one atlas page only when the render frame is larger than a page
|
||||
// (>4K, or a GPU whose max texture is below the frame) — multi-page can't split
|
||||
// one image across pages (a quad samples one texture), so tiling does, keeping
|
||||
// the never-drop guarantee. (#1436 itself was atlas-AREA overflow, fixed by the
|
||||
// multi-page pack below, not oversized single images.) Tiles are built in list
|
||||
// order (= libass blend/painter order, preserved for emission); the single-page
|
||||
// pack runs height-sorted via a separate key array so emission order is untouched.
|
||||
typedef struct {
|
||||
ASS_Image* img; // source image (for bitmap/stride/color/dst_x/dst_y)
|
||||
int ox, oy; // tile offset within the source bitmap
|
||||
int tw, th; // tile size (<= atlasMaxW x atlasMaxH)
|
||||
int page; // atlas page the tile is packed into; -1 if dropped for capacity
|
||||
int sx, sy; // packed slot within the page; valid when page >= 0
|
||||
} PackTile;
|
||||
|
||||
typedef struct {
|
||||
int th; // tile height (the sort key)
|
||||
int idx; // index into the build-order tiles[] array
|
||||
} TileSortKey;
|
||||
|
||||
static int compareTileKeysByHeightDesc(const void* a, const void* b) {
|
||||
return ((const TileSortKey*)b)->th - ((const TileSortKey*)a)->th;
|
||||
}
|
||||
// Packing/composite policy lives in AssPack.c (pure C, desktop-testable); this
|
||||
// file owns the JNI boundary, buffer plumbing and logging.
|
||||
|
||||
static int imageListHasOutput(ASS_Image* image) {
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
@@ -293,11 +267,12 @@ static int truncationLogCounter = 0;
|
||||
// [5]=hasOutput [6]=pageCount
|
||||
// [7 .. 7+MAX-1] = pageHeights[pageCount]
|
||||
// [7+MAX .. 7+2*MAX-1] = pageQuadCounts[pageCount]
|
||||
#define ASS_HEADER_INTS (7 + 2 * MAX_ATLAS_PAGES)
|
||||
// [7+2*MAX] = mode (ASS_PACK_MODE_ATLAS | ASS_PACK_MODE_COMPOSITE)
|
||||
#define ASS_HEADER_INTS (7 + 2 * ASS_PACK_MAX_PAGES + 1)
|
||||
|
||||
static jint writeAtlasHeader(
|
||||
JNIEnv* env, jintArray headerBuf, int atlasWidth, int quadCount, int changed, int truncated, int requiredPages,
|
||||
int hasOutput, int pageCount, const int* pageHeights, const int* pageQuads) {
|
||||
int hasOutput, int pageCount, const int* pageHeights, const int* pageQuads, int mode) {
|
||||
int hdr[ASS_HEADER_INTS];
|
||||
memset(hdr, 0, sizeof(hdr));
|
||||
hdr[0] = atlasWidth;
|
||||
@@ -307,36 +282,32 @@ static jint writeAtlasHeader(
|
||||
hdr[4] = requiredPages;
|
||||
hdr[5] = hasOutput;
|
||||
hdr[6] = pageCount;
|
||||
for (int i = 0; i < pageCount && i < MAX_ATLAS_PAGES; i++) {
|
||||
for (int i = 0; i < pageCount && i < ASS_PACK_MAX_PAGES; i++) {
|
||||
hdr[7 + i] = pageHeights ? pageHeights[i] : 0;
|
||||
hdr[7 + MAX_ATLAS_PAGES + i] = pageQuads ? pageQuads[i] : 0;
|
||||
hdr[7 + ASS_PACK_MAX_PAGES + i] = pageQuads ? pageQuads[i] : 0;
|
||||
}
|
||||
hdr[7 + 2 * ASS_PACK_MAX_PAGES] = mode;
|
||||
(*env)->SetIntArrayRegion(env, headerBuf, 0, ASS_HEADER_INTS, hdr);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Renders a frame into the provided atlas + vertex direct ByteBuffers.
|
||||
//
|
||||
// - atlasBuf holds one or more vertically-stacked ALPHA_8 *pages*, each atlasMaxW ×
|
||||
// atlasMaxH (row stride atlasMaxW); page p starts at byte offset p*atlasMaxW*atlasMaxH.
|
||||
// The buffer's capacity bounds how many pages this render may fill; AssAtlasFrame
|
||||
// reports pageHeights (rows worth uploading per page) and requiredPages.
|
||||
// - In the common ATLAS mode, atlasBuf holds one or more vertically-stacked ALPHA_8
|
||||
// *pages*, each atlasMaxW × atlasMaxH (row stride atlasMaxW); page p starts at byte
|
||||
// offset p*atlasMaxW*atlasMaxH. The buffer's capacity bounds how many pages this
|
||||
// render may fill; AssAtlasFrame reports pageHeights (rows worth uploading per page)
|
||||
// and requiredPages. UVs are page-local, normalized against atlasMaxW × atlasMaxH.
|
||||
// - In COMPOSITE mode (frames whose tiles can never fit ASS_PACK_MAX_PAGES pages or
|
||||
// the vertex budget) atlasBuf instead starts with one premultiplied RGBA rect of
|
||||
// atlasWidth × pageHeights[0] pixels, drawn as the single emitted quad (UVs 0..1).
|
||||
// - vertexBuf holds a per-quad vertex stream (6 vertices × (2 pos + 2 uv + 4 color)
|
||||
// floats = 48 floats = 192 bytes per quad). Must match BYTES_PER_QUAD/VERTEX in
|
||||
// AssSubtitleAtlasPipeline.kt. UVs are page-local, normalized against atlasMaxW ×
|
||||
// atlasMaxH (the per-page texture dims).
|
||||
// - The common case packs everything into a single height-sorted page (minimizes
|
||||
// packed height, byte-identical to the prior single-page packer). When that
|
||||
// overflows (a 4K full-screen sign can exceed one GL-max texture), the packer
|
||||
// spills into additional pages in list order: page assignment is monotonic in
|
||||
// libass's painter order, so each page's quads are one contiguous run in the
|
||||
// vertex stream and drawing the pages in turn reproduces the blend order.
|
||||
// - Vertices are always emitted in original list order (= libass's painter order).
|
||||
// AssSubtitleAtlasPipeline.kt. Vertices are emitted in libass's painter order.
|
||||
//
|
||||
// Never fails on content size: when the frame needs more pages than the buffer holds
|
||||
// (requiredPages > pageHeights.size) the caller grows the buffer and re-renders; any
|
||||
// genuinely undrawable tiles (past MAX_ATLAS_PAGES / the vertex budget) are dropped
|
||||
// and counted in truncated.
|
||||
// Never drops content for size: when the frame needs more capacity than the buffer
|
||||
// holds (requiredPages > pageHeights.size) the caller grows the buffer and re-renders;
|
||||
// frames too dense for the paged atlas flatten into the RGBA composite (see AssPack.c).
|
||||
//
|
||||
// Returns 0 for missing buffers/handles (the caller maps that to a null frame); 1 when
|
||||
// the header was written. On changed == 0 the header carries (atlasWidth=0, quadCount=0,
|
||||
@@ -359,7 +330,7 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFr
|
||||
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, hasOutput=%d)", (long long)time,
|
||||
tAss - t0, changed, hasOutput);
|
||||
}
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, hasOutput, 1, NULL, NULL);
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, hasOutput, 1, NULL, NULL, ASS_PACK_MODE_ATLAS);
|
||||
}
|
||||
|
||||
if (image == NULL) {
|
||||
@@ -368,7 +339,7 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFr
|
||||
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, no output)", (long long)time,
|
||||
tAss - t0, changed);
|
||||
}
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL, ASS_PACK_MODE_ATLAS);
|
||||
}
|
||||
|
||||
uint8_t* atlasPixels = (uint8_t*)(*env)->GetDirectBufferAddress(env, atlasBuf);
|
||||
@@ -382,253 +353,45 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFr
|
||||
(long long)atlasCap);
|
||||
return 0;
|
||||
}
|
||||
// 48 floats per quad × 4 bytes = 192 bytes/quad
|
||||
const int maxQuads = (int)(vertexCap / 192);
|
||||
const size_t pageBytes = (size_t)atlasMaxW * atlasMaxH;
|
||||
int providedPages = (int)(atlasCap / (jlong)pageBytes);
|
||||
if (providedPages < 1) return 0; // one page is guaranteed above; keep the page math safe
|
||||
if (providedPages > MAX_ATLAS_PAGES) providedPages = MAX_ATLAS_PAGES;
|
||||
|
||||
// Split every image into <= atlasMaxW x atlasMaxH tiles, then pack the tiles.
|
||||
// tiles[] stays in list order (= blend/painter order for emission); keys[] is
|
||||
// sorted by height for the single-page pack so it produces tight rows.
|
||||
int total = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) {
|
||||
int cols = (img->w + atlasMaxW - 1) / atlasMaxW;
|
||||
int rows = (img->h + atlasMaxH - 1) / atlasMaxH;
|
||||
total += cols * rows;
|
||||
}
|
||||
}
|
||||
if (total == 0) {
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
PackTile* tiles = (PackTile*)malloc(sizeof(PackTile) * (size_t)total);
|
||||
TileSortKey* keys = (TileSortKey*)malloc(sizeof(TileSortKey) * (size_t)total);
|
||||
if (!tiles || !keys) {
|
||||
free(tiles);
|
||||
free(keys);
|
||||
AssPackResult pack;
|
||||
if (!ass_pack_frame(image, atlasPixels, (size_t)atlasCap, atlasMaxW, atlasMaxH, vertices, (size_t)vertexCap, &pack)) {
|
||||
return 0;
|
||||
}
|
||||
int n = 0;
|
||||
long long srcPixels = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
srcPixels += (long long)img->w * img->h;
|
||||
for (int oy = 0; oy < img->h; oy += atlasMaxH) {
|
||||
int th = img->h - oy;
|
||||
if (th > atlasMaxH) th = atlasMaxH;
|
||||
for (int ox = 0; ox < img->w; ox += atlasMaxW) {
|
||||
int tw = img->w - ox;
|
||||
if (tw > atlasMaxW) tw = atlasMaxW;
|
||||
tiles[n] = (PackTile){.img = img, .ox = ox, .oy = oy, .tw = tw, .th = th, .page = -1, .sx = -1, .sy = -1};
|
||||
keys[n] = (TileSortKey){.th = th, .idx = n};
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
int pageHeights[MAX_ATLAS_PAGES] = {0};
|
||||
int pageQuads[MAX_ATLAS_PAGES] = {0};
|
||||
int pageCount = 1;
|
||||
int requiredPages = 1;
|
||||
int truncated = 0;
|
||||
|
||||
// Pass 1a: height-sorted single page — the common case, minimal packed height
|
||||
// (byte-identical to the prior single-page packer when the frame fits one page).
|
||||
qsort(keys, (size_t)n, sizeof(TileSortKey), compareTileKeysByHeightDesc);
|
||||
int cursorX = 0, cursorY = 0, rowH = 0, packedH = 0, accepted = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[keys[i].idx];
|
||||
if (accepted >= maxQuads) break;
|
||||
int cx = cursorX, cy = cursorY, rh = rowH;
|
||||
if (cx + t->tw > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + t->th > atlasMaxH) continue; // doesn't fit a single page
|
||||
t->page = 0;
|
||||
t->sx = cx;
|
||||
t->sy = cy;
|
||||
cursorX = cx + t->tw;
|
||||
cursorY = cy;
|
||||
rowH = (t->th > rh) ? t->th : rh;
|
||||
if (cy + t->th > packedH) packedH = cy + t->th;
|
||||
accepted++;
|
||||
}
|
||||
|
||||
if (accepted == n) {
|
||||
pageHeights[0] = packedH;
|
||||
pageQuads[0] = accepted;
|
||||
} else {
|
||||
// Pass 1b: the frame overflows one page. Re-pack in list order, starting a new
|
||||
// page whenever a tile won't fit the current one. List order keeps the page
|
||||
// index monotonic in painter order, so each page's quads stay one contiguous run.
|
||||
for (int i = 0; i < n; i++) {
|
||||
tiles[i].page = -1;
|
||||
tiles[i].sx = -1;
|
||||
tiles[i].sy = -1;
|
||||
}
|
||||
int page = 0, cx = 0, cy = 0, rh = 0, placed = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[i];
|
||||
if (cx + t->tw > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + t->th > atlasMaxH) {
|
||||
page++;
|
||||
cx = 0;
|
||||
cy = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (page + 1 > requiredPages) requiredPages = page + 1;
|
||||
if (page < providedPages && placed < maxQuads) {
|
||||
t->page = page;
|
||||
t->sx = cx;
|
||||
t->sy = cy;
|
||||
if (cy + t->th > pageHeights[page]) pageHeights[page] = cy + t->th;
|
||||
pageQuads[page]++;
|
||||
placed++;
|
||||
}
|
||||
cx += t->tw;
|
||||
rh = (t->th > rh) ? t->th : rh;
|
||||
}
|
||||
pageCount = (requiredPages < providedPages) ? requiredPages : providedPages;
|
||||
accepted = placed;
|
||||
truncated = n - placed;
|
||||
}
|
||||
|
||||
// Warn only for genuinely-unrecoverable loss. A frame that needs more pages than
|
||||
// the buffer currently holds, yet fits within MAX_ATLAS_PAGES and the vertex
|
||||
// budget, is recoverable: the caller grows the buffer and re-renders, so the
|
||||
// first (discarded) render's truncated > 0 is a false alarm, not data loss. Tiles
|
||||
// are only truly lost past the page cap or the vertex budget.
|
||||
const int recoverableGrow = requiredPages <= MAX_ATLAS_PAGES && n <= maxQuads;
|
||||
if (truncated > 0 && !recoverableGrow && (truncationLogCounter++ & 63) == 0) {
|
||||
// Warn only for genuinely-unrecoverable loss. A frame that needs more capacity than
|
||||
// the buffer currently holds is recoverable: the caller grows the buffer and
|
||||
// re-renders, so the first (discarded) render's truncated > 0 is a false alarm, not
|
||||
// data loss. With the composite fallback, unrecoverable truncation should be
|
||||
// unreachable for real content.
|
||||
const int maxQuads = (int)(vertexCap / 192);
|
||||
const int recoverableGrow =
|
||||
pack.requiredPages <= ASS_PACK_MAX_PAGES && (pack.mode == ASS_PACK_MODE_COMPOSITE || pack.totalTiles <= maxQuads);
|
||||
if (pack.truncated > 0 && !recoverableGrow && (truncationLogCounter++ & 63) == 0) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d tiles dropped (atlas %dx%d, need %d pages have %d)",
|
||||
truncated, n, atlasMaxW, atlasMaxH, requiredPages, providedPages);
|
||||
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d tiles dropped (atlas %dx%d, need %d pages have %lld)",
|
||||
pack.truncated, pack.totalTiles, atlasMaxW, atlasMaxH, pack.requiredPages,
|
||||
(long long)(atlasCap / ((jlong)atlasMaxW * atlasMaxH)));
|
||||
}
|
||||
if (accepted == 0) {
|
||||
free(tiles);
|
||||
free(keys);
|
||||
return writeAtlasHeader(env, headerBuf, 0, 0, changed, truncated, requiredPages, 1, 1, NULL, NULL);
|
||||
}
|
||||
|
||||
// Clear only the packed rows of each written page.
|
||||
for (int p = 0; p < pageCount; p++) {
|
||||
memset(atlasPixels + (size_t)p * pageBytes, 0, (size_t)atlasMaxW * pageHeights[p]);
|
||||
}
|
||||
|
||||
// Emit tiles in list order (= libass's painter/blend order), copying each placed
|
||||
// tile into its page slot and emitting its quad. Monotonic page assignment makes
|
||||
// each page's quads a contiguous run, matching pageQuads[] for the per-page draw.
|
||||
int qi = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[i];
|
||||
if (t->page < 0) continue;
|
||||
ASS_Image* img = t->img;
|
||||
const int px = t->sx;
|
||||
const int py = t->sy;
|
||||
uint8_t* pageBase = atlasPixels + (size_t)t->page * pageBytes;
|
||||
|
||||
for (int y = 0; y < t->th; y++) {
|
||||
uint8_t* dst = pageBase + (size_t)(py + y) * atlasMaxW + px;
|
||||
const uint8_t* src = img->bitmap + (size_t)(t->oy + y) * img->stride + t->ox;
|
||||
memcpy(dst, src, (size_t)t->tw);
|
||||
}
|
||||
|
||||
const float x0 = (float)(img->dst_x + t->ox);
|
||||
const float y0 = (float)(img->dst_y + t->oy);
|
||||
const float x1 = x0 + (float)t->tw;
|
||||
const float y1 = y0 + (float)t->th;
|
||||
const float u0 = (float)px / (float)atlasMaxW;
|
||||
const float v0 = (float)py / (float)atlasMaxH;
|
||||
const float u1 = (float)(px + t->tw) / (float)atlasMaxW;
|
||||
const float v1 = (float)(py + t->th) / (float)atlasMaxH;
|
||||
const unsigned int c = img->color;
|
||||
const float r = (float)((c >> 24) & 0xFFu) / 255.0f;
|
||||
const float g = (float)((c >> 16) & 0xFFu) / 255.0f;
|
||||
const float b = (float)((c >> 8) & 0xFFu) / 255.0f;
|
||||
const float a = (float)(0xFFu - (c & 0xFFu)) / 255.0f;
|
||||
|
||||
float* vx = vertices + (size_t)qi * 48;
|
||||
// 8 floats per vertex: x, y, u, v, r, g, b, a.
|
||||
// Triangle 1: (x0,y0) (x1,y0) (x0,y1)
|
||||
vx[0] = x0;
|
||||
vx[1] = y0;
|
||||
vx[2] = u0;
|
||||
vx[3] = v0;
|
||||
vx[4] = r;
|
||||
vx[5] = g;
|
||||
vx[6] = b;
|
||||
vx[7] = a;
|
||||
vx[8] = x1;
|
||||
vx[9] = y0;
|
||||
vx[10] = u1;
|
||||
vx[11] = v0;
|
||||
vx[12] = r;
|
||||
vx[13] = g;
|
||||
vx[14] = b;
|
||||
vx[15] = a;
|
||||
vx[16] = x0;
|
||||
vx[17] = y1;
|
||||
vx[18] = u0;
|
||||
vx[19] = v1;
|
||||
vx[20] = r;
|
||||
vx[21] = g;
|
||||
vx[22] = b;
|
||||
vx[23] = a;
|
||||
// Triangle 2: (x1,y0) (x1,y1) (x0,y1)
|
||||
vx[24] = x1;
|
||||
vx[25] = y0;
|
||||
vx[26] = u1;
|
||||
vx[27] = v0;
|
||||
vx[28] = r;
|
||||
vx[29] = g;
|
||||
vx[30] = b;
|
||||
vx[31] = a;
|
||||
vx[32] = x1;
|
||||
vx[33] = y1;
|
||||
vx[34] = u1;
|
||||
vx[35] = v1;
|
||||
vx[36] = r;
|
||||
vx[37] = g;
|
||||
vx[38] = b;
|
||||
vx[39] = a;
|
||||
vx[40] = x0;
|
||||
vx[41] = y1;
|
||||
vx[42] = u0;
|
||||
vx[43] = v1;
|
||||
vx[44] = r;
|
||||
vx[45] = g;
|
||||
vx[46] = b;
|
||||
vx[47] = a;
|
||||
|
||||
qi++;
|
||||
}
|
||||
|
||||
free(tiles);
|
||||
free(keys);
|
||||
|
||||
// Slow-render breakdown: separates libass's own cost (rasterize/blur/shape)
|
||||
// from this function's packing + memcpy, so device logs attribute the time.
|
||||
// from this function's packing/compositing, so device logs attribute the time.
|
||||
const long long tEnd = nowMs();
|
||||
if (tEnd - t0 > 40) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN, LOG_TAG,
|
||||
"slow render t=%lldms: total=%lldms ass=%lldms pack+copy=%lldms images=%d srcPx=%lldk "
|
||||
"atlas=%dx%d pages=%d quads=%d",
|
||||
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, atlasMaxH, pageCount, qi);
|
||||
"atlas=%dx%d pages=%d quads=%d mode=%d",
|
||||
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, pack.totalTiles, pack.srcPixels / 1000, atlasMaxW,
|
||||
atlasMaxH, pack.pageCount, pack.quadCount, pack.mode);
|
||||
}
|
||||
|
||||
// atlasWidth is the full row stride (GLES2 can't upload with stride ≠ width);
|
||||
// pageHeights/pageQuadCounts describe the per-page upload + draw ranges.
|
||||
// ATLAS: atlasWidth is the full row stride (GLES2 can't upload with stride ≠ width)
|
||||
// and pageHeights/pageQuadCounts describe the per-page upload + draw ranges.
|
||||
// COMPOSITE: atlasWidth × pageHeights[0] are the RGBA rect dims for the one quad.
|
||||
return writeAtlasHeader(
|
||||
env, headerBuf, atlasMaxW, qi, changed, truncated, requiredPages, 1, pageCount, pageHeights, pageQuads);
|
||||
env, headerBuf, pack.atlasWidth, pack.quadCount, changed, pack.truncated, pack.requiredPages,
|
||||
pack.totalTiles > 0 ? 1 : 0, pack.pageCount, pack.pageHeights, pack.pageQuads, pack.mode);
|
||||
}
|
||||
|
||||
// --- AssFrameTimestamps (EGL_ANDROID_get_frame_timestamps) ---
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
#include "AssPack.h"
|
||||
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
// A tile is a <= atlasMaxW x atlasMaxH sub-rect of an ASS_Image. A single image
|
||||
// can exceed one atlas page only when the render frame is larger than a page
|
||||
// (>4K, or a GPU whose max texture is below the frame) — multi-page can't split
|
||||
// one image across pages (a quad samples one texture), so tiling does, keeping
|
||||
// the never-drop guarantee. (#1436 itself was atlas-AREA overflow, fixed by the
|
||||
// multi-page pack below, not oversized single images.) Tiles are built in list
|
||||
// order (= libass blend/painter order, preserved for emission); the single-page
|
||||
// pack runs height-sorted via a separate key array so emission order is untouched.
|
||||
typedef struct {
|
||||
ASS_Image* img; // source image (for bitmap/stride/color/dst_x/dst_y)
|
||||
int ox, oy; // tile offset within the source bitmap
|
||||
int tw, th; // tile size (<= atlasMaxW x atlasMaxH)
|
||||
int page; // atlas page the tile is packed into; -1 if dropped for capacity
|
||||
int sx, sy; // packed slot within the page; valid when page >= 0
|
||||
} PackTile;
|
||||
|
||||
typedef struct {
|
||||
int th; // tile height (the sort key)
|
||||
int idx; // index into the build-order tiles[] array
|
||||
} TileSortKey;
|
||||
|
||||
static int compareTileKeysByHeightDesc(const void* a, const void* b) {
|
||||
return ((const TileSortKey*)b)->th - ((const TileSortKey*)a)->th;
|
||||
}
|
||||
|
||||
// 8 floats per vertex (x, y, u, v, r, g, b, a) x 6 vertices; layout must match
|
||||
// BYTES_PER_QUAD/VERTEX in AssSubtitleAtlasPipeline.kt.
|
||||
static void emitQuad(
|
||||
float* vx, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float r, float g,
|
||||
float b, float a) {
|
||||
const float pos[6][2] = {{x0, y0}, {x1, y0}, {x0, y1}, {x1, y0}, {x1, y1}, {x0, y1}};
|
||||
const float uv[6][2] = {{u0, v0}, {u1, v0}, {u0, v1}, {u1, v0}, {u1, v1}, {u0, v1}};
|
||||
for (int i = 0; i < 6; i++) {
|
||||
*vx++ = pos[i][0];
|
||||
*vx++ = pos[i][1];
|
||||
*vx++ = uv[i][0];
|
||||
*vx++ = uv[i][1];
|
||||
*vx++ = r;
|
||||
*vx++ = g;
|
||||
*vx++ = b;
|
||||
*vx++ = a;
|
||||
}
|
||||
}
|
||||
|
||||
// Flattens the whole image list into one premultiplied RGBA rect (the union
|
||||
// bounding box) at the start of `atlasPixels`, emitted as a single quad. The
|
||||
// blend is libass painter-order src-over, the same math the GL path applies to
|
||||
// alpha-atlas quads, so output is visually identical — memory just becomes
|
||||
// O(union area <= frame area) instead of O(sum of image areas). Used for
|
||||
// frames whose summed image area cannot fit ASS_PACK_MAX_PAGES alpha pages
|
||||
// (#1868: ~150 overlapping paint-strokes put ~5 pages of tiles at 1080p and
|
||||
// ~19 at 4K behind a 4-page cap, silently dropping the painter-order tail —
|
||||
// the sign's text).
|
||||
static void compositeFrame(
|
||||
ASS_Image* image, uint8_t* atlasPixels, size_t atlasCap, size_t pageBytes, float* vertices, size_t vertexCap,
|
||||
AssPackResult* out) {
|
||||
int ux0 = INT_MAX, uy0 = INT_MAX, ux1 = INT_MIN, uy1 = INT_MIN;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
if (img->dst_x < ux0) ux0 = img->dst_x;
|
||||
if (img->dst_y < uy0) uy0 = img->dst_y;
|
||||
if (img->dst_x + img->w > ux1) ux1 = img->dst_x + img->w;
|
||||
if (img->dst_y + img->h > uy1) uy1 = img->dst_y + img->h;
|
||||
}
|
||||
const int uw = ux1 - ux0;
|
||||
const int uh = uy1 - uy0;
|
||||
const size_t rgbaBytes = (size_t)uw * uh * 4;
|
||||
|
||||
out->mode = ASS_PACK_MODE_COMPOSITE;
|
||||
out->requiredPages = (int)((rgbaBytes + pageBytes - 1) / pageBytes);
|
||||
out->pageCount = 1;
|
||||
if (rgbaBytes > atlasCap || vertexCap < 192) {
|
||||
// Buffers too small for the flattened rect: report the needed capacity and
|
||||
// write nothing — the caller grows and re-renders (same contract as the
|
||||
// multi-page atlas grow). truncated flags the frame as not presentable.
|
||||
out->truncated = out->totalTiles;
|
||||
return;
|
||||
}
|
||||
|
||||
memset(atlasPixels, 0, rgbaBytes);
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
const unsigned int c = img->color;
|
||||
const unsigned cr = (c >> 24) & 0xFFu;
|
||||
const unsigned cg = (c >> 16) & 0xFFu;
|
||||
const unsigned cb = (c >> 8) & 0xFFu;
|
||||
const unsigned ca = 0xFFu - (c & 0xFFu);
|
||||
if (ca == 0) continue;
|
||||
for (int y = 0; y < img->h; y++) {
|
||||
const uint8_t* src = img->bitmap + (size_t)y * img->stride;
|
||||
uint8_t* dst = atlasPixels + (((size_t)(img->dst_y - uy0 + y) * uw) + (size_t)(img->dst_x - ux0)) * 4;
|
||||
for (int x = 0; x < img->w; x++, dst += 4) {
|
||||
const unsigned a = (src[x] * ca + 127u) / 255u;
|
||||
if (a == 0) continue;
|
||||
const unsigned inv = 255u - a;
|
||||
dst[0] = (uint8_t)((cr * a + dst[0] * inv + 127u) / 255u);
|
||||
dst[1] = (uint8_t)((cg * a + dst[1] * inv + 127u) / 255u);
|
||||
dst[2] = (uint8_t)((cb * a + dst[2] * inv + 127u) / 255u);
|
||||
dst[3] = (uint8_t)((255u * a + dst[3] * inv + 127u) / 255u);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out->atlasWidth = uw;
|
||||
out->pageHeights[0] = uh;
|
||||
out->pageQuads[0] = 1;
|
||||
out->quadCount = 1;
|
||||
out->truncated = 0;
|
||||
emitQuad(
|
||||
vertices, (float)ux0, (float)uy0, (float)(ux0 + uw), (float)(uy0 + uh), 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
|
||||
1.0f);
|
||||
}
|
||||
|
||||
int ass_pack_frame(
|
||||
ASS_Image* image, uint8_t* atlasPixels, size_t atlasCap, int atlasMaxW, int atlasMaxH, float* vertices,
|
||||
size_t vertexCap, AssPackResult* out) {
|
||||
memset(out, 0, sizeof(*out));
|
||||
out->mode = ASS_PACK_MODE_ATLAS;
|
||||
out->requiredPages = 1;
|
||||
out->pageCount = 1;
|
||||
|
||||
// 48 floats per quad x 4 bytes = 192 bytes/quad
|
||||
const int maxQuads = (int)(vertexCap / 192);
|
||||
const size_t pageBytes = (size_t)atlasMaxW * atlasMaxH;
|
||||
int providedPages = (int)(atlasCap / pageBytes);
|
||||
if (providedPages > ASS_PACK_MAX_PAGES) providedPages = ASS_PACK_MAX_PAGES;
|
||||
|
||||
// Split every image into <= atlasMaxW x atlasMaxH tiles, then pack the tiles.
|
||||
// tiles[] stays in list order (= blend/painter order for emission); keys[] is
|
||||
// sorted by height for the single-page pack so it produces tight rows.
|
||||
int total = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w > 0 && img->h > 0) {
|
||||
int cols = (img->w + atlasMaxW - 1) / atlasMaxW;
|
||||
int rows = (img->h + atlasMaxH - 1) / atlasMaxH;
|
||||
total += cols * rows;
|
||||
}
|
||||
}
|
||||
out->totalTiles = total;
|
||||
if (total == 0) return 1;
|
||||
|
||||
PackTile* tiles = (PackTile*)malloc(sizeof(PackTile) * (size_t)total);
|
||||
TileSortKey* keys = (TileSortKey*)malloc(sizeof(TileSortKey) * (size_t)total);
|
||||
if (!tiles || !keys) {
|
||||
free(tiles);
|
||||
free(keys);
|
||||
return 0;
|
||||
}
|
||||
int n = 0;
|
||||
for (ASS_Image* img = image; img != NULL; img = img->next) {
|
||||
if (img->w <= 0 || img->h <= 0) continue;
|
||||
out->srcPixels += (long long)img->w * img->h;
|
||||
for (int oy = 0; oy < img->h; oy += atlasMaxH) {
|
||||
int th = img->h - oy;
|
||||
if (th > atlasMaxH) th = atlasMaxH;
|
||||
for (int ox = 0; ox < img->w; ox += atlasMaxW) {
|
||||
int tw = img->w - ox;
|
||||
if (tw > atlasMaxW) tw = atlasMaxW;
|
||||
tiles[n] = (PackTile){.img = img, .ox = ox, .oy = oy, .tw = tw, .th = th, .page = -1, .sx = -1, .sy = -1};
|
||||
keys[n] = (TileSortKey){.th = th, .idx = n};
|
||||
n++;
|
||||
}
|
||||
}
|
||||
}
|
||||
int truncated = 0;
|
||||
|
||||
// Pass 1a: height-sorted single page — the common case, minimal packed height
|
||||
// (byte-identical to the prior single-page packer when the frame fits one page).
|
||||
qsort(keys, (size_t)n, sizeof(TileSortKey), compareTileKeysByHeightDesc);
|
||||
int cursorX = 0, cursorY = 0, rowH = 0, packedH = 0, accepted = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[keys[i].idx];
|
||||
if (accepted >= maxQuads) break;
|
||||
int cx = cursorX, cy = cursorY, rh = rowH;
|
||||
if (cx + t->tw > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + t->th > atlasMaxH) continue; // doesn't fit a single page
|
||||
t->page = 0;
|
||||
t->sx = cx;
|
||||
t->sy = cy;
|
||||
cursorX = cx + t->tw;
|
||||
cursorY = cy;
|
||||
rowH = (t->th > rh) ? t->th : rh;
|
||||
if (cy + t->th > packedH) packedH = cy + t->th;
|
||||
accepted++;
|
||||
}
|
||||
|
||||
if (accepted == n) {
|
||||
out->pageHeights[0] = packedH;
|
||||
out->pageQuads[0] = accepted;
|
||||
} else {
|
||||
// Pass 1b: the frame overflows one page. Re-pack in list order, starting a new
|
||||
// page whenever a tile won't fit the current one. List order keeps the page
|
||||
// index monotonic in painter order, so each page's quads stay one contiguous run.
|
||||
for (int i = 0; i < n; i++) {
|
||||
tiles[i].page = -1;
|
||||
tiles[i].sx = -1;
|
||||
tiles[i].sy = -1;
|
||||
}
|
||||
int requiredPages = 1;
|
||||
int page = 0, cx = 0, cy = 0, rh = 0, placed = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[i];
|
||||
if (cx + t->tw > atlasMaxW) {
|
||||
cy += rh;
|
||||
cx = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (cy + t->th > atlasMaxH) {
|
||||
page++;
|
||||
cx = 0;
|
||||
cy = 0;
|
||||
rh = 0;
|
||||
}
|
||||
if (page + 1 > requiredPages) requiredPages = page + 1;
|
||||
if (page < providedPages && placed < maxQuads) {
|
||||
t->page = page;
|
||||
t->sx = cx;
|
||||
t->sy = cy;
|
||||
if (cy + t->th > out->pageHeights[page]) out->pageHeights[page] = cy + t->th;
|
||||
out->pageQuads[page]++;
|
||||
placed++;
|
||||
}
|
||||
cx += t->tw;
|
||||
rh = (t->th > rh) ? t->th : rh;
|
||||
}
|
||||
if (requiredPages > ASS_PACK_MAX_PAGES || n > maxQuads) {
|
||||
// The frame can never fit the paged alpha atlas: its tiles exceed the page
|
||||
// cap or the vertex budget outright. Flatten instead of dropping the
|
||||
// painter-order tail (#1868).
|
||||
free(tiles);
|
||||
free(keys);
|
||||
memset(out->pageHeights, 0, sizeof(out->pageHeights));
|
||||
memset(out->pageQuads, 0, sizeof(out->pageQuads));
|
||||
compositeFrame(image, atlasPixels, atlasCap, pageBytes, vertices, vertexCap, out);
|
||||
return 1;
|
||||
}
|
||||
out->requiredPages = requiredPages;
|
||||
out->pageCount = (requiredPages < providedPages) ? requiredPages : providedPages;
|
||||
accepted = placed;
|
||||
truncated = n - placed;
|
||||
}
|
||||
|
||||
out->truncated = truncated;
|
||||
if (accepted == 0) {
|
||||
free(tiles);
|
||||
free(keys);
|
||||
memset(out->pageHeights, 0, sizeof(out->pageHeights));
|
||||
memset(out->pageQuads, 0, sizeof(out->pageQuads));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Clear only the packed rows of each written page.
|
||||
for (int p = 0; p < out->pageCount; p++) {
|
||||
memset(atlasPixels + (size_t)p * pageBytes, 0, (size_t)atlasMaxW * out->pageHeights[p]);
|
||||
}
|
||||
|
||||
// Emit tiles in list order (= libass's painter/blend order), copying each placed
|
||||
// tile into its page slot and emitting its quad. Monotonic page assignment makes
|
||||
// each page's quads a contiguous run, matching pageQuads[] for the per-page draw.
|
||||
int qi = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
PackTile* t = &tiles[i];
|
||||
if (t->page < 0) continue;
|
||||
ASS_Image* img = t->img;
|
||||
const int px = t->sx;
|
||||
const int py = t->sy;
|
||||
uint8_t* pageBase = atlasPixels + (size_t)t->page * pageBytes;
|
||||
|
||||
for (int y = 0; y < t->th; y++) {
|
||||
uint8_t* dst = pageBase + (size_t)(py + y) * atlasMaxW + px;
|
||||
const uint8_t* src = img->bitmap + (size_t)(t->oy + y) * img->stride + t->ox;
|
||||
memcpy(dst, src, (size_t)t->tw);
|
||||
}
|
||||
|
||||
const unsigned int c = img->color;
|
||||
emitQuad(
|
||||
vertices + (size_t)qi * 48, (float)(img->dst_x + t->ox), (float)(img->dst_y + t->oy),
|
||||
(float)(img->dst_x + t->ox + t->tw), (float)(img->dst_y + t->oy + t->th), (float)px / (float)atlasMaxW,
|
||||
(float)py / (float)atlasMaxH, (float)(px + t->tw) / (float)atlasMaxW, (float)(py + t->th) / (float)atlasMaxH,
|
||||
(float)((c >> 24) & 0xFFu) / 255.0f, (float)((c >> 16) & 0xFFu) / 255.0f, (float)((c >> 8) & 0xFFu) / 255.0f,
|
||||
(float)(0xFFu - (c & 0xFFu)) / 255.0f);
|
||||
qi++;
|
||||
}
|
||||
|
||||
free(tiles);
|
||||
free(keys);
|
||||
out->quadCount = qi;
|
||||
out->atlasWidth = atlasMaxW;
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Pure-C frame packer behind the JNI atlas render entry point (AssKt.c).
|
||||
// Kept free of JNI/Android includes so desktop test harnesses can compile the
|
||||
// exact shipped packing/composite logic against a host libass build.
|
||||
#ifndef PLEZY_ASS_PACK_H
|
||||
#define PLEZY_ASS_PACK_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "ass/ass.h"
|
||||
|
||||
// Hard cap on atlas pages. 4 pages of a GL-max texture covers the worst real
|
||||
// frame measured for ordinary typesetting (a 4K-rendered full-screen letter
|
||||
// needs 3); denser frames (#1868: ~1500 overlapping paint-stroke images whose
|
||||
// summed area is ~19 pages at 4K) fall back to the RGBA composite below instead
|
||||
// of dropping tiles. Must match AssAtlasPipelineConfig.MAX_ATLAS_PAGES.
|
||||
#define ASS_PACK_MAX_PAGES 4
|
||||
|
||||
// Result modes. ATLAS: one or more ALPHA_8 pages plus per-quad vertices, the
|
||||
// common fast path. COMPOSITE: the frame's images were flattened CPU-side into
|
||||
// a single premultiplied RGBA rect (the union bounding box) drawn as one quad —
|
||||
// memory is bounded by frame area instead of the sum of per-image areas.
|
||||
#define ASS_PACK_MODE_ATLAS 0
|
||||
#define ASS_PACK_MODE_COMPOSITE 1
|
||||
|
||||
typedef struct {
|
||||
int mode; // ASS_PACK_MODE_*
|
||||
// ATLAS: row stride of every page. COMPOSITE: width of the RGBA rect.
|
||||
int atlasWidth;
|
||||
int quadCount;
|
||||
// Tiles dropped for capacity (frame incomplete). Composite output never
|
||||
// drops content; it reports truncated == totalTiles only in the
|
||||
// nothing-written grow request state (quadCount == 0).
|
||||
int truncated;
|
||||
// Pages of caller buffer capacity this frame needs to render completely.
|
||||
// When it exceeds the provided capacity the caller grows and re-renders.
|
||||
int requiredPages;
|
||||
int pageCount;
|
||||
int totalTiles; // tiles the frame splits into (caller-side logging)
|
||||
long long srcPixels; // summed source image area (caller-side logging)
|
||||
// ATLAS: packed rows per page / quads per page (contiguous vertex runs).
|
||||
// COMPOSITE: pageHeights[0] = RGBA rect height, pageQuads[0] = 1.
|
||||
int pageHeights[ASS_PACK_MAX_PAGES];
|
||||
int pageQuads[ASS_PACK_MAX_PAGES];
|
||||
} AssPackResult;
|
||||
|
||||
// Packs libass's image list for `atlasPixels`/`vertices` (layout documented at
|
||||
// the JNI entry point in AssKt.c). Never drops content for size: frames that
|
||||
// cannot fit ASS_PACK_MAX_PAGES alpha pages (or the vertex budget) flatten into
|
||||
// an RGBA composite; when the provided buffers are too small for either
|
||||
// representation, requiredPages tells the caller how much to grow before
|
||||
// re-rendering, and nothing is written. Returns 0 only on allocation failure.
|
||||
int ass_pack_frame(
|
||||
ASS_Image* image, uint8_t* atlasPixels, size_t atlasCap, int atlasMaxW, int atlasMaxH, float* vertices,
|
||||
size_t vertexCap, AssPackResult* out);
|
||||
|
||||
#endif // PLEZY_ASS_PACK_H
|
||||
@@ -44,7 +44,7 @@ set_target_properties(ass PROPERTIES
|
||||
IMPORTED_LOCATION "${LIBASS_ARCHIVE}")
|
||||
target_include_directories(ass INTERFACE "${LIBASS_ROOT}/include")
|
||||
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c SurfaceTxProbe.c)
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c AssPack.c SurfaceTxProbe.c)
|
||||
add_dependencies(${CMAKE_PROJECT_NAME} libass_prebuilt_${LIBASS_ABI_TARGET})
|
||||
# HarfBuzz brings C++; link the shared STL that the app already packages.
|
||||
# (SurfaceTxProbe resolves its libandroid/libsync entry points via dlsym, so no extra link.)
|
||||
|
||||
@@ -4,33 +4,44 @@ package com.edde746.plezy.libass
|
||||
* Result of a packed-atlas render. The atlas pixel data is stored in the direct ByteBuffer
|
||||
* that was passed into [AssRender.renderFrameAtlas]; the vertex stream is in the other.
|
||||
*
|
||||
* The atlas may span more than one *page* — a heavy full-screen sign can produce more
|
||||
* sub-pixels than a single GL-max texture holds. Pages are vertically stacked in the
|
||||
* atlas ByteBuffer (page `p` at byte offset `p * atlasWidth * atlasMaxHeight`), each its
|
||||
* own texture, and are drawn in turn. Quads are emitted in libass painter order and page
|
||||
* assignment is monotonic in that order, so each page's quads form one contiguous run in
|
||||
* the vertex stream ([pageQuadCounts]); the runner uploads page `p`, then draws its run.
|
||||
* In the common [MODE_ATLAS] the atlas may span more than one ALPHA_8 *page* — a heavy
|
||||
* full-screen sign can produce more sub-pixels than a single GL-max texture holds. Pages
|
||||
* are vertically stacked in the atlas ByteBuffer (page `p` at byte offset
|
||||
* `p * atlasWidth * atlasMaxHeight`), each its own texture, and are drawn in turn. Quads
|
||||
* are emitted in libass painter order and page assignment is monotonic in that order, so
|
||||
* each page's quads form one contiguous run in the vertex stream ([pageQuadCounts]); the
|
||||
* runner uploads page `p`, then draws its run.
|
||||
*
|
||||
* In [MODE_COMPOSITE] the frame was too dense for the paged atlas (its summed image area
|
||||
* exceeds every page: overlapping paint-stroke signs, #1868) and the native side flattened
|
||||
* it into one premultiplied RGBA rect of [atlasWidth] × `pageHeights[0]` pixels at the
|
||||
* start of the atlas ByteBuffer, drawn as the single emitted quad with UVs 0..1.
|
||||
*
|
||||
* Built in Kotlin by [AssRender.renderFrameAtlas] from the int[] header the native
|
||||
* renderer fills (see `writeAtlasHeader` in AssKt.c) — never constructed from JNI, so
|
||||
* the minifier may obfuscate it freely without breaking the native boundary.
|
||||
*
|
||||
* @param atlasWidth atlas row stride in pixels (= the allocated width; same for every
|
||||
* page; 0 when [changed] == 0)
|
||||
* page; 0 when [changed] == 0) — or the RGBA rect width in
|
||||
* [MODE_COMPOSITE]
|
||||
* @param pageHeights packed height (rows worth uploading) of each page; `size` = page count
|
||||
* @param pageQuadCounts quads on each page, contiguous in the vertex stream in this order;
|
||||
* `size` = page count, `sum` = [quadCount]
|
||||
* @param quadCount total quads; the vertex buffer holds [quadCount] * 6 vertices
|
||||
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
|
||||
* @param truncated images dropped because the frame needed more than [requiredPages]
|
||||
* pages of capacity or exceeded the vertex budget; the frame is
|
||||
* incomplete but never stale (should be unreachable for real content)
|
||||
* @param requiredPages pages this frame needs to render completely. When it exceeds
|
||||
* [pageHeights].size the caller must grow the atlas buffer and
|
||||
* re-render; the rendered pages are still valid in the meantime.
|
||||
* @param truncated images dropped because the frame needed more capacity than the
|
||||
* buffer holds; the frame is incomplete but never stale. Recoverable
|
||||
* by growing to [requiredPages]; with the composite fallback,
|
||||
* unrecoverable truncation should be unreachable for real content
|
||||
* @param requiredPages pages of buffer capacity this frame needs to render completely.
|
||||
* When it exceeds [pageHeights].size the caller must grow the atlas
|
||||
* buffer and re-render; the rendered pages are still valid in the
|
||||
* meantime.
|
||||
* @param hasOutput true when libass reported at least one visible image for this
|
||||
* timestamp, even when [changed] is 0 and the buffers were not
|
||||
* rewritten. false means this timestamp should be blank.
|
||||
* @param mode [MODE_ATLAS] or [MODE_COMPOSITE]; must match the ASS_PACK_MODE_*
|
||||
* constants in AssPack.h
|
||||
*/
|
||||
class AssAtlasFrame(
|
||||
val atlasWidth: Int,
|
||||
@@ -40,8 +51,17 @@ class AssAtlasFrame(
|
||||
val changed: Int,
|
||||
val truncated: Int,
|
||||
val requiredPages: Int,
|
||||
val hasOutput: Boolean
|
||||
val hasOutput: Boolean,
|
||||
val mode: Int = MODE_ATLAS
|
||||
) {
|
||||
companion object {
|
||||
/** One or more ALPHA_8 atlas pages, per-quad colors in the vertex stream. */
|
||||
const val MODE_ATLAS = 0
|
||||
|
||||
/** One premultiplied RGBA rect at the start of the atlas buffer, one quad. */
|
||||
const val MODE_COMPOSITE = 1
|
||||
}
|
||||
|
||||
/** Number of atlas pages this frame occupies. */
|
||||
val pageCount: Int get() = pageHeights.size
|
||||
|
||||
|
||||
@@ -8,9 +8,9 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
|
||||
companion object {
|
||||
|
||||
/** Must match MAX_ATLAS_PAGES + the header layout in AssKt.c (`writeAtlasHeader`). */
|
||||
/** Must match ASS_PACK_MAX_PAGES + the header layout in AssPack.h/AssKt.c (`writeAtlasHeader`). */
|
||||
private const val MAX_ATLAS_PAGES = 4
|
||||
private const val HEADER_INTS = 7 + 2 * MAX_ATLAS_PAGES
|
||||
private const val HEADER_INTS = 7 + 2 * MAX_ATLAS_PAGES + 1
|
||||
|
||||
@JvmStatic
|
||||
external fun nativeAssRenderInit(ass: Long): Long
|
||||
@@ -89,6 +89,9 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
lock.withLock { this.track = track }
|
||||
}
|
||||
|
||||
/** False after [setTrack] with null (subtitles disabled) — renders would return null. */
|
||||
val hasTrack: Boolean get() = lock.withLock { track != null }
|
||||
|
||||
fun setFontScale(scale: Float) {
|
||||
generation.incrementAndGet()
|
||||
withNative { nativeAssRenderSetFontScale(it, scale) }
|
||||
@@ -175,7 +178,8 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
|
||||
changed = header[2],
|
||||
truncated = header[3],
|
||||
requiredPages = header[4],
|
||||
hasOutput = header[5] != 0
|
||||
hasOutput = header[5] != 0,
|
||||
mode = header[7 + 2 * MAX_ATLAS_PAGES]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user