Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
977414bc3c |
@@ -1,9 +0,0 @@
|
||||
BasedOnStyle: Google
|
||||
AlignAfterOpenBracket: AlwaysBreak
|
||||
ColumnLimit: 120
|
||||
IndentWidth: 2
|
||||
ContinuationIndentWidth: 4
|
||||
DerivePointerAlignment: false
|
||||
LineEnding: LF
|
||||
PointerAlignment: Left
|
||||
SortIncludes: true
|
||||
@@ -1,28 +0,0 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.{c,cc,cpp,h,hpp,m,mm}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.dart]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.{kt,kts,java}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
|
||||
ktlint_code_style = android_studio
|
||||
ktlint_standard_max-line-length = disabled
|
||||
ktlint_standard_no-wildcard-imports = disabled
|
||||
ktlint_standard_property-naming = disabled
|
||||
|
||||
[*.swift]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
@@ -1,3 +0,0 @@
|
||||
*.sh text eol=lf
|
||||
*.Dockerfile text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
@@ -1,21 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -uo pipefail
|
||||
|
||||
if [ "${SKIP_HOOKS:-}" = "1" ]; then
|
||||
echo "[pre-commit] skipped (SKIP_HOOKS=1)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
GIT_DIR="$(git rev-parse --git-dir)"
|
||||
if [ -f "$GIT_DIR/MERGE_MSG" ] || [ -f "$GIT_DIR/MERGE_HEAD" ] || [ -f "$GIT_DIR/REVERT_HEAD" ]; then
|
||||
echo "[pre-commit] skipped (merge/revert in progress)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if git diff --cached --quiet; then
|
||||
echo "[pre-commit] nothing staged — skipping checks"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ROOT="$(git rev-parse --show-toplevel)"
|
||||
exec "$ROOT/scripts/ci_checks.sh"
|
||||
@@ -1,2 +0,0 @@
|
||||
github: edde746
|
||||
liberapay: edde746
|
||||
@@ -1,123 +0,0 @@
|
||||
name: Bug Report
|
||||
description: Report a bug or unexpected behavior
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to report a bug! Please fill out the information below to help us diagnose and fix the issue.
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Bug Description
|
||||
description: A clear and concise description of what the bug is.
|
||||
placeholder: What went wrong?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to Reproduce
|
||||
description: Steps to reproduce the behavior
|
||||
placeholder: |
|
||||
1. Go to '...'
|
||||
2. Tap on '...'
|
||||
3. Scroll down to '...'
|
||||
4. See error
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected Behavior
|
||||
description: What did you expect to happen?
|
||||
placeholder: Describe what should have happened
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual Behavior
|
||||
description: What actually happened?
|
||||
placeholder: Describe what actually happened
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: plezy-version
|
||||
attributes:
|
||||
label: Plezy Version
|
||||
description: Check the app settings for the version number and paste it here
|
||||
placeholder: e.g., 1.7.0
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: platform
|
||||
attributes:
|
||||
label: Platform
|
||||
description: Which platform(s) are affected?
|
||||
multiple: true
|
||||
options:
|
||||
- iOS
|
||||
- Android
|
||||
- Windows
|
||||
- macOS
|
||||
- Android TV
|
||||
- tvOS
|
||||
- Linux
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: media-server
|
||||
attributes:
|
||||
label: Media Server
|
||||
description: Are you using Jellyfin or Plex?
|
||||
multiple: true
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: device
|
||||
attributes:
|
||||
label: Device Information
|
||||
description: What device are you using?
|
||||
placeholder: e.g., iPhone 14 Pro, Pixel 7, Chrome on macOS
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Logs and Stack Traces
|
||||
description: Please paste any relevant logs or stack traces
|
||||
value: |
|
||||
<details>
|
||||
<summary>Logs</summary>
|
||||
|
||||
```
|
||||
Paste logs here
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- type: textarea
|
||||
id: screenshots
|
||||
attributes:
|
||||
label: Screenshots
|
||||
description: If applicable, add screenshots to help explain your problem
|
||||
placeholder: Drag and drop screenshots here
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
attributes:
|
||||
label: Additional Context
|
||||
description: Add any other context about the problem here
|
||||
@@ -1,5 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Questions and Discussions
|
||||
url: https://github.com/edde746/plezy/discussions
|
||||
about: Ask questions and discuss ideas with the community
|
||||
@@ -1,82 +0,0 @@
|
||||
name: Feature Request
|
||||
description: Suggest a new feature or enhancement
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for suggesting a new feature! Please provide as much detail as possible.
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem Statement
|
||||
description: Is your feature request related to a problem? Please describe.
|
||||
placeholder: I'm frustrated when... / It would be helpful if...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: solution
|
||||
attributes:
|
||||
label: Proposed Solution
|
||||
description: Describe the solution you'd like to see
|
||||
placeholder: What feature would solve this problem?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives Considered
|
||||
description: Have you considered any alternative solutions or features?
|
||||
placeholder: Describe alternatives you've considered
|
||||
|
||||
- type: textarea
|
||||
id: use-case
|
||||
attributes:
|
||||
label: Use Case
|
||||
description: Describe how you would use this feature
|
||||
placeholder: |
|
||||
1. As a user, I would...
|
||||
2. This would help me...
|
||||
3. The benefit would be...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: platform
|
||||
attributes:
|
||||
label: Target Platform
|
||||
description: Which platform(s) should this feature target?
|
||||
multiple: true
|
||||
options:
|
||||
- iOS
|
||||
- Android
|
||||
- Windows
|
||||
- macOS
|
||||
- Android TV
|
||||
- tvOS
|
||||
- Linux
|
||||
- All platforms
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: media-server
|
||||
attributes:
|
||||
label: Media Server
|
||||
description: Which media server(s) is this for?
|
||||
multiple: true
|
||||
options:
|
||||
- Jellyfin
|
||||
- Plex
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
attributes:
|
||||
label: Additional Context
|
||||
description: Add any other context, mockups, or screenshots about the feature request
|
||||
placeholder: Add mockups, links to similar features, or any other helpful context
|
||||
@@ -1,909 +0,0 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
build_android:
|
||||
description: Build Android
|
||||
default: true
|
||||
type: boolean
|
||||
build_ios:
|
||||
description: Build iOS
|
||||
default: true
|
||||
type: boolean
|
||||
build_macos:
|
||||
description: Build macOS
|
||||
default: true
|
||||
type: boolean
|
||||
build_windows:
|
||||
description: Build Windows
|
||||
default: true
|
||||
type: boolean
|
||||
build_linux:
|
||||
description: Build Linux
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
env:
|
||||
SENTRY_DART_DEFINE: ${{ github.repository == 'edde746/plezy' && '--dart-define=ENABLE_SENTRY=true' || '' }}
|
||||
GIT_COMMIT_DART_DEFINE: --dart-define=GIT_COMMIT=${{ github.sha }}
|
||||
SENTRY_ENV_DART_DEFINE: --dart-define=SENTRY_ENVIRONMENT=github
|
||||
DONATIONS_DART_DEFINE: --dart-define=ENABLE_DONATIONS=true
|
||||
LINUX_APT_PACKAGES: >
|
||||
clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev
|
||||
libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev
|
||||
libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev
|
||||
libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev
|
||||
libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev
|
||||
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
|
||||
ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
if: ${{ inputs.build_android }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache Gradle
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-gradle-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Configure Android signing
|
||||
run: |
|
||||
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 --decode > android/app/upload-keystore.jks
|
||||
cat > android/key.properties << EOF
|
||||
storePassword=${{ secrets.ANDROID_STORE_PASSWORD }}
|
||||
keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
storeFile=upload-keystore.jks
|
||||
EOF
|
||||
|
||||
- name: Build APKs
|
||||
run: flutter build apk --release --split-per-abi --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-android-apk ${{ env.DONATIONS_DART_DEFINE }} --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-android-apk
|
||||
run: ./scripts/upload-symbols.sh android-apk
|
||||
|
||||
- name: Clean up keystore
|
||||
if: always()
|
||||
run: rm -f android/app/upload-keystore.jks android/key.properties
|
||||
|
||||
- name: Package APKs
|
||||
run: |
|
||||
tar -czf plezy-android-arm64-v8a.tar.gz -C build/app/outputs/flutter-apk app-arm64-v8a-release.apk --transform 's/app-arm64-v8a-release.apk/plezy.apk/'
|
||||
tar -czf plezy-android-armeabi-v7a.tar.gz -C build/app/outputs/flutter-apk app-armeabi-v7a-release.apk --transform 's/app-armeabi-v7a-release.apk/plezy.apk/'
|
||||
tar -czf plezy-android-x86_64.tar.gz -C build/app/outputs/flutter-apk app-x86_64-release.apk --transform 's/app-x86_64-release.apk/plezy.apk/'
|
||||
|
||||
- name: Attest APKs
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: |
|
||||
plezy-android-arm64-v8a.tar.gz
|
||||
plezy-android-armeabi-v7a.tar.gz
|
||||
plezy-android-x86_64.tar.gz
|
||||
|
||||
- name: Upload APKs
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: android-apk
|
||||
path: |
|
||||
plezy-android-arm64-v8a.tar.gz
|
||||
plezy-android-armeabi-v7a.tar.gz
|
||||
plezy-android-x86_64.tar.gz
|
||||
|
||||
build-ios:
|
||||
if: ${{ inputs.build_ios }}
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache CocoaPods
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
ios/Pods
|
||||
~/Library/Caches/CocoaPods
|
||||
~/.cocoapods
|
||||
key: ${{ runner.os }}-pods-${{ hashFiles('**/Podfile.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pods-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build iOS (no codesign)
|
||||
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-ios ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/ios
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-ios
|
||||
run: ./scripts/upload-symbols.sh ios
|
||||
|
||||
- name: Create IPA
|
||||
run: |
|
||||
mkdir -p Payload
|
||||
cp -r build/ios/iphoneos/Runner.app Payload/
|
||||
zip -r plezy-ios.ipa Payload
|
||||
|
||||
- name: Attest IPA
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: plezy-ios.ipa
|
||||
|
||||
- name: Upload IPA
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ios-ipa
|
||||
path: plezy-ios.ipa
|
||||
|
||||
build-macos:
|
||||
if: ${{ inputs.build_macos }}
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache CocoaPods
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
macos/Pods
|
||||
~/Library/Caches/CocoaPods
|
||||
~/.cocoapods
|
||||
key: ${{ runner.os }}-macos-pods-${{ hashFiles('**/Podfile.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-macos-pods-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build macOS
|
||||
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-macos ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/macos
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-macos
|
||||
run: ./scripts/upload-symbols.sh macos
|
||||
|
||||
- name: Import Code Signing Certificate
|
||||
env:
|
||||
MACOS_CERTIFICATE_BASE64: ${{ secrets.MACOS_CERTIFICATE_BASE64 }}
|
||||
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
|
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
||||
|
||||
# Add keychain to search list
|
||||
security list-keychains -d user -s $KEYCHAIN_PATH login.keychain
|
||||
|
||||
- name: Sign Application
|
||||
env:
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
# Find the identity
|
||||
IDENTITY=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | grep -o '".*"' | tr -d '"')
|
||||
echo "Signing with identity: $IDENTITY"
|
||||
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
|
||||
# Deep sign everything inside-out: executables, dylibs, XPC services, app bundles, frameworks
|
||||
find "$APP_PATH/Contents/Frameworks" \( -name "*.xpc" -o -name "*.app" -o -name "*.framework" -o -name "*.dylib" \) -print0 \
|
||||
| sort -zr \
|
||||
| while IFS= read -r -d '' item; do
|
||||
echo "Signing: $item"
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$item"
|
||||
done
|
||||
|
||||
# Sign any remaining bare executables (e.g. Sparkle's Autoupdate)
|
||||
find "$APP_PATH/Contents/Frameworks" -type f -perm +111 ! -name "*.dylib" ! -path "*/Headers/*" ! -path "*/Modules/*" -print0 \
|
||||
| while IFS= read -r -d '' exe; do
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$exe" 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Sign the app bundle itself
|
||||
echo "Signing app bundle: $APP_PATH"
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime --entitlements macos/Runner/Release.entitlements "$APP_PATH"
|
||||
|
||||
- name: Verify Signature
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
echo "Verifying signature..."
|
||||
codesign -dvvv "$APP_PATH"
|
||||
echo "Verifying signed entitlements..."
|
||||
codesign -d --entitlements :- "$APP_PATH" > "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-jit" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-unsigned-executable-memory" "$RUNNER_TEMP/macos-entitlements.plist"
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
|
||||
- name: Notarize Application
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
|
||||
|
||||
# Create a temporary ZIP for notarization submission
|
||||
echo "Creating ZIP for notarization..."
|
||||
ditto -c -k --keepParent "$APP_PATH" notarization.zip
|
||||
|
||||
# Submit for notarization
|
||||
echo "Submitting to Apple's notary service..."
|
||||
xcrun notarytool submit notarization.zip \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait
|
||||
|
||||
# Staple the notarization ticket to the app
|
||||
echo "Stapling notarization ticket..."
|
||||
xcrun stapler staple "$APP_PATH"
|
||||
|
||||
# Verify stapling
|
||||
echo "Verifying notarization..."
|
||||
xcrun stapler validate "$APP_PATH"
|
||||
|
||||
- name: Create DMG
|
||||
run: |
|
||||
mkdir -p dmg-staging
|
||||
cp -R build/macos/Build/Products/Release/Plezy.app dmg-staging/
|
||||
ln -s /Applications dmg-staging/Applications
|
||||
hdiutil create -format ULMO -srcfolder dmg-staging -volname "Plezy" plezy-macos.dmg
|
||||
|
||||
- name: Sign DMG for Sparkle (EdDSA)
|
||||
if: env.SPARKLE_PRIVATE_KEY != ''
|
||||
env:
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
run: |
|
||||
printf -- "-----BEGIN ED25519 PRIVATE KEY-----\n%s\n-----END ED25519 PRIVATE KEY-----\n" "$SPARKLE_PRIVATE_KEY" > ed25519_key.pem
|
||||
OUTPUT=$(dart run auto_updater:sign_update plezy-macos.dmg ed25519_key.pem)
|
||||
rm ed25519_key.pem
|
||||
# Extract edSignature value from output like: sparkle:edSignature="..." length="..."
|
||||
SIGNATURE=$(echo "$OUTPUT" | grep -o 'edSignature="[^"]*"' | sed 's/edSignature="//;s/"//')
|
||||
echo "MACOS_ED_SIGNATURE=$SIGNATURE" >> $GITHUB_ENV
|
||||
echo "MACOS_DMG_SIZE=$(stat -f%z plezy-macos.dmg)" >> $GITHUB_ENV
|
||||
|
||||
- name: Attest macOS DMG
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: plezy-macos.dmg
|
||||
|
||||
- name: Write macOS signature metadata
|
||||
run: |
|
||||
echo "${{ env.MACOS_ED_SIGNATURE }}" > macos-ed-signature.txt
|
||||
echo "${{ env.MACOS_DMG_SIZE }}" > macos-dmg-size.txt
|
||||
|
||||
- name: Upload macOS DMG
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-dmg
|
||||
path: |
|
||||
plezy-macos.dmg
|
||||
macos-ed-signature.txt
|
||||
macos-dmg-size.txt
|
||||
|
||||
build-windows:
|
||||
name: Build Windows (${{ matrix.arch }})
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: windows-latest
|
||||
flutter_setup: action
|
||||
native_cache_path: build/windows/x64/_deps
|
||||
- arch: arm64
|
||||
runner: windows-11-arm
|
||||
flutter_setup: git
|
||||
native_cache_path: |
|
||||
build/windows/arm64/_deps
|
||||
build/windows/arm64/mpv-dev-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cache Windows native dependencies
|
||||
id: windows-native-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ matrix.native_cache_path }}
|
||||
key: windows-native-${{ matrix.arch }}-${{ hashFiles('windows/CMakeLists.txt') }}
|
||||
|
||||
- name: Install 7-Zip
|
||||
if: matrix.arch == 'arm64' && steps.windows-native-cache.outputs.cache-hit != 'true'
|
||||
shell: pwsh
|
||||
run: choco install 7zip -y
|
||||
|
||||
- name: Setup Flutter
|
||||
if: matrix.flutter_setup == 'action'
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Set up Flutter 3.44.0 (git tag)
|
||||
if: matrix.flutter_setup == 'git'
|
||||
# Flutter publishes no windows-arm64 SDK archive, so subosito can't
|
||||
# resolve 3.44.0 for arm64: the stable manifest has no arm64 entry, and
|
||||
# `channel: master` would git-clone master HEAD (whose engine != our
|
||||
# patched 3.44.0). Clone the 3.44.0 tag directly to get engine rev
|
||||
# 4c525dac, which install-patched-engine.ps1 asserts before swapping.
|
||||
shell: pwsh
|
||||
run: |
|
||||
$root = "$env:RUNNER_TEMP\flutter"
|
||||
git clone --depth 1 --branch 3.44.0 https://github.com/flutter/flutter.git $root
|
||||
"$root\bin" | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
|
||||
& "$root\bin\flutter.bat" --version
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\AppData\Local\Pub\Cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
shell: pwsh
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Install patched Flutter engine (DComp)
|
||||
shell: pwsh
|
||||
run: |
|
||||
flutter precache --windows
|
||||
.\windows\tool\install-patched-engine.ps1
|
||||
|
||||
- name: Build Windows ${{ matrix.arch }}
|
||||
shell: pwsh
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-${{ matrix.arch }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-${{ matrix.arch }}
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: pwsh
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-windows-${{ matrix.arch }}
|
||||
run: .\scripts\upload-symbols.ps1 windows-${{ matrix.arch }}
|
||||
|
||||
- name: Upload ${{ matrix.arch }} build
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-${{ matrix.arch }}-build
|
||||
path: build/windows/${{ matrix.arch }}/runner/Release/
|
||||
|
||||
package-windows:
|
||||
needs: build-windows
|
||||
if: ${{ inputs.build_windows }}
|
||||
runs-on: windows-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Dart
|
||||
uses: dart-lang/setup-dart@v1
|
||||
|
||||
- name: Download x64 build
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-x64-build
|
||||
path: build-x64
|
||||
|
||||
- name: Download arm64 build
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-arm64-build
|
||||
path: build-arm64
|
||||
|
||||
- name: Read version from pubspec
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = (Select-String -Path pubspec.yaml -Pattern '^version:\s*(\S+)').Matches[0].Groups[1].Value -replace '\+.*'
|
||||
echo "version=$v" >> $env:GITHUB_OUTPUT
|
||||
|
||||
- name: Build installer and portables
|
||||
run: .\windows\build-installer.ps1 -X64BuildDir "build-x64" -Arm64BuildDir "build-arm64" -Version "${{ steps.version.outputs.version }}"
|
||||
|
||||
- name: Sign installer for WinSparkle (EdDSA)
|
||||
if: env.SPARKLE_PRIVATE_KEY != ''
|
||||
env:
|
||||
SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir _signer | Out-Null
|
||||
@{name="signer"; environment=@{sdk=">=3.0.0 <4.0.0"}; dependencies=@{cryptography="^2.7.0"}} | ConvertTo-Json -Depth 3 | Out-File _signer/pubspec.yaml
|
||||
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/edde746/auto_updater/main/packages/auto_updater/bin/sign_update.dart" -OutFile _signer/sign.dart
|
||||
Push-Location _signer
|
||||
dart pub get
|
||||
Set-Content -Path ed25519_key.pem -Value $env:SPARKLE_PRIVATE_KEY -Encoding ascii -NoNewline
|
||||
$output = dart run sign.dart ../plezy-windows-installer.exe ed25519_key.pem
|
||||
Pop-Location
|
||||
Remove-Item _signer -Recurse -Force
|
||||
$sig = [regex]::Match($output, 'edSignature="([^"]*)"').Groups[1].Value
|
||||
Set-Content -Path win-ed-signature.txt -Value $sig -Encoding ascii -NoNewline
|
||||
Set-Content -Path win-installer-size.txt -Value (Get-Item plezy-windows-installer.exe).Length.ToString() -Encoding ascii -NoNewline
|
||||
|
||||
- name: Attest Windows artifacts
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: |
|
||||
plezy-windows-x64-portable.7z
|
||||
plezy-windows-arm64-portable.7z
|
||||
plezy-windows-installer.exe
|
||||
|
||||
- name: Upload x64 portable
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x64-portable
|
||||
path: plezy-windows-x64-portable.7z
|
||||
|
||||
- name: Upload arm64 portable
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-arm64-portable
|
||||
path: plezy-windows-arm64-portable.7z
|
||||
|
||||
- name: Upload installer
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-installer
|
||||
path: |
|
||||
plezy-windows-installer.exe
|
||||
win-ed-signature.txt
|
||||
win-installer-size.txt
|
||||
|
||||
build-linux:
|
||||
name: Build Linux (${{ matrix.arch }})
|
||||
if: ${{ inputs.build_linux }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
runner: ubuntu-latest
|
||||
flutter_channel: stable
|
||||
pkg_config_arch: x86_64-linux-gnu
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
flutter_channel: master
|
||||
pkg_config_arch: aarch64-linux-gnu
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: ${{ matrix.flutter_channel }}
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
|
||||
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: ${{ env.LINUX_APT_PACKAGES }}
|
||||
version: 1.1
|
||||
|
||||
- name: Install Linux dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
read -r -a packages <<< "$LINUX_APT_PACKAGES"
|
||||
|
||||
for attempt in 1 2 3; do
|
||||
if sudo apt-get update -o Acquire::Retries=3 && sudo apt-get install -y -o Acquire::Retries=3 "${packages[@]}"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
sudo apt-get clean
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
sleep $((attempt * 15))
|
||||
done
|
||||
|
||||
exit 1
|
||||
|
||||
- name: Cache libmpv build
|
||||
id: libmpv-cache
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: libmpv-prefix
|
||||
key: libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh') }}
|
||||
|
||||
- name: Build libmpv
|
||||
if: steps.libmpv-cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: bash linux/packaging/build-libmpv.sh
|
||||
|
||||
- name: Install fpm
|
||||
shell: bash
|
||||
run: sudo gem install fpm
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: flutter pub get --enforce-lockfile --no-example
|
||||
|
||||
- name: Build Linux ${{ matrix.arch }}
|
||||
shell: bash
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-${{ matrix.arch }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-${{ matrix.arch }}
|
||||
env:
|
||||
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/${{ matrix.pkg_config_arch }}/pkgconfig
|
||||
|
||||
- name: Upload symbols to bugs.plezy.app
|
||||
if: github.repository == 'edde746/plezy'
|
||||
shell: bash
|
||||
env:
|
||||
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
|
||||
SENTRY_DIST: github-linux-${{ matrix.arch }}
|
||||
run: ./scripts/upload-symbols.sh linux-${{ matrix.arch }}
|
||||
|
||||
- name: Resolve bundle directory
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${{ matrix.arch }}" == "x64" ]]; then
|
||||
bundle_dir=build/linux/x64/release/bundle
|
||||
else
|
||||
bundle_dir=$(find build/linux -path "*/release/bundle" -type d | head -1)
|
||||
fi
|
||||
if [[ -z "$bundle_dir" || ! -d "$bundle_dir" ]]; then
|
||||
echo "ERROR: Linux bundle directory not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "BUNDLE_DIR=$bundle_dir" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build Linux Packages
|
||||
shell: bash
|
||||
run: |
|
||||
BUILD_DIR="$BUNDLE_DIR" \
|
||||
ARCH_SUFFIX=${{ matrix.arch }} \
|
||||
OUTPUT_DIR="$GITHUB_WORKSPACE" \
|
||||
python3 linux/packaging/build-packages.py
|
||||
|
||||
- name: Copy libmpv into bundle
|
||||
shell: bash
|
||||
run: |
|
||||
BUNDLE_LIB="$BUNDLE_DIR/lib"
|
||||
LIBMPV_DIR=$(dirname "$(find libmpv-prefix -name 'libmpv.so' | head -1)")
|
||||
cp -a "$LIBMPV_DIR"/libmpv.so* "$BUNDLE_LIB/"
|
||||
cp -a libmpv-prefix/lib/libshaderc_shared.so* "$BUNDLE_LIB/"
|
||||
|
||||
- name: Bundle shared libraries for portable tarball
|
||||
shell: bash
|
||||
run: bash linux/packaging/bundle-libs.sh "$BUNDLE_DIR"
|
||||
|
||||
- name: Copy wrapper script into bundle
|
||||
shell: bash
|
||||
run: cp linux/packaging/plezy.sh "$BUNDLE_DIR/plezy.sh"
|
||||
|
||||
- name: Verify no missing dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
cd "$BUNDLE_DIR"
|
||||
MISSING=$(LD_LIBRARY_PATH=lib ldd ./plezy 2>&1 | grep "not found" || true)
|
||||
if [[ -n "$MISSING" ]]; then
|
||||
echo "ERROR: Unresolved dependencies found:" >&2
|
||||
echo "$MISSING" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "All dependencies resolved."
|
||||
|
||||
- name: Create tarball
|
||||
shell: bash
|
||||
run: |
|
||||
cd "$BUNDLE_DIR"
|
||||
tar -czf "$GITHUB_WORKSPACE/plezy-linux-${{ matrix.arch }}.tar.gz" *
|
||||
|
||||
- name: Attest Linux ${{ matrix.arch }} artifacts
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: |
|
||||
plezy-linux-${{ matrix.arch }}.tar.gz
|
||||
plezy-linux-${{ matrix.arch }}.deb
|
||||
plezy-linux-${{ matrix.arch }}.rpm
|
||||
plezy-linux-${{ matrix.arch }}.pkg.tar.zst
|
||||
|
||||
- name: Upload Linux ${{ matrix.arch }} artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-${{ matrix.arch }}
|
||||
path: |
|
||||
plezy-linux-${{ matrix.arch }}.tar.gz
|
||||
plezy-linux-${{ matrix.arch }}.deb
|
||||
plezy-linux-${{ matrix.arch }}.rpm
|
||||
plezy-linux-${{ matrix.arch }}.pkg.tar.zst
|
||||
|
||||
create-release:
|
||||
needs: [build-android, build-ios, build-macos, build-windows, package-windows, build-linux]
|
||||
if: ${{ always() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && (inputs.build_android || inputs.build_ios || inputs.build_macos || inputs.build_windows || inputs.build_linux) }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: pubspec.yaml
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Download Android artifacts
|
||||
if: ${{ inputs.build_android }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: android-apk
|
||||
path: artifacts/android-apk
|
||||
|
||||
- name: Download iOS artifact
|
||||
if: ${{ inputs.build_ios }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ios-ipa
|
||||
path: artifacts/ios-ipa
|
||||
|
||||
- name: Download macOS artifact
|
||||
if: ${{ inputs.build_macos }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: macos-dmg
|
||||
path: artifacts/macos-dmg
|
||||
|
||||
- name: Download Windows x64 artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-x64-portable
|
||||
path: artifacts/windows-x64-portable
|
||||
|
||||
- name: Download Windows arm64 artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-arm64-portable
|
||||
path: artifacts/windows-arm64-portable
|
||||
|
||||
- name: Download Windows installer artifact
|
||||
if: ${{ inputs.build_windows }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: windows-installer
|
||||
path: artifacts/windows-installer
|
||||
|
||||
- name: Download Linux x64 artifacts
|
||||
if: ${{ inputs.build_linux }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: linux-x64
|
||||
path: artifacts/linux-x64
|
||||
|
||||
- name: Download Linux arm64 artifacts
|
||||
if: ${{ inputs.build_linux }}
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: linux-arm64
|
||||
path: artifacts/linux-arm64
|
||||
|
||||
- name: Display structure of downloaded files
|
||||
run: ls -R artifacts
|
||||
|
||||
- name: Read version from pubspec.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //' | sed 's/+.*//')
|
||||
BUILD_NUMBER=$(grep '^version:' pubspec.yaml | sed 's/.*+//')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "build_number=$BUILD_NUMBER" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Generate appcast.xml
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
BUILD_NUMBER="${{ steps.version.outputs.build_number }}"
|
||||
|
||||
# Read macOS signature metadata (may be empty if secrets not configured)
|
||||
MACOS_ED_SIG=""
|
||||
MACOS_DMG_SIZE="0"
|
||||
if [ -f artifacts/macos-dmg/macos-ed-signature.txt ]; then
|
||||
MACOS_ED_SIG=$(cat artifacts/macos-dmg/macos-ed-signature.txt)
|
||||
fi
|
||||
if [ -f artifacts/macos-dmg/macos-dmg-size.txt ]; then
|
||||
MACOS_DMG_SIZE=$(cat artifacts/macos-dmg/macos-dmg-size.txt)
|
||||
fi
|
||||
|
||||
# Read Windows signature metadata (may be empty if secrets not configured)
|
||||
WIN_ED_SIG=""
|
||||
WIN_INSTALLER_SIZE="0"
|
||||
if [ -f artifacts/windows-installer/win-ed-signature.txt ]; then
|
||||
WIN_ED_SIG=$(cat artifacts/windows-installer/win-ed-signature.txt)
|
||||
fi
|
||||
if [ -f artifacts/windows-installer/win-installer-size.txt ]; then
|
||||
WIN_INSTALLER_SIZE=$(cat artifacts/windows-installer/win-installer-size.txt)
|
||||
fi
|
||||
|
||||
cat > appcast.xml << XMLEOF
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
|
||||
<channel>
|
||||
<title>Plezy Updates</title>
|
||||
<item>
|
||||
<title>Version ${VERSION}</title>
|
||||
<sparkle:version>${BUILD_NUMBER}</sparkle:version>
|
||||
<sparkle:shortVersionString>${VERSION}</sparkle:shortVersionString>
|
||||
<sparkle:releaseNotesLink>https://gh-html.edde746.dev/edde746/plezy/${VERSION}</sparkle:releaseNotesLink>
|
||||
XMLEOF
|
||||
|
||||
# macOS enclosure
|
||||
if [ -n "$MACOS_ED_SIG" ]; then
|
||||
cat >> appcast.xml << XMLEOF
|
||||
<enclosure url="https://github.com/edde746/plezy/releases/download/${VERSION}/plezy-macos.dmg"
|
||||
length="${MACOS_DMG_SIZE}" type="application/octet-stream"
|
||||
sparkle:edSignature="${MACOS_ED_SIG}"
|
||||
sparkle:os="macos" />
|
||||
XMLEOF
|
||||
fi
|
||||
|
||||
# Windows enclosure
|
||||
if [ -n "$WIN_ED_SIG" ]; then
|
||||
cat >> appcast.xml << XMLEOF
|
||||
<enclosure url="https://github.com/edde746/plezy/releases/download/${VERSION}/plezy-windows-installer.exe"
|
||||
length="${WIN_INSTALLER_SIZE}" type="application/octet-stream"
|
||||
sparkle:edSignature="${WIN_ED_SIG}"
|
||||
sparkle:installerArguments="/SILENT /SP-"
|
||||
sparkle:os="windows" />
|
||||
XMLEOF
|
||||
fi
|
||||
|
||||
cat >> appcast.xml << 'XMLEOF'
|
||||
</item>
|
||||
</channel>
|
||||
</rss>
|
||||
XMLEOF
|
||||
|
||||
# Clean up leading whitespace from heredoc indentation
|
||||
sed -i 's/^ //' appcast.xml
|
||||
|
||||
echo "Generated appcast.xml:"
|
||||
cat appcast.xml
|
||||
|
||||
- name: Collect release files
|
||||
id: release-files
|
||||
run: |
|
||||
{
|
||||
echo 'files<<EOF'
|
||||
if [ "${{ inputs.build_android }}" = "true" ]; then
|
||||
echo artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
|
||||
echo artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
|
||||
echo artifacts/android-apk/plezy-android-x86_64.tar.gz
|
||||
fi
|
||||
if [ "${{ inputs.build_ios }}" = "true" ]; then
|
||||
echo artifacts/ios-ipa/plezy-ios.ipa
|
||||
fi
|
||||
if [ "${{ inputs.build_macos }}" = "true" ]; then
|
||||
echo artifacts/macos-dmg/plezy-macos.dmg
|
||||
fi
|
||||
if [ "${{ inputs.build_windows }}" = "true" ]; then
|
||||
echo artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
|
||||
echo artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
|
||||
echo artifacts/windows-installer/plezy-windows-installer.exe
|
||||
fi
|
||||
if [ "${{ inputs.build_linux }}" = "true" ]; then
|
||||
echo 'artifacts/linux-x64/*'
|
||||
echo 'artifacts/linux-arm64/*'
|
||||
fi
|
||||
echo appcast.xml
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: ${{ steps.release-files.outputs.files }}
|
||||
draft: true
|
||||
prerelease: false
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,225 +0,0 @@
|
||||
name: CI - Sanity Checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Code Analysis
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
|
||||
flutter pub get
|
||||
|
||||
- name: Install saf_util development dependencies
|
||||
working-directory: packages/saf_util
|
||||
run: flutter pub get
|
||||
|
||||
- name: Verify generated files committed
|
||||
run: scripts/codegen.sh --check
|
||||
|
||||
- name: Verify translation hygiene
|
||||
run: python3 scripts/clean_translations.py --check --strict
|
||||
|
||||
- name: Verify workflow and script guards
|
||||
run: |
|
||||
python3 scripts/check_build_workflow.py
|
||||
python3 scripts/check_update_packages_workflow.py
|
||||
python3 scripts/test_pubspec_version.py
|
||||
python3 scripts/test_clean_translations.py
|
||||
|
||||
- name: Verify formatting
|
||||
run: |
|
||||
paths=(lib)
|
||||
[ ! -d test ] || paths+=(test)
|
||||
find "${paths[@]}" -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f -print0 |
|
||||
xargs -0 -r dart format --output=none --set-exit-if-changed
|
||||
- name: Analyze code
|
||||
run: dart run scripts/check_analyzer.dart
|
||||
|
||||
- name: Check for unused code
|
||||
run: |
|
||||
echo "🔍 Checking for unused code..."
|
||||
dart run dart_code_linter:metrics check-unused-code lib 2>&1 | tee unused_code.txt
|
||||
if grep -qi "no unused code found" unused_code.txt; then
|
||||
echo "✅ No unused code found"
|
||||
else
|
||||
echo "❌ Found unused code:"
|
||||
cat unused_code.txt
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Check for unused files
|
||||
run: |
|
||||
echo "🔍 Checking for unused files..."
|
||||
dart run dart_code_linter:metrics check-unused-files lib 2>&1 | tee unused_files.txt
|
||||
if grep -qi "no unused files found" unused_files.txt; then
|
||||
echo "✅ No unused files found"
|
||||
else
|
||||
echo "❌ Found unused files:"
|
||||
cat unused_files.txt
|
||||
exit 1
|
||||
fi
|
||||
|
||||
test:
|
||||
name: Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
flutter clean
|
||||
flutter pub get
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
if [ -d "test" ] && [ "$(find test -name '*_test.dart' | wc -l)" -gt 0 ]; then
|
||||
flutter test
|
||||
else
|
||||
echo "No tests found, skipping test execution"
|
||||
fi
|
||||
|
||||
android-test:
|
||||
name: Android JVM Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Cache Gradle
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.gradle/caches
|
||||
~/.gradle/wrapper
|
||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-gradle-
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Configure Android local properties
|
||||
run: printf 'flutter.sdk=%s\nsdk.dir=%s\n' "$FLUTTER_ROOT" "$ANDROID_HOME" > android/local.properties
|
||||
|
||||
- name: Run Android JVM unit tests
|
||||
working-directory: android
|
||||
run: ./gradlew :app:testDebugUnitTest :saf_util:testDebugUnitTest :libass:testDebugUnitTest -x :app:compileFlutterBuildDebug --continue
|
||||
|
||||
native-format:
|
||||
name: Native Formatting
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
|
||||
- name: Verify native formatting
|
||||
run: scripts/format_native.sh --check
|
||||
|
||||
dependency-check:
|
||||
name: Dependency Validation
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Flutter
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: "stable"
|
||||
flutter-version: "3.44.0"
|
||||
cache: true
|
||||
pub-cache: false
|
||||
|
||||
- name: Cache Pub dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.pub-cache
|
||||
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
|
||||
|
||||
- name: Verify dependencies
|
||||
run: |
|
||||
flutter clean
|
||||
flutter pub get
|
||||
flutter pub outdated
|
||||
@@ -1,80 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Version number (e.g., 1.9.0)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Validate version format
|
||||
run: |
|
||||
if ! echo "${{ inputs.version }}" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||
echo "Error: Version must be in semantic versioning format (e.g., 1.9.0)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Extract current build number
|
||||
id: get_build
|
||||
run: |
|
||||
CURRENT_BUILD=$(python3 scripts/pubspec_version.py --build-number pubspec.yaml)
|
||||
NEW_BUILD=$((10#$CURRENT_BUILD + 1))
|
||||
|
||||
echo "current_build=$CURRENT_BUILD" >> $GITHUB_OUTPUT
|
||||
echo "new_build=$NEW_BUILD" >> $GITHUB_OUTPUT
|
||||
echo "Current build: $CURRENT_BUILD"
|
||||
echo "New build: $NEW_BUILD"
|
||||
|
||||
- name: Update pubspec.yaml
|
||||
run: |
|
||||
NEW_VERSION="${{ inputs.version }}+${{ steps.get_build.outputs.new_build }}"
|
||||
sed -i "s/^version: .*/version: $NEW_VERSION/" pubspec.yaml
|
||||
echo "Updated version to: $NEW_VERSION"
|
||||
cat pubspec.yaml | grep '^version:'
|
||||
|
||||
- name: Configure Git
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
- name: Commit version bump
|
||||
run: |
|
||||
git add pubspec.yaml
|
||||
git commit -m "chore: bump version to ${{ inputs.version }}"
|
||||
|
||||
- name: Create Git tag
|
||||
run: |
|
||||
git tag "${{ inputs.version }}"
|
||||
echo "Created tag: ${{ inputs.version }}"
|
||||
|
||||
- name: Push changes and tag
|
||||
run: |
|
||||
git push origin main
|
||||
git push origin --tags
|
||||
|
||||
- name: Trigger build workflow
|
||||
run: |
|
||||
curl --fail-with-body -L \
|
||||
-X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "X-GitHub-Api-Version: 2022-11-28" \
|
||||
https://api.github.com/repos/${{ github.repository }}/actions/workflows/build.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
|
||||
echo "Build workflow triggered successfully"
|
||||
@@ -1,129 +0,0 @@
|
||||
name: Update Packages
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: Published release tag to update packages for
|
||||
required: true
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
resolve-release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
tag: ${{ steps.release.outputs.tag }}
|
||||
steps:
|
||||
- name: Resolve published release tag
|
||||
id: release
|
||||
env:
|
||||
EVENT_TAG: ${{ github.event.release.tag_name }}
|
||||
INPUT_TAG: ${{ inputs.release_tag }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$GITHUB_EVENT_NAME" = "release" ]; then
|
||||
REQUESTED_TAG="$EVENT_TAG"
|
||||
else
|
||||
REQUESTED_TAG="$INPUT_TAG"
|
||||
fi
|
||||
|
||||
if [ -z "$REQUESTED_TAG" ]; then
|
||||
echo "A release tag is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
RELEASE=$(gh release view "$REQUESTED_TAG" --repo "$GITHUB_REPOSITORY" \
|
||||
--json tagName,isDraft,publishedAt)
|
||||
RESOLVED_TAG=$(jq -r '.tagName' <<< "$RELEASE")
|
||||
IS_DRAFT=$(jq -r '.isDraft' <<< "$RELEASE")
|
||||
PUBLISHED_AT=$(jq -r '.publishedAt // empty' <<< "$RELEASE")
|
||||
|
||||
if [ "$RESOLVED_TAG" != "$REQUESTED_TAG" ] || \
|
||||
[ "$IS_DRAFT" != "false" ] || [ -z "$PUBLISHED_AT" ]; then
|
||||
echo "Tag '$REQUESTED_TAG' is not an exact published release tag." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "tag=$RESOLVED_TAG" >> "$GITHUB_OUTPUT"
|
||||
|
||||
update-homebrew:
|
||||
needs: resolve-release
|
||||
runs-on: macos-latest
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.resolve-release.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download and hash release
|
||||
id: release
|
||||
run: |
|
||||
curl --fail-with-body -L -o plezy-macos.dmg \
|
||||
"https://github.com/edde746/plezy/releases/download/$RELEASE_TAG/plezy-macos.dmg"
|
||||
SHA256=$(shasum -a 256 plezy-macos.dmg | cut -d' ' -f1)
|
||||
echo "sha256=$SHA256" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Update cask
|
||||
run: |
|
||||
sed -i '' "s/version \".*\"/version \"$RELEASE_TAG\"/" Casks/plezy.rb
|
||||
sed -i '' "s/sha256 \".*\"/sha256 \"${{ steps.release.outputs.sha256 }}\"/" Casks/plezy.rb
|
||||
|
||||
- name: Commit
|
||||
run: |
|
||||
BRANCH="${{ github.event.repository.default_branch }}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add Casks/plezy.rb
|
||||
if ! git diff --staged --quiet; then
|
||||
git commit -m "chore: update cask to $RELEASE_TAG"
|
||||
git push origin "HEAD:$BRANCH"
|
||||
else
|
||||
echo "No cask changes to commit."
|
||||
fi
|
||||
|
||||
update-winget:
|
||||
needs: resolve-release
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: vedantmgoyal9/winget-releaser@v2
|
||||
with:
|
||||
identifier: edde746.Plezy
|
||||
installers-regex: 'plezy-windows-installer\.exe$'
|
||||
release-tag: ${{ needs.resolve-release.outputs.tag }}
|
||||
token: ${{ secrets.WINGET_TOKEN }}
|
||||
|
||||
update-appcast-branch:
|
||||
needs: resolve-release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.resolve-release.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Download appcast.xml from release
|
||||
run: |
|
||||
gh release download "$RELEASE_TAG" \
|
||||
--pattern "appcast.xml"
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Push to appcast branch
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
BLOB=$(git hash-object -w appcast.xml)
|
||||
TREE=$(printf "100644 blob %s\tappcast.xml\n" "$BLOB" | git mktree)
|
||||
COMMIT=$(git commit-tree "$TREE" -m "Update appcast for $RELEASE_TAG")
|
||||
git push origin "$COMMIT:refs/heads/appcast" --force
|
||||
@@ -1,74 +0,0 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.build/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
.swiftpm/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.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.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
.pub/
|
||||
/build/
|
||||
/debug-info/
|
||||
|
||||
# tvOS: build artifacts and generated assets (regenerated by xcode_appletv.sh)
|
||||
tvos/build/
|
||||
tvos/Pods/
|
||||
tvos/Podfile.lock
|
||||
tvos/Runner.xcworkspace/xcuserdata/
|
||||
tvos/Runner.xcodeproj/xcuserdata/
|
||||
tvos/Runner.xcodeproj/project.xcworkspace/xcuserdata/
|
||||
tvos/Flutter/Generated.xcconfig
|
||||
tvos/Flutter/flutter_export_environment.sh
|
||||
tvos/Flutter/libPods-Runner.a
|
||||
tvos/tvos_flutter_assets/
|
||||
tvos/Runner/GeneratedPluginRegistrant.h
|
||||
tvos/Runner/GeneratedPluginRegistrant.m
|
||||
|
||||
# Symbolication related
|
||||
app.*.symbols
|
||||
|
||||
# Obfuscation related
|
||||
app.*.map.json
|
||||
|
||||
# Android Studio will place build artifacts here
|
||||
/android/app/debug
|
||||
/android/app/profile
|
||||
/android/app/release
|
||||
|
||||
# Code duplication reports
|
||||
duplication-report/
|
||||
|
||||
.env.*
|
||||
.env
|
||||
!.env.example
|
||||
|
||||
**/fastlane/**/
|
||||
**/fastlane/report.xml
|
||||
maestro/**/*.png
|
||||
|
||||
server/deploy.sh
|
||||
server/Caddyfile
|
||||
@@ -1,45 +0,0 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "077b4a4ce10a07b82caa6897f0c626f9c0a3ac90"
|
||||
channel: "stable"
|
||||
|
||||
project_type: app
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
- platform: android
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
- platform: ios
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
- platform: linux
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
- platform: macos
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
- platform: web
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
- platform: windows
|
||||
create_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
base_revision: 077b4a4ce10a07b82caa6897f0c626f9c0a3ac90
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"indentation" : {
|
||||
"spaces" : 2
|
||||
},
|
||||
"lineLength" : 120,
|
||||
"maximumBlankLines" : 1,
|
||||
"respectsExistingLineBreaks" : true,
|
||||
"rules" : {},
|
||||
"version" : 1
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Fork and clone the repository
|
||||
2. Run `flutter pub get` to install dependencies
|
||||
3. Run `scripts/codegen.sh` to generate translations and Dart model code
|
||||
4. Start developing!
|
||||
|
||||
## Development
|
||||
|
||||
- Follow Dart/Flutter conventions
|
||||
- Run `dart format .` to format Dart code (note: generated files like `*.g.dart` are excluded from CI checks)
|
||||
- Run `scripts/format_native.sh --fix` to format Kotlin, Swift, C++, C, Objective-C, and native headers
|
||||
- Run `flutter analyze` before submitting to check for issues
|
||||
- Run `flutter test` if tests are available
|
||||
- Test your changes thoroughly
|
||||
|
||||
### Code Quality Checks
|
||||
|
||||
The project includes automated CI checks that run on all pull requests:
|
||||
|
||||
1. **Code Formatting**: Ensures code follows Dart and native formatting standards
|
||||
- Run locally: `dart format .` to format Dart files
|
||||
- Run locally: `scripts/format_native.sh --fix` to format native files
|
||||
- Note: CI only checks non-generated files (excludes `.g.dart`, `.freezed.dart`)
|
||||
- Generated files are reformatted automatically by build tools
|
||||
|
||||
2. **Static Analysis**: Checks for code issues and potential bugs
|
||||
- Run locally: `flutter analyze`
|
||||
- Note: CI excludes generated files from analysis (configured in `analysis_options.yaml`)
|
||||
|
||||
3. **Generated Code**: Ensures generated translations and model files are current
|
||||
- Run locally: `scripts/codegen.sh --check`
|
||||
|
||||
4. **Tests**: Runs unit and widget tests (when available)
|
||||
- Run locally: `flutter test`
|
||||
|
||||
All these checks must pass before your changes can be merged.
|
||||
|
||||
## Internationalization (i18n)
|
||||
|
||||
This project uses `slang` for internationalization with JSON files.
|
||||
|
||||
### Adding New Strings
|
||||
|
||||
1. Add your string to `lib/i18n/strings.i18n.json`:
|
||||
```json
|
||||
{
|
||||
"section": {
|
||||
"myNewString": "My new text"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Run `dart run slang` to regenerate translation files
|
||||
|
||||
3. Use in your code:
|
||||
```dart
|
||||
Text(t.section.myNewString)
|
||||
```
|
||||
|
||||
### Adding New Languages
|
||||
|
||||
1. Create new JSON file: `lib/i18n/[locale].i18n.json`
|
||||
2. Copy structure from `en.i18n.json` and translate values
|
||||
3. Run `dart run slang` to regenerate files
|
||||
|
||||
### Guidelines
|
||||
|
||||
- Organize strings logically in nested objects
|
||||
- Use camelCase for keys
|
||||
- Keep strings concise and clear
|
||||
- Always run `dart run slang` after changes
|
||||
@@ -1,35 +0,0 @@
|
||||
cask "plezy" do
|
||||
version "2.8.0"
|
||||
sha256 "78df0227fc9a578c259fa7cdda526a2679fe46f5be6620f7a020e18d08f206f5"
|
||||
|
||||
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
|
||||
name "Plezy"
|
||||
desc "Modern Plex and Jellyfin client built with Flutter"
|
||||
homepage "https://github.com/edde746/plezy"
|
||||
|
||||
livecheck do
|
||||
url :url
|
||||
strategy :github_latest
|
||||
end
|
||||
|
||||
auto_updates true
|
||||
|
||||
app "Plezy.app"
|
||||
|
||||
postflight do
|
||||
system_command "/usr/bin/xattr",
|
||||
args: ["-cr", "#{appdir}/Plezy.app"],
|
||||
sudo: false
|
||||
end
|
||||
|
||||
uninstall quit: "com.edde746.plezy"
|
||||
|
||||
zap trash: [
|
||||
"~/Library/Application Support/com.edde746.plezy",
|
||||
"~/Library/Caches/com.edde746.plezy",
|
||||
"~/Library/HTTPStorages/com.edde746.plezy",
|
||||
"~/Library/Preferences/com.edde746.plezy.plist",
|
||||
"~/Library/Saved Application State/com.edde746.plezy.savedState",
|
||||
"~/Library/WebKit/com.edde746.plezy",
|
||||
]
|
||||
end
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,163 +0,0 @@
|
||||
<h1>
|
||||
<img src="assets/plezy.png" alt="Plezy Logo" height="24" style="vertical-align: middle;" />
|
||||
Plezy
|
||||
</h1>
|
||||
|
||||
A modern client for Plex and Jellyfin on desktop, mobile, and TV. Built with Flutter for native performance and a clean interface.
|
||||
|
||||
<p>
|
||||
<a href="https://plezy.app">Website</a> ·
|
||||
<a href="https://plezy.app/#screenshots">Screenshots</a> ·
|
||||
<a href="#download">Download</a> ·
|
||||
<a href="CONTRIBUTING.md">Contributing</a> ·
|
||||
<a href="LICENSE">License</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/readme-showcase.webp" alt="Plezy mobile screenshots" width="900" />
|
||||
</p>
|
||||
|
||||
## Download
|
||||
|
||||
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
|
||||
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
|
||||
<a href='https://www.amazon.com/gp/product/B0GK65CVS1'><img height='60' alt='Available at the Amazon App Store' src='./assets/amazon-badge.png'/></a>
|
||||
|
||||
| Platform | Download |
|
||||
| --- | --- |
|
||||
| Windows | [Installer (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe) · [Portable x64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-x64-portable.7z) · [Portable arm64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-arm64-portable.7z) |
|
||||
| macOS | [DMG (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg) |
|
||||
| Linux x64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz) |
|
||||
| Linux arm64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.tar.gz) |
|
||||
|
||||
Package managers:
|
||||
|
||||
- [Nix](https://search.nixos.org/packages?channel=unstable&query=plezy) - Community package by [@mio-19](https://github.com/mio-19) and [@MiniHarinn](https://github.com/MiniHarinn)
|
||||
- **Homebrew** (macOS):
|
||||
```bash
|
||||
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):
|
||||
```bash
|
||||
yay -S plezy-bin
|
||||
```
|
||||
- **WinGet** (Windows):
|
||||
```bash
|
||||
winget install edde746.Plezy
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
### <img src="assets/readme_icons/browse.svg" height="20" alt="" align="center" /> Browse & Discover
|
||||
- Libraries, collections, and playlists
|
||||
- Discover hub — Continue Watching, Next Up, trending, and recommendations
|
||||
- Cross-server search
|
||||
- Filtering, sorting, and alphabetical jump navigation
|
||||
- Extras — trailers, deleted scenes, behind-the-scenes
|
||||
|
||||
### <img src="assets/readme_icons/playback.svg" height="20" alt="" align="center" /> Playback
|
||||
- Wide codec support (HEVC, AV1, VP9, and more)
|
||||
- HDR and Dolby Vision[^1]
|
||||
- Full ASS/SSA subtitles with customizable styling
|
||||
- Online subtitle search & download[^2]
|
||||
- Audio & subtitle choices remembered per title
|
||||
- Progress sync and resume
|
||||
- Auto-play next episode with skip intro / skip credits
|
||||
- Chapter navigation with thumbnail scrub previews
|
||||
- Playback speed, audio sync offset, sleep timer
|
||||
- Ambient lighting and GLSL shader presets[^3]
|
||||
- Picture-in-Picture[^4]
|
||||
- Refresh-rate matching[^5]
|
||||
- External player launch (VLC, MX Player, etc.)
|
||||
|
||||
### <img src="assets/readme_icons/live-tv.svg" height="20" alt="" align="center" /> Live TV & DVR
|
||||
- Live TV channel browsing with favorites
|
||||
- DVR support with EPG guide, recording rules, and scheduled recordings[^2]
|
||||
- Multi-server Live TV support where available
|
||||
|
||||
### <img src="assets/readme_icons/downloads.svg" height="20" alt="" align="center" /> Downloads & Offline
|
||||
- Download media for offline viewing
|
||||
- Background queue with pause / resume
|
||||
- Sync rules for automatic downloads
|
||||
- Offline browsing with watch state sync-back on reconnect
|
||||
|
||||
### <img src="assets/readme_icons/watch-together.svg" height="20" alt="" align="center" /> Watch Together
|
||||
- Synchronized playback with friends
|
||||
- Real-time play / pause / seek sync
|
||||
|
||||
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
|
||||
- Discord Rich Presence[^6]
|
||||
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
|
||||
- Plezy Remote — control desktop and TV from mobile
|
||||
- Watch Next row
|
||||
|
||||
### <img src="assets/readme_icons/customization.svg" height="20" alt="" align="center" /> Platform & Customization
|
||||
- Desktop, mobile, and TV — full D-pad, keyboard, and gamepad support
|
||||
- Customizable keyboard shortcuts[^6]
|
||||
- Metadata and artwork editing
|
||||
- Settings import/export
|
||||
- Localized in English plus 14 translations
|
||||
|
||||
[^1]: Not available on Linux.
|
||||
[^2]: Plex only.
|
||||
[^3]: Not available on iOS or tvOS.
|
||||
[^4]: Android, iOS, and macOS.
|
||||
[^5]: Windows, Android, and tvOS.
|
||||
[^6]: Desktop only.
|
||||
|
||||
## Building from Source
|
||||
|
||||
### Prerequisites
|
||||
- Flutter SDK 3.38.4+
|
||||
- A Plex account or Jellyfin server with user credentials
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
git clone https://github.com/edde746/plezy.git
|
||||
cd plezy
|
||||
flutter pub get
|
||||
scripts/codegen.sh
|
||||
flutter run
|
||||
```
|
||||
|
||||
### Code Generation
|
||||
|
||||
After modifying model classes or other generated sources:
|
||||
|
||||
```bash
|
||||
scripts/codegen.sh
|
||||
```
|
||||
|
||||
After modifying translations:
|
||||
|
||||
```bash
|
||||
dart run slang
|
||||
```
|
||||
|
||||
### Local Checks
|
||||
|
||||
```bash
|
||||
scripts/ci_checks.sh
|
||||
```
|
||||
|
||||
To install the same pre-commit checks locally:
|
||||
|
||||
```bash
|
||||
scripts/setup_hooks.sh
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for development workflow, formatting, tests, and translation guidelines.
|
||||
|
||||
## License
|
||||
|
||||
Plezy is licensed under [GPL-3.0](LICENSE).
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
- Built with [Flutter](https://flutter.dev)
|
||||
- Supports [Plex Media Server](https://www.plex.tv) and [Jellyfin](https://jellyfin.org)
|
||||
- Playback powered by [mpv](https://mpv.io), [MPVKit](https://github.com/mpvkit/MPVKit), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), [libass-android](https://github.com/peerless2012/libass-android), and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
|
||||
@@ -1,84 +0,0 @@
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
analyzer:
|
||||
exclude:
|
||||
- "**/*.g.dart"
|
||||
- "**/*.freezed.dart"
|
||||
plugins:
|
||||
- dart_code_linter
|
||||
|
||||
linter:
|
||||
rules:
|
||||
unawaited_futures: true
|
||||
cancel_subscriptions: true
|
||||
close_sinks: true
|
||||
use_super_parameters: true
|
||||
prefer_final_locals: true
|
||||
prefer_final_in_for_each: true
|
||||
avoid_print: true
|
||||
|
||||
dart_code_linter:
|
||||
rules-exclude:
|
||||
- "test/**"
|
||||
metrics-exclude:
|
||||
- "test/**"
|
||||
|
||||
extends:
|
||||
- package:dart_code_linter/presets/recommended.yaml
|
||||
|
||||
rules:
|
||||
# --- Flutter rules (on top of recommended) ---
|
||||
- avoid-border-all
|
||||
- avoid-shrink-wrap-in-lists
|
||||
- avoid-expanded-as-spacer
|
||||
- avoid-wrapping-in-padding
|
||||
- prefer-const-border-radius
|
||||
- prefer-correct-edge-insets-constructor
|
||||
- prefer-define-hero-tag
|
||||
- use-setstate-synchronously
|
||||
|
||||
# --- Additional useful Dart rules ---
|
||||
- avoid-cascade-after-if-null
|
||||
- avoid-collection-methods-with-unrelated-types
|
||||
- avoid-unnecessary-type-assertions
|
||||
- avoid-unrelated-type-assertions
|
||||
- double-literal-format
|
||||
- prefer-first
|
||||
- prefer-last
|
||||
- prefer-enums-by-name
|
||||
- prefer-commenting-analyzer-ignores
|
||||
|
||||
# --- Disable noisy rules from recommended preset ---
|
||||
- no-magic-number: false
|
||||
- avoid-dynamic: false
|
||||
- format-comment: false
|
||||
- newline-before-return: false
|
||||
- prefer-moving-to-variable: false
|
||||
- member-ordering: false
|
||||
- prefer-extracting-callbacks: false
|
||||
- avoid-returning-widgets: false
|
||||
- no-equal-arguments: false
|
||||
- avoid-passing-async-when-sync-expected: false
|
||||
- avoid-redundant-async: false
|
||||
- no-empty-block: false
|
||||
- prefer-trailing-comma: false
|
||||
- avoid-non-null-assertion: false
|
||||
- prefer-conditional-expressions: false
|
||||
|
||||
metrics:
|
||||
cyclomatic-complexity: 70
|
||||
halstead-volume: 16000
|
||||
maintainability-index: 8
|
||||
maximum-nesting-level: 7
|
||||
number-of-parameters: 25
|
||||
number-of-methods: 150
|
||||
source-lines-of-code: 500
|
||||
|
||||
anti-patterns:
|
||||
- long-method:
|
||||
lines-of-code: 500
|
||||
- long-parameter-list:
|
||||
number-of-parameters: 25
|
||||
|
||||
formatter:
|
||||
page_width: 120
|
||||
@@ -1,11 +0,0 @@
|
||||
/.gradle
|
||||
/captures/
|
||||
/local.properties
|
||||
GeneratedPluginRegistrant.java
|
||||
.cxx/
|
||||
|
||||
# Remember to never publicly share your keystore.
|
||||
# See https://flutter.dev/to/reference-keystore
|
||||
key.properties
|
||||
**/*.keystore
|
||||
**/*.jks
|
||||
@@ -1,10 +0,0 @@
|
||||
# Autogenerated by fastlane
|
||||
#
|
||||
# Ensure this file is checked in to source control!
|
||||
|
||||
source "https://rubygems.org"
|
||||
|
||||
gem 'fastlane'
|
||||
|
||||
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
|
||||
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
||||
@@ -1,244 +0,0 @@
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
CFPropertyList (3.0.8)
|
||||
abbrev (0.1.2)
|
||||
addressable (2.8.8)
|
||||
public_suffix (>= 2.0.2, < 8.0)
|
||||
artifactory (3.0.17)
|
||||
atomos (0.1.3)
|
||||
aws-eventstream (1.4.0)
|
||||
aws-partitions (1.1215.0)
|
||||
aws-sdk-core (3.242.0)
|
||||
aws-eventstream (~> 1, >= 1.3.0)
|
||||
aws-partitions (~> 1, >= 1.992.0)
|
||||
aws-sigv4 (~> 1.9)
|
||||
base64
|
||||
bigdecimal
|
||||
jmespath (~> 1, >= 1.6.1)
|
||||
logger
|
||||
aws-sdk-kms (1.122.0)
|
||||
aws-sdk-core (~> 3, >= 3.241.4)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sdk-s3 (1.213.0)
|
||||
aws-sdk-core (~> 3, >= 3.241.4)
|
||||
aws-sdk-kms (~> 1)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sigv4 (1.12.1)
|
||||
aws-eventstream (~> 1, >= 1.0.2)
|
||||
babosa (1.0.4)
|
||||
base64 (0.2.0)
|
||||
benchmark (0.5.0)
|
||||
bigdecimal (4.0.1)
|
||||
claide (1.1.0)
|
||||
colored (1.2)
|
||||
colored2 (3.1.2)
|
||||
commander (4.6.0)
|
||||
highline (~> 2.0.0)
|
||||
csv (3.3.5)
|
||||
declarative (0.0.20)
|
||||
digest-crc (0.7.0)
|
||||
rake (>= 12.0.0, < 14.0.0)
|
||||
domain_name (0.6.20240107)
|
||||
dotenv (2.8.1)
|
||||
emoji_regex (3.2.3)
|
||||
excon (0.112.0)
|
||||
faraday (1.10.5)
|
||||
faraday-em_http (~> 1.0)
|
||||
faraday-em_synchrony (~> 1.0)
|
||||
faraday-excon (~> 1.1)
|
||||
faraday-httpclient (~> 1.0)
|
||||
faraday-multipart (~> 1.0)
|
||||
faraday-net_http (~> 1.0)
|
||||
faraday-net_http_persistent (~> 1.0)
|
||||
faraday-patron (~> 1.0)
|
||||
faraday-rack (~> 1.0)
|
||||
faraday-retry (~> 1.0)
|
||||
ruby2_keywords (>= 0.0.4)
|
||||
faraday-cookie_jar (0.0.8)
|
||||
faraday (>= 0.8.0)
|
||||
http-cookie (>= 1.0.0)
|
||||
faraday-em_http (1.0.0)
|
||||
faraday-em_synchrony (1.0.1)
|
||||
faraday-excon (1.1.0)
|
||||
faraday-httpclient (1.0.1)
|
||||
faraday-multipart (1.2.0)
|
||||
multipart-post (~> 2.0)
|
||||
faraday-net_http (1.0.2)
|
||||
faraday-net_http_persistent (1.2.0)
|
||||
faraday-patron (1.0.0)
|
||||
faraday-rack (1.0.0)
|
||||
faraday-retry (1.0.3)
|
||||
faraday_middleware (1.2.1)
|
||||
faraday (~> 1.0)
|
||||
fastimage (2.4.0)
|
||||
fastlane (2.232.1)
|
||||
CFPropertyList (>= 2.3, < 4.0.0)
|
||||
abbrev (~> 0.1.2)
|
||||
addressable (>= 2.8, < 3.0.0)
|
||||
artifactory (~> 3.0)
|
||||
aws-sdk-s3 (~> 1.197)
|
||||
babosa (>= 1.0.3, < 2.0.0)
|
||||
base64 (~> 0.2.0)
|
||||
benchmark (>= 0.1.0)
|
||||
bundler (>= 1.17.3, < 5.0.0)
|
||||
colored (~> 1.2)
|
||||
commander (~> 4.6)
|
||||
csv (~> 3.3)
|
||||
dotenv (>= 2.1.1, < 3.0.0)
|
||||
emoji_regex (>= 0.1, < 4.0)
|
||||
excon (>= 0.71.0, < 1.0.0)
|
||||
faraday (~> 1.0)
|
||||
faraday-cookie_jar (~> 0.0.6)
|
||||
faraday_middleware (~> 1.0)
|
||||
fastimage (>= 2.1.0, < 3.0.0)
|
||||
fastlane-sirp (>= 1.0.0)
|
||||
gh_inspector (>= 1.1.2, < 2.0.0)
|
||||
google-apis-androidpublisher_v3 (~> 0.3)
|
||||
google-apis-playcustomapp_v1 (~> 0.1)
|
||||
google-cloud-env (>= 1.6.0, <= 2.1.1)
|
||||
google-cloud-storage (~> 1.31)
|
||||
highline (~> 2.0)
|
||||
http-cookie (~> 1.0.5)
|
||||
json (< 3.0.0)
|
||||
jwt (>= 2.1.0, < 3)
|
||||
logger (>= 1.6, < 2.0)
|
||||
mini_magick (>= 4.9.4, < 5.0.0)
|
||||
multipart-post (>= 2.0.0, < 3.0.0)
|
||||
mutex_m (~> 0.3.0)
|
||||
naturally (~> 2.2)
|
||||
nkf (~> 0.2.0)
|
||||
optparse (>= 0.1.1, < 1.0.0)
|
||||
ostruct (>= 0.1.0)
|
||||
plist (>= 3.1.0, < 4.0.0)
|
||||
rubyzip (>= 2.0.0, < 3.0.0)
|
||||
security (= 0.1.5)
|
||||
simctl (~> 1.6.3)
|
||||
terminal-notifier (>= 2.0.0, < 3.0.0)
|
||||
terminal-table (~> 3)
|
||||
tty-screen (>= 0.6.3, < 1.0.0)
|
||||
tty-spinner (>= 0.8.0, < 1.0.0)
|
||||
word_wrap (~> 1.0.0)
|
||||
xcodeproj (>= 1.13.0, < 2.0.0)
|
||||
xcpretty (~> 0.4.1)
|
||||
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
|
||||
fastlane-plugin-amazon_appstore (1.4.0)
|
||||
faraday (~> 1.0)
|
||||
faraday_middleware (~> 1.0)
|
||||
fastlane-sirp (1.0.0)
|
||||
sysrandom (~> 1.0)
|
||||
gh_inspector (1.1.3)
|
||||
google-apis-androidpublisher_v3 (0.96.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-core (0.18.0)
|
||||
addressable (~> 2.5, >= 2.5.1)
|
||||
googleauth (~> 1.9)
|
||||
httpclient (>= 2.8.3, < 3.a)
|
||||
mini_mime (~> 1.0)
|
||||
mutex_m
|
||||
representable (~> 3.0)
|
||||
retriable (>= 2.0, < 4.a)
|
||||
google-apis-iamcredentials_v1 (0.26.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-playcustomapp_v1 (0.17.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-apis-storage_v1 (0.60.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-cloud-core (1.8.0)
|
||||
google-cloud-env (>= 1.0, < 3.a)
|
||||
google-cloud-errors (~> 1.0)
|
||||
google-cloud-env (2.1.1)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-errors (1.5.0)
|
||||
google-cloud-storage (1.58.0)
|
||||
addressable (~> 2.8)
|
||||
digest-crc (~> 0.4)
|
||||
google-apis-core (>= 0.18, < 2)
|
||||
google-apis-iamcredentials_v1 (~> 0.18)
|
||||
google-apis-storage_v1 (>= 0.42)
|
||||
google-cloud-core (~> 1.6)
|
||||
googleauth (~> 1.9)
|
||||
mini_mime (~> 1.0)
|
||||
googleauth (1.11.2)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-env (~> 2.1)
|
||||
jwt (>= 1.4, < 3.0)
|
||||
multi_json (~> 1.11)
|
||||
os (>= 0.9, < 2.0)
|
||||
signet (>= 0.16, < 2.a)
|
||||
highline (2.0.3)
|
||||
http-cookie (1.0.8)
|
||||
domain_name (~> 0.5)
|
||||
httpclient (2.9.0)
|
||||
mutex_m
|
||||
jmespath (1.6.2)
|
||||
json (2.18.1)
|
||||
jwt (2.10.2)
|
||||
base64
|
||||
logger (1.7.0)
|
||||
mini_magick (4.13.2)
|
||||
mini_mime (1.1.5)
|
||||
multi_json (1.19.1)
|
||||
multipart-post (2.4.1)
|
||||
mutex_m (0.3.0)
|
||||
nanaimo (0.4.0)
|
||||
naturally (2.3.0)
|
||||
nkf (0.2.0)
|
||||
optparse (0.8.1)
|
||||
os (1.1.4)
|
||||
ostruct (0.6.3)
|
||||
plist (3.7.2)
|
||||
public_suffix (7.0.2)
|
||||
rake (13.3.1)
|
||||
representable (3.2.0)
|
||||
declarative (< 0.1.0)
|
||||
trailblazer-option (>= 0.1.1, < 0.2.0)
|
||||
uber (< 0.2.0)
|
||||
retriable (3.1.2)
|
||||
rexml (3.4.4)
|
||||
rouge (3.28.0)
|
||||
ruby2_keywords (0.0.5)
|
||||
rubyzip (2.4.1)
|
||||
security (0.1.5)
|
||||
signet (0.21.0)
|
||||
addressable (~> 2.8)
|
||||
faraday (>= 0.17.5, < 3.a)
|
||||
jwt (>= 1.5, < 4.0)
|
||||
multi_json (~> 1.10)
|
||||
simctl (1.6.10)
|
||||
CFPropertyList
|
||||
naturally
|
||||
sysrandom (1.0.5)
|
||||
terminal-notifier (2.0.0)
|
||||
terminal-table (3.0.2)
|
||||
unicode-display_width (>= 1.1.1, < 3)
|
||||
trailblazer-option (0.1.2)
|
||||
tty-cursor (0.7.1)
|
||||
tty-screen (0.8.2)
|
||||
tty-spinner (0.9.3)
|
||||
tty-cursor (~> 0.7)
|
||||
uber (0.1.0)
|
||||
unicode-display_width (2.6.0)
|
||||
word_wrap (1.0.0)
|
||||
xcodeproj (1.27.0)
|
||||
CFPropertyList (>= 2.3.3, < 4.0)
|
||||
atomos (~> 0.1.3)
|
||||
claide (>= 1.0.2, < 2.0)
|
||||
colored2 (~> 3.1)
|
||||
nanaimo (~> 0.4.0)
|
||||
rexml (>= 3.3.6, < 4.0)
|
||||
xcpretty (0.4.1)
|
||||
rouge (~> 3.28.0)
|
||||
xcpretty-travis-formatter (1.0.1)
|
||||
xcpretty (~> 0.2, >= 0.0.7)
|
||||
|
||||
PLATFORMS
|
||||
arm64-darwin-25
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
fastlane
|
||||
fastlane-plugin-amazon_appstore
|
||||
|
||||
BUNDLED WITH
|
||||
2.7.2
|
||||
@@ -1,216 +0,0 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
val mpvVersion = "v1.0.7"
|
||||
val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile
|
||||
val mpvAar = "libmpv-release.aar"
|
||||
|
||||
val downloadLibmpv by tasks.registering {
|
||||
val stamp = File(mpvDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == mpvVersion }
|
||||
doLast {
|
||||
mpvDir.mkdirs()
|
||||
val url = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
|
||||
exec { commandLine("curl", "-sfL", url, "-o", File(mpvDir, mpvAar).absolutePath) }
|
||||
stamp.writeText(mpvVersion)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract libc++_shared.so from the libmpv AAR so the app source set can package
|
||||
// it with top merge priority (see packaging { jniLibs } and sourceSets below).
|
||||
val extractMpvLibcxx by tasks.registering {
|
||||
dependsOn(downloadLibmpv)
|
||||
val aar = File(mpvDir, mpvAar)
|
||||
val outDir = File(mpvDir, "libcxx")
|
||||
inputs.file(aar)
|
||||
outputs.dir(outDir)
|
||||
doLast {
|
||||
outDir.deleteRecursively() // drop stale ABIs from a previous AAR version
|
||||
outDir.mkdirs()
|
||||
exec {
|
||||
commandLine(
|
||||
"unzip",
|
||||
"-q",
|
||||
"-o",
|
||||
aar.absolutePath,
|
||||
"jni/*/libc++_shared.so",
|
||||
"-d",
|
||||
outDir.absolutePath
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val doviVersion = "2.3.1"
|
||||
val doviDir = layout.buildDirectory.dir("libdovi").get().asFile
|
||||
val doviAbis = mapOf(
|
||||
"arm64-v8a" to "aarch64-linux-android",
|
||||
"armeabi-v7a" to "armv7-linux-androideabi",
|
||||
"x86" to "i686-linux-android",
|
||||
"x86_64" to "x86_64-linux-android"
|
||||
)
|
||||
|
||||
val downloadLibdovi by tasks.registering {
|
||||
val stamp = File(doviDir, ".version")
|
||||
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == doviVersion }
|
||||
doLast {
|
||||
doviDir.mkdirs()
|
||||
val baseUrl = "https://github.com/edde746/libdovi-builds/releases/download/v$doviVersion"
|
||||
doviAbis.forEach { (abi, triple) ->
|
||||
val archive = File(doviDir, "$triple.tar.gz")
|
||||
exec { commandLine("curl", "-sfL", "$baseUrl/libdovi-$triple.tar.gz", "-o", archive.absolutePath) }
|
||||
val outDir = File(doviDir, "$abi/lib")
|
||||
outDir.mkdirs()
|
||||
exec { commandLine("tar", "-xzf", archive.absolutePath, "-C", outDir.absolutePath) }
|
||||
archive.delete()
|
||||
}
|
||||
stamp.writeText(doviVersion)
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.edde746.plezy"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
|
||||
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
|
||||
versionName = flutter.versionName
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
arguments += listOf(
|
||||
"-DDOVI_ENABLE_LIBDOVI=ON",
|
||||
"-DDOVI_LIBDOVI_PREBUILT_ROOT=${doviDir.absolutePath}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (System.getenv("AMAZON") != null) {
|
||||
versionCode = (flutter.versionCode ?: 0) + 3000
|
||||
ndk {
|
||||
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path = file("src/main/cpp/CMakeLists.txt")
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
val keystoreProperties = Properties()
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
|
||||
keyAlias = keystoreProperties["keyAlias"] as String
|
||||
keyPassword = keystoreProperties["keyPassword"] as String
|
||||
storeFile = file(keystoreProperties["storeFile"] as String)
|
||||
storePassword = keystoreProperties["storePassword"] as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// Only use release signing if key.properties exists (not in CI/CD)
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
// If key.properties doesn't exist, it will use debug signing for CI builds
|
||||
ndk {
|
||||
debugSymbolLevel = "FULL"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// pickFirst only suppresses the duplicate libc++ merge error; the
|
||||
// sourceSets rule below makes libmpv's newer runtime win for
|
||||
// std::from_chars<float>, while older native consumers remain ABI-compatible.
|
||||
pickFirsts.add("lib/*/libc++_shared.so")
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
|
||||
// order cannot accidentally select the older libc++ copy.
|
||||
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
|
||||
dependsOn(downloadLibdovi)
|
||||
}
|
||||
|
||||
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
|
||||
dependsOn(downloadLibmpv, extractMpvLibcxx)
|
||||
}
|
||||
// Gradle snapshots jniLibs source dirs before task execution; this keeps the
|
||||
// extracted libmpv libc++ directory present during input discovery.
|
||||
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
|
||||
dependsOn(extractMpvLibcxx)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(files(File(mpvDir, mpvAar)))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
|
||||
// Android TV Watch Next integration
|
||||
implementation("androidx.tvprovider:tvprovider:1.0.0")
|
||||
|
||||
// Media3 ExoPlayer for Android
|
||||
implementation("androidx.media3:media3-exoplayer:1.9.2")
|
||||
implementation("androidx.media3:media3-exoplayer-hls:1.9.2")
|
||||
implementation("androidx.media3:media3-ui:1.9.2")
|
||||
implementation("androidx.media3:media3-common:1.9.2")
|
||||
|
||||
// Cronet for HTTP/2 multiplexing + better connection management
|
||||
implementation("androidx.media3:media3-datasource-cronet:1.9.2")
|
||||
implementation("org.chromium.net:cronet-embedded:143.7445.0")
|
||||
|
||||
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
|
||||
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
|
||||
|
||||
// Keeping libass in-project lets its static core share the app's native
|
||||
// packaging rules.
|
||||
implementation(project(":libass"))
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
// Real android.util.* implementations for tests exercising media3 classes
|
||||
// (MatroskaExtractor uses SparseArray, which is a no-op stub on plain JVM)
|
||||
testImplementation("org.robolectric:robolectric:4.15.1")
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- The INTERNET permission is required for development. Specifically,
|
||||
the Flutter tool needs it to communicate with the running application
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
</manifest>
|
||||
@@ -1,121 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- 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"/>
|
||||
|
||||
<!-- Explicitly remove media permissions that media_kit may add -->
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" tools:node="remove" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
|
||||
<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"/>
|
||||
<!-- 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
|
||||
android:label="Plezy"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:banner="@drawable/tv_banner"
|
||||
android:appCategory="video"
|
||||
android:largeHeap="true"
|
||||
android:usesCleartextTraffic="true">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/LaunchTheme"
|
||||
android:supportsPictureInPicture="true"
|
||||
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"
|
||||
/>
|
||||
<meta-data
|
||||
android:name="flutter_deeplinking_enabled"
|
||||
android:value="false" />
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
<!-- 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 -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<category android:name="android.intent.category.DEFAULT"/>
|
||||
<category android:name="android.intent.category.BROWSABLE"/>
|
||||
<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"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_provider_paths" />
|
||||
</provider>
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
android:name="flutterEmbedding"
|
||||
android:value="2" />
|
||||
</application>
|
||||
<!-- Required to query activities that can process text, see:
|
||||
https://developer.android.com/training/package-visibility and
|
||||
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
|
||||
|
||||
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
||||
<data android:mimeType="text/plain"/>
|
||||
</intent>
|
||||
<!-- Required for url_launcher to open HTTPS URLs -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="https" />
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:scheme="http" />
|
||||
</intent>
|
||||
<!-- Required to resolve external video player apps on Android 11+ -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<data android:mimeType="video/*" />
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
@@ -1,19 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.22.1)
|
||||
project(dovi_bridge)
|
||||
|
||||
option(DOVI_ENABLE_LIBDOVI "Link real libdovi" ON)
|
||||
set(DOVI_LIBDOVI_PREBUILT_ROOT "" CACHE PATH "Path to prebuilt libdovi")
|
||||
|
||||
add_library(dovi_bridge SHARED dovi_bridge.cpp)
|
||||
|
||||
if(DOVI_ENABLE_LIBDOVI)
|
||||
add_library(dovi_static STATIC IMPORTED)
|
||||
set_target_properties(dovi_static PROPERTIES
|
||||
IMPORTED_LOCATION "${DOVI_LIBDOVI_PREBUILT_ROOT}/${ANDROID_ABI}/lib/libdovi.a")
|
||||
target_compile_definitions(dovi_bridge PRIVATE DOVI_REAL_LINKED=1)
|
||||
target_include_directories(dovi_bridge PRIVATE ${CMAKE_SOURCE_DIR}/include)
|
||||
target_link_libraries(dovi_bridge dovi_static log)
|
||||
else()
|
||||
target_compile_definitions(dovi_bridge PRIVATE DOVI_REAL_LINKED=0)
|
||||
target_link_libraries(dovi_bridge log)
|
||||
endif()
|
||||
@@ -1,146 +0,0 @@
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
#define TAG "DoviBridge"
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
||||
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
|
||||
|
||||
#if DOVI_REAL_LINKED
|
||||
#include "include/libdovi/rpu_parser.h"
|
||||
#endif
|
||||
|
||||
static const char* BRIDGE_VERSION = "1.0.0";
|
||||
static constexpr jint CONVERT_FAILED = -1;
|
||||
static constexpr jint DESTINATION_TOO_SMALL = -2;
|
||||
static constexpr jint MAX_RPU_INPUT_SIZE = 8192;
|
||||
static constexpr size_t MAX_RPU_OUTPUT_SIZE = 16384;
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_DoviBridge_nativeConvertDv7RpuToDv81(
|
||||
JNIEnv* env, jclass, jbyteArray payload, jint payload_offset, jint payload_length, jbyteArray output,
|
||||
jint output_offset, jint output_capacity, jint mode) {
|
||||
#if !DOVI_REAL_LINKED
|
||||
return CONVERT_FAILED;
|
||||
#else
|
||||
if (payload == nullptr || output == nullptr) return CONVERT_FAILED;
|
||||
if (payload_offset < 0 || payload_length <= 0 || output_offset < 0 || output_capacity < 0) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
const jsize payload_array_len = env->GetArrayLength(payload);
|
||||
const jsize output_array_len = env->GetArrayLength(output);
|
||||
if (payload_offset > payload_array_len || payload_length > payload_array_len - payload_offset) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
if (output_offset > output_array_len) return DESTINATION_TOO_SMALL;
|
||||
|
||||
const jsize logical_output_len = output_capacity < output_array_len ? output_capacity : output_array_len;
|
||||
if (output_offset > logical_output_len) return DESTINATION_TOO_SMALL;
|
||||
|
||||
// Valid RPU NALs are typically <2 KiB; reject unreasonable sizes
|
||||
if (payload_length > MAX_RPU_INPUT_SIZE) {
|
||||
LOGW("RPU payload too large (%d bytes), skipping", payload_length);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
// Copy to native heap so libdovi never touches JVM heap memory.
|
||||
// Do not use GetPrimitiveArrayCritical here: it can block concurrent GC
|
||||
// compaction during sustained playback. A thread-local scratch buffer avoids
|
||||
// per-frame heap churn while keeping libdovi away from JVM heap memory.
|
||||
thread_local std::vector<uint8_t> scratch;
|
||||
try {
|
||||
scratch.resize(static_cast<size_t>(payload_length));
|
||||
} catch (...) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
env->GetByteArrayRegion(payload, payload_offset, payload_length, reinterpret_cast<jbyte*>(scratch.data()));
|
||||
if (env->ExceptionCheck()) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
// Try dovi_parse_unspec62_nalu first (handles escaped NALs), fallback to dovi_parse_rpu
|
||||
const auto rpu_len = static_cast<size_t>(payload_length);
|
||||
DoviRpuOpaque* rpu = dovi_parse_unspec62_nalu(scratch.data(), rpu_len);
|
||||
|
||||
if (rpu == nullptr) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
const char* err = dovi_rpu_get_error(rpu);
|
||||
if (err != nullptr) {
|
||||
// Fallback: try dovi_parse_rpu (raw RPU without NAL framing)
|
||||
dovi_rpu_free(rpu);
|
||||
rpu = dovi_parse_rpu(scratch.data(), rpu_len);
|
||||
if (rpu == nullptr) {
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
if (err != nullptr) {
|
||||
LOGW("RPU parse failed: %s", err);
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
// Mode 2 matches Kodi's P8.1 compatibility path and sets luma/chroma curves to no-op.
|
||||
int32_t ret = dovi_convert_rpu_with_mode(rpu, static_cast<uint8_t>(mode));
|
||||
if (ret != 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
LOGW("RPU conversion failed (mode %d): %s", mode, err ? err : "unknown");
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
// Write back as UNSPEC62 NAL
|
||||
const DoviData* out = dovi_write_unspec62_nalu(rpu);
|
||||
if (out == nullptr || out->data == nullptr || out->len == 0) {
|
||||
err = dovi_rpu_get_error(rpu);
|
||||
LOGW("RPU write failed: %s", err ? err : "unknown");
|
||||
if (out != nullptr) dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
if (out->len > MAX_RPU_OUTPUT_SIZE) {
|
||||
LOGW("RPU output unexpectedly large (%zu bytes), discarding", out->len);
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return CONVERT_FAILED;
|
||||
}
|
||||
|
||||
const auto writable = static_cast<size_t>(logical_output_len - output_offset);
|
||||
if (out->len > writable) {
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
return DESTINATION_TOO_SMALL;
|
||||
}
|
||||
|
||||
env->SetByteArrayRegion(
|
||||
output, output_offset, static_cast<jsize>(out->len), reinterpret_cast<const jbyte*>(out->data));
|
||||
const bool write_failed = env->ExceptionCheck();
|
||||
const auto written = static_cast<jint>(out->len);
|
||||
|
||||
dovi_data_free(out);
|
||||
dovi_rpu_free(rpu);
|
||||
|
||||
return write_failed ? CONVERT_FAILED : written;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeIsConversionPathReady(JNIEnv*, jclass) {
|
||||
#if DOVI_REAL_LINKED
|
||||
return JNI_TRUE;
|
||||
#else
|
||||
return JNI_FALSE;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jstring JNICALL
|
||||
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeGetBridgeVersion(JNIEnv* env, jclass) {
|
||||
return env->NewStringUTF(BRIDGE_VERSION);
|
||||
}
|
||||
@@ -1,747 +0,0 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#ifndef DOVI_H
|
||||
#define DOVI_H
|
||||
|
||||
|
||||
#define RPU_PARSER_MAJOR 3
|
||||
#define RPU_PARSER_MINOR 3
|
||||
#define RPU_PARSER_PATCH 2
|
||||
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define DoviNUM_COMPONENTS 3
|
||||
|
||||
/**
|
||||
* Opaque Dolby Vision RPU.
|
||||
*
|
||||
* Use dovi_rpu_free to free.
|
||||
* It should be freed regardless of whether or not an error occurred.
|
||||
*/
|
||||
typedef struct DoviRpuOpaque DoviRpuOpaque;
|
||||
|
||||
/**
|
||||
* Struct representing a data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the data buffer
|
||||
*/
|
||||
const uint8_t *data;
|
||||
/**
|
||||
* Data buffer size
|
||||
*/
|
||||
size_t len;
|
||||
} DoviData;
|
||||
|
||||
/**
|
||||
* C struct for rpu_data_header()
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Profile guessed from the values in the header
|
||||
*/
|
||||
uint8_t guessed_profile;
|
||||
/**
|
||||
* Enhancement layer type (FEL or MEL) if the RPU is profile 7
|
||||
* null pointer if not profile 7
|
||||
*/
|
||||
const char *el_type;
|
||||
/**
|
||||
* Deprecated since 3.2.0
|
||||
* The field is not actually part of the RPU header
|
||||
*/
|
||||
uint8_t rpu_nal_prefix;
|
||||
uint8_t rpu_type;
|
||||
uint16_t rpu_format;
|
||||
uint8_t vdr_rpu_profile;
|
||||
uint8_t vdr_rpu_level;
|
||||
bool vdr_seq_info_present_flag;
|
||||
bool chroma_resampling_explicit_filter_flag;
|
||||
uint8_t coefficient_data_type;
|
||||
uint64_t coefficient_log2_denom;
|
||||
uint8_t vdr_rpu_normalized_idc;
|
||||
bool bl_video_full_range_flag;
|
||||
uint64_t bl_bit_depth_minus8;
|
||||
uint64_t el_bit_depth_minus8;
|
||||
uint64_t vdr_bit_depth_minus8;
|
||||
bool spatial_resampling_filter_flag;
|
||||
uint8_t reserved_zero_3bits;
|
||||
bool el_spatial_resampling_filter_flag;
|
||||
bool disable_residual_flag;
|
||||
bool vdr_dm_metadata_present_flag;
|
||||
bool use_prev_vdr_rpu_flag;
|
||||
uint64_t prev_vdr_rpu_id;
|
||||
} DoviRpuDataHeader;
|
||||
|
||||
/**
|
||||
* Struct representing a data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the data buffer. Can be null if length is zero.
|
||||
*/
|
||||
const uint16_t *data;
|
||||
/**
|
||||
* Data buffer size
|
||||
*/
|
||||
size_t len;
|
||||
} DoviU16Data;
|
||||
|
||||
/**
|
||||
* Struct representing a data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the data buffer. Can be null if length is zero.
|
||||
*/
|
||||
const uint64_t *data;
|
||||
/**
|
||||
* Data buffer size
|
||||
*/
|
||||
size_t len;
|
||||
} DoviU64Data;
|
||||
|
||||
/**
|
||||
* Struct representing a data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the data buffer
|
||||
*/
|
||||
const int64_t *data;
|
||||
/**
|
||||
* Data buffer size
|
||||
*/
|
||||
size_t len;
|
||||
} DoviI64Data;
|
||||
|
||||
/**
|
||||
* Struct representing a 2D data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of Data structs
|
||||
*/
|
||||
const DoviI64Data *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviI64Data2D;
|
||||
|
||||
/**
|
||||
* Struct representing a 2D data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of Data structs
|
||||
*/
|
||||
const DoviU64Data *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviU64Data2D;
|
||||
|
||||
typedef struct {
|
||||
DoviU64Data poly_order_minus1;
|
||||
DoviData linear_interp_flag;
|
||||
DoviI64Data2D poly_coef_int;
|
||||
DoviU64Data2D poly_coef;
|
||||
} DoviPolynomialCurve;
|
||||
|
||||
/**
|
||||
* Struct representing a 3D data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of I64Data2D structs
|
||||
*/
|
||||
const DoviI64Data2D *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviI64Data3D;
|
||||
|
||||
/**
|
||||
* Struct representing a 3D data buffer
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of U64Data2D structs
|
||||
*/
|
||||
const DoviU64Data2D *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviU64Data3D;
|
||||
|
||||
typedef struct {
|
||||
DoviData mmr_order_minus1;
|
||||
DoviI64Data mmr_constant_int;
|
||||
DoviU64Data mmr_constant;
|
||||
DoviI64Data3D mmr_coef_int;
|
||||
DoviU64Data3D mmr_coef;
|
||||
} DoviMMRCurve;
|
||||
|
||||
typedef struct {
|
||||
/**
|
||||
* [2, 9]
|
||||
*/
|
||||
uint64_t num_pivots_minus2;
|
||||
DoviU16Data pivots;
|
||||
/**
|
||||
* Consistent for a component
|
||||
* Luma (component 0): Polynomial = 0
|
||||
* Chroma (components 1 and 2): MMR = 1
|
||||
*/
|
||||
uint8_t mapping_idc;
|
||||
/**
|
||||
* mapping_idc = 0, null pointer otherwise
|
||||
*/
|
||||
const DoviPolynomialCurve *polynomial;
|
||||
/**
|
||||
* mapping_idc = 1, null pointer otherwise
|
||||
*/
|
||||
const DoviMMRCurve *mmr;
|
||||
} DoviReshapingCurve;
|
||||
|
||||
/**
|
||||
* C struct for rpu_data_nlq()
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t nlq_offset[DoviNUM_COMPONENTS];
|
||||
uint64_t vdr_in_max_int[DoviNUM_COMPONENTS];
|
||||
uint64_t vdr_in_max[DoviNUM_COMPONENTS];
|
||||
uint64_t linear_deadzone_slope_int[DoviNUM_COMPONENTS];
|
||||
uint64_t linear_deadzone_slope[DoviNUM_COMPONENTS];
|
||||
uint64_t linear_deadzone_threshold_int[DoviNUM_COMPONENTS];
|
||||
uint64_t linear_deadzone_threshold[DoviNUM_COMPONENTS];
|
||||
} DoviRpuDataNlq;
|
||||
|
||||
/**
|
||||
* C struct for rpu_data_mapping()
|
||||
*/
|
||||
typedef struct {
|
||||
uint64_t vdr_rpu_id;
|
||||
uint64_t mapping_color_space;
|
||||
uint64_t mapping_chroma_format_idc;
|
||||
uint64_t num_x_partitions_minus1;
|
||||
uint64_t num_y_partitions_minus1;
|
||||
DoviReshapingCurve curves[DoviNUM_COMPONENTS];
|
||||
/**
|
||||
* Set to -1 to represent Option::None
|
||||
*/
|
||||
int32_t nlq_method_idc;
|
||||
/**
|
||||
* Set to -1 to represent Option::None
|
||||
*/
|
||||
int32_t nlq_num_pivots_minus2;
|
||||
/**
|
||||
* Length of zero when not present. Only present in profile 4 and 7.
|
||||
*/
|
||||
DoviU16Data nlq_pred_pivot_value;
|
||||
/**
|
||||
* Pointer to `RpuDataNlq` struct, null if not dual layer profile
|
||||
*/
|
||||
const DoviRpuDataNlq *nlq;
|
||||
} DoviRpuDataMapping;
|
||||
|
||||
/**
|
||||
* Statistical analysis of the frame: min, max, avg brightness.
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t min_pq;
|
||||
uint16_t max_pq;
|
||||
uint16_t avg_pq;
|
||||
} DoviExtMetadataBlockLevel1;
|
||||
|
||||
/**
|
||||
* Creative intent trim passes per target display peak brightness
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t target_max_pq;
|
||||
uint16_t trim_slope;
|
||||
uint16_t trim_offset;
|
||||
uint16_t trim_power;
|
||||
uint16_t trim_chroma_weight;
|
||||
uint16_t trim_saturation_gain;
|
||||
int16_t ms_weight;
|
||||
} DoviExtMetadataBlockLevel2;
|
||||
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of ExtMetadataBlockLevel2 structs
|
||||
*/
|
||||
const DoviExtMetadataBlockLevel2 *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviLevel2BlockList;
|
||||
|
||||
/**
|
||||
* Level 1 offsets.
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t min_pq_offset;
|
||||
uint16_t max_pq_offset;
|
||||
uint16_t avg_pq_offset;
|
||||
} DoviExtMetadataBlockLevel3;
|
||||
|
||||
/**
|
||||
* Something about temporal stability
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t anchor_pq;
|
||||
uint16_t anchor_power;
|
||||
} DoviExtMetadataBlockLevel4;
|
||||
|
||||
/**
|
||||
* Active area of the picture (letterbox, aspect ratio)
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t active_area_left_offset;
|
||||
uint16_t active_area_right_offset;
|
||||
uint16_t active_area_top_offset;
|
||||
uint16_t active_area_bottom_offset;
|
||||
} DoviExtMetadataBlockLevel5;
|
||||
|
||||
/**
|
||||
* ST2086/HDR10 metadata fallback
|
||||
*/
|
||||
typedef struct {
|
||||
uint16_t max_display_mastering_luminance;
|
||||
uint16_t min_display_mastering_luminance;
|
||||
uint16_t max_content_light_level;
|
||||
uint16_t max_frame_average_light_level;
|
||||
} DoviExtMetadataBlockLevel6;
|
||||
|
||||
/**
|
||||
* Creative intent trim passes per target display peak brightness
|
||||
* For CM v4.0, L8 metadata only is present and used to compute L2
|
||||
*
|
||||
* This block can have varying byte lengths: 10, 12, 13, 19, 25
|
||||
* Depending on the length, the fields parsed default to zero and may not be set.
|
||||
* Up to (including):
|
||||
* - 10: ms_weight
|
||||
* - 12: target_mid_contrast
|
||||
* - 13: clip_trim
|
||||
* - 19: saturation_vector_field[0-5]
|
||||
* - 25: hue_vector_field[0-5]
|
||||
*/
|
||||
typedef struct {
|
||||
uint64_t length;
|
||||
uint8_t target_display_index;
|
||||
uint16_t trim_slope;
|
||||
uint16_t trim_offset;
|
||||
uint16_t trim_power;
|
||||
uint16_t trim_chroma_weight;
|
||||
uint16_t trim_saturation_gain;
|
||||
uint16_t ms_weight;
|
||||
uint16_t target_mid_contrast;
|
||||
uint16_t clip_trim;
|
||||
uint8_t saturation_vector_field0;
|
||||
uint8_t saturation_vector_field1;
|
||||
uint8_t saturation_vector_field2;
|
||||
uint8_t saturation_vector_field3;
|
||||
uint8_t saturation_vector_field4;
|
||||
uint8_t saturation_vector_field5;
|
||||
uint8_t hue_vector_field0;
|
||||
uint8_t hue_vector_field1;
|
||||
uint8_t hue_vector_field2;
|
||||
uint8_t hue_vector_field3;
|
||||
uint8_t hue_vector_field4;
|
||||
uint8_t hue_vector_field5;
|
||||
} DoviExtMetadataBlockLevel8;
|
||||
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of ExtMetadataBlockLevel8 structs
|
||||
*/
|
||||
const DoviExtMetadataBlockLevel8 *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviLevel8BlockList;
|
||||
|
||||
/**
|
||||
* Source/mastering display color primaries
|
||||
*
|
||||
* This block can have varying byte lengths: 1 or 17
|
||||
* Depending on the length, the fields parsed default to zero and may not be set.
|
||||
* Up to (including):
|
||||
* - 1: source_primary_index
|
||||
* - 17: source_primary_{red,green,blue,white}_{x,y}
|
||||
*/
|
||||
typedef struct {
|
||||
uint64_t length;
|
||||
uint8_t source_primary_index;
|
||||
uint16_t source_primary_red_x;
|
||||
uint16_t source_primary_red_y;
|
||||
uint16_t source_primary_green_x;
|
||||
uint16_t source_primary_green_y;
|
||||
uint16_t source_primary_blue_x;
|
||||
uint16_t source_primary_blue_y;
|
||||
uint16_t source_primary_white_x;
|
||||
uint16_t source_primary_white_y;
|
||||
} DoviExtMetadataBlockLevel9;
|
||||
|
||||
/**
|
||||
* Custom target display information
|
||||
*
|
||||
* This block can have varying byte lengths: 5 or 21
|
||||
* Depending on the length, the fields parsed default to zero and may not be set.
|
||||
* Up to (including):
|
||||
* - 5: target_primary_index
|
||||
* - 21: target_primary_{red,green,blue,white}_{x,y}
|
||||
*/
|
||||
typedef struct {
|
||||
uint64_t length;
|
||||
uint8_t target_display_index;
|
||||
uint16_t target_max_pq;
|
||||
uint16_t target_min_pq;
|
||||
uint8_t target_primary_index;
|
||||
uint16_t target_primary_red_x;
|
||||
uint16_t target_primary_red_y;
|
||||
uint16_t target_primary_green_x;
|
||||
uint16_t target_primary_green_y;
|
||||
uint16_t target_primary_blue_x;
|
||||
uint16_t target_primary_blue_y;
|
||||
uint16_t target_primary_white_x;
|
||||
uint16_t target_primary_white_y;
|
||||
} DoviExtMetadataBlockLevel10;
|
||||
|
||||
typedef struct {
|
||||
/**
|
||||
* Pointer to the list of ExtMetadataBlockLevel10 structs
|
||||
*/
|
||||
const DoviExtMetadataBlockLevel10 *const *list;
|
||||
/**
|
||||
* List length
|
||||
*/
|
||||
size_t len;
|
||||
} DoviLevel10BlockList;
|
||||
|
||||
/**
|
||||
* Content type metadata level
|
||||
*/
|
||||
typedef struct {
|
||||
uint8_t content_type;
|
||||
uint8_t whitepoint;
|
||||
bool reference_mode_flag;
|
||||
uint8_t reserved_byte2;
|
||||
uint8_t reserved_byte3;
|
||||
} DoviExtMetadataBlockLevel11;
|
||||
|
||||
/**
|
||||
* Metadata level present in CM v4.0
|
||||
*/
|
||||
typedef struct {
|
||||
uint8_t dm_mode;
|
||||
uint8_t dm_version_index;
|
||||
} DoviExtMetadataBlockLevel254;
|
||||
|
||||
/**
|
||||
* Metadata level optionally present in CM v2.9.
|
||||
* Different display modes (calibration/verify/bypass), debugging
|
||||
*/
|
||||
typedef struct {
|
||||
uint8_t dm_run_mode;
|
||||
uint8_t dm_run_version;
|
||||
uint8_t dm_debug0;
|
||||
uint8_t dm_debug1;
|
||||
uint8_t dm_debug2;
|
||||
uint8_t dm_debug3;
|
||||
} DoviExtMetadataBlockLevel255;
|
||||
|
||||
/**
|
||||
* C struct for the list of ext_metadata_block()
|
||||
*/
|
||||
typedef struct {
|
||||
/**
|
||||
* Number of metadata blocks
|
||||
*/
|
||||
uint64_t num_ext_blocks;
|
||||
const DoviExtMetadataBlockLevel1 *level1;
|
||||
DoviLevel2BlockList level2;
|
||||
const DoviExtMetadataBlockLevel3 *level3;
|
||||
const DoviExtMetadataBlockLevel4 *level4;
|
||||
const DoviExtMetadataBlockLevel5 *level5;
|
||||
const DoviExtMetadataBlockLevel6 *level6;
|
||||
DoviLevel8BlockList level8;
|
||||
const DoviExtMetadataBlockLevel9 *level9;
|
||||
DoviLevel10BlockList level10;
|
||||
const DoviExtMetadataBlockLevel11 *level11;
|
||||
const DoviExtMetadataBlockLevel254 *level254;
|
||||
const DoviExtMetadataBlockLevel255 *level255;
|
||||
} DoviDmData;
|
||||
|
||||
/**
|
||||
* C struct for vdr_dm_data()
|
||||
*/
|
||||
typedef struct {
|
||||
bool compressed;
|
||||
uint64_t affected_dm_metadata_id;
|
||||
uint64_t current_dm_metadata_id;
|
||||
uint64_t scene_refresh_flag;
|
||||
int16_t ycc_to_rgb_coef0;
|
||||
int16_t ycc_to_rgb_coef1;
|
||||
int16_t ycc_to_rgb_coef2;
|
||||
int16_t ycc_to_rgb_coef3;
|
||||
int16_t ycc_to_rgb_coef4;
|
||||
int16_t ycc_to_rgb_coef5;
|
||||
int16_t ycc_to_rgb_coef6;
|
||||
int16_t ycc_to_rgb_coef7;
|
||||
int16_t ycc_to_rgb_coef8;
|
||||
uint32_t ycc_to_rgb_offset0;
|
||||
uint32_t ycc_to_rgb_offset1;
|
||||
uint32_t ycc_to_rgb_offset2;
|
||||
int16_t rgb_to_lms_coef0;
|
||||
int16_t rgb_to_lms_coef1;
|
||||
int16_t rgb_to_lms_coef2;
|
||||
int16_t rgb_to_lms_coef3;
|
||||
int16_t rgb_to_lms_coef4;
|
||||
int16_t rgb_to_lms_coef5;
|
||||
int16_t rgb_to_lms_coef6;
|
||||
int16_t rgb_to_lms_coef7;
|
||||
int16_t rgb_to_lms_coef8;
|
||||
uint16_t signal_eotf;
|
||||
uint16_t signal_eotf_param0;
|
||||
uint16_t signal_eotf_param1;
|
||||
uint32_t signal_eotf_param2;
|
||||
uint8_t signal_bit_depth;
|
||||
uint8_t signal_color_space;
|
||||
uint8_t signal_chroma_format;
|
||||
uint8_t signal_full_range_flag;
|
||||
uint16_t source_min_pq;
|
||||
uint16_t source_max_pq;
|
||||
uint16_t source_diagonal;
|
||||
DoviDmData dm_data;
|
||||
} DoviVdrDmData;
|
||||
|
||||
/**
|
||||
* Heap allocated list of valid RPU pointers
|
||||
*/
|
||||
typedef struct {
|
||||
DoviRpuOpaque *const *list;
|
||||
size_t len;
|
||||
const char *error;
|
||||
} DoviRpuOpaqueList;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif // __cplusplus
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the data must be valid.
|
||||
*
|
||||
* Parse a Dolby Vision RPU from unescaped byte buffer.
|
||||
* Adds an error if the parsing fails.
|
||||
*/
|
||||
DoviRpuOpaque *dovi_parse_rpu(const uint8_t *buf, size_t len);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the data must be valid.
|
||||
*
|
||||
* Parse a Dolby Vision from a AV1 ITU-T T.35 metadata OBU byte buffer.
|
||||
* Adds an error if the parsing fails.
|
||||
*/
|
||||
DoviRpuOpaque *dovi_parse_itu_t35_dovi_metadata_obu(const uint8_t *buf, size_t len);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the data must be valid.
|
||||
*
|
||||
* Parse a Dolby Vision from a (possibly) escaped HEVC UNSPEC 62 NAL unit byte buffer.
|
||||
* Adds an error if the parsing fails.
|
||||
*/
|
||||
DoviRpuOpaque *dovi_parse_unspec62_nalu(const uint8_t *buf, size_t len);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the opaque struct must be valid.
|
||||
* Avoid using on opaque pointers obtained through `dovi_parse_rpu_bin_file`.
|
||||
*
|
||||
* Free the RpuOpaque
|
||||
*/
|
||||
void dovi_rpu_free(DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the opaque struct must be valid.
|
||||
*
|
||||
* Get the last logged error for the RpuOpaque operations.
|
||||
*
|
||||
* On invalid parsing, an error is added.
|
||||
* The user should manually verify if there is an error, as the parsing does not return an error code.
|
||||
*/
|
||||
const char *dovi_rpu_get_error(const DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The data pointer should exist, and be allocated by Rust.
|
||||
*
|
||||
* Free a Data buffer
|
||||
*/
|
||||
void dovi_data_free(const DoviData *data);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
*
|
||||
* Writes the encoded RPU as a byte buffer.
|
||||
* If an error occurs in the writing, it is logged to RpuOpaque.error
|
||||
*/
|
||||
const DoviData *dovi_write_rpu(DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
*
|
||||
* Writes the encoded RPU, escapes the bytes for HEVC and prepends the buffer with 0x7C01.
|
||||
* If an error occurs in the writing, it is logged to RpuOpaque.error
|
||||
*/
|
||||
const DoviData *dovi_write_unspec62_nalu(DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
* The mode must be between 0 and 4.
|
||||
*
|
||||
* Converts the RPU to be compatible with a different Dolby Vision profile.
|
||||
* Possible modes:
|
||||
* - 0: Don't modify the RPU
|
||||
* - 1: Converts the RPU to be MEL compatible
|
||||
* - 2: Converts the RPU to be profile 8.1 compatible. Both luma and chroma mapping curves are set to no-op.
|
||||
* This mode handles source profiles 5, 7 and 8.
|
||||
* - 3: Converts to static profile 8.4
|
||||
* - 4: Converts to profile 8.1 preserving luma and chroma mapping. Old mode 2 behaviour.
|
||||
*
|
||||
* If an error occurs, it is logged to RpuOpaque.error.
|
||||
* Returns 0 if successful, -1 otherwise.
|
||||
*/
|
||||
int32_t dovi_convert_rpu_with_mode(DoviRpuOpaque *ptr,
|
||||
uint8_t mode);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the opaque struct must be valid.
|
||||
*
|
||||
* Get the DoVi RPU header struct.
|
||||
*/
|
||||
const DoviRpuDataHeader *dovi_rpu_get_header(const DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the struct must be valid.
|
||||
*
|
||||
* Frees the memory used by the RPU header.
|
||||
*/
|
||||
void dovi_rpu_free_header(const DoviRpuDataHeader *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the opaque struct must be valid.
|
||||
*
|
||||
* Get the DoVi RpuDataMapping struct.
|
||||
*/
|
||||
const DoviRpuDataMapping *dovi_rpu_get_data_mapping(const DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the struct must be valid.
|
||||
*
|
||||
* Frees the memory used by the RpuDataMapping.
|
||||
*/
|
||||
void dovi_rpu_free_data_mapping(const DoviRpuDataMapping *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the opaque struct must be valid.
|
||||
*
|
||||
* Get the DoVi VdrDmData struct.
|
||||
*/
|
||||
const DoviVdrDmData *dovi_rpu_get_vdr_dm_data(const DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the struct must be valid.
|
||||
*
|
||||
* Frees the memory used by the VdrDmData struct.
|
||||
*/
|
||||
void dovi_rpu_free_vdr_dm_data(const DoviVdrDmData *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the file path must be valid.
|
||||
*
|
||||
* Parses an existing RPU binary file.
|
||||
*
|
||||
* Returns the heap allocated `DoviRpuList` as a pointer.
|
||||
* The returned pointer may be null, or the list could be empty if an error occurred.
|
||||
*/
|
||||
const DoviRpuOpaqueList *dovi_parse_rpu_bin_file(const char *path);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The pointer to the struct must be valid.
|
||||
*
|
||||
* Frees the memory used by the DoviRpuOpaqueList struct.
|
||||
*/
|
||||
void dovi_rpu_list_free(const DoviRpuOpaqueList *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
*
|
||||
* Sets the L5 metadata active area offsets.
|
||||
* If there is no L5 block present, it is created with the offsets.
|
||||
*/
|
||||
int32_t dovi_rpu_set_active_area_offsets(DoviRpuOpaque *ptr,
|
||||
uint16_t left,
|
||||
uint16_t right,
|
||||
uint16_t top,
|
||||
uint16_t bottom);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
*
|
||||
* Converts the existing reshaping/mapping to become no-op.
|
||||
*/
|
||||
int32_t dovi_rpu_remove_mapping(DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
*
|
||||
* Writes the encoded RPU as `itu_t_t35_payload_bytes` for AV1 ITU-T T.35 metadata OBU
|
||||
* If an error occurs in the writing, it is logged to RpuOpaque.error
|
||||
*/
|
||||
const DoviData *dovi_write_av1_rpu_metadata_obu_t35_payload(DoviRpuOpaque *ptr);
|
||||
|
||||
/**
|
||||
* # Safety
|
||||
* The struct pointer must be valid.
|
||||
*
|
||||
* Writes the encoded RPU a complete AV1 `metadata_itut_t35()` OBU
|
||||
* If an error occurs in the writing, it is logged to RpuOpaque.error
|
||||
*/
|
||||
const DoviData *dovi_write_av1_rpu_metadata_obu_t35_complete(DoviRpuOpaque *ptr);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif // __cplusplus
|
||||
|
||||
#endif /* DOVI_H */
|
||||
@@ -1,46 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.TextureView
|
||||
|
||||
internal class DeferredSurfaceTextureListener(
|
||||
private val delegate: TextureView.SurfaceTextureListener,
|
||||
private val handler: Handler = Handler(Looper.getMainLooper()),
|
||||
private val onSurfaceAvailable: () -> Unit = {},
|
||||
private val isCurrentSurface: (SurfaceTexture) -> Boolean
|
||||
) : TextureView.SurfaceTextureListener {
|
||||
|
||||
private var pendingResize: Runnable? = null
|
||||
|
||||
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
delegate.onSurfaceTextureAvailable(surface, width, height)
|
||||
onSurfaceAvailable()
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
pendingResize?.let(handler::removeCallbacks)
|
||||
pendingResize = Runnable {
|
||||
pendingResize = null
|
||||
if (isCurrentSurface(surface)) {
|
||||
delegate.onSurfaceTextureSizeChanged(surface, width, height)
|
||||
}
|
||||
}
|
||||
handler.postDelayed(pendingResize!!, RESIZE_DELAY_MILLIS)
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
|
||||
delegate.onSurfaceTextureUpdated(surface)
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
|
||||
pendingResize?.let(handler::removeCallbacks)
|
||||
pendingResize = null
|
||||
return delegate.onSurfaceTextureDestroyed(surface)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val RESIZE_DELAY_MILLIS = 100L
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.core.content.FileProvider
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.io.File
|
||||
|
||||
internal class ExternalPlayerChannel(private val activity: Activity) {
|
||||
companion object {
|
||||
private const val CHANNEL = "com.plezy/external_player"
|
||||
const val REQUEST_CODE = 7461
|
||||
|
||||
private const val API_MX_RETURN_RESULT = "return_result"
|
||||
private const val API_MX_RESULT_ID = "com.mxtech.intent.result.VIEW"
|
||||
private const val API_MX_RESULT_POSITION = "position"
|
||||
private const val API_MX_RESULT_DURATION = "duration"
|
||||
private const val API_MX_RESULT_END_BY = "end_by"
|
||||
private const val API_MX_RESULT_END_BY_PLAYBACK_COMPLETION = "playback_completion"
|
||||
private const val API_MX_TITLE = "title"
|
||||
private const val API_MX_FILENAME = "filename"
|
||||
private const val API_MX_SECURE_URI = "secure_uri"
|
||||
private const val API_VLC_RESULT_POSITION = "extra_position"
|
||||
private const val API_VLC_RESULT_DURATION = "extra_duration"
|
||||
|
||||
private const val API_VIMU_TITLE = "forcename"
|
||||
private const val API_VIMU_SEEK_POSITION = "startfrom"
|
||||
private const val API_VIMU_RESUME = "forceresume"
|
||||
private const val API_VIMU_RESULT_ID = "net.gtvbox.videoplayer.result"
|
||||
private const val API_VIMU_RESULT_ERROR = 4
|
||||
private const val API_VIMU_RESULT_PLAYBACK_COMPLETED = 1
|
||||
|
||||
private val positionExtras = arrayOf(API_MX_RESULT_POSITION, API_VLC_RESULT_POSITION)
|
||||
private val durationExtras = arrayOf(API_MX_RESULT_DURATION, API_VLC_RESULT_DURATION)
|
||||
}
|
||||
|
||||
private var pendingResult: MethodChannel.Result? = null
|
||||
|
||||
fun attach(messenger: BinaryMessenger) {
|
||||
MethodChannel(messenger, CHANNEL).setMethodCallHandler(::onMethodCall)
|
||||
}
|
||||
|
||||
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
|
||||
if (requestCode != REQUEST_CODE) return false
|
||||
val result = pendingResult
|
||||
pendingResult = null
|
||||
if (result == null) {
|
||||
android.util.Log.w("ExternalPlayerChannel", "Result received without a pending channel call")
|
||||
} else {
|
||||
result.success(buildResult(resultCode, data))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun dispose() {
|
||||
pendingResult?.error("ACTIVITY_DESTROYED", "Activity was destroyed while external player was active", null)
|
||||
pendingResult = null
|
||||
}
|
||||
|
||||
internal fun buildResult(resultCode: Int, data: Intent?): Map<String, Any?> {
|
||||
val extras = data?.extras
|
||||
val endPosition = firstNumberExtra(extras, positionExtras)
|
||||
val duration = firstNumberExtra(extras, durationExtras)
|
||||
val action = data?.action
|
||||
val playbackCompleted = when (action) {
|
||||
API_MX_RESULT_ID -> extras?.getString(API_MX_RESULT_END_BY) == API_MX_RESULT_END_BY_PLAYBACK_COMPLETION
|
||||
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_PLAYBACK_COMPLETED
|
||||
else -> false
|
||||
}
|
||||
val playbackError = action == API_VIMU_RESULT_ID && resultCode == API_VIMU_RESULT_ERROR
|
||||
|
||||
return mapOf(
|
||||
"launched" to true,
|
||||
"resultCode" to resultCode,
|
||||
"resultOk" to (resultCode == Activity.RESULT_OK),
|
||||
"action" to action,
|
||||
"positionMs" to endPosition,
|
||||
"durationMs" to duration,
|
||||
"playbackCompleted" to playbackCompleted,
|
||||
"playbackError" to playbackError
|
||||
)
|
||||
}
|
||||
|
||||
private fun firstNumberExtra(extras: Bundle?, keys: Array<String>): Long? {
|
||||
if (extras == null) return null
|
||||
for (key in keys) {
|
||||
@Suppress("DEPRECATION")
|
||||
val value = extras.get(key)
|
||||
when (value) {
|
||||
is Number -> return value.toLong()
|
||||
is String -> value.toLongOrNull()?.let { return it }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
private fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
if (call.method != "openVideo") {
|
||||
result.notImplemented()
|
||||
return
|
||||
}
|
||||
|
||||
val filePath = call.argument<String>("filePath")
|
||||
val packageNames = call.argument<List<Any?>>("packages")
|
||||
?.mapNotNull { (it as? String)?.trim()?.takeIf(String::isNotEmpty) }
|
||||
?: emptyList()
|
||||
val title = call.argument<String>("title")?.trim()?.takeIf(String::isNotEmpty)
|
||||
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
|
||||
|
||||
if (filePath == null) {
|
||||
result.error("INVALID_ARGUMENT", "filePath is required", null)
|
||||
return
|
||||
}
|
||||
if (pendingResult != null) {
|
||||
result.error("ALREADY_ACTIVE", "An external player is already active", null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
val source = resolveSource(filePath)
|
||||
val targetPackages = if (packageNames.isEmpty()) listOf<String?>(null) else packageNames
|
||||
for (packageName in targetPackages) {
|
||||
try {
|
||||
pendingResult = result
|
||||
activity.startActivityForResult(
|
||||
buildIntent(source, packageName, startPositionMs, title),
|
||||
REQUEST_CODE
|
||||
)
|
||||
return
|
||||
} catch (_: ActivityNotFoundException) {
|
||||
pendingResult = null
|
||||
}
|
||||
}
|
||||
|
||||
val message = if (packageNames.isEmpty()) {
|
||||
"No app found for video"
|
||||
} else {
|
||||
"No app found for packages: ${packageNames.joinToString(", ")}"
|
||||
}
|
||||
result.error("APP_NOT_FOUND", message, null)
|
||||
} catch (error: Exception) {
|
||||
pendingResult = null
|
||||
result.error("LAUNCH_FAILED", error.message ?: error.javaClass.simpleName, null)
|
||||
}
|
||||
}
|
||||
|
||||
private data class Source(val uri: Uri, val grantRead: Boolean, val fileName: String?)
|
||||
|
||||
private fun resolveSource(filePath: String): Source {
|
||||
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
|
||||
val uri = Uri.parse(filePath)
|
||||
return Source(uri, grantRead = false, fileName = uri.lastPathSegment)
|
||||
}
|
||||
if (filePath.startsWith("content://")) {
|
||||
val uri = Uri.parse(filePath)
|
||||
return Source(uri, grantRead = true, fileName = uri.lastPathSegment)
|
||||
}
|
||||
|
||||
val path = if (filePath.startsWith("file://")) filePath.removePrefix("file://") else filePath
|
||||
val file = File(path)
|
||||
val uri = FileProvider.getUriForFile(activity, "com.edde746.plezy.fileprovider", file)
|
||||
return Source(uri, grantRead = true, fileName = file.name)
|
||||
}
|
||||
|
||||
private fun buildIntent(
|
||||
source: Source,
|
||||
packageName: String?,
|
||||
startPositionMs: Long,
|
||||
title: String?
|
||||
): Intent = Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(source.uri, "video/*")
|
||||
if (source.grantRead) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
packageName?.let(::setPackage)
|
||||
val startPosition = startPositionMs.coerceAtLeast(0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
if (startPosition > 0) {
|
||||
putExtra(API_MX_RESULT_POSITION, startPosition)
|
||||
putExtra(API_VIMU_SEEK_POSITION, startPosition)
|
||||
}
|
||||
putExtra(API_MX_RETURN_RESULT, true)
|
||||
putExtra(API_MX_SECURE_URI, true)
|
||||
putExtra(API_VIMU_RESUME, false)
|
||||
title?.let {
|
||||
putExtra(API_MX_TITLE, it)
|
||||
putExtra(API_VIMU_TITLE, it)
|
||||
}
|
||||
source.fileName?.let { putExtra(API_MX_FILENAME, it) }
|
||||
}
|
||||
}
|
||||
@@ -1,706 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.AppOpsManager
|
||||
import android.app.PictureInPictureParams
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import android.util.Rational
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowManager
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.FrameLayout
|
||||
import com.edde746.plezy.exoplayer.ExoPlayerPlugin
|
||||
import com.edde746.plezy.mpv.MpvAudioPlayerPlugin
|
||||
import com.edde746.plezy.mpv.MpvPlayerPlugin
|
||||
import com.edde746.plezy.shared.DeviceQuirks
|
||||
import com.edde746.plezy.shared.ThemeHelper
|
||||
import com.edde746.plezy.watchnext.WatchNextPlugin
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.android.FlutterTextureView
|
||||
import io.flutter.embedding.android.RenderMode
|
||||
import io.flutter.embedding.android.TransparencyMode
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.embedding.engine.FlutterShellArgs
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "MainActivity"
|
||||
private const val TEXT_INPUT_DIAGNOSTICS_ENABLED = false
|
||||
|
||||
// Mirrors DevicePerformance._lowMemThresholdBytes (2252 MiB): nominal
|
||||
// "2GB" devices report totalMem slightly above 2 GiB after carve-outs.
|
||||
private const val LOW_MEM_THRESHOLD_BYTES = 2252L shl 20
|
||||
|
||||
var usingSkia = false
|
||||
}
|
||||
|
||||
private val PIP_CHANNEL = "com.plezy/pip"
|
||||
private val THEME_CHANNEL = "com.plezy/theme"
|
||||
private val DEVICE_CHANNEL = "com.plezy/device"
|
||||
private val DEVICE_ADJUSTMENT_CHANNEL = "com.plezy/device_adjustment"
|
||||
private val TEXT_INPUT_CHANNEL = "com.plezy/text_input"
|
||||
private val APP_EXIT_CHANNEL = "com.plezy/app_exit"
|
||||
private var watchNextPlugin: WatchNextPlugin? = null
|
||||
private var nativeTextInputFocused = false
|
||||
private var originalWindowBrightness: Float? = null
|
||||
private var flutterTextureView: FlutterTextureView? = null
|
||||
private var flutterSurfaceReconnectPending = false
|
||||
private var activityStarted = false
|
||||
private val externalPlayerChannel = ExternalPlayerChannel(this)
|
||||
|
||||
private inline fun logTextInputDiag(message: () -> String) {
|
||||
if (TEXT_INPUT_DIAGNOSTICS_ENABLED) {
|
||||
Log.i(TAG, "TextInputDiag ${message()}")
|
||||
}
|
||||
}
|
||||
|
||||
// Auto PiP state
|
||||
private var autoPipReady = false
|
||||
private var autoPipWidth: Int = 16
|
||||
private var autoPipHeight: Int = 9
|
||||
|
||||
private fun isAndroidTvDevice(): Boolean = getAndroidTvDetection()["isTv"] as Boolean
|
||||
|
||||
private fun isImeVisible(): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return false
|
||||
return window.decorView.rootWindowInsets?.isVisible(WindowInsets.Type.ime()) == true
|
||||
}
|
||||
|
||||
private fun keyActionName(action: Int): String = when (action) {
|
||||
KeyEvent.ACTION_DOWN -> "down"
|
||||
KeyEvent.ACTION_UP -> "up"
|
||||
KeyEvent.ACTION_MULTIPLE -> "multiple"
|
||||
else -> "unknown($action)"
|
||||
}
|
||||
|
||||
private fun sourceNames(source: Int): String {
|
||||
val names = mutableListOf<String>()
|
||||
if ((source and InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD) names.add("keyboard")
|
||||
if ((source and InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) names.add("dpad")
|
||||
if ((source and InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) names.add("gamepad")
|
||||
if ((source and InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) names.add("joystick")
|
||||
if ((source and InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN) names.add("touchscreen")
|
||||
if ((source and InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) names.add("mouse")
|
||||
return names.ifEmpty { listOf("unknown") }.joinToString("+")
|
||||
}
|
||||
|
||||
private fun isDpadKeyCode(keyCode: Int): Boolean = when (keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent.KEYCODE_DPAD_CENTER,
|
||||
KeyEvent.KEYCODE_BACK,
|
||||
KeyEvent.KEYCODE_ENTER,
|
||||
KeyEvent.KEYCODE_NUMPAD_ENTER -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
private fun describeDevice(event: KeyEvent): String {
|
||||
val device = event.device ?: return "device=null deviceId=${event.deviceId}"
|
||||
return "deviceId=${event.deviceId} name=${device.name} vendor=${device.vendorId} product=${device.productId} " +
|
||||
"keyboardType=${device.keyboardType} sources=0x${Integer.toHexString(device.sources)}[${sourceNames(device.sources)}]"
|
||||
}
|
||||
|
||||
private fun describeKeyEvent(event: KeyEvent): String = "action=${keyActionName(event.action)} key=${KeyEvent.keyCodeToString(event.keyCode)}(${event.keyCode}) " +
|
||||
"scan=${event.scanCode} repeat=${event.repeatCount} source=0x${Integer.toHexString(event.source)}[${sourceNames(event.source)}] " +
|
||||
"flags=0x${Integer.toHexString(event.flags)} meta=0x${Integer.toHexString(event.metaState)} ${describeDevice(event)}"
|
||||
|
||||
private fun describeImeState(): String {
|
||||
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
val focus = currentFocus
|
||||
return "nativeTextInputFocused=$nativeTextInputFocused imeVisible=${isImeVisible()} " +
|
||||
"acceptingText=${imm.isAcceptingText} activeDecor=${imm.isActive(window.decorView)} " +
|
||||
"decorHasFocus=${window.decorView.hasFocus()} currentFocus=${focus?.javaClass?.name} " +
|
||||
"currentFocusHasFocus=${focus?.hasFocus()} currentFocusFocused=${focus?.isFocused}"
|
||||
}
|
||||
|
||||
private fun shouldForwardDpadBeforeIme(): Boolean {
|
||||
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
val forward = !nativeTextInputFocused && !isImeVisible() && !imm.isAcceptingText
|
||||
logTextInputDiag { "shouldForwardDpadBeforeIme=$forward ${describeImeState()}" }
|
||||
return forward
|
||||
}
|
||||
|
||||
private fun getAndroidTvDetection(): Map<String, Any> {
|
||||
val pm = packageManager
|
||||
val uiModeType = resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK
|
||||
val isTelevisionUiMode = uiModeType == Configuration.UI_MODE_TYPE_TELEVISION
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
val hasTelevisionFeature = pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
|
||||
val hasLeanback = pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
|
||||
val hasFireTvFeature = pm.hasSystemFeature("amazon.hardware.fire_tv")
|
||||
val hasTouchscreen = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
|
||||
val hasFakeTouch = pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH)
|
||||
|
||||
val reasons = mutableListOf<String>()
|
||||
if (isTelevisionUiMode) reasons.add("ui_mode_television")
|
||||
if (hasTelevisionFeature) reasons.add("television_feature")
|
||||
if (hasLeanback) reasons.add("leanback")
|
||||
if (hasFireTvFeature) reasons.add("fire_tv")
|
||||
if (!hasTouchscreen) reasons.add("no_touchscreen")
|
||||
|
||||
return mapOf(
|
||||
"isTv" to reasons.isNotEmpty(),
|
||||
"reasons" to reasons,
|
||||
"isTelevisionUiMode" to isTelevisionUiMode,
|
||||
"hasTelevisionFeature" to hasTelevisionFeature,
|
||||
"hasLeanback" to hasLeanback,
|
||||
"hasFireTvFeature" to hasFireTvFeature,
|
||||
"hasTouchscreen" to hasTouchscreen,
|
||||
"hasFakeTouch" to hasFakeTouch,
|
||||
"manufacturer" to Build.MANUFACTURER,
|
||||
"model" to Build.MODEL
|
||||
)
|
||||
}
|
||||
|
||||
/** Hardware capability signals used by Dart to pick the visual-effects tier. */
|
||||
private fun getPerformanceSignals(): Map<String, Any> {
|
||||
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
val memoryInfo = ActivityManager.MemoryInfo()
|
||||
activityManager.getMemoryInfo(memoryInfo)
|
||||
return mapOf(
|
||||
// Actual process bitness: low-end TV boxes often run 32-bit userspace.
|
||||
"is64Bit" to Process.is64Bit(),
|
||||
"isLowRamDevice" to activityManager.isLowRamDevice,
|
||||
"totalMemBytes" to memoryInfo.totalMem
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Same triple DevicePerformance uses for the reduced tier on the Dart
|
||||
* side — keep the two in sync. Evaluated here too because engine shell
|
||||
* args must be decided before Dart runs.
|
||||
*/
|
||||
private fun isLowRamClass(): Boolean {
|
||||
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||
val memoryInfo = ActivityManager.MemoryInfo()
|
||||
activityManager.getMemoryInfo(memoryInfo)
|
||||
return !Process.is64Bit() || activityManager.isLowRamDevice || memoryInfo.totalMem <= LOW_MEM_THRESHOLD_BYTES
|
||||
}
|
||||
|
||||
/** User-assigned device name (Settings > About > Device name), or null. */
|
||||
private fun getDeviceName(): String? {
|
||||
// The name the user gave the device; also used by Cast/Nearby.
|
||||
val name = Settings.Global.getString(contentResolver, Settings.Global.DEVICE_NAME)
|
||||
if (!name.isNullOrBlank()) return name
|
||||
// Fallback: the Bluetooth name usually mirrors the device name. Reading the
|
||||
// settings string needs no BLUETOOTH permission (unlike BluetoothAdapter).
|
||||
val bt = Settings.Secure.getString(contentResolver, "bluetooth_name")
|
||||
return if (!bt.isNullOrBlank()) bt else null
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
// Apply persisted theme color to the window background before anything
|
||||
// else renders. This prevents a white flash between the native splash
|
||||
// screen and Flutter's first frame for non-default themes (e.g. OLED).
|
||||
val prefs = getSharedPreferences("plezy_prefs", Context.MODE_PRIVATE)
|
||||
val savedTheme = prefs.getString("splash_theme", null)
|
||||
ThemeHelper.themeColor(savedTheme)?.let { window.decorView.setBackgroundColor(it) }
|
||||
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
// Disable the Android splash screen fade-out animation to avoid
|
||||
// a flicker before Flutter draws its first frame.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
splashScreen.setOnExitAnimationListener { splashScreenView -> splashScreenView.remove() }
|
||||
}
|
||||
|
||||
// Disable Android's default focus highlight ring that appears when using
|
||||
// D-pad navigation so the Flutter UI can render its own focus state.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
window.decorView.defaultFocusHighlightEnabled = false
|
||||
}
|
||||
|
||||
// Wrap the content view in a layout that intercepts DPAD key events
|
||||
// before the IME input stage, which can consume DPAD direction events
|
||||
// from virtual remotes before they reach Flutter's key handler.
|
||||
val content = findViewById<ViewGroup>(android.R.id.content)
|
||||
val wrapper = object : FrameLayout(this) {
|
||||
override fun dispatchKeyEventPreIme(event: KeyEvent): Boolean {
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag { "preIme received ${describeKeyEvent(event)} ${describeImeState()}" }
|
||||
}
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
KeyEvent.KEYCODE_DPAD_CENTER -> {
|
||||
if (shouldForwardDpadBeforeIme()) {
|
||||
logTextInputDiag { "preIme forwarding-to-Flutter-and-consuming ${describeKeyEvent(event)}" }
|
||||
super.dispatchKeyEvent(event)
|
||||
return true
|
||||
}
|
||||
logTextInputDiag { "preIme letting-IME-handle ${describeKeyEvent(event)}" }
|
||||
}
|
||||
}
|
||||
val handled = super.dispatchKeyEventPreIme(event)
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag { "preIme superResult=$handled ${describeKeyEvent(event)} ${describeImeState()}" }
|
||||
}
|
||||
return handled
|
||||
}
|
||||
}
|
||||
while (content.childCount > 0) {
|
||||
val child = content.getChildAt(0)
|
||||
content.removeViewAt(0)
|
||||
wrapper.addView(child)
|
||||
}
|
||||
content.addView(
|
||||
wrapper,
|
||||
ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
)
|
||||
|
||||
// Handle Watch Next deep link from initial launch
|
||||
handleWatchNextIntent(intent)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
// Handle Watch Next deep link when app is already running
|
||||
handleWatchNextIntent(intent)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag { "activity.dispatchKeyEvent before ${describeKeyEvent(event)} ${describeImeState()}" }
|
||||
}
|
||||
val handled = super.dispatchKeyEvent(event)
|
||||
if (isDpadKeyCode(event.keyCode)) {
|
||||
logTextInputDiag {
|
||||
"activity.dispatchKeyEvent after handled=$handled ${describeKeyEvent(event)} ${describeImeState()}"
|
||||
}
|
||||
}
|
||||
return handled
|
||||
}
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (!externalPlayerChannel.onActivityResult(requestCode, resultCode, data)) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
externalPlayerChannel.dispose()
|
||||
activityStarted = false
|
||||
flutterSurfaceReconnectPending = false
|
||||
flutterTextureView = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun handleWatchNextIntent(intent: Intent?) {
|
||||
val contentId = WatchNextPlugin.handleIntent(intent)
|
||||
if (contentId != null) {
|
||||
// Notify the plugin to send event to Flutter
|
||||
watchNextPlugin?.notifyDeepLink(contentId)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getFlutterShellArgs(): FlutterShellArgs {
|
||||
val args = super.getFlutterShellArgs()
|
||||
usingSkia = shouldDisableImpeller()
|
||||
if (usingSkia) args.add("--enable-impeller=false")
|
||||
if (isLowRamClass()) {
|
||||
// Bound the memory pools Dart can't reach: Skia's GPU resource cache
|
||||
// is sized from the surface area (hundreds of MB on a 4K-composited
|
||||
// TV) and the Dart old gen defaults to a large fraction of physical
|
||||
// RAM. Both drive LMK kills on 2GB boxes (#1349).
|
||||
if (usingSkia) args.add("--resource-cache-max-bytes-threshold=50331648")
|
||||
args.add("--old-gen-heap-size=256")
|
||||
Log.i(TAG, "Low-RAM device: capped engine caches (skia=$usingSkia, oldGen=256MB)")
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
private fun shouldDisableImpeller(): Boolean {
|
||||
if (DeviceQuirks.isEWaste) return true
|
||||
// NVIDIA Tegra (Shield TV)
|
||||
if (Build.MANUFACTURER.equals("NVIDIA", ignoreCase = true)) return true
|
||||
// Huawei/HONOR Kirin SoCs use Mali GPUs
|
||||
if (Build.MANUFACTURER.equals("Huawei", ignoreCase = true) ||
|
||||
Build.MANUFACTURER.equals("HONOR", ignoreCase = true)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
if (isAndroidTvDevice()) return !tvSupportsImpeller()
|
||||
return false
|
||||
}
|
||||
|
||||
// Impeller froze API 30 Fire TV hardware (#749) and Flutter's Vulkan → GLES
|
||||
// fallback still miscompiles gradients/SVGs, so only TV devices on Android 12+
|
||||
// with a Vulkan 1.1 driver leave the Skia path.
|
||||
private fun tvSupportsImpeller(): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
|
||||
// Fire OS reports modern API levels on GPUs whose drivers can't back it up
|
||||
if (Build.MANUFACTURER.equals("Amazon", ignoreCase = true)) return false
|
||||
val vulkan11 = 0x401000 // FEATURE_VULKAN_HARDWARE_VERSION encodes 1.1.0 as 0x401000
|
||||
return packageManager.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, vulkan11)
|
||||
}
|
||||
|
||||
override fun getRenderMode(): RenderMode {
|
||||
// Keep Flutter in the normal View hierarchy so video/subtitle SurfaceViews
|
||||
// remain the only native composition layers. This restores the pre-1.35.0
|
||||
// behavior and avoids compositor regressions with Dolby Vision playback.
|
||||
return RenderMode.texture
|
||||
}
|
||||
|
||||
override fun getTransparencyMode(): TransparencyMode {
|
||||
// Keep Flutter transparent so video/subtitles are visible below.
|
||||
return TransparencyMode.transparent
|
||||
}
|
||||
|
||||
override fun onFlutterTextureViewCreated(flutterTextureView: FlutterTextureView) {
|
||||
this.flutterTextureView = flutterTextureView
|
||||
val original = flutterTextureView.surfaceTextureListener ?: return
|
||||
flutterTextureView.surfaceTextureListener =
|
||||
DeferredSurfaceTextureListener(
|
||||
delegate = original,
|
||||
onSurfaceAvailable = ::tryReconnectFlutterSurface
|
||||
) { surface ->
|
||||
flutterTextureView.isAvailable && flutterTextureView.surfaceTexture === surface
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
activityStarted = false
|
||||
if (isAndroidTvDevice()) flutterSurfaceReconnectPending = true
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
activityStarted = true
|
||||
tryReconnectFlutterSurface()
|
||||
}
|
||||
|
||||
private fun tryReconnectFlutterSurface() {
|
||||
if (!activityStarted || !flutterSurfaceReconnectPending) return
|
||||
val textureView = flutterTextureView ?: return
|
||||
textureView.post {
|
||||
if (!activityStarted ||
|
||||
!flutterSurfaceReconnectPending ||
|
||||
textureView !== flutterTextureView ||
|
||||
!textureView.isAttachedToWindow ||
|
||||
!textureView.isAvailable
|
||||
) {
|
||||
return@post
|
||||
}
|
||||
|
||||
// Some TV firmware retains an available TextureView while invalidating
|
||||
// its compositor surface during standby. Force Flutter's supported
|
||||
// surface-swap path so rendering resumes without restarting the engine.
|
||||
Log.i(TAG, "Reconnecting Flutter texture surface after Android TV standby")
|
||||
textureView.pause()
|
||||
textureView.resume()
|
||||
flutterSurfaceReconnectPending = false
|
||||
}
|
||||
}
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
flutterEngine.plugins.add(MpvPlayerPlugin())
|
||||
flutterEngine.plugins.add(ExoPlayerPlugin())
|
||||
flutterEngine.plugins.add(MpvAudioPlayerPlugin())
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DEVICE_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"getTvDetection" -> result.success(getAndroidTvDetection())
|
||||
"getDeviceName" -> result.success(getDeviceName())
|
||||
"getPerformanceSignals" -> result.success(getPerformanceSignals())
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DEVICE_ADJUSTMENT_CHANNEL).setMethodCallHandler { call, result ->
|
||||
handleDeviceAdjustmentCall(call.method, call.arguments, result)
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, TEXT_INPUT_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"setNativeTextInputFocused" -> {
|
||||
val oldValue = nativeTextInputFocused
|
||||
nativeTextInputFocused = call.arguments as? Boolean ?: false
|
||||
logTextInputDiag {
|
||||
"methodChannel setNativeTextInputFocused old=$oldValue new=$nativeTextInputFocused ${describeImeState()}"
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, APP_EXIT_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"requestExit" -> {
|
||||
result.success(true)
|
||||
window.decorView.post {
|
||||
finishAndRemoveTask()
|
||||
}
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
externalPlayerChannel.attach(flutterEngine.dartExecutor.binaryMessenger)
|
||||
|
||||
// Splash screen theme: persist user's chosen theme for next launch (API 31+)
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, THEME_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"getRenderer" -> result.success(if (usingSkia) "Skia" else "Impeller")
|
||||
"setSplashTheme" -> {
|
||||
val mode = call.argument<String>("mode")
|
||||
|
||||
// Persist for next cold start & update window background now
|
||||
getSharedPreferences("plezy_prefs", Context.MODE_PRIVATE)
|
||||
.edit().putString("splash_theme", mode).apply()
|
||||
ThemeHelper.themeColor(mode)?.let { window.decorView.setBackgroundColor(it) }
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val themeId = when (mode) {
|
||||
"dark" -> R.style.SplashTheme_Dark
|
||||
"oled" -> R.style.SplashTheme_Oled
|
||||
"light" -> R.style.SplashTheme_Light
|
||||
"system" -> android.content.res.Resources.ID_NULL
|
||||
else -> android.content.res.Resources.ID_NULL
|
||||
}
|
||||
splashScreen.setSplashScreenTheme(themeId)
|
||||
}
|
||||
result.success(true)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
// Register Watch Next plugin and keep reference for deep link handling
|
||||
watchNextPlugin = WatchNextPlugin()
|
||||
flutterEngine.plugins.add(watchNextPlugin!!)
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, PIP_CHANNEL).setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"isSupported" -> {
|
||||
result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !isAndroidTvDevice())
|
||||
}
|
||||
"enter" -> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "android_version"))
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
if (isAndroidTvDevice()) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "not_supported"))
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
if (!isPipPermissionGranted()) {
|
||||
result.success(mapOf("success" to false, "errorCode" to "permission_disabled"))
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
try {
|
||||
val width = call.argument<Int>("width") ?: 16
|
||||
val height = call.argument<Int>("height") ?: 9
|
||||
val params = buildPipParams(width, height)
|
||||
val success = enterPictureInPictureMode(params)
|
||||
if (success) {
|
||||
result.success(mapOf("success" to true))
|
||||
} else {
|
||||
result.success(mapOf("success" to false, "errorCode" to "failed"))
|
||||
}
|
||||
} 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")))
|
||||
}
|
||||
}
|
||||
"setAutoPipReady" -> {
|
||||
if (isAndroidTvDevice()) {
|
||||
autoPipReady = false
|
||||
result.success(true)
|
||||
return@setMethodCallHandler
|
||||
}
|
||||
|
||||
autoPipReady = call.argument<Boolean>("ready") ?: false
|
||||
autoPipWidth = call.argument<Int>("width") ?: 16
|
||||
autoPipHeight = call.argument<Int>("height") ?: 9
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
try {
|
||||
val params = buildPipParams(autoPipWidth, autoPipHeight, autoEnterEnabled = autoPipReady)
|
||||
setPictureInPictureParams(params)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to set auto-PiP params", e)
|
||||
}
|
||||
}
|
||||
result.success(true)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleDeviceAdjustmentCall(method: String, arguments: Any?, result: MethodChannel.Result) {
|
||||
try {
|
||||
when (method) {
|
||||
"getBrightness" -> result.success(getScreenBrightnessFraction())
|
||||
"setBrightness" -> {
|
||||
setScreenBrightnessFraction(argumentAsDouble(arguments))
|
||||
result.success(null)
|
||||
}
|
||||
"restoreBrightness" -> {
|
||||
restoreScreenBrightness()
|
||||
result.success(null)
|
||||
}
|
||||
"getMediaVolume" -> result.success(getMediaVolumeFraction())
|
||||
"setMediaVolume" -> {
|
||||
setMediaVolumeFraction(argumentAsDouble(arguments))
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
} catch (e: IllegalArgumentException) {
|
||||
result.error("INVALID_ARGUMENT", e.message ?: e.javaClass.simpleName, null)
|
||||
} catch (e: Exception) {
|
||||
result.error("DEVICE_ADJUSTMENT_FAILED", e.message ?: e.javaClass.simpleName, null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun argumentAsDouble(arguments: Any?): Double {
|
||||
val value = (arguments as? Number)?.toDouble()
|
||||
?: throw IllegalArgumentException("Expected a numeric value")
|
||||
if (value.isNaN() || value.isInfinite()) {
|
||||
throw IllegalArgumentException("Expected a finite numeric value")
|
||||
}
|
||||
return value.coerceIn(0.0, 1.0)
|
||||
}
|
||||
|
||||
private fun getScreenBrightnessFraction(): Double {
|
||||
val windowBrightness = window.attributes.screenBrightness
|
||||
if (windowBrightness >= 0f) return windowBrightness.coerceIn(0f, 1f).toDouble()
|
||||
|
||||
return try {
|
||||
Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS).coerceIn(0, 255) / 255.0
|
||||
} catch (e: Settings.SettingNotFoundException) {
|
||||
0.5
|
||||
}
|
||||
}
|
||||
|
||||
private fun setScreenBrightnessFraction(value: Double) {
|
||||
if (originalWindowBrightness == null) originalWindowBrightness = window.attributes.screenBrightness
|
||||
val attributes = window.attributes
|
||||
attributes.screenBrightness = value.coerceIn(0.0, 1.0).toFloat()
|
||||
window.attributes = attributes
|
||||
}
|
||||
|
||||
private fun restoreScreenBrightness() {
|
||||
val attributes = window.attributes
|
||||
attributes.screenBrightness = originalWindowBrightness ?: WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
|
||||
window.attributes = attributes
|
||||
originalWindowBrightness = null
|
||||
}
|
||||
|
||||
private fun getMediaVolumeFraction(): Double {
|
||||
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
|
||||
val minVolume = streamMinVolume(audioManager)
|
||||
if (maxVolume <= minVolume) return 0.0
|
||||
|
||||
val volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC).coerceIn(minVolume, maxVolume)
|
||||
return (volume - minVolume).toDouble() / (maxVolume - minVolume).toDouble()
|
||||
}
|
||||
|
||||
private fun setMediaVolumeFraction(value: Double) {
|
||||
val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
|
||||
val minVolume = streamMinVolume(audioManager)
|
||||
val target = (minVolume + value.coerceIn(0.0, 1.0) * (maxVolume - minVolume))
|
||||
.roundToInt()
|
||||
.coerceIn(minVolume, maxVolume)
|
||||
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, target, 0)
|
||||
}
|
||||
|
||||
private fun streamMinVolume(audioManager: AudioManager): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
|
||||
super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
|
||||
flutterEngine?.let { engine ->
|
||||
MethodChannel(engine.dartExecutor.binaryMessenger, PIP_CHANNEL).invokeMethod("onPipChanged", isInPictureInPictureMode)
|
||||
engine.plugins.get(ExoPlayerPlugin::class.java)?.let { plugin ->
|
||||
(plugin as? ExoPlayerPlugin)?.onPipModeChanged(isInPictureInPictureMode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUserLeaveHint() {
|
||||
super.onUserLeaveHint()
|
||||
// Auto PiP for API 26-30 (API 31+ uses setAutoEnterEnabled)
|
||||
if (!isAndroidTvDevice() &&
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.S &&
|
||||
autoPipReady &&
|
||||
isPipPermissionGranted()
|
||||
) {
|
||||
try {
|
||||
// Notify Flutter to prepare video filter before PiP
|
||||
flutterEngine?.dartExecutor?.binaryMessenger?.let { messenger ->
|
||||
MethodChannel(messenger, PIP_CHANNEL).invokeMethod("onAutoPipEntering", null)
|
||||
}
|
||||
val params = buildPipParams(autoPipWidth, autoPipHeight)
|
||||
enterPictureInPictureMode(params)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to enter auto-PiP", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isPipPermissionGranted(): Boolean {
|
||||
val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
|
||||
return appOpsManager.checkOpNoThrow(
|
||||
AppOpsManager.OPSTR_PICTURE_IN_PICTURE,
|
||||
applicationInfo.uid,
|
||||
packageName
|
||||
) == AppOpsManager.MODE_ALLOWED
|
||||
}
|
||||
|
||||
private fun buildPipParams(width: Int, height: Int, autoEnterEnabled: Boolean? = null): PictureInPictureParams {
|
||||
val (w, h) = if (width <= 0 || height <= 0) {
|
||||
Pair(16, 9)
|
||||
} else {
|
||||
val ratio = width.toFloat() / height.toFloat()
|
||||
when {
|
||||
ratio < 1f / 2.39f -> Pair(100, 239)
|
||||
ratio > 2.39f -> Pair(239, 100)
|
||||
else -> Pair(width, height)
|
||||
}
|
||||
}
|
||||
val builder = PictureInPictureParams.Builder()
|
||||
.setAspectRatio(Rational(w, h))
|
||||
if (autoEnterEnabled != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
builder.setAutoEnterEnabled(autoEnterEnabled)
|
||||
}
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
|
||||
/**
|
||||
* Native mirror of MainActivity.getAndroidTvDetection(): any TV signal counts.
|
||||
* Kept in sync with the Dart-facing detection so native gating matches
|
||||
* PlatformDetector.isTV().
|
||||
*/
|
||||
object TvDetection {
|
||||
fun isTv(context: Context): Boolean {
|
||||
val pm = context.packageManager
|
||||
val uiModeType = context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
return uiModeType == Configuration.UI_MODE_TYPE_TELEVISION ||
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION) ||
|
||||
pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
|
||||
pm.hasSystemFeature("amazon.hardware.fire_tv") ||
|
||||
!pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
|
||||
}
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.os.Build
|
||||
import android.view.SurfaceControl
|
||||
import android.view.SurfaceView
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Auto-calibrates [ExoPlayerCore]'s subtitle/video layer offset by measuring, per device, how much
|
||||
* later the codec VIDEO plane reaches the display than the GL subtitle OVERLAY plane — the
|
||||
* inter-plane latency (a deep video VPP on TV boxes) that otherwise makes subtitles a frame ahead.
|
||||
*
|
||||
* Both planes are pinned to the same video-frame target (releaseTimeNs). Measuring BOTH with the
|
||||
* same mechanism — [SurfaceTxProbe] + the API-34 previous-release fence — the per-SoC buffer-recycle
|
||||
* bias cancels in the difference, leaving the pure offset:
|
||||
*
|
||||
* offsetFrames = round( (median(videoReleaseVsTarget) − median(overlayReleaseVsTarget)) / frameMs )
|
||||
*
|
||||
* This is a MEDIAN-of-each-plane model, NOT a per-frame paired difference: every sample is
|
||||
* self-paired to its own frame's target, and the per-plane release-vs-target is a steady hardware
|
||||
* constant, so the two medians need not come from the same frames — only from the same (stable)
|
||||
* device. Both medians use a recent-sample window so they stay roughly contemporaneous, and a
|
||||
* confidence gate refuses to converge on an ambiguous (~half-frame) result.
|
||||
*
|
||||
* Video samples arrive every few frames from the metadata listener (codec thread); overlay samples
|
||||
* from the libass GL thread's pre-swap hook (sparse — only when subtitles swap). Once both planes
|
||||
* have enough samples and the result is confident it converges ONCE, applies + persists, and stops
|
||||
* all probing (zero steady-state overhead). Re-runs each play to re-confirm.
|
||||
*
|
||||
* Threads: probeVideo (codec), probeOverlay (libass GL), onResult (probe reader). The lock guards
|
||||
* only counter/sample state and is NEVER held across the binder/JNI `applyTransactionToFrame` call
|
||||
* (so the GL swap path is never stalled by it). The native slot ring is allocated atomically.
|
||||
*/
|
||||
internal class AssLatencyCalibrator(
|
||||
private val videoSurface: SurfaceView,
|
||||
private val overlaySurface: SurfaceView,
|
||||
private val onCalibrated: (Int) -> Unit,
|
||||
private val onDone: () -> Unit,
|
||||
private val log: (String) -> Unit
|
||||
) {
|
||||
private val lock = Any()
|
||||
private val finished = AtomicBoolean(false)
|
||||
private val applyFail = AtomicInteger(0)
|
||||
|
||||
@Volatile private var frameIntervalNs: Long = 0L
|
||||
|
||||
@Volatile private var converged = false
|
||||
|
||||
@Volatile private var stopped = false
|
||||
|
||||
private var videoFrames = 0
|
||||
private var videoAttempts = 0
|
||||
private var overlaySwaps = 0
|
||||
private var overlayAttempts = 0
|
||||
private val videoRel = ArrayDeque<Double>()
|
||||
private val overlayRel = ArrayDeque<Double>()
|
||||
|
||||
fun start() {
|
||||
SurfaceTxProbe.sink = { tag, latch, release, count, state, source, cb ->
|
||||
onResult(tag, latch, release, count, state, source, cb)
|
||||
}
|
||||
log("calibration started (API ${Build.VERSION.SDK_INT})")
|
||||
}
|
||||
|
||||
fun probeVideo(releaseTimeNs: Long, fps: Float) {
|
||||
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
|
||||
if (fps > 1f) frameIntervalNs = (1_000_000_000.0 / fps).toLong()
|
||||
var doAttach = false
|
||||
var giveUp = false
|
||||
synchronized(lock) {
|
||||
videoFrames++
|
||||
if (videoFrames > GIVEUP_FRAMES) {
|
||||
giveUp = true
|
||||
} else if (videoAttempts < VIDEO_ATTEMPT_CAP && videoFrames % VIDEO_EVERY == 0) {
|
||||
videoAttempts++
|
||||
doAttach = true
|
||||
}
|
||||
}
|
||||
if (giveUp) {
|
||||
finishIncomplete()
|
||||
} else if (doAttach) {
|
||||
attach(videoSurface, releaseTimeNs, SurfaceTxProbe.SOURCE_VIDEO)
|
||||
}
|
||||
}
|
||||
|
||||
fun probeOverlay(releaseTimeNs: Long) {
|
||||
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
|
||||
var doAttach = false
|
||||
synchronized(lock) {
|
||||
overlaySwaps++
|
||||
if (overlayAttempts < OVERLAY_ATTEMPT_CAP && overlaySwaps % OVERLAY_EVERY == 0) {
|
||||
overlayAttempts++
|
||||
doAttach = true
|
||||
}
|
||||
}
|
||||
if (doAttach) attach(overlaySurface, releaseTimeNs, SurfaceTxProbe.SOURCE_OVERLAY)
|
||||
}
|
||||
|
||||
/** Never called while holding [lock]: applyTransactionToFrame is a binder call and runs on the
|
||||
* GL swap path. The native slot allocation is atomic, so concurrent callers are safe. */
|
||||
private fun attach(surface: SurfaceView, releaseTimeNs: Long, source: Int) {
|
||||
try {
|
||||
val tx = SurfaceControl.Transaction()
|
||||
SurfaceTxProbe.nativeAttach(tx, releaseTimeNs, source)
|
||||
surface.applyTransactionToFrame(tx)
|
||||
} catch (t: Throwable) {
|
||||
if (applyFail.incrementAndGet() == 1) {
|
||||
log("applyTransactionToFrame failed: ${t.javaClass.simpleName}: ${t.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onResult(
|
||||
tag: Long,
|
||||
latchNs: Long,
|
||||
releaseNs: Long,
|
||||
surfaceCount: Int,
|
||||
fenceState: Int,
|
||||
source: Int,
|
||||
callbackNs: Long
|
||||
) {
|
||||
if (surfaceCount <= 0 || fenceState != FENCE_OK || releaseNs <= 0) return
|
||||
val relMs = (releaseNs - tag) / 1_000_000.0
|
||||
var result: Int? = null
|
||||
synchronized(lock) {
|
||||
if (converged || stopped) return
|
||||
val list = if (source == SurfaceTxProbe.SOURCE_OVERLAY) overlayRel else videoRel
|
||||
val window = if (source == SurfaceTxProbe.SOURCE_OVERLAY) OVERLAY_WINDOW else VIDEO_WINDOW
|
||||
list.addLast(relMs)
|
||||
while (list.size > window) list.removeFirst() // keep a recent window so medians stay fresh
|
||||
result = tryComputeOffset()
|
||||
}
|
||||
result?.let {
|
||||
onCalibrated(it)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
private fun tryComputeOffset(): Int? {
|
||||
val frameMs = frameIntervalNs / 1_000_000.0
|
||||
if (frameMs <= 0.5) return null
|
||||
if (videoRel.size < VIDEO_MIN || overlayRel.size < OVERLAY_MIN) return null
|
||||
val medV = median(videoRel)
|
||||
val medO = median(overlayRel)
|
||||
val offsetMs = medV - medO
|
||||
val raw = offsetMs / frameMs
|
||||
val frames = raw.roundToInt()
|
||||
// Confidence gate: only trust a measurement that points clearly at an integer frame count.
|
||||
// An ambiguous ~half-frame result (corruption / drift / wrong fps) keeps collecting instead.
|
||||
if (abs(raw - frames) > CONFIDENCE_TOL) return null
|
||||
val clamped = frames.coerceIn(-2, 2)
|
||||
converged = true
|
||||
log(
|
||||
"CALIBRATED offsetFrames=$clamped raw=${"%.2f".format(raw)} " +
|
||||
"(video=${"%.1f".format(medV)}ms − overlay=${"%.1f".format(medO)}ms = ${"%.1f".format(offsetMs)}ms " +
|
||||
"/ frameMs=${"%.2f".format(frameMs)}) samples video=${videoRel.size} overlay=${overlayRel.size} " +
|
||||
"applyFail=${applyFail.get()}"
|
||||
)
|
||||
return clamped
|
||||
}
|
||||
|
||||
private fun finishIncomplete() {
|
||||
if (converged || stopped) return
|
||||
log(
|
||||
"calibration incomplete after $videoFrames frames " +
|
||||
"(video=${videoRel.size} overlay=${overlayRel.size}); keeping seed"
|
||||
)
|
||||
finish()
|
||||
}
|
||||
|
||||
fun stop() = finish()
|
||||
|
||||
private fun finish() {
|
||||
if (!finished.compareAndSet(false, true)) return
|
||||
stopped = true
|
||||
SurfaceTxProbe.sink = null
|
||||
onDone()
|
||||
}
|
||||
|
||||
private fun median(xs: Collection<Double>): Double {
|
||||
val s = xs.sorted()
|
||||
val n = s.size
|
||||
return if (n % 2 == 1) s[n / 2] else (s[n / 2 - 1] + s[n / 2]) / 2.0
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val FENCE_OK = 3
|
||||
private const val VIDEO_EVERY = 2
|
||||
private const val OVERLAY_EVERY = 1 // overlay swaps are already sparse
|
||||
private const val VIDEO_MIN = 40
|
||||
private const val OVERLAY_MIN = 12
|
||||
private const val VIDEO_WINDOW = 60 // recent-sample window for the median
|
||||
private const val OVERLAY_WINDOW = 40
|
||||
private const val VIDEO_ATTEMPT_CAP = 200 // ~16s @24fps/2 of video probing, then the window freezes
|
||||
private const val OVERLAY_ATTEMPT_CAP = 60
|
||||
private const val CONFIDENCE_TOL = 0.33 // |raw − round(raw)| must be within ⅓ frame to converge
|
||||
private const val GIVEUP_FRAMES = 1800 // ~75s @24fps without enough confident overlay samples
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.media.audiofx.DynamicsProcessing
|
||||
import android.media.audiofx.LoudnessEnhancer
|
||||
import android.os.Build
|
||||
import androidx.annotation.RequiresApi
|
||||
|
||||
/**
|
||||
* Session-bound loudness normalization approximating mpv's
|
||||
* `loudnorm=I=-14:TP=-3:LRA=4` filter (#1289).
|
||||
*
|
||||
* API 28+: DynamicsProcessing with a single full-range compressor band as a
|
||||
* slow AGC plus a limiter for the true-peak ceiling. API 25-27, or when the
|
||||
* device lacks the DynamicsProcessing effect HAL: LoudnessEnhancer (fixed
|
||||
* makeup gain with built-in limiting).
|
||||
*
|
||||
* Effects bind to the audio session, so they survive AudioTrack re-creation
|
||||
* (seeks, format changes) while the session id is stable. They only process
|
||||
* PCM mixer streams — the caller must force decoded PCM output and disable
|
||||
* tunneling while enabled. DynamicsProcessing parameters are per-channel, so
|
||||
* the effect is re-created when the output channel count changes (dialogue
|
||||
* lives in the center channel of 5.1 PCM).
|
||||
*/
|
||||
class AudioNormalizationEffect(private val log: (String, String, String) -> Unit) {
|
||||
|
||||
private companion object {
|
||||
const val EFFECT_PRIORITY = 0
|
||||
|
||||
// DynamicsProcessing — tuned for movie mixes whose dialogue sits around
|
||||
// -27 LUFS: compress above threshold, make up toward I=-14, limit at TP=-3.
|
||||
const val FRAME_DURATION_MS = 10f
|
||||
const val MBC_CUTOFF_HZ = 20_000f
|
||||
const val MBC_ATTACK_MS = 30f
|
||||
const val MBC_RELEASE_MS = 300f
|
||||
const val MBC_RATIO = 4f
|
||||
const val MBC_THRESHOLD_DB = -34f
|
||||
const val MBC_KNEE_DB = 6f
|
||||
const val MBC_NOISE_GATE_DB = -90f // effectively disabled
|
||||
const val MBC_EXPANDER_RATIO = 1f // no downward expansion
|
||||
const val MBC_POST_GAIN_DB = 15f
|
||||
const val LIMITER_ATTACK_MS = 1f
|
||||
const val LIMITER_RELEASE_MS = 60f
|
||||
const val LIMITER_RATIO = 10f
|
||||
const val LIMITER_THRESHOLD_DB = -3f
|
||||
const val DEFAULT_CHANNEL_COUNT = 2
|
||||
const val MAX_CHANNEL_COUNT = 8
|
||||
|
||||
// LoudnessEnhancer fallback: fixed boost, internally limited.
|
||||
const val LOUDNESS_ENHANCER_GAIN_MB = 900 // +9 dB
|
||||
}
|
||||
|
||||
private var dynamicsProcessing: DynamicsProcessing? = null
|
||||
private var loudnessEnhancer: LoudnessEnhancer? = null
|
||||
private var attachedSessionId = 0
|
||||
private var attachedChannelCount = 0
|
||||
|
||||
val isActive: Boolean get() = dynamicsProcessing != null || loudnessEnhancer != null
|
||||
|
||||
/** For stats/QA: which engine is processing. */
|
||||
val describe: String
|
||||
get() = when {
|
||||
dynamicsProcessing != null -> "DynamicsProcessing"
|
||||
loudnessEnhancer != null -> "LoudnessEnhancer"
|
||||
else -> "off"
|
||||
}
|
||||
|
||||
/** Attach to [sessionId]; idempotent for an unchanged (session, channels) pair. */
|
||||
fun attach(sessionId: Int, channelCount: Int?) {
|
||||
val channels = (channelCount ?: DEFAULT_CHANNEL_COUNT).coerceIn(1, MAX_CHANNEL_COUNT)
|
||||
if (sessionId == attachedSessionId && channels == attachedChannelCount && isActive) return
|
||||
release()
|
||||
if (sessionId == 0) return // AUDIO_SESSION_ID_UNSET — retry on onAudioSessionIdChanged
|
||||
attachedSessionId = sessionId
|
||||
attachedChannelCount = channels
|
||||
if (Build.VERSION.SDK_INT >= 28 && tryDynamicsProcessing(sessionId, channels)) return
|
||||
tryLoudnessEnhancer(sessionId)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
dynamicsProcessing?.let { effect ->
|
||||
runCatching { effect.setEnabled(false) }
|
||||
runCatching { effect.release() }
|
||||
}
|
||||
dynamicsProcessing = null
|
||||
loudnessEnhancer?.let { effect ->
|
||||
runCatching { effect.setEnabled(false) }
|
||||
runCatching { effect.release() }
|
||||
}
|
||||
loudnessEnhancer = null
|
||||
attachedSessionId = 0
|
||||
attachedChannelCount = 0
|
||||
}
|
||||
|
||||
@RequiresApi(28)
|
||||
private fun tryDynamicsProcessing(sessionId: Int, channelCount: Int): Boolean = try {
|
||||
val band = DynamicsProcessing.MbcBand(
|
||||
// inUse
|
||||
true,
|
||||
MBC_CUTOFF_HZ,
|
||||
MBC_ATTACK_MS,
|
||||
MBC_RELEASE_MS,
|
||||
MBC_RATIO,
|
||||
MBC_THRESHOLD_DB,
|
||||
MBC_KNEE_DB,
|
||||
MBC_NOISE_GATE_DB,
|
||||
MBC_EXPANDER_RATIO,
|
||||
// preGain
|
||||
0f,
|
||||
MBC_POST_GAIN_DB
|
||||
)
|
||||
val mbc = DynamicsProcessing.Mbc(
|
||||
// inUse
|
||||
true,
|
||||
// enabled
|
||||
true,
|
||||
// bandCount
|
||||
1
|
||||
).apply { setBand(0, band) }
|
||||
val limiter = DynamicsProcessing.Limiter(
|
||||
// inUse
|
||||
true,
|
||||
// enabled
|
||||
true,
|
||||
// linkGroup
|
||||
0,
|
||||
LIMITER_ATTACK_MS,
|
||||
LIMITER_RELEASE_MS,
|
||||
LIMITER_RATIO,
|
||||
LIMITER_THRESHOLD_DB,
|
||||
// postGain
|
||||
0f
|
||||
)
|
||||
val channel = DynamicsProcessing.Channel(
|
||||
// inputGain
|
||||
0f,
|
||||
// preEqInUse
|
||||
false,
|
||||
// preEqBandCount
|
||||
0,
|
||||
// mbcInUse
|
||||
true,
|
||||
// mbcBandCount
|
||||
1,
|
||||
// postEqInUse
|
||||
false,
|
||||
// postEqBandCount
|
||||
0,
|
||||
// limiterInUse
|
||||
true
|
||||
).apply {
|
||||
setMbc(mbc)
|
||||
setLimiter(limiter)
|
||||
}
|
||||
val config = DynamicsProcessing.Config.Builder(
|
||||
DynamicsProcessing.VARIANT_FAVOR_FREQUENCY_RESOLUTION,
|
||||
channelCount,
|
||||
// preEqInUse
|
||||
false,
|
||||
// preEqBandCount
|
||||
0,
|
||||
// mbcInUse
|
||||
true,
|
||||
// mbcBandCount
|
||||
1,
|
||||
// postEqInUse
|
||||
false,
|
||||
// postEqBandCount
|
||||
0,
|
||||
// limiterInUse
|
||||
true
|
||||
)
|
||||
.setPreferredFrameDuration(FRAME_DURATION_MS)
|
||||
.setAllChannelsTo(channel)
|
||||
.build()
|
||||
dynamicsProcessing = DynamicsProcessing(EFFECT_PRIORITY, sessionId, config).apply { setEnabled(true) }
|
||||
log("info", "audio-normalization", "DynamicsProcessing attached (session=$sessionId, channels=$channelCount)")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
log(
|
||||
"warn",
|
||||
"audio-normalization",
|
||||
"DynamicsProcessing unavailable (${e.javaClass.simpleName}: ${e.message}); trying LoudnessEnhancer"
|
||||
)
|
||||
dynamicsProcessing = null
|
||||
false
|
||||
}
|
||||
|
||||
private fun tryLoudnessEnhancer(sessionId: Int) {
|
||||
try {
|
||||
loudnessEnhancer = LoudnessEnhancer(sessionId).apply {
|
||||
setTargetGain(LOUDNESS_ENHANCER_GAIN_MB)
|
||||
setEnabled(true)
|
||||
}
|
||||
log("info", "audio-normalization", "LoudnessEnhancer attached (session=$sessionId, gain=${LOUDNESS_ENHANCER_GAIN_MB}mB)")
|
||||
} catch (e: Exception) {
|
||||
loudnessEnhancer = null
|
||||
attachedSessionId = 0
|
||||
attachedChannelCount = 0
|
||||
log(
|
||||
"warn",
|
||||
"audio-normalization",
|
||||
"No loudness effect available on this device (${e.javaClass.simpleName}: ${e.message})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.MimeTypes
|
||||
|
||||
internal fun isPassthroughAudioMimeType(mimeType: String): Boolean = when (mimeType) {
|
||||
"audio/ac3",
|
||||
"audio/eac3",
|
||||
"audio/eac3-joc",
|
||||
"audio/ac4",
|
||||
"audio/vnd.dts",
|
||||
"audio/vnd.dts.hd",
|
||||
"audio/vnd.dts.uhd",
|
||||
MimeTypes.AUDIO_TRUEHD -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
internal fun shouldBlockDirectOutputForPassthrough(mimeType: String, audioPassthroughEnabled: Boolean): Boolean = !audioPassthroughEnabled && isPassthroughAudioMimeType(mimeType)
|
||||
@@ -1,95 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import java.io.EOFException
|
||||
|
||||
/** Shared whole-sample buffering protocol for TrackOutput transforms. */
|
||||
abstract class BufferedTransformingTrackOutput(
|
||||
protected val delegate: TrackOutput,
|
||||
initialBufferSize: Int,
|
||||
initialReadBufferSize: Int = initialBufferSize
|
||||
) : TrackOutput {
|
||||
protected var inputBuffer = ByteArray(initialBufferSize)
|
||||
private set
|
||||
|
||||
private var inputLength = 0
|
||||
private var buffering = false
|
||||
private var readBuffer = ByteArray(initialReadBufferSize)
|
||||
private val outputParsable = ParsableByteArray()
|
||||
|
||||
protected abstract val transformEnabled: Boolean
|
||||
protected abstract val transformedBuffer: ByteArray
|
||||
|
||||
/** Returns transformed length, or a negative value to drop the sample. */
|
||||
protected abstract fun transformSample(inputLength: Int, flags: Int): Int
|
||||
open override fun format(format: Format) = delegate.format(format)
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (!transformEnabled) {
|
||||
return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
}
|
||||
|
||||
buffering = true
|
||||
if (readBuffer.size < length) readBuffer = ByteArray(length)
|
||||
val bytesRead = input.read(readBuffer, 0, length)
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT && !allowEndOfInput) throw EOFException()
|
||||
if (bytesRead > 0) appendInput(readBuffer, bytesRead)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
if (!transformEnabled) {
|
||||
delegate.sampleData(data, length, sampleDataPart)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = true
|
||||
ensureInputCapacity(inputLength + length)
|
||||
data.readBytes(inputBuffer, inputLength, length)
|
||||
inputLength += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
if (!transformEnabled || !buffering) {
|
||||
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
return
|
||||
}
|
||||
|
||||
buffering = false
|
||||
val sourceLength = inputLength
|
||||
inputLength = 0
|
||||
val transformedLength = transformSample(sourceLength, flags)
|
||||
if (transformedLength < 0) return
|
||||
|
||||
outputParsable.reset(transformedBuffer, transformedLength)
|
||||
delegate.sampleData(outputParsable, transformedLength, TrackOutput.SAMPLE_DATA_PART_MAIN)
|
||||
delegate.sampleMetadata(timeUs, flags, transformedLength, 0, cryptoData)
|
||||
}
|
||||
|
||||
private fun appendInput(source: ByteArray, length: Int) {
|
||||
ensureInputCapacity(inputLength + length)
|
||||
System.arraycopy(source, 0, inputBuffer, inputLength, length)
|
||||
inputLength += length
|
||||
}
|
||||
|
||||
private fun ensureInputCapacity(needed: Int) {
|
||||
if (inputBuffer.size < needed) {
|
||||
inputBuffer = inputBuffer.copyOf(maxOf(needed, inputBuffer.size * 2))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,378 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.content.Context
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaCodecList
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
|
||||
enum class DvConversionMode { DISABLED, DV81, HEVC_STRIP }
|
||||
|
||||
object DoviBridge {
|
||||
private const val TAG = "DoviBridge"
|
||||
|
||||
data class DvAutoDecision(
|
||||
val mode: DvConversionMode,
|
||||
val reason: String,
|
||||
val bridgeReady: Boolean,
|
||||
val displayDv: Boolean,
|
||||
val nativeDecoder: Boolean,
|
||||
val advertisedP7: Boolean,
|
||||
val advertisedP8: Boolean,
|
||||
val decoders: String,
|
||||
val displayHdr: String
|
||||
) {
|
||||
fun logMessage(): String = "AUTO P7 DV decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
|
||||
"displayDV=$displayDv, nativeDecoder=$nativeDecoder, advertisedP7=$advertisedP7, " +
|
||||
"advertisedP8=$advertisedP8, decoders=$decoders, displayHdr=$displayHdr"
|
||||
}
|
||||
|
||||
data class Dv7FallbackDecision(
|
||||
val mode: DvConversionMode,
|
||||
val reason: String,
|
||||
val bridgeReady: Boolean,
|
||||
val displayDv: Boolean,
|
||||
val advertisedP8: Boolean,
|
||||
val displayHdr: String
|
||||
) {
|
||||
fun logMessage(): String = "DV7 fallback decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
|
||||
"displayDV=$displayDv, advertisedP8=$advertisedP8, displayHdr=$displayHdr"
|
||||
}
|
||||
|
||||
private val DOLBY_VISION_MIME_TYPES = setOf(
|
||||
"video/dolby-vision",
|
||||
"video/hevcdv",
|
||||
"video/dv_hevc"
|
||||
)
|
||||
|
||||
const val CONVERT_FAILED = -1
|
||||
const val DESTINATION_TOO_SMALL = -2
|
||||
|
||||
private data class DvProfileLevel(val profile: Int, val level: Int)
|
||||
|
||||
private data class DvDecoderCapability(
|
||||
val name: String,
|
||||
val mimeType: String,
|
||||
val profileLevels: List<DvProfileLevel>
|
||||
)
|
||||
|
||||
private val nativeLoaded: Boolean by lazy {
|
||||
try {
|
||||
System.loadLibrary("dovi_bridge")
|
||||
true
|
||||
} catch (_: UnsatisfiedLinkError) {
|
||||
Log.w(TAG, "Native lib not found")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private val conversionPathReady: Boolean by lazy {
|
||||
nativeLoaded && runCatching { nativeIsConversionPathReady() }.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun isAvailable(): Boolean = conversionPathReady
|
||||
|
||||
private val dolbyVisionDecoders: List<DvDecoderCapability> by lazy {
|
||||
try {
|
||||
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
|
||||
codecList.codecInfos.flatMap { info ->
|
||||
if (info.isEncoder) {
|
||||
emptyList()
|
||||
} else {
|
||||
info.supportedTypes.mapNotNull { type ->
|
||||
if (!DOLBY_VISION_MIME_TYPES.contains(type.lowercase())) return@mapNotNull null
|
||||
val capabilities = runCatching { info.getCapabilitiesForType(type) }
|
||||
.onFailure { Log.w(TAG, "Failed to query ${info.name} capabilities for $type", it) }
|
||||
.getOrNull()
|
||||
?: return@mapNotNull null
|
||||
DvDecoderCapability(
|
||||
name = info.name,
|
||||
mimeType = type,
|
||||
profileLevels = capabilities.profileLevels.map { DvProfileLevel(it.profile, it.level) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to query native Dolby Vision decoder support", e)
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
val hasNativeDolbyVisionDecoder: Boolean by lazy {
|
||||
dolbyVisionDecoders.isNotEmpty().also {
|
||||
Log.i(TAG, "Native Dolby Vision decoder available: $it; decoders=${describeDolbyVisionDecoders()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceAdvertisesDvProfile(profile: Int, minApi: Int = 0): Boolean {
|
||||
if (Build.VERSION.SDK_INT < minApi) return false
|
||||
return dolbyVisionDecoders.any { decoder ->
|
||||
decoder.profileLevels.any { it.profile == profile }
|
||||
}
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile7: Boolean by lazy {
|
||||
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb)
|
||||
.also { Log.i(TAG, "Device advertises exact DV Profile 7 (DvheDtb): $it") }
|
||||
}
|
||||
|
||||
val deviceSupportsDvProfile8: Boolean by lazy {
|
||||
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
|
||||
.also { Log.i(TAG, "Device advertises DV Profile 8 (DvheSt): $it") }
|
||||
}
|
||||
|
||||
fun displaySupportsDolbyVision(context: Context): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
|
||||
Log.i(TAG, "Display Dolby Vision support: false (HDR capabilities require API 24, device API=${Build.VERSION.SDK_INT})")
|
||||
return false
|
||||
}
|
||||
|
||||
val display = getCurrentDisplay(context)
|
||||
if (display == null) {
|
||||
Log.i(TAG, "Display Dolby Vision support: false (no active display)")
|
||||
return false
|
||||
}
|
||||
|
||||
val hdrTypes = runCatching { getDisplayHdrTypes(display) }.getOrElse { error ->
|
||||
Log.w(TAG, "Display Dolby Vision support: false (failed to query HDR types)", error)
|
||||
return false
|
||||
}
|
||||
val supported = hdrTypes.contains(Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION)
|
||||
Log.i(TAG, "Display Dolby Vision support: $supported; ${describeDisplayHdrCapabilities(display)}")
|
||||
return supported
|
||||
}
|
||||
|
||||
fun describeDisplayHdrCapabilities(context: Context): String {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "HDR capabilities unavailable (API=${Build.VERSION.SDK_INT})"
|
||||
val display = getCurrentDisplay(context) ?: return "HDR capabilities unavailable (no active display)"
|
||||
return describeDisplayHdrCapabilities(display)
|
||||
}
|
||||
|
||||
fun logSupportSummary(context: Context) {
|
||||
Log.i(
|
||||
TAG,
|
||||
"DV support summary: bridgeReady=${isAvailable()}, displayDV=${displaySupportsDolbyVision(context)}, " +
|
||||
"nativeDecoder=$hasNativeDolbyVisionDecoder, advertisedP7=$deviceSupportsDvProfile7, " +
|
||||
"advertisedP8=$deviceSupportsDvProfile8, decoders=${describeDolbyVisionDecoders()}, " +
|
||||
"displayHdr=${describeDisplayHdrCapabilities(context)}"
|
||||
)
|
||||
}
|
||||
|
||||
fun getConversionDecision(context: Context): DvAutoDecision {
|
||||
val bridgeReady = isAvailable()
|
||||
val displayDv = displaySupportsDolbyVision(context)
|
||||
val nativeDecoder = hasNativeDolbyVisionDecoder
|
||||
val advertisedP7 = deviceSupportsDvProfile7
|
||||
val advertisedP8 = deviceSupportsDvProfile8
|
||||
|
||||
val mode = when {
|
||||
!displayDv -> DvConversionMode.HEVC_STRIP
|
||||
advertisedP7 -> DvConversionMode.DISABLED
|
||||
advertisedP8 && bridgeReady -> DvConversionMode.DV81
|
||||
else -> DvConversionMode.HEVC_STRIP
|
||||
}
|
||||
val reason = when {
|
||||
!displayDv -> "active display does not support Dolby Vision; stripping DV metadata for HEVC fallback"
|
||||
advertisedP7 -> "active display supports Dolby Vision and decoder advertises exact Profile 7; trying native DV first"
|
||||
advertisedP8 && bridgeReady -> "active display supports Dolby Vision and decoder advertises Profile 8; converting to Profile 8.1"
|
||||
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
|
||||
else -> "Dolby Vision output path is unavailable; stripping DV metadata for HEVC fallback"
|
||||
}
|
||||
val decision = DvAutoDecision(
|
||||
mode = mode,
|
||||
reason = reason,
|
||||
bridgeReady = bridgeReady,
|
||||
displayDv = displayDv,
|
||||
nativeDecoder = nativeDecoder,
|
||||
advertisedP7 = advertisedP7,
|
||||
advertisedP8 = advertisedP8,
|
||||
decoders = describeDolbyVisionDecoders(),
|
||||
displayHdr = describeDisplayHdrCapabilities(context)
|
||||
)
|
||||
Log.i(TAG, decision.logMessage())
|
||||
return decision
|
||||
}
|
||||
|
||||
fun getConversionMode(context: Context): DvConversionMode = getConversionDecision(context).mode
|
||||
|
||||
/** Get the fallback mode when native DV7 decoding fails. */
|
||||
fun getDv7FallbackDecision(context: Context): Dv7FallbackDecision {
|
||||
val bridgeReady = isAvailable()
|
||||
val displayDv = displaySupportsDolbyVision(context)
|
||||
val advertisedP8 = deviceSupportsDvProfile8
|
||||
val mode = if (displayDv && advertisedP8 && bridgeReady) DvConversionMode.DV81 else DvConversionMode.HEVC_STRIP
|
||||
val reason = when {
|
||||
mode == DvConversionMode.DV81 -> "display supports Dolby Vision and decoder advertises Profile 8"
|
||||
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
|
||||
else -> "Dolby Vision output or Profile 8 support is unavailable"
|
||||
}
|
||||
val decision = Dv7FallbackDecision(
|
||||
mode = mode,
|
||||
reason = reason,
|
||||
bridgeReady = bridgeReady,
|
||||
displayDv = displayDv,
|
||||
advertisedP8 = advertisedP8,
|
||||
displayHdr = describeDisplayHdrCapabilities(context)
|
||||
)
|
||||
Log.i(TAG, decision.logMessage())
|
||||
return decision
|
||||
}
|
||||
|
||||
fun getDv7FallbackMode(context: Context): DvConversionMode = getDv7FallbackDecision(context).mode
|
||||
|
||||
private fun getCurrentDisplay(context: Context): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
context.display
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
(context.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.defaultDisplay
|
||||
}
|
||||
|
||||
private fun describeDolbyVisionDecoders(): String {
|
||||
if (dolbyVisionDecoders.isEmpty()) return "none"
|
||||
return dolbyVisionDecoders.joinToString { decoder ->
|
||||
val profiles = if (decoder.profileLevels.isEmpty()) {
|
||||
"none"
|
||||
} else {
|
||||
decoder.profileLevels.joinToString(prefix = "[", postfix = "]") {
|
||||
"${describeDvProfile(it.profile)}/${describeDvLevel(it.level)}"
|
||||
}
|
||||
}
|
||||
"${decoder.name}(${decoder.mimeType}, profiles=$profiles)"
|
||||
}
|
||||
}
|
||||
|
||||
private fun describeHdrTypes(hdrTypes: IntArray): String {
|
||||
if (hdrTypes.isEmpty()) return "none"
|
||||
return hdrTypes.joinToString(prefix = "[", postfix = "]") { type ->
|
||||
when (type) {
|
||||
Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "DOLBY_VISION"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10"
|
||||
Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG"
|
||||
Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10_PLUS"
|
||||
else -> "unknown(${hex(type)})"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun describeDisplayHdrCapabilities(display: Display): String {
|
||||
val hdrCapabilities = getDisplayHdrCapabilities(display)
|
||||
val parts = mutableListOf(
|
||||
"display=${display.displayId}:${display.name}",
|
||||
"activeMode=${describeDisplayMode(display.mode)}"
|
||||
)
|
||||
if (hdrCapabilities == null) {
|
||||
parts += "hdrCapabilities=unavailable"
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
parts += "hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}"
|
||||
parts += "desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
|
||||
"maxAvg=${formatLuminance(hdrCapabilities.desiredMaxAverageLuminance)}, " +
|
||||
"min=${formatLuminance(hdrCapabilities.desiredMinLuminance)}"
|
||||
}
|
||||
parts += "supportedModes=${display.supportedModes.joinToString(prefix = "[", postfix = "]") { describeDisplayMode(it) }}"
|
||||
return parts.joinToString(prefix = "{", postfix = "}")
|
||||
}
|
||||
|
||||
private fun getDisplayHdrCapabilities(display: Display): Display.HdrCapabilities? = runCatching {
|
||||
display.hdrCapabilities
|
||||
}.onFailure { Log.w(TAG, "Failed to query display HDR capabilities", it) }.getOrNull()
|
||||
|
||||
private fun getDisplayHdrTypes(display: Display): IntArray {
|
||||
val hdrCapabilities = getDisplayHdrCapabilities(display) ?: return IntArray(0)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
return runCatching { display.mode.supportedHdrTypes }.getOrElse { error ->
|
||||
Log.w(TAG, "Failed to query mode HDR types; falling back to display HDR capabilities", error)
|
||||
@Suppress("DEPRECATION")
|
||||
hdrCapabilities.supportedHdrTypes
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
return hdrCapabilities.supportedHdrTypes
|
||||
}
|
||||
|
||||
private fun describeDisplayMode(mode: Display.Mode): String {
|
||||
val hdr = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
", hdr=${describeHdrTypes(mode.supportedHdrTypes)}"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz$hdr"
|
||||
}
|
||||
|
||||
private fun formatLuminance(value: Float): String = if (value.isNaN() || value <= 0f) "unknown" else "${value}nits"
|
||||
|
||||
private fun describeDvProfile(profile: Int): String = when (profile) {
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPer -> "P0/DvavPer"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPen -> "P1/DvavPen"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDer -> "P2/DvheDer"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDen -> "P3/DvheDen"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr -> "P4/DvheDtr"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheStn -> "P5/DvheStn"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDth -> "P6/DvheDth"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb -> "P7/DvheDtb"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt -> "P8/DvheSt"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavSe -> "P9/DvavSe"
|
||||
else -> "unknown(${hex(profile)})"
|
||||
}
|
||||
|
||||
private fun describeDvLevel(level: Int): String = when (level) {
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd24 -> "L1/Hd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd30 -> "L2/Hd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd24 -> "L3/Fhd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd30 -> "L4/Fhd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd60 -> "L5/Fhd60"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd24 -> "L6/Uhd24"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd30 -> "L7/Uhd30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd48 -> "L8/Uhd48"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd60 -> "L9/Uhd60"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd120 -> "L10/Uhd120"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k30 -> "L11/8k30"
|
||||
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k60 -> "L12/8k60"
|
||||
else -> "unknown(${hex(level)})"
|
||||
}
|
||||
|
||||
private fun hex(value: Int): String = "0x${value.toString(16)}"
|
||||
|
||||
fun convertRpuNalu(
|
||||
payload: ByteArray,
|
||||
payloadOffset: Int,
|
||||
payloadLength: Int,
|
||||
output: ByteArray,
|
||||
outputOffset: Int,
|
||||
outputCapacity: Int,
|
||||
mode: Int = 2
|
||||
): Int {
|
||||
if (!conversionPathReady || payloadLength <= 0) return CONVERT_FAILED
|
||||
return runCatching {
|
||||
nativeConvertDv7RpuToDv81(payload, payloadOffset, payloadLength, output, outputOffset, outputCapacity, mode)
|
||||
}
|
||||
.onFailure { Log.w(TAG, "RPU conversion failed: ${it.message}") }
|
||||
.getOrDefault(CONVERT_FAILED)
|
||||
}
|
||||
|
||||
fun getVersion(): String? {
|
||||
if (!nativeLoaded) return null
|
||||
return runCatching { nativeGetBridgeVersion() }.getOrNull()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeConvertDv7RpuToDv81(
|
||||
payload: ByteArray,
|
||||
payloadOffset: Int,
|
||||
payloadLength: Int,
|
||||
output: ByteArray,
|
||||
outputOffset: Int,
|
||||
outputCapacity: Int,
|
||||
mode: Int
|
||||
): Int
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeIsConversionPathReady(): Boolean
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeGetBridgeVersion(): String
|
||||
}
|
||||
@@ -1,672 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
|
||||
/**
|
||||
* TrackOutput wrapper that processes DV Profile 7 HEVC samples based on conversion mode:
|
||||
*
|
||||
* - DV81: Convert RPU NALs via libdovi mode 2 to Profile 8.1, present as
|
||||
* video/dolby-vision with dvhe.08.XX codec string. Conversion failures drop
|
||||
* that RPU instead of forwarding Profile 7 metadata into a Profile 8.1 stream.
|
||||
* - HEVC_STRIP: Strip DV RPU/EL NALs, present as plain video/hevc.
|
||||
*
|
||||
* Two modes of NAL framing (auto-detected):
|
||||
* - Annex B (MKV path): MatroskaExtractor outputs 00 00 00 01 start codes
|
||||
* - Length-prefixed (MP4 path): Mp4Extractor outputs 4-byte big-endian lengths
|
||||
*
|
||||
* NAL processing:
|
||||
* - Type 62 (UNSPEC62): DV RPU → convert (DV81) or strip (HEVC_STRIP)
|
||||
* - Type 63 (UNSPEC63): DV Enhancement Layer → strip
|
||||
* - All other NALs: pass through unchanged, matching Kodi's compatibility path
|
||||
*
|
||||
* All buffers are reused across samples to minimize GC pressure on the hot path.
|
||||
*/
|
||||
class DoviConvertingTrackOutput(
|
||||
delegate: TrackOutput,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val emitLog: ((String, String, String) -> Unit)? = null
|
||||
) : BufferedTransformingTrackOutput(delegate, INITIAL_BUFFER_SIZE) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DoviConvertTrack"
|
||||
private const val NAL_TYPE_UNSPEC62 = 62
|
||||
private const val NAL_TYPE_UNSPEC63 = 63
|
||||
private const val LIBDOVI_MODE_TO_81 = 2
|
||||
private const val INITIAL_BUFFER_SIZE = 256 * 1024
|
||||
private const val MAX_CONVERTED_RPU_SIZE = 16 * 1024
|
||||
private val ANNEX_B_START_CODE = byteArrayOf(0, 0, 0, 1)
|
||||
}
|
||||
|
||||
var conversionActive = false
|
||||
private set
|
||||
var strippedNalCount = 0L
|
||||
private set
|
||||
var strippedRpuNalCount = 0L
|
||||
private set
|
||||
var strippedElNalCount = 0L
|
||||
private set
|
||||
var strippedInitNalCount = 0L
|
||||
private set
|
||||
var convertedRpuCount = 0L
|
||||
private set
|
||||
var rpuConversionFailureCount = 0L
|
||||
private set
|
||||
var rpuOutputTooSmallCount = 0L
|
||||
private set
|
||||
val averageRpuConversionTimeUs: Long
|
||||
get() = if (rpuConversionCallCount > 0) totalRpuConversionTimeUs / rpuConversionCallCount else 0L
|
||||
val averageSampleProcessingTimeUs: Long
|
||||
get() = if (sampleCount > 0) totalSampleProcessingTimeUs / sampleCount else 0L
|
||||
|
||||
// Reusable buffers — grown as needed, never shrunk
|
||||
private var outputBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var outputLen = 0
|
||||
|
||||
// Sample counter for periodic logging
|
||||
private var sampleCount = 0L
|
||||
private var rpuConversionCallCount = 0L
|
||||
private var totalRpuConversionTimeUs = 0L
|
||||
private var totalSampleProcessingTimeUs = 0L
|
||||
private var loggedSupplementalWrapper = false
|
||||
private var loggedEncryptedSupplementalPassthrough = false
|
||||
private var outputIsProcessed = false
|
||||
|
||||
override fun format(format: Format) {
|
||||
if (!conversionActive) {
|
||||
val codecs = format.codecs
|
||||
if (isDvProfile7Codec(codecs)) {
|
||||
val codecString = codecs ?: ""
|
||||
conversionActive = true
|
||||
logInfo("DV Profile 7 detected ($codecString), mode=$dvMode")
|
||||
when (dvMode) {
|
||||
DvConversionMode.DV81 -> logInfo("DV81: Kodi-style libdovi conversion (convert RPU type 62, drop EL type 63)")
|
||||
DvConversionMode.HEVC_STRIP -> logInfo("HEVC_STRIP: Kodi-compatible strip (drop RPU type 62 and EL type 63 only)")
|
||||
else -> Unit
|
||||
}
|
||||
logInfo(
|
||||
"Original format: mime=${format.sampleMimeType}, codecs=$codecString, " +
|
||||
"initData=${format.initializationData.size} entries " +
|
||||
"(${format.initializationData.mapIndexed { i, d -> "$i:${d.size}B" }.joinToString()})"
|
||||
)
|
||||
val strippedInitializationData = stripInitializationData(format.initializationData)
|
||||
|
||||
val newFormat = when (dvMode) {
|
||||
DvConversionMode.DV81 -> {
|
||||
// Parse DV level from codec string: "dvhe.07.06" → 6
|
||||
val level = codecString.split('.').getOrNull(2)?.toIntOrNull() ?: 6
|
||||
val newCodecs = "dvhe.08.%02d".format(level)
|
||||
val dvConfigRecord = buildDv81ConfigRecord(level)
|
||||
logInfo("DV81: rewriting to $newCodecs, config=${dvConfigRecord.size}B")
|
||||
|
||||
format.buildUpon()
|
||||
.setSampleMimeType(MimeTypes.VIDEO_DOLBY_VISION)
|
||||
.setCodecs(newCodecs)
|
||||
.setInitializationData(strippedInitializationData + dvConfigRecord)
|
||||
.build()
|
||||
}
|
||||
else -> {
|
||||
// HEVC_STRIP: present as plain HEVC
|
||||
logInfo("HEVC_STRIP: rewriting to video/hevc")
|
||||
format.buildUpon()
|
||||
.setSampleMimeType(MimeTypes.VIDEO_H265)
|
||||
.setCodecs(null)
|
||||
.setInitializationData(strippedInitializationData)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
logInfo(
|
||||
"Rewritten format: mime=${newFormat.sampleMimeType}, " +
|
||||
"codecs=${newFormat.codecs}, initData=${newFormat.initializationData.size} entries"
|
||||
)
|
||||
delegate.format(newFormat)
|
||||
return
|
||||
}
|
||||
}
|
||||
delegate.format(format)
|
||||
}
|
||||
|
||||
override val transformEnabled: Boolean
|
||||
get() = conversionActive
|
||||
|
||||
override val transformedBuffer: ByteArray
|
||||
get() = if (outputIsProcessed) outputBuf else inputBuffer
|
||||
|
||||
override fun transformSample(inputLength: Int, flags: Int): Int {
|
||||
val processStartNs = System.nanoTime()
|
||||
outputIsProcessed = if ((flags and C.BUFFER_FLAG_ENCRYPTED) != 0) {
|
||||
if (!loggedEncryptedSupplementalPassthrough && (flags and C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA) != 0) {
|
||||
loggedEncryptedSupplementalPassthrough = true
|
||||
logWarn("Encrypted supplemental sample encountered, passing raw sample")
|
||||
}
|
||||
false
|
||||
} else {
|
||||
try {
|
||||
processSampleData(flags, inputLength)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
logError("NAL processing failed, passing raw sample", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
val transformedLength = if (outputIsProcessed) outputLen else inputLength
|
||||
if (outputIsProcessed) {
|
||||
recordSampleProcessing((System.nanoTime() - processStartNs) / 1_000L)
|
||||
}
|
||||
|
||||
// Skip empty samples (all NALs were DV layers) — don't confuse the decoder.
|
||||
return if (transformedLength == 0) -1 else transformedLength
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a sample, unwrapping Media3 supplemental-data framing when present.
|
||||
*
|
||||
* Samples with C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA are stored as:
|
||||
* [4-byte big-endian main sample size][main sample][supplemental data].
|
||||
* Only the main sample contains video NALs and should be rewritten.
|
||||
*/
|
||||
private fun processSampleData(flags: Int, dataLen: Int) {
|
||||
if ((flags and C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA) == 0) {
|
||||
processNalUnits(0, dataLen)
|
||||
return
|
||||
}
|
||||
|
||||
if (dataLen < 4) {
|
||||
logWarn("Bad supplemental sample: ${dataLen}B is too small")
|
||||
copyRawSample(dataLen)
|
||||
return
|
||||
}
|
||||
|
||||
val mainSampleLen = readInt32BE(inputBuffer, 0)
|
||||
if (mainSampleLen < 0 || mainSampleLen > dataLen - 4) {
|
||||
logWarn("Bad supplemental sample: mainLen=$mainSampleLen total=$dataLen")
|
||||
copyRawSample(dataLen)
|
||||
return
|
||||
}
|
||||
|
||||
val supplementalLen = dataLen - 4 - mainSampleLen
|
||||
if (!loggedSupplementalWrapper) {
|
||||
loggedSupplementalWrapper = true
|
||||
logDebug(
|
||||
"Supplemental wrapper detected: total=${dataLen}B, main=${mainSampleLen}B, " +
|
||||
"supplemental=${supplementalLen}B, innerFirstBytes=${formatBytes(inputBuffer, 4, 8)}"
|
||||
)
|
||||
}
|
||||
|
||||
processNalUnits(4, mainSampleLen)
|
||||
|
||||
val processedMainLen = outputLen
|
||||
if (processedMainLen == 0) {
|
||||
outputLen = 0
|
||||
return
|
||||
}
|
||||
|
||||
ensureOutputCapacity(4 + processedMainLen + supplementalLen)
|
||||
System.arraycopy(outputBuf, 0, outputBuf, 4, processedMainLen)
|
||||
writeInt32BE(outputBuf, 0, processedMainLen)
|
||||
if (supplementalLen > 0) {
|
||||
System.arraycopy(inputBuffer, 4 + mainSampleLen, outputBuf, 4 + processedMainLen, supplementalLen)
|
||||
}
|
||||
outputLen = 4 + processedMainLen + supplementalLen
|
||||
|
||||
if (sampleCount <= 3 || (sampleCount % 500 == 0L)) {
|
||||
logDebug(
|
||||
"Sample #$sampleCount (Supplemental): main=${mainSampleLen}B -> ${processedMainLen}B, " +
|
||||
"supplemental=${supplementalLen}B, total=${dataLen}B -> ${outputLen}B"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process NAL units in sampleBuf[dataOffset..dataOffset+dataLen). Auto-detects format:
|
||||
* - Annex B (00 00 00 01 / 00 00 01 start codes) — used by MatroskaExtractor
|
||||
* - Length-prefixed (4-byte big-endian length) — used by Mp4Extractor
|
||||
*
|
||||
* Result is written to outputBuf[0..outputLen).
|
||||
*/
|
||||
private fun processNalUnits(dataOffset: Int, dataLen: Int) {
|
||||
outputLen = 0
|
||||
if (dataLen < 4) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
System.arraycopy(inputBuffer, dataOffset, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
return
|
||||
}
|
||||
|
||||
// Auto-detect: Annex B starts with 00 00 00 01 or 00 00 01
|
||||
val isAnnexB = (
|
||||
dataLen >= 4 &&
|
||||
inputBuffer[dataOffset] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 1] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 2] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 3] == 1.toByte()
|
||||
) ||
|
||||
(
|
||||
dataLen >= 3 &&
|
||||
inputBuffer[dataOffset] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 1] == 0.toByte() &&
|
||||
inputBuffer[dataOffset + 2] == 1.toByte()
|
||||
)
|
||||
|
||||
if (sampleCount == 0L) {
|
||||
logDebug(
|
||||
"NAL format detected: ${if (isAnnexB) "Annex B" else "length-prefixed"}, " +
|
||||
"first bytes: ${formatBytes(inputBuffer, dataOffset, 8)}"
|
||||
)
|
||||
}
|
||||
|
||||
if (isAnnexB) processAnnexBNals(dataOffset, dataLen) else processLengthPrefixedNals(dataOffset, dataLen)
|
||||
}
|
||||
|
||||
/** Process Annex B formatted NAL units (MKV path). Scans inline, no list allocation. */
|
||||
private fun processAnnexBNals(dataOffset: Int, dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
val dataEnd = dataOffset + dataLen
|
||||
var kept = 0
|
||||
var stripped = 0
|
||||
|
||||
// Find first start code
|
||||
var scEnd = -1
|
||||
var i = dataOffset
|
||||
while (i < dataEnd - 2) {
|
||||
if (inputBuffer[i] == 0.toByte() && inputBuffer[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataEnd && inputBuffer[i + 2] == 0.toByte() && inputBuffer[i + 3] == 1.toByte()) {
|
||||
scEnd = i + 4
|
||||
break
|
||||
} else if (inputBuffer[i + 2] == 1.toByte()) {
|
||||
scEnd = i + 3
|
||||
break
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if (scEnd < 0) {
|
||||
// No start codes found — pass through
|
||||
System.arraycopy(inputBuffer, dataOffset, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
sampleCount++
|
||||
return
|
||||
}
|
||||
|
||||
var nalStart = scEnd
|
||||
|
||||
while (nalStart < dataEnd) {
|
||||
// Find next start code to determine end of current NAL
|
||||
var nalEnd = dataEnd
|
||||
i = nalStart
|
||||
while (i < dataEnd - 2) {
|
||||
if (inputBuffer[i] == 0.toByte() && inputBuffer[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < dataEnd && inputBuffer[i + 2] == 0.toByte() && inputBuffer[i + 3] == 1.toByte()) {
|
||||
nalEnd = i
|
||||
break
|
||||
} else if (inputBuffer[i + 2] == 1.toByte()) {
|
||||
nalEnd = i
|
||||
break
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
val nalLen = nalEnd - nalStart
|
||||
if (nalLen > 0) {
|
||||
val action = processNalInline(nalStart, nalLen)
|
||||
if (action == NalAction.KEEP) {
|
||||
ensureOutputCapacity(outputLen + 4 + nalLen)
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
System.arraycopy(inputBuffer, nalStart, outputBuf, outputLen, nalLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
} else if (action == NalAction.CONVERT) {
|
||||
val convertedLen = convertRpuIntoOutput(nalStart, nalLen, outputLen + 4)
|
||||
if (convertedLen >= 0) {
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
outputLen += convertedLen
|
||||
convertedRpuCount++
|
||||
kept++
|
||||
} else {
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
} else {
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
}
|
||||
|
||||
// Advance past the next start code
|
||||
if (nalEnd >= dataEnd) break
|
||||
nalStart = if (nalEnd + 3 < dataEnd && inputBuffer[nalEnd + 2] == 0.toByte() && inputBuffer[nalEnd + 3] == 1.toByte()) {
|
||||
nalEnd + 4
|
||||
} else {
|
||||
nalEnd + 3
|
||||
}
|
||||
}
|
||||
|
||||
sampleCount++
|
||||
if (sampleCount <= 3 || (sampleCount % 500 == 0L)) {
|
||||
logDebug(
|
||||
"Sample #$sampleCount (AnnexB): ${dataLen}B -> ${outputLen}B, " +
|
||||
"kept=$kept stripped=$stripped NALs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Process length-prefixed NAL units (MP4 path). */
|
||||
private fun processLengthPrefixedNals(dataOffset: Int, dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
val dataEnd = dataOffset + dataLen
|
||||
var pos = dataOffset
|
||||
var kept = 0
|
||||
var stripped = 0
|
||||
|
||||
while (pos + 4 <= dataEnd) {
|
||||
val nalLen = ((inputBuffer[pos].toInt() and 0xFF) shl 24) or
|
||||
((inputBuffer[pos + 1].toInt() and 0xFF) shl 16) or
|
||||
((inputBuffer[pos + 2].toInt() and 0xFF) shl 8) or
|
||||
(inputBuffer[pos + 3].toInt() and 0xFF)
|
||||
|
||||
if (nalLen <= 0 || pos + 4 + nalLen > dataEnd) {
|
||||
if (sampleCount < 5) {
|
||||
logWarn("Bad NAL length $nalLen at pos ${pos - dataOffset} (data.size=$dataLen)")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
val nalStart = pos + 4
|
||||
val action = processNalInline(nalStart, nalLen)
|
||||
if (action == NalAction.KEEP) {
|
||||
ensureOutputCapacity(outputLen + 4 + nalLen)
|
||||
writeInt32BE(outputBuf, outputLen, nalLen)
|
||||
outputLen += 4
|
||||
System.arraycopy(inputBuffer, nalStart, outputBuf, outputLen, nalLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
} else if (action == NalAction.CONVERT) {
|
||||
val convertedLen = convertRpuIntoOutput(nalStart, nalLen, outputLen + 4)
|
||||
if (convertedLen >= 0) {
|
||||
writeInt32BE(outputBuf, outputLen, convertedLen)
|
||||
outputLen += 4
|
||||
outputLen += convertedLen
|
||||
convertedRpuCount++
|
||||
kept++
|
||||
} else {
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
} else {
|
||||
recordStrippedNal(action)
|
||||
stripped++
|
||||
}
|
||||
|
||||
pos += 4 + nalLen
|
||||
}
|
||||
|
||||
sampleCount++
|
||||
if (sampleCount <= 3 || (sampleCount % 500 == 0L)) {
|
||||
logDebug(
|
||||
"Sample #$sampleCount (LenPrefix): ${dataLen}B -> ${outputLen}B, " +
|
||||
"kept=$kept stripped=$stripped NALs"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private enum class NalAction { KEEP, STRIP_RPU, STRIP_EL, CONVERT }
|
||||
|
||||
private fun recordStrippedNal(action: NalAction) {
|
||||
strippedNalCount++
|
||||
// CONVERT reaches here only after conversion fails; raw P7 RPUs are not safe in P8.1 output.
|
||||
when (action) {
|
||||
NalAction.STRIP_RPU, NalAction.CONVERT -> strippedRpuNalCount++
|
||||
NalAction.STRIP_EL -> strippedElNalCount++
|
||||
NalAction.KEEP -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun convertRpuIntoOutput(nalStart: Int, nalLen: Int, outputOffset: Int): Int {
|
||||
ensureOutputCapacity(outputOffset + MAX_CONVERTED_RPU_SIZE)
|
||||
|
||||
var retriedAfterResize = false
|
||||
while (true) {
|
||||
val startNs = System.nanoTime()
|
||||
val written = DoviBridge.convertRpuNalu(
|
||||
payload = inputBuffer,
|
||||
payloadOffset = nalStart,
|
||||
payloadLength = nalLen,
|
||||
output = outputBuf,
|
||||
outputOffset = outputOffset,
|
||||
outputCapacity = outputBuf.size,
|
||||
mode = LIBDOVI_MODE_TO_81
|
||||
)
|
||||
totalRpuConversionTimeUs += (System.nanoTime() - startNs) / 1_000L
|
||||
rpuConversionCallCount++
|
||||
|
||||
if (written >= 0) return written
|
||||
|
||||
if (written == DoviBridge.DESTINATION_TOO_SMALL) {
|
||||
rpuOutputTooSmallCount++
|
||||
if (!retriedAfterResize) {
|
||||
val doubled = if (outputBuf.size <= Int.MAX_VALUE / 2) outputBuf.size * 2 else Int.MAX_VALUE
|
||||
ensureOutputCapacity(maxOf(doubled, outputOffset + MAX_CONVERTED_RPU_SIZE))
|
||||
retriedAfterResize = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
rpuConversionFailureCount++
|
||||
return written
|
||||
}
|
||||
}
|
||||
|
||||
private fun recordSampleProcessing(elapsedUs: Long) {
|
||||
totalSampleProcessingTimeUs += elapsedUs
|
||||
if (sampleCount <= 3 || (sampleCount > 0 && sampleCount % 500 == 0L)) {
|
||||
logDebug(
|
||||
"Perf: avgSample=${averageSampleProcessingTimeUs}us, " +
|
||||
"avgRpu=${averageRpuConversionTimeUs}us, converted=$convertedRpuCount, " +
|
||||
"rpuFailures=$rpuConversionFailureCount, rpuTooSmall=$rpuOutputTooSmallCount"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stripInitializationData(initializationData: List<ByteArray>): List<ByteArray> {
|
||||
if (initializationData.isEmpty()) return emptyList()
|
||||
|
||||
val stripped = ArrayList<ByteArray>(initializationData.size)
|
||||
var beforeBytes = 0
|
||||
var afterBytes = 0
|
||||
var droppedBuffers = 0
|
||||
|
||||
for (data in initializationData) {
|
||||
beforeBytes += data.size
|
||||
val processed = stripInitializationAnnexB(data)
|
||||
if (processed == null) {
|
||||
// Media3's HEVC init data is normally Annex B. Non-AnnexB entries in
|
||||
// Dolby Vision formats are typically dvcC/dvvC records, which must not
|
||||
// be forwarded when advertising plain HEVC.
|
||||
droppedBuffers++
|
||||
continue
|
||||
}
|
||||
if (processed.isEmpty()) {
|
||||
droppedBuffers++
|
||||
continue
|
||||
}
|
||||
afterBytes += processed.size
|
||||
stripped.add(processed)
|
||||
}
|
||||
|
||||
logInfo(
|
||||
"Init data stripped: ${initializationData.size} entries/${beforeBytes}B -> " +
|
||||
"${stripped.size} entries/${afterBytes}B, strippedNals=$strippedInitNalCount, " +
|
||||
"droppedBuffers=$droppedBuffers"
|
||||
)
|
||||
|
||||
return stripped
|
||||
}
|
||||
|
||||
private fun stripInitializationAnnexB(data: ByteArray): ByteArray? {
|
||||
if (data.isEmpty()) return data
|
||||
|
||||
val firstStartCodeEnd = findStartCodeEnd(data, 0) ?: return null
|
||||
ensureOutputCapacity(data.size)
|
||||
outputLen = 0
|
||||
|
||||
var kept = 0
|
||||
var stripped = 0
|
||||
var nalStart = firstStartCodeEnd
|
||||
|
||||
while (nalStart < data.size) {
|
||||
val nalEnd = findNextStartCodeOffset(data, nalStart) ?: data.size
|
||||
val nalLen = nalEnd - nalStart
|
||||
if (nalLen > 0) {
|
||||
when (classifyNal(data, nalStart, nalLen, convertRpu = false)) {
|
||||
NalAction.KEEP -> {
|
||||
ensureOutputCapacity(outputLen + 4 + nalLen)
|
||||
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
|
||||
outputLen += 4
|
||||
System.arraycopy(data, nalStart, outputBuf, outputLen, nalLen)
|
||||
outputLen += nalLen
|
||||
kept++
|
||||
}
|
||||
else -> {
|
||||
strippedInitNalCount++
|
||||
stripped++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (nalEnd >= data.size) break
|
||||
nalStart = findStartCodeEnd(data, nalEnd) ?: break
|
||||
}
|
||||
|
||||
logDebug("Init data sample: ${data.size}B -> ${outputLen}B, kept=$kept stripped=$stripped NALs")
|
||||
return outputBuf.copyOf(outputLen)
|
||||
}
|
||||
|
||||
private fun findStartCodeEnd(data: ByteArray, from: Int): Int? {
|
||||
var i = from
|
||||
while (i < data.size - 2) {
|
||||
if (data[i] == 0.toByte() && data[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < data.size && data[i + 2] == 0.toByte() && data[i + 3] == 1.toByte()) {
|
||||
return i + 4
|
||||
} else if (data[i + 2] == 1.toByte()) {
|
||||
return i + 3
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findNextStartCodeOffset(data: ByteArray, from: Int): Int? {
|
||||
var i = from
|
||||
while (i < data.size - 2) {
|
||||
if (data[i] == 0.toByte() && data[i + 1] == 0.toByte()) {
|
||||
if (i + 3 < data.size && data[i + 2] == 0.toByte() && data[i + 3] == 1.toByte()) {
|
||||
return i
|
||||
} else if (data[i + 2] == 1.toByte()) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
i++
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Classify a NAL at sampleBuf[offset..offset+len) without copying. */
|
||||
private fun processNalInline(offset: Int, len: Int): NalAction = classifyNal(inputBuffer, offset, len, convertRpu = dvMode == DvConversionMode.DV81)
|
||||
|
||||
private fun isDvProfile7Codec(codecs: String?): Boolean {
|
||||
val normalized = codecs?.lowercase() ?: return false
|
||||
return normalized.startsWith("dvhe.07") || normalized.startsWith("dvh1.07")
|
||||
}
|
||||
|
||||
private fun classifyNal(data: ByteArray, offset: Int, len: Int, convertRpu: Boolean): NalAction {
|
||||
if (len < 2) return NalAction.KEEP
|
||||
val nalType = (data[offset].toInt() ushr 1) and 0x3F
|
||||
return when {
|
||||
nalType == NAL_TYPE_UNSPEC62 && convertRpu -> NalAction.CONVERT
|
||||
nalType == NAL_TYPE_UNSPEC62 -> NalAction.STRIP_RPU
|
||||
nalType == NAL_TYPE_UNSPEC63 -> NalAction.STRIP_EL
|
||||
else -> NalAction.KEEP
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeInt32BE(buf: ByteArray, offset: Int, value: Int) {
|
||||
buf[offset] = ((value ushr 24) and 0xFF).toByte()
|
||||
buf[offset + 1] = ((value ushr 16) and 0xFF).toByte()
|
||||
buf[offset + 2] = ((value ushr 8) and 0xFF).toByte()
|
||||
buf[offset + 3] = (value and 0xFF).toByte()
|
||||
}
|
||||
|
||||
private fun readInt32BE(buf: ByteArray, offset: Int): Int = ((buf[offset].toInt() and 0xFF) shl 24) or
|
||||
((buf[offset + 1].toInt() and 0xFF) shl 16) or
|
||||
((buf[offset + 2].toInt() and 0xFF) shl 8) or
|
||||
(buf[offset + 3].toInt() and 0xFF)
|
||||
|
||||
private fun copyRawSample(dataLen: Int) {
|
||||
ensureOutputCapacity(dataLen)
|
||||
System.arraycopy(inputBuffer, 0, outputBuf, 0, dataLen)
|
||||
outputLen = dataLen
|
||||
}
|
||||
|
||||
private fun formatBytes(data: ByteArray, offset: Int, length: Int): String {
|
||||
val end = minOf(data.size, offset + length)
|
||||
if (offset >= end) return ""
|
||||
return (offset until end).joinToString(" ") { "%02X".format(data[it]) }
|
||||
}
|
||||
|
||||
private fun ensureOutputCapacity(needed: Int) {
|
||||
if (outputBuf.size < needed) {
|
||||
outputBuf = outputBuf.copyOf(maxOf(needed, outputBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun logDebug(message: String) {
|
||||
Log.d(TAG, message)
|
||||
emitLog?.invoke("debug", "dv-convert", message)
|
||||
}
|
||||
|
||||
private fun logInfo(message: String) {
|
||||
Log.i(TAG, message)
|
||||
emitLog?.invoke("info", "dv-convert", message)
|
||||
}
|
||||
|
||||
private fun logWarn(message: String) {
|
||||
Log.w(TAG, message)
|
||||
emitLog?.invoke("warn", "dv-convert", message)
|
||||
}
|
||||
|
||||
private fun logError(message: String, throwable: Throwable) {
|
||||
Log.e(TAG, message, throwable)
|
||||
emitLog?.invoke("error", "dv-convert", "$message: ${throwable.message}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a 24-byte DOVIDecoderConfigurationRecord for DV Profile 8.1.
|
||||
*
|
||||
* Binary layout (from Dolby Vision spec):
|
||||
* byte[0]: dv_version_major = 1
|
||||
* byte[1]: dv_version_minor = 0
|
||||
* byte[2]: dv_profile (7 bits) | dv_level MSB (1 bit)
|
||||
* byte[3]: dv_level low 5 bits (5 bits) | rpu_present (1) | el_present (1) | bl_present (1)
|
||||
* byte[4]: bl_compatibility_id (4 bits) | md_compression (2 bits) | reserved (2 bits)
|
||||
* byte[5-23]: reserved (zeros)
|
||||
*/
|
||||
private fun buildDv81ConfigRecord(level: Int): ByteArray {
|
||||
val record = ByteArray(24)
|
||||
record[0] = 0x01 // dv_version_major = 1
|
||||
record[1] = 0x00 // dv_version_minor = 0
|
||||
record[2] = ((8 shl 1) or ((level ushr 5) and 0x01)).toByte() // profile=8 | level MSB
|
||||
record[3] = (((level and 0x1F) shl 3) or 0x05).toByte() // level low 5 | rpu=1 el=0 bl=1
|
||||
record[4] = (1 shl 4).toByte() // bl_compatibility_id=1 (HDR10)
|
||||
// bytes 5-23 remain 0 (reserved)
|
||||
return record
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
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.TrackOutput
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that intercepts video track creation
|
||||
* to insert DoviConvertingTrackOutput for DV processing.
|
||||
* Shared by DoviExtractorWrapper for both MP4 and MKV containers.
|
||||
*/
|
||||
class DoviExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput,
|
||||
private val dvMode: DvConversionMode,
|
||||
private val emitLog: ((String, String, String) -> Unit)?,
|
||||
private val onVideoTrackWrapped: (DoviConvertingTrackOutput) -> Unit
|
||||
) : ExtractorOutput {
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (type == C.TRACK_TYPE_VIDEO) {
|
||||
val wrapper = DoviConvertingTrackOutput(original, dvMode, emitLog)
|
||||
onVideoTrackWrapped(wrapper)
|
||||
return wrapper
|
||||
}
|
||||
return original
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
|
||||
/**
|
||||
* Extractor decorator for Mp4/FragmentedMp4 containers.
|
||||
* Wraps the video TrackOutput with DoviConvertingTrackOutput to perform
|
||||
* DV Profile 7 → 8.1 conversion via inline NAL processing.
|
||||
*/
|
||||
class DoviExtractorWrapper(
|
||||
private val delegate: Extractor,
|
||||
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
|
||||
private val emitLog: ((String, String, String) -> Unit)? = null
|
||||
) : Extractor {
|
||||
|
||||
@Volatile var doviTrackOutput: DoviConvertingTrackOutput? = null
|
||||
private set
|
||||
|
||||
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
|
||||
|
||||
override fun init(output: ExtractorOutput) {
|
||||
delegate.init(DoviExtractorOutputWrapper(output, dvMode, emitLog) { doviTrackOutput = it })
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Stereo downmix coefficient builder (Kodi-style center boost).
|
||||
*
|
||||
* Channel-order assumptions per input count follow the Android channel-mask
|
||||
* bit order that MediaCodec / the FFmpeg extension emit:
|
||||
* 3 = FL FR FC, 4 = FL FR BL BR, 5 = FL FR FC BL BR, 6 = FL FR FC LFE BL BR,
|
||||
* 7 = 6.1 (5.1 + BC), 8 = 7.1 (5.1 + SL SR). LFE is dropped, matching
|
||||
* ffmpeg's default lfe_mix_level=0 (and what the mpv backends produce).
|
||||
*
|
||||
* All coefficients must stay >= 0: ChannelMixingMatrix throws on negatives.
|
||||
*/
|
||||
object DownmixMatrices {
|
||||
const val MIN_DOWNMIX_INPUT_CHANNELS = 3
|
||||
const val MAX_DOWNMIX_INPUT_CHANNELS = 8
|
||||
const val MAX_CENTER_BOOST_DB = 12
|
||||
|
||||
const val SURROUND_GAIN = 0.70710678f // -3 dB
|
||||
private const val BACK_CENTER_GAIN = 0.5f // SURROUND_GAIN split across both outputs
|
||||
|
||||
/** Kodi's mechanism: center coefficient = 10^((-3 + boostDb) / 20); boost 0 is the standard -3 dB. */
|
||||
fun centerGain(centerBoostDb: Int): Float = 10f.pow((-3f + centerBoostDb.coerceIn(0, MAX_CENTER_BOOST_DB)) / 20f)
|
||||
|
||||
/**
|
||||
* Row-major stereo coefficients ([inputChannel * 2 + outputChannel]), or null
|
||||
* when [inputChannels] is not downmixed (mono/stereo pass through; >8ch
|
||||
* unsupported, the caller keeps an identity matrix).
|
||||
*
|
||||
* [normalize] scales the matrix so the loudest output sum is <= 1 (cannot
|
||||
* clip); disabled keeps the original level like Kodi's "maintain original
|
||||
* volume" (the 16-bit mix saturates on clip).
|
||||
*/
|
||||
fun stereoCoefficients(inputChannels: Int, centerBoostDb: Int, normalize: Boolean): FloatArray? {
|
||||
val c = centerGain(centerBoostDb)
|
||||
val s = SURROUND_GAIN
|
||||
val rows: List<FloatArray> = when (inputChannels) {
|
||||
3 -> listOf(fl(), fr(), both(c))
|
||||
4 -> listOf(fl(), fr(), left(s), right(s))
|
||||
5 -> listOf(fl(), fr(), both(c), left(s), right(s))
|
||||
6 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s))
|
||||
7 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s), both(BACK_CENTER_GAIN))
|
||||
8 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s), left(s), right(s))
|
||||
else -> return null
|
||||
}
|
||||
val flat = FloatArray(rows.size * 2)
|
||||
rows.forEachIndexed { i, row ->
|
||||
flat[i * 2] = row[0]
|
||||
flat[i * 2 + 1] = row[1]
|
||||
}
|
||||
if (normalize) {
|
||||
var sumL = 0f
|
||||
var sumR = 0f
|
||||
for (i in rows.indices) {
|
||||
sumL += flat[i * 2]
|
||||
sumR += flat[i * 2 + 1]
|
||||
}
|
||||
val peak = maxOf(sumL, sumR, 1f)
|
||||
if (peak > 1f) {
|
||||
for (i in flat.indices) flat[i] /= peak
|
||||
}
|
||||
}
|
||||
return flat
|
||||
}
|
||||
|
||||
private fun fl() = floatArrayOf(1f, 0f)
|
||||
private fun fr() = floatArrayOf(0f, 1f)
|
||||
private fun left(gain: Float) = floatArrayOf(gain, 0f)
|
||||
private fun right(gain: Float) = floatArrayOf(0f, gain)
|
||||
private fun both(gain: Float) = floatArrayOf(gain, gain)
|
||||
private fun lfe() = floatArrayOf(0f, 0f)
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* In-place sanitizer for HEVC Annex B buffers carrying both Dolby Vision and HDR10+
|
||||
* dynamic metadata. Buggy chipsets (Fire TV 4K Max, MediaTek-based Google TV, ...)
|
||||
* crash or black-screen when a native DV codec also receives in-band HDR10+ SEI, so
|
||||
* only the metadata the active decode path consumes may be kept:
|
||||
*
|
||||
* - Native DV codec: strip HDR10+ SEI NALs (types 39/40 with ST 2094-40 payload),
|
||||
* the decoder follows the DV RPU. Port of androidx/media#3085 / Kodi xbmc#24584.
|
||||
* - HEVC fallback for a DV format: strip DV RPU/EL NALs (types 62/63) instead,
|
||||
* leaving HDR10+ for the display.
|
||||
*
|
||||
* Runs on the playback thread against MediaCodec's direct input buffers, where
|
||||
* per-byte ByteBuffer accessor calls are far too slow for high-bitrate UHD remuxes
|
||||
* (#1313). Each sample is therefore staged through a reusable heap array with a
|
||||
* single bulk get, scanned and compacted with array ops, and only the modified tail
|
||||
* is written back. Instances are not thread-safe: use one per renderer.
|
||||
*
|
||||
* Pure JVM (no android/media3 imports) so it stays unit-testable on the host.
|
||||
*/
|
||||
class DvBitstreamSanitizer {
|
||||
|
||||
private companion object {
|
||||
const val NAL_TYPE_PREFIX_SEI = 39
|
||||
const val NAL_TYPE_SUFFIX_SEI = 40
|
||||
const val NAL_TYPE_UNSPEC62 = 62 // DV RPU
|
||||
const val NAL_TYPE_UNSPEC63 = 63 // DV Enhancement Layer
|
||||
|
||||
const val SEI_PAYLOAD_TYPE_ITU_T_T35 = 4
|
||||
|
||||
const val INITIAL_SCRATCH_SIZE = 256 * 1024
|
||||
}
|
||||
|
||||
/** Reusable staging buffer — grown as needed, never shrunk. */
|
||||
private var scratch = ByteArray(INITIAL_SCRATCH_SIZE)
|
||||
|
||||
/**
|
||||
* Scans `[position, limit)` of [data] for Annex B NAL units and removes the selected
|
||||
* metadata NALs by compacting the buffer in place and reducing its limit. The position
|
||||
* is left unchanged. Returns the number of NAL units stripped.
|
||||
*
|
||||
* A sample with no start codes at all is left untouched: it cannot contain the
|
||||
* targeted NALs, and emptying it would only confuse the decoder.
|
||||
*/
|
||||
fun sanitize(data: ByteBuffer, stripHdr10PlusSei: Boolean, stripDvRpu: Boolean): Int {
|
||||
val startPos = data.position()
|
||||
val len = data.limit() - startPos
|
||||
if (len == 0) return 0
|
||||
if (scratch.size < len) scratch = ByteArray(maxOf(len, scratch.size * 2))
|
||||
val buf = scratch
|
||||
data.get(buf, 0, len)
|
||||
data.position(startPos)
|
||||
|
||||
var writeLen = 0
|
||||
var firstModified = -1
|
||||
var strippedCount = 0
|
||||
var nalStartIndex = -1
|
||||
var startCodeLen = 0
|
||||
|
||||
var i = 0
|
||||
while (i <= len) {
|
||||
// Find next start code or end of buffer.
|
||||
val atEnd = i == len
|
||||
var foundStartCode = false
|
||||
var nextStartCodeLen = 0
|
||||
if (!atEnd && i + 2 < len && buf[i].toInt() == 0 && buf[i + 1].toInt() == 0) {
|
||||
if (buf[i + 2].toInt() == 1) {
|
||||
foundStartCode = true
|
||||
nextStartCodeLen = 3
|
||||
} else if (buf[i + 2].toInt() == 0 && i + 3 < len && buf[i + 3].toInt() == 1) {
|
||||
foundStartCode = true
|
||||
nextStartCodeLen = 4
|
||||
}
|
||||
}
|
||||
|
||||
if (foundStartCode || atEnd) {
|
||||
if (nalStartIndex >= 0) {
|
||||
// Complete NAL unit (including its start code) from nalStartIndex to i.
|
||||
val nalDataStart = nalStartIndex + startCodeLen
|
||||
val nalEnd = i
|
||||
var strip = false
|
||||
|
||||
if (nalEnd - nalDataStart >= 2) {
|
||||
// HEVC NAL header: forbidden_zero_bit(1) + nal_unit_type(6) + nuh_layer_id MSB(1).
|
||||
val nalUnitType = (buf[nalDataStart].toInt() and 0x7E) shr 1
|
||||
strip = when (nalUnitType) {
|
||||
NAL_TYPE_UNSPEC62, NAL_TYPE_UNSPEC63 -> stripDvRpu
|
||||
NAL_TYPE_PREFIX_SEI, NAL_TYPE_SUFFIX_SEI ->
|
||||
stripHdr10PlusSei && isHdr10PlusSeiNalUnit(buf, nalDataStart + 2, nalEnd)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
if (strip) {
|
||||
strippedCount++
|
||||
if (firstModified < 0) firstModified = writeLen
|
||||
} else {
|
||||
if (writeLen != nalStartIndex) {
|
||||
// Also reached with zero strips when bytes precede the first start code.
|
||||
if (firstModified < 0) firstModified = writeLen
|
||||
System.arraycopy(buf, nalStartIndex, buf, writeLen, nalEnd - nalStartIndex)
|
||||
}
|
||||
writeLen += nalEnd - nalStartIndex
|
||||
}
|
||||
}
|
||||
nalStartIndex = i
|
||||
startCodeLen = nextStartCodeLen
|
||||
i += if (nextStartCodeLen > 0) nextStartCodeLen else 1
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if (writeLen == len || firstModified < 0) return 0
|
||||
|
||||
// Bytes before firstModified are byte-identical to the buffer; write back only the tail.
|
||||
data.position(startPos + firstModified)
|
||||
data.put(buf, firstModified, writeLen - firstModified)
|
||||
data.limit(startPos + writeLen)
|
||||
data.position(startPos)
|
||||
return strippedCount
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the SEI RBSP (starting after the 2-byte HEVC NAL header) begins with an
|
||||
* HDR10+ message: user_data_registered_itu_t_t35 with country code 0xB5 (United States),
|
||||
* provider code 0x003C (Samsung), provider oriented code 0x0001, application identifier 4
|
||||
* (ST 2094-40), application version 0 or 1. Malformed/truncated data returns false so the
|
||||
* NAL is kept.
|
||||
*/
|
||||
private fun isHdr10PlusSeiNalUnit(buf: ByteArray, rbspStart: Int, nalEnd: Int): Boolean {
|
||||
var pos = rbspStart
|
||||
if (pos >= nalEnd) return false
|
||||
|
||||
// SEI payload type: accumulated 0xFF bytes plus the final byte.
|
||||
var payloadType = 0
|
||||
while (pos < nalEnd) {
|
||||
val b = buf[pos++].toInt() and 0xFF
|
||||
payloadType += b
|
||||
if (b != 0xFF) break
|
||||
}
|
||||
|
||||
// SEI payload size, same encoding.
|
||||
var payloadSize = 0
|
||||
while (pos < nalEnd) {
|
||||
val b = buf[pos++].toInt() and 0xFF
|
||||
payloadSize += b
|
||||
if (b != 0xFF) break
|
||||
}
|
||||
|
||||
if (payloadType != SEI_PAYLOAD_TYPE_ITU_T_T35 || payloadSize < 7 || pos + 7 > nalEnd) {
|
||||
return false
|
||||
}
|
||||
|
||||
// The identifier bytes (B5 00 3C 00 01 04 00/01) cannot contain the 0x000003 emulation
|
||||
// prevention pattern, so they can be read without RBSP unescaping.
|
||||
val countryCode = buf[pos].toInt() and 0xFF
|
||||
val providerCode = ((buf[pos + 1].toInt() and 0xFF) shl 8) or (buf[pos + 2].toInt() and 0xFF)
|
||||
val orientedCode = ((buf[pos + 3].toInt() and 0xFF) shl 8) or (buf[pos + 4].toInt() and 0xFF)
|
||||
val appIdentifier = buf[pos + 5].toInt() and 0xFF
|
||||
val appVersion = buf[pos + 6].toInt() and 0xFF
|
||||
|
||||
return countryCode == 0xB5 &&
|
||||
providerCode == 0x003C &&
|
||||
orientedCode == 0x0001 &&
|
||||
appIdentifier == 4 &&
|
||||
(appVersion == 0 || appVersion == 1)
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.mkv.MatroskaExtractor
|
||||
|
||||
/** MKV CodecID for Microsoft ACM compatibility mode. */
|
||||
private const val CODEC_ID_ACM = "A_MS/ACM"
|
||||
|
||||
/**
|
||||
* MatroskaExtractor.init is final and extractorOutput private; subclasses swap
|
||||
* in wrapping outputs via reflection once the Segment element starts (shared
|
||||
* with ZlibMatroskaExtractor).
|
||||
*/
|
||||
internal val matroskaExtractorOutputField by lazy {
|
||||
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
|
||||
isAccessible = true
|
||||
}
|
||||
}
|
||||
|
||||
/** WAVEFORMATEX format tag for LOAS/LATM-wrapped AAC (WAVE_FORMAT_MPEG_LOAS). */
|
||||
private const val WAVE_FORMAT_MPEG_LOAS = 0x1602
|
||||
|
||||
/**
|
||||
* Returns whether a track is LOAS/LATM AAC muxed as A_MS/ACM — ffmpeg's (and
|
||||
* therefore Plex's) fallback mapping for aac_latm, which Matroska has no native
|
||||
* codec ID for. The WAVEFORMATEX wFormatTag is the first 2 bytes (LE) of
|
||||
* CodecPrivate.
|
||||
*/
|
||||
fun isLoasAcmTrack(codecId: String?, codecPrivate: ByteArray?): Boolean = codecId == CODEC_ID_ACM &&
|
||||
codecPrivate != null &&
|
||||
codecPrivate.size >= 2 &&
|
||||
((codecPrivate[0].toInt() and 0xFF) or ((codecPrivate[1].toInt() and 0xFF) shl 8)) == WAVE_FORMAT_MPEG_LOAS
|
||||
|
||||
/**
|
||||
* ExtractorOutput wrapper that wraps marked tracks with [LatmTrackOutput].
|
||||
* Call [markNextTrackLatm] before the parent extractor creates the track
|
||||
* (i.e. before super.endMasterElement(ID_TRACK_ENTRY)).
|
||||
*/
|
||||
class LatmExtractorOutputWrapper(
|
||||
private val delegate: ExtractorOutput
|
||||
) : ExtractorOutput {
|
||||
|
||||
private var nextTrackIsLatm = false
|
||||
private val latmOutputs = mutableListOf<LatmTrackOutput>()
|
||||
|
||||
fun markNextTrackLatm() {
|
||||
nextTrackIsLatm = true
|
||||
}
|
||||
|
||||
/** Resets LATM parser state after an extractor seek. */
|
||||
fun resetTracks() {
|
||||
latmOutputs.forEach { it.reset() }
|
||||
}
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
if (!nextTrackIsLatm) return original
|
||||
nextTrackIsLatm = false
|
||||
return LatmTrackOutput(original, id).also { latmOutputs.add(it) }
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
|
||||
/**
|
||||
* MatroskaExtractor with LOAS/LATM AAC support, used for Plex Live TV MKV
|
||||
* streams (which bypass the ASS/DV extractor chain). VOD playback gets the
|
||||
* same LATM handling via ZlibMatroskaExtractor.
|
||||
*/
|
||||
class LatmMatroskaExtractor(flags: Int) : MatroskaExtractor(flags) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "LatmMkvExtractor"
|
||||
private const val ID_SEGMENT = 0x18538067
|
||||
private const val ID_TRACK_ENTRY = 0xAE
|
||||
}
|
||||
|
||||
private var latmWrapper: LatmExtractorOutputWrapper? = null
|
||||
|
||||
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
|
||||
super.startMasterElement(id, contentPosition, contentSize)
|
||||
|
||||
// init() is final, so install the wrapping output when the Segment starts —
|
||||
// before any TrackEntry can create a track through it.
|
||||
if (id == ID_SEGMENT && latmWrapper == null) {
|
||||
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
|
||||
val wrapper = LatmExtractorOutputWrapper(currentOutput)
|
||||
latmWrapper = wrapper
|
||||
matroskaExtractorOutputField.set(this, wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
override fun endMasterElement(id: Int) {
|
||||
if (id == ID_TRACK_ENTRY) {
|
||||
val track = getCurrentTrack(id)
|
||||
if (isLoasAcmTrack(track.codecId, track.codecPrivate)) {
|
||||
Log.i(TAG, "Track ${track.number} is LOAS/LATM AAC, unwrapping to raw AAC")
|
||||
latmWrapper?.markNextTrackLatm()
|
||||
}
|
||||
}
|
||||
super.endMasterElement(id)
|
||||
}
|
||||
|
||||
override fun seek(position: Long, timeUs: Long) {
|
||||
latmWrapper?.resetTracks()
|
||||
super.seek(position, timeUs)
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.DataReader
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.util.ParsableByteArray
|
||||
import androidx.media3.extractor.ExtractorOutput
|
||||
import androidx.media3.extractor.SeekMap
|
||||
import androidx.media3.extractor.TrackOutput
|
||||
import androidx.media3.extractor.ts.LatmReader
|
||||
import androidx.media3.extractor.ts.TsPayloadReader
|
||||
import java.io.EOFException
|
||||
|
||||
/**
|
||||
* TrackOutput wrapper that unwraps LOAS/LATM-framed AAC (MKV A_MS/ACM with
|
||||
* WAVEFORMATEX tag 0x1602) into raw AAC access units MediaCodec can decode.
|
||||
*
|
||||
* Each MKV block payload is one or more complete LOAS AudioSyncStream frames.
|
||||
* Blocks are buffered between sampleData() and sampleMetadata(), then fed to
|
||||
* media3's LatmReader, which parses the StreamMuxConfig (emitting a proper AAC
|
||||
* Format with AudioSpecificConfig) and outputs byte-aligned raw AAC samples.
|
||||
*
|
||||
* The parent extractor's audio/x-unknown Format is swallowed; its track-selection
|
||||
* metadata (id, label, language, selection flags) is merged onto the Format
|
||||
* LatmReader derives from the stream.
|
||||
*/
|
||||
class LatmTrackOutput(
|
||||
private val delegate: TrackOutput,
|
||||
private val trackId: Int
|
||||
) : TrackOutput {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "LatmTrackOutput"
|
||||
private const val INITIAL_BUFFER_SIZE = 4 * 1024
|
||||
private const val MAX_LOGGED_ERRORS = 3
|
||||
}
|
||||
|
||||
private var latmReader: LatmReader? = null
|
||||
private var originalFormat: Format? = null
|
||||
private val parsable = ParsableByteArray()
|
||||
|
||||
// Reusable block buffer — grown as needed, never shrunk
|
||||
private var buf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var bufLen = 0
|
||||
private var readBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
private var errorCount = 0
|
||||
|
||||
/** Forwards LatmReader's decoded Format merged with the original track metadata. */
|
||||
private val mergeProxy = object : TrackOutput {
|
||||
override fun format(format: Format) {
|
||||
val original = originalFormat
|
||||
val merged = if (original == null) {
|
||||
format
|
||||
} else {
|
||||
format.buildUpon()
|
||||
.setId(original.id)
|
||||
.setLabel(original.label)
|
||||
.setLanguage(original.language ?: format.language)
|
||||
.setSelectionFlags(original.selectionFlags)
|
||||
.build()
|
||||
}
|
||||
delegate.format(merged)
|
||||
}
|
||||
|
||||
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int = delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) = delegate.sampleData(data, length, sampleDataPart)
|
||||
|
||||
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) = delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
|
||||
}
|
||||
|
||||
private val readerExtractorOutput = object : ExtractorOutput {
|
||||
override fun track(id: Int, type: Int): TrackOutput = mergeProxy
|
||||
override fun endTracks() {}
|
||||
override fun seekMap(seekMap: SeekMap) {}
|
||||
}
|
||||
|
||||
override fun format(format: Format) {
|
||||
originalFormat = format
|
||||
if (latmReader == null) {
|
||||
latmReader = LatmReader(format.language, format.roleFlags, MimeTypes.VIDEO_MATROSKA).also {
|
||||
it.createTracks(readerExtractorOutput, TsPayloadReader.TrackIdGenerator(trackId, 1))
|
||||
}
|
||||
}
|
||||
// Swallow the parent's audio/x-unknown Format; LatmReader emits the real
|
||||
// AAC Format (with AudioSpecificConfig) from the first StreamMuxConfig.
|
||||
}
|
||||
|
||||
override fun sampleData(
|
||||
input: DataReader,
|
||||
length: Int,
|
||||
allowEndOfInput: Boolean,
|
||||
sampleDataPart: Int
|
||||
): Int {
|
||||
if (readBuf.size < length) readBuf = ByteArray(length)
|
||||
val bytesRead = input.read(readBuf, 0, length)
|
||||
if (bytesRead == C.RESULT_END_OF_INPUT && !allowEndOfInput) throw EOFException()
|
||||
if (bytesRead > 0) append(readBuf, bytesRead)
|
||||
return bytesRead
|
||||
}
|
||||
|
||||
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
|
||||
ensureCapacity(bufLen + length)
|
||||
data.readBytes(buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
override fun sampleMetadata(
|
||||
timeUs: Long,
|
||||
flags: Int,
|
||||
size: Int,
|
||||
offset: Int,
|
||||
cryptoData: TrackOutput.CryptoData?
|
||||
) {
|
||||
// offset counts down to 0 across a laced BlockGroup; the buffer holds the
|
||||
// whole block's data, so slice this sample out and clear at the last one.
|
||||
val start = bufLen - offset - size
|
||||
val reader = latmReader
|
||||
if (reader == null || start < 0) {
|
||||
if (errorCount++ < MAX_LOGGED_ERRORS) {
|
||||
Log.e(TAG, "Dropping sample (reader=${reader != null}, start=$start, size=$size, offset=$offset)")
|
||||
}
|
||||
if (offset == 0) bufLen = 0
|
||||
return
|
||||
}
|
||||
try {
|
||||
reader.packetStarted(timeUs, 0)
|
||||
parsable.reset(buf, start + size)
|
||||
parsable.position = start
|
||||
reader.consume(parsable)
|
||||
} catch (e: Exception) {
|
||||
if (errorCount++ < MAX_LOGGED_ERRORS) {
|
||||
Log.e(TAG, "LATM parse failed (${size}B), dropping sample", e)
|
||||
}
|
||||
reader.seek() // resync on the next LOAS syncword
|
||||
}
|
||||
if (offset == 0) bufLen = 0
|
||||
}
|
||||
|
||||
/** Drops buffered MKV data while retaining the LATM StreamMuxConfig. */
|
||||
fun reset() {
|
||||
bufLen = 0
|
||||
}
|
||||
|
||||
private fun append(src: ByteArray, length: Int) {
|
||||
ensureCapacity(bufLen + length)
|
||||
System.arraycopy(src, 0, buf, bufLen, length)
|
||||
bufLen += length
|
||||
}
|
||||
|
||||
private fun ensureCapacity(needed: Int) {
|
||||
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
|
||||
}
|
||||
}
|
||||
@@ -1,617 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.Format
|
||||
import androidx.media3.common.MimeTypes
|
||||
import androidx.media3.common.PlaybackParameters
|
||||
import androidx.media3.common.audio.ChannelMixingAudioProcessor
|
||||
import androidx.media3.common.audio.ChannelMixingMatrix
|
||||
import androidx.media3.common.util.Clock
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.decoder.DecoderInputBuffer
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.Renderer
|
||||
import androidx.media3.exoplayer.analytics.PlayerId
|
||||
import androidx.media3.exoplayer.audio.AudioOutput
|
||||
import androidx.media3.exoplayer.audio.AudioOutputProvider
|
||||
import androidx.media3.exoplayer.audio.AudioSink
|
||||
import androidx.media3.exoplayer.audio.AudioTrackAudioOutputProvider
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioSink
|
||||
import androidx.media3.exoplayer.audio.DefaultAudioTrackBufferSizeProvider
|
||||
import androidx.media3.exoplayer.audio.ForwardingAudioSink
|
||||
import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter
|
||||
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
|
||||
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
|
||||
import androidx.media3.exoplayer.video.VideoRendererEventListener
|
||||
import com.edde746.plezy.TvDetection
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlin.math.abs
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context) {
|
||||
|
||||
/**
|
||||
* Android TV: MediaCodec.setOutputSurface is broken on many TV SoCs (Sony Bravia
|
||||
* MediaTek etc., ExoPlayer #5119/#8329) — force full codec re-init on surface
|
||||
* changes instead (#1481). TV-only: phones keep the fast path for PiP churn.
|
||||
*/
|
||||
private val forceSetOutputSurfaceWorkaround: Boolean = TvDetection.isTv(context)
|
||||
|
||||
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
|
||||
val audioDelayUs = AtomicLong(0L)
|
||||
|
||||
/**
|
||||
* Stereo-downmix processor; inactive while every registered matrix is identity.
|
||||
* Pre-populated for counts 1..12 so sink configure can never hit
|
||||
* "No mixing matrix for input channel count". ExoPlayerCore swaps in
|
||||
* downmix matrices via [DownmixMatrices] when the setting is enabled.
|
||||
*/
|
||||
val channelMixProcessor = ChannelMixingAudioProcessor().apply {
|
||||
for (count in 1..12) putChannelMixingMatrix(ChannelMixingMatrix.create(count, count))
|
||||
}
|
||||
|
||||
/** Returns whether direct encoded output should be hidden so decoded PCM output can be selected. */
|
||||
var shouldBlockDirectAudioOutput: ((Format) -> Boolean)? = null
|
||||
|
||||
/** Called before Media3 reacts to an audio route/capability change. */
|
||||
var onAudioCapabilitiesChanged: (() -> Unit)? = null
|
||||
|
||||
var audioDiagnosticsLogger: ((String, String, String) -> Unit)? = null
|
||||
|
||||
var videoDiagnosticsLogger: ((String, String, String) -> Unit)? = null
|
||||
|
||||
override fun buildVideoRenderers(
|
||||
context: Context,
|
||||
extensionRendererMode: Int,
|
||||
mediaCodecSelector: MediaCodecSelector,
|
||||
enableDecoderFallback: Boolean,
|
||||
eventHandler: Handler,
|
||||
eventListener: VideoRendererEventListener,
|
||||
allowedVideoJoiningTimeMs: Long,
|
||||
out: ArrayList<Renderer>
|
||||
) {
|
||||
// Let super build the full list (it also appends extension renderers reflectively,
|
||||
// e.g. the jellyfin ffmpeg artifact's video renderer), then swap the stock
|
||||
// MediaCodecVideoRenderer for the DV-sanitizing variant at the same index.
|
||||
super.buildVideoRenderers(
|
||||
context,
|
||||
extensionRendererMode,
|
||||
mediaCodecSelector,
|
||||
enableDecoderFallback,
|
||||
eventHandler,
|
||||
eventListener,
|
||||
allowedVideoJoiningTimeMs,
|
||||
out
|
||||
)
|
||||
val index = out.indexOfFirst { it.javaClass == MediaCodecVideoRenderer::class.java }
|
||||
if (index < 0) return
|
||||
out[index] = DvSanitizingVideoRenderer(
|
||||
MediaCodecVideoRenderer.Builder(context)
|
||||
.setCodecAdapterFactory(codecAdapterFactory)
|
||||
.setMediaCodecSelector(mediaCodecSelector)
|
||||
.setAllowedJoiningTimeMs(allowedVideoJoiningTimeMs)
|
||||
.setEnableDecoderFallback(enableDecoderFallback)
|
||||
.setEventHandler(eventHandler)
|
||||
.setEventListener(eventListener)
|
||||
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
|
||||
forceSetOutputSurfaceWorkaround,
|
||||
videoDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
|
||||
override fun buildAudioSink(
|
||||
context: Context,
|
||||
enableFloatOutput: Boolean,
|
||||
enableAudioOutputPlaybackParams: Boolean
|
||||
): AudioSink {
|
||||
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
|
||||
|
||||
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
|
||||
.setMinPcmBufferDurationUs(500_000)
|
||||
.setMaxPcmBufferDurationUs(1_000_000)
|
||||
.setPcmBufferMultiplicationFactor(4)
|
||||
.build()
|
||||
|
||||
val realProvider = AudioTrackAudioOutputProvider.Builder(context)
|
||||
.setAudioTrackBufferSizeProvider(bufferSizeProvider)
|
||||
.build()
|
||||
|
||||
// Shared position: RawPositionAudioOutput writes the raw AudioTrack position,
|
||||
// PositionFixAudioSink reads it to bypass DefaultAudioSink's writtenDuration clamp.
|
||||
val rawPositionUs = AtomicLong(Long.MIN_VALUE)
|
||||
|
||||
val defaultSink = DefaultAudioSink.Builder(context)
|
||||
.setEnableFloatOutput(enableFloatOutput)
|
||||
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
|
||||
// Wraps in DefaultAudioProcessorChain, keeping stock silence-skip +
|
||||
// Sonic; the downmix runs first and only in the decoded-PCM path.
|
||||
.setAudioProcessors(arrayOf(channelMixProcessor))
|
||||
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs, audioDiagnosticsLogger))
|
||||
.build()
|
||||
|
||||
return PositionFixAudioSink(
|
||||
defaultSink,
|
||||
rawPositionUs,
|
||||
audioDelayUs,
|
||||
shouldBlockDirectAudioOutput,
|
||||
onAudioCapabilitiesChanged,
|
||||
audioDiagnosticsLogger
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes video stutter with large audio frames (e.g. 120ms Opus).
|
||||
*
|
||||
* DefaultAudioSink.getCurrentPositionUs() clamps the playback position to
|
||||
* writtenDuration via Math.min(positionUs, framesToDurationUs(writtenFrames)).
|
||||
* With large audio frames, data arrives in bursts and writtenDuration lags behind
|
||||
* the real AudioTrack playback position between bursts, creating a sawtooth
|
||||
* position pattern (plateau → jump) that makes the video renderer drop frames.
|
||||
*
|
||||
* Fix: when DefaultAudioSink's position falls behind the raw AudioTrack position,
|
||||
* return startMediaTimeUs + rawPosition instead, giving the video renderer a
|
||||
* smooth clock to sync against.
|
||||
*
|
||||
* Also suppresses Amlogic AudioTrack timestamp discontinuity errors.
|
||||
*
|
||||
* The raw AudioTrack position advances at real-time rate regardless of speed
|
||||
* (AudioTrackPositionTracker reports post-time-stretch output frames). The
|
||||
* bypass multiplies by speed to convert to media time, matching what
|
||||
* DefaultAudioSink.applyMediaPositionParameters() does internally. Reference
|
||||
* points are captured on speed changes for correct mid-playback transitions.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
private class PositionFixAudioSink(
|
||||
sink: AudioSink,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val audioDelayUs: AtomicLong,
|
||||
private val shouldBlockDirectAudioOutput: ((Format) -> Boolean)?,
|
||||
private val onAudioCapabilitiesChanged: (() -> Unit)?,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : ForwardingAudioSink(sink) {
|
||||
|
||||
private var startMediaTimeUs = Long.MIN_VALUE
|
||||
private var suppressedErrorCount = 0
|
||||
|
||||
// Speed tracking for position bypass
|
||||
private var currentSpeed = 1.0f
|
||||
private var refMediaTimeUs = Long.MIN_VALUE
|
||||
private var refRawPositionUs = 0L
|
||||
|
||||
// Transient counter-offset: after seek/flush, ramp offset from 0 to full
|
||||
// over recoveryDurationUs to prevent video frame drops.
|
||||
private var recoveryDurationUs = 0L
|
||||
private val loggedDirectBlockMimeTypes = mutableSetOf<String>()
|
||||
private var loggedFirstBuffer = false
|
||||
|
||||
override fun supportsFormat(format: Format): Boolean {
|
||||
if (blocksDirectAudioOutput(format)) return false
|
||||
return super.supportsFormat(format)
|
||||
}
|
||||
|
||||
override fun getFormatSupport(format: Format): Int {
|
||||
if (blocksDirectAudioOutput(format)) return AudioSink.SINK_FORMAT_UNSUPPORTED
|
||||
return super.getFormatSupport(format)
|
||||
}
|
||||
|
||||
private fun blocksDirectAudioOutput(format: Format): Boolean {
|
||||
if (shouldBlockDirectAudioOutput?.invoke(format) != true) return false
|
||||
val mimeType = format.sampleMimeType ?: "unknown"
|
||||
if (loggedDirectBlockMimeTypes.add(mimeType)) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"audio",
|
||||
"Blocking direct $mimeType output; decoded PCM output will be preferred"
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override fun handleBuffer(
|
||||
buffer: ByteBuffer,
|
||||
presentationTimeUs: Long,
|
||||
encodedAccessUnitCount: Int
|
||||
): Boolean {
|
||||
if (!loggedFirstBuffer && buffer.hasRemaining()) {
|
||||
loggedFirstBuffer = true
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"audio-sink",
|
||||
"First buffer: size=${buffer.remaining()}B, pts=${presentationTimeUs}us, accessUnits=$encodedAccessUnitCount"
|
||||
)
|
||||
}
|
||||
if (startMediaTimeUs == Long.MIN_VALUE) {
|
||||
startMediaTimeUs = presentationTimeUs
|
||||
refMediaTimeUs = presentationTimeUs
|
||||
refRawPositionUs = 0
|
||||
val delayUs = audioDelayUs.get()
|
||||
recoveryDurationUs = if (delayUs == 0L) 0L else maxOf(200_000L, 2L * abs(delayUs))
|
||||
}
|
||||
return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
|
||||
}
|
||||
|
||||
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) {
|
||||
// Capture reference point before speed changes
|
||||
val rawPos = rawPositionUs.get()
|
||||
if (rawPos > 0 && refMediaTimeUs != Long.MIN_VALUE) {
|
||||
refMediaTimeUs = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
|
||||
refRawPositionUs = rawPos
|
||||
}
|
||||
currentSpeed = playbackParameters.speed
|
||||
super.setPlaybackParameters(playbackParameters)
|
||||
}
|
||||
|
||||
override fun getCurrentPositionUs(sourceEnded: Boolean): Long {
|
||||
val delegatePos = super.getCurrentPositionUs(sourceEnded)
|
||||
if (delegatePos == Long.MIN_VALUE || refMediaTimeUs == Long.MIN_VALUE) {
|
||||
return delegatePos
|
||||
}
|
||||
|
||||
val rawPos = rawPositionUs.get()
|
||||
val basePos = if (rawPos <= 0) {
|
||||
delegatePos
|
||||
} else {
|
||||
val expectedPos = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
|
||||
if (expectedPos > delegatePos + 30_000) expectedPos else delegatePos
|
||||
}
|
||||
|
||||
// Audio delay with transient counter-offset to prevent frame drops after seeks.
|
||||
// After flush, offset ramps linearly from 0 to full over recoveryDurationUs.
|
||||
val delayUs = audioDelayUs.get()
|
||||
if (delayUs == 0L) return basePos
|
||||
|
||||
val elapsedUs = basePos - startMediaTimeUs
|
||||
val netOffsetUs = if (recoveryDurationUs <= 0L || elapsedUs >= recoveryDurationUs) {
|
||||
delayUs
|
||||
} else {
|
||||
(delayUs * elapsedUs) / recoveryDurationUs
|
||||
}
|
||||
return basePos + netOffsetUs
|
||||
}
|
||||
|
||||
// --- Suppress timestamp discontinuity errors ---
|
||||
|
||||
override fun setListener(listener: AudioSink.Listener) {
|
||||
super.setListener(
|
||||
@OptIn(UnstableApi::class) object : AudioSink.Listener {
|
||||
override fun onPositionDiscontinuity() = listener.onPositionDiscontinuity()
|
||||
override fun onPositionAdvancing(playoutStartSystemTimeUs: Long) = listener.onPositionAdvancing(playoutStartSystemTimeUs)
|
||||
override fun onUnderrun(bufferSize: Int, bufferSizeMs: Long, elapsedSinceLastFeedMs: Long) = listener.onUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)
|
||||
override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) = listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
|
||||
override fun onOffloadBufferEmptying() = listener.onOffloadBufferEmptying()
|
||||
override fun onOffloadBufferFull() = listener.onOffloadBufferFull()
|
||||
override fun onAudioCapabilitiesChanged() {
|
||||
onAudioCapabilitiesChanged?.invoke()
|
||||
listener.onAudioCapabilitiesChanged()
|
||||
}
|
||||
override fun onAudioTrackInitialized(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackInitialized(audioTrackConfig)
|
||||
override fun onAudioTrackReleased(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackReleased(audioTrackConfig)
|
||||
override fun onSilenceSkipped() = listener.onSilenceSkipped()
|
||||
override fun onAudioSessionIdChanged(audioSessionId: Int) = listener.onAudioSessionIdChanged(audioSessionId)
|
||||
|
||||
override fun onAudioSinkError(audioSinkError: Exception) {
|
||||
if (isTimestampDiscontinuity(audioSinkError)) {
|
||||
suppressedErrorCount++
|
||||
return
|
||||
}
|
||||
listener.onAudioSinkError(audioSinkError)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override fun flush() {
|
||||
startMediaTimeUs = Long.MIN_VALUE
|
||||
refMediaTimeUs = Long.MIN_VALUE
|
||||
refRawPositionUs = 0
|
||||
recoveryDurationUs = 0L
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
super.flush()
|
||||
}
|
||||
|
||||
override fun reset() {
|
||||
startMediaTimeUs = Long.MIN_VALUE
|
||||
refMediaTimeUs = Long.MIN_VALUE
|
||||
refRawPositionUs = 0
|
||||
recoveryDurationUs = 0L
|
||||
currentSpeed = 1.0f
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
suppressedErrorCount = 0
|
||||
super.reset()
|
||||
}
|
||||
|
||||
private fun isTimestampDiscontinuity(e: Exception): Boolean {
|
||||
val name = e.javaClass.simpleName
|
||||
val msg = e.message ?: ""
|
||||
return name == "InvalidAudioTrackTimestampException" ||
|
||||
name == "UnexpectedDiscontinuityException" ||
|
||||
msg.contains("timestamp discontinuity", ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a text renderer to shift subtitle timing by [delayUs] microseconds.
|
||||
* Positive delay → subtitles appear later, negative → earlier.
|
||||
* Only render() needs the offset — the text renderer uses positionUs to decide
|
||||
* which cues are active; other Renderer methods are timing-independent.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class SubtitleDelayRenderer(
|
||||
private val delegate: Renderer,
|
||||
private val delayUs: AtomicLong
|
||||
) : Renderer by delegate {
|
||||
override fun render(positionUs: Long, elapsedRealtimeUs: Long) {
|
||||
delegate.render(positionUs - delayUs.get(), elapsedRealtimeUs)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MediaCodecVideoRenderer that resolves the DV / HDR10+ dual-dynamic-metadata conflict
|
||||
* per decode path (#1296, generalizes androidx/media#3085):
|
||||
* - native DV codec selected (media3 only selects one when decoder AND display support DV):
|
||||
* strip in-band HDR10+ SEI — conflicting dynamic metadata crashes Fire TV-class chipsets
|
||||
* - HEVC fallback for an HEVC-based DV format: strip DV RPU/EL NALs (profiles 7/8, where the
|
||||
* base layer remains valid HDR10/HLG), keeping HDR10+ for the display
|
||||
*
|
||||
* Flags are reassigned on every codec init: tunneling toggles and DV retries re-init the
|
||||
* codec without recreating renderers, and decoder fallback can switch the codec MIME.
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
internal class DvSanitizingVideoRenderer(
|
||||
builder: Builder,
|
||||
private val forceSetOutputSurfaceWorkaround: Boolean,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : MediaCodecVideoRenderer(builder) {
|
||||
|
||||
private val sanitizer = DvBitstreamSanitizer()
|
||||
|
||||
private var stripHdr10PlusSei = false
|
||||
private var stripDvRpu = false
|
||||
private var loggedSurfaceWorkaround = false
|
||||
|
||||
// On TV SoCs MediaCodec.setOutputSurface() silently yields a black picture after
|
||||
// the screensaver/background destroys and recreates the surface (#1481). Returning
|
||||
// true makes media3 release + re-init the codec instead. media3's built-in device
|
||||
// list doesn't cover 2019+ Bravias; consulted once per codec init.
|
||||
override fun codecNeedsSetOutputSurfaceWorkaround(name: String): Boolean {
|
||||
if (forceSetOutputSurfaceWorkaround) {
|
||||
if (!loggedSurfaceWorkaround) {
|
||||
loggedSurfaceWorkaround = true
|
||||
log?.invoke(
|
||||
"info",
|
||||
"video",
|
||||
"TV setOutputSurface workaround active: codec will fully re-init on surface changes (codec=$name)"
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return super.codecNeedsSetOutputSurfaceWorkaround(name)
|
||||
}
|
||||
|
||||
// Sanitize diagnostics — playback-thread only, cumulative for the renderer's lifetime.
|
||||
private var sanitizedSampleCount = 0L
|
||||
private var totalSanitizeTimeUs = 0L
|
||||
private var maxSanitizeTimeUs = 0L
|
||||
private var totalStrippedNals = 0L
|
||||
private var totalStrippedBytes = 0L
|
||||
|
||||
override fun onCodecInitialized(
|
||||
name: String,
|
||||
configuration: MediaCodecAdapter.Configuration,
|
||||
initializedTimestampMs: Long,
|
||||
initializationDurationMs: Long
|
||||
) {
|
||||
super.onCodecInitialized(name, configuration, initializedTimestampMs, initializationDurationMs)
|
||||
val codecs = configuration.format.codecs?.lowercase() ?: ""
|
||||
val dvHevcFormat = configuration.format.sampleMimeType == MimeTypes.VIDEO_DOLBY_VISION &&
|
||||
(codecs.startsWith("dvhe.") || codecs.startsWith("dvh1."))
|
||||
val codecMimeType = configuration.codecInfo.codecMimeType
|
||||
val newStripHdr10PlusSei = dvHevcFormat && codecMimeType == MimeTypes.VIDEO_DOLBY_VISION
|
||||
val newStripDvRpu = dvHevcFormat &&
|
||||
codecMimeType == MimeTypes.VIDEO_H265 &&
|
||||
isBlCompatibleDvProfile(codecs)
|
||||
if (newStripHdr10PlusSei != stripHdr10PlusSei || newStripDvRpu != stripDvRpu) {
|
||||
log?.invoke(
|
||||
"info",
|
||||
"video",
|
||||
"DV bitstream sanitizing: stripHdr10PlusSei=$newStripHdr10PlusSei, " +
|
||||
"stripDvRpu=$newStripDvRpu (codec=$name, codecs=${configuration.format.codecs})"
|
||||
)
|
||||
}
|
||||
stripHdr10PlusSei = newStripHdr10PlusSei
|
||||
stripDvRpu = newStripDvRpu
|
||||
}
|
||||
|
||||
override fun onQueueInputBuffer(buffer: DecoderInputBuffer) {
|
||||
if (stripHdr10PlusSei || stripDvRpu) {
|
||||
val data = buffer.data
|
||||
if (data != null && data.hasRemaining() && !buffer.isEncrypted) {
|
||||
val sizeBefore = data.remaining()
|
||||
val startNs = System.nanoTime()
|
||||
val stripped = sanitizer.sanitize(data, stripHdr10PlusSei, stripDvRpu)
|
||||
val elapsedUs = (System.nanoTime() - startNs) / 1_000
|
||||
sanitizedSampleCount++
|
||||
totalSanitizeTimeUs += elapsedUs
|
||||
if (elapsedUs > maxSanitizeTimeUs) maxSanitizeTimeUs = elapsedUs
|
||||
totalStrippedNals += stripped
|
||||
totalStrippedBytes += sizeBefore - data.remaining()
|
||||
if (sanitizedSampleCount <= 3 || sanitizedSampleCount % 500 == 0L) {
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"dv-sanitize",
|
||||
"Sample #$sanitizedSampleCount: ${sizeBefore}B -> ${data.remaining()}B, " +
|
||||
"stripped=$stripped, took=${elapsedUs}us " +
|
||||
"(avg=${totalSanitizeTimeUs / sanitizedSampleCount}us, max=${maxSanitizeTimeUs}us, " +
|
||||
"totalNals=$totalStrippedNals, totalBytes=${totalStrippedBytes}B)"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
super.onQueueInputBuffer(buffer)
|
||||
}
|
||||
|
||||
private fun isBlCompatibleDvProfile(codecs: String): Boolean = codecs.startsWith("dvhe.07") ||
|
||||
codecs.startsWith("dvh1.07") ||
|
||||
codecs.startsWith("dvhe.08") ||
|
||||
codecs.startsWith("dvh1.08")
|
||||
}
|
||||
|
||||
// --- AudioOutput wrapping: shares raw position with PositionFixAudioSink ---
|
||||
// Also implements AudioTrack reuse across seeks to avoid expensive teardown/recreation.
|
||||
// DefaultAudioSink releases the AudioOutput on every flush (seek), which destroys the
|
||||
// AudioTrack and creates a new one. On Android TV with tunneled playback, this causes
|
||||
// 7-10s audio dropout while the hardware pipeline reinitializes (Sony Bravia, etc).
|
||||
// By flushing instead of releasing and caching the output, we skip the teardown cycle.
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
private class RawPositionOutputProvider(
|
||||
private val delegate: AudioOutputProvider,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : AudioOutputProvider {
|
||||
|
||||
private var cachedOutput: RawPositionAudioOutput? = null
|
||||
private var cachedConfig: AudioOutputProvider.OutputConfig? = null
|
||||
|
||||
override fun getFormatSupport(config: AudioOutputProvider.FormatConfig) = delegate.getFormatSupport(config)
|
||||
|
||||
override fun getOutputConfig(config: AudioOutputProvider.FormatConfig) = delegate.getOutputConfig(config)
|
||||
|
||||
override fun getAudioOutput(config: AudioOutputProvider.OutputConfig): AudioOutput {
|
||||
val cached = cachedOutput
|
||||
if (cached != null && cachedConfig == config) {
|
||||
cachedOutput = null
|
||||
return cached
|
||||
}
|
||||
cached?.forceRelease()
|
||||
cachedOutput = null
|
||||
|
||||
val realOutput = delegate.getAudioOutput(config)
|
||||
cachedConfig = config
|
||||
return RawPositionAudioOutput(realOutput, rawPositionUs, this, log)
|
||||
}
|
||||
|
||||
fun returnToCache(output: RawPositionAudioOutput) {
|
||||
val existing = cachedOutput
|
||||
if (existing != null && existing !== output) {
|
||||
existing.forceRelease()
|
||||
}
|
||||
cachedOutput = output
|
||||
}
|
||||
|
||||
override fun addListener(listener: AudioOutputProvider.Listener) = delegate.addListener(listener)
|
||||
|
||||
override fun removeListener(listener: AudioOutputProvider.Listener) = delegate.removeListener(listener)
|
||||
|
||||
override fun setClock(clock: Clock) = delegate.setClock(clock)
|
||||
|
||||
override fun release() {
|
||||
cachedOutput?.forceRelease()
|
||||
cachedOutput = null
|
||||
cachedConfig = null
|
||||
delegate.release()
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
private class RawPositionAudioOutput(
|
||||
private val delegate: AudioOutput,
|
||||
private val rawPositionUs: AtomicLong,
|
||||
private val provider: RawPositionOutputProvider,
|
||||
private val log: ((String, String, String) -> Unit)?
|
||||
) : AudioOutput {
|
||||
|
||||
private var loggedFirstWrite = false
|
||||
private var writeCount = 0L
|
||||
private var writtenBytes = 0L
|
||||
private var failed = false
|
||||
|
||||
override fun getPositionUs(): Long {
|
||||
val pos = delegate.getPositionUs()
|
||||
rawPositionUs.set(pos)
|
||||
return pos
|
||||
}
|
||||
|
||||
override fun play() = delegate.play()
|
||||
override fun pause() = delegate.pause()
|
||||
|
||||
@Throws(AudioOutput.WriteException::class)
|
||||
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long): Boolean {
|
||||
val before = buffer.position()
|
||||
val handled = try {
|
||||
delegate.write(buffer, size, presentationTimeUs)
|
||||
} catch (e: AudioOutput.WriteException) {
|
||||
failed = true
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
log?.invoke("warn", "audio-output", "Write failed; AudioTrack will not be reused: ${e.message}")
|
||||
throw e
|
||||
}
|
||||
val written = buffer.position() - before
|
||||
if (written > 0) {
|
||||
writeCount++
|
||||
writtenBytes += written.toLong()
|
||||
if (!loggedFirstWrite) {
|
||||
loggedFirstWrite = true
|
||||
log?.invoke(
|
||||
"debug",
|
||||
"audio-output",
|
||||
"First write: wrote=${written}B, handled=$handled, pts=${presentationTimeUs}us, writes=$writeCount, total=${writtenBytes}B"
|
||||
)
|
||||
}
|
||||
}
|
||||
return handled
|
||||
}
|
||||
|
||||
override fun flush() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
loggedFirstWrite = false
|
||||
writeCount = 0
|
||||
writtenBytes = 0
|
||||
delegate.flush()
|
||||
}
|
||||
|
||||
override fun stop() = delegate.stop()
|
||||
|
||||
override fun release() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
if (failed) {
|
||||
delegate.release()
|
||||
return
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 25) {
|
||||
delegate.stop()
|
||||
delegate.flush()
|
||||
provider.returnToCache(this)
|
||||
} else {
|
||||
delegate.release()
|
||||
}
|
||||
}
|
||||
|
||||
fun forceRelease() {
|
||||
rawPositionUs.set(Long.MIN_VALUE)
|
||||
delegate.release()
|
||||
}
|
||||
|
||||
override fun setVolume(volume: Float) = delegate.setVolume(volume)
|
||||
override fun isOffloadedPlayback() = delegate.isOffloadedPlayback()
|
||||
override fun getAudioSessionId() = delegate.getAudioSessionId()
|
||||
override fun getSampleRate() = delegate.getSampleRate()
|
||||
override fun getBufferSizeInFrames() = delegate.getBufferSizeInFrames()
|
||||
override fun getPlaybackParameters() = delegate.getPlaybackParameters()
|
||||
override fun isStalled() = delegate.isStalled()
|
||||
override fun addListener(listener: AudioOutput.Listener) = delegate.addListener(listener)
|
||||
override fun removeListener(listener: AudioOutput.Listener) = delegate.removeListener(listener)
|
||||
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) = delegate.setPlaybackParameters(playbackParameters)
|
||||
override fun setOffloadDelayPadding(delayInFrames: Int, paddingInFrames: Int) = delegate.setOffloadDelayPadding(delayInFrames, paddingInFrames)
|
||||
override fun setOffloadEndOfStream() = delegate.setOffloadEndOfStream()
|
||||
override fun setPlayerId(playerId: PlayerId) = delegate.setPlayerId(playerId)
|
||||
override fun attachAuxEffect(effectId: Int) = delegate.attachAuxEffect(effectId)
|
||||
override fun setAuxEffectSendLevel(level: Float) = delegate.setAuxEffectSendLevel(level)
|
||||
override fun setPreferredDevice(preferredDevice: AudioDeviceInfo?) = delegate.setPreferredDevice(preferredDevice)
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.C
|
||||
|
||||
/**
|
||||
* Decision logic for the post-resume video stall watchdog (#1454).
|
||||
*
|
||||
* Some TV SoCs (the Amlogic Mi Box class) stall the MediaCodec output path after a
|
||||
* pause -> resume: the playback clock and audio keep advancing but no new video
|
||||
* frame reaches the screen until the codec is flushed by a seek. The watchdog
|
||||
* snapshots the rendered-frame counter when playback resumes and evaluates it one
|
||||
* check window later; a confirmed stall is recovered with a small backward seek
|
||||
* (ExoPlayer short-circuits a same-position seek without resetting renderers, so
|
||||
* the recovery must move by a nonzero delta to force the codec flush).
|
||||
*/
|
||||
internal object ResumeStallPolicy {
|
||||
/** Floor for the check window; frame-interval scaling only ever raises it. */
|
||||
const val DEFAULT_CHECK_WINDOW_MS = 1000L
|
||||
|
||||
/** Frames that must have been due within the window before calling it a stall. */
|
||||
const val MIN_FRAME_INTERVALS = 4
|
||||
|
||||
/** Assumed fps when neither the format nor timestamp detection knows it. */
|
||||
const val FALLBACK_FPS = 24f
|
||||
|
||||
/** Recovery seek delta. Must stay under the 350ms watch-together drift deadband. */
|
||||
const val SEEK_BACK_MS = 250L
|
||||
|
||||
/** Re-checks allowed while the clock itself is not advancing (generic stall, not this bug). */
|
||||
const val MAX_RECHECKS = 2
|
||||
|
||||
/** Recovery cap per media session; a pathological stream stops arming after this. */
|
||||
const val MAX_RECOVERIES_PER_SESSION = 5
|
||||
|
||||
enum class Verdict { HEALTHY, RECHECK, SKIP_NEAR_EOF, STALLED }
|
||||
|
||||
/** Window sized so even low-fps or slowed-down content has had several frames due. */
|
||||
fun checkWindowMs(formatFps: Float?, detectedFps: Float?, speed: Float): Long {
|
||||
val fps = formatFps?.takeIf { it > 1f } ?: detectedFps?.takeIf { it > 1f } ?: FALLBACK_FPS
|
||||
val frameIntervalMs = (1000f / fps / speed.coerceAtLeast(0.25f)).toLong()
|
||||
return maxOf(DEFAULT_CHECK_WINDOW_MS, MIN_FRAME_INTERVALS * frameIntervalMs)
|
||||
}
|
||||
|
||||
fun evaluate(
|
||||
baselineFrames: Int,
|
||||
currentFrames: Int,
|
||||
baselinePositionMs: Long,
|
||||
currentPositionMs: Long,
|
||||
durationMs: Long,
|
||||
windowMs: Long
|
||||
): Verdict = when {
|
||||
// Any counter movement counts as healthy, including a renderer re-enable
|
||||
// resetting DecoderCounters below the baseline.
|
||||
currentFrames != baselineFrames -> Verdict.HEALTHY
|
||||
currentPositionMs - baselinePositionMs < windowMs / 2 -> Verdict.RECHECK
|
||||
durationMs != C.TIME_UNSET && durationMs - currentPositionMs < 2 * windowMs -> Verdict.SKIP_NEAR_EOF
|
||||
else -> Verdict.STALLED
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.media3.common.text.Cue
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
@OptIn(UnstableApi::class)
|
||||
internal object SubtitleCueLayout {
|
||||
|
||||
fun layout(cues: List<Cue>, positionPercent: Int, fontSize: Float): List<Cue> = applyPosition(stackUnpositioned(cues), positionPercent, fontSize)
|
||||
|
||||
// SRT carries no per-cue positioning, so SubripParser emits cues with
|
||||
// lineType = TYPE_UNSET. SubtitlePainter then renders every such cue at the
|
||||
// same default bottom-anchored position, causing visible overlap when more
|
||||
// than one is active. Reassign line numbers from the bottom up so concurrent
|
||||
// unpositioned cues stack instead. Workaround for
|
||||
// https://github.com/androidx/media/issues/2237; can be removed once
|
||||
// https://github.com/androidx/media/pull/3151 lands and we upgrade Media3.
|
||||
private fun stackUnpositioned(cues: List<Cue>): List<Cue> {
|
||||
if (cues.size < 2) return cues
|
||||
val toStack = cues.indices.filter {
|
||||
cues[it].lineType == Cue.TYPE_UNSET && cues[it].text != null
|
||||
}
|
||||
if (toStack.size < 2) return cues
|
||||
val rebuilt = cues.toMutableList()
|
||||
var nextRow = -1
|
||||
// Reverse so the last cue in the group lands on row -1 (bottom).
|
||||
for (idx in toStack.reversed()) {
|
||||
val cue = cues[idx]
|
||||
rebuilt[idx] = cue.buildUpon()
|
||||
.setLine(nextRow.toFloat(), Cue.LINE_TYPE_NUMBER)
|
||||
.setLineAnchor(Cue.ANCHOR_TYPE_END)
|
||||
.build()
|
||||
val rowsConsumed = (cue.text?.toString()?.count { it == '\n' } ?: 0) + 1
|
||||
nextRow -= rowsConsumed
|
||||
}
|
||||
return rebuilt
|
||||
}
|
||||
|
||||
private fun applyPosition(cues: List<Cue>, positionPercent: Int, fontSize: Float): List<Cue> {
|
||||
val clampedPosition = positionPercent.coerceIn(0, 100)
|
||||
if (clampedPosition == 100 || cues.isEmpty()) return cues
|
||||
|
||||
val baseLine = clampedPosition / 100f
|
||||
val rowHeight = (fontSize / 720f * 1.2f).coerceAtLeast(0.01f)
|
||||
var changed = false
|
||||
|
||||
val rebuilt = cues.map { cue ->
|
||||
if (!usesDefaultVerticalPlacement(cue)) return@map cue
|
||||
|
||||
val rowOffset = if (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f) {
|
||||
(-cue.line - 1f).coerceAtLeast(0f)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
val line = if (clampedPosition == 0) {
|
||||
(rowOffset * rowHeight).coerceAtMost(1f)
|
||||
} else {
|
||||
(baseLine - rowOffset * rowHeight).coerceIn(0f, 1f)
|
||||
}
|
||||
val lineAnchor = if (clampedPosition == 0) Cue.ANCHOR_TYPE_START else Cue.ANCHOR_TYPE_END
|
||||
|
||||
changed = true
|
||||
cue.buildUpon()
|
||||
.setLine(line, Cue.LINE_TYPE_FRACTION)
|
||||
.setLineAnchor(lineAnchor)
|
||||
.build()
|
||||
}
|
||||
|
||||
return if (changed) rebuilt else cues
|
||||
}
|
||||
|
||||
private fun usesDefaultVerticalPlacement(cue: Cue): Boolean {
|
||||
if (cue.text == null || cue.bitmap != null || cue.verticalType != Cue.TYPE_UNSET) return false
|
||||
return cue.line == Cue.DIMEN_UNSET || (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.ui.AspectRatioFrameLayout
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal data class SubtitleViewDimensions(val width: Int, val height: Int)
|
||||
|
||||
internal object SubtitleViewLayout {
|
||||
fun textDimensions(
|
||||
containerWidth: Int,
|
||||
containerHeight: Int,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
pixelRatio: Float,
|
||||
resizeMode: Int,
|
||||
zoomScale: Float
|
||||
): SubtitleViewDimensions? {
|
||||
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
|
||||
if (containerWidth <= 0 || containerHeight <= 0) return null
|
||||
|
||||
if (resizeMode != AspectRatioFrameLayout.RESIZE_MODE_FIT) {
|
||||
return SubtitleViewDimensions(containerWidth, containerHeight)
|
||||
}
|
||||
|
||||
val base = fit(containerWidth, containerHeight, videoAspect)
|
||||
return when {
|
||||
zoomScale < 0.999f -> scale(base, zoomScale)
|
||||
zoomScale > 1.001f -> SubtitleViewDimensions(containerWidth, containerHeight)
|
||||
else -> base
|
||||
}
|
||||
}
|
||||
|
||||
fun bitmapDimensions(
|
||||
containerWidth: Int,
|
||||
containerHeight: Int,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int,
|
||||
pixelRatio: Float,
|
||||
resizeMode: Int,
|
||||
zoomScale: Float
|
||||
): SubtitleViewDimensions? {
|
||||
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
|
||||
if (containerWidth <= 0 || containerHeight <= 0) return null
|
||||
|
||||
// PGS/VOB cues are authored in video coordinates, but users expect them to
|
||||
// remain readable and fully visible when the video is cropped or zoomed.
|
||||
// Fit to the visible container instead of following the cropped video rect.
|
||||
return fit(containerWidth, containerHeight, videoAspect)
|
||||
}
|
||||
|
||||
private fun videoAspect(videoWidth: Int, videoHeight: Int, pixelRatio: Float): Float? {
|
||||
if (videoWidth <= 0 || videoHeight <= 0 || pixelRatio <= 0f) return null
|
||||
val aspect = (videoWidth * pixelRatio) / videoHeight
|
||||
return if (aspect.isFinite() && aspect > 0f) aspect else null
|
||||
}
|
||||
|
||||
// Largest [videoAspect] rectangle that fits inside the container, as (width, height)
|
||||
// in float pixels. Shared by the SubtitleView sizing (rounded to ints in [fit]) and
|
||||
// the libass FIT-mode margins in updateAssMargins() (kept as floats for the zoom
|
||||
// multiply) so both agree on the video dst rect.
|
||||
fun letterbox(containerWidth: Int, containerHeight: Int, videoAspect: Float): Pair<Float, Float> {
|
||||
val containerAspect = containerWidth.toFloat() / containerHeight
|
||||
return if (videoAspect > containerAspect) {
|
||||
containerWidth.toFloat() to containerWidth / videoAspect
|
||||
} else {
|
||||
containerHeight * videoAspect to containerHeight.toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
private fun fit(containerWidth: Int, containerHeight: Int, videoAspect: Float): SubtitleViewDimensions {
|
||||
val (width, height) = letterbox(containerWidth, containerHeight, videoAspect)
|
||||
return SubtitleViewDimensions(
|
||||
width.roundToInt().coerceAtLeast(1),
|
||||
height.roundToInt().coerceAtLeast(1)
|
||||
)
|
||||
}
|
||||
|
||||
private fun scale(dimensions: SubtitleViewDimensions, scale: Float): SubtitleViewDimensions {
|
||||
val safeScale = scale.coerceAtLeast(0.001f)
|
||||
return SubtitleViewDimensions(
|
||||
(dimensions.width * safeScale).roundToInt().coerceAtLeast(1),
|
||||
(dimensions.height * safeScale).roundToInt().coerceAtLeast(1)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.view.SurfaceControl
|
||||
import androidx.annotation.Keep
|
||||
|
||||
/**
|
||||
* EXPERIMENTAL SPIKE: the API-34 transaction callback path is the only in-app signal we have
|
||||
* for comparing the codec video plane and the libass overlay plane with the same clock.
|
||||
*/
|
||||
// R8 cannot see the JNI-by-name callback edge, and class-level @Keep is not enough for members.
|
||||
@Keep
|
||||
object SurfaceTxProbe {
|
||||
init {
|
||||
System.loadLibrary("asskt")
|
||||
}
|
||||
|
||||
const val SOURCE_VIDEO = 0
|
||||
const val SOURCE_OVERLAY = 1
|
||||
|
||||
// CLOCK_MONOTONIC keeps native callback times comparable with ExoPlayer release targets.
|
||||
@Volatile
|
||||
@JvmStatic
|
||||
var sink: ((Long, Long, Long, Int, Int, Int, Long) -> Unit)? = null
|
||||
|
||||
// The same transaction must be applied to the frame so the callback follows that buffer.
|
||||
@JvmStatic
|
||||
external fun nativeAttach(transaction: SurfaceControl.Transaction, tag: Long, source: Int)
|
||||
|
||||
// JNI calls this by name after shrink.
|
||||
@Keep
|
||||
@JvmStatic
|
||||
fun onResult(
|
||||
tag: Long,
|
||||
latchNs: Long,
|
||||
releaseNs: Long,
|
||||
surfaceCount: Int,
|
||||
fenceState: Int,
|
||||
source: Int,
|
||||
callbackNs: Long
|
||||
) {
|
||||
val s = sink ?: return
|
||||
s.invoke(tag, latchNs, releaseNs, surfaceCount, fenceState, source, callbackNs)
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import android.util.Log
|
||||
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) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ZlibTrackOutput"
|
||||
private const val INITIAL_BUFFER_SIZE = 256 * 1024
|
||||
private const val INFLATE_CHUNK = 64 * 1024
|
||||
}
|
||||
|
||||
var active = false
|
||||
|
||||
private val inflater = Inflater()
|
||||
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
|
||||
|
||||
override val transformEnabled: Boolean
|
||||
get() = active
|
||||
|
||||
override val transformedBuffer: ByteArray
|
||||
get() = inflateBuf
|
||||
|
||||
override fun transformSample(inputLength: Int, flags: Int): Int = try {
|
||||
inflater.reset()
|
||||
inflater.setInput(inputBuffer, 0, inputLength)
|
||||
var written = 0
|
||||
while (!inflater.finished()) {
|
||||
if (written == inflateBuf.size) growInflateBuf()
|
||||
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
|
||||
if (count == 0 && !inflater.finished()) break
|
||||
written += count
|
||||
}
|
||||
written
|
||||
} catch (e: DataFormatException) {
|
||||
Log.e(TAG, "Zlib inflate failed (${inputLength}B), passing raw", e)
|
||||
ensureInflateCapacity(inputLength)
|
||||
System.arraycopy(inputBuffer, 0, inflateBuf, 0, inputLength)
|
||||
inputLength
|
||||
}
|
||||
|
||||
private fun ensureInflateCapacity(needed: Int) {
|
||||
if (inflateBuf.size < needed) {
|
||||
inflateBuf = ByteArray(maxOf(needed, inflateBuf.size * 2))
|
||||
}
|
||||
}
|
||||
|
||||
private fun growInflateBuf() {
|
||||
inflateBuf = inflateBuf.copyOf(inflateBuf.size * 2)
|
||||
}
|
||||
}
|
||||
@@ -1,134 +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 (see LatmMatroskaExtractor for the
|
||||
* Live TV counterpart).
|
||||
*/
|
||||
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()
|
||||
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
|
||||
|
||||
override fun track(id: Int, type: Int): TrackOutput {
|
||||
val original = delegate.track(id, type)
|
||||
val wrapper = ZlibInflatingTrackOutput(original)
|
||||
lastCreatedWrapper = wrapper
|
||||
return wrapper
|
||||
}
|
||||
|
||||
fun activateLast() {
|
||||
lastCreatedWrapper?.active = true
|
||||
}
|
||||
|
||||
override fun endTracks() = delegate.endTracks()
|
||||
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import dev.jdtech.mpv.EndFileReason
|
||||
import dev.jdtech.mpv.LogLevel
|
||||
import dev.jdtech.mpv.LogMessage
|
||||
import dev.jdtech.mpv.MpvEvent
|
||||
|
||||
/** Adds the native diagnostic that libmpv-android exposes separately via logFlow. */
|
||||
internal class MpvEndFileDiagnostics {
|
||||
private var errorMessage: String? = null
|
||||
|
||||
fun onStartFile() {
|
||||
errorMessage = null
|
||||
}
|
||||
|
||||
fun onLogMessage(message: LogMessage) {
|
||||
if (message.level == LogLevel.Fatal || message.level == LogLevel.Error) {
|
||||
errorMessage = message.text.takeIf { it.isNotBlank() }
|
||||
}
|
||||
}
|
||||
|
||||
fun onEndFile(event: MpvEvent.EndFile): Map<String, Any>? {
|
||||
val reason = event.reason
|
||||
if (reason == null) {
|
||||
errorMessage = null
|
||||
return null
|
||||
}
|
||||
val data = mutableMapOf<String, Any>("reason" to reason.id)
|
||||
if (reason == EndFileReason.Error) {
|
||||
errorMessage?.let { data["message"] = it }
|
||||
}
|
||||
errorMessage = null
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -1,495 +0,0 @@
|
||||
package com.edde746.plezy.mpv
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import com.edde746.plezy.shared.PlayerChannelBinding
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
/**
|
||||
* Channel plumbing for [MpvPlayerCore]. The default instance is the video
|
||||
* player; the [audioOnly] instance (see [MpvAudioPlayerPlugin]) drives the
|
||||
* dedicated music core on its own channel pair with two lifecycle
|
||||
* differences:
|
||||
* - the core is built on the application context, not the Activity, so
|
||||
* background music playback survives activity teardown — it is only
|
||||
* disposed on explicit Dart `dispose` or engine detach, never in
|
||||
* [onDetachedFromActivity];
|
||||
* - all video-only surface work is skipped inside the core.
|
||||
*/
|
||||
open class MpvPlayerPlugin(
|
||||
private val channelBase: String = "com.plezy/mpv_player",
|
||||
private val audioOnly: Boolean = false
|
||||
) : FlutterPlugin,
|
||||
MethodChannel.MethodCallHandler,
|
||||
EventChannel.StreamHandler,
|
||||
ActivityAware,
|
||||
com.edde746.plezy.shared.PlayerDelegate {
|
||||
|
||||
private val tag = if (audioOnly) "MpvAudioPlayerPlugin" else "MpvPlayerPlugin"
|
||||
|
||||
private val channels = PlayerChannelBinding(channelBase, this, this, tag)
|
||||
private var playerCore: MpvPlayerCore? = null
|
||||
private var activity: Activity? = null
|
||||
private var activityBinding: ActivityPluginBinding? = null
|
||||
private var applicationContext: Context? = null
|
||||
private val nameToId = mutableMapOf<String, Int>()
|
||||
private var sessionGeneration = 0
|
||||
|
||||
/** Same semantics as Activity.runOnUiThread, without needing an Activity. */
|
||||
private fun runOnMain(block: () -> Unit) = channels.runOnMain(block)
|
||||
|
||||
// Pending `MethodChannel.Result`s for an init that is currently in flight.
|
||||
// Concurrent `invoke('initialize')` calls share the same outcome instead
|
||||
// of each tearing down the in-flight core and starting their own — which
|
||||
// was the root cause of #930.
|
||||
private val pendingInitResults = mutableListOf<MethodChannel.Result>()
|
||||
|
||||
@Volatile private var isInitializing = false
|
||||
|
||||
// FlutterPlugin
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
applicationContext = binding.applicationContext
|
||||
channels.attach(binding)
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
channels.detach()
|
||||
if (audioOnly) {
|
||||
// The audio core is not activity-bound; engine detach is its terminal
|
||||
// native lifecycle event (mirrors the video core's activity detach).
|
||||
disposeCoreForTeardown()
|
||||
}
|
||||
applicationContext = null
|
||||
}
|
||||
|
||||
private fun disposeCoreForTeardown() {
|
||||
++sessionGeneration
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
// Any in-flight init callback would never fire (its scope is cancelled
|
||||
// by dispose), so close out queued callers explicitly.
|
||||
completePendingInits(success = false)
|
||||
}
|
||||
|
||||
// ActivityAware
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(tag, "Attached to activity")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {
|
||||
// The audio-only core deliberately outlives the activity (background
|
||||
// music); it is torn down on engine detach / Dart dispose instead.
|
||||
if (!audioOnly) {
|
||||
disposeCoreForTeardown()
|
||||
}
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(tag, "Detached from activity")
|
||||
}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
activityBinding = binding
|
||||
Log.d(tag, "Reattached to activity for config changes")
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {
|
||||
activity = null
|
||||
activityBinding = null
|
||||
Log.d(tag, "Detached from activity for config changes")
|
||||
}
|
||||
|
||||
// EventChannel.StreamHandler
|
||||
|
||||
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
|
||||
channels.listen(events)
|
||||
}
|
||||
|
||||
override fun onCancel(arguments: Any?) {
|
||||
channels.cancel()
|
||||
}
|
||||
|
||||
// MethodChannel.MethodCallHandler
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"initialize" -> handleInitialize(result)
|
||||
"dispose" -> handleDispose(result)
|
||||
"setProperty" -> handleSetProperty(call, result)
|
||||
"getProperty" -> handleGetProperty(call, result)
|
||||
"getStats" -> handleGetStats(result)
|
||||
"observeProperty" -> handleObserveProperty(call, result)
|
||||
"command" -> handleCommand(call, result)
|
||||
"setVisible" -> handleSetVisible(call, result)
|
||||
"updateFrame" -> handleUpdateFrame(result)
|
||||
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
|
||||
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
|
||||
"requestAudioFocus" -> handleRequestAudioFocus(result)
|
||||
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
|
||||
"openContentFd" -> handleOpenContentFd(call, result)
|
||||
"closeContentFd" -> handleCloseContentFd(call, result)
|
||||
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
|
||||
"setLogLevel" -> handleSetLogLevel(call, result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleInitialize(result: MethodChannel.Result) {
|
||||
// Video cores need the Activity (surface/view hierarchy); the audio-only
|
||||
// core is built on the application context so it can outlive it.
|
||||
val coreContext: Context? = if (audioOnly) applicationContext else activity
|
||||
if (coreContext == null) {
|
||||
if (audioOnly) {
|
||||
result.error("NO_CONTEXT", "Application context not available", null)
|
||||
} else {
|
||||
result.error("NO_ACTIVITY", "Activity not available", null)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (playerCore?.isInitialized == true) {
|
||||
Log.d(tag, "Already initialized")
|
||||
result.success(true)
|
||||
return
|
||||
}
|
||||
|
||||
// Coalesce concurrent inits: the second caller waits for the first
|
||||
// call's outcome instead of disposing the in-flight core. The Dart
|
||||
// side memoizes too, but this is defense in depth for any direct
|
||||
// `invoke('initialize')` that bypasses _ensureInitialized.
|
||||
synchronized(pendingInitResults) {
|
||||
pendingInitResults += result
|
||||
if (isInitializing) {
|
||||
Log.d(tag, "Init already in flight, queuing caller")
|
||||
return
|
||||
}
|
||||
isInitializing = true
|
||||
}
|
||||
|
||||
runOnMain {
|
||||
val gen: Int
|
||||
val core: MpvPlayerCore
|
||||
try {
|
||||
// Caller invariant: dispose() was already called explicitly,
|
||||
// OR `playerCore?.isInitialized == true` and we early-exited
|
||||
// above. We never tear down a core that's mid-initialization.
|
||||
if (playerCore != null && playerCore?.isInitialized != true) {
|
||||
Log.w(tag, "Discarding stale uninitialized core before re-init")
|
||||
playerCore?.dispose()
|
||||
playerCore = null
|
||||
}
|
||||
|
||||
gen = ++sessionGeneration
|
||||
core = MpvPlayerCore(coreContext, audioOnly).apply {
|
||||
delegate = this@MpvPlayerPlugin
|
||||
}
|
||||
playerCore = core
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Failed to initialize: ${e.message}", e)
|
||||
completePendingInits(success = false, errorMessage = e.message)
|
||||
return@runOnMain
|
||||
}
|
||||
|
||||
core.initialize { success ->
|
||||
val stale = gen != sessionGeneration || playerCore !== core
|
||||
if (stale) {
|
||||
Log.d(tag, "Stale init callback (gen=$gen, current=$sessionGeneration)")
|
||||
} else {
|
||||
// Start hidden - now safe because setVisible operates on the container,
|
||||
// not the SurfaceView directly (matching ExoPlayer's approach).
|
||||
// No-op on the audio-only core, which has no render layer.
|
||||
core.setVisible(false)
|
||||
Log.d(tag, "Initialized: $success")
|
||||
}
|
||||
completePendingInits(success = !stale && success)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun completePendingInits(success: Boolean, errorMessage: String? = null) {
|
||||
val pending = synchronized(pendingInitResults) {
|
||||
isInitializing = false
|
||||
val copy = pendingInitResults.toList()
|
||||
pendingInitResults.clear()
|
||||
copy
|
||||
}
|
||||
for (r in pending) {
|
||||
if (errorMessage != null) {
|
||||
r.error("INIT_FAILED", errorMessage, null)
|
||||
} else {
|
||||
r.success(success)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleDispose(result: MethodChannel.Result) {
|
||||
runOnMain {
|
||||
val core = playerCore
|
||||
++sessionGeneration
|
||||
playerCore = null
|
||||
|
||||
// Any in-flight init callback is cancelled with the scope, so
|
||||
// close out queued callers here instead of leaking them.
|
||||
completePendingInits(success = false)
|
||||
|
||||
core?.dispose {
|
||||
Log.d(tag, "Disposed")
|
||||
result.success(null)
|
||||
} ?: result.success(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val value = call.argument<String>("value")
|
||||
|
||||
if (name == null || value == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
|
||||
core.setProperty(name, value) {
|
||||
result.success(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
|
||||
if (name == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(null)
|
||||
return
|
||||
}
|
||||
|
||||
val gen = sessionGeneration
|
||||
core.getPropertyAsync(name) { value ->
|
||||
if (gen != sessionGeneration || playerCore !== core) {
|
||||
result.success(null)
|
||||
} else {
|
||||
result.success(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetStats(result: MethodChannel.Result) {
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(mapOf("playerType" to "mpv"))
|
||||
return
|
||||
}
|
||||
|
||||
val gen = sessionGeneration
|
||||
Thread {
|
||||
val stats = core.getStats()
|
||||
runOnMain {
|
||||
if (gen != sessionGeneration || playerCore !== core) {
|
||||
result.success(mapOf("playerType" to "mpv"))
|
||||
} else {
|
||||
result.success(stats)
|
||||
}
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
|
||||
val name = call.argument<String>("name")
|
||||
val format = call.argument<String>("format")
|
||||
val id = call.argument<Int>("id")
|
||||
|
||||
if (name == null || format == null || id == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'name', 'format', or 'id'", null)
|
||||
return
|
||||
}
|
||||
|
||||
nameToId[name] = id
|
||||
playerCore?.observeProperty(name, format)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
|
||||
val args = call.argument<List<String>>("args")
|
||||
|
||||
if (args == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'args'", null)
|
||||
return
|
||||
}
|
||||
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.error("NOT_INITIALIZED", "Player not initialized", null)
|
||||
return
|
||||
}
|
||||
core.command(args.toTypedArray()) { success ->
|
||||
if (success) {
|
||||
result.success(null)
|
||||
} else {
|
||||
result.error("COMMAND_FAILED", "mpv command failed", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSetLogLevel(call: MethodCall, result: MethodChannel.Result) {
|
||||
if (call.argument<String>("level") == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'level'", null)
|
||||
return
|
||||
}
|
||||
result.error(
|
||||
"UNSUPPORTED",
|
||||
"Runtime mpv log level changes are not supported on Android",
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
|
||||
val visible = call.argument<Boolean>("visible")
|
||||
|
||||
if (visible == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'visible'", null)
|
||||
return
|
||||
}
|
||||
|
||||
playerCore?.setVisible(visible)
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleUpdateFrame(result: MethodChannel.Result) {
|
||||
playerCore?.updateFrame()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
|
||||
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
|
||||
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
|
||||
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
|
||||
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
|
||||
|
||||
Log.d(tag, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
|
||||
val core = playerCore
|
||||
if (core == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
|
||||
result.success(switched)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
|
||||
Log.d(tag, "clearVideoFrameRate")
|
||||
playerCore?.clearVideoFrameRate()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(tag, "requestAudioFocus")
|
||||
val granted = playerCore?.requestAudioFocus() ?: false
|
||||
result.success(granted)
|
||||
}
|
||||
|
||||
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
|
||||
Log.d(tag, "abandonAudioFocus")
|
||||
playerCore?.abandonAudioFocus()
|
||||
result.success(null)
|
||||
}
|
||||
|
||||
private fun handleOpenContentFd(call: MethodCall, result: MethodChannel.Result) {
|
||||
val uriString = call.argument<String>("uri")
|
||||
if (uriString == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'uri'", null)
|
||||
return
|
||||
}
|
||||
|
||||
// The audio instance may run without an Activity (background music), so
|
||||
// resolve SAF content URIs through the application context there.
|
||||
val contentResolver = (if (audioOnly) applicationContext else activity)?.contentResolver
|
||||
if (contentResolver == null) {
|
||||
result.error(if (audioOnly) "NO_CONTEXT" else "NO_ACTIVITY", "Context not available", null)
|
||||
return
|
||||
}
|
||||
|
||||
// Open file descriptor off UI thread to prevent ANR on slow storage
|
||||
Thread {
|
||||
try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val pfd = contentResolver.openFileDescriptor(uri, "r")
|
||||
if (pfd == null) {
|
||||
runOnMain {
|
||||
result.error("OPEN_FAILED", "Failed to open file descriptor for $uriString", null)
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
|
||||
val fd = pfd.detachFd()
|
||||
Log.d(tag, "Opened content FD $fd for $uriString")
|
||||
runOnMain { result.success(fd) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Failed to open content FD: ${e.message}", e)
|
||||
runOnMain { result.error("OPEN_FAILED", e.message, null) }
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
// Reclaims a detached fd from handleOpenContentFd that mpv will never
|
||||
// consume (a gapless-armed entry dropped before mpv opened it). The Dart
|
||||
// side guarantees single-close and only calls this when the entry provably
|
||||
// never played.
|
||||
private fun handleCloseContentFd(call: MethodCall, result: MethodChannel.Result) {
|
||||
val fd = call.argument<Int>("fd")
|
||||
if (fd == null || fd < 0) {
|
||||
result.error("INVALID_ARGS", "Missing 'fd'", null)
|
||||
return
|
||||
}
|
||||
try {
|
||||
ParcelFileDescriptor.adoptFd(fd).close()
|
||||
Log.d(tag, "Closed content FD $fd")
|
||||
result.success(null)
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Failed to close content FD $fd: ${e.message}", e)
|
||||
result.error("CLOSE_FAILED", e.message, null)
|
||||
}
|
||||
}
|
||||
|
||||
// PlayerDelegate
|
||||
|
||||
override fun onPropertyChange(name: String, value: Any?) {
|
||||
val propId = nameToId[name] ?: return
|
||||
channels.emitProperty(propId, value)
|
||||
}
|
||||
|
||||
override fun onEvent(name: String, data: Map<String, Any>?) {
|
||||
channels.emitEvent(name, data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The audio-only music instance on `com.plezy/mpv_audio_player[/events]`.
|
||||
* A distinct class (not just a configured [MpvPlayerPlugin]) because
|
||||
* FlutterEngine's plugin registry keys plugins by class and would silently
|
||||
* drop a second [MpvPlayerPlugin] registration.
|
||||
*/
|
||||
class MpvAudioPlayerPlugin : MpvPlayerPlugin(channelBase = "com.plezy/mpv_audio_player", audioOnly = true)
|
||||
@@ -1,106 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.util.Log
|
||||
|
||||
class AudioFocusManager(
|
||||
context: Context,
|
||||
private val handler: Handler,
|
||||
private val onPause: () -> Unit,
|
||||
private val onResume: () -> Unit,
|
||||
private val isPaused: () -> Boolean,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) },
|
||||
private val contentType: Int = AudioAttributes.CONTENT_TYPE_MOVIE
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "AudioFocusManager"
|
||||
}
|
||||
|
||||
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
private var audioFocusRequest: AudioFocusRequest? = null
|
||||
private var hasAudioFocus: Boolean = false
|
||||
var wasPlayingBeforeFocusLoss: Boolean = false
|
||||
private set
|
||||
|
||||
private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
|
||||
when (focusChange) {
|
||||
AudioManager.AUDIOFOCUS_GAIN -> {
|
||||
log("Focus gained")
|
||||
hasAudioFocus = true
|
||||
if (wasPlayingBeforeFocusLoss) {
|
||||
onResume()
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
}
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS -> {
|
||||
log("Focus lost permanently")
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = !isPaused()
|
||||
onPause()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
|
||||
log("Focus lost transiently")
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = !isPaused()
|
||||
onPause()
|
||||
}
|
||||
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
|
||||
log("Focus lost transiently (can duck)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun requestAudioFocus(): Boolean {
|
||||
Log.d(TAG, "Requesting audio focus")
|
||||
|
||||
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(contentType)
|
||||
.build()
|
||||
)
|
||||
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
|
||||
.build()
|
||||
|
||||
audioFocusRequest = focusRequest
|
||||
audioManager.requestAudioFocus(focusRequest)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.requestAudioFocus(
|
||||
audioFocusChangeListener,
|
||||
AudioManager.STREAM_MUSIC,
|
||||
AudioManager.AUDIOFOCUS_GAIN
|
||||
)
|
||||
}
|
||||
|
||||
hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
|
||||
Log.d(TAG, "Audio focus request result: $result, granted: $hasAudioFocus")
|
||||
return hasAudioFocus
|
||||
}
|
||||
|
||||
fun abandonAudioFocus() {
|
||||
Log.d(TAG, "Abandoning audio focus")
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
|
||||
audioFocusRequest = null
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.abandonAudioFocus(audioFocusChangeListener)
|
||||
}
|
||||
|
||||
hasAudioFocus = false
|
||||
wasPlayingBeforeFocusLoss = false
|
||||
}
|
||||
|
||||
fun release() {
|
||||
abandonAudioFocus()
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.os.Build
|
||||
|
||||
object DeviceQuirks {
|
||||
val isEWaste: Boolean
|
||||
get() = isGooglePixelDevice || isGoogleTensorDevice
|
||||
|
||||
private val isGooglePixelDevice: Boolean
|
||||
get() = (
|
||||
Build.MANUFACTURER.equals("Google", ignoreCase = true) ||
|
||||
Build.BRAND.equals("google", ignoreCase = true)
|
||||
) &&
|
||||
Build.MODEL.contains("Pixel", ignoreCase = true)
|
||||
|
||||
private val isGoogleTensorDevice: Boolean
|
||||
get() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
|
||||
val soc = Build.SOC_MODEL
|
||||
return soc.startsWith("Tensor", ignoreCase = true) ||
|
||||
soc.startsWith("GS", ignoreCase = true)
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.graphics.PixelFormat
|
||||
import android.os.Build
|
||||
import android.view.SurfaceView
|
||||
import android.view.TextureView
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
|
||||
object FlutterOverlayHelper {
|
||||
|
||||
/**
|
||||
* Find the top-level container holding the Flutter render surface. Returns the
|
||||
* direct child of [contentView] that contains a FlutterSurfaceView/FlutterTextureView
|
||||
* at any depth — `bringChildToFront` only works for direct children, so this is the
|
||||
* node to pass to [configureFlutterZOrder].
|
||||
*
|
||||
* Searches any depth because an app may wrap Flutter (e.g. for key-event dispatch)
|
||||
* and push it below the direct-child level.
|
||||
*/
|
||||
fun findFlutterContainer(contentView: ViewGroup, excludeView: View? = null): ViewGroup? {
|
||||
for (i in contentView.childCount - 1 downTo 0) {
|
||||
val child = contentView.getChildAt(i)
|
||||
if (child === excludeView || child !is ViewGroup) continue
|
||||
if (findRenderSurface(child) != null) return child
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun findRenderSurface(root: ViewGroup): View? {
|
||||
for (i in 0 until root.childCount) {
|
||||
val child = root.getChildAt(i)
|
||||
if (child is SurfaceView || child is TextureView) return child
|
||||
if (child is ViewGroup) findRenderSurface(child)?.let { return it }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply [SurfaceView.setCompositionOrder] on API 36+; no-op on older APIs where
|
||||
* the legacy [SurfaceView.setZOrderOnTop]/[SurfaceView.setZOrderMediaOverlay]
|
||||
* bucket settings govern Z-order instead.
|
||||
*
|
||||
* The value maps directly to the SurfaceView's `mSubLayer`. Per AOSP semantics:
|
||||
* `mSubLayer >= 0` (non-negative `order`) is composited above the parent window
|
||||
* and skips the hole-punch in `draw()`; `mSubLayer < 0` (negative `order`) is
|
||||
* behind the parent window and the SurfaceView is made visible by punching a
|
||||
* transparent hole in the parent canvas. Valid range is `[-2, 2]`. Picking the
|
||||
* right sign matters: any view that draws on the parent canvas (e.g. Media3's
|
||||
* `CanvasSubtitleOutput` for SRT/VTT/SDH) is hidden by SurfaceViews with
|
||||
* non-negative orders that sit on top of the same area.
|
||||
*/
|
||||
fun applyCompositionOrder(view: SurfaceView, order: Int) {
|
||||
if (Build.VERSION.SDK_INT >= 36) view.compositionOrder = order
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure z-ordering so the Flutter UI renders above the video/subtitle surfaces.
|
||||
*
|
||||
* On API 36+ the value is applied via [SurfaceView.setCompositionOrder] and maps
|
||||
* directly to `mSubLayer` (see [applyCompositionOrder] for the sign semantics).
|
||||
* On pre-36 SurfaceView builds the value is mapped to the legacy on-top bucket
|
||||
* when positive. On TextureView builds the value is unused (view hierarchy order
|
||||
* handles it).
|
||||
*
|
||||
* Pass a non-negative value (e.g. `1`) so Flutter renders above the parent canvas
|
||||
* and lets the legacy transparent-mode `setZOrderOnTop(true)` semantics carry over.
|
||||
*/
|
||||
fun configureFlutterZOrder(contentView: ViewGroup, container: ViewGroup, compositionOrder: Int) {
|
||||
contentView.bringChildToFront(container)
|
||||
when (val surface = findRenderSurface(container)) {
|
||||
is SurfaceView -> {
|
||||
if (Build.VERSION.SDK_INT >= 36) {
|
||||
// Clear legacy bucket hints so compositionOrder is authoritative.
|
||||
// Flutter's FlutterSurfaceView sets setZOrderOnTop(true) in its
|
||||
// transparent-mode constructor, which otherwise pins it to z=1.
|
||||
surface.setZOrderOnTop(false)
|
||||
surface.setZOrderMediaOverlay(false)
|
||||
surface.compositionOrder = compositionOrder
|
||||
} else {
|
||||
// Pre-36 has 3 coarse sublayer buckets. Put Flutter in the on-top
|
||||
// bucket so it renders above the video (default) and libass subtitle
|
||||
// (media overlay) SurfaceViews. NB: setZOrderMediaOverlay overwrites
|
||||
// mSubLayer internally, so don't call it here or it cancels setZOrderOnTop.
|
||||
surface.setZOrderOnTop(compositionOrder > 0)
|
||||
}
|
||||
surface.holder.setFormat(PixelFormat.TRANSLUCENT)
|
||||
}
|
||||
is TextureView -> surface.isOpaque = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
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,
|
||||
private val handler: Handler,
|
||||
private val log: (String) -> Unit = { Log.d(TAG, it) }
|
||||
) {
|
||||
companion object {
|
||||
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 displayListener: DisplayManager.DisplayListener? = null
|
||||
private var pendingSettleRunnable: Runnable? = null
|
||||
private var watchdogRunnable: Runnable? = null
|
||||
private var pendingCompletion: ((switched: Boolean) -> Unit)? = null
|
||||
|
||||
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
|
||||
// - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the caller's
|
||||
// [extraDelayMs], with `switched=true`; or
|
||||
// - via a watchdog if the real event never arrives, so the caller doesn't hang.
|
||||
//
|
||||
// The caller is responsible for pausing playback before calling and resuming
|
||||
// it after [onComplete] fires.
|
||||
fun setVideoFrameRate(
|
||||
fps: Float,
|
||||
videoDurationMs: Long,
|
||||
extraDelayMs: Long,
|
||||
videoWidth: Int = 0,
|
||||
videoHeight: Int = 0,
|
||||
onComplete: (switched: Boolean) -> Unit
|
||||
) {
|
||||
currentVideoFps = fps
|
||||
currentVideoWidth = videoWidth
|
||||
currentVideoHeight = videoHeight
|
||||
if (fps <= 0f) {
|
||||
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
log(
|
||||
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
|
||||
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
|
||||
)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
setDisplayMode(fps, extraDelayMs, onComplete)
|
||||
} else {
|
||||
onComplete(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearVideoFrameRate() {
|
||||
Log.d(TAG, "clearVideoFrameRate")
|
||||
currentVideoFps = 0f
|
||||
// Resolve any pending setVideoFrameRate future as "not switched" so
|
||||
// the Dart caller's await doesn't hang on player dispose.
|
||||
firePendingCompletion("clear", switched = false)
|
||||
// Restore default display mode on API M (preferredDisplayModeId persists)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
activity.window?.attributes?.let { attrs ->
|
||||
attrs.preferredDisplayModeId = 0
|
||||
activity.window?.attributes = attrs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Release pending callbacks/listener without restoring the display mode.
|
||||
// Used by player-core dispose paths so a backend handoff (e.g. ExoPlayer→MPV
|
||||
// audio fallback) doesn't clobber the just-applied refresh-rate switch —
|
||||
// window-scoped preferredDisplayModeId persists across the SurfaceView swap,
|
||||
// letting MPV inherit the rate without a second HDMI renegotiation.
|
||||
fun releasePending() {
|
||||
Log.d(TAG, "releasePending")
|
||||
currentVideoFps = 0f
|
||||
firePendingCompletion("release", switched = false)
|
||||
}
|
||||
|
||||
private fun cancelPendingCallbacks() {
|
||||
pendingSettleRunnable?.let { handler.removeCallbacks(it) }
|
||||
watchdogRunnable?.let { handler.removeCallbacks(it) }
|
||||
pendingSettleRunnable = null
|
||||
watchdogRunnable = null
|
||||
}
|
||||
|
||||
private fun firePendingCompletion(reason: String, switched: Boolean) {
|
||||
cancelPendingCallbacks()
|
||||
displayListener?.let {
|
||||
getDisplayManager().unregisterDisplayListener(it)
|
||||
displayListener = null
|
||||
}
|
||||
val cb = pendingCompletion ?: return
|
||||
pendingCompletion = null
|
||||
log("complete reason=$reason, switched=$switched, currentMode=${currentModeDescription()}")
|
||||
cb(switched)
|
||||
}
|
||||
|
||||
private fun registerDisplayListener(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
// Resolve any previous pending op before starting a new one.
|
||||
firePendingCompletion("superseded", switched = false)
|
||||
pendingCompletion = onComplete
|
||||
|
||||
displayListener = object : DisplayManager.DisplayListener {
|
||||
override fun onDisplayAdded(displayId: Int) = Unit
|
||||
override fun onDisplayRemoved(displayId: Int) = Unit
|
||||
override fun onDisplayChanged(displayId: Int) {
|
||||
// Unregister immediately so a chatty display (e.g. several
|
||||
// onDisplayChanged events during HDMI renegotiation) doesn't
|
||||
// queue multiple settle callbacks.
|
||||
getDisplayManager().unregisterDisplayListener(this)
|
||||
displayListener = null
|
||||
|
||||
val settle = Runnable { firePendingCompletion("display settled", switched = currentRateMatch(fps) != null) }
|
||||
pendingSettleRunnable = settle
|
||||
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
|
||||
}
|
||||
}
|
||||
getDisplayManager().registerDisplayListener(displayListener, handler)
|
||||
|
||||
// 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) }
|
||||
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)
|
||||
}
|
||||
|
||||
private fun currentModeDescription(): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
describeMode(currentDisplayMode())
|
||||
} else {
|
||||
"unavailable"
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun currentDisplay(): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
activity.display
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
(activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun currentDisplayMode(): Display.Mode? = currentDisplay()?.mode
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun describeMode(mode: Display.Mode?): String {
|
||||
if (mode == null) return "unknown"
|
||||
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz"
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun findBestModeMatch(
|
||||
fps: Float,
|
||||
currentMode: Display.Mode,
|
||||
supportedModes: Array<Display.Mode>,
|
||||
videoWidth: Int,
|
||||
videoHeight: Int
|
||||
): DisplayModeCandidate? {
|
||||
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
|
||||
// switch, the least disruptive (no resolution/HDMI renegotiation).
|
||||
supportedModes.asSequence()
|
||||
.filter { it.physicalHeight == currentMode.physicalHeight && it.physicalWidth == currentMode.physicalWidth }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
compareBy<DisplayModeCandidate> { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
|
||||
)
|
||||
?.let { return it }
|
||||
|
||||
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
|
||||
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
|
||||
// that downscales the video below its native size (trading detail for cadence).
|
||||
// Requires known video dimensions; without them keep Tier-1-only behaviour.
|
||||
if (videoWidth <= 0 || videoHeight <= 0) return null
|
||||
val currentArea = currentMode.physicalWidth.toLong() * currentMode.physicalHeight
|
||||
return supportedModes.asSequence()
|
||||
.filter { it.physicalWidth >= videoWidth && it.physicalHeight >= videoHeight }
|
||||
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
|
||||
.minWithOrNull(
|
||||
// Prefer the resolution closest to the panel's current one (least change,
|
||||
// keeps panel-native res when a high-res match exists), then refresh match.
|
||||
compareBy<DisplayModeCandidate> { abs(it.mode.physicalWidth.toLong() * it.mode.physicalHeight - currentArea) }
|
||||
.thenBy { it.match.priority }
|
||||
.thenBy { it.match.error }
|
||||
)
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.M)
|
||||
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
|
||||
log("setDisplayMode fps=$fps")
|
||||
val display = currentDisplay()
|
||||
if (display == null) {
|
||||
log("display unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
val supportedModes = display.supportedModes
|
||||
if (supportedModes == null) {
|
||||
log("supported display modes unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
val currentMode = display.mode
|
||||
log("supported modes=${describeSupportedModes(supportedModes)}")
|
||||
|
||||
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes, currentVideoWidth, currentVideoHeight)
|
||||
if (modeMatch == null) {
|
||||
log(
|
||||
"no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight} " +
|
||||
"(video=${currentVideoWidth}x$currentVideoHeight)"
|
||||
)
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
val modeToUse = modeMatch.mode
|
||||
if (modeToUse.modeId == currentMode.modeId) {
|
||||
log("current mode already matches ${fps}fps (${modeMatch.match.reason}), no switch needed")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
|
||||
log(
|
||||
"switching to ${describeMode(modeToUse)} for ${fps}fps " +
|
||||
"(${modeMatch.match.reason}, error=${modeMatch.match.error})"
|
||||
)
|
||||
val window = activity.window
|
||||
if (window == null) {
|
||||
log("window unavailable")
|
||||
onComplete(false)
|
||||
return
|
||||
}
|
||||
registerDisplayListener(fps, extraDelayMs, onComplete)
|
||||
window.attributes = window.attributes.apply { preferredDisplayModeId = modeToUse.modeId }
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaCodecList
|
||||
import android.os.Build
|
||||
import java.util.Locale
|
||||
|
||||
/** Canonical decoder lookup and hardware classification for native playback. */
|
||||
internal object MediaCodecQuery {
|
||||
fun findHardwareDecoder(
|
||||
mimeType: String,
|
||||
codecKind: Int = MediaCodecList.REGULAR_CODECS,
|
||||
predicate: (MediaCodecInfo, String) -> Boolean = { _, _ -> true }
|
||||
): MediaCodecInfo? {
|
||||
for (info in MediaCodecList(codecKind).codecInfos) {
|
||||
if (info.isEncoder || !isHardwareAccelerated(info)) continue
|
||||
for (type in info.supportedTypes) {
|
||||
if (type.equals(mimeType, ignoreCase = true) && predicate(info, type)) {
|
||||
return info
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun isHardwareAccelerated(info: MediaCodecInfo): Boolean = isHardwareAccelerated(Build.VERSION.SDK_INT, info.isHardwareAccelerated, info.name)
|
||||
|
||||
internal fun isHardwareAccelerated(
|
||||
sdkInt: Int,
|
||||
platformReportsHardware: Boolean,
|
||||
name: String
|
||||
): Boolean {
|
||||
// API 29 added manufacturer-provided classification, but some Codec2
|
||||
// builders still flag known software components as hardware. Require both
|
||||
// signals there; older releases expose only component names.
|
||||
return if (sdkInt >= Build.VERSION_CODES.Q) {
|
||||
platformReportsHardware && !isSoftwareCodecName(name)
|
||||
} else {
|
||||
!isSoftwareCodecName(name)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isSoftwareCodecName(name: String): Boolean {
|
||||
val normalized = name.lowercase(Locale.ROOT)
|
||||
return normalized.startsWith("omx.google.") ||
|
||||
normalized.startsWith("omx.ffmpeg.") ||
|
||||
normalized.startsWith("c2.android.") ||
|
||||
normalized.startsWith("c2.google.") ||
|
||||
normalized.startsWith("c2.ffmpeg.") ||
|
||||
normalized.contains(".sw.")
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.net.Uri
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
|
||||
internal data class ResolvedMpvUri(
|
||||
val value: String,
|
||||
private val ownedFd: Int? = null
|
||||
) {
|
||||
fun closeIfUnused() {
|
||||
val fd = ownedFd ?: return
|
||||
try {
|
||||
ParcelFileDescriptor.adoptFd(fd).close()
|
||||
} catch (error: Exception) {
|
||||
Log.w("MpvContentUriResolver", "Failed to close unused content FD $fd", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal object MpvContentUriResolver {
|
||||
private const val TAG = "MpvContentUriResolver"
|
||||
|
||||
fun resolve(
|
||||
uriString: String,
|
||||
resolver: ContentResolver,
|
||||
mainHandler: Handler,
|
||||
onResolved: (ResolvedMpvUri) -> Unit
|
||||
) {
|
||||
resolve(uriString, mainHandler, opener = {
|
||||
val descriptor = resolver.openFileDescriptor(Uri.parse(uriString), "r") ?: return@resolve null
|
||||
descriptor.detachFd()
|
||||
}, onResolved = onResolved)
|
||||
}
|
||||
|
||||
internal fun resolve(
|
||||
uriString: String,
|
||||
mainHandler: Handler,
|
||||
opener: () -> Int?,
|
||||
onResolved: (ResolvedMpvUri) -> Unit
|
||||
) {
|
||||
if (!uriString.startsWith("content://")) {
|
||||
onResolved(ResolvedMpvUri(uriString))
|
||||
return
|
||||
}
|
||||
|
||||
Thread {
|
||||
check(Looper.myLooper() != Looper.getMainLooper()) {
|
||||
"Content file descriptors must not be opened on the main thread"
|
||||
}
|
||||
val fd = try {
|
||||
opener()
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "Failed to open content FD for $uriString", error)
|
||||
null
|
||||
}
|
||||
val resolved = if (fd == null) {
|
||||
ResolvedMpvUri(uriString)
|
||||
} else {
|
||||
Log.d(TAG, "Opened content FD $fd for $uriString")
|
||||
ResolvedMpvUri("fdclose://$fd", fd)
|
||||
}
|
||||
mainHandler.post { onResolved(resolved) }
|
||||
}.start()
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
/** Owns the identical MethodChannel/EventChannel lifecycle for native players. */
|
||||
internal class PlayerChannelBinding(
|
||||
private val channelBase: String,
|
||||
private val methodCallHandler: MethodChannel.MethodCallHandler,
|
||||
private val streamHandler: EventChannel.StreamHandler,
|
||||
private val logTag: String
|
||||
) {
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private lateinit var eventChannel: EventChannel
|
||||
private var eventSink: EventChannel.EventSink? = null
|
||||
|
||||
val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
fun attach(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, channelBase)
|
||||
methodChannel.setMethodCallHandler(methodCallHandler)
|
||||
|
||||
eventChannel = EventChannel(binding.binaryMessenger, "$channelBase/events")
|
||||
eventChannel.setStreamHandler(streamHandler)
|
||||
|
||||
Log.d(logTag, "Attached to engine")
|
||||
}
|
||||
|
||||
fun detach() {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
eventChannel.setStreamHandler(null)
|
||||
eventSink = null
|
||||
Log.d(logTag, "Detached from engine")
|
||||
}
|
||||
|
||||
fun listen(events: EventChannel.EventSink?) {
|
||||
eventSink = events
|
||||
Log.d(logTag, "Event stream connected")
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
eventSink = null
|
||||
Log.d(logTag, "Event stream disconnected")
|
||||
}
|
||||
|
||||
fun runOnMain(block: () -> Unit) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
block()
|
||||
} else {
|
||||
mainHandler.post(block)
|
||||
}
|
||||
}
|
||||
|
||||
fun emitProperty(id: Int, value: Any?) {
|
||||
runOnMain { eventSink?.success(listOf(id, value)) }
|
||||
}
|
||||
|
||||
fun emitEvent(name: String, data: Map<String, Any>? = null) {
|
||||
val event = mutableMapOf<String, Any>(
|
||||
"type" to "event",
|
||||
"name" to name
|
||||
)
|
||||
data?.let { event["data"] = it }
|
||||
runOnMain { eventSink?.success(event) }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
interface PlayerDelegate {
|
||||
fun onPropertyChange(name: String, value: Any?)
|
||||
fun onEvent(name: String, data: Map<String, Any>?)
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.app.Activity
|
||||
import android.graphics.Color
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
|
||||
/** Shared Android view scaffold beneath the ExoPlayer and mpv cores. */
|
||||
internal object PlayerSurfaceHost {
|
||||
fun createContainer(activity: Activity, clipChildren: Boolean = false): FrameLayout = FrameLayout(activity).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
setBackgroundColor(Color.BLACK)
|
||||
this.clipChildren = clipChildren
|
||||
}
|
||||
|
||||
fun createVideoSurface(activity: Activity, callback: SurfaceHolder.Callback): SurfaceView = SurfaceView(activity).apply {
|
||||
layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
holder.addCallback(callback)
|
||||
setZOrderOnTop(false)
|
||||
setZOrderMediaOverlay(false)
|
||||
FlutterOverlayHelper.applyCompositionOrder(this, -2)
|
||||
}
|
||||
|
||||
fun attachToContent(activity: Activity, container: FrameLayout): ViewGroup {
|
||||
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
|
||||
contentView.addView(container, 0)
|
||||
ensureFlutterOverlayOnTop(contentView, container)
|
||||
return contentView
|
||||
}
|
||||
|
||||
fun ensureFlutterOverlayOnTop(contentView: ViewGroup, surfaceContainer: ViewGroup?): Boolean {
|
||||
val flutterContainer = FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)
|
||||
?: return false
|
||||
if (contentView.getChildAt(contentView.childCount - 1) !== flutterContainer) {
|
||||
FlutterOverlayHelper.configureFlutterZOrder(contentView, flutterContainer, compositionOrder = 1)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.edde746.plezy.shared
|
||||
|
||||
import android.graphics.Color
|
||||
|
||||
object ThemeHelper {
|
||||
fun themeColor(mode: String?): Int? = when (mode) {
|
||||
"oled" -> Color.BLACK
|
||||
"dark" -> Color.parseColor("#0E0F12")
|
||||
"light" -> Color.parseColor("#F7F7F8")
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package com.edde746.plezy.watchnext
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.tvprovider.media.tv.TvContractCompat
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* Flutter plugin for Android TV Watch Next integration.
|
||||
* Syncs Plex "On Deck" content to the Android TV launcher's Watch Next row.
|
||||
*/
|
||||
class WatchNextPlugin :
|
||||
FlutterPlugin,
|
||||
MethodChannel.MethodCallHandler {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WatchNextPlugin"
|
||||
private const val METHOD_CHANNEL = "com.plezy/watch_next"
|
||||
|
||||
private var pendingDeepLink: String? = null
|
||||
|
||||
/**
|
||||
* Parse a Watch Next deep link intent.
|
||||
* Returns the content ID if this was a Watch Next intent, null otherwise.
|
||||
*/
|
||||
fun handleIntent(intent: Intent?): String? {
|
||||
val data = intent?.data ?: return null
|
||||
if (data.scheme == "plezy" && data.authority == "play") {
|
||||
return data.getQueryParameter("content_id")
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var methodChannel: MethodChannel
|
||||
private var applicationContext: Context? = null
|
||||
private var watchNextProvider: WatchNextProvider? = null
|
||||
private val ioExecutor by lazy { Executors.newSingleThreadExecutor() }
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
applicationContext = binding.applicationContext
|
||||
watchNextProvider = WatchNextProvider(binding.applicationContext)
|
||||
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
|
||||
methodChannel.setMethodCallHandler(this)
|
||||
}
|
||||
|
||||
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
methodChannel.setMethodCallHandler(null)
|
||||
applicationContext = null
|
||||
watchNextProvider = null
|
||||
ioExecutor.shutdown()
|
||||
}
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"isSupported" -> handleIsSupported(result)
|
||||
"sync" -> handleSync(call, result)
|
||||
"clear" -> handleClear(result)
|
||||
"remove" -> handleRemove(call, result)
|
||||
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleIsSupported(result: MethodChannel.Result) {
|
||||
val context = applicationContext
|
||||
if (context == null) {
|
||||
result.success(false)
|
||||
return
|
||||
}
|
||||
result.success(context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK))
|
||||
}
|
||||
|
||||
private fun handleSync(call: MethodCall, result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
|
||||
val itemsData = call.argument<List<Map<String, Any?>>>("items")
|
||||
if (itemsData == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'items' argument", null)
|
||||
return
|
||||
}
|
||||
|
||||
val items = itemsData.mapNotNull { parseWatchNextItem(it) }
|
||||
executeOnIo(result) { provider.syncWatchNextPrograms(items) }
|
||||
}
|
||||
|
||||
private fun handleClear(result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
executeOnIo(result) { provider.clearAll() }
|
||||
}
|
||||
|
||||
private fun handleRemove(call: MethodCall, result: MethodChannel.Result) {
|
||||
val provider = watchNextProvider
|
||||
if (provider == null) {
|
||||
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
|
||||
return
|
||||
}
|
||||
|
||||
val contentId = call.argument<String>("contentId")
|
||||
if (contentId == null) {
|
||||
result.error("INVALID_ARGS", "Missing 'contentId' argument", null)
|
||||
return
|
||||
}
|
||||
executeOnIo(result) { provider.removeItem(contentId) }
|
||||
}
|
||||
|
||||
private fun executeOnIo(result: MethodChannel.Result, block: () -> Any?) {
|
||||
try {
|
||||
ioExecutor.execute {
|
||||
try {
|
||||
val value = block()
|
||||
mainHandler.post { result.success(value) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "IO operation failed: ${e.message}", e)
|
||||
mainHandler.post { result.error("IO_ERROR", e.message, null) }
|
||||
}
|
||||
}
|
||||
} catch (e: java.util.concurrent.RejectedExecutionException) {
|
||||
result.error("SHUTDOWN", "Plugin is shutting down", null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleGetInitialDeepLink(result: MethodChannel.Result) {
|
||||
val contentId = pendingDeepLink
|
||||
pendingDeepLink = null
|
||||
result.success(contentId)
|
||||
}
|
||||
|
||||
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
|
||||
val contentId = data["contentId"] as? String ?: return null
|
||||
val title = data["title"] as? String ?: return null
|
||||
|
||||
val typeString = data["type"] as? String ?: "movie"
|
||||
val type = when (typeString.lowercase()) {
|
||||
"episode" -> TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE
|
||||
"movie" -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
|
||||
else -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
|
||||
}
|
||||
|
||||
return WatchNextProvider.WatchNextItem(
|
||||
contentId = contentId,
|
||||
title = title,
|
||||
episodeTitle = data["episodeTitle"] as? String,
|
||||
description = data["description"] as? String,
|
||||
posterUri = data["posterUri"] as? String,
|
||||
type = type,
|
||||
duration = (data["duration"] as? Number)?.toLong() ?: 0L,
|
||||
lastPlaybackPosition = (data["lastPlaybackPosition"] as? Number)?.toLong() ?: 0L,
|
||||
lastEngagementTime = (data["lastEngagementTime"] as? Number)?.toLong() ?: System.currentTimeMillis(),
|
||||
seriesTitle = data["seriesTitle"] as? String,
|
||||
seasonNumber = (data["seasonNumber"] as? Number)?.toInt(),
|
||||
episodeNumber = (data["episodeNumber"] as? Number)?.toInt()
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a deep link content ID for delivery to Flutter.
|
||||
* Called from MainActivity on intent receipt.
|
||||
*/
|
||||
fun notifyDeepLink(contentId: String) {
|
||||
pendingDeepLink = contentId
|
||||
try {
|
||||
methodChannel.invokeMethod("onWatchNextTap", mapOf("contentId" to contentId))
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Method channel not ready, stored as pending deep link")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package com.edde746.plezy.watchnext
|
||||
|
||||
import android.content.ContentProviderOperation
|
||||
import android.content.ContentUris
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.tvprovider.media.tv.TvContractCompat
|
||||
import androidx.tvprovider.media.tv.WatchNextProgram
|
||||
|
||||
/**
|
||||
* Wraps Android TvProvider API for Watch Next row integration.
|
||||
* Manages WatchNextProgram entries for Plex "On Deck" content.
|
||||
*/
|
||||
class WatchNextProvider(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WatchNextProvider"
|
||||
}
|
||||
|
||||
data class WatchNextItem(
|
||||
val contentId: String,
|
||||
val title: String,
|
||||
val episodeTitle: String?,
|
||||
val description: String?,
|
||||
val posterUri: String?,
|
||||
val type: Int,
|
||||
val duration: Long,
|
||||
val lastPlaybackPosition: Long,
|
||||
val lastEngagementTime: Long,
|
||||
val seriesTitle: String?,
|
||||
val seasonNumber: Int?,
|
||||
val episodeNumber: Int?
|
||||
)
|
||||
|
||||
/**
|
||||
* Sync items to Watch Next row.
|
||||
* Uses applyBatch to delete + insert in a single transaction so the
|
||||
* launcher receives one content-change notification with the full set.
|
||||
*/
|
||||
fun syncWatchNextPrograms(items: List<WatchNextItem>): Boolean = try {
|
||||
val ops = ArrayList<ContentProviderOperation>()
|
||||
|
||||
ops.add(
|
||||
ContentProviderOperation.newDelete(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI
|
||||
).build()
|
||||
)
|
||||
|
||||
for (item in items) {
|
||||
val program = buildProgram(item)
|
||||
ops.add(
|
||||
ContentProviderOperation.newInsert(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI
|
||||
).withValues(program.toContentValues()).build()
|
||||
)
|
||||
}
|
||||
|
||||
context.contentResolver.applyBatch(TvContractCompat.AUTHORITY, ops)
|
||||
Log.d(TAG, "Synced ${items.size} Watch Next entries")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to sync Watch Next programs", e)
|
||||
false
|
||||
}
|
||||
|
||||
fun clearAll(): Boolean = try {
|
||||
context.contentResolver.delete(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
null,
|
||||
null
|
||||
)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to clear Watch Next entries", e)
|
||||
false
|
||||
}
|
||||
|
||||
fun removeItem(contentId: String): Boolean {
|
||||
return try {
|
||||
val cursor = context.contentResolver.query(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
arrayOf(
|
||||
TvContractCompat.WatchNextPrograms._ID,
|
||||
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID
|
||||
),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
|
||||
cursor?.use {
|
||||
val idIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms._ID)
|
||||
val providerIdIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID)
|
||||
|
||||
if (idIndex < 0 || providerIdIndex < 0) return false
|
||||
|
||||
while (it.moveToNext()) {
|
||||
if (it.getString(providerIdIndex) == contentId) {
|
||||
val id = it.getLong(idIndex)
|
||||
val deleteUri = ContentUris.withAppendedId(
|
||||
TvContractCompat.WatchNextPrograms.CONTENT_URI,
|
||||
id
|
||||
)
|
||||
context.contentResolver.delete(deleteUri, null, null)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to remove Watch Next item: $contentId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildProgram(item: WatchNextItem): WatchNextProgram {
|
||||
val watchNextType = if (item.lastPlaybackPosition > 0) {
|
||||
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE
|
||||
} else {
|
||||
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT
|
||||
}
|
||||
|
||||
val builder = WatchNextProgram.Builder()
|
||||
.setType(item.type)
|
||||
.setWatchNextType(watchNextType)
|
||||
.setTitle(item.title)
|
||||
.setInternalProviderId(item.contentId)
|
||||
.setLastEngagementTimeUtcMillis(item.lastEngagementTime)
|
||||
|
||||
item.description?.let { builder.setDescription(it) }
|
||||
|
||||
item.posterUri?.let { uri ->
|
||||
try {
|
||||
builder.setPosterArtUri(Uri.parse(uri))
|
||||
builder.setPosterArtAspectRatio(TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to parse poster URI: $uri", e)
|
||||
}
|
||||
}
|
||||
|
||||
if (item.duration > 0) {
|
||||
builder.setDurationMillis(item.duration.toInt())
|
||||
if (item.lastPlaybackPosition > 0) {
|
||||
builder.setLastPlaybackPositionMillis(item.lastPlaybackPosition.toInt())
|
||||
}
|
||||
}
|
||||
|
||||
if (item.type == TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE) {
|
||||
item.episodeTitle?.let { builder.setEpisodeTitle(it) }
|
||||
item.seasonNumber?.let { builder.setSeasonNumber(it) }
|
||||
item.episodeNumber?.let { builder.setEpisodeNumber(it) }
|
||||
}
|
||||
|
||||
val intentUri = Uri.Builder()
|
||||
.scheme("plezy")
|
||||
.authority("play")
|
||||
.appendQueryParameter("content_id", item.contentId)
|
||||
.build()
|
||||
builder.setIntentUri(intentUri)
|
||||
|
||||
return builder.build()
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 820 B |
@@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="?android:colorBackground" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
</layer-list>
|
||||
|
Before Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 115 KiB |
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<vector xmlns:aapt="http://schemas.android.com/aapt"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:height="108dp"
|
||||
android:width="108dp"
|
||||
android:viewportHeight="911.63"
|
||||
android:viewportWidth="911.63">
|
||||
<group android:translateX="276.65" android:translateY="223.88">
|
||||
<path android:pathData="M335.65,192.66L68.01,38.14C37.78,20.69,0,42.5,0,77.41v309.04c0,34.91,37.78,56.72,68.01,39.27l267.64-154.52c30.23-17.45,30.23-61.08,0-78.54ZM255.53,276.8c-19.1,17.66-38.75,26.49-58.4,26.49s-39.29-8.83-58.39-26.49c-14.39-13.3-28.55-20.05-42.11-20.05s-27.72,6.75-42.1,20.05c-4.87,4.5-12.46,4.2-16.96-0.67-4.5-4.86-4.2-12.45 0.67-16.95,38.2-35.33,78.59-35.33,116.79,0,14.38,13.3,28.55,20.04,42.1,20.04s27.72-6.74,42.11-20.04c4.86-4.5,12.46-4.21,16.95,0.66,4.5,4.87,4.21,12.46-0.66,16.96ZM255.53,204.04c-19.1,17.67-38.75,26.5-58.4,26.5s-39.29-8.83-58.39-26.5c-14.39-13.3-28.55-20.04-42.11-20.04s-27.72,6.74-42.1,20.04c-4.87,4.5-12.46,4.21-16.96-0.66s-4.2-12.46,0.67-16.96c38.2-35.32,78.59-35.32,116.79,0,14.38,13.3,28.55,20.05,42.1,20.05s27.72-6.75,42.11-20.05c4.86-4.5,12.46-4.2,16.95,0.67,4.5,4.86,4.21,12.45-0.66,16.95Z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:type="linear"
|
||||
android:startX="22.67"
|
||||
android:startY="425.72"
|
||||
android:endX="201.83"
|
||||
android:endY="115.4">
|
||||
<item android:color="#FFAB543A" android:offset="0.0" />
|
||||
<item android:color="#FFFF7E57" android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:height="108dp"
|
||||
android:width="108dp"
|
||||
android:viewportHeight="911.63"
|
||||
android:viewportWidth="911.63">
|
||||
<group android:translateX="276.65" android:translateY="223.88">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M335.65,192.66L68.01,38.14C37.78,20.69,0,42.5,0,77.41v309.04c0,34.91,37.78,56.72,68.01,39.27l267.64-154.52c30.23-17.45,30.23-61.08,0-78.54ZM255.53,276.8c-19.1,17.66-38.75,26.49-58.4,26.49s-39.29-8.83-58.39-26.49c-14.39-13.3-28.55-20.05-42.11-20.05s-27.72,6.75-42.1,20.05c-4.87,4.5-12.46,4.2-16.96-0.67-4.5-4.86-4.2-12.45 0.67-16.95,38.2-35.33,78.59-35.33,116.79,0,14.38,13.3,28.55,20.04,42.1,20.04s27.72-6.74,42.11-20.04c4.86-4.5,12.46-4.21,16.95,0.66,4.5,4.87,4.21,12.46-0.66,16.96ZM255.53,204.04c-19.1,17.67-38.75,26.5-58.4,26.5s-39.29-8.83-58.39-26.5c-14.39-13.3-28.55-20.04-42.11-20.04s-27.72,6.74-42.1,20.04c-4.87,4.5-12.46,4.21-16.96-0.66s-4.2-12.46,0.67-16.96c38.2-35.32,78.59-35.32,116.79,0,14.38,13.3,28.55,20.05,42.1,20.05s27.72-6.75,42.11-20.05c4.86-4.5,12.46-4.2,16.95,0.67,4.5,4.86,4.21,12.45-0.66,16.95Z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@color/splash_background" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
</layer-list>
|
||||
@@ -1,3 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<inset xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:drawable="@drawable/ic_launcher_foreground" />
|
||||
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome" />
|
||||
</adaptive-icon>
|
||||
|
Before Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 14 KiB |
@@ -1,39 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<style name="SplashTheme.Dark" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_dark</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Oled" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_oled</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Light" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_light</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.System" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#1a1a1a</color>
|
||||
<color name="splash_background">#0E0F12</color>
|
||||
<color name="splash_dark">#0E0F12</color>
|
||||
<color name="splash_oled">#000000</color>
|
||||
<color name="splash_light">#F7F7F8</color>
|
||||
</resources>
|
||||
@@ -1,44 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||
running.
|
||||
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<!-- Splash theme variants for setSplashScreenTheme -->
|
||||
<style name="SplashTheme.Dark" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_dark</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Oled" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_oled</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Light" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_light</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.System" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- TV (Android TV / Google TV / Fire TV) launch + window background.
|
||||
The television UI-mode qualifier outranks night/notnight, so this wins
|
||||
even on TVs that report notnight (most do) where values/ would resolve
|
||||
the near-white #F7F7F8. Black matches the OLED default theme on TV. -->
|
||||
<color name="splash_background">#000000</color>
|
||||
</resources>
|
||||
@@ -1,39 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<style name="SplashTheme.Dark" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_dark</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Oled" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_oled</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Light" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_light</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.System" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_icon</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#ffffff</color>
|
||||
<color name="splash_background">#F7F7F8</color>
|
||||
<color name="splash_dark">#0E0F12</color>
|
||||
<color name="splash_oled">#000000</color>
|
||||
<color name="splash_light">#F7F7F8</color>
|
||||
</resources>
|
||||
@@ -1,44 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<!-- Theme applied to the Android Window as soon as the process has started.
|
||||
This theme determines the color of the Android Window while your
|
||||
Flutter UI initializes, as well as behind your Flutter UI while its
|
||||
running.
|
||||
|
||||
This Theme is only used starting with V2 of Flutter's Android embedding. -->
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<!-- Disable Android's default green focus highlight that appears during d-pad/keyboard navigation -->
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<!-- Splash theme variants for setSplashScreenTheme -->
|
||||
<style name="SplashTheme.Dark" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_dark</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Oled" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_oled</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.Light" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_light</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
<style name="SplashTheme.System" parent="@android:style/Theme.Light.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_background</item>
|
||||
<item name="android:defaultFocusHighlightEnabled">false</item>
|
||||
<item name="android:colorControlHighlight">@android:color/transparent</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,14 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths>
|
||||
<!-- App-internal files directory (getApplicationDocumentsDirectory on Android) -->
|
||||
<files-path name="app_files" path="." />
|
||||
<!-- External files directory (fallback) -->
|
||||
<external-files-path name="external_files" path="." />
|
||||
<!-- External storage root (for custom download paths on shared storage) -->
|
||||
<external-path name="external" path="." />
|
||||
<!-- Cache directories -->
|
||||
<cache-path name="cache" path="." />
|
||||
<external-cache-path name="external_cache" path="." />
|
||||
<!-- Filesystem root (ultimate fallback for any absolute path) -->
|
||||
<root-path name="root" path="" />
|
||||
</paths>
|
||||
@@ -1,7 +0,0 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- The INTERNET permission is required for development. Specifically,
|
||||
the Flutter tool needs it to communicate with the running application
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
</manifest>
|
||||
@@ -1,102 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.graphics.SurfaceTexture
|
||||
import android.os.Looper
|
||||
import android.view.TextureView
|
||||
import java.time.Duration
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.Shadows.shadowOf
|
||||
import org.robolectric.annotation.LooperMode
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@LooperMode(LooperMode.Mode.PAUSED)
|
||||
class DeferredSurfaceTextureListenerTest {
|
||||
|
||||
private lateinit var surface: SurfaceTexture
|
||||
private lateinit var delegate: RecordingListener
|
||||
private lateinit var listener: DeferredSurfaceTextureListener
|
||||
private var currentSurface: SurfaceTexture? = null
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
surface = SurfaceTexture(0)
|
||||
currentSurface = surface
|
||||
delegate = RecordingListener()
|
||||
listener = DeferredSurfaceTextureListener(delegate) { candidate -> candidate === currentSurface }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
surface.release()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forwardsRepeatedSameSizeCallbacks() {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
idlePastResizeDelay()
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(listOf(1920 to 1080, 1920 to 1080), delegate.sizes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun coalescesPendingCallbacksToLatestSize() {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1280, 720)
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(listOf(1920 to 1080), delegate.sizes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ignoresCallbackForObsoleteSurface() {
|
||||
val replacement = SurfaceTexture(0)
|
||||
try {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
currentSurface = replacement
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(emptyList<Pair<Int, Int>>(), delegate.sizes)
|
||||
} finally {
|
||||
replacement.release()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun destroyingSurfaceCancelsPendingCallback() {
|
||||
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
|
||||
listener.onSurfaceTextureDestroyed(surface)
|
||||
idlePastResizeDelay()
|
||||
|
||||
assertEquals(emptyList<Pair<Int, Int>>(), delegate.sizes)
|
||||
assertEquals(1, delegate.destroyedCount)
|
||||
}
|
||||
|
||||
private fun idlePastResizeDelay() {
|
||||
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(101))
|
||||
}
|
||||
|
||||
private class RecordingListener : TextureView.SurfaceTextureListener {
|
||||
val sizes = mutableListOf<Pair<Int, Int>>()
|
||||
var destroyedCount = 0
|
||||
|
||||
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) = Unit
|
||||
|
||||
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
|
||||
sizes += width to height
|
||||
}
|
||||
|
||||
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) = Unit
|
||||
|
||||
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
|
||||
destroyedCount++
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package com.edde746.plezy
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.Robolectric
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class ExternalPlayerChannelTest {
|
||||
|
||||
@Test
|
||||
fun mxPlayerResultPreservesPositionDurationAndCompletion() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).get()
|
||||
val channel = ExternalPlayerChannel(activity)
|
||||
val data = Intent("com.mxtech.intent.result.VIEW")
|
||||
.putExtra("position", 123)
|
||||
.putExtra("duration", "456")
|
||||
.putExtra("end_by", "playback_completion")
|
||||
|
||||
val result = channel.buildResult(Activity.RESULT_OK, data)
|
||||
|
||||
assertEquals(123L, result["positionMs"])
|
||||
assertEquals(456L, result["durationMs"])
|
||||
assertEquals(true, result["playbackCompleted"])
|
||||
assertEquals(false, result["playbackError"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activityDestroyCompletesPendingChannelCall() {
|
||||
val activity = Robolectric.buildActivity(Activity::class.java).get()
|
||||
val channel = ExternalPlayerChannel(activity)
|
||||
val result = RecordingResult()
|
||||
channel.javaClass.getDeclaredField("pendingResult").apply {
|
||||
isAccessible = true
|
||||
set(channel, result)
|
||||
}
|
||||
|
||||
channel.dispose()
|
||||
|
||||
assertTrue(result.completed)
|
||||
assertEquals("ACTIVITY_DESTROYED", result.errorCode)
|
||||
}
|
||||
|
||||
private class RecordingResult : MethodChannel.Result {
|
||||
var completed = false
|
||||
var errorCode: String? = null
|
||||
|
||||
override fun success(result: Any?) {
|
||||
completed = true
|
||||
}
|
||||
|
||||
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
|
||||
completed = true
|
||||
this.errorCode = errorCode
|
||||
}
|
||||
|
||||
override fun notImplemented() {
|
||||
completed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.edde746.plezy.exoplayer
|
||||
|
||||
import androidx.media3.common.MimeTypes
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class AudioOutputPolicyTest {
|
||||
|
||||
@Test
|
||||
fun passthroughDisabledBlocksBitstreamFormats() {
|
||||
val bitstreamFormats = listOf(
|
||||
"audio/ac3",
|
||||
"audio/eac3",
|
||||
"audio/eac3-joc",
|
||||
"audio/ac4",
|
||||
"audio/vnd.dts",
|
||||
"audio/vnd.dts.hd",
|
||||
"audio/vnd.dts.uhd",
|
||||
MimeTypes.AUDIO_TRUEHD
|
||||
)
|
||||
|
||||
for (mimeType in bitstreamFormats) {
|
||||
assertTrue(mimeType, shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled = false))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passthroughEnabledAllowsBitstreamFormats() {
|
||||
assertFalse(shouldBlockDirectOutputForPassthrough("audio/ac3", audioPassthroughEnabled = true))
|
||||
assertFalse(shouldBlockDirectOutputForPassthrough(MimeTypes.AUDIO_TRUEHD, audioPassthroughEnabled = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passthroughDisabledLeavesDecodedFormatsAvailable() {
|
||||
val decodedFormats = listOf(
|
||||
MimeTypes.AUDIO_AAC,
|
||||
MimeTypes.AUDIO_OPUS,
|
||||
MimeTypes.AUDIO_RAW,
|
||||
MimeTypes.AUDIO_FLAC
|
||||
)
|
||||
|
||||
for (mimeType in decodedFormats) {
|
||||
assertFalse(mimeType, shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled = false))
|
||||
}
|
||||
}
|
||||
}
|
||||