diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 40a2cdd36..89876ae61 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -414,9 +414,7 @@ jobs: - arch: arm64 runner: windows-11-arm flutter_setup: git - native_cache_path: | - build/windows/arm64/_deps - build/windows/arm64/mpv-dev-arm64 + native_cache_path: build/windows/arm64/_deps steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -429,11 +427,6 @@ jobs: path: ${{ matrix.native_cache_path }} key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-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@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 @@ -725,17 +718,49 @@ jobs: exit 1 - - name: Cache libmpv build + - name: Cache libmpv prefix id: libmpv-cache uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: libmpv-prefix - key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh', 'linux/packaging/native-inputs.json') }} + key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-libmpv-${{ runner.arch }}-${{ hashFiles('mpv-build.lock.json') }} - - name: Build libmpv + # The prebuilt prefix from our unified mpv-build repo: the lock names the + # asset and the expected SHA-256, so the bytes are verified before a + # single one is extracted. The tarball is a self-relocating prefix tree + # (lib/ or lib// with the libmpv.so* chain, lib/libshaderc_shared.so*, + # include/, and pkgconfig/ dirs with ${pcfiledir}-relative roots), so the + # downstream PKG_CONFIG_PATH, bundle-copy, and find steps are unchanged. + - name: Fetch libmpv if: steps.libmpv-cache.outputs.cache-hit != 'true' shell: bash - run: bash linux/packaging/build-libmpv.sh + run: | + command -v zstd >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y --no-install-recommends zstd; } + python3 - <<'PY' + import hashlib + import json + import platform + import subprocess + import tempfile + import urllib.request + from pathlib import Path + + lock = json.loads(Path("mpv-build.lock.json").read_text(encoding="utf-8")) + group = lock["artifacts"]["linux"] + entry = group["assets"][platform.machine()] + url = f"{group['assetBase']}/{entry['asset']}" + print(f"fetching {url}", flush=True) + with urllib.request.urlopen(url) as response: + data = response.read() + digest = hashlib.sha256(data).hexdigest() + if digest != entry["checksum"]: + raise SystemExit(f"{entry['asset']}: SHA-256 {digest} does not match locked {entry['checksum']}") + Path("libmpv-prefix").mkdir(exist_ok=True) + with tempfile.NamedTemporaryFile(suffix=".tar.zst") as archive: + archive.write(data) + archive.flush() + subprocess.run(["tar", "--zstd", "-xf", archive.name, "-C", "libmpv-prefix"], check=True) + PY - name: Install fpm shell: bash diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 80846af74..0dcb11806 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -252,9 +252,6 @@ jobs: - name: Verify native formatting run: scripts/format_native.sh --check - - name: Verify Linux native acquisition and build plan - run: bash linux/packaging/build-libmpv_test.sh - linux-native-test: name: Linux native reliability (${{ matrix.sanitizer }}) runs-on: ubuntu-latest @@ -645,10 +642,10 @@ jobs: cache: true pub-cache: false - # The packaging deps, minus libmpv: this job builds it from source below, - # because the distro's is a different version with different windowing - # backends, and a package smoke-built against it cannot show that - # build-libmpv.sh still works or that the bundle it produces is coherent. + # The packaging deps, minus libmpv: that arrives prebuilt from mpv-build + # below. The dev packages still matter — they install the runtime + # libraries the pinned libmpv links (ass, pulse, pipewire, ...), which + # bundle-libs.sh resolves off the host into the bundle. - name: Install packaging dependencies run: | sudo apt-get update @@ -662,25 +659,52 @@ jobs: liblua5.2-dev rpm libarchive-tools imagemagick ruby-dev build-essential sudo gem install fpm --version 1.17.0 --no-document - # Keyed the same way build.yml keys it, so editing the script or its pinned - # inputs is what invalidates the cache - and this branch's whole point is - # that those edits get exercised somewhere. - - name: Cache libmpv build + # Keyed the same way build.yml keys it: the lock names the asset and its + # checksum, so editing the lock is what invalidates the cache. + - name: Cache libmpv prefix id: libmpv-cache uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 with: path: libmpv-prefix - key: ci-libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh', 'linux/packaging/native-inputs.json') }} + key: ci-libmpv-${{ runner.arch }}-${{ hashFiles('mpv-build.lock.json') }} - - name: Build libmpv + # Same contract as build.yml: read mpv-build.lock.json, download the + # linux asset for this arch, verify its SHA-256, extract the prefix tree. + - name: Fetch libmpv if: steps.libmpv-cache.outputs.cache-hit != 'true' - run: bash linux/packaging/build-libmpv.sh + run: | + command -v zstd >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y --no-install-recommends zstd; } + python3 - <<'PY' + import hashlib + import json + import platform + import subprocess + import tempfile + import urllib.request + from pathlib import Path - # The windowing backends the runner depends on, read off the library the - # script just produced. The plane hands mpv MPV_RENDER_PARAM_WL_DISPLAY, so - # a libmpv without Wayland cannot find the VAAPI device and quietly decodes - # in software; X11 and VDPAU are gone with the texture path. - - name: Check the built libmpv's backends + lock = json.loads(Path("mpv-build.lock.json").read_text(encoding="utf-8")) + group = lock["artifacts"]["linux"] + entry = group["assets"][platform.machine()] + url = f"{group['assetBase']}/{entry['asset']}" + print(f"fetching {url}", flush=True) + with urllib.request.urlopen(url) as response: + data = response.read() + digest = hashlib.sha256(data).hexdigest() + if digest != entry["checksum"]: + raise SystemExit(f"{entry['asset']}: SHA-256 {digest} does not match locked {entry['checksum']}") + Path("libmpv-prefix").mkdir(exist_ok=True) + with tempfile.NamedTemporaryFile(suffix=".tar.zst") as archive: + archive.write(data) + archive.flush() + subprocess.run(["tar", "--zstd", "-xf", archive.name, "-C", "libmpv-prefix"], check=True) + PY + + # The windowing backends the runner depends on, read off the pinned + # library just extracted. The plane hands mpv MPV_RENDER_PARAM_WL_DISPLAY, + # so a libmpv without Wayland cannot find the VAAPI device and quietly + # decodes in software; X11 and VDPAU are gone with the texture path. + - name: Check the pinned libmpv's backends run: | LIB=$(find libmpv-prefix -name 'libmpv.so.2' | head -1) echo "== $LIB ==" diff --git a/README.md b/README.md index c8944cb78..e4285144b 100644 --- a/README.md +++ b/README.md @@ -205,4 +205,4 @@ Plezy is licensed under [GPL-3.0](LICENSE). - Built with [Flutter](https://flutter.dev) - Supports [Plex Media Server](https://www.plex.tv), [Jellyfin](https://jellyfin.org), and [Emby](https://emby.media) -- 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) +- Playback powered by [mpv](https://mpv.io) via our [mpv-build](https://github.com/edde746/mpv-build) pipeline (started as a fork of [MPVKit](https://github.com/mpvkit/MPVKit); the Android Kotlin/JNI glue descends from [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), and [libass-android](https://github.com/peerless2012/libass-android) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 77c303737..7bbbbbb95 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -58,95 +58,31 @@ plugins { id("dev.flutter.flutter-gradle-plugin") } -val mpvVersion = "v1.2.2" -val mpvSha256 = "0207bb46660c239268c4c17bddc7fd570722513344b136c7c5336aca135dc8a0" -val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile -val mpvAar = "libmpv-release.aar" -val mpvUrl = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar" - -// Dev-only escape hatch: point the build at a locally built libmpv AAR -// (libmpv-android's build-local.sh output) to test fork patches before a -// release is pinned. The URL + sha256 above stay authoritative otherwise. -val localMpvAar: String? = (project.findProperty("plezy.localMpvAar") as String?) - ?: System.getenv("PLEZY_LOCAL_MPV_AAR") +// The in-project :libmpv module owns the mpv-build pin (repo-root +// mpv-build.lock.json assets + checksums, plus the plezy.localMpvDir/ +// PLEZY_LOCAL_MPV_DIR escape hatch) and extracts the per-ABI tarballs' +// prebuilt native libraries. This file reads two of its output trees +// back: FFmpeg .so files for the Media3 adapter link step, and the libc++ +// runtime packaged at PROJECT scope below. +val libmpvBuildDir = project(":libmpv").layout.buildDirectory.dir("libmpv").get().asFile +val libmpvNativeJniDir = File(libmpvBuildDir, "native/jni") +val libmpvLibcxxJniDir = File(libmpvBuildDir, "libcxx/jni") val media3Version = "1.11.0" val mpvFfmpegVersion = "8.0.1" val mpvFfmpegSourceSha256 = "05ee0b03119b45c0bdb4df654b96802e909e0a752f72e4fe3794f487229e5a41" val mpvFfmpegSourceUrl = "https://ffmpeg.org/releases/ffmpeg-$mpvFfmpegVersion.tar.xz" -val mpvFfmpegDevelopmentDir = File(mpvDir, "ffmpeg-development") - -val downloadLibmpv = tasks.register("downloadLibmpv") { - val aar = File(mpvDir, mpvAar) - val manifest = File(mpvDir, ".manifest") - inputs.property("version", mpvVersion) - inputs.property("sourceUrl", mpvUrl) - inputs.property("sha256", mpvSha256) - inputs.property("localOverride", localMpvAar ?: "") - localMpvAar?.let { inputs.file(it) } - outputs.files(aar, manifest) - doLast { - mpvDir.parentFile.mkdirs() - val staging = File(mpvDir.parentFile, "${mpvDir.name}.staging-${UUID.randomUUID()}") - try { - staging.mkdirs() - val stagedAar = File(staging, mpvAar) - if (localMpvAar != null) { - File(localMpvAar).copyTo(stagedAar, overwrite = true) - File(staging, ".manifest").writeText("version=local\nsource=$localMpvAar\n") - } else { - try { - providers.exec { - commandLine("curl", "-sfL", mpvUrl, "-o", stagedAar.absolutePath) - }.result.get().assertNormalExitValue() - } catch (error: Exception) { - throw GradleException("Failed to download $mpvAar $mpvVersion", error) - } - verifySha256(stagedAar, mpvSha256, "$mpvAar $mpvVersion") - File(staging, ".manifest").writeText("version=$mpvVersion\nsha256=$mpvSha256\n") - } - promoteDirectory(staging, mpvDir) - } finally { - staging.deleteRecursively() - } - } -} - -// 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 = tasks.register("extractMpvLibcxx") { - 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() - providers.exec { - commandLine( - "unzip", - "-q", - "-o", - aar.absolutePath, - "jni/*/libc++_shared.so", - "-d", - outDir.absolutePath - ) - }.result.get().assertNormalExitValue() - } -} +val mpvFfmpegDevelopmentDir = layout.buildDirectory.dir("libmpv-ffmpeg-development").get().asFile // Build the Media3 JNI adapter against the same shared FFmpeg libraries that // libmpv packages. Headers are pinned to libmpv's FFmpeg version and remain // build-only; the APK contains one FFmpeg implementation for both players. val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment") { - dependsOn(downloadLibmpv) - val aar = File(mpvDir, mpvAar) + dependsOn(":libmpv:extractLibmpvNative") val manifest = File(mpvFfmpegDevelopmentDir, ".manifest") val abis = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64") val libraries = listOf("avcodec", "avutil", "swresample") - inputs.file(aar) + inputs.dir(libmpvNativeJniDir) inputs.property("ffmpegVersion", mpvFfmpegVersion) inputs.property("sourceUrl", mpvFfmpegSourceUrl) inputs.property("sourceSha256", mpvFfmpegSourceSha256) @@ -216,15 +152,12 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment") ) project.copy { - from(zipTree(aar)) { + from(libmpvNativeJniDir) { include( - "jni/*/libavcodec.so", - "jni/*/libavutil.so", - "jni/*/libswresample.so" + "*/libavcodec.so", + "*/libavutil.so", + "*/libswresample.so" ) - eachFile { - path = path.removePrefix("jni/") - } } includeEmptyDirs = false into(nativeDir) @@ -235,11 +168,11 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment") }.filterNot(File::isFile) if (missing.isNotEmpty()) { throw GradleException( - "libmpv $mpvVersion is missing FFmpeg libraries: ${missing.joinToString { it.relativeTo(staging).path }}" + "the :libmpv prebuilt tree is missing FFmpeg libraries: ${missing.joinToString { it.relativeTo(staging).path }}" ) } File(staging, ".manifest").writeText( - "mpv=$mpvVersion\nffmpeg=$mpvFfmpegVersion\nsourceSha256=$mpvFfmpegSourceSha256\n" + "ffmpeg=$mpvFfmpegVersion\nsourceSha256=$mpvFfmpegSourceSha256\n" ) sourceArchive.delete() extractedSource.deleteRecursively() @@ -349,7 +282,7 @@ android { defaultConfig { applicationId = "com.edde746.plezy" - minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26 + minSdk = 25 // Fire OS 6.x (API 25); :libmpv shares the same floor targetSdk = flutter.targetSdkVersion versionCode = flutter.versionCode versionName = flutter.versionName @@ -448,8 +381,9 @@ android { packaging { jniLibs { // pickFirst only suppresses the duplicate libc++ merge error; the - // sourceSets rule below makes libmpv's newer runtime win for - // std::from_chars, while older native consumers remain ABI-compatible. + // sourceSets rule below makes the runtime :libmpv extracts from the + // mpv-build tarballs win for std::from_chars, while older + // native consumers remain ABI-compatible. pickFirsts.add("lib/*/libc++_shared.so") } } @@ -457,8 +391,10 @@ android { 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")) + // order cannot accidentally select an older libc++ copy. The directory + // is :libmpv's extractLibmpvNative output (the tarballs' 16 KB-capable + // libc++), wired below via the JniLibFolders dependency. + jniLibs.srcDir(libmpvLibcxxJniDir) } } @@ -514,16 +450,18 @@ tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") } tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach { - dependsOn(downloadLibmpv, extractMpvLibcxx, prepareMpvFfmpegDevelopment) + dependsOn(prepareMpvFfmpegDevelopment) } // 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) + dependsOn(":libmpv:extractLibmpvNative") } dependencies { - implementation(files(File(mpvDir, mpvAar))) + // mpv Kotlin API + JNI glue live in-project; the prebuilt libmpv/FFmpeg .so + // set rides along from the module's extracted mpv-build tarballs. + implementation(project(":libmpv")) implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0") // Android TV Watch Next integration diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 22ab19465..9f7588f83 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -6,9 +6,6 @@ - - - diff --git a/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvEndFileDiagnostics.kt b/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvEndFileDiagnostics.kt index 46930b6a2..b6b8a4da2 100644 --- a/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvEndFileDiagnostics.kt +++ b/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvEndFileDiagnostics.kt @@ -1,9 +1,9 @@ package com.edde746.plezy.mpv -import dev.jdtech.mpv.EndFileReason -import dev.jdtech.mpv.LogLevel -import dev.jdtech.mpv.LogMessage -import dev.jdtech.mpv.MpvEvent +import com.edde746.plezy.libmpv.EndFileReason +import com.edde746.plezy.libmpv.LogLevel +import com.edde746.plezy.libmpv.LogMessage +import com.edde746.plezy.libmpv.MpvEvent /** Adds the native diagnostic that libmpv-android exposes separately via logFlow. */ internal class MpvEndFileDiagnostics { diff --git a/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvPlayerCore.kt b/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvPlayerCore.kt index 5b21e0b21..9a4d83750 100644 --- a/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvPlayerCore.kt +++ b/android/app/src/main/kotlin/com/edde746/plezy/mpv/MpvPlayerCore.kt @@ -17,12 +17,12 @@ import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import com.edde746.plezy.exoplayer.DoviBridge +import com.edde746.plezy.libmpv.* import com.edde746.plezy.shared.AudioFocusManager import com.edde746.plezy.shared.FrameRateManager import com.edde746.plezy.shared.PlayerDelegate import com.edde746.plezy.shared.PlayerSurfaceHost import com.edde746.plezy.shared.SurfacePlayerCore -import dev.jdtech.mpv.* import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock diff --git a/android/app/src/test/kotlin/com/edde746/plezy/mpv/MpvPlayerPluginTest.kt b/android/app/src/test/kotlin/com/edde746/plezy/mpv/MpvPlayerPluginTest.kt index cfb99425a..a18e9b66c 100644 --- a/android/app/src/test/kotlin/com/edde746/plezy/mpv/MpvPlayerPluginTest.kt +++ b/android/app/src/test/kotlin/com/edde746/plezy/mpv/MpvPlayerPluginTest.kt @@ -7,11 +7,11 @@ import android.os.Looper import android.view.ViewGroup import android.view.ViewTreeObserver import android.widget.FrameLayout +import com.edde746.plezy.libmpv.EndFileReason +import com.edde746.plezy.libmpv.LogLevel +import com.edde746.plezy.libmpv.LogMessage +import com.edde746.plezy.libmpv.MpvEvent import com.edde746.plezy.shared.AudioFocusManager -import dev.jdtech.mpv.EndFileReason -import dev.jdtech.mpv.LogLevel -import dev.jdtech.mpv.LogMessage -import dev.jdtech.mpv.MpvEvent import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.EventChannel import io.flutter.plugin.common.MethodCall diff --git a/android/libass/build.gradle.kts b/android/libass/build.gradle.kts index 6998c8234..c7397ae25 100644 --- a/android/libass/build.gradle.kts +++ b/android/libass/build.gradle.kts @@ -12,7 +12,7 @@ android { compileSdk = 36 // Matches the app's latest stable NDK so every project-owned native library // is built with the same 16 KB page-size-capable libc++ toolchain. That copy - // is NOT what ships: the app packages the libmpv AAR's newer copy with top + // is NOT what ships: the app packages the mpv-build tarball's newer copy with top // merge priority (see app/build.gradle.kts packaging { jniLibs } + sourceSets). ndkVersion = "29.0.14206865" diff --git a/android/libmpv/build.gradle.kts b/android/libmpv/build.gradle.kts new file mode 100644 index 000000000..39b7c6561 --- /dev/null +++ b/android/libmpv/build.gradle.kts @@ -0,0 +1,290 @@ +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.security.MessageDigest +import java.util.UUID +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +fun verifySha256(file: File, expected: String, identity: String) { + val digest = MessageDigest.getInstance("SHA-256") + file.inputStream().buffered().use { input -> + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + while (true) { + val count = input.read(buffer) + if (count < 0) break + digest.update(buffer, 0, count) + } + } + val actual = digest.digest().joinToString("") { + (it.toInt() and 0xff).toString(16).padStart(2, '0') + } + if (actual != expected) { + throw GradleException("SHA-256 mismatch for $identity: expected $expected, got $actual") + } +} + +fun promoteDirectory(staging: File, destination: File) { + val backup = File(destination.parentFile, "${destination.name}.backup-${UUID.randomUUID()}") + val hadDestination = destination.exists() + try { + if (hadDestination) { + Files.move(destination.toPath(), backup.toPath(), StandardCopyOption.ATOMIC_MOVE) + } + try { + Files.move(staging.toPath(), destination.toPath(), StandardCopyOption.ATOMIC_MOVE) + } catch (promotionFailure: Exception) { + if (hadDestination && backup.exists()) { + try { + Files.move(backup.toPath(), destination.toPath(), StandardCopyOption.ATOMIC_MOVE) + } catch (restoreFailure: Exception) { + promotionFailure.addSuppressed(restoreFailure) + } + } + throw promotionFailure + } + if (hadDestination && backup.exists() && !backup.deleteRecursively()) { + throw GradleException("Failed to remove obsolete native artifact backup at ${backup.absolutePath}") + } + } finally { + staging.deleteRecursively() + } +} + +// mpv Kotlin API + JNI glue built in-project (imported from the libmpv-android +// fork, commit e60c3ba); the external dependency is reduced to prebuilt native +// trees carried by the mpv-build per-ABI tarballs pinned below. +plugins { + id("com.android.library") + id("org.jetbrains.kotlin.android") +} + +// Single source for the pinned native artifacts: the repo-root +// mpv-build.lock.json (github.com/edde746/mpv-build release assets + sha256 +// checksums). This module downloads and extracts them; app/build.gradle.kts +// reads FFmpeg .so files and the libc++ runtime back out of the extracted +// trees. +val mpvAbis = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64") +val mpvLockFile = rootProject.file("../mpv-build.lock.json") +val mpvLockAndroid = run { + @Suppress("UNCHECKED_CAST") + val lock = groovy.json.JsonSlurper().parse(mpvLockFile) as Map + @Suppress("UNCHECKED_CAST") + ((lock["artifacts"] as? Map)?.get("android") as? Map) + ?: throw GradleException("$mpvLockFile has no artifacts.android section") +} +val mpvKey = mpvLockAndroid["key"] as? String + ?: throw GradleException("$mpvLockFile artifacts.android.key is missing") +val mpvAssetBase = mpvLockAndroid["assetBase"] as? String + ?: throw GradleException("$mpvLockFile artifacts.android.assetBase is missing") +@Suppress("UNCHECKED_CAST") +val mpvAssets = (mpvLockAndroid["assets"] as? Map>).let { assets -> + val missing = mpvAbis.filter { assets?.get(it)?.get("asset").isNullOrEmpty() || assets?.get(it)?.get("checksum").isNullOrEmpty() } + if (assets == null || missing.isNotEmpty()) { + throw GradleException("$mpvLockFile artifacts.android.assets lacks asset+checksum for: ${missing.joinToString()}") + } + assets +} + +val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile +val mpvArchivesDir = File(mpvDir, "archives") +val mpvNativeDir = File(mpvDir, "native") +val mpvLibcxxDir = File(mpvDir, "libcxx") +// Downloaded archives are renamed to a key-independent name so a lock bump +// (new key) changes task inputs, not the output file set. +fun stagedArchiveName(abi: String) = "libmpv-android-$abi.tar.gz" + +// Dev-only escape hatch: point the build at a directory of locally built +// mpv-build android tarballs (platforms/android output, one +// libmpv-android--.tar.gz per ABI) to test changes before a lock +// bump. Checksums are skipped for local archives; the lock stays +// authoritative otherwise. +val localMpvDir: String? = (project.findProperty("plezy.localMpvDir") as String?) + ?: System.getenv("PLEZY_LOCAL_MPV_DIR") + +fun localArchive(abi: String): File { + val dir = File(localMpvDir!!) + val exact = File(dir, mpvAssets.getValue(abi).getValue("asset")) + if (exact.isFile) return exact + val pattern = Regex("libmpv-android-.+-${Regex.escape(abi)}\\.tar\\.gz") + val matches = dir.listFiles()?.filter { it.isFile && pattern.matches(it.name) }.orEmpty() + return matches.singleOrNull() ?: throw GradleException( + "PLEZY_LOCAL_MPV_DIR=$localMpvDir must contain exactly one libmpv-android-*-$abi.tar.gz, found ${matches.size}" + ) +} + +val downloadLibmpv = tasks.register("downloadLibmpv") { + val manifest = File(mpvArchivesDir, ".manifest") + inputs.file(mpvLockFile) + inputs.property("localOverride", localMpvDir ?: "") + if (localMpvDir != null) mpvAbis.forEach { abi -> inputs.file(localArchive(abi)) } + outputs.files(mpvAbis.map { File(mpvArchivesDir, stagedArchiveName(it)) } + manifest) + doLast { + mpvDir.mkdirs() + val staging = File(mpvDir, "archives.staging-${UUID.randomUUID()}") + try { + staging.mkdirs() + val manifestText = StringBuilder() + mpvAbis.forEach { abi -> + val staged = File(staging, stagedArchiveName(abi)) + if (localMpvDir != null) { + val source = localArchive(abi) + source.copyTo(staged, overwrite = true) + manifestText.append("$abi=local:${source.absolutePath}\n") + } else { + val asset = mpvAssets.getValue(abi).getValue("asset") + val checksum = mpvAssets.getValue(abi).getValue("checksum") + try { + providers.exec { + commandLine("curl", "-sfL", "$mpvAssetBase/$asset", "-o", staged.absolutePath) + }.result.get().assertNormalExitValue() + } catch (error: Exception) { + throw GradleException("Failed to download $asset (mpv-build $mpvKey)", error) + } + verifySha256(staged, checksum, "$asset (mpv-build $mpvKey)") + manifestText.append("$abi=$asset sha256=$checksum\n") + } + } + File(staging, ".manifest").writeText(manifestText.toString()) + promoteDirectory(staging, mpvArchivesDir) + } finally { + staging.deleteRecursively() + } + } +} + +// Each tarball is a native tree: lib/*.so (libmpv, seven FFmpeg libraries, +// libc++_shared) + include/mpv/*.h. The .so files land in the per-ABI jniLibs +// layout under native/jni, the headers under native/include for the CMake +// glue build, and libc++ in a separate tree that the app packages at PROJECT +// scope so the tarball's 16 KB-capable runtime deterministically wins the +// merge (see app/build.gradle.kts packaging { jniLibs } + sourceSets). +val extractLibmpvNative = tasks.register("extractLibmpvNative") { + dependsOn(downloadLibmpv) + inputs.files(mpvAbis.map { File(mpvArchivesDir, stagedArchiveName(it)) }) + outputs.dir(mpvNativeDir) + outputs.dir(mpvLibcxxDir) + doLast { + val nativeStaging = File(mpvDir, "native.staging-${UUID.randomUUID()}") + val libcxxStaging = File(mpvDir, "libcxx.staging-${UUID.randomUUID()}") + val unpackRoot = File(mpvDir, "unpack-${UUID.randomUUID()}") + try { + mpvAbis.forEach { abi -> + val unpack = File(unpackRoot, abi).apply { mkdirs() } + providers.exec { + commandLine( + "tar", + "-xzf", + File(mpvArchivesDir, stagedArchiveName(abi)).absolutePath, + "-C", + unpack.absolutePath + ) + }.result.get().assertNormalExitValue() + val jniDir = File(nativeStaging, "jni/$abi") + File(unpack, "lib").listFiles()?.filter { it.isFile && it.name.endsWith(".so") }?.forEach { so -> + val target = if (so.name == "libc++_shared.so") { + File(libcxxStaging, "jni/$abi/${so.name}") + } else { + File(jniDir, so.name) + } + target.parentFile.mkdirs() + Files.move(so.toPath(), target.toPath()) + } + // Headers are identical across ABIs; keep the first archive's copy. + val include = File(unpack, "include") + val includeTarget = File(nativeStaging, "include") + if (!includeTarget.exists() && include.isDirectory) { + include.copyRecursively(includeTarget) + } + } + val missing = buildList { + mpvAbis.forEach { abi -> + if (!File(nativeStaging, "jni/$abi/libmpv.so").isFile) add("native/jni/$abi/libmpv.so") + if (!File(nativeStaging, "jni/$abi/libavcodec.so").isFile) add("native/jni/$abi/libavcodec.so") + if (!File(libcxxStaging, "jni/$abi/libc++_shared.so").isFile) add("libcxx/jni/$abi/libc++_shared.so") + } + if (!File(nativeStaging, "include/mpv/client.h").isFile) add("native/include/mpv/client.h") + } + if (missing.isNotEmpty()) { + throw GradleException( + "mpv-build $mpvKey android archives are missing expected entries: ${missing.joinToString()}" + ) + } + promoteDirectory(nativeStaging, mpvNativeDir) + promoteDirectory(libcxxStaging, mpvLibcxxDir) + } finally { + nativeStaging.deleteRecursively() + libcxxStaging.deleteRecursively() + unpackRoot.deleteRecursively() + } + } +} + +android { + namespace = "com.edde746.plezy.libmpv" + compileSdk = 36 + // Matches the app's latest stable NDK so every project-owned native library + // is built with the same 16 KB page-size-capable libc++ toolchain. That copy + // is NOT what ships: the app packages the mpv-build tarball's newer copy with + // top merge priority (see app/build.gradle.kts packaging { jniLibs } + sourceSets). + ndkVersion = "29.0.14206865" + + defaultConfig { + // Fire OS 6.x (API 25), same floor as the app. The fork declared 26, but + // nothing in this API or glue uses anything above 25. + minSdk = 25 + consumerProguardFiles("consumer-rules.pro") + externalNativeBuild { + cmake { + arguments += listOf( + "-DANDROID_STL=c++_shared", + "-DMPV_PREBUILT_ROOT=${mpvNativeDir.absolutePath}" + ) + cFlags += "-Werror" + cppFlags += "-std=c++11" + } + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + externalNativeBuild { + cmake { + path = file("src/main/cpp/CMakeLists.txt") + version = "4.1.2" + } + } + + sourceSets { + getByName("main") { + // Prebuilt libmpv + FFmpeg .so files extracted from the mpv-build tarballs; + // the glue libplayer.so comes from the CMake build above. + jniLibs.srcDir(File(mpvNativeDir, "jni")) + } + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +// The imported libmpv.so/libavcodec.so must exist before CMake links the glue. +tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach { + dependsOn(extractLibmpvNative) +} +// Gradle snapshots jniLibs source dirs before task execution; this keeps the +// extracted prebuilt directory present during input discovery. +tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach { + dependsOn(extractLibmpvNative) +} +tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach { + dependsOn(extractLibmpvNative) +} + +dependencies { + // Same version the app pins; MpvPlayer's public flows compile against it. + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0") +} diff --git a/android/libmpv/consumer-rules.pro b/android/libmpv/consumer-rules.pro new file mode 100644 index 000000000..34b7190a5 --- /dev/null +++ b/android/libmpv/consumer-rules.pro @@ -0,0 +1,14 @@ +# JNI exports bind by name (Java_com_edde746_plezy_libmpv_MpvPlayer_native*); keep the names stable. +-keepclasseswithmembernames class com.edde746.plezy.libmpv.* { + native ; +} + +# jni_utils.cpp caches MpvPlayer with FindClass and resolves these static callbacks +# with GetStaticMethodID on the native event thread. R8 sees no reference to the +# class name or the member names, so both must stay alive and un-renamed. +-keep class com.edde746.plezy.libmpv.MpvPlayer { + public static void onPropertyChanged(...); + public static void onEvent(int); + public static void onEndFile(int); + public static void onLogMessage(java.lang.String, int, java.lang.String); +} diff --git a/android/libmpv/src/main/AndroidManifest.xml b/android/libmpv/src/main/AndroidManifest.xml new file mode 100644 index 000000000..8bdb7e14b --- /dev/null +++ b/android/libmpv/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android/libmpv/src/main/cpp/CMakeLists.txt b/android/libmpv/src/main/cpp/CMakeLists.txt new file mode 100644 index 000000000..1b0325a58 --- /dev/null +++ b/android/libmpv/src/main/cpp/CMakeLists.txt @@ -0,0 +1,45 @@ +cmake_minimum_required(VERSION 3.22.1) + +project("libmpv") + +# The JNI glue this module compiles; MpvPlayer loads it with +# System.loadLibrary("player") after libmpv.so itself. +add_library( + player + SHARED + main.cpp render.cpp log.cpp jni_utils.cpp property.cpp event.cpp +) + +# Prebuilt libraries extracted from the pinned mpv-build per-ABI tarballs by the +# extractLibmpvNative Gradle task; MPV_PREBUILT_ROOT points at its output. +add_library( + mpv + SHARED + IMPORTED +) + +set_target_properties( + mpv + PROPERTIES IMPORTED_LOCATION + ${MPV_PREBUILT_ROOT}/jni/${ANDROID_ABI}/libmpv.so +) + +# av_jni_set_java_vm / av_jni_set_android_app_ctx (main.cpp) live in FFmpeg's +# libavcodec, which the same tarballs package. +add_library( + avcodec + SHARED + IMPORTED +) + +set_target_properties( + avcodec + PROPERTIES IMPORTED_LOCATION + ${MPV_PREBUILT_ROOT}/jni/${ANDROID_ABI}/libavcodec.so +) + +# mpv public headers ride in the extracted tarballs next to libmpv.so; the +# vendored tree only carries FFmpeg's libavcodec/jni.h (see include/README.md). +include_directories( ${MPV_PREBUILT_ROOT}/include ${CMAKE_CURRENT_SOURCE_DIR}/include ) + +target_link_libraries( player mpv avcodec log ) diff --git a/android/libmpv/src/main/cpp/event.cpp b/android/libmpv/src/main/cpp/event.cpp new file mode 100644 index 000000000..479f2e413 --- /dev/null +++ b/android/libmpv/src/main/cpp/event.cpp @@ -0,0 +1,101 @@ +#include +#include + +#include "globals.h" +#include "jni_utils.h" +#include "log.h" + +static void sendPropertyUpdateToJava(JNIEnv* env, mpv_event_property* prop) { + jstring jprop = env->NewStringUTF(prop->name); + jstring jvalue = NULL; + switch (prop->format) { + case MPV_FORMAT_NONE: + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onPropertyChanged_S, jprop); + break; + case MPV_FORMAT_FLAG: + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onPropertyChanged_Sb, jprop, *(int*)prop->data); + break; + case MPV_FORMAT_INT64: + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onPropertyChanged_Sl, jprop, *(int64_t*)prop->data); + break; + case MPV_FORMAT_DOUBLE: + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onPropertyChanged_Sd, jprop, *(double*)prop->data); + break; + case MPV_FORMAT_STRING: + jvalue = env->NewStringUTF(*(const char**)prop->data); + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onPropertyChanged_SS, jprop, jvalue); + break; + default: + break; + } + if (jprop) env->DeleteLocalRef(jprop); + if (jvalue) env->DeleteLocalRef(jvalue); +} + +static void sendEventToJava(JNIEnv* env, int event) { + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onEvent, event); +} + +static void sendEndFileToJava(JNIEnv* env, mpv_event* event) { + mpv_event_end_file* end_file = (mpv_event_end_file*)event->data; + int reason = end_file ? end_file->reason : -1; + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onEndFile, (jint)reason); +} + +static inline bool invalid_utf8(unsigned char c) { return c == 0xc0 || c == 0xc1 || c >= 0xf5; } + +static void sendLogMessageToJava(JNIEnv* env, mpv_event_log_message* msg) { + const auto invalid_utf8 = [](unsigned char c) { return c == 0xc0 || c == 0xc1 || c >= 0xf5; }; + for (int i = 0; msg->text[i]; i++) { + if (invalid_utf8(static_cast(msg->text[i]))) return; + } + + jstring jprefix = env->NewStringUTF(msg->prefix); + jstring jtext = env->NewStringUTF(msg->text); + + env->CallStaticVoidMethod(mpv_MpvPlayer, mpv_MpvPlayer_onLogMessage, jprefix, (jint)msg->log_level, jtext); + + if (jprefix) env->DeleteLocalRef(jprefix); + if (jtext) env->DeleteLocalRef(jtext); +} + +void* event_thread(void* arg) { + JNIEnv* env = NULL; + acquire_jni_env(g_vm, &env); + if (!env) die("failed to acquire java env"); + + while (true) { + mpv_event* mp_event; + mpv_event_property* mp_property; + mpv_event_log_message* msg; + + mp_event = mpv_wait_event(g_mpv, -1.0); + + if (g_event_thread_request_exit) break; + + if (mp_event->event_id == MPV_EVENT_NONE) continue; + + switch (mp_event->event_id) { + case MPV_EVENT_LOG_MESSAGE: + msg = (mpv_event_log_message*)mp_event->data; + ALOGV("[%s:%s] %s", msg->prefix, msg->level, msg->text); + sendLogMessageToJava(env, msg); + break; + case MPV_EVENT_PROPERTY_CHANGE: + mp_property = (mpv_event_property*)mp_event->data; + sendPropertyUpdateToJava(env, mp_property); + break; + case MPV_EVENT_END_FILE: + sendEndFileToJava(env, mp_event); + break; + default: + ALOGV("event: %s\n", mpv_event_name(mp_event->event_id)); + sendEventToJava(env, mp_event->event_id); + break; + } + } + + g_vm->DetachCurrentThread(); + + return NULL; +} diff --git a/android/libmpv/src/main/cpp/event.h b/android/libmpv/src/main/cpp/event.h new file mode 100644 index 000000000..d9699006c --- /dev/null +++ b/android/libmpv/src/main/cpp/event.h @@ -0,0 +1,3 @@ +#pragma once + +void* event_thread(void* arg); diff --git a/android/libmpv/src/main/cpp/globals.h b/android/libmpv/src/main/cpp/globals.h new file mode 100644 index 000000000..483573d67 --- /dev/null +++ b/android/libmpv/src/main/cpp/globals.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include + +#include + +extern JavaVM* g_vm; +extern mpv_handle* g_mpv; +extern std::atomic g_event_thread_request_exit; diff --git a/android/libmpv/src/main/cpp/include/README.md b/android/libmpv/src/main/cpp/include/README.md new file mode 100644 index 000000000..6449c9496 --- /dev/null +++ b/android/libmpv/src/main/cpp/include/README.md @@ -0,0 +1,15 @@ +# Vendored native headers + +Build-time headers for the JNI glue in this module; nothing here ships in the APK. +Each file carries its own upstream license text — none is modified. + +- `libavcodec/jni.h` — FFmpeg n8.0.1 (https://github.com/FFmpeg/FFmpeg, tag `n8.0.1`, + commit `894da5ca7d742e4429ffb2af534fcda0103ef593`), copied unmodified. Declares + `av_jni_set_java_vm` / `av_jni_set_android_app_ctx`, which `main.cpp` calls into the + `libavcodec.so` packaged by the pinned mpv-build tarballs (FFmpeg 8.0.1 — the + version `app/build.gradle.kts` also pins for the Media3 adapter headers). + +The mpv public headers (`mpv/client.h`, `mpv/render.h`, `mpv/render_gl.h`, +`mpv/stream_cb.h`) are no longer vendored: each mpv-build per-ABI tarball carries +`include/mpv/*.h` matching its `libmpv.so`, and `extractLibmpvNative` places them +under `native/include`, which CMake reads via `MPV_PREBUILT_ROOT`. diff --git a/android/libmpv/src/main/cpp/include/libavcodec/jni.h b/android/libmpv/src/main/cpp/include/libavcodec/jni.h new file mode 100644 index 000000000..955cd2809 --- /dev/null +++ b/android/libmpv/src/main/cpp/include/libavcodec/jni.h @@ -0,0 +1,67 @@ +/* + * JNI public API functions + * + * Copyright (c) 2015-2016 Matthieu Bouron + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AVCODEC_JNI_H +#define AVCODEC_JNI_H + +/* + * Manually set a Java virtual machine which will be used to retrieve the JNI + * environment. Once a Java VM is set it cannot be changed afterwards, meaning + * you can call multiple times av_jni_set_java_vm with the same Java VM pointer + * however it will error out if you try to set a different Java VM. + * + * @param vm Java virtual machine + * @param log_ctx context used for logging, can be NULL + * @return 0 on success, < 0 otherwise + */ +int av_jni_set_java_vm(void *vm, void *log_ctx); + +/* + * Get the Java virtual machine which has been set with av_jni_set_java_vm. + * + * @param vm Java virtual machine + * @return a pointer to the Java virtual machine + */ +void *av_jni_get_java_vm(void *log_ctx); + +/* + * Set the Android application context which will be used to retrieve the Android + * content resolver to handle content uris. + * + * This function is only available on Android. + * + * @param app_ctx global JNI reference to the Android application context + * @return 0 on success, < 0 otherwise + */ +int av_jni_set_android_app_ctx(void *app_ctx, void *log_ctx); + +/* + * Get the Android application context that has been set with + * av_jni_set_android_app_ctx. + * + * This function is only available on Android. + * + * @return a pointer the the Android application context + */ +void *av_jni_get_android_app_ctx(void); + +#endif /* AVCODEC_JNI_H */ diff --git a/android/libmpv/src/main/cpp/include/mpv/client.h b/android/libmpv/src/main/cpp/include/mpv/client.h new file mode 100644 index 000000000..85cff63bd --- /dev/null +++ b/android/libmpv/src/main/cpp/include/mpv/client.h @@ -0,0 +1,2032 @@ +/* Copyright (C) 2017 the mpv developers + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Note: the client API is licensed under ISC (see above) to enable + * other wrappers outside of mpv. But keep in mind that the + * mpv core is by default still GPLv2+ - unless built with + * -Dgpl=false, which makes it LGPLv2+. + */ + +#ifndef MPV_CLIENT_API_H_ +#define MPV_CLIENT_API_H_ + +#include +#include + +#ifdef _WIN32 +#define MPV_EXPORT __declspec(dllexport) +#define MPV_SELECTANY __declspec(selectany) +#elif defined(__GNUC__) || defined(__clang__) +#define MPV_EXPORT __attribute__((visibility("default"))) +#define MPV_SELECTANY +#else +#define MPV_EXPORT +#define MPV_SELECTANY +#endif + +#ifdef __cpp_decltype +#define MPV_DECLTYPE decltype +#else +#define MPV_DECLTYPE __typeof__ +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Mechanisms provided by this API + * ------------------------------- + * + * This API provides general control over mpv playback. It does not give you + * direct access to individual components of the player, only the whole thing. + * It's somewhat equivalent to MPlayer's slave mode. You can send commands, + * retrieve or set playback status or settings with properties, and receive + * events. + * + * The API can be used in two ways: + * 1) Internally in mpv, to provide additional features to the command line + * player. Lua scripting uses this. (Currently there is no plugin API to + * get a client API handle in external user code. It has to be a fixed + * part of the player at compilation time.) + * 2) Using mpv as a library with mpv_create(). This basically allows embedding + * mpv in other applications. + * + * Documentation + * ------------- + * + * The libmpv C API is documented directly in this header. Note that most + * actual interaction with this player is done through + * options/commands/properties, which can be accessed through this API. + * Essentially everything is done with them, including loading a file, + * retrieving playback progress, and so on. + * + * These are documented elsewhere: + * * http://mpv.io/manual/master/#options + * * http://mpv.io/manual/master/#list-of-input-commands + * * http://mpv.io/manual/master/#properties + * + * You can also look at the examples here: + * * https://github.com/mpv-player/mpv-examples/tree/master/libmpv + * + * Event loop + * ---------- + * + * In general, the API user should run an event loop in order to receive events. + * This event loop should call mpv_wait_event(), which will return once a new + * mpv client API is available. It is also possible to integrate client API + * usage in other event loops (e.g. GUI toolkits) with the + * mpv_set_wakeup_callback() function, and then polling for events by calling + * mpv_wait_event() with a 0 timeout. + * + * Note that the event loop is detached from the actual player. Not calling + * mpv_wait_event() will not stop playback. It will eventually congest the + * event queue of your API handle, though. + * + * Synchronous vs. asynchronous calls + * ---------------------------------- + * + * The API allows both synchronous and asynchronous calls. Synchronous calls + * have to wait until the playback core is ready, which currently can take + * an unbounded time (e.g. if network is slow or unresponsive). Asynchronous + * calls just queue operations as requests, and return the result of the + * operation as events. + * + * Asynchronous calls + * ------------------ + * + * The client API includes asynchronous functions. These allow you to send + * requests instantly, and get replies as events at a later point. The + * requests are made with functions carrying the _async suffix, and replies + * are returned by mpv_wait_event() (interleaved with the normal event stream). + * + * A 64 bit userdata value is used to allow the user to associate requests + * with replies. The value is passed as reply_userdata parameter to the request + * function. The reply to the request will have the reply + * mpv_event->reply_userdata field set to the same value as the + * reply_userdata parameter of the corresponding request. + * + * This userdata value is arbitrary and is never interpreted by the API. Note + * that the userdata value 0 is also allowed, but then the client must be + * careful not accidentally interpret the mpv_event->reply_userdata if an + * event is not a reply. (For non-replies, this field is set to 0.) + * + * Asynchronous calls may be reordered in arbitrarily with other synchronous + * and asynchronous calls. If you want a guaranteed order, you need to wait + * until asynchronous calls report completion before doing the next call. + * + * See also the section "Asynchronous command details" in the manpage. + * + * Multithreading + * -------------- + * + * The client API is generally fully thread-safe, unless otherwise noted. + * Currently, there is no real advantage in using more than 1 thread to access + * the client API, since everything is serialized through a single lock in the + * playback core. + * + * Basic environment requirements + * ------------------------------ + * + * This documents basic requirements on the C environment. This is especially + * important if mpv is used as library with mpv_create(). + * + * - The LC_NUMERIC locale category must be set to "C". If your program calls + * setlocale(), be sure not to use LC_ALL, or if you do, reset LC_NUMERIC + * to its sane default: setlocale(LC_NUMERIC, "C"). + * - If a X11 based VO is used, mpv will set the xlib error handler. This error + * handler is process-wide, and there's no proper way to share it with other + * xlib users within the same process. This might confuse GUI toolkits. + * - mpv uses some other libraries that are not library-safe, such as Fribidi + * (used through libass), ALSA, FFmpeg, and possibly more. + * - The FPU precision must be set at least to double precision. + * - On Windows, mpv will call timeBeginPeriod(1). + * - On memory exhaustion, mpv will kill the process. + * - In certain cases, mpv may start sub processes (such as with the ytdl + * wrapper script). + * - Using UNIX IPC (off by default) will override the SIGPIPE signal handler, + * and set it to SIG_IGN. Some invocations of the "subprocess" command will + * also do that. + * - mpv may start sub processes, so overriding SIGCHLD, or waiting on all PIDs + * (such as calling wait()) by the parent process or any other library within + * the process must be avoided. libmpv itself only waits for its own PIDs. + * - If anything in the process registers signal handlers, they must set the + * SA_RESTART flag. Otherwise you WILL get random failures on signals. + * + * Encoding of filenames + * --------------------- + * + * mpv uses UTF-8 everywhere. + * + * On some platforms (like Linux), filenames actually do not have to be UTF-8; + * for this reason libmpv supports non-UTF-8 strings. libmpv uses what the + * kernel uses and does not recode filenames. At least on Linux, passing a + * string to libmpv is like passing a string to the fopen() function. + * + * On Windows, filenames are always UTF-8, libmpv converts between UTF-8 and + * UTF-16 when using win32 API functions. libmpv never uses or accepts + * filenames in the local 8 bit encoding. It does not use fopen() either; + * it uses _wfopen(). + * + * On macOS, filenames and other strings taken/returned by libmpv can have + * inconsistent unicode normalization. This can sometimes lead to problems. + * You have to hope for the best. + * + * Also see the remarks for MPV_FORMAT_STRING. + * + * Embedding the video window + * -------------------------- + * + * Using the render API (in render.h) is recommended. This API requires + * you to create and maintain an OpenGL context, to which you can render + * video using a specific API call. This API does not include keyboard or mouse + * input directly. + * + * There is an older way to embed the native mpv window into your own. You have + * to get the raw window handle, and set it as "wid" option. This works on X11, + * win32, and macOS only. It's much easier to use than the render API, but + * also has various problems. + * + * Also see client API examples and the mpv manpage. There is an extensive + * discussion here: + * https://github.com/mpv-player/mpv-examples/tree/master/libmpv#methods-of-embedding-the-video-window + * + * Compatibility + * ------------- + * + * mpv development doesn't stand still, and changes to mpv internals as well as + * to its interface can cause compatibility issues to client API users. + * + * The API is versioned (see MPV_CLIENT_API_VERSION), and changes to it are + * documented in DOCS/client-api-changes.rst. The C API itself will probably + * remain compatible for a long time, but the functionality exposed by it + * could change more rapidly. For example, it's possible that options are + * renamed, or change the set of allowed values. + * + * Defensive programming should be used to potentially deal with the fact that + * options, commands, and properties could disappear, change their value range, + * or change the underlying datatypes. It might be a good idea to prefer + * MPV_FORMAT_STRING over other types to decouple your code from potential + * mpv changes. + * + * Also see: DOCS/compatibility.rst + * + * Future changes + * -------------- + * + * This are the planned changes that will most likely be done on the next major + * bump of the library: + * + * - remove all symbols that are marked as deprecated + * - reassign enum numerical values to remove gaps + * - disabling all events by default + */ + +/** + * The version is incremented on each API change. The 16 lower bits form the + * minor version number, and the 16 higher bits the major version number. If + * the API becomes incompatible to previous versions, the major version + * number is incremented. This affects only C part, and not properties and + * options. + * + * Every API bump is described in DOCS/client-api-changes.rst + * + * You can use MPV_MAKE_VERSION() and compare the result with integer + * relational operators (<, >, <=, >=). + */ +#define MPV_MAKE_VERSION(major, minor) (((major) << 16) | (minor) | 0UL) +#define MPV_CLIENT_API_VERSION MPV_MAKE_VERSION(2, 5) + +/** + * The API user is allowed to "#define MPV_ENABLE_DEPRECATED 0" before + * including any libmpv headers. Then deprecated symbols will be excluded + * from the headers. (Of course, deprecated properties and commands and + * other functionality will still work.) + */ +#ifndef MPV_ENABLE_DEPRECATED +#define MPV_ENABLE_DEPRECATED 1 +#endif + +/** + * Return the MPV_CLIENT_API_VERSION the mpv source has been compiled with. + */ +MPV_EXPORT unsigned long mpv_client_api_version(void); + +/** + * Client context used by the client API. Every client has its own private + * handle. + */ +typedef struct mpv_handle mpv_handle; + +/** + * List of error codes than can be returned by API functions. 0 and positive + * return values always mean success, negative values are always errors. + */ +typedef enum mpv_error { + /** + * No error happened (used to signal successful operation). + * Keep in mind that many API functions returning error codes can also + * return positive values, which also indicate success. API users can + * hardcode the fact that ">= 0" means success. + */ + MPV_ERROR_SUCCESS = 0, + /** + * The event ringbuffer is full. This means the client is choked, and can't + * receive any events. This can happen when too many asynchronous requests + * have been made, but not answered. Probably never happens in practice, + * unless the mpv core is frozen for some reason, and the client keeps + * making asynchronous requests. (Bugs in the client API implementation + * could also trigger this, e.g. if events become "lost".) + */ + MPV_ERROR_EVENT_QUEUE_FULL = -1, + /** + * Memory allocation failed. + */ + MPV_ERROR_NOMEM = -2, + /** + * The mpv core wasn't configured and initialized yet. See the notes in + * mpv_create(). + */ + MPV_ERROR_UNINITIALIZED = -3, + /** + * Generic catch-all error if a parameter is set to an invalid or + * unsupported value. This is used if there is no better error code. + */ + MPV_ERROR_INVALID_PARAMETER = -4, + /** + * Trying to set an option that doesn't exist. + */ + MPV_ERROR_OPTION_NOT_FOUND = -5, + /** + * Trying to set an option using an unsupported MPV_FORMAT. + */ + MPV_ERROR_OPTION_FORMAT = -6, + /** + * Setting the option failed. Typically this happens if the provided option + * value could not be parsed. + */ + MPV_ERROR_OPTION_ERROR = -7, + /** + * The accessed property doesn't exist. + */ + MPV_ERROR_PROPERTY_NOT_FOUND = -8, + /** + * Trying to set or get a property using an unsupported MPV_FORMAT. + */ + MPV_ERROR_PROPERTY_FORMAT = -9, + /** + * The property exists, but is not available. This usually happens when the + * associated subsystem is not active, e.g. querying audio parameters while + * audio is disabled. + */ + MPV_ERROR_PROPERTY_UNAVAILABLE = -10, + /** + * Error setting or getting a property. + */ + MPV_ERROR_PROPERTY_ERROR = -11, + /** + * General error when running a command with mpv_command and similar. + */ + MPV_ERROR_COMMAND = -12, + /** + * Generic error on loading (usually used with mpv_event_end_file.error). + */ + MPV_ERROR_LOADING_FAILED = -13, + /** + * Initializing the audio output failed. + */ + MPV_ERROR_AO_INIT_FAILED = -14, + /** + * Initializing the video output failed. + */ + MPV_ERROR_VO_INIT_FAILED = -15, + /** + * There was no audio or video data to play. This also happens if the + * file was recognized, but did not contain any audio or video streams, + * or no streams were selected. + */ + MPV_ERROR_NOTHING_TO_PLAY = -16, + /** + * When trying to load the file, the file format could not be determined, + * or the file was too broken to open it. + */ + MPV_ERROR_UNKNOWN_FORMAT = -17, + /** + * Generic error for signaling that certain system requirements are not + * fulfilled. + */ + MPV_ERROR_UNSUPPORTED = -18, + /** + * The API function which was called is a stub only. + */ + MPV_ERROR_NOT_IMPLEMENTED = -19, + /** + * Unspecified error. + */ + MPV_ERROR_GENERIC = -20 +} mpv_error; + +/** + * Return a string describing the error. For unknown errors, the string + * "unknown error" is returned. + * + * @param error error number, see enum mpv_error + * @return A static string describing the error. The string is completely + * static, i.e. doesn't need to be deallocated, and is valid forever. + */ +MPV_EXPORT const char *mpv_error_string(int error); + +/** + * General function to deallocate memory returned by some of the API functions. + * Call this only if it's explicitly documented as allowed. Calling this on + * mpv memory not owned by the caller will lead to undefined behavior. + * + * @param data A valid pointer returned by the API, or NULL. + */ +MPV_EXPORT void mpv_free(void *data); + +/** + * Return the name of this client handle. Every client has its own unique + * name, which is mostly used for user interface purposes. + * + * @return The client name. The string is read-only and is valid until the + * mpv_handle is destroyed. + */ +MPV_EXPORT const char *mpv_client_name(mpv_handle *ctx); + +/** + * Return the ID of this client handle. Every client has its own unique ID. This + * ID is never reused by the core, even if the mpv_handle at hand gets destroyed + * and new handles get allocated. + * + * IDs are never 0 or negative. + * + * Some mpv APIs (not necessarily all) accept a name in the form "@" in + * addition of the proper mpv_client_name(), where "" is the ID in decimal + * form (e.g. "@123"). For example, the "script-message-to" command takes the + * client name as first argument, but also accepts the client ID formatted in + * this manner. + * + * @return The client ID. + */ +MPV_EXPORT int64_t mpv_client_id(mpv_handle *ctx); + +/** + * Create a new mpv instance and an associated client API handle to control + * the mpv instance. This instance is in a pre-initialized state, + * and needs to be initialized to be actually used with most other API + * functions. + * + * Some API functions will return MPV_ERROR_UNINITIALIZED in the uninitialized + * state. You can call mpv_set_property() (or mpv_set_property_string() and + * other variants, and before mpv 0.21.0 mpv_set_option() etc.) to set initial + * options. After this, call mpv_initialize() to start the player, and then use + * e.g. mpv_command() to start playback of a file. + * + * The point of separating handle creation and actual initialization is that + * you can configure things which can't be changed during runtime. + * + * Unlike the command line player, this will have initial settings suitable + * for embedding in applications. The following settings are different: + * - stdin/stdout/stderr and the terminal will never be accessed. This is + * equivalent to setting the --no-terminal option. + * (Technically, this also suppresses C signal handling.) + * - No config files will be loaded. This is roughly equivalent to using + * --config=no. Since libmpv 1.15, you can actually re-enable this option, + * which will make libmpv load config files during mpv_initialize(). If you + * do this, you are strongly encouraged to set the "config-dir" option too. + * (Otherwise it will load the mpv command line player's config.) + * For example: + * mpv_set_option_string(mpv, "config-dir", "/my/path"); // set config root + * mpv_set_option_string(mpv, "config", "yes"); // enable config loading + * (call mpv_initialize() _after_ this) + * - Idle mode is enabled, which means the playback core will enter idle mode + * if there are no more files to play on the internal playlist, instead of + * exiting. This is equivalent to the --idle option. + * - Disable parts of input handling. + * - Most of the different settings can be viewed with the command line player + * by running "mpv --show-profile=libmpv". + * + * All this assumes that API users want a mpv instance that is strictly + * isolated from the command line player's configuration, user settings, and + * so on. You can re-enable disabled features by setting the appropriate + * options. + * + * The mpv command line parser is not available through this API, but you can + * set individual options with mpv_set_property(). Files for playback must be + * loaded with mpv_command() or others. + * + * Note that you should avoid doing concurrent accesses on the uninitialized + * client handle. (Whether concurrent access is definitely allowed or not has + * yet to be decided.) + * + * @return a new mpv client API handle. Returns NULL on error. Currently, this + * can happen in the following situations: + * - out of memory + * - LC_NUMERIC is not set to "C" (see general remarks) + */ +MPV_EXPORT mpv_handle *mpv_create(void); + +/** + * Initialize an uninitialized mpv instance. If the mpv instance is already + * running, an error is returned. + * + * This function needs to be called to make full use of the client API if the + * client API handle was created with mpv_create(). + * + * Only the following options are required to be set _before_ mpv_initialize(): + * - options which are only read at initialization time: + * - config + * - config-dir + * - input-conf + * - load-scripts + * - script + * - player-operation-mode + * - input-app-events (macOS) + * - all encoding mode options + * + * @return error code + */ +MPV_EXPORT int mpv_initialize(mpv_handle *ctx); + +/** + * Disconnect and destroy the mpv_handle. ctx will be deallocated with this + * API call. + * + * If the last mpv_handle is detached, the core player is destroyed. In + * addition, if there are only weak mpv_handles (such as created by + * mpv_create_weak_client() or internal scripts), these mpv_handles will + * be sent MPV_EVENT_SHUTDOWN. This function may block until these clients + * have responded to the shutdown event, and the core is finally destroyed. + */ +MPV_EXPORT void mpv_destroy(mpv_handle *ctx); + +/** + * Similar to mpv_destroy(), but brings the player and all clients down + * as well, and waits until all of them are destroyed. This function blocks. The + * advantage over mpv_destroy() is that while mpv_destroy() merely + * detaches the client handle from the player, this function quits the player, + * waits until all other clients are destroyed (i.e. all mpv_handles are + * detached), and also waits for the final termination of the player. + * + * Since mpv_destroy() is called somewhere on the way, it's not safe to + * call other functions concurrently on the same context. + * + * Since mpv client API version 1.29: + * The first call on any mpv_handle will block until the core is destroyed. + * This means it will wait until other mpv_handle have been destroyed. If you + * want asynchronous destruction, just run the "quit" command, and then react + * to the MPV_EVENT_SHUTDOWN event. + * If another mpv_handle already called mpv_terminate_destroy(), this call will + * not actually block. It will destroy the mpv_handle, and exit immediately, + * while other mpv_handles might still be uninitializing. + * + * Before mpv client API version 1.29: + * If this is called on a mpv_handle that was not created with mpv_create(), + * this function will merely send a quit command and then call + * mpv_destroy(), without waiting for the actual shutdown. + */ +MPV_EXPORT void mpv_terminate_destroy(mpv_handle *ctx); + +/** + * Create a new client handle connected to the same player core as ctx. This + * context has its own event queue, its own mpv_request_event() state, its own + * mpv_request_log_messages() state, its own set of observed properties, and + * its own state for asynchronous operations. Otherwise, everything is shared. + * + * This handle should be destroyed with mpv_destroy() if no longer + * needed. The core will live as long as there is at least 1 handle referencing + * it. Any handle can make the core quit, which will result in every handle + * receiving MPV_EVENT_SHUTDOWN. + * + * This function can not be called before the main handle was initialized with + * mpv_initialize(). The new handle is always initialized, unless ctx=NULL was + * passed. + * + * @param ctx Used to get the reference to the mpv core; handle-specific + * settings and parameters are not used. + * If NULL, this function behaves like mpv_create() (ignores name). + * @param name The client name. This will be returned by mpv_client_name(). If + * the name is already in use, or contains non-alphanumeric + * characters (other than '_'), the name is modified to fit. + * If NULL, an arbitrary name is automatically chosen. + * @return a new handle, or NULL on error + */ +MPV_EXPORT mpv_handle *mpv_create_client(mpv_handle *ctx, const char *name); + +/** + * This is the same as mpv_create_client(), but the created mpv_handle is + * treated as a weak reference. If all mpv_handles referencing a core are + * weak references, the core is automatically destroyed. (This still goes + * through normal uninit of course. Effectively, if the last non-weak mpv_handle + * is destroyed, then the weak mpv_handles receive MPV_EVENT_SHUTDOWN and are + * asked to terminate as well.) + * + * Note if you want to use this like refcounting: you have to be aware that + * mpv_terminate_destroy() _and_ mpv_destroy() for the last non-weak + * mpv_handle will block until all weak mpv_handles are destroyed. + */ +MPV_EXPORT mpv_handle *mpv_create_weak_client(mpv_handle *ctx, const char *name); + +/** + * Load a config file. This loads and parses the file, and sets every entry in + * the config file's default section as if mpv_set_option_string() is called. + * + * The filename should be an absolute path. If it isn't, the actual path used + * is unspecified. (Note: an absolute path starts with '/' on UNIX.) If the + * file wasn't found, MPV_ERROR_INVALID_PARAMETER is returned. + * + * If a fatal error happens when parsing a config file, MPV_ERROR_OPTION_ERROR + * is returned. Errors when setting options as well as other types or errors + * are ignored (even if options do not exist). You can still try to capture + * the resulting error messages with mpv_request_log_messages(). Note that it's + * possible that some options were successfully set even if any of these errors + * happen. + * + * @param filename absolute path to the config file on the local filesystem + * @return error code + */ +MPV_EXPORT int mpv_load_config_file(mpv_handle *ctx, const char *filename); + +/** + * Return the internal time in nanoseconds. This has an arbitrary start offset, + * but will never wrap or go backwards. + * + * Note that this is always the real time, and doesn't necessarily have to do + * with playback time. For example, playback could go faster or slower due to + * playback speed, or due to playback being paused. Use the "time-pos" property + * instead to get the playback status. + * + * Unlike other libmpv APIs, this can be called at absolutely any time (even + * within wakeup callbacks), as long as the context is valid. + * + * Safe to be called from mpv render API threads. + */ +MPV_EXPORT int64_t mpv_get_time_ns(mpv_handle *ctx); + +/** + * Same as mpv_get_time_ns but in microseconds. + */ +MPV_EXPORT int64_t mpv_get_time_us(mpv_handle *ctx); + +/** + * Data format for options and properties. The API functions to get/set + * properties and options support multiple formats, and this enum describes + * them. + */ +typedef enum mpv_format { + /** + * Invalid. Sometimes used for empty values. This is always defined to 0, + * so a normal 0-init of mpv_format (or e.g. mpv_node) is guaranteed to set + * this it to MPV_FORMAT_NONE (which makes some things saner as consequence). + */ + MPV_FORMAT_NONE = 0, + /** + * The basic type is char*. It returns the raw property string, like + * using ${=property} in input.conf (see input.rst). + * + * NULL isn't an allowed value. + * + * Warning: although the encoding is usually UTF-8, this is not always the + * case. File tags often store strings in some legacy codepage, + * and even filenames don't necessarily have to be in UTF-8 (at + * least on Linux). If you pass the strings to code that requires + * valid UTF-8, you have to sanitize it in some way. + * On Windows, filenames are always UTF-8, and libmpv converts + * between UTF-8 and UTF-16 when using win32 API functions. See + * the "Encoding of filenames" section for details. + * + * Example for reading: + * + * char *result = NULL; + * if (mpv_get_property(ctx, "property", MPV_FORMAT_STRING, &result) < 0) + * goto error; + * printf("%s\n", result); + * mpv_free(result); + * + * Or just use mpv_get_property_string(). + * + * Example for writing: + * + * char *value = "the new value"; + * // yep, you pass the address to the variable + * // (needed for symmetry with other types and mpv_get_property) + * mpv_set_property(ctx, "property", MPV_FORMAT_STRING, &value); + * + * Or just use mpv_set_property_string(). + * + */ + MPV_FORMAT_STRING = 1, + /** + * The basic type is char*. It returns the OSD property string, like + * using ${property} in input.conf (see input.rst). In many cases, this + * is the same as the raw string, but in other cases it's formatted for + * display on OSD. It's intended to be human readable. Do not attempt to + * parse these strings. + * + * Only valid when doing read access. The rest works like MPV_FORMAT_STRING. + */ + MPV_FORMAT_OSD_STRING = 2, + /** + * The basic type is int. The only allowed values are 0 ("no") + * and 1 ("yes"). + * + * Example for reading: + * + * int result; + * if (mpv_get_property(ctx, "property", MPV_FORMAT_FLAG, &result) < 0) + * goto error; + * printf("%s\n", result ? "true" : "false"); + * + * Example for writing: + * + * int flag = 1; + * mpv_set_property(ctx, "property", MPV_FORMAT_FLAG, &flag); + */ + MPV_FORMAT_FLAG = 3, + /** + * The basic type is int64_t. + */ + MPV_FORMAT_INT64 = 4, + /** + * The basic type is double. + */ + MPV_FORMAT_DOUBLE = 5, + /** + * The type is mpv_node. + * + * For reading, you usually would pass a pointer to a stack-allocated + * mpv_node value to mpv, and when you're done you call + * mpv_free_node_contents(&node). + * You're expected not to write to the data - if you have to, copy it + * first (which you have to do manually). + * + * For writing, you construct your own mpv_node, and pass a pointer to the + * API. The API will never write to your data (and copy it if needed), so + * you're free to use any form of allocation or memory management you like. + * + * Warning: when reading, always check the mpv_node.format member. For + * example, properties might change their type in future versions + * of mpv, or sometimes even during runtime. + * + * Example for reading: + * + * mpv_node result; + * if (mpv_get_property(ctx, "property", MPV_FORMAT_NODE, &result) < 0) + * goto error; + * printf("format=%d\n", (int)result.format); + * mpv_free_node_contents(&result). + * + * Example for writing: + * + * mpv_node value; + * value.format = MPV_FORMAT_STRING; + * value.u.string = "hello"; + * mpv_set_property(ctx, "property", MPV_FORMAT_NODE, &value); + */ + MPV_FORMAT_NODE = 6, + /** + * Used with mpv_node only. Can usually not be used directly. + */ + MPV_FORMAT_NODE_ARRAY = 7, + /** + * See MPV_FORMAT_NODE_ARRAY. + */ + MPV_FORMAT_NODE_MAP = 8, + /** + * A raw, untyped byte array. Only used only with mpv_node, and only in + * some very specific situations. (Some commands use it.) + */ + MPV_FORMAT_BYTE_ARRAY = 9 +} mpv_format; + +/** + * Generic data storage. + * + * If mpv writes this struct (e.g. via mpv_get_property()), you must not change + * the data. In some cases (mpv_get_property()), you have to free it with + * mpv_free_node_contents(). If you fill this struct yourself, you're also + * responsible for freeing it, and you must not call mpv_free_node_contents(). + */ +typedef struct mpv_node { + union { + char *string; /** valid if format==MPV_FORMAT_STRING */ + int flag; /** valid if format==MPV_FORMAT_FLAG */ + int64_t int64; /** valid if format==MPV_FORMAT_INT64 */ + double double_; /** valid if format==MPV_FORMAT_DOUBLE */ + /** + * valid if format==MPV_FORMAT_NODE_ARRAY + * or if format==MPV_FORMAT_NODE_MAP + */ + struct mpv_node_list *list; + /** + * valid if format==MPV_FORMAT_BYTE_ARRAY + */ + struct mpv_byte_array *ba; + } u; + /** + * Type of the data stored in this struct. This value rules what members in + * the given union can be accessed. The following formats are currently + * defined to be allowed in mpv_node: + * + * MPV_FORMAT_STRING (u.string) + * MPV_FORMAT_FLAG (u.flag) + * MPV_FORMAT_INT64 (u.int64) + * MPV_FORMAT_DOUBLE (u.double_) + * MPV_FORMAT_NODE_ARRAY (u.list) + * MPV_FORMAT_NODE_MAP (u.list) + * MPV_FORMAT_BYTE_ARRAY (u.ba) + * MPV_FORMAT_NONE (no member) + * + * If you encounter a value you don't know, you must not make any + * assumptions about the contents of union u. + */ + mpv_format format; +} mpv_node; + +/** + * (see mpv_node) + */ +typedef struct mpv_node_list { + /** + * Number of entries. Negative values are not allowed. + */ + int num; + /** + * MPV_FORMAT_NODE_ARRAY: + * values[N] refers to value of the Nth item + * + * MPV_FORMAT_NODE_MAP: + * values[N] refers to value of the Nth key/value pair + * + * If num > 0, values[0] to values[num-1] (inclusive) are valid. + * Otherwise, this can be NULL. + */ + mpv_node *values; + /** + * MPV_FORMAT_NODE_ARRAY: + * unused (typically NULL), access is not allowed + * + * MPV_FORMAT_NODE_MAP: + * keys[N] refers to key of the Nth key/value pair. If num > 0, keys[0] to + * keys[num-1] (inclusive) are valid. Otherwise, this can be NULL. + * The keys are in random order. The only guarantee is that keys[N] belongs + * to the value values[N]. NULL keys are not allowed. + */ + char **keys; +} mpv_node_list; + +/** + * (see mpv_node) + */ +typedef struct mpv_byte_array { + /** + * Pointer to the data. In what format the data is stored is up to whatever + * uses MPV_FORMAT_BYTE_ARRAY. + */ + void *data; + /** + * Size of the data pointed to by ptr. + */ + size_t size; +} mpv_byte_array; + +/** + * Frees any data referenced by the node. It doesn't free the node itself. + * Call this only if the mpv client API set the node. If you constructed the + * node yourself (manually), you have to free it yourself. + * + * If node->format is MPV_FORMAT_NONE, this call does nothing. Likewise, if + * the client API sets a node with this format, this function doesn't need to + * be called. (This is just a clarification that there's no danger of anything + * strange happening in these cases.) + */ +MPV_EXPORT void mpv_free_node_contents(mpv_node *node); + +/** + * Set an option. Note that you can't normally set options during runtime. It + * works in uninitialized state (see mpv_create()), and in some cases in at + * runtime. + * + * Using a format other than MPV_FORMAT_NODE is equivalent to constructing a + * mpv_node with the given format and data, and passing the mpv_node to this + * function. + * + * Note: this is semi-deprecated. For most purposes, this is not needed anymore. + * Starting with mpv version 0.21.0 (version 1.23) most options can be set + * with mpv_set_property() (and related functions), and even before + * mpv_initialize(). In some obscure corner cases, using this function + * to set options might still be required (see + * "Inconsistencies between options and properties" in the manpage). Once + * these are resolved, the option setting functions might be fully + * deprecated. + * + * @param name Option name. This is the same as on the mpv command line, but + * without the leading "--". + * @param format see enum mpv_format. + * @param[in] data Option value (according to the format). + * @return error code + */ +MPV_EXPORT int mpv_set_option(mpv_handle *ctx, const char *name, mpv_format format, + void *data); + +/** + * Convenience function to set an option to a string value. This is like + * calling mpv_set_option() with MPV_FORMAT_STRING. + * + * @return error code + */ +MPV_EXPORT int mpv_set_option_string(mpv_handle *ctx, const char *name, const char *data); + +/** + * Send a command to the player. Commands are the same as those used in + * input.conf, except that this function takes parameters in a pre-split + * form. + * + * The commands and their parameters are documented in input.rst. + * + * Does not use OSD and string expansion by default (unlike mpv_command_string() + * and input.conf). + * + * @param[in] args NULL-terminated list of strings. Usually, the first item + * is the command, and the following items are arguments. + * @return error code + */ +MPV_EXPORT int mpv_command(mpv_handle *ctx, const char **args); + +/** + * Same as mpv_command(), but allows passing structured data in any format. + * In particular, calling mpv_command() is exactly like calling + * mpv_command_node() with the format set to MPV_FORMAT_NODE_ARRAY, and + * every arg passed in order as MPV_FORMAT_STRING. + * + * Does not use OSD and string expansion by default. + * + * The args argument can have one of the following formats: + * + * MPV_FORMAT_NODE_ARRAY: + * Positional arguments. Each entry is an argument using an arbitrary + * format (the format must be compatible to the used command). Usually, + * the first item is the command name (as MPV_FORMAT_STRING). The order + * of arguments is as documented in each command description. + * + * MPV_FORMAT_NODE_MAP: + * Named arguments. This requires at least an entry with the key "name" + * to be present, which must be a string, and contains the command name. + * The special entry "_flags" is optional, and if present, must be an + * array of strings, each being a command prefix to apply. All other + * entries are interpreted as arguments. They must use the argument names + * as documented in each command description. Some commands do not + * support named arguments at all, and must use MPV_FORMAT_NODE_ARRAY. + * + * @param[in] args mpv_node with format set to one of the values documented + * above (see there for details) + * @param[out] result Optional, pass NULL if unused. If not NULL, and if the + * function succeeds, this is set to command-specific return + * data. You must call mpv_free_node_contents() to free it + * (again, only if the command actually succeeds). + * Not many commands actually use this at all. + * @return error code (the result parameter is not set on error) + */ +MPV_EXPORT int mpv_command_node(mpv_handle *ctx, mpv_node *args, mpv_node *result); + +/** + * This is essentially identical to mpv_command() but it also returns a result. + * + * Does not use OSD and string expansion by default. + * + * @param[in] args NULL-terminated list of strings. Usually, the first item + * is the command, and the following items are arguments. + * @param[out] result Optional, pass NULL if unused. If not NULL, and if the + * function succeeds, this is set to command-specific return + * data. You must call mpv_free_node_contents() to free it + * (again, only if the command actually succeeds). + * Not many commands actually use this at all. + * @return error code (the result parameter is not set on error) + */ +MPV_EXPORT int mpv_command_ret(mpv_handle *ctx, const char **args, mpv_node *result); + +/** + * Same as mpv_command, but use input.conf parsing for splitting arguments. + * This is slightly simpler, but also more error prone, since arguments may + * need quoting/escaping. + * + * This also has OSD and string expansion enabled by default. + */ +MPV_EXPORT int mpv_command_string(mpv_handle *ctx, const char *args); + +/** + * Same as mpv_command, but run the command asynchronously. + * + * Commands are executed asynchronously. You will receive a + * MPV_EVENT_COMMAND_REPLY event. This event will also have an + * error code set if running the command failed. For commands that + * return data, the data is put into mpv_event_command.result. + * + * The only case when you do not receive an event is when the function call + * itself fails. This happens only if parsing the command itself (or otherwise + * validating it) fails, i.e. the return code of the API call is not 0 or + * positive. + * + * Safe to be called from mpv render API threads. + * + * @param reply_userdata the value mpv_event.reply_userdata of the reply will + * be set to (see section about asynchronous calls) + * @param args NULL-terminated list of strings (see mpv_command()) + * @return error code (if parsing or queuing the command fails) + */ +MPV_EXPORT int mpv_command_async(mpv_handle *ctx, uint64_t reply_userdata, + const char **args); + +/** + * Same as mpv_command_node(), but run it asynchronously. Basically, this + * function is to mpv_command_node() what mpv_command_async() is to + * mpv_command(). + * + * See mpv_command_async() for details. + * + * Safe to be called from mpv render API threads. + * + * @param reply_userdata the value mpv_event.reply_userdata of the reply will + * be set to (see section about asynchronous calls) + * @param args as in mpv_command_node() + * @return error code (if parsing or queuing the command fails) + */ +MPV_EXPORT int mpv_command_node_async(mpv_handle *ctx, uint64_t reply_userdata, + mpv_node *args); + +/** + * Signal to all async requests with the matching ID to abort. This affects + * the following API calls: + * + * mpv_command_async + * mpv_command_node_async + * + * All of these functions take a reply_userdata parameter. This API function + * tells all requests with the matching reply_userdata value to try to return + * as soon as possible. If there are multiple requests with matching ID, it + * aborts all of them. + * + * This API function is mostly asynchronous itself. It will not wait until the + * command is aborted. Instead, the command will terminate as usual, but with + * some work not done. How this is signaled depends on the specific command (for + * example, the "subprocess" command will indicate it by "killed_by_us" set to + * true in the result). How long it takes also depends on the situation. The + * aborting process is completely asynchronous. + * + * Not all commands may support this functionality. In this case, this function + * will have no effect. The same is true if the request using the passed + * reply_userdata has already terminated, has not been started yet, or was + * never in use at all. + * + * You have to be careful of race conditions: the time during which the abort + * request will be effective is _after_ e.g. mpv_command_async() has returned, + * and before the command has signaled completion with MPV_EVENT_COMMAND_REPLY. + * + * @param reply_userdata ID of the request to be aborted (see above) + */ +MPV_EXPORT void mpv_abort_async_command(mpv_handle *ctx, uint64_t reply_userdata); + +/** + * Set a property to a given value. Properties are essentially variables which + * can be queried or set at runtime. For example, writing to the pause property + * will actually pause or unpause playback. + * + * If the format doesn't match with the internal format of the property, access + * usually will fail with MPV_ERROR_PROPERTY_FORMAT. In some cases, the data + * is automatically converted and access succeeds. For example, MPV_FORMAT_INT64 + * is always converted to MPV_FORMAT_DOUBLE, and access using MPV_FORMAT_STRING + * usually invokes a string parser. The same happens when calling this function + * with MPV_FORMAT_NODE: the underlying format may be converted to another + * type if possible. + * + * Using a format other than MPV_FORMAT_NODE is equivalent to constructing a + * mpv_node with the given format and data, and passing the mpv_node to this + * function. (Before API version 1.21, this was different.) + * + * Note: starting with mpv 0.21.0 (client API version 1.23), this can be used to + * set options in general. It even can be used before mpv_initialize() + * has been called. If called before mpv_initialize(), setting properties + * not backed by options will result in MPV_ERROR_PROPERTY_UNAVAILABLE. + * In some cases, properties and options still conflict. In these cases, + * mpv_set_property() accesses the options before mpv_initialize(), and + * the properties after mpv_initialize(). These conflicts will be removed + * in mpv 0.23.0. See mpv_set_option() for further remarks. + * + * @param name The property name. See input.rst for a list of properties. + * @param format see enum mpv_format. + * @param[in] data Option value. + * @return error code + */ +MPV_EXPORT int mpv_set_property(mpv_handle *ctx, const char *name, mpv_format format, + void *data); + +/** + * Convenience function to set a property to a string value. + * + * This is like calling mpv_set_property() with MPV_FORMAT_STRING. + */ +MPV_EXPORT int mpv_set_property_string(mpv_handle *ctx, const char *name, const char *data); + +/** + * Convenience function to delete a property. + * + * This is equivalent to running the command "del [name]". + * + * @param name The property name. See input.rst for a list of properties. + * @return error code + */ +MPV_EXPORT int mpv_del_property(mpv_handle *ctx, const char *name); + +/** + * Set a property asynchronously. You will receive the result of the operation + * as MPV_EVENT_SET_PROPERTY_REPLY event. The mpv_event.error field will contain + * the result status of the operation. Otherwise, this function is similar to + * mpv_set_property(). + * + * Safe to be called from mpv render API threads. + * + * @param reply_userdata see section about asynchronous calls + * @param name The property name. + * @param format see enum mpv_format. + * @param[in] data Option value. The value will be copied by the function. It + * will never be modified by the client API. + * @return error code if sending the request failed + */ +MPV_EXPORT int mpv_set_property_async(mpv_handle *ctx, uint64_t reply_userdata, + const char *name, mpv_format format, void *data); + +/** + * Read the value of the given property. + * + * If the format doesn't match with the internal format of the property, access + * usually will fail with MPV_ERROR_PROPERTY_FORMAT. In some cases, the data + * is automatically converted and access succeeds. For example, MPV_FORMAT_INT64 + * is always converted to MPV_FORMAT_DOUBLE, and access using MPV_FORMAT_STRING + * usually invokes a string formatter. + * + * @param name The property name. + * @param format see enum mpv_format. + * @param[out] data Pointer to the variable holding the option value. On + * success, the variable will be set to a copy of the option + * value. For formats that require dynamic memory allocation, + * you can free the value with mpv_free() (strings) or + * mpv_free_node_contents() (MPV_FORMAT_NODE). + * @return error code + */ +MPV_EXPORT int mpv_get_property(mpv_handle *ctx, const char *name, mpv_format format, + void *data); + +/** + * Return the value of the property with the given name as string. This is + * equivalent to mpv_get_property() with MPV_FORMAT_STRING. + * + * See MPV_FORMAT_STRING for character encoding issues. + * + * On error, NULL is returned. Use mpv_get_property() if you want fine-grained + * error reporting. + * + * @param name The property name. + * @return Property value, or NULL if the property can't be retrieved. Free + * the string with mpv_free(). + */ +MPV_EXPORT char *mpv_get_property_string(mpv_handle *ctx, const char *name); + +/** + * Return the property as "OSD" formatted string. This is the same as + * mpv_get_property_string, but using MPV_FORMAT_OSD_STRING. + * + * @return Property value, or NULL if the property can't be retrieved. Free + * the string with mpv_free(). + */ +MPV_EXPORT char *mpv_get_property_osd_string(mpv_handle *ctx, const char *name); + +/** + * Get a property asynchronously. You will receive the result of the operation + * as well as the property data with the MPV_EVENT_GET_PROPERTY_REPLY event. + * You should check the mpv_event.error field on the reply event. + * + * Safe to be called from mpv render API threads. + * + * @param reply_userdata see section about asynchronous calls + * @param name The property name. + * @param format see enum mpv_format. + * @return error code if sending the request failed + */ +MPV_EXPORT int mpv_get_property_async(mpv_handle *ctx, uint64_t reply_userdata, + const char *name, mpv_format format); + +/** + * Get a notification whenever the given property changes. You will receive + * updates as MPV_EVENT_PROPERTY_CHANGE. Note that this is not very precise: + * for some properties, it may not send updates even if the property changed. + * This depends on the property, and it's a valid feature request to ask for + * better update handling of a specific property. (For some properties, like + * ``clock``, which shows the wall clock, this mechanism doesn't make too + * much sense anyway.) + * + * Property changes are coalesced: the change events are returned only once the + * event queue becomes empty (e.g. mpv_wait_event() would block or return + * MPV_EVENT_NONE), and then only one event per changed property is returned. + * + * You always get an initial change notification. This is meant to initialize + * the user's state to the current value of the property. + * + * Normally, change events are sent only if the property value changes according + * to the requested format. mpv_event_property will contain the property value + * as data member. + * + * Warning: if a property is unavailable or retrieving it caused an error, + * MPV_FORMAT_NONE will be set in mpv_event_property, even if the + * format parameter was set to a different value. In this case, the + * mpv_event_property.data field is invalid. + * + * If the property is observed with the format parameter set to MPV_FORMAT_NONE, + * you get low-level notifications whether the property _may_ have changed, and + * the data member in mpv_event_property will be unset. With this mode, you + * will have to determine yourself whether the property really changed. On the + * other hand, this mechanism can be faster and uses less resources. + * + * Observing a property that doesn't exist is allowed. (Although it may still + * cause some sporadic change events.) + * + * Keep in mind that you will get change notifications even if you change a + * property yourself. Try to avoid endless feedback loops, which could happen + * if you react to the change notifications triggered by your own change. + * + * Only the mpv_handle on which this was called will receive the property + * change events, or can unobserve them. + * + * Safe to be called from mpv render API threads. + * + * @param reply_userdata This will be used for the mpv_event.reply_userdata + * field for the received MPV_EVENT_PROPERTY_CHANGE + * events. (Also see section about asynchronous calls, + * although this function is somewhat different from + * actual asynchronous calls.) + * If you have no use for this, pass 0. + * Also see mpv_unobserve_property(). + * @param name The property name. + * @param format see enum mpv_format. Can be MPV_FORMAT_NONE to omit values + * from the change events. + * @return error code (usually fails only on OOM or unsupported format) + */ +MPV_EXPORT int mpv_observe_property(mpv_handle *mpv, uint64_t reply_userdata, + const char *name, mpv_format format); + +/** + * Undo mpv_observe_property(). This will remove all observed properties for + * which the given number was passed as reply_userdata to mpv_observe_property. + * + * Safe to be called from mpv render API threads. + * + * @param registered_reply_userdata ID that was passed to mpv_observe_property + * @return negative value is an error code, >=0 is number of removed properties + * on success (includes the case when 0 were removed) + */ +MPV_EXPORT int mpv_unobserve_property(mpv_handle *mpv, uint64_t registered_reply_userdata); + +typedef enum mpv_event_id { + /** + * Nothing happened. Happens on timeouts or sporadic wakeups. + */ + MPV_EVENT_NONE = 0, + /** + * Happens when the player quits. The player enters a state where it tries + * to disconnect all clients. Most requests to the player will fail, and + * the client should react to this and quit with mpv_destroy() as soon as + * possible. + */ + MPV_EVENT_SHUTDOWN = 1, + /** + * See mpv_request_log_messages(). + */ + MPV_EVENT_LOG_MESSAGE = 2, + /** + * Reply to a mpv_get_property_async() request. + * See also mpv_event and mpv_event_property. + */ + MPV_EVENT_GET_PROPERTY_REPLY = 3, + /** + * Reply to a mpv_set_property_async() request. + * (Unlike MPV_EVENT_GET_PROPERTY, mpv_event_property is not used.) + */ + MPV_EVENT_SET_PROPERTY_REPLY = 4, + /** + * Reply to a mpv_command_async() or mpv_command_node_async() request. + * See also mpv_event and mpv_event_command. + */ + MPV_EVENT_COMMAND_REPLY = 5, + /** + * Notification before playback start of a file (before the file is loaded). + * See also mpv_event and mpv_event_start_file. + */ + MPV_EVENT_START_FILE = 6, + /** + * Notification after playback end (after the file was unloaded). + * See also mpv_event and mpv_event_end_file. + */ + MPV_EVENT_END_FILE = 7, + /** + * Notification when the file has been loaded (headers were read etc.), and + * decoding starts. + */ + MPV_EVENT_FILE_LOADED = 8, +#if MPV_ENABLE_DEPRECATED + /** + * Idle mode was entered. In this mode, no file is played, and the playback + * core waits for new commands. (The command line player normally quits + * instead of entering idle mode, unless --idle was specified. If mpv + * was started with mpv_create(), idle mode is enabled by default.) + * + * @deprecated This is equivalent to using mpv_observe_property() on the + * "idle-active" property. The event is redundant, and might be + * removed in the far future. As a further warning, this event + * is not necessarily sent at the right point anymore (at the + * start of the program), while the property behaves correctly. + */ + MPV_EVENT_IDLE = 11, + /** + * Sent every time after a video frame is displayed. Note that currently, + * this will be sent in lower frequency if there is no video, or playback + * is paused - but that will be removed in the future, and it will be + * restricted to video frames only. + * + * @deprecated Use mpv_observe_property() with relevant properties instead + * (such as "playback-time"). + */ + MPV_EVENT_TICK = 14, +#endif + /** + * Triggered by the script-message input command. The command uses the + * first argument of the command as client name (see mpv_client_name()) to + * dispatch the message, and passes along all arguments starting from the + * second argument as strings. + * See also mpv_event and mpv_event_client_message. + */ + MPV_EVENT_CLIENT_MESSAGE = 16, + /** + * Happens after video changed in some way. This can happen on resolution + * changes, pixel format changes, or video filter changes. The event is + * sent after the video filters and the VO are reconfigured. Applications + * embedding a mpv window should listen to this event in order to resize + * the window if needed. + * Note that this event can happen sporadically, and you should check + * yourself whether the video parameters really changed before doing + * something expensive. + */ + MPV_EVENT_VIDEO_RECONFIG = 17, + /** + * Similar to MPV_EVENT_VIDEO_RECONFIG. This is relatively uninteresting, + * because there is no such thing as audio output embedding. + */ + MPV_EVENT_AUDIO_RECONFIG = 18, + /** + * Happens when a seek was initiated. Playback stops. Usually it will + * resume with MPV_EVENT_PLAYBACK_RESTART as soon as the seek is finished. + */ + MPV_EVENT_SEEK = 20, + /** + * There was a discontinuity of some sort (like a seek), and playback + * was reinitialized. Usually happens on start of playback and after + * seeking. The main purpose is allowing the client to detect when a seek + * request is finished. + */ + MPV_EVENT_PLAYBACK_RESTART = 21, + /** + * Event sent due to mpv_observe_property(). + * See also mpv_event and mpv_event_property. + */ + MPV_EVENT_PROPERTY_CHANGE = 22, + /** + * Happens if the internal per-mpv_handle ringbuffer overflows, and at + * least 1 event had to be dropped. This can happen if the client doesn't + * read the event queue quickly enough with mpv_wait_event(), or if the + * client makes a very large number of asynchronous calls at once. + * + * Event delivery will continue normally once this event was returned + * (this forces the client to empty the queue completely). + */ + MPV_EVENT_QUEUE_OVERFLOW = 24, + /** + * Triggered if a hook handler was registered with mpv_hook_add(), and the + * hook is invoked. If you receive this, you must handle it, and continue + * the hook with mpv_hook_continue(). + * See also mpv_event and mpv_event_hook. + */ + MPV_EVENT_HOOK = 25, + // Internal note: adjust INTERNAL_EVENT_BASE when adding new events. +} mpv_event_id; + +/** + * Return a string describing the event. For unknown events, NULL is returned. + * + * Note that all events actually returned by the API will also yield a non-NULL + * string with this function. + * + * @param event event ID, see see enum mpv_event_id + * @return A static string giving a short symbolic name of the event. It + * consists of lower-case alphanumeric characters and can include "-" + * characters. This string is suitable for use in e.g. scripting + * interfaces. + * The string is completely static, i.e. doesn't need to be deallocated, + * and is valid forever. + */ +MPV_EXPORT const char *mpv_event_name(mpv_event_id event); + +typedef struct mpv_event_property { + /** + * Name of the property. + */ + const char *name; + /** + * Format of the data field in the same struct. See enum mpv_format. + * This is always the same format as the requested format, except when + * the property could not be retrieved (unavailable, or an error happened), + * in which case the format is MPV_FORMAT_NONE. + */ + mpv_format format; + /** + * Received property value. Depends on the format. This is like the + * pointer argument passed to mpv_get_property(). + * + * For example, for MPV_FORMAT_STRING you get the string with: + * + * char *value = *(char **)(event_property->data); + * + * Note that this is set to NULL if retrieving the property failed (the + * format will be MPV_FORMAT_NONE). + */ + void *data; +} mpv_event_property; + +/** + * Numeric log levels. The lower the number, the more important the message is. + * MPV_LOG_LEVEL_NONE is never used when receiving messages. The string in + * the comment after the value is the name of the log level as used for the + * mpv_request_log_messages() function. + * Unused numeric values are unused, but reserved for future use. + */ +typedef enum mpv_log_level { + MPV_LOG_LEVEL_NONE = 0, /// "no" - disable absolutely all messages + MPV_LOG_LEVEL_FATAL = 10, /// "fatal" - critical/aborting errors + MPV_LOG_LEVEL_ERROR = 20, /// "error" - simple errors + MPV_LOG_LEVEL_WARN = 30, /// "warn" - possible problems + MPV_LOG_LEVEL_INFO = 40, /// "info" - informational message + MPV_LOG_LEVEL_V = 50, /// "v" - noisy informational message + MPV_LOG_LEVEL_DEBUG = 60, /// "debug" - very noisy technical information + MPV_LOG_LEVEL_TRACE = 70, /// "trace" - extremely noisy +} mpv_log_level; + +typedef struct mpv_event_log_message { + /** + * The module prefix, identifies the sender of the message. As a special + * case, if the message buffer overflows, this will be set to the string + * "overflow" (which doesn't appear as prefix otherwise), and the text + * field will contain an informative message. + */ + const char *prefix; + /** + * The log level as string. See mpv_request_log_messages() for possible + * values. The level "no" is never used here. + */ + const char *level; + /** + * The log message. It consists of 1 line of text, and is terminated with + * a newline character. (Before API version 1.6, it could contain multiple + * or partial lines.) + */ + const char *text; + /** + * The same contents as the level field, but as a numeric ID. + * Since API version 1.6. + */ + mpv_log_level log_level; +} mpv_event_log_message; + +/// Since API version 1.9. +typedef enum mpv_end_file_reason { + /** + * The end of file was reached. Sometimes this may also happen on + * incomplete or corrupted files, or if the network connection was + * interrupted when playing a remote file. It also happens if the + * playback range was restricted with --end or --frames or similar. + */ + MPV_END_FILE_REASON_EOF = 0, + /** + * Playback was stopped by an external action (e.g. playlist controls). + */ + MPV_END_FILE_REASON_STOP = 2, + /** + * Playback was stopped by the quit command or player shutdown. + */ + MPV_END_FILE_REASON_QUIT = 3, + /** + * Some kind of error happened that lead to playback abort. Does not + * necessarily happen on incomplete or broken files (in these cases, both + * MPV_END_FILE_REASON_ERROR or MPV_END_FILE_REASON_EOF are possible). + * + * mpv_event_end_file.error will be set. + */ + MPV_END_FILE_REASON_ERROR = 4, + /** + * The file was a playlist or similar. When the playlist is read, its + * entries will be appended to the playlist after the entry of the current + * file, the entry of the current file is removed, and a MPV_EVENT_END_FILE + * event is sent with reason set to MPV_END_FILE_REASON_REDIRECT. Then + * playback continues with the playlist contents. + * Since API version 1.18. + */ + MPV_END_FILE_REASON_REDIRECT = 5, +} mpv_end_file_reason; + +/// Since API version 1.108. +typedef struct mpv_event_start_file { + /** + * Playlist entry ID of the file being loaded now. + */ + int64_t playlist_entry_id; +} mpv_event_start_file; + +typedef struct mpv_event_end_file { + /** + * Corresponds to the values in enum mpv_end_file_reason. + * + * Unknown values should be treated as unknown. + */ + mpv_end_file_reason reason; + /** + * If reason==MPV_END_FILE_REASON_ERROR, this contains a mpv error code + * (one of MPV_ERROR_...) giving an approximate reason why playback + * failed. In other cases, this field is 0 (no error). + * Since API version 1.9. + */ + int error; + /** + * Playlist entry ID of the file that was being played or attempted to be + * played. This has the same value as the playlist_entry_id field in the + * corresponding mpv_event_start_file event. + * Since API version 1.108. + */ + int64_t playlist_entry_id; + /** + * If loading ended, because the playlist entry to be played was for example + * a playlist, and the current playlist entry is replaced with a number of + * other entries. This may happen at least with MPV_END_FILE_REASON_REDIRECT + * (other event types may use this for similar but different purposes in the + * future). In this case, playlist_insert_id will be set to the playlist + * entry ID of the first inserted entry, and playlist_insert_num_entries to + * the total number of inserted playlist entries. Note this in this specific + * case, the ID of the last inserted entry is playlist_insert_id+num-1. + * Beware that depending on circumstances, you may observe the new playlist + * entries before seeing the event (e.g. reading the "playlist" property or + * getting a property change notification before receiving the event). + * Since API version 1.108. + */ + int64_t playlist_insert_id; + /** + * See playlist_insert_id. Only non-0 if playlist_insert_id is valid. Never + * negative. + * Since API version 1.108. + */ + int playlist_insert_num_entries; +} mpv_event_end_file; + +typedef struct mpv_event_client_message { + /** + * Arbitrary arguments chosen by the sender of the message. If num_args > 0, + * you can access args[0] through args[num_args - 1] (inclusive). What + * these arguments mean is up to the sender and receiver. + * None of the valid items are NULL. + */ + int num_args; + const char **args; +} mpv_event_client_message; + +typedef struct mpv_event_hook { + /** + * The hook name as passed to mpv_hook_add(). + */ + const char *name; + /** + * Internal ID that must be passed to mpv_hook_continue(). + */ + uint64_t id; +} mpv_event_hook; + +// Since API version 1.102. +typedef struct mpv_event_command { + /** + * Result data of the command. Note that success/failure is signaled + * separately via mpv_event.error. This field is only for result data + * in case of success. Most commands leave it at MPV_FORMAT_NONE. Set + * to MPV_FORMAT_NONE on failure. + */ + mpv_node result; +} mpv_event_command; + +typedef struct mpv_event { + /** + * One of mpv_event. Keep in mind that later ABI compatible releases might + * add new event types. These should be ignored by the API user. + */ + mpv_event_id event_id; + /** + * This is mainly used for events that are replies to (asynchronous) + * requests. It contains a status code, which is >= 0 on success, or < 0 + * on error (a mpv_error value). Usually, this will be set if an + * asynchronous request fails. + * Used for: + * MPV_EVENT_GET_PROPERTY_REPLY + * MPV_EVENT_SET_PROPERTY_REPLY + * MPV_EVENT_COMMAND_REPLY + */ + int error; + /** + * If the event is in reply to a request (made with this API and this + * API handle), this is set to the reply_userdata parameter of the request + * call. Otherwise, this field is 0. + * Used for: + * MPV_EVENT_GET_PROPERTY_REPLY + * MPV_EVENT_SET_PROPERTY_REPLY + * MPV_EVENT_COMMAND_REPLY + * MPV_EVENT_PROPERTY_CHANGE + * MPV_EVENT_HOOK + */ + uint64_t reply_userdata; + /** + * The meaning and contents of the data member depend on the event_id: + * MPV_EVENT_GET_PROPERTY_REPLY: mpv_event_property* + * MPV_EVENT_PROPERTY_CHANGE: mpv_event_property* + * MPV_EVENT_LOG_MESSAGE: mpv_event_log_message* + * MPV_EVENT_CLIENT_MESSAGE: mpv_event_client_message* + * MPV_EVENT_START_FILE: mpv_event_start_file* (since v1.108) + * MPV_EVENT_END_FILE: mpv_event_end_file* + * MPV_EVENT_HOOK: mpv_event_hook* + * MPV_EVENT_COMMAND_REPLY* mpv_event_command* + * other: NULL + * + * Note: future enhancements might add new event structs for existing or new + * event types. + */ + void *data; +} mpv_event; + +/** + * Convert the given src event to a mpv_node, and set *dst to the result. *dst + * is set to a MPV_FORMAT_NODE_MAP, with fields for corresponding mpv_event and + * mpv_event.data/mpv_event_* fields. + * + * The exact details are not completely documented out of laziness. A start + * is located in the "Events" section of the manpage. + * + * *dst may point to newly allocated memory, or pointers in mpv_event. You must + * copy the entire mpv_node if you want to reference it after mpv_event becomes + * invalid (such as making a new mpv_wait_event() call, or destroying the + * mpv_handle from which it was returned). Call mpv_free_node_contents() to free + * any memory allocations made by this API function. + * + * Safe to be called from mpv render API threads. + * + * @param dst Target. This is not read and fully overwritten. Must be released + * with mpv_free_node_contents(). Do not write to pointers returned + * by it. (On error, this may be left as an empty node.) + * @param src The source event. Not modified (it's not const due to the author's + * prejudice of the C version of const). + * @return error code (MPV_ERROR_NOMEM only, if at all) + */ +MPV_EXPORT int mpv_event_to_node(mpv_node *dst, mpv_event *src); + +/** + * Enable or disable the given event. + * + * Some events are enabled by default. Some events can't be disabled. + * + * (Informational note: currently, all events are enabled by default, except + * MPV_EVENT_TICK.) + * + * Safe to be called from mpv render API threads. + * + * @param event See enum mpv_event_id. + * @param enable 1 to enable receiving this event, 0 to disable it. + * @return error code + */ +MPV_EXPORT int mpv_request_event(mpv_handle *ctx, mpv_event_id event, int enable); + +/** + * Enable or disable receiving of log messages. These are the messages the + * command line player prints to the terminal. This call sets the minimum + * required log level for a message to be received with MPV_EVENT_LOG_MESSAGE. + * + * @param min_level Minimal log level as string. Valid log levels: + * no fatal error warn info v debug trace + * The value "no" disables all messages. This is the default. + * An exception is the value "terminal-default", which uses the + * log level as set by the "--msg-level" option. This works + * even if the terminal is disabled. (Since API version 1.19.) + * Also see mpv_log_level. + * @return error code + */ +MPV_EXPORT int mpv_request_log_messages(mpv_handle *ctx, const char *min_level); + +/** + * Wait for the next event, or until the timeout expires, or if another thread + * makes a call to mpv_wakeup(). Passing 0 as timeout will never wait, and + * is suitable for polling. + * + * The internal event queue has a limited size (per client handle). If you + * don't empty the event queue quickly enough with mpv_wait_event(), it will + * overflow and silently discard further events. If this happens, making + * asynchronous requests will fail as well (with MPV_ERROR_EVENT_QUEUE_FULL). + * + * Only one thread is allowed to call this on the same mpv_handle at a time. + * The API won't complain if more than one thread calls this, but it will cause + * race conditions in the client when accessing the shared mpv_event struct. + * Note that most other API functions are not restricted by this, and no API + * function internally calls mpv_wait_event(). Additionally, concurrent calls + * to different mpv_handles are always safe. + * + * As long as the timeout is 0, this is safe to be called from mpv render API + * threads. + * + * @param timeout Timeout in seconds, after which the function returns even if + * no event was received. A MPV_EVENT_NONE is returned on + * timeout. A value of 0 will disable waiting. Negative values + * will wait with an infinite timeout. + * @return A struct containing the event ID and other data. The pointer (and + * fields in the struct) stay valid until the next mpv_wait_event() + * call, or until the mpv_handle is destroyed. You must not write to + * the struct, and all memory referenced by it will be automatically + * released by the API on the next mpv_wait_event() call, or when the + * context is destroyed. The return value is never NULL. + */ +MPV_EXPORT mpv_event *mpv_wait_event(mpv_handle *ctx, double timeout); + +/** + * Interrupt the current mpv_wait_event() call. This will wake up the thread + * currently waiting in mpv_wait_event(). If no thread is waiting, the next + * mpv_wait_event() call will return immediately (this is to avoid lost + * wakeups). + * + * mpv_wait_event() will receive a MPV_EVENT_NONE if it's woken up due to + * this call. But note that this dummy event might be skipped if there are + * already other events queued. All what counts is that the waiting thread + * is woken up at all. + * + * Safe to be called from mpv render API threads. + */ +MPV_EXPORT void mpv_wakeup(mpv_handle *ctx); + +/** + * Set a custom function that should be called when there are new events. Use + * this if blocking in mpv_wait_event() to wait for new events is not feasible. + * + * Keep in mind that the callback will be called from foreign threads. You + * must not make any assumptions of the environment, and you must return as + * soon as possible (i.e. no long blocking waits). Exiting the callback through + * any other means than a normal return is forbidden (no throwing exceptions, + * no longjmp() calls). You must not change any local thread state (such as + * the C floating point environment). + * + * You are not allowed to call any client API functions inside of the callback. + * In particular, you should not do any processing in the callback, but wake up + * another thread that does all the work. The callback is meant strictly for + * notification only, and is called from arbitrary core parts of the player, + * that make no considerations for reentrant API use or allowing the callee to + * spend a lot of time doing other things. Keep in mind that it's also possible + * that the callback is called from a thread while a mpv API function is called + * (i.e. it can be reentrant). + * + * In general, the client API expects you to call mpv_wait_event() to receive + * notifications, and the wakeup callback is merely a helper utility to make + * this easier in certain situations. Note that it's possible that there's + * only one wakeup callback invocation for multiple events. You should call + * mpv_wait_event() with no timeout until MPV_EVENT_NONE is reached, at which + * point the event queue is empty. + * + * If you actually want to do processing in a callback, spawn a thread that + * does nothing but call mpv_wait_event() in a loop and dispatches the result + * to a callback. + * + * Only one wakeup callback can be set. + * + * @param cb function that should be called if a wakeup is required + * @param d arbitrary userdata passed to cb + */ +MPV_EXPORT void mpv_set_wakeup_callback(mpv_handle *ctx, void (*cb)(void *d), void *d); + +/** + * Block until all asynchronous requests are done. This affects functions like + * mpv_command_async(), which return immediately and return their result as + * events. + * + * This is a helper, and somewhat equivalent to calling mpv_wait_event() in a + * loop until all known asynchronous requests have sent their reply as event, + * except that the event queue is not emptied. + * + * In case you called mpv_suspend() before, this will also forcibly reset the + * suspend counter of the given handle. + */ +MPV_EXPORT void mpv_wait_async_requests(mpv_handle *ctx); + +/** + * A hook is like a synchronous event that blocks the player. You register + * a hook handler with this function. You will get an event, which you need + * to handle, and once things are ready, you can let the player continue with + * mpv_hook_continue(). + * + * Currently, hooks can't be removed explicitly. But they will be implicitly + * removed if the mpv_handle it was registered with is destroyed. This also + * continues the hook if it was being handled by the destroyed mpv_handle (but + * this should be avoided, as it might mess up order of hook execution). + * + * Hook handlers are ordered globally by priority and order of registration. + * Handlers for the same hook with same priority are invoked in order of + * registration (the handler registered first is run first). Handlers with + * lower priority are run first (which seems backward). + * + * See the "Hooks" section in the manpage to see which hooks are currently + * defined. + * + * Some hooks might be reentrant (so you get multiple MPV_EVENT_HOOK for the + * same hook). If this can happen for a specific hook type, it will be + * explicitly documented in the manpage. + * + * Only the mpv_handle on which this was called will receive the hook events, + * or can "continue" them. + * + * @param reply_userdata This will be used for the mpv_event.reply_userdata + * field for the received MPV_EVENT_HOOK events. + * If you have no use for this, pass 0. + * @param name The hook name. This should be one of the documented names. But + * if the name is unknown, the hook event will simply be never + * raised. + * @param priority See remarks above. Use 0 as a neutral default. + * @return error code (usually fails only on OOM) + */ +MPV_EXPORT int mpv_hook_add(mpv_handle *ctx, uint64_t reply_userdata, + const char *name, int priority); + +/** + * Respond to a MPV_EVENT_HOOK event. You must call this after you have handled + * the event. There is no way to "cancel" or "stop" the hook. + * + * Calling this will will typically unblock the player for whatever the hook + * is responsible for (e.g. for the "on_load" hook it lets it continue + * playback). + * + * It is explicitly undefined behavior to call this more than once for each + * MPV_EVENT_HOOK, to pass an incorrect ID, or to call this on a mpv_handle + * different from the one that registered the handler and received the event. + * + * @param id This must be the value of the mpv_event_hook.id field for the + * corresponding MPV_EVENT_HOOK. + * @return error code + */ +MPV_EXPORT int mpv_hook_continue(mpv_handle *ctx, uint64_t id); + +#if MPV_ENABLE_DEPRECATED + +/** + * Return a UNIX file descriptor referring to the read end of a pipe. This + * pipe can be used to wake up a poll() based processing loop. The purpose of + * this function is very similar to mpv_set_wakeup_callback(), and provides + * a primitive mechanism to handle coordinating a foreign event loop and the + * libmpv event loop. The pipe is non-blocking. It's closed when the mpv_handle + * is destroyed. This function always returns the same value (on success). + * + * This is in fact implemented using the same underlying code as for + * mpv_set_wakeup_callback() (though they don't conflict), and it is as if each + * callback invocation writes a single 0 byte to the pipe. When the pipe + * becomes readable, the code calling poll() (or select()) on the pipe should + * read all contents of the pipe and then call mpv_wait_event(c, 0) until + * no new events are returned. The pipe contents do not matter and can just + * be discarded. There is not necessarily one byte per readable event in the + * pipe. For example, the pipes are non-blocking, and mpv won't block if the + * pipe is full. Pipes are normally limited to 4096 bytes, so if there are + * more than 4096 events, the number of readable bytes can not equal the number + * of events queued. Also, it's possible that mpv does not write to the pipe + * once it's guaranteed that the client was already signaled. See the example + * below how to do it correctly. + * + * Example: + * + * int pipefd = mpv_get_wakeup_pipe(mpv); + * if (pipefd < 0) + * error(); + * while (1) { + * struct pollfd pfds[1] = { + * { .fd = pipefd, .events = POLLIN }, + * }; + * // Wait until there are possibly new mpv events. + * poll(pfds, 1, -1); + * if (pfds[0].revents & POLLIN) { + * // Empty the pipe. Doing this before calling mpv_wait_event() + * // ensures that no wakeups are missed. It's not so important to + * // make sure the pipe is really empty (it will just cause some + * // additional wakeups in unlikely corner cases). + * char unused[256]; + * read(pipefd, unused, sizeof(unused)); + * while (1) { + * mpv_event *ev = mpv_wait_event(mpv, 0); + * // If MPV_EVENT_NONE is received, the event queue is empty. + * if (ev->event_id == MPV_EVENT_NONE) + * break; + * // Process the event. + * ... + * } + * } + * } + * + * @deprecated this function will be removed in the future. If you need this + * functionality, use mpv_set_wakeup_callback(), create a pipe + * manually, and call write() on your pipe in the callback. + * + * @return A UNIX FD of the read end of the wakeup pipe, or -1 on error. + * On MS Windows/MinGW, this will always return -1. + */ +MPV_EXPORT int mpv_get_wakeup_pipe(mpv_handle *ctx); + +#endif + +/** + * Defining MPV_CPLUGIN_DYNAMIC_SYM during plugin compilation will replace mpv_* + * functions with function pointers. Those pointer will be initialized when + * loading the plugin. + * + * It is recommended to use this symbol table when targeting Windows. The loader + * does not have notion of global symbols. Loading cplugin into mpv process will + * not allow this plugin to call any of the symbols that may be available in + * other modules. Instead cplugin has to link explicitly to specific PE binary, + * libmpv-2.dll/mpv.exe or any other binary that may have linked mpv statically. + * This limits portability of cplugin as it would need to be compiled separately + * for each of target PE binary that includes mpv's symbols. Which in practice + * is unrealistic, as we want one cplugin to be loaded without those restrictions. + * + * Instead of linking to any PE binary, we create function pointers for all mpv's + * exported symbols. For convenience names of entrypoints are redefined to those + * pointer, so no changes are required in cplugin source code, except of defining + * MPV_CPLUGIN_DYNAMIC_SYM. Those function pointer are exported to make them + * available for mpv to init with correct values during runtime, before calling + * `mpv_open_cplugin`. + * + * Note that those pointers are decorated with `selectany` attribute, so no need + * to worry about multiple definitions, linker will keep only single instance. + */ +#ifdef MPV_CPLUGIN_DYNAMIC_SYM + +#define MPV_DEFINE_SYM_PTR(name) \ + MPV_SELECTANY MPV_EXPORT \ + MPV_DECLTYPE(name) *pfn_##name; + +MPV_DEFINE_SYM_PTR(mpv_client_api_version) +#define mpv_client_api_version pfn_mpv_client_api_version +MPV_DEFINE_SYM_PTR(mpv_error_string) +#define mpv_error_string pfn_mpv_error_string +MPV_DEFINE_SYM_PTR(mpv_free) +#define mpv_free pfn_mpv_free +MPV_DEFINE_SYM_PTR(mpv_client_name) +#define mpv_client_name pfn_mpv_client_name +MPV_DEFINE_SYM_PTR(mpv_client_id) +#define mpv_client_id pfn_mpv_client_id +MPV_DEFINE_SYM_PTR(mpv_create) +#define mpv_create pfn_mpv_create +MPV_DEFINE_SYM_PTR(mpv_initialize) +#define mpv_initialize pfn_mpv_initialize +MPV_DEFINE_SYM_PTR(mpv_destroy) +#define mpv_destroy pfn_mpv_destroy +MPV_DEFINE_SYM_PTR(mpv_terminate_destroy) +#define mpv_terminate_destroy pfn_mpv_terminate_destroy +MPV_DEFINE_SYM_PTR(mpv_create_client) +#define mpv_create_client pfn_mpv_create_client +MPV_DEFINE_SYM_PTR(mpv_create_weak_client) +#define mpv_create_weak_client pfn_mpv_create_weak_client +MPV_DEFINE_SYM_PTR(mpv_load_config_file) +#define mpv_load_config_file pfn_mpv_load_config_file +MPV_DEFINE_SYM_PTR(mpv_get_time_ns) +#define mpv_get_time_ns pfn_mpv_get_time_ns +MPV_DEFINE_SYM_PTR(mpv_get_time_us) +#define mpv_get_time_us pfn_mpv_get_time_us +MPV_DEFINE_SYM_PTR(mpv_free_node_contents) +#define mpv_free_node_contents pfn_mpv_free_node_contents +MPV_DEFINE_SYM_PTR(mpv_set_option) +#define mpv_set_option pfn_mpv_set_option +MPV_DEFINE_SYM_PTR(mpv_set_option_string) +#define mpv_set_option_string pfn_mpv_set_option_string +MPV_DEFINE_SYM_PTR(mpv_command) +#define mpv_command pfn_mpv_command +MPV_DEFINE_SYM_PTR(mpv_command_node) +#define mpv_command_node pfn_mpv_command_node +MPV_DEFINE_SYM_PTR(mpv_command_ret) +#define mpv_command_ret pfn_mpv_command_ret +MPV_DEFINE_SYM_PTR(mpv_command_string) +#define mpv_command_string pfn_mpv_command_string +MPV_DEFINE_SYM_PTR(mpv_command_async) +#define mpv_command_async pfn_mpv_command_async +MPV_DEFINE_SYM_PTR(mpv_command_node_async) +#define mpv_command_node_async pfn_mpv_command_node_async +MPV_DEFINE_SYM_PTR(mpv_abort_async_command) +#define mpv_abort_async_command pfn_mpv_abort_async_command +MPV_DEFINE_SYM_PTR(mpv_set_property) +#define mpv_set_property pfn_mpv_set_property +MPV_DEFINE_SYM_PTR(mpv_set_property_string) +#define mpv_set_property_string pfn_mpv_set_property_string +MPV_DEFINE_SYM_PTR(mpv_del_property) +#define mpv_del_property pfn_mpv_del_property +MPV_DEFINE_SYM_PTR(mpv_set_property_async) +#define mpv_set_property_async pfn_mpv_set_property_async +MPV_DEFINE_SYM_PTR(mpv_get_property) +#define mpv_get_property pfn_mpv_get_property +MPV_DEFINE_SYM_PTR(mpv_get_property_string) +#define mpv_get_property_string pfn_mpv_get_property_string +MPV_DEFINE_SYM_PTR(mpv_get_property_osd_string) +#define mpv_get_property_osd_string pfn_mpv_get_property_osd_string +MPV_DEFINE_SYM_PTR(mpv_get_property_async) +#define mpv_get_property_async pfn_mpv_get_property_async +MPV_DEFINE_SYM_PTR(mpv_observe_property) +#define mpv_observe_property pfn_mpv_observe_property +MPV_DEFINE_SYM_PTR(mpv_unobserve_property) +#define mpv_unobserve_property pfn_mpv_unobserve_property +MPV_DEFINE_SYM_PTR(mpv_event_name) +#define mpv_event_name pfn_mpv_event_name +MPV_DEFINE_SYM_PTR(mpv_event_to_node) +#define mpv_event_to_node pfn_mpv_event_to_node +MPV_DEFINE_SYM_PTR(mpv_request_event) +#define mpv_request_event pfn_mpv_request_event +MPV_DEFINE_SYM_PTR(mpv_request_log_messages) +#define mpv_request_log_messages pfn_mpv_request_log_messages +MPV_DEFINE_SYM_PTR(mpv_wait_event) +#define mpv_wait_event pfn_mpv_wait_event +MPV_DEFINE_SYM_PTR(mpv_wakeup) +#define mpv_wakeup pfn_mpv_wakeup +MPV_DEFINE_SYM_PTR(mpv_set_wakeup_callback) +#define mpv_set_wakeup_callback pfn_mpv_set_wakeup_callback +MPV_DEFINE_SYM_PTR(mpv_wait_async_requests) +#define mpv_wait_async_requests pfn_mpv_wait_async_requests +MPV_DEFINE_SYM_PTR(mpv_hook_add) +#define mpv_hook_add pfn_mpv_hook_add +MPV_DEFINE_SYM_PTR(mpv_hook_continue) +#define mpv_hook_continue pfn_mpv_hook_continue +MPV_DEFINE_SYM_PTR(mpv_get_wakeup_pipe) +#define mpv_get_wakeup_pipe pfn_mpv_get_wakeup_pipe + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/android/libmpv/src/main/cpp/include/mpv/render.h b/android/libmpv/src/main/cpp/include/mpv/render.h new file mode 100644 index 000000000..99aadeb5d --- /dev/null +++ b/android/libmpv/src/main/cpp/include/mpv/render.h @@ -0,0 +1,760 @@ +/* Copyright (C) 2018 the mpv developers + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef MPV_CLIENT_API_RENDER_H_ +#define MPV_CLIENT_API_RENDER_H_ + +#include "client.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Overview + * -------- + * + * This API can be used to make mpv render using supported graphic APIs (such + * as OpenGL). It can be used to handle video display. + * + * The renderer needs to be created with mpv_render_context_create() before + * you start playback (or otherwise cause a VO to be created). Then (with most + * backends) mpv_render_context_render() can be used to explicitly render the + * current video frame. Use mpv_render_context_set_update_callback() to get + * notified when there is a new frame to draw. + * + * Preferably rendering should be done in a separate thread. If you call + * normal libmpv API functions on the renderer thread, deadlocks can result + * (these are made non-fatal with timeouts, but user experience will obviously + * suffer). See "Threading" section below. + * + * You can output and embed video without this API by setting the mpv "wid" + * option to a native window handle (see "Embedding the video window" section + * in the client.h header). In general, using the render API is recommended, + * because window embedding can cause various issues, especially with GUI + * toolkits and certain platforms. + * + * Supported backends + * ------------------ + * + * OpenGL: via MPV_RENDER_API_TYPE_OPENGL, see render_gl.h header. + * Software: via MPV_RENDER_API_TYPE_SW, see section "Software renderer" + * + * Threading + * --------- + * + * You are recommended to do rendering on a separate thread than normal libmpv + * use. + * + * The mpv_render_* functions can be called from any thread, under the + * following conditions: + * - only one of the mpv_render_* functions can be called at the same time + * (unless they belong to different mpv cores created by mpv_create()) + * - never can be called from within the callbacks set with + * mpv_set_wakeup_callback() or mpv_render_context_set_update_callback() + * - if the OpenGL backend is used, for all functions the OpenGL context + * must be "current" in the calling thread, and it must be the same OpenGL + * context as the mpv_render_context was created with. Otherwise, undefined + * behavior will occur. + * - the thread does not call libmpv API functions other than the mpv_render_* + * functions, except APIs which are declared as safe (see below). Likewise, + * there must be no lock or wait dependency from the render thread to a + * thread using other libmpv functions. Basically, the situation that your + * render thread waits for a "not safe" libmpv API function to return must + * not happen. If you ignore this requirement, deadlocks can happen, which + * are made non-fatal with timeouts; then playback quality will be degraded, + * and the message + * mpv_render_context_render() not being called or stuck. + * is logged. If you set MPV_RENDER_PARAM_ADVANCED_CONTROL, you promise that + * this won't happen, and must absolutely guarantee it, or a real deadlock + * will freeze the mpv core thread forever. + * + * libmpv functions which are safe to call from a render thread are: + * - functions marked with "Safe to be called from mpv render API threads." + * - client.h functions which don't have an explicit or implicit mpv_handle + * parameter + * - mpv_render_* functions; but only for the same mpv_render_context pointer. + * If the pointer is different, mpv_render_context_free() is not safe. (The + * reason is that if MPV_RENDER_PARAM_ADVANCED_CONTROL is set, it may have + * to process still queued requests from the core, which it can do only for + * the current context, while requests for other contexts would deadlock. + * Also, it may have to wait and block for the core to terminate the video + * chain to make sure no resources are used after context destruction.) + * - if the mpv_handle parameter refers to a different mpv core than the one + * you're rendering for (very obscure, but allowed) + * + * Note about old libmpv version: + * + * Before API version 1.105 (basically in mpv 0.29.x), simply enabling + * MPV_RENDER_PARAM_ADVANCED_CONTROL could cause deadlock issues. This can + * be worked around by setting the "vd-lavc-dr" option to "no". + * In addition, you were required to call all mpv_render*() API functions + * from the same thread on which mpv_render_context_create() was originally + * run (for the same the mpv_render_context). Not honoring it led to UB + * (deadlocks, use of invalid mp_thread handles), even if you moved your GL + * context to a different thread correctly. + * These problems were addressed in API version 1.105 (mpv 0.30.0). + * + * Context and handle lifecycle + * ---------------------------- + * + * Video initialization will fail if the render context was not initialized yet + * (with mpv_render_context_create()), or it will revert to a VO that creates + * its own window. + * + * Currently, there can be only 1 mpv_render_context at a time per mpv core. + * + * Calling mpv_render_context_free() while a VO is using the render context is + * active will disable video. + * + * You must free the context with mpv_render_context_free() before the mpv core + * is destroyed. If this doesn't happen, undefined behavior will result. + * + * Software renderer + * ----------------- + * + * MPV_RENDER_API_TYPE_SW provides an extremely simple (but slow) renderer to + * memory surfaces. You probably don't want to use this. Use other render API + * types, or other methods of video embedding. + * + * Use mpv_render_context_create() with MPV_RENDER_PARAM_API_TYPE set to + * MPV_RENDER_API_TYPE_SW. + * + * Call mpv_render_context_render() with various MPV_RENDER_PARAM_SW_* fields + * to render the video frame to an in-memory surface. The following fields are + * required: MPV_RENDER_PARAM_SW_SIZE, MPV_RENDER_PARAM_SW_FORMAT, + * MPV_RENDER_PARAM_SW_STRIDE, MPV_RENDER_PARAM_SW_POINTER. + * + * This method of rendering is very slow, because everything, including color + * conversion, scaling, and OSD rendering, is done on the CPU, single-threaded. + * In particular, large video or display sizes, as well as presence of OSD or + * subtitles can make it too slow for realtime. As with other software rendering + * VOs, setting "sw-fast" may help. Enabling or disabling zimg may help, + * depending on the platform. + * + * In addition, certain multimedia job creation measures like HDR may not work + * properly, and will have to be manually handled by for example inserting + * filters. + * + * This API is not really suitable to extract individual frames from video etc. + * (basically non-playback uses) - there are better libraries for this. It can + * be used this way, but it may be clunky and tricky. + * + * Further notes: + * - MPV_RENDER_PARAM_FLIP_Y is currently ignored (unsupported) + * - MPV_RENDER_PARAM_DEPTH is ignored (meaningless) + */ + +/** + * Opaque context, returned by mpv_render_context_create(). + */ +typedef struct mpv_render_context mpv_render_context; + +/** + * Parameters for mpv_render_param (which is used in a few places such as + * mpv_render_context_create(). + * + * Also see mpv_render_param for conventions and how to use it. + */ +typedef enum mpv_render_param_type { + /** + * Not a valid value, but also used to terminate a params array. Its value + * is always guaranteed to be 0 (even if the ABI changes in the future). + */ + MPV_RENDER_PARAM_INVALID = 0, + /** + * The render API to use. Valid for mpv_render_context_create(). + * + * Type: char* + * + * Defined APIs: + * + * MPV_RENDER_API_TYPE_OPENGL: + * OpenGL desktop 2.1 or later (preferably core profile compatible to + * OpenGL 3.2), or OpenGLES 2.0 or later. + * Providing MPV_RENDER_PARAM_OPENGL_INIT_PARAMS is required. + * It is expected that an OpenGL context is valid and "current" when + * calling mpv_render_* functions (unless specified otherwise). It + * must be the same context for the same mpv_render_context. + */ + MPV_RENDER_PARAM_API_TYPE = 1, + /** + * Required parameters for initializing the OpenGL renderer. Valid for + * mpv_render_context_create(). + * Type: mpv_opengl_init_params* + */ + MPV_RENDER_PARAM_OPENGL_INIT_PARAMS = 2, + /** + * Describes a GL render target. Valid for mpv_render_context_render(). + * Type: mpv_opengl_fbo* + */ + MPV_RENDER_PARAM_OPENGL_FBO = 3, + /** + * Control flipped rendering. Valid for mpv_render_context_render(). + * Type: int* + * If the value is set to 0, render normally. Otherwise, render it flipped, + * which is needed e.g. when rendering to an OpenGL default framebuffer + * (which has a flipped coordinate system). + */ + MPV_RENDER_PARAM_FLIP_Y = 4, + /** + * Control surface depth. Valid for mpv_render_context_render(). + * Type: int* + * This implies the depth of the surface passed to the render function in + * bits per channel. If omitted or set to 0, the renderer will assume 8. + * Typically used to control dithering. + */ + MPV_RENDER_PARAM_DEPTH = 5, + /** + * ICC profile blob. Valid for mpv_render_context_set_parameter(). + * Type: mpv_byte_array* + * Set an ICC profile for use with the "icc-profile-auto" option. (If the + * option is not enabled, the ICC data will not be used.) + */ + MPV_RENDER_PARAM_ICC_PROFILE = 6, + /** + * Deprecated + * Ambient light in lux. Valid for mpv_render_context_set_parameter(). + * Type: int* + * This can be used for automatic gamma correction. + */ + MPV_RENDER_PARAM_AMBIENT_LIGHT = 7, + /** + * X11 Display, sometimes used for hwdec. Valid for + * mpv_render_context_create(). The Display must stay valid for the lifetime + * of the mpv_render_context. + * Type: Display* + */ + MPV_RENDER_PARAM_X11_DISPLAY = 8, + /** + * Wayland display, sometimes used for hwdec. Valid for + * mpv_render_context_create(). The wl_display must stay valid for the + * lifetime of the mpv_render_context. + * Type: struct wl_display* + */ + MPV_RENDER_PARAM_WL_DISPLAY = 9, + /** + * Better control about rendering and enabling some advanced features. Valid + * for mpv_render_context_create(). + * + * This conflates multiple requirements the API user promises to abide if + * this option is enabled: + * + * - The API user's render thread, which is calling the mpv_render_*() + * functions, never waits for the core. Otherwise deadlocks can happen. + * See "Threading" section. + * - The callback set with mpv_render_context_set_update_callback() can now + * be called even if there is no new frame. The API user should call the + * mpv_render_context_update() function, and interpret the return value + * for whether a new frame should be rendered. + * - Correct functionality is impossible if the update callback is not set, + * or not set soon enough after mpv_render_context_create() (the core can + * block while waiting for you to call mpv_render_context_update(), and + * if the update callback is not correctly set, it will deadlock, or + * block for too long). + * + * In general, setting this option will enable the following features (and + * possibly more): + * + * - "Direct rendering", which means the player decodes directly to a + * texture, which saves a copy per video frame ("vd-lavc-dr" option + * needs to be enabled, and the rendering backend as well as the + * underlying GPU API/driver needs to have support for it). + * - Rendering screenshots with the GPU API if supported by the backend + * (instead of using a suboptimal software fallback via libswscale). + * + * Warning: do not just add this without reading the "Threading" section + * above, and then wondering that deadlocks happen. The + * requirements are tricky. But also note that even if advanced + * control is disabled, not adhering to the rules will lead to + * playback problems. Enabling advanced controls simply makes + * violating these rules fatal. + * + * Type: int*: 0 for disable (default), 1 for enable + */ + MPV_RENDER_PARAM_ADVANCED_CONTROL = 10, + /** + * Return information about the next frame to render. Valid for + * mpv_render_context_get_info(). + * + * Type: mpv_render_frame_info* + * + * It strictly returns information about the _next_ frame. The implication + * is that e.g. mpv_render_context_update()'s return value will have + * MPV_RENDER_UPDATE_FRAME set, and the user is supposed to call + * mpv_render_context_render(). If there is no next frame, then the + * return value will have is_valid set to 0. + */ + MPV_RENDER_PARAM_NEXT_FRAME_INFO = 11, + /** + * Enable or disable video timing. Valid for mpv_render_context_render(). + * + * Type: int*: 0 for disable, 1 for enable (default) + * + * When video is timed to audio, the player attempts to render video a bit + * ahead, and then do a blocking wait until the target display time is + * reached. This blocks mpv_render_context_render() for up to the amount + * specified with the "video-timing-offset" global option. You can set + * this parameter to 0 to disable this kind of waiting. If you do, it's + * recommended to use the target time value in mpv_render_frame_info to + * wait yourself, or to set the "video-timing-offset" to 0 instead. + * + * Disabling this without doing anything in addition will result in A/V sync + * being slightly off. + */ + MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME = 12, + /** + * Use to skip rendering in mpv_render_context_render(). + * + * Type: int*: 0 for rendering (default), 1 for skipping + * + * If this is set, you don't need to pass a target surface to the render + * function (and if you do, it's completely ignored). This can still call + * into the lower level APIs (i.e. if you use OpenGL, the OpenGL context + * must be set). + * + * Be aware that the render API will consider this frame as having been + * rendered. All other normal rules also apply, for example about whether + * you have to call mpv_render_context_report_swap(). It also does timing + * in the same way. + */ + MPV_RENDER_PARAM_SKIP_RENDERING = 13, + /** + * Deprecated. Not supported. Use MPV_RENDER_PARAM_DRM_DISPLAY_V2 instead. + * Type : struct mpv_opengl_drm_params* + */ + MPV_RENDER_PARAM_DRM_DISPLAY = 14, + /** + * DRM draw surface size, contains draw surface dimensions. + * Valid for mpv_render_context_create(). + * Type : struct mpv_opengl_drm_draw_surface_size* + */ + MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE = 15, + /** + * DRM display, contains drm display handles. + * Valid for mpv_render_context_create(). + * Type : struct mpv_opengl_drm_params_v2* + */ + MPV_RENDER_PARAM_DRM_DISPLAY_V2 = 16, + /** + * MPV_RENDER_API_TYPE_SW only: rendering target surface size, mandatory. + * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render(). + * Type: int[2] (e.g.: int s[2] = {w, h}; param.data = &s[0];) + * + * The video frame is transformed as with other VOs. Typically, this means + * the video gets scaled and black bars are added if the video size or + * aspect ratio mismatches with the target size. + */ + MPV_RENDER_PARAM_SW_SIZE = 17, + /** + * MPV_RENDER_API_TYPE_SW only: rendering target surface pixel format, + * mandatory. + * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render(). + * Type: char* (e.g.: char *f = "rgb0"; param.data = f;) + * + * Valid values are: + * "rgb0", "bgr0", "0bgr", "0rgb" + * 4 bytes per pixel RGB, 1 byte (8 bit) per component, component bytes + * with increasing address from left to right (e.g. "rgb0" has r at + * address 0), the "0" component contains uninitialized garbage (often + * the value 0, but not necessarily; the bad naming is inherited from + * FFmpeg) + * Pixel alignment size: 4 bytes + * "rgb24" + * 3 bytes per pixel RGB. This is strongly discouraged because it is + * very slow. + * Pixel alignment size: 1 bytes + * other + * The API may accept other pixel formats, using mpv internal format + * names, as long as it's internally marked as RGB, has exactly 1 + * plane, and is supported as conversion output. It is not a good idea + * to rely on any of these. Their semantics and handling could change. + */ + MPV_RENDER_PARAM_SW_FORMAT = 18, + /** + * MPV_RENDER_API_TYPE_SW only: rendering target surface bytes per line, + * mandatory. + * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render(). + * Type: size_t* + * + * This is the number of bytes between a pixel (x, y) and (x, y + 1) on the + * target surface. It must be a multiple of the pixel size, and have space + * for the surface width as specified by MPV_RENDER_PARAM_SW_SIZE. + * + * Both stride and pointer value should be a multiple of 64 to facilitate + * fast SIMD operation. Lower alignment might trigger slower code paths, + * and in the worst case, will copy the entire target frame. If mpv is built + * with zimg (and zimg is not disabled), the performance impact might be + * less. + * In either cases, the pointer and stride must be aligned at least to the + * pixel alignment size. Otherwise, crashes and undefined behavior is + * possible on platforms which do not support unaligned accesses (either + * through normal memory access or aligned SIMD memory access instructions). + */ + MPV_RENDER_PARAM_SW_STRIDE = 19, + /* + * MPV_RENDER_API_TYPE_SW only: rendering target surface pixel data pointer, + * mandatory. + * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render(). + * Type: void* + * + * This points to the first pixel at the left/top corner (0, 0). In + * particular, each line y starts at (pointer + stride * y). Upon rendering, + * all data between pointer and (pointer + stride * h) is overwritten. + * Whether the padding between (w, y) and (0, y + 1) is overwritten is left + * unspecified (it should not be, but unfortunately some scaler backends + * will do it anyway). It is assumed that even the padding after the last + * line (starting at bytepos(w, h) until (pointer + stride * h)) is + * writable. + * + * See MPV_RENDER_PARAM_SW_STRIDE for alignment requirements. + */ + MPV_RENDER_PARAM_SW_POINTER = 20, +} mpv_render_param_type; + +/** + * For backwards compatibility with the old naming of + * MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE + */ +#define MPV_RENDER_PARAM_DRM_OSD_SIZE MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE + +/** + * Used to pass arbitrary parameters to some mpv_render_* functions. The + * meaning of the data parameter is determined by the type, and each + * MPV_RENDER_PARAM_* documents what type the value must point to. + * + * Each value documents the required data type as the pointer you cast to + * void* and set on mpv_render_param.data. For example, if MPV_RENDER_PARAM_FOO + * documents the type as Something* , then the code should look like this: + * + * Something foo = {...}; + * mpv_render_param param; + * param.type = MPV_RENDER_PARAM_FOO; + * param.data = & foo; + * + * Normally, the data field points to exactly 1 object. If the type is char*, + * it points to a 0-terminated string. + * + * In all cases (unless documented otherwise) the pointers need to remain + * valid during the call only. Unless otherwise documented, the API functions + * will not write to the params array or any data pointed to it. + * + * As a convention, parameter arrays are always terminated by type==0. There + * is no specific order of the parameters required. The order of the 2 fields in + * this struct is guaranteed (even after ABI changes). + */ +typedef struct mpv_render_param { + enum mpv_render_param_type type; + void *data; +} mpv_render_param; + + +/** + * Predefined values for MPV_RENDER_PARAM_API_TYPE. + */ +// See render_gl.h +#define MPV_RENDER_API_TYPE_OPENGL "opengl" +// See section "Software renderer" +#define MPV_RENDER_API_TYPE_SW "sw" + +/** + * Flags used in mpv_render_frame_info.flags. Each value represents a bit in it. + */ +typedef enum mpv_render_frame_info_flag { + /** + * Set if there is actually a next frame. If unset, there is no next frame + * yet, and other flags and fields that require a frame to be queued will + * be unset. + * + * This is set for _any_ kind of frame, even for redraw requests. + * + * Note that when this is unset, it simply means no new frame was + * decoded/queued yet, not necessarily that the end of the video was + * reached. A new frame can be queued after some time. + * + * If the return value of mpv_render_context_render() had the + * MPV_RENDER_UPDATE_FRAME flag set, this flag will usually be set as well, + * unless the frame is rendered, or discarded by other asynchronous events. + */ + MPV_RENDER_FRAME_INFO_PRESENT = 1 << 0, + /** + * If set, the frame is not an actual new video frame, but a redraw request. + * For example if the video is paused, and an option that affects video + * rendering was changed (or any other reason), an update request can be + * issued and this flag will be set. + * + * Typically, redraw frames will not be subject to video timing. + * + * Implies MPV_RENDER_FRAME_INFO_PRESENT. + */ + MPV_RENDER_FRAME_INFO_REDRAW = 1 << 1, + /** + * If set, this is supposed to reproduce the previous frame perfectly. This + * is usually used for certain "video-sync" options ("display-..." modes). + * Typically the renderer will blit the video from a FBO. Unset otherwise. + * + * Implies MPV_RENDER_FRAME_INFO_PRESENT. + */ + MPV_RENDER_FRAME_INFO_REPEAT = 1 << 2, + /** + * If set, the player timing code expects that the user thread blocks on + * vsync (by either delaying the render call, or by making a call to + * mpv_render_context_report_swap() at vsync time). + * + * Implies MPV_RENDER_FRAME_INFO_PRESENT. + */ + MPV_RENDER_FRAME_INFO_BLOCK_VSYNC = 1 << 3, +} mpv_render_frame_info_flag; + +/** + * Information about the next video frame that will be rendered. Can be + * retrieved with MPV_RENDER_PARAM_NEXT_FRAME_INFO. + */ +typedef struct mpv_render_frame_info { + /** + * A bitset of mpv_render_frame_info_flag values (i.e. multiple flags are + * combined with bitwise or). + */ + uint64_t flags; + /** + * Absolute time at which the frame is supposed to be displayed. This is in + * the same unit and base as the time returned by mpv_get_time_us(). For + * frames that are redrawn, or if vsync locked video timing is used (see + * "video-sync" option), then this can be 0. The "video-timing-offset" + * option determines how much "headroom" the render thread gets (but a high + * enough frame rate can reduce it anyway). mpv_render_context_render() will + * normally block until the time is elapsed, unless you pass it + * MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME = 0. + */ + int64_t target_time; +} mpv_render_frame_info; + +/** + * Initialize the renderer state. Depending on the backend used, this will + * access the underlying GPU API and initialize its own objects. + * + * You must free the context with mpv_render_context_free(). Not doing so before + * the mpv core is destroyed may result in memory leaks or crashes. + * + * Currently, only at most 1 context can exists per mpv core (it represents the + * main video output). + * + * You should pass the following parameters: + * - MPV_RENDER_PARAM_API_TYPE to select the underlying backend/GPU API. + * - Backend-specific init parameter, like MPV_RENDER_PARAM_OPENGL_INIT_PARAMS. + * - Setting MPV_RENDER_PARAM_ADVANCED_CONTROL and following its rules is + * strongly recommended. + * - If you want to use hwdec, possibly hwdec interop resources. + * + * @param res set to the context (on success) or NULL (on failure). The value + * is never read and always overwritten. + * @param mpv handle used to get the core (the mpv_render_context won't depend + * on this specific handle, only the core referenced by it) + * @param params an array of parameters, terminated by type==0. It's left + * unspecified what happens with unknown parameters. At least + * MPV_RENDER_PARAM_API_TYPE is required, and most backends will + * require another backend-specific parameter. + * @return error code, including but not limited to: + * MPV_ERROR_UNSUPPORTED: the OpenGL version is not supported + * (or required extensions are missing) + * MPV_ERROR_NOT_IMPLEMENTED: an unknown API type was provided, or + * support for the requested API was not + * built in the used libmpv binary. + * MPV_ERROR_INVALID_PARAMETER: at least one of the provided parameters was + * not valid. + */ +MPV_EXPORT int mpv_render_context_create(mpv_render_context **res, mpv_handle *mpv, + mpv_render_param *params); + +/** + * Attempt to change a single parameter. Not all backends and parameter types + * support all kinds of changes. + * + * @param ctx a valid render context + * @param param the parameter type and data that should be set + * @return error code. If a parameter could actually be changed, this returns + * success, otherwise an error code depending on the parameter type + * and situation. + */ +MPV_EXPORT int mpv_render_context_set_parameter(mpv_render_context *ctx, + mpv_render_param param); + +/** + * Retrieve information from the render context. This is NOT a counterpart to + * mpv_render_context_set_parameter(), because you generally can't read + * parameters set with it, and this function is not meant for this purpose. + * Instead, this is for communicating information from the renderer back to the + * user. See mpv_render_param_type; entries which support this function + * explicitly mention it, and for other entries you can assume it will fail. + * + * You pass param with param.type set and param.data pointing to a variable + * of the required data type. The function will then overwrite that variable + * with the returned value (at least on success). + * + * @param ctx a valid render context + * @param param the parameter type and data that should be retrieved + * @return error code. If a parameter could actually be retrieved, this returns + * success, otherwise an error code depending on the parameter type + * and situation. MPV_ERROR_NOT_IMPLEMENTED is used for unknown + * param.type, or if retrieving it is not supported. + */ +MPV_EXPORT int mpv_render_context_get_info(mpv_render_context *ctx, + mpv_render_param param); + +typedef void (*mpv_render_update_fn)(void *cb_ctx); + +/** + * Set the callback that notifies you when a new video frame is available, or + * if the video display configuration somehow changed and requires a redraw. + * Similar to mpv_set_wakeup_callback(), you must not call any mpv API from + * the callback, and all the other listed restrictions apply (such as not + * exiting the callback by throwing exceptions). + * + * This can be called from any thread, except from an update callback. In case + * of the OpenGL backend, no OpenGL state or API is accessed. + * + * Calling this will raise an update callback immediately. + * + * @param callback callback(callback_ctx) is called if the frame should be + * redrawn + * @param callback_ctx opaque argument to the callback + */ +MPV_EXPORT void mpv_render_context_set_update_callback(mpv_render_context *ctx, + mpv_render_update_fn callback, + void *callback_ctx); + +/** + * The API user is supposed to call this when the update callback was invoked + * (like all mpv_render_* functions, this has to happen on the render thread, + * and _not_ from the update callback itself). + * + * This is optional if MPV_RENDER_PARAM_ADVANCED_CONTROL was not set (default). + * Otherwise, it's a hard requirement that this is called after each update + * callback. If multiple update callback happened, and the function could not + * be called sooner, it's OK to call it once after the last callback. + * + * If an update callback happens during or after this function, the function + * must be called again at the soonest possible time. + * + * If MPV_RENDER_PARAM_ADVANCED_CONTROL was set, this will do additional work + * such as allocating textures for the video decoder. + * + * @return a bitset of mpv_render_update_flag values (i.e. multiple flags are + * combined with bitwise or). Typically, this will tell the API user + * what should happen next. E.g. if the MPV_RENDER_UPDATE_FRAME flag is + * set, mpv_render_context_render() should be called. If flags unknown + * to the API user are set, or if the return value is 0, nothing needs + * to be done. + */ +MPV_EXPORT uint64_t mpv_render_context_update(mpv_render_context *ctx); + +/** + * Flags returned by mpv_render_context_update(). Each value represents a bit + * in the function's return value. + */ +typedef enum mpv_render_update_flag { + /** + * A new video frame must be rendered. mpv_render_context_render() must be + * called. + */ + MPV_RENDER_UPDATE_FRAME = 1 << 0, +} mpv_render_context_flag; + +/** + * Render video. + * + * Typically renders the video to a target surface provided via mpv_render_param + * (the details depend on the backend in use). Options like "panscan" are + * applied to determine which part of the video should be visible and how the + * video should be scaled. You can change these options at runtime by using the + * mpv property API. + * + * The renderer will reconfigure itself every time the target surface + * configuration (such as size) is changed. + * + * This function implicitly pulls a video frame from the internal queue and + * renders it. If no new frame is available, the previous frame is redrawn. + * The update callback set with mpv_render_context_set_update_callback() + * notifies you when a new frame was added. The details potentially depend on + * the backends and the provided parameters. + * + * Generally, libmpv will invoke your update callback some time before the video + * frame should be shown, and then lets this function block until the supposed + * display time. This will limit your rendering to video FPS. You can prevent + * this by setting the "video-timing-offset" global option to 0. (This applies + * only to "audio" video sync mode.) + * + * You should pass the following parameters: + * - Backend-specific target object, such as MPV_RENDER_PARAM_OPENGL_FBO. + * - Possibly transformations, such as MPV_RENDER_PARAM_FLIP_Y. + * + * @param ctx a valid render context + * @param params an array of parameters, terminated by type==0. Which parameters + * are required depends on the backend. It's left unspecified what + * happens with unknown parameters. + * @return error code + */ +MPV_EXPORT int mpv_render_context_render(mpv_render_context *ctx, mpv_render_param *params); + +/** + * Tell the renderer that a frame was flipped at the given time. This is + * optional, but can help the player to achieve better timing. + * + * Note that calling this at least once informs libmpv that you will use this + * function. If you use it inconsistently, expect bad video playback. + * + * If this is called while no video is initialized, it is ignored. + * + * @param ctx a valid render context + */ +MPV_EXPORT void mpv_render_context_report_swap(mpv_render_context *ctx); + +/** + * Destroy the mpv renderer state. + * + * If video is still active (e.g. a file playing), video will be disabled + * forcefully. + * + * @param ctx a valid render context. After this function returns, this is not + * a valid pointer anymore. NULL is also allowed and does nothing. + */ +MPV_EXPORT void mpv_render_context_free(mpv_render_context *ctx); + +#ifdef MPV_CPLUGIN_DYNAMIC_SYM + +MPV_DEFINE_SYM_PTR(mpv_render_context_create) +#define mpv_render_context_create pfn_mpv_render_context_create +MPV_DEFINE_SYM_PTR(mpv_render_context_set_parameter) +#define mpv_render_context_set_parameter pfn_mpv_render_context_set_parameter +MPV_DEFINE_SYM_PTR(mpv_render_context_get_info) +#define mpv_render_context_get_info pfn_mpv_render_context_get_info +MPV_DEFINE_SYM_PTR(mpv_render_context_set_update_callback) +#define mpv_render_context_set_update_callback pfn_mpv_render_context_set_update_callback +MPV_DEFINE_SYM_PTR(mpv_render_context_update) +#define mpv_render_context_update pfn_mpv_render_context_update +MPV_DEFINE_SYM_PTR(mpv_render_context_render) +#define mpv_render_context_render pfn_mpv_render_context_render +MPV_DEFINE_SYM_PTR(mpv_render_context_report_swap) +#define mpv_render_context_report_swap pfn_mpv_render_context_report_swap +MPV_DEFINE_SYM_PTR(mpv_render_context_free) +#define mpv_render_context_free pfn_mpv_render_context_free + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/android/libmpv/src/main/cpp/include/mpv/render_gl.h b/android/libmpv/src/main/cpp/include/mpv/render_gl.h new file mode 100644 index 000000000..aa2719d5c --- /dev/null +++ b/android/libmpv/src/main/cpp/include/mpv/render_gl.h @@ -0,0 +1,211 @@ +/* Copyright (C) 2018 the mpv developers + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef MPV_CLIENT_API_RENDER_GL_H_ +#define MPV_CLIENT_API_RENDER_GL_H_ + +#include "render.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * OpenGL backend + * -------------- + * + * This header contains definitions for using OpenGL with the render.h API. + * + * OpenGL interop + * -------------- + * + * The OpenGL backend has some special rules, because OpenGL itself uses + * implicit per-thread contexts, which causes additional API problems. + * + * This assumes the OpenGL context lives on a certain thread controlled by the + * API user. All mpv_render_* APIs have to be assumed to implicitly use the + * OpenGL context if you pass a mpv_render_context using the OpenGL backend, + * unless specified otherwise. + * + * The OpenGL context is indirectly accessed through the OpenGL function + * pointers returned by the get_proc_address callback in mpv_opengl_init_params. + * Generally, mpv will not load the system OpenGL library when using this API. + * + * OpenGL state + * ------------ + * + * OpenGL has a large amount of implicit state. All the mpv functions mentioned + * above expect that the OpenGL state is reasonably set to OpenGL standard + * defaults. Likewise, mpv will attempt to leave the OpenGL context with + * standard defaults. The following state is excluded from this: + * + * - the glViewport state + * - the glScissor state (but GL_SCISSOR_TEST is in its default value) + * - glBlendFuncSeparate() state (but GL_BLEND is in its default value) + * - glClearColor() state + * - mpv may overwrite the callback set with glDebugMessageCallback() + * - mpv always disables GL_DITHER at init + * + * Messing with the state could be avoided by creating shared OpenGL contexts, + * but this is avoided for the sake of compatibility and interoperability. + * + * On OpenGL 2.1, mpv will strictly call functions like glGenTextures() to + * create OpenGL objects. You will have to do the same. This ensures that + * objects created by mpv and the API users don't clash. Also, legacy state + * must be either in its defaults, or not interfere with core state. + * + * API use + * ------- + * + * The mpv_render_* API is used. That API supports multiple backends, and this + * section documents specifics for the OpenGL backend. + * + * Use mpv_render_context_create() with MPV_RENDER_PARAM_API_TYPE set to + * MPV_RENDER_API_TYPE_OPENGL, and MPV_RENDER_PARAM_OPENGL_INIT_PARAMS provided. + * + * Call mpv_render_context_render() with MPV_RENDER_PARAM_OPENGL_FBO to render + * the video frame to an FBO. + * + * Hardware decoding + * ----------------- + * + * Hardware decoding via this API is fully supported, but requires some + * additional setup. (At least if direct hardware decoding modes are wanted, + * instead of copying back surface data from GPU to CPU RAM.) + * + * There may be certain requirements on the OpenGL implementation: + * + * - Windows: ANGLE is required (although in theory GL/DX interop could be used) + * - Intel/Linux: EGL is required, and also the native display resource needs + * to be provided (e.g. MPV_RENDER_PARAM_X11_DISPLAY for X11 and + * MPV_RENDER_PARAM_WL_DISPLAY for Wayland) + * - nVidia/Linux: Both GLX and EGL should work (GLX is required if vdpau is + * used, e.g. due to old drivers.) + * - macOS: CGL is required (CGLGetCurrentContext() returning non-NULL) + * - iOS: EAGL is required (EAGLContext.currentContext returning non-nil) + * + * Once these things are setup, hardware decoding can be enabled/disabled at + * any time by setting the "hwdec" property. + */ + +/** + * For initializing the mpv OpenGL state via MPV_RENDER_PARAM_OPENGL_INIT_PARAMS. + */ +typedef struct mpv_opengl_init_params { + /** + * This retrieves OpenGL function pointers, and will use them in subsequent + * operation. + * Usually, you can simply call the GL context APIs from this callback (e.g. + * glXGetProcAddressARB or wglGetProcAddress), but some APIs do not always + * return pointers for all standard functions (even if present); in this + * case you have to compensate by looking up these functions yourself when + * libmpv wants to resolve them through this callback. + * libmpv will not normally attempt to resolve GL functions on its own, nor + * does it link to GL libraries directly. + */ + void *(*get_proc_address)(void *ctx, const char *name); + /** + * Value passed as ctx parameter to get_proc_address(). + */ + void *get_proc_address_ctx; +} mpv_opengl_init_params; + +/** + * For MPV_RENDER_PARAM_OPENGL_FBO. + */ +typedef struct mpv_opengl_fbo { + /** + * Framebuffer object name. This must be either a valid FBO generated by + * glGenFramebuffers() that is complete and color-renderable, or 0. If the + * value is 0, this refers to the OpenGL default framebuffer. + */ + int fbo; + /** + * Valid dimensions. This must refer to the size of the framebuffer. This + * must always be set. + */ + int w, h; + /** + * Underlying texture internal format (e.g. GL_RGBA8), or 0 if unknown. If + * this is the default framebuffer, this can be an equivalent. + */ + int internal_format; +} mpv_opengl_fbo; + +/** + * Deprecated. For MPV_RENDER_PARAM_DRM_DISPLAY. + */ +typedef struct mpv_opengl_drm_params { + int fd; + int crtc_id; + int connector_id; + struct _drmModeAtomicReq **atomic_request_ptr; + int render_fd; +} mpv_opengl_drm_params; + +/** + * For MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE. + */ +typedef struct mpv_opengl_drm_draw_surface_size { + /** + * size of the draw plane surface in pixels. + */ + int width, height; +} mpv_opengl_drm_draw_surface_size; + +/** + * For MPV_RENDER_PARAM_DRM_DISPLAY_V2. + */ +typedef struct mpv_opengl_drm_params_v2 { + /** + * DRM fd (int). Set to -1 if invalid. + */ + int fd; + + /** + * Currently used crtc id + */ + int crtc_id; + + /** + * Currently used connector id + */ + int connector_id; + + /** + * Pointer to a drmModeAtomicReq pointer that is being used for the renderloop. + * This pointer should hold a pointer to the atomic request pointer + * The atomic request pointer is usually changed at every renderloop. + */ + struct _drmModeAtomicReq **atomic_request_ptr; + + /** + * DRM render node. Used for VAAPI interop. + * Set to -1 if invalid. + */ + int render_fd; +} mpv_opengl_drm_params_v2; + + +/** + * For backwards compatibility with the old naming of mpv_opengl_drm_draw_surface_size + */ +#define mpv_opengl_drm_osd_size mpv_opengl_drm_draw_surface_size + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/android/libmpv/src/main/cpp/include/mpv/stream_cb.h b/android/libmpv/src/main/cpp/include/mpv/stream_cb.h new file mode 100644 index 000000000..9ae6f31a1 --- /dev/null +++ b/android/libmpv/src/main/cpp/include/mpv/stream_cb.h @@ -0,0 +1,247 @@ +/* Copyright (C) 2017 the mpv developers + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef MPV_CLIENT_API_STREAM_CB_H_ +#define MPV_CLIENT_API_STREAM_CB_H_ + +#include "client.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Warning: this API is not stable yet. + * + * Overview + * -------- + * + * This API can be used to make mpv read from a stream with a custom + * implementation. This interface is inspired by funopen on BSD and + * fopencookie on linux. The stream is backed by user-defined callbacks + * which can implement customized open, read, seek, size and close behaviors. + * + * Usage + * ----- + * + * Register your stream callbacks with the mpv_stream_cb_add_ro() function. You + * have to provide a mpv_stream_cb_open_ro_fn callback to it (open_fn argument). + * + * Once registered, you can `loadfile myprotocol://myfile`. Your open_fn will be + * invoked with the URI and you must fill out the provided mpv_stream_cb_info + * struct. This includes your stream callbacks (like read_fn), and an opaque + * cookie, which will be passed as the first argument to all the remaining + * stream callbacks. + * + * Note that your custom callbacks must not invoke libmpv APIs as that would + * cause a deadlock. (Unless you call a different mpv_handle than the one the + * callback was registered for, and the mpv_handles refer to different mpv + * instances.) + * + * Stream lifetime + * --------------- + * + * A stream remains valid until its close callback has been called. It's up to + * libmpv to call the close callback, and the libmpv user cannot close it + * directly with the stream_cb API. + * + * For example, if you consider your custom stream to become suddenly invalid + * (maybe because the underlying stream died), libmpv will continue using your + * stream. All you can do is returning errors from each callback, until libmpv + * gives up and closes it. + * + * Protocol registration and lifetime + * ---------------------------------- + * + * Protocols remain registered until the mpv instance is terminated. This means + * in particular that it can outlive the mpv_handle that was used to register + * it, but once mpv_terminate_destroy() is called, your registered callbacks + * will not be called again. + * + * Protocol unregistration is finished after the mpv core has been destroyed + * (e.g. after mpv_terminate_destroy() has returned). + * + * If you do not call mpv_terminate_destroy() yourself (e.g. plugin-style code), + * you will have to deal with the registration or even streams outliving your + * code. Here are some possible ways to do this: + * - call mpv_terminate_destroy(), which destroys the core, and will make sure + * all streams are closed once this function returns + * - you refcount all resources your stream "cookies" reference, so that it + * doesn't matter if streams live longer than expected + * - create "cancellation" semantics: after your protocol has been unregistered, + * notify all your streams that are still opened, and make them drop all + * referenced resources - then return errors from the stream callbacks as + * long as the stream is still opened + * + */ + +/** + * Read callback used to implement a custom stream. The semantics of the + * callback match read(2) in blocking mode. Short reads are allowed (you can + * return less bytes than requested, and libmpv will retry reading the rest + * with another call). If no data can be immediately read, the callback must + * block until there is new data. A return of 0 will be interpreted as final + * EOF, although libmpv might retry the read, or seek to a different position. + * + * @param cookie opaque cookie identifying the stream, + * returned from mpv_stream_cb_open_fn + * @param buf buffer to read data into + * @param size of the buffer + * @return number of bytes read into the buffer + * @return 0 on EOF + * @return -1 on error + */ +typedef int64_t (*mpv_stream_cb_read_fn)(void *cookie, char *buf, uint64_t nbytes); + +/** + * Seek callback used to implement a custom stream. + * + * Note that mpv will issue a seek to position 0 immediately after opening. This + * is used to test whether the stream is seekable (since seekability might + * depend on the URI contents, not just the protocol). Return + * MPV_ERROR_UNSUPPORTED if seeking is not implemented for this stream. This + * seek also serves to establish the fact that streams start at position 0. + * + * This callback can be NULL, in which it behaves as if always returning + * MPV_ERROR_UNSUPPORTED. + * + * @param cookie opaque cookie identifying the stream, + * returned from mpv_stream_cb_open_fn + * @param offset target absolute stream position + * @return the resulting offset of the stream + * MPV_ERROR_UNSUPPORTED or MPV_ERROR_GENERIC if the seek failed + */ +typedef int64_t (*mpv_stream_cb_seek_fn)(void *cookie, int64_t offset); + +/** + * Size callback used to implement a custom stream. + * + * Return MPV_ERROR_UNSUPPORTED if no size is known. + * + * This callback can be NULL, in which it behaves as if always returning + * MPV_ERROR_UNSUPPORTED. + * + * @param cookie opaque cookie identifying the stream, + * returned from mpv_stream_cb_open_fn + * @return the total size in bytes of the stream + */ +typedef int64_t (*mpv_stream_cb_size_fn)(void *cookie); + +/** + * Close callback used to implement a custom stream. + * + * @param cookie opaque cookie identifying the stream, + * returned from mpv_stream_cb_open_fn + */ +typedef void (*mpv_stream_cb_close_fn)(void *cookie); + +/** + * Cancel callback used to implement a custom stream. + * + * This callback is used to interrupt any current or future read and seek + * operations. It will be called from a separate thread than the demux + * thread, and should not block. + * + * This callback can be NULL. + * + * Available since API 1.106. + * + * @param cookie opaque cookie identifying the stream, + * returned from mpv_stream_cb_open_fn + */ +typedef void (*mpv_stream_cb_cancel_fn)(void *cookie); + +/** + * See mpv_stream_cb_open_ro_fn callback. + */ +typedef struct mpv_stream_cb_info { + /** + * Opaque user-provided value, which will be passed to the other callbacks. + * The close callback will be called to release the cookie. It is not + * interpreted by mpv. It doesn't even need to be a valid pointer. + * + * The user sets this in the mpv_stream_cb_open_ro_fn callback. + */ + void *cookie; + + /** + * Callbacks set by the user in the mpv_stream_cb_open_ro_fn callback. Some + * of them are optional, and can be left unset. + * + * The following callbacks are mandatory: read_fn, close_fn + */ + mpv_stream_cb_read_fn read_fn; + mpv_stream_cb_seek_fn seek_fn; + mpv_stream_cb_size_fn size_fn; + mpv_stream_cb_close_fn close_fn; + mpv_stream_cb_cancel_fn cancel_fn; /* since API 1.106 */ +} mpv_stream_cb_info; + +/** + * Open callback used to implement a custom read-only (ro) stream. The user + * must set the callback fields in the passed info struct. The cookie field + * also can be set to store state associated to the stream instance. + * + * Note that the info struct is valid only for the duration of this callback. + * You can't change the callbacks or the pointer to the cookie at a later point. + * + * Each stream instance created by the open callback can have different + * callbacks. + * + * The close_fn callback will terminate the stream instance. The pointers to + * your callbacks and cookie will be discarded, and the callbacks will not be + * called again. + * + * @param user_data opaque user data provided via mpv_stream_cb_add() + * @param uri name of the stream to be opened (with protocol prefix) + * @param info fields which the user should fill + * @return 0 on success, MPV_ERROR_LOADING_FAILED if the URI cannot be opened. + */ +typedef int (*mpv_stream_cb_open_ro_fn)(void *user_data, char *uri, + mpv_stream_cb_info *info); + +/** + * Add a custom stream protocol. This will register a protocol handler under + * the given protocol prefix, and invoke the given callbacks if an URI with the + * matching protocol prefix is opened. + * + * The "ro" is for read-only - only read-only streams can be registered with + * this function. + * + * The callback remains registered until the mpv core is registered. + * + * If a custom stream with the same name is already registered, then the + * MPV_ERROR_INVALID_PARAMETER error is returned. + * + * @param protocol protocol prefix, for example "foo" for "foo://" URIs + * @param user_data opaque pointer passed into the mpv_stream_cb_open_fn + * callback. + * @return error code + */ +MPV_EXPORT int mpv_stream_cb_add_ro(mpv_handle *ctx, const char *protocol, void *user_data, + mpv_stream_cb_open_ro_fn open_fn); + +#ifdef MPV_CPLUGIN_DYNAMIC_SYM + +MPV_DEFINE_SYM_PTR(mpv_stream_cb_add_ro) +#define mpv_stream_cb_add_ro pfn_mpv_stream_cb_add_ro + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/android/libmpv/src/main/cpp/jni_utils.cpp b/android/libmpv/src/main/cpp/jni_utils.cpp new file mode 100644 index 000000000..5cc93033e --- /dev/null +++ b/android/libmpv/src/main/cpp/jni_utils.cpp @@ -0,0 +1,51 @@ +#define UTIL_EXTERN +#include "jni_utils.h" + +#include + +#include + +bool acquire_jni_env(JavaVM* vm, JNIEnv** env) { + int ret = vm->GetEnv((void**)env, JNI_VERSION_1_6); + if (ret == JNI_EDETACHED) + return vm->AttachCurrentThread(env, NULL) == 0; + else + return ret == JNI_OK; +} + +void init_methods_cache(JNIEnv* env) { + static bool methods_initialized = false; + if (methods_initialized) return; + + // Plain assignments straight from env->FindClass, promoted to global refs + // on the following line, keep every Get*MethodID owner traceable for + // scripts/checks/check_shrinker_rules.py. + java_Integer = env->FindClass("java/lang/Integer"); + java_Integer = reinterpret_cast(env->NewGlobalRef(java_Integer)); + java_Integer_init = env->GetMethodID(java_Integer, "", "(I)V"); + java_Double = env->FindClass("java/lang/Double"); + java_Double = reinterpret_cast(env->NewGlobalRef(java_Double)); + java_Double_init = env->GetMethodID(java_Double, "", "(D)V"); + java_Boolean = env->FindClass("java/lang/Boolean"); + java_Boolean = reinterpret_cast(env->NewGlobalRef(java_Boolean)); + java_Boolean_init = env->GetMethodID(java_Boolean, "", "(Z)V"); + + mpv_MpvPlayer = env->FindClass("com/edde746/plezy/libmpv/MpvPlayer"); + mpv_MpvPlayer = reinterpret_cast(env->NewGlobalRef(mpv_MpvPlayer)); + mpv_MpvPlayer_onPropertyChanged_S = + env->GetStaticMethodID(mpv_MpvPlayer, "onPropertyChanged", "(Ljava/lang/String;)V"); + mpv_MpvPlayer_onPropertyChanged_Sb = + env->GetStaticMethodID(mpv_MpvPlayer, "onPropertyChanged", "(Ljava/lang/String;Z)V"); + mpv_MpvPlayer_onPropertyChanged_Sl = + env->GetStaticMethodID(mpv_MpvPlayer, "onPropertyChanged", "(Ljava/lang/String;J)V"); + mpv_MpvPlayer_onPropertyChanged_Sd = + env->GetStaticMethodID(mpv_MpvPlayer, "onPropertyChanged", "(Ljava/lang/String;D)V"); + mpv_MpvPlayer_onPropertyChanged_SS = + env->GetStaticMethodID(mpv_MpvPlayer, "onPropertyChanged", "(Ljava/lang/String;Ljava/lang/String;)V"); + mpv_MpvPlayer_onEvent = env->GetStaticMethodID(mpv_MpvPlayer, "onEvent", "(I)V"); + mpv_MpvPlayer_onEndFile = env->GetStaticMethodID(mpv_MpvPlayer, "onEndFile", "(I)V"); + mpv_MpvPlayer_onLogMessage = + env->GetStaticMethodID(mpv_MpvPlayer, "onLogMessage", "(Ljava/lang/String;ILjava/lang/String;)V"); + + methods_initialized = true; +} diff --git a/android/libmpv/src/main/cpp/jni_utils.h b/android/libmpv/src/main/cpp/jni_utils.h new file mode 100644 index 000000000..69945fe8f --- /dev/null +++ b/android/libmpv/src/main/cpp/jni_utils.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +#define jni_func_name(name) Java_com_edde746_plezy_libmpv_MpvPlayer_##name +#define jni_func(return_type, name, ...) \ + JNIEXPORT return_type JNICALL jni_func_name(name)(JNIEnv * env, jobject obj, ##__VA_ARGS__) + +bool acquire_jni_env(JavaVM* vm, JNIEnv** env); +void init_methods_cache(JNIEnv* env); + +#ifndef UTIL_EXTERN +#define UTIL_EXTERN extern +#endif + +UTIL_EXTERN jclass java_Integer, java_Double, java_Boolean; +UTIL_EXTERN jmethodID java_Integer_init, java_Double_init, java_Boolean_init; + +UTIL_EXTERN jclass mpv_MpvPlayer; +UTIL_EXTERN jmethodID mpv_MpvPlayer_onPropertyChanged_S, mpv_MpvPlayer_onPropertyChanged_Sb, + mpv_MpvPlayer_onPropertyChanged_Sl, mpv_MpvPlayer_onPropertyChanged_Sd, mpv_MpvPlayer_onPropertyChanged_SS, + mpv_MpvPlayer_onEvent, mpv_MpvPlayer_onEndFile, mpv_MpvPlayer_onLogMessage; diff --git a/android/libmpv/src/main/cpp/log.cpp b/android/libmpv/src/main/cpp/log.cpp new file mode 100644 index 000000000..83e1a5d03 --- /dev/null +++ b/android/libmpv/src/main/cpp/log.cpp @@ -0,0 +1,13 @@ +#include "log.h" + +#include "globals.h" +#include "jni_utils.h" + +void die(const char* msg) { + ALOGE("%s", msg); + JNIEnv* env = nullptr; + if (g_vm && acquire_jni_env(g_vm, &env) && env) { + jclass cls = env->FindClass("java/lang/RuntimeException"); + if (cls) env->ThrowNew(cls, msg); + } +} diff --git a/android/libmpv/src/main/cpp/log.h b/android/libmpv/src/main/cpp/log.h new file mode 100644 index 000000000..53d8bb11f --- /dev/null +++ b/android/libmpv/src/main/cpp/log.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +#define DEBUG 1 + +#define LOG_TAG "mpv" +#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#if DEBUG +#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__) +#else +#define ALOGV(...) (void)0 +#endif + +void die(const char* msg); + +#define CHECK_MPV_INIT() \ + do { \ + if (__builtin_expect(!g_mpv, 0)) { \ + die("libmpv is not initialized"); \ + return; \ + } \ + } while (0) + +#define CHECK_MPV_INIT_RET(val) \ + do { \ + if (__builtin_expect(!g_mpv, 0)) { \ + die("libmpv is not initialized"); \ + return val; \ + } \ + } while (0) diff --git a/android/libmpv/src/main/cpp/main.cpp b/android/libmpv/src/main/cpp/main.cpp new file mode 100644 index 000000000..309923b42 --- /dev/null +++ b/android/libmpv/src/main/cpp/main.cpp @@ -0,0 +1,152 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +extern "C" { +#include +} + +#include "event.h" +#include "jni_utils.h" +#include "log.h" + +#define ARRAYLEN(a) (sizeof(a) / sizeof(a[0])) + +void render_cleanup(JNIEnv* env); + +static void* destroy_mpv_thread(void* arg) { + mpv_handle* handle = (mpv_handle*)arg; + mpv_terminate_destroy(handle); + return NULL; +} + +// Fire-and-forget mpv_terminate_destroy on a detached thread. +// Safe because the event thread has been joined and g_mpv cleared — +// no other code references this handle. +static void async_destroy(mpv_handle* handle) { + pthread_t tid; + if (pthread_create(&tid, NULL, destroy_mpv_thread, handle) == 0) { + pthread_detach(tid); + } else { + // Fallback: destroy synchronously if thread creation fails + mpv_terminate_destroy(handle); + } +} + +extern "C" { +jni_func(void, nativeCreate, jobject appctx); +jni_func(void, nativeInit); +jni_func(void, nativeDestroy); + +jni_func(void, nativeCommand, jobjectArray jarray); +}; + +JavaVM* g_vm; +mpv_handle* g_mpv; +std::atomic g_event_thread_request_exit(false); + +static pthread_t event_thread_id; +static std::mutex g_lifecycle_mutex; + +static void prepare_environment(JNIEnv* env, jobject appctx) { + setlocale(LC_NUMERIC, "C"); + + if (!env->GetJavaVM(&g_vm) && g_vm) av_jni_set_java_vm(g_vm, NULL); + + jobject global_appctx = env->NewGlobalRef(appctx); + if (global_appctx) av_jni_set_android_app_ctx(global_appctx, NULL); + + init_methods_cache(env); +} + +jni_func(void, nativeCreate, jobject appctx) { + std::lock_guard lock(g_lifecycle_mutex); + prepare_environment(env, appctx); + + mpv_handle* leaked_mpv = NULL; + if (g_mpv) { + ALOGE("destroying leaked mpv instance"); + leaked_mpv = g_mpv; + g_event_thread_request_exit = true; + mpv_wakeup(leaked_mpv); + pthread_join(event_thread_id, NULL); + g_mpv = NULL; + render_cleanup(env); + } + + g_mpv = mpv_create(); + if (!g_mpv) { + die("context init failed"); + if (leaked_mpv) mpv_terminate_destroy(leaked_mpv); + return; + } + + mpv_request_log_messages(g_mpv, "v"); + + // Async teardown of leaked handle — doesn't block caller + if (leaked_mpv) async_destroy(leaked_mpv); +} + +jni_func(void, nativeInit) { + if (!g_mpv) { + die("mpv is not created"); + return; + } + + if (mpv_initialize(g_mpv) < 0) { + die("mpv init failed"); + return; + } + + g_event_thread_request_exit = false; + if (pthread_create(&event_thread_id, NULL, event_thread, NULL) != 0) { + die("thread create failed"); + return; + } + pthread_setname_np(event_thread_id, "event_thread"); +} + +jni_func(void, nativeDestroy) { + std::lock_guard lock(g_lifecycle_mutex); + if (!g_mpv) { + ALOGV("mpv destroy called but it's already destroyed"); + return; + } + mpv_handle* local_mpv = g_mpv; + + g_event_thread_request_exit = true; + mpv_wakeup(local_mpv); + pthread_join(event_thread_id, NULL); + + g_mpv = NULL; + render_cleanup(env); + + // Async teardown — nativeDestroy returns immediately + async_destroy(local_mpv); +} + +jni_func(void, nativeCommand, jobjectArray jarray) { + CHECK_MPV_INIT(); + + const char* arguments[128] = {0}; + int len = env->GetArrayLength(jarray); + if (len >= ARRAYLEN(arguments)) { + die("too many command arguments"); + return; + } + + for (int i = 0; i < len; ++i) + arguments[i] = env->GetStringUTFChars((jstring)env->GetObjectArrayElement(jarray, i), NULL); + + mpv_command(g_mpv, arguments); + + for (int i = 0; i < len; ++i) + env->ReleaseStringUTFChars((jstring)env->GetObjectArrayElement(jarray, i), arguments[i]); +} diff --git a/android/libmpv/src/main/cpp/property.cpp b/android/libmpv/src/main/cpp/property.cpp new file mode 100644 index 000000000..983838e4e --- /dev/null +++ b/android/libmpv/src/main/cpp/property.cpp @@ -0,0 +1,115 @@ +#include +#include + +#include + +#include "globals.h" +#include "jni_utils.h" +#include "log.h" + +extern "C" { +jni_func(jint, nativeSetOptionString, jstring option, jstring value); + +jni_func(jobject, nativeGetPropertyInt, jstring property); +jni_func(void, nativeSetPropertyInt, jstring property, jint value); +jni_func(jobject, nativeGetPropertyDouble, jstring property); +jni_func(void, nativeSetPropertyDouble, jstring property, jdouble value); +jni_func(jobject, nativeGetPropertyBoolean, jstring property); +jni_func(void, nativeSetPropertyBoolean, jstring property, jboolean value); +jni_func(jstring, nativeGetPropertyString, jstring jproperty); +jni_func(void, nativeSetPropertyString, jstring jproperty, jstring jvalue); + +jni_func(void, nativeObserveProperty, jstring property, jint format); +} + +jni_func(jint, nativeSetOptionString, jstring joption, jstring jvalue) { + CHECK_MPV_INIT_RET(0); + + const char* option = env->GetStringUTFChars(joption, NULL); + const char* value = env->GetStringUTFChars(jvalue, NULL); + + int result = mpv_set_option_string(g_mpv, option, value); + + env->ReleaseStringUTFChars(joption, option); + env->ReleaseStringUTFChars(jvalue, value); + + return result; +} + +static int common_get_property(JNIEnv* env, jstring jproperty, mpv_format format, void* output) { + CHECK_MPV_INIT_RET(-1); + + const char* prop = env->GetStringUTFChars(jproperty, NULL); + int result = mpv_get_property(g_mpv, prop, format, output); + if (result < 0) ALOGE("mpv_get_property(%s) format %d returned error %s", prop, format, mpv_error_string(result)); + env->ReleaseStringUTFChars(jproperty, prop); + + return result; +} + +static int common_set_property(JNIEnv* env, jstring jproperty, mpv_format format, void* value) { + CHECK_MPV_INIT_RET(-1); + + const char* prop = env->GetStringUTFChars(jproperty, NULL); + int result = mpv_set_property(g_mpv, prop, format, value); + if (result < 0) + ALOGE("mpv_set_property(%s, %p) format %d returned error %s", prop, value, format, mpv_error_string(result)); + env->ReleaseStringUTFChars(jproperty, prop); + + return result; +} + +jni_func(jobject, nativeGetPropertyInt, jstring jproperty) { + int64_t value = 0; + if (common_get_property(env, jproperty, MPV_FORMAT_INT64, &value) < 0) return NULL; + return env->NewObject(java_Integer, java_Integer_init, (jint)value); +} + +jni_func(jobject, nativeGetPropertyDouble, jstring jproperty) { + double value = 0; + if (common_get_property(env, jproperty, MPV_FORMAT_DOUBLE, &value) < 0) return NULL; + return env->NewObject(java_Double, java_Double_init, (jdouble)value); +} + +jni_func(jobject, nativeGetPropertyBoolean, jstring jproperty) { + int value = 0; + if (common_get_property(env, jproperty, MPV_FORMAT_FLAG, &value) < 0) return NULL; + return env->NewObject(java_Boolean, java_Boolean_init, (jboolean)value); +} + +jni_func(jstring, nativeGetPropertyString, jstring jproperty) { + char* value; + if (common_get_property(env, jproperty, MPV_FORMAT_STRING, &value) < 0) return NULL; + jstring jvalue = env->NewStringUTF(value); + mpv_free(value); + return jvalue; +} + +jni_func(void, nativeSetPropertyInt, jstring jproperty, jint jvalue) { + int64_t value = static_cast(jvalue); + common_set_property(env, jproperty, MPV_FORMAT_INT64, &value); +} + +jni_func(void, nativeSetPropertyDouble, jstring jproperty, jdouble jvalue) { + double value = static_cast(jvalue); + common_set_property(env, jproperty, MPV_FORMAT_DOUBLE, &value); +} + +jni_func(void, nativeSetPropertyBoolean, jstring jproperty, jboolean jvalue) { + int value = jvalue == JNI_TRUE ? 1 : 0; + common_set_property(env, jproperty, MPV_FORMAT_FLAG, &value); +} + +jni_func(void, nativeSetPropertyString, jstring jproperty, jstring jvalue) { + const char* value = env->GetStringUTFChars(jvalue, NULL); + common_set_property(env, jproperty, MPV_FORMAT_STRING, &value); + env->ReleaseStringUTFChars(jvalue, value); +} + +jni_func(void, nativeObserveProperty, jstring property, jint format) { + CHECK_MPV_INIT(); + const char* prop = env->GetStringUTFChars(property, NULL); + int result = mpv_observe_property(g_mpv, 0, prop, (mpv_format)format); + if (result < 0) ALOGE("mpv_observe_property(%s) format %d returned error %s", prop, format, mpv_error_string(result)); + env->ReleaseStringUTFChars(property, prop); +} diff --git a/android/libmpv/src/main/cpp/render.cpp b/android/libmpv/src/main/cpp/render.cpp new file mode 100644 index 000000000..2e579e358 --- /dev/null +++ b/android/libmpv/src/main/cpp/render.cpp @@ -0,0 +1,79 @@ +#include +#include + +#include "globals.h" +#include "jni_utils.h" +#include "log.h" + +extern "C" { +jni_func(void, nativeAttachSurface, jobject surface_); +jni_func(void, nativeDetachSurface); +jni_func(void, nativeAttachOsdSurface, jobject surface_); +jni_func(void, nativeDetachOsdSurface); +}; + +static jobject surface; + +jni_func(void, nativeAttachSurface, jobject surface_) { + CHECK_MPV_INIT(); + + surface = env->NewGlobalRef(surface_); + if (!surface) { + die("invalid surface provided"); + return; + } + int64_t wid = reinterpret_cast(surface); + int result = mpv_set_option(g_mpv, "wid", MPV_FORMAT_INT64, &wid); + if (result < 0) ALOGE("mpv_set_option(wid) returned error %s", mpv_error_string(result)); +} + +jni_func(void, nativeDetachSurface) { + CHECK_MPV_INIT(); + + int64_t wid = 0; + int result = mpv_set_option(g_mpv, "wid", MPV_FORMAT_INT64, &wid); + if (result < 0) ALOGE("mpv_set_option(wid) returned error %s", mpv_error_string(result)); + + env->DeleteGlobalRef(surface); + surface = NULL; +} + +static jobject osd_surface; + +// The OSD plane of vo=mediacodec. Same lifetime rules as the video surface: +// the global ref must outlive the VO, so detach only after vo has been unset. +jni_func(void, nativeAttachOsdSurface, jobject surface_) { + CHECK_MPV_INIT(); + + osd_surface = env->NewGlobalRef(surface_); + if (!osd_surface) { + die("invalid osd surface provided"); + return; + } + int64_t wid = reinterpret_cast(osd_surface); + int result = mpv_set_option(g_mpv, "vo-mediacodec-osd-surface", MPV_FORMAT_INT64, &wid); + if (result < 0) ALOGE("mpv_set_option(vo-mediacodec-osd-surface) returned error %s", mpv_error_string(result)); +} + +jni_func(void, nativeDetachOsdSurface) { + CHECK_MPV_INIT(); + if (!osd_surface) return; + + int64_t wid = 0; + int result = mpv_set_option(g_mpv, "vo-mediacodec-osd-surface", MPV_FORMAT_INT64, &wid); + if (result < 0) ALOGE("mpv_set_option(vo-mediacodec-osd-surface) returned error %s", mpv_error_string(result)); + + env->DeleteGlobalRef(osd_surface); + osd_surface = NULL; +} + +void render_cleanup(JNIEnv* env) { + if (surface) { + env->DeleteGlobalRef(surface); + surface = NULL; + } + if (osd_surface) { + env->DeleteGlobalRef(osd_surface); + osd_surface = NULL; + } +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/EndFileReason.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/EndFileReason.kt new file mode 100644 index 000000000..26da01410 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/EndFileReason.kt @@ -0,0 +1,13 @@ +package com.edde746.plezy.libmpv + +enum class EndFileReason(val id: Int) { + Eof(0), + Stop(2), + Quit(3), + Error(4), + Redirect(5); + + companion object { + fun fromId(id: Int): EndFileReason? = entries.find { it.id == id } + } +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/LogLevel.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/LogLevel.kt new file mode 100644 index 000000000..af2e394e0 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/LogLevel.kt @@ -0,0 +1,15 @@ +package com.edde746.plezy.libmpv + +enum class LogLevel(internal val nativeValue: Int) { + Fatal(10), + Error(20), + Warn(30), + Info(40), + Verbose(50), + Debug(60), + Trace(70); + + companion object { + internal fun fromNative(value: Int): LogLevel? = entries.find { it.nativeValue == value } + } +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/LogMessage.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/LogMessage.kt new file mode 100644 index 000000000..afff5fc98 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/LogMessage.kt @@ -0,0 +1,7 @@ +package com.edde746.plezy.libmpv + +data class LogMessage( + val prefix: String, + val level: LogLevel, + val text: String +) diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvEvent.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvEvent.kt new file mode 100644 index 000000000..4bad9ab82 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvEvent.kt @@ -0,0 +1,30 @@ +package com.edde746.plezy.libmpv + +sealed interface MpvEvent { + data object Shutdown : MpvEvent + data object StartFile : MpvEvent + data class EndFile(val reason: EndFileReason?) : MpvEvent + data object FileLoaded : MpvEvent + data object VideoReconfig : MpvEvent + data object AudioReconfig : MpvEvent + data object Seek : MpvEvent + data object PlaybackRestart : MpvEvent + data object QueueOverflow : MpvEvent + data class Other(val eventId: Int) : MpvEvent + + companion object { + internal fun fromId(id: Int): MpvEvent? = when (id) { + 1 -> Shutdown + 6 -> StartFile + 8 -> FileLoaded + 17 -> VideoReconfig + 18 -> AudioReconfig + 20 -> Seek + 21 -> PlaybackRestart + 24 -> QueueOverflow + // 0=NONE, 2=LOG_MESSAGE, 7=END_FILE, 22=PROPERTY_CHANGE handled separately + 0, 2, 7, 22 -> null + else -> Other(id) + } + } +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvException.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvException.kt new file mode 100644 index 000000000..692fa7359 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvException.kt @@ -0,0 +1,3 @@ +package com.edde746.plezy.libmpv + +class MpvException(message: String) : RuntimeException(message) diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvPlayer.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvPlayer.kt new file mode 100644 index 000000000..f568bd7f7 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvPlayer.kt @@ -0,0 +1,338 @@ +package com.edde746.plezy.libmpv + +import android.content.Context +import android.view.Surface +import java.util.concurrent.atomic.AtomicReference +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.filterIsInstance +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +class MpvPlayer private constructor() : AutoCloseable { + + companion object { + init { + System.loadLibrary("mpv") + System.loadLibrary("player") + } + + private val instance = AtomicReference(null) + + suspend fun create( + context: Context, + configure: MpvPlayerConfig.() -> Unit = {} + ): MpvPlayer = withContext(Dispatchers.IO) { + val player = MpvPlayer() + // Atomically replace; mark old as closed so its background close() skips nativeDestroy + instance.getAndSet(player)?.also { it.closed = true } + // nativeCreate's safety net handles any leaked native session + try { + nativeCreate(context.applicationContext) + MpvPlayerConfig().apply(configure) + nativeInit() + ensureActive() + player + } catch (e: Throwable) { + instance.compareAndSet(player, null) + try { + nativeDestroy() + } catch (_: Throwable) {} + throw e + } + } + + // JNI callbacks — called from native event thread + + @JvmStatic + fun onPropertyChanged(name: String) { + instance.get()?.rawPropertyChanges?.trySend(PropertyChange.None(name)) + } + + @JvmStatic + fun onPropertyChanged(name: String, value: Boolean) { + instance.get()?.rawPropertyChanges?.trySend(PropertyChange.Flag(name, value)) + } + + @JvmStatic + fun onPropertyChanged(name: String, value: Long) { + instance.get()?.rawPropertyChanges?.trySend(PropertyChange.Int64(name, value)) + } + + @JvmStatic + fun onPropertyChanged(name: String, value: Double) { + instance.get()?.rawPropertyChanges?.trySend(PropertyChange.Double(name, value)) + } + + @JvmStatic + fun onPropertyChanged(name: String, value: String) { + instance.get()?.rawPropertyChanges?.trySend( + PropertyChange.Str(name, sanitizeString(value)) + ) + } + + @JvmStatic + fun onEvent(eventId: Int) { + val event = MpvEvent.fromId(eventId) ?: return + instance.get()?.rawEvents?.trySend(event) + } + + @JvmStatic + fun onEndFile(reason: Int) { + instance.get()?.rawEvents?.trySend( + MpvEvent.EndFile(EndFileReason.fromId(reason)) + ) + } + + @JvmStatic + fun onLogMessage(prefix: String, level: Int, text: String) { + val logLevel = LogLevel.fromNative(level) ?: return + instance.get()?.rawLogMessages?.trySend( + LogMessage(prefix, logLevel, sanitizeString(text).trimEnd()) + ) + } + + private fun sanitizeString(s: String): String { + val sb = StringBuilder(s.length) + var i = 0 + while (i < s.length) { + val c = s[i] + if (c.isHighSurrogate()) { + if (i + 1 < s.length && s[i + 1].isLowSurrogate()) { + sb.append(c) + sb.append(s[i + 1]) + i += 2 + } else { + sb.append('\uFFFD') + i++ + } + } else if (c.isLowSurrogate()) { + sb.append('\uFFFD') + i++ + } else { + sb.append(c) + i++ + } + } + return sb.toString() + } + + // JNI native declarations — private to avoid internal name mangling + + @JvmStatic private external fun nativeCreate(appctx: Context) + + @JvmStatic private external fun nativeInit() + + @JvmStatic private external fun nativeDestroy() + + @JvmStatic private external fun nativeCommand(cmd: Array) + + @JvmStatic private external fun nativeSetOptionString(name: String, value: String): Int + + @JvmStatic private external fun nativeAttachSurface(surface: Surface) + + @JvmStatic private external fun nativeDetachSurface() + + @JvmStatic private external fun nativeAttachOsdSurface(surface: Surface) + + @JvmStatic private external fun nativeDetachOsdSurface() + + @JvmStatic private external fun nativeGetPropertyInt(name: String): Int? + + @JvmStatic private external fun nativeGetPropertyDouble(name: String): Double? + + @JvmStatic private external fun nativeGetPropertyBoolean(name: String): Boolean? + + @JvmStatic private external fun nativeGetPropertyString(name: String): String? + + @JvmStatic private external fun nativeSetPropertyInt(name: String, value: Int) + + @JvmStatic private external fun nativeSetPropertyDouble(name: String, value: Double) + + @JvmStatic private external fun nativeSetPropertyBoolean(name: String, value: Boolean) + + @JvmStatic private external fun nativeSetPropertyString(name: String, value: String) + + @JvmStatic private external fun nativeObserveProperty(name: String, format: Int) + + internal fun setOptionString(name: String, value: String): Int = nativeSetOptionString(name, value) + } + + // The native event thread hands everything to unbounded channels: trySend + // on them cannot fail (until close) and cannot block mpv's event loop. A + // pump per stream re-emits into the SharedFlow, whose SUSPEND overflow + // parks the pump - not the native thread - while a collector catches up. + // The previous design tryEmit-ed straight into the 64-slot SharedFlow + // buffer, which silently dropped whatever arrived during a burst; losing + // e.g. the one cplayer log line that signals a failed video chain. + private val rawEvents = Channel(Channel.UNLIMITED) + private val rawPropertyChanges = Channel(Channel.UNLIMITED) + private val rawLogMessages = Channel(Channel.UNLIMITED) + + private val events = MutableSharedFlow(extraBufferCapacity = 64) + private val propertyChanges = MutableSharedFlow(extraBufferCapacity = 64) + private val logMessages = MutableSharedFlow(extraBufferCapacity = 64) + + private val pumpScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + init { + pumpScope.launch { for (e in rawEvents) events.emit(e) } + pumpScope.launch { for (c in rawPropertyChanges) propertyChanges.emit(c) } + pumpScope.launch { for (m in rawLogMessages) logMessages.emit(m) } + } + + val eventFlow: SharedFlow = events.asSharedFlow() + val propertyFlow: SharedFlow = propertyChanges.asSharedFlow() + val logFlow: SharedFlow = logMessages.asSharedFlow() + + // Commands + + suspend fun command(vararg args: String) { + checkNotClosed() + withContext(Dispatchers.IO) { nativeCommand(args) } + } + + // Surface — not suspend, called from SurfaceHolder.Callback + + fun attachSurface(surface: Surface) { + checkNotClosed() + nativeAttachSurface(surface) + } + + fun detachSurface() { + checkNotClosed() + nativeDetachSurface() + } + + /** OSD/subtitle plane for `vo=mediacodec`; attach before selecting the VO. */ + fun attachOsdSurface(surface: Surface) { + checkNotClosed() + nativeAttachOsdSurface(surface) + } + + fun detachOsdSurface() { + checkNotClosed() + nativeDetachOsdSurface() + } + + // Property getters + + suspend fun getInt(name: String): Int? { + checkNotClosed() + return withContext(Dispatchers.IO) { nativeGetPropertyInt(name) } + } + + suspend fun getDouble(name: String): Double? { + checkNotClosed() + return withContext(Dispatchers.IO) { nativeGetPropertyDouble(name) } + } + + suspend fun getFlag(name: String): Boolean? { + checkNotClosed() + return withContext(Dispatchers.IO) { nativeGetPropertyBoolean(name) } + } + + suspend fun getString(name: String): String? { + checkNotClosed() + return withContext(Dispatchers.IO) { nativeGetPropertyString(name) } + } + + // Property setters + + suspend fun setProperty(name: String, value: Int) { + checkNotClosed() + withContext(Dispatchers.IO) { nativeSetPropertyInt(name, value) } + } + + suspend fun setProperty(name: String, value: Double) { + checkNotClosed() + withContext(Dispatchers.IO) { nativeSetPropertyDouble(name, value) } + } + + suspend fun setProperty(name: String, value: Boolean) { + checkNotClosed() + withContext(Dispatchers.IO) { nativeSetPropertyBoolean(name, value) } + } + + suspend fun setProperty(name: String, value: String) { + checkNotClosed() + withContext(Dispatchers.IO) { nativeSetPropertyString(name, value) } + } + + // Property observation + + fun observeProperty(name: String, format: PropertyFormat): Flow { + checkNotClosed() + nativeObserveProperty(name, format.nativeValue) + return propertyFlow.filter { it.name == name } + } + + fun observeFlag(name: String): Flow { + checkNotClosed() + nativeObserveProperty(name, PropertyFormat.Flag.nativeValue) + return propertyFlow + .filterIsInstance() + .filter { it.name == name } + .map { it.value } + } + + fun observeInt(name: String): Flow { + checkNotClosed() + nativeObserveProperty(name, PropertyFormat.Int64.nativeValue) + return propertyFlow + .filterIsInstance() + .filter { it.name == name } + .map { it.value } + } + + fun observeDouble(name: String): Flow { + checkNotClosed() + nativeObserveProperty(name, PropertyFormat.Double.nativeValue) + return propertyFlow + .filterIsInstance() + .filter { it.name == name } + .map { it.value } + } + + fun observeString(name: String): Flow { + checkNotClosed() + nativeObserveProperty(name, PropertyFormat.String.nativeValue) + return propertyFlow + .filterIsInstance() + .filter { it.name == name } + .map { it.value } + } + + // Lifecycle + + @Volatile + private var closed = false + + override fun close() { + if (closed) return + closed = true + // Only destroy native if we're still the active player. + // If create() already replaced us, nativeCreate's safety net handles native cleanup. + if (instance.compareAndSet(this, null)) { + nativeDestroy() + } + // After nativeDestroy no callback can produce: closing the channels + // lets each pump drain what is already queued and then complete. + rawEvents.close() + rawPropertyChanges.close() + rawLogMessages.close() + } + + private fun checkNotClosed() { + check(!closed) { "MpvPlayer has been closed" } + } +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvPlayerConfig.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvPlayerConfig.kt new file mode 100644 index 000000000..dc8cdcae8 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/MpvPlayerConfig.kt @@ -0,0 +1,10 @@ +package com.edde746.plezy.libmpv + +class MpvPlayerConfig internal constructor() { + fun setOption(name: String, value: String) { + val result = MpvPlayer.setOptionString(name, value) + if (result < 0) { + throw MpvException("Failed to set option '$name' to '$value': error $result") + } + } +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/PropertyChange.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/PropertyChange.kt new file mode 100644 index 000000000..69044dd07 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/PropertyChange.kt @@ -0,0 +1,11 @@ +package com.edde746.plezy.libmpv + +sealed interface PropertyChange { + val name: String + + data class None(override val name: String) : PropertyChange + data class Flag(override val name: String, val value: Boolean) : PropertyChange + data class Int64(override val name: String, val value: Long) : PropertyChange + data class Double(override val name: String, val value: kotlin.Double) : PropertyChange + data class Str(override val name: String, val value: String) : PropertyChange +} diff --git a/android/libmpv/src/main/java/com/edde746/plezy/libmpv/PropertyFormat.kt b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/PropertyFormat.kt new file mode 100644 index 000000000..fce91ea29 --- /dev/null +++ b/android/libmpv/src/main/java/com/edde746/plezy/libmpv/PropertyFormat.kt @@ -0,0 +1,9 @@ +package com.edde746.plezy.libmpv + +enum class PropertyFormat(internal val nativeValue: Int) { + None(0), + String(1), + Flag(3), + Int64(4), + Double(5) +} diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index c83071db1..7dc192ad7 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -25,3 +25,4 @@ plugins { include(":app") include(":libass") +include(":libmpv") diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 9f0398a27..f8218cba5 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -283,7 +283,7 @@ mainGroup = 97C146E51CF9000F007C117D; packageReferences = ( 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, - 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */, + 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "mpv-build" */, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; @@ -797,12 +797,12 @@ /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ - 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */ = { + 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "mpv-build" */ = { isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/edde746/MPVKit"; + repositoryURL = "https://github.com/edde746/mpv-build"; requirement = { kind = revision; - revision = b8b922ec74b84ac3a496e29e226a3a3e91491045; + revision = d7c3d559c91b689407daafe580b758f8b7df6078; }; }; /* End XCRemoteSwiftPackageReference section */ @@ -810,7 +810,7 @@ /* Begin XCSwiftPackageProductDependency section */ 6A8A46202EDB320D0057B88C /* MPVKit */ = { isa = XCSwiftPackageProductDependency; - package = 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "MPVKit" */; + package = 6A8A461F2EDB320D0057B88C /* XCRemoteSwiftPackageReference "mpv-build" */; productName = MPVKit; }; 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 753ae7fee..d3a77949c 100644 --- a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -28,11 +28,11 @@ } }, { - "identity" : "mpvkit", + "identity" : "mpv-build", "kind" : "remoteSourceControl", - "location" : "https://github.com/edde746/MPVKit", + "location" : "https://github.com/edde746/mpv-build", "state" : { - "revision" : "b8b922ec74b84ac3a496e29e226a3a3e91491045" + "revision" : "d7c3d559c91b689407daafe580b758f8b7df6078" } }, { diff --git a/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved index 753ae7fee..d3a77949c 100644 --- a/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -28,11 +28,11 @@ } }, { - "identity" : "mpvkit", + "identity" : "mpv-build", "kind" : "remoteSourceControl", - "location" : "https://github.com/edde746/MPVKit", + "location" : "https://github.com/edde746/mpv-build", "state" : { - "revision" : "b8b922ec74b84ac3a496e29e226a3a3e91491045" + "revision" : "d7c3d559c91b689407daafe580b758f8b7df6078" } }, { diff --git a/linux/packaging/build-libmpv.sh b/linux/packaging/build-libmpv.sh deleted file mode 100755 index 312ff8e54..000000000 --- a/linux/packaging/build-libmpv.sh +++ /dev/null @@ -1,358 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -NATIVE_INPUTS_MANIFEST="${NATIVE_INPUTS_MANIFEST:-$SCRIPT_DIR/native-inputs.json}" - -manifest_value() { - python3 - "$NATIVE_INPUTS_MANIFEST" "$1" "$2" <<'PY' -import json -import sys - -with open(sys.argv[1], encoding="utf-8") as source: - manifest = json.load(source) -value = manifest["inputs"][sys.argv[2]][sys.argv[3]] -if not isinstance(value, str) or not value: - raise SystemExit(f"invalid manifest value: {sys.argv[2]}.{sys.argv[3]}") -print(value) -PY -} - -# For keys that are genuinely optional, where absence means "not offered" -# rather than a broken manifest. Pinned values never come through here: a -# missing checksum or commit has to stay fatal. -manifest_optional() { - python3 - "$NATIVE_INPUTS_MANIFEST" "$1" "$2" <<'PY' -import json -import sys - -with open(sys.argv[1], encoding="utf-8") as source: - manifest = json.load(source) -value = manifest["inputs"][sys.argv[2]].get(sys.argv[3], "") -if not isinstance(value, str): - raise SystemExit(f"invalid manifest value: {sys.argv[2]}.{sys.argv[3]}") -print(value) -PY -} - -FFMPEG_VERSION="$(manifest_value ffmpeg version)" -FFMPEG_URL="$(manifest_value ffmpeg url)" -FFMPEG_SHA256="$(manifest_value ffmpeg sha256)" -DAV1D_VERSION="$(manifest_value dav1d version)" -DAV1D_URL="$(manifest_value dav1d url)" -DAV1D_MIRROR="$(manifest_optional dav1d mirror)" -DAV1D_REF="$(manifest_value dav1d ref)" -DAV1D_COMMIT="$(manifest_value dav1d commit)" -SHADERC_VERSION="$(manifest_value shaderc version)" -SHADERC_URL="$(manifest_value shaderc url)" -SHADERC_REF="$(manifest_value shaderc ref)" -SHADERC_COMMIT="$(manifest_value shaderc commit)" -LIBPLACEBO_VERSION="$(manifest_value libplacebo version)" -LIBPLACEBO_URL="$(manifest_value libplacebo url)" -LIBPLACEBO_MIRROR="$(manifest_optional libplacebo mirror)" -LIBPLACEBO_REF="$(manifest_value libplacebo ref)" -LIBPLACEBO_COMMIT="$(manifest_value libplacebo commit)" -MPV_VERSION="$(manifest_value mpv version)" -MPV_URL="$(manifest_value mpv url)" -MPV_SHA256="$(manifest_value mpv sha256)" - -sha256_file() { - if command -v sha256sum >/dev/null 2>&1; then - sha256sum "$1" | cut -d ' ' -f 1 - else - shasum -a 256 "$1" | cut -d ' ' -f 1 - fi -} - -download_verified() { - local url="$1" - local expected_sha256="$2" - local destination="$3" - local temporary - local actual_sha256 - - if [[ ! "$expected_sha256" =~ ^[0-9a-f]{64}$ ]]; then - echo "Invalid SHA-256 pin for $url" >&2 - return 1 - fi - - mkdir -p "$(dirname "$destination")" - temporary="$(mktemp "${destination}.tmp.XXXXXX")" - # Retries cover the transfer only. A checksum mismatch below is never retried: - # that is a tampered or moved artefact, not a flaky connection, and trying - # again would only turn a loud failure into an intermittent one. - if ! curl \ - --fail \ - --location \ - --silent \ - --show-error \ - --retry 3 \ - --retry-connrefused \ - --retry-delay 5 \ - --connect-timeout 30 \ - --proto '=https,file' \ - --tlsv1.2 \ - --output "$temporary" \ - "$url"; then - rm -f "$temporary" - return 1 - fi - - actual_sha256="$(sha256_file "$temporary")" - if [ "$actual_sha256" != "$expected_sha256" ]; then - echo "SHA-256 mismatch for $url" >&2 - echo "Expected: $expected_sha256" >&2 - echo "Actual: $actual_sha256" >&2 - rm -f "$temporary" "$destination" - return 1 - fi - - mv "$temporary" "$destination" -} - -checkout_verified_ref() { - local url="$1" - local ref="$2" - local expected_commit="$3" - local destination="$4" - local mirror="${5:-}" - local actual_commit - local source - local attempt - - if [[ ! "$expected_commit" =~ ^[0-9a-f]{40}$ ]]; then - echo "Invalid Git commit pin for $url at $ref" >&2 - return 1 - fi - - # Retries and the mirror cover the transfer, never the verification. The commit - # pin below is checked identically whichever source answered, so a mirror can - # only supply the same tree or fail - it cannot substitute another one. - # - # This exists because code.videolan.org, the only source fetched over git, - # refused connections for well over two minutes at a time across several CI - # runs and took every build with it. - rm -rf "$destination" - for source in "$url" ${mirror:+"$mirror"}; do - for attempt in 1 2 3; do - if git clone --quiet --depth 1 --branch "$ref" --no-checkout \ - "$source" "$destination"; then - break 2 - fi - rm -rf "$destination" - # No point pausing before giving up on this source. - if [ "$attempt" -lt 3 ]; then sleep $((attempt * 5)); fi - done - echo "Could not clone $source at $ref after 3 attempts" >&2 - done - if [ ! -d "$destination" ]; then - echo "No source produced $ref for $url" >&2 - return 1 - fi - - actual_commit="$(git -C "$destination" rev-parse 'HEAD^{commit}')" - if [ "$actual_commit" != "$expected_commit" ]; then - echo "Git ref mismatch for $ref" >&2 - echo "Expected: $expected_commit" >&2 - echo "Actual: $actual_commit" >&2 - rm -rf "$destination" - return 1 - fi - - git -C "$destination" checkout --quiet --detach "$expected_commit" -} - -cleanup_srcdir="" - -cleanup() { - if [ -n "$cleanup_srcdir" ]; then - rm -rf -- "$cleanup_srcdir" - fi -} - -main() { - local prefix="${PREFIX:-$(pwd)/libmpv-prefix}" - local jobs="${JOBS:-$(nproc)}" - local srcdir - - mkdir -p "$prefix" - prefix="$(realpath "$prefix")" - export PKG_CONFIG_PATH="$prefix/lib/pkgconfig:$prefix/lib/$(uname -m)-linux-gnu/pkgconfig:${PKG_CONFIG_PATH:-}" - - srcdir="$(mktemp -d)" - cleanup_srcdir="$srcdir" - trap cleanup EXIT - cd "$srcdir" - - echo "==> Sources in $srcdir" - echo "==> Install prefix: $prefix" - echo "" - - # ─── Step 1: dav1d (static library) ──────────────────────────────────────── - # The bundled ffmpeg has no AV1 software decoder: its native av1 decoder is - # hardware-accelerated only, and no libaom/libdav1d is linked in. When hwdec - # is unavailable or cannot serve the source (an AV1 file on a GPU without AV1 - # decode), AV1 has no path at all - every packet fails, video hits EOF and - # the plane goes black while audio keeps playing. dav1d is the software - # floor under AV1, exactly as libass is for subtitles. It must come before - # ffmpeg, whose configure resolves --enable-libdav1d against dav1d's - # pkg-config file. - echo "==> Building dav1d $DAV1D_VERSION (static)..." - checkout_verified_ref \ - "$DAV1D_URL" "$DAV1D_REF" "$DAV1D_COMMIT" \ - "$srcdir/dav1d-v${DAV1D_VERSION}" "$DAV1D_MIRROR" - cd "dav1d-v${DAV1D_VERSION}" - - meson setup build \ - --prefix="$prefix" \ - --default-library=static \ - -Denable_tools=false \ - -Denable_tests=false \ - -Denable_examples=false \ - -Denable_docs=false - - ninja -C build -j"$jobs" - ninja -C build install - cd "$srcdir" - echo "" - echo "==> dav1d done." - echo "" - - # ─── Step 2: ffmpeg (static libraries) ───────────────────────────────────── - echo "==> Building ffmpeg $FFMPEG_VERSION (static, decoder-only)..." - download_verified "$FFMPEG_URL" "$FFMPEG_SHA256" "$srcdir/ffmpeg.tar.xz" - tar -xJf "$srcdir/ffmpeg.tar.xz" - cd "ffmpeg-${FFMPEG_VERSION}" - - ./configure \ - --prefix="$prefix" \ - --enable-gpl \ - --enable-version3 \ - --enable-static \ - --disable-shared \ - --enable-pic \ - --disable-programs \ - --disable-doc \ - --disable-encoders \ - --disable-muxers \ - --enable-muxer=spdif \ - --disable-devices \ - --disable-bsfs \ - --enable-bsf=aac_adtstoasc,av1_metadata,extract_extradata,h264_metadata,h264_mp4toannexb,hevc_metadata,hevc_mp4toannexb,vp9_metadata \ - --disable-filters \ - --enable-filter=aformat,aresample,format,loudnorm,null,scale \ - --enable-gnutls \ - --enable-vaapi \ - --enable-libdav1d \ - --disable-vdpau \ - --disable-debug \ - --disable-stripping - - make -j"$jobs" - make install - cd "$srcdir" - echo "" - echo "==> ffmpeg done." - echo "" - - # ─── Step 3: shaderc (static library) ─────────────────────────────────────── - echo "==> Building shaderc $SHADERC_VERSION (static)..." - checkout_verified_ref \ - "$SHADERC_URL" "$SHADERC_REF" "$SHADERC_COMMIT" \ - "$srcdir/shaderc-v${SHADERC_VERSION}" - cd "shaderc-v${SHADERC_VERSION}" - ./utils/git-sync-deps - - cmake -S . -B build \ - -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_INSTALL_PREFIX="$prefix" \ - -DSHADERC_SKIP_TESTS=ON \ - -DSHADERC_SKIP_EXAMPLES=ON \ - -DSHADERC_SKIP_COPYRIGHT_CHECK=ON \ - -DBUILD_SHARED_LIBS=OFF \ - -DCMAKE_POSITION_INDEPENDENT_CODE=ON - - cmake --build build -j"$jobs" - cmake --install build - cd "$srcdir" - echo "" - echo "==> shaderc done." - echo "" - - # ─── Step 4: libplacebo (static library) ─────────────────────────────────── - echo "==> Building libplacebo $LIBPLACEBO_VERSION (static)..." - checkout_verified_ref \ - "$LIBPLACEBO_URL" "$LIBPLACEBO_REF" "$LIBPLACEBO_COMMIT" \ - "$srcdir/libplacebo-v${LIBPLACEBO_VERSION}" "$LIBPLACEBO_MIRROR" - cd "libplacebo-v${LIBPLACEBO_VERSION}" - git submodule update --init --recursive - - meson setup build \ - --prefix="$prefix" \ - --default-library=static \ - -Dvulkan=disabled \ - -Dd3d11=disabled \ - -Ddemos=false \ - -Dtests=false - - ninja -C build -j"$jobs" - ninja -C build install - cd "$srcdir" - echo "" - echo "==> libplacebo done." - echo "" - - # ─── Step 5: mpv (shared libmpv) ─────────────────────────────────────────── - echo "==> Building mpv $MPV_VERSION (shared libmpv only)..." - download_verified "$MPV_URL" "$MPV_SHA256" "$srcdir/mpv.tar.gz" - tar -xzf "$srcdir/mpv.tar.gz" - cd "mpv-${MPV_VERSION}" - - # The runner's only video path is a Wayland subsurface, and it hands mpv - # MPV_RENDER_PARAM_WL_DISPLAY so VAAPI can find the device instead of falling - # back to software decoding. A libmpv built without Wayland cannot use that. - # VDPAU goes with X11 - it has no Wayland backend at all. - # - # drm/vaapi-drm/egl are pinned enabled, not left on auto: mpv's `drm` feature - # silently drops to disabled when libdisplay-info is missing, and every VAAPI - # path that does not depend on a display server - vaapi-copy's standalone - # render-node device and the GL dmabuf interop - is derived from it. Shipping - # that build quietly lands every source on software decoding (the 2.13.0 - # Fedora report). Enabled means the configure fails when the pieces are - # absent instead of degrading in silence. - meson setup build \ - --prefix="$prefix" \ - -Dlibmpv=true \ - -Dcplayer=false \ - -Dbuild-date=false \ - -Dlua=enabled \ - -Djavascript=enabled \ - -Dcplugins=disabled \ - -Dmanpage-build=disabled \ - -Djack=disabled \ - -Dvulkan=disabled \ - -Dd3d11=disabled \ - -Dgl=enabled \ - -Degl=enabled \ - -Ddrm=enabled \ - -Dvaapi=enabled \ - -Dvaapi-drm=enabled \ - -Dvaapi-wayland=enabled \ - -Dalsa=enabled \ - -Dpulse=enabled \ - -Dpipewire=enabled \ - -Dvdpau=disabled \ - -Dwayland=enabled \ - -Dx11=disabled - - ninja -C build -j"$jobs" - ninja -C build install - echo "" - echo "==> mpv done." - echo "" - echo "==> libmpv build complete. Output in $prefix" -} - -if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then - main "$@" -fi diff --git a/linux/packaging/build-libmpv_test.sh b/linux/packaging/build-libmpv_test.sh deleted file mode 100755 index e67bc3273..000000000 --- a/linux/packaging/build-libmpv_test.sh +++ /dev/null @@ -1,305 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -# shellcheck source=build-libmpv.sh -source "$SCRIPT_DIR/build-libmpv.sh" - -fail() { - echo "FAIL: $*" >&2 - exit 1 -} - -assert_absent() { - [ ! -e "$1" ] || fail "unexpected path remains: $1" -} - -init_repository() { - mkdir -p "$1" - git -C "$1" init --quiet - git -C "$1" config user.name "Plezy provenance test" - git -C "$1" config user.email "provenance-test@invalid.example" -} - -temporary="$(mktemp -d)" -trap 'rm -rf "$temporary"' EXIT - -fixture="$temporary/source.bin" -destination="$temporary/download/output.bin" -printf 'reviewed native input\n' >"$fixture" -expected="$(sha256_file "$fixture")" -download_verified "file://$fixture" "$expected" "$destination" -cmp -s "$fixture" "$destination" || fail "verified download changed bytes" - -printf 'reviewed native inpuu\n' >"$fixture" -rm -f "$destination" -if download_verified "file://$fixture" "$expected" "$destination"; then - fail "changed archive was accepted" -fi -assert_absent "$destination" -if compgen -G "$destination.tmp.*" >/dev/null; then - fail "failed download left a temporary file" -fi - -repository="$temporary/repository" -checkout="$temporary/checkout" -init_repository "$repository" -printf 'first\n' >"$repository/input.txt" -git -C "$repository" add input.txt -git -C "$repository" commit --quiet -m first -git -C "$repository" tag release -approved_commit="$(git -C "$repository" rev-parse HEAD)" -checkout_verified_ref "file://$repository" release "$approved_commit" "$checkout" -[ "$(git -C "$checkout" rev-parse HEAD)" = "$approved_commit" ] || - fail "verified checkout selected the wrong commit" - -# A dead primary must fall through to the mirror, because the whole point is -# that one unreachable host cannot stop the build. This runs while the tag still -# points at the approved commit; the moved-tag case is below. -unreachable="file://$temporary/definitely-not-a-repository" -checkout_verified_ref "$unreachable" release "$approved_commit" "$checkout" "file://$repository" -[ "$(git -C "$checkout" rev-parse HEAD)" = "$approved_commit" ] || - fail "mirror fallback selected the wrong commit" - -# And the mirror answers to the same pin. A mirror serving a different tree is -# the one thing a fallback must never quietly accept. -mirror_repository="$temporary/mirror" -init_repository "$mirror_repository" -printf 'substituted\n' >"$mirror_repository/input.txt" -git -C "$mirror_repository" add input.txt -git -C "$mirror_repository" commit --quiet -m substituted -git -C "$mirror_repository" tag release -if checkout_verified_ref "$unreachable" release "$approved_commit" "$checkout" "file://$mirror_repository"; then - fail "mirror serving another commit was accepted" -fi -assert_absent "$checkout" - -printf 'second\n' >"$repository/input.txt" -git -C "$repository" commit --quiet -am second -git -C "$repository" tag --force release >/dev/null -if checkout_verified_ref "file://$repository" release "$approved_commit" "$checkout"; then - fail "moved tag was accepted" -fi -assert_absent "$checkout" - -# ─── The build plan ───────────────────────────────────────────────────────── -# Everything above checks how sources arrive. What they are then configured -# with decides whether the feature works at all, and it fails quietly: a libmpv -# built without -Dwayland=enabled still compiles, still links and still plays, -# it just has no Wayland backend, so the render context cannot accept -# MPV_RENDER_PARAM_WL_DISPLAY, vaapi finds no device and hardware decoding -# drops to a copy-back path. Nothing crashes, so nothing else notices. Run -# main() for real against stub build tools and assert the argument vectors they -# were handed. - -stub_bin="$temporary/stub-bin" -stub_extra="$temporary/stub-extra" -records="$temporary/records" -mkdir -p "$stub_bin" "$stub_extra" "$records" "$temporary/tmp" - -# Deliberately unlike the pinned versions: every path below is derived from the -# manifest, so a stub that matched by accident would prove nothing. -ffmpeg_version="9.9.9" -dav1d_version="2.2.2" -shaderc_version="6.6.6" -libplacebo_version="7.7.7" -mpv_version="8.8.8" - -# Each stub records the vector it was called with, one argument per line, plus -# the directory it ran in - which is what tells mpv's meson call apart from -# libplacebo's. An argument containing a newline would corrupt the record, and -# none of these ever does: they are literal flags and mktemp -d paths. -make_stub() { - local directory="$1" name="$2" extra="${3:-}" - cat >"$directory/$name" <"\$record" -$extra -STUB - chmod +x "$directory/$name" -} - -payload="$temporary/payload.bin" -printf 'stub archive payload\n' >"$payload" -payload_sha256="$(sha256_file "$payload")" - -curl_extra=' -output="" -previous="" -for argument in "$@"; do - if [ "$previous" = "--output" ]; then output="$argument"; fi - previous="$argument" -done -[ -n "$output" ] || { echo "stub curl: no --output argument" >&2; exit 1; } -cp -- "'"$payload"'" "$output" -' - -# The unmapped case is fatal on purpose: a new archive in the build plan has to -# come here and be described rather than silently extract to nothing. -tar_extra=' -archive="$(basename -- "${!#}")" -case "$archive" in - ffmpeg.tar.xz) directory="ffmpeg-'"$ffmpeg_version"'" ;; - mpv.tar.gz) directory="mpv-'"$mpv_version"'" ;; - *) echo "stub tar: unexpected archive $archive" >&2; exit 1 ;; -esac -mkdir -p "$directory" -cp -- "'"$stub_extra"'/configure" "$directory/configure" -chmod +x "$directory/configure" -' - -# ffmpeg runs ./configure out of its own tarball, so that one is planted by the -# tar stub rather than found on PATH. -make_stub "$stub_extra" configure -make_stub "$stub_bin" curl "$curl_extra" -make_stub "$stub_bin" tar "$tar_extra" -for tool in make cmake meson ninja; do - make_stub "$stub_bin" "$tool" -done - -# git stays real, pointed at local repositories: the checkout is pinned by -# commit, and a stub that answered rev-parse would be asserting its own input. -shaderc_repository="$temporary/shaderc-source" -init_repository "$shaderc_repository" -mkdir -p "$shaderc_repository/utils" -printf '#!/bin/sh\nexit 0\n' >"$shaderc_repository/utils/git-sync-deps" -chmod +x "$shaderc_repository/utils/git-sync-deps" -git -C "$shaderc_repository" add utils/git-sync-deps -# Windows checkouts do not track the mode bit, and the build plan executes it. -git -C "$shaderc_repository" update-index --chmod=+x utils/git-sync-deps -git -C "$shaderc_repository" commit --quiet -m shaderc -git -C "$shaderc_repository" tag release -shaderc_commit="$(git -C "$shaderc_repository" rev-parse HEAD)" - -dav1d_repository="$temporary/dav1d-source" -init_repository "$dav1d_repository" -printf 'stub dav1d\n' >"$dav1d_repository/meson.build" -git -C "$dav1d_repository" add meson.build -git -C "$dav1d_repository" commit --quiet -m dav1d -git -C "$dav1d_repository" tag release -dav1d_commit="$(git -C "$dav1d_repository" rev-parse HEAD)" - -libplacebo_repository="$temporary/libplacebo-source" -init_repository "$libplacebo_repository" -printf 'stub libplacebo\n' >"$libplacebo_repository/meson.build" -git -C "$libplacebo_repository" add meson.build -git -C "$libplacebo_repository" commit --quiet -m libplacebo -git -C "$libplacebo_repository" tag release -libplacebo_commit="$(git -C "$libplacebo_repository" rev-parse HEAD)" - -manifest="$temporary/native-inputs.json" -cat >"$manifest" <"$build_log" 2>&1; then - cat "$build_log" >&2 - fail "the stubbed build plan did not run to completion" -fi - -recorded_call() { - local program="$1" directory="$2" candidate - for candidate in "$records"/record.*; do - [ -f "$candidate" ] || continue - if [ "$(sed -n 1p "$candidate")" = "$program" ] && - [ "$(basename -- "$(sed -n 2p "$candidate")")" = "$directory" ]; then - printf '%s\n' "$candidate" - return 0 - fi - done - return 1 -} - -# -Fxq, so this matches a whole recorded argument. A substring search would -# accept -Dwayland=enabled inside a comment, which is exactly the hole here. -assert_argument() { - local record="$1" argument="$2" description="$3" - tail -n +3 "$record" | grep -Fxq -- "$argument" || - fail "$description does not pass $argument" -} - -mpv_meson="$(recorded_call meson "mpv-$mpv_version")" || - fail "the build plan never ran meson in the mpv source tree" -[ "$(sed -n 3p "$mpv_meson")" = "setup" ] || - fail "mpv's first meson call is no longer 'setup'" - -assert_argument "$mpv_meson" "-Dwayland=enabled" "mpv's meson setup" -assert_argument "$mpv_meson" "-Dx11=disabled" "mpv's meson setup" -assert_argument "$mpv_meson" "-Dvaapi=enabled" "mpv's meson setup" -assert_argument "$mpv_meson" "-Dgl=enabled" "mpv's meson setup" -assert_argument "$mpv_meson" "-Degl=enabled" "mpv's meson setup" - -# The DRM-derived providers are the ones that keep hardware decoding alive when -# the Wayland VA display cannot be had: vaapi-copy opens the render node on its -# own, and the GL dmabuf interop gives direct vaapi a display-independent -# path. mpv auto-disables the whole `drm` feature when libdisplay-info is -# missing, so these are pinned enabled and asserted here. -assert_argument "$mpv_meson" "-Ddrm=enabled" "mpv's meson setup" -assert_argument "$mpv_meson" "-Dvaapi-drm=enabled" "mpv's meson setup" -assert_argument "$mpv_meson" "-Dvaapi-wayland=enabled" "mpv's meson setup" - -# vaapi has to reach ffmpeg too, or mpv's hwdec has no decoder behind it. And -# the bundled ffmpeg needs a software AV1 decoder: its native av1 codec is -# hardware-accelerated only, so without dav1d an AV1 source on a machine whose -# GPU cannot decode it fails every packet and plays black video with audio. -ffmpeg_configure="$(recorded_call configure "ffmpeg-$ffmpeg_version")" || - fail "the build plan never configured ffmpeg" -assert_argument "$ffmpeg_configure" "--enable-vaapi" "ffmpeg's configure" -assert_argument "$ffmpeg_configure" "--enable-libdav1d" "ffmpeg's configure" - -# dav1d must be built static so ffmpeg absorbs it into the bundled libmpv: -# a shared dav1d would have to travel in the bundle and be kept version-true -# with the host, which is exactly the coupling the rest of the plan avoids. -dav1d_meson="$(recorded_call meson "dav1d-v$dav1d_version")" || - fail "the build plan never ran meson in the dav1d source tree" -assert_argument "$dav1d_meson" "--default-library=static" "dav1d's meson setup" - -# libplacebo runs meson as well, and its call carries no Wayland flag: finding -# it separately is what proves the directory above really discriminated. -recorded_call meson "libplacebo-v$libplacebo_version" >/dev/null || - fail "the build plan never ran meson in the libplacebo source tree" - -echo "Linux native acquisition and build plan verification passed" diff --git a/linux/packaging/build-packages.py b/linux/packaging/build-packages.py index a8725c69a..d24d55420 100755 --- a/linux/packaging/build-packages.py +++ b/linux/packaging/build-packages.py @@ -232,14 +232,14 @@ def main(): if not BUILD_DIR.exists(): print(f"Error: Build directory not found at {BUILD_DIR}") print("Please run 'flutter build linux --release' first or set BUILD_DIR.") - # The runner requires pkg-config to find mpv, and build-libmpv.sh exports - # PKG_CONFIG_PATH only inside its own process. Without carrying it across, - # the build either cannot configure at all or - worse, because it looks - # like success - links whatever distro libmpv happens to be installed - # instead of the pinned Wayland-enabled one these packages assume. CI sets - # this explicitly for the same reason and installs no libmpv-dev. - print("The build needs the pinned libmpv on its pkg-config path, which build-libmpv.sh") - print("exports only for itself:") + # The runner requires pkg-config to find mpv, and nothing exports + # PKG_CONFIG_PATH for the build. Without it, the build either cannot + # configure at all or - worse, because it looks like success - links + # whatever distro libmpv happens to be installed instead of the pinned + # Wayland-enabled one these packages assume. CI sets this explicitly for + # the same reason and installs no libmpv-dev. + print("The build needs the pinned libmpv on its pkg-config path: extract the") + print("mpv-build.lock.json linux artifact into libmpv-prefix/, then") print(' PKG_CONFIG_PATH="$(pwd)/libmpv-prefix/lib/pkgconfig:$(pwd)/libmpv-prefix/lib/x86_64-linux-gnu/pkgconfig" \\') print(" flutter build linux --release") exit(1) @@ -262,14 +262,15 @@ def main(): print("The packages declare no host libmpv, so one has to travel inside them.") print("Stage the bundle first, exactly as both workflows do:") # meson installs libmpv under an architecture triple on Debian and Ubuntu - # while CMake installed shaderc straight into lib/, which is why the two - # lines below are not the same shape. The workflows locate libmpv the same - # way; a hardcoded libmpv-prefix/lib/libmpv.so* finds nothing there. + # while shaderc sits straight in lib/, which is why the two lines below + # are not the same shape. The prebuilt mpv-build prefix preserves that + # layout and the workflows locate libmpv the same way; a hardcoded + # libmpv-prefix/lib/libmpv.so* finds nothing there. print(' cp -a "$(dirname "$(find libmpv-prefix -name libmpv.so | head -1)")"/libmpv.so* /lib/') - # The pinned libmpv links libshaderc_shared, which build-libmpv.sh leaves - # in libmpv-prefix - not a directory the loader searches. bundle-libs.sh - # cannot recover it either: it resolves what ldd reports, and ldd cannot - # find a soname that is only in the build prefix. So it is copied by hand + # The pinned libmpv links libshaderc_shared, which the prefix carries in + # lib/ - not a directory the loader searches. bundle-libs.sh cannot + # recover it either: it resolves what ldd reports, and ldd cannot find a + # soname that is only in the extracted prefix. So it is copied by hand # before the walk, or the bundle gets an unpinned host shaderc at best. print(" cp -a libmpv-prefix/lib/libshaderc_shared.so* /lib/") print(" bash linux/packaging/bundle-libs.sh ") diff --git a/linux/packaging/native-inputs.json b/linux/packaging/native-inputs.json index d06f95ac8..b259023a5 100644 --- a/linux/packaging/native-inputs.json +++ b/linux/packaging/native-inputs.json @@ -2,55 +2,13 @@ "formatVersion": 1, "refreshContract": { "rules": [ - "Audit each new upstream release before changing its version, URL, ref, commit, or SHA-256.", - "For an archive, verify upstream release evidence first, hash the complete reviewed file, and update URL and SHA-256 together.", - "For Git, verify the upstream release-producing tag record, record the full dereferenced root commit, and review its dependency lock or gitlinks before updating.", - "Run python3 scripts/verify_runtime_inputs.py and bash linux/packaging/build-libmpv_test.sh before a Linux build.", + "Audit each new upstream release before changing its version, URL, or SHA-256.", + "Verify upstream release evidence first, hash the complete reviewed file, and update URL and SHA-256 together.", + "Run python3 scripts/checks/verify_runtime_inputs.py after any edit.", "Never derive an expected checksum from bytes inside the production build or verification command." ] }, "inputs": { - "ffmpeg": { - "kind": "archive", - "version": "7.1", - "url": "https://ffmpeg.org/releases/ffmpeg-7.1.tar.xz", - "sha256": "40973d44970dbc83ef302b0609f2e74982be2d85916dd2ee7472d30678a7abe6", - "provenance": "FFmpeg release archive verified against ffmpeg-7.1.tar.xz.asc with the official ffmpeg-devel.asc full fingerprint FCF986EA15E6E293A5644F10B4322F04D67658D8 before recording this digest." - }, - "dav1d": { - "kind": "git", - "version": "1.5.4", - "url": "https://code.videolan.org/videolan/dav1d.git", - "mirror": "https://github.com/videolan/dav1d.git", - "ref": "1.5.4", - "commit": "54706fc6bc0cdecab7e9593974a4039cc038fca7", - "provenance": "Official VideoLAN GitLab tag record 1.5.4 dereferences to this root commit; upstream's own GitHub mirror (videolan/dav1d, not a fork) reports the same annotated tag object 191bdda98ec3c68137754dc97da1db34043d7cd4 dereferencing to that same commit. The tag is annotated by the dav1d maintainers but not GPG-verified by GitHub; the two independent remotes agreeing on the tag object and root commit is the pinning evidence. The mirror is consulted only after the primary fails, and the commit pin is verified identically either way." - }, - "shaderc": { - "kind": "git", - "version": "2024.4", - "url": "https://github.com/google/shaderc.git", - "ref": "v2024.4", - "commit": "caa54d9779d5605aca4e1a0c0c962a3d8f4aeb31", - "provenance": "Official GitHub annotated tag object 3cd72062f297df05e6a042f2616c42bc8956c326 dereferences to this root commit; its DEPS file pins synchronized dependencies by full commit." - }, - "libplacebo": { - "kind": "git", - "version": "7.351.0", - "url": "https://code.videolan.org/videolan/libplacebo.git", - "mirror": "https://github.com/haasn/libplacebo.git", - "ref": "v7.351.0", - "commit": "3188549fba13bbdf3a5a98de2a38c2e71f04e21e", - "provenance": "Official VideoLAN GitLab tag record v7.351.0 contains a PGP-signed release message and dereferences to this root commit; its gitlinks pin recursive submodules. The mirror is upstream's own author repository (haasn/libplacebo, not a fork), whose annotated v7.351.0 tag object 98c1416e95b21cd767b84ac9ee430ccadf263ff6 dereferences to that same commit. It is consulted only after the primary fails, and the commit pin is verified identically either way, so it cannot introduce a different tree." - }, - "mpv": { - "kind": "archive", - "version": "0.40.0", - "url": "https://github.com/mpv-player/mpv/archive/refs/tags/v0.40.0.tar.gz", - "sha256": "10a0f4654f62140a6dd4d380dcf0bbdbdcf6e697556863dc499c296182f081a3", - "commit": "e48ac7ce08462f5e33af6ef9deeac6fa87eef01e", - "provenance": "GitHub reports annotated tag object 287d7cdb78975ae350d7c2a287eae3c2072c93f7 as a valid PGP signature over release commit e48ac7ce08462f5e33af6ef9deeac6fa87eef01e; the complete tag archive was then hashed." - }, "simdutf": { "kind": "archive", "version": "6.4.2", diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj index fd190ecda..3b3544f5a 100644 --- a/macos/Runner.xcodeproj/project.pbxproj +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -342,7 +342,7 @@ mainGroup = 33CC10E42044A3C60003C045; packageReferences = ( 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, - 6AB6B0932EDB27C100EAC8DB /* XCRemoteSwiftPackageReference "MPVKit" */, + 6AB6B0932EDB27C100EAC8DB /* XCRemoteSwiftPackageReference "mpv-build" */, ); productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; projectDirPath = ""; @@ -890,12 +890,12 @@ /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ - 6AB6B0932EDB27C100EAC8DB /* XCRemoteSwiftPackageReference "MPVKit" */ = { + 6AB6B0932EDB27C100EAC8DB /* XCRemoteSwiftPackageReference "mpv-build" */ = { isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/edde746/MPVKit"; + repositoryURL = "https://github.com/edde746/mpv-build"; requirement = { kind = revision; - revision = b8b922ec74b84ac3a496e29e226a3a3e91491045; + revision = d7c3d559c91b689407daafe580b758f8b7df6078; }; }; /* End XCRemoteSwiftPackageReference section */ @@ -903,7 +903,7 @@ /* Begin XCSwiftPackageProductDependency section */ 6AB6B0942EDB27C100EAC8DB /* MPVKit */ = { isa = XCSwiftPackageProductDependency; - package = 6AB6B0932EDB27C100EAC8DB /* XCRemoteSwiftPackageReference "MPVKit" */; + package = 6AB6B0932EDB27C100EAC8DB /* XCRemoteSwiftPackageReference "mpv-build" */; productName = MPVKit; }; 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 01fc288b4..82a612757 100644 --- a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,11 +1,11 @@ { "pins" : [ { - "identity" : "mpvkit", + "identity" : "mpv-build", "kind" : "remoteSourceControl", - "location" : "https://github.com/edde746/MPVKit", + "location" : "https://github.com/edde746/mpv-build", "state" : { - "revision" : "b8b922ec74b84ac3a496e29e226a3a3e91491045" + "revision" : "d7c3d559c91b689407daafe580b758f8b7df6078" } }, { diff --git a/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved index 01fc288b4..82a612757 100644 --- a/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,11 +1,11 @@ { "pins" : [ { - "identity" : "mpvkit", + "identity" : "mpv-build", "kind" : "remoteSourceControl", - "location" : "https://github.com/edde746/MPVKit", + "location" : "https://github.com/edde746/mpv-build", "state" : { - "revision" : "b8b922ec74b84ac3a496e29e226a3a3e91491045" + "revision" : "d7c3d559c91b689407daafe580b758f8b7df6078" } }, { diff --git a/mpv-build.lock.json b/mpv-build.lock.json new file mode 100644 index 000000000..680f607cf --- /dev/null +++ b/mpv-build.lock.json @@ -0,0 +1,57 @@ +{ + "artifacts": { + "android": { + "assetBase": "https://github.com/edde746/mpv-build/releases/download/binaries-android", + "assets": { + "arm64-v8a": { + "asset": "libmpv-android-b63d0798e9a8-arm64-v8a.tar.gz", + "checksum": "0e6eb12a35cff0fc7978a219cef0ba33c6ee8cdfcc28221b34c7033472a16c60" + }, + "armeabi-v7a": { + "asset": "libmpv-android-b63d0798e9a8-armeabi-v7a.tar.gz", + "checksum": "3f55259c6b77ec729c3345c5fd2e18cbd0e27b7a53999d645b252d6d8c20fd2f" + }, + "x86": { + "asset": "libmpv-android-b63d0798e9a8-x86.tar.gz", + "checksum": "03212e4d0403fe616a11665f0ee19529e9abaf167fc3f311cf28a58452eea7f5" + }, + "x86_64": { + "asset": "libmpv-android-b63d0798e9a8-x86_64.tar.gz", + "checksum": "c4e3cd20f2fb9c61d38f2b63fc7b95ca1a2e3d4ccd6f16446d57ce4b8018b6a1" + } + }, + "key": "b63d0798e9a8" + }, + "linux": { + "assetBase": "https://github.com/edde746/mpv-build/releases/download/binaries-linux", + "assets": { + "aarch64": { + "asset": "libmpv-linux-a4236264f6ea-aarch64.tar.zst", + "checksum": "711101cae8e36f9c45e5e9b4527e6658f6023650f0b957289582eb956cbd0b73" + }, + "x86_64": { + "asset": "libmpv-linux-a4236264f6ea-x86_64.tar.zst", + "checksum": "fb29710f6d413e89ff047edb42a91ead3ea9ccb9a09d42bb91fa9ec900f4a0b4" + } + }, + "key": "a4236264f6ea" + }, + "windows": { + "assetBase": "https://github.com/edde746/mpv-build/releases/download/binaries-windows", + "assets": { + "aarch64": { + "asset": "libmpv-windows-1da76841036d-aarch64.zip", + "checksum": "94c0e4d27794fb3bb754b0c62409c6b0cf17161fbafa16c3213d0239821a6836" + }, + "x86_64": { + "asset": "libmpv-windows-1da76841036d-x86_64.zip", + "checksum": "6a927cbbb7d44ecbefa3643ef0b435e3fa521b6a1123bb8c5d6349441ed3a760" + } + }, + "key": "1da76841036d" + } + }, + "commit": "d7c3d559c91b689407daafe580b758f8b7df6078", + "formatVersion": 1, + "repo": "edde746/mpv-build" +} diff --git a/scripts/checks/check_build_workflow.py b/scripts/checks/check_build_workflow.py index d4ce992b6..f1a679f6d 100644 --- a/scripts/checks/check_build_workflow.py +++ b/scripts/checks/check_build_workflow.py @@ -127,9 +127,7 @@ require( r"(?ms) - arch: arm64\n" r" runner: windows-11-arm\n" r" flutter_setup: git\n" - r" native_cache_path: \|\n" - r" build/windows/arm64/_deps\n" - r" build/windows/arm64/mpv-dev-arm64\n", + r" native_cache_path: build/windows/arm64/_deps\n", windows, ) is not None, @@ -146,10 +144,16 @@ for expected in ( "path: build/windows/${{ matrix.arch }}/runner/Release/", ): require(expected in windows, f"Windows matrix missing: {expected}") +# libmpv comes from our mpv-build release zips via FetchContent for both +# arches (no 7-Zip, no unpinned sourceforge download); the checksums must +# stay enforced. require( - "if: matrix.arch == 'arm64' && steps.windows-native-cache.outputs.cache-hit != 'true'" - in windows, - "7-Zip installation must remain ARM-only and cache-aware", + "URL_HASH SHA256=${MPV_SHA256}" in (ROOT / "windows/CMakeLists.txt").read_text(encoding="utf-8"), + "Windows libmpv fetch must keep URL_HASH enforcement", +) +require( + "sourceforge" not in (ROOT / "windows/CMakeLists.txt").read_text(encoding="utf-8"), + "Windows libmpv fetch must not regress to the unpinned sourceforge download", ) require( re.search( @@ -230,11 +234,10 @@ require( "Linux build attestation permissions changed", ) require_explicit_shells("build-linux", linux, "bash") -libmpv_cache = named_step(linux, "Cache libmpv build") +libmpv_cache = named_step(linux, "Cache libmpv prefix") require( - "hashFiles('linux/packaging/build-libmpv.sh', 'linux/packaging/native-inputs.json')" - in libmpv_cache, - "libmpv cache identity must include its build script and native input manifest", + "hashFiles('mpv-build.lock.json')" in libmpv_cache, + "libmpv cache identity must include the mpv-build lock", ) diff --git a/scripts/checks/check_shrinker_rules.py b/scripts/checks/check_shrinker_rules.py index c540f38b1..0467906f1 100755 --- a/scripts/checks/check_shrinker_rules.py +++ b/scripts/checks/check_shrinker_rules.py @@ -14,9 +14,11 @@ invisible to R8 and gets shrunk or renamed away. Four such surfaces exist: private ``MatroskaExtractor`` fields this way), in every ``android/**/src/main`` source root including the ``libass`` module. -None of these lookups leaves a reference R8 can see, so only -``android/app/proguard-rules.pro`` keeps their targets, and losing a keep surfaces -solely as broken behaviour in a release build. +None of these lookups leaves a reference R8 can see, so only the keep rules R8 +actually receives — ``android/app/proguard-rules.pro`` plus each library module's +``consumer-rules.pro`` — protect their targets, and losing a keep surfaces solely +as broken behaviour in a release build. Both the native and JVM checks cover every +module under ``android/``. """ from __future__ import annotations @@ -28,7 +30,6 @@ from pathlib import Path PROGUARD_RULES = Path("android/app/proguard-rules.pro") ANDROID_ROOT = Path("android") -CPP_ROOT = Path("android/app/src/main/cpp") NATIVE_SUFFIXES = {".c", ".cc", ".cpp", ".h", ".hpp"} JVM_SUFFIXES = {".kt", ".java"} # Dependency namespaces reached only through reflection have no direct callers. @@ -142,10 +143,14 @@ def _binary_name(jni_name: str) -> str: def _native_sources(root: Path) -> list[Path]: - cpp_root = root / CPP_ROOT - if not cpp_root.is_dir(): - return [] - return sorted(path for path in cpp_root.rglob("*") if path.suffix in NATIVE_SUFFIXES) + """Native sources in every module's ``src/main/cpp`` under ``android/``.""" + return sorted( + path + for main in _main_source_dirs(root) + if (main / "cpp").is_dir() + for path in (main / "cpp").rglob("*") + if path.suffix in NATIVE_SUFFIXES + ) def _main_source_dirs(root: Path) -> list[Path]: @@ -202,6 +207,9 @@ def _check_native_lookups(root: Path, keeps: list[Keep], errors: list[str]) -> N label = source.relative_to(root).as_posix() for owner in sorted(set(owners.values())): + if owner.startswith(PLATFORM_PREFIXES): + # Bootclasspath classes are not in the app dex; R8 cannot touch them. + continue if not any(keep.keeps_class_name and keep.matches_class(owner) for keep in keeps): errors.append(f"{label} resolves {owner} with FindClass but no -keep covers it") @@ -214,6 +222,8 @@ def _check_native_lookups(root: Path, keeps: list[Keep], errors: list[str]) -> N f"back to a FindClass call; assign the jclass from FindClass or extend {Path(__file__).name}" ) continue + if owner.startswith(PLATFORM_PREFIXES): + continue matching = [keep for keep in keeps if keep.matches_class(owner)] if not any(keep.keeps_member_alive and keep.keeps_member(member) for keep in matching): errors.append(f"{label} resolves {owner}.{member} from native code but no -keep retains that member") @@ -327,7 +337,12 @@ def validate(root: Path) -> list[str]: f"builds{': ' + ', '.join(reflected) if reflected else ''}" ] - keeps = _parse_keeps(rules_path.read_text(encoding="utf-8")) + rules_text = rules_path.read_text(encoding="utf-8") + # AGP feeds every library module's consumer rules into the app's R8 + # invocation, so keeps there are as effective as the app's own. + for consumer_rules in sorted((root / ANDROID_ROOT).glob("*/consumer-rules.pro")): + rules_text += "\n" + consumer_rules.read_text(encoding="utf-8") + keeps = _parse_keeps(rules_text) errors = [] for binary_name in reflected: if not any(keep.keeps_class_name and keep.matches_class(binary_name) for keep in keeps): diff --git a/scripts/checks/test_check_build_workflow.py b/scripts/checks/test_check_build_workflow.py index 84ba65418..f1f506b57 100755 --- a/scripts/checks/test_check_build_workflow.py +++ b/scripts/checks/test_check_build_workflow.py @@ -121,17 +121,17 @@ class BuildWorkflowGuardTest(unittest.TestCase): self.assertNotEqual(result.returncode, 0) self.assertIn("cleanup must run from a finally block", result.stderr) - def test_libmpv_cache_without_native_manifest_is_rejected(self) -> None: + def test_libmpv_cache_without_lock_identity_is_rejected(self) -> None: workflow = self._workflow().replace( - "hashFiles('linux/packaging/build-libmpv.sh', 'linux/packaging/native-inputs.json')", - "hashFiles('linux/packaging/build-libmpv.sh')", + "hashFiles('mpv-build.lock.json')", + "hashFiles('linux/packaging/native-inputs.json')", 1, ) result = self._run(workflow) self.assertNotEqual(result.returncode, 0) - self.assertIn("native input manifest", result.stderr) + self.assertIn("mpv-build lock", result.stderr) def test_draft_release_without_explicit_tag_is_rejected(self) -> None: workflow = self._workflow().replace( diff --git a/scripts/checks/test_check_shrinker_rules.py b/scripts/checks/test_check_shrinker_rules.py index 1c8726e8d..5062c7447 100755 --- a/scripts/checks/test_check_shrinker_rules.py +++ b/scripts/checks/test_check_shrinker_rules.py @@ -327,6 +327,51 @@ class ShrinkerRulesCheckerTest(unittest.TestCase): CHECKER.validate(self.root), ) + # The libmpv module shape: JNI callbacks resolved from a library module's own + # cpp tree, kept alive by that module's consumer rules rather than the app's. + LIBMPV_STYLE_SOURCE = ( + "static void cache(JNIEnv *env) {\n" + ' mpv_MpvPlayer = env->FindClass("com/edde746/plezy/libmpv/MpvPlayer");\n' + " mpv_MpvPlayer = reinterpret_cast(env->NewGlobalRef(mpv_MpvPlayer));\n" + ' onEvent = env->GetStaticMethodID(mpv_MpvPlayer, "onEvent", "(I)V");\n' + "}\n" + ) + + def test_library_module_native_lookups_are_scanned(self) -> None: + self._write_rules(FULL_RULES) + self._write_source("android/libmpv/src/main/cpp/jni_utils.cpp", self.LIBMPV_STYLE_SOURCE) + + self.assertEqual( + {"with FindClass", "from native code"}, + self._failure_kinds(CHECKER.validate(self.root)), + ) + + def test_module_consumer_rules_satisfy_native_lookups(self) -> None: + self._write_rules(FULL_RULES) + self._write_source("android/libmpv/src/main/cpp/jni_utils.cpp", self.LIBMPV_STYLE_SOURCE) + self._write_source( + "android/libmpv/consumer-rules.pro", + "-keep class com.edde746.plezy.libmpv.MpvPlayer {\n" + " public static void onEvent(int);\n" + "}\n", + ) + + self.assertEqual([], CHECKER.validate(self.root)) + + def test_bootclasspath_native_lookups_need_no_keep(self) -> None: + # Boxing helpers resolve java.lang.Integer and its constructor by name; + # neither is in the app dex, so R8 cannot shrink or rename them. + self._write_rules(FULL_RULES) + self._write_source( + "android/libmpv/src/main/cpp/boxing.cpp", + "static void cache(JNIEnv *env) {\n" + ' java_Integer = env->FindClass("java/lang/Integer");\n' + ' java_Integer_init = env->GetMethodID(java_Integer, "", "(I)V");\n' + "}\n", + ) + + self.assertEqual([], CHECKER.validate(self.root)) + if __name__ == "__main__": unittest.main() diff --git a/scripts/checks/test_verify_runtime_inputs.py b/scripts/checks/test_verify_runtime_inputs.py index 3aa9c4be3..3ab2c7b38 100755 --- a/scripts/checks/test_verify_runtime_inputs.py +++ b/scripts/checks/test_verify_runtime_inputs.py @@ -20,7 +20,6 @@ REPOSITORY = Path(__file__).resolve().parents[2] FIXTURES = ( "pubspec.lock", "linux/CMakeLists.txt", - "linux/packaging/build-libmpv.sh", "linux/packaging/native-inputs.json", "packages/wakelock_plus/pubspec.yaml", "packages/wakelock_plus/pubspec.lock", @@ -122,14 +121,14 @@ class RuntimeInputVerifierTest(unittest.TestCase): def test_rejects_malformed_native_pin_and_version_url_drift(self) -> None: manifest = self._json("linux/packaging/native-inputs.json") - manifest["inputs"]["ffmpeg"]["sha256"] = "not-a-digest" - manifest["inputs"]["mpv"]["url"] = "https://example.invalid/mpv-current.tar.gz" + manifest["inputs"]["simdutf"]["sha256"] = "not-a-digest" + manifest["inputs"]["simdutf"]["url"] = "https://example.invalid/singleheader-current.zip" self._write_json("linux/packaging/native-inputs.json", manifest) errors = CHECKER.validate(self.root) - self.assertTrue(any("ffmpeg.sha256" in error for error in errors)) - self.assertTrue(any("mpv.url" in error and "declared version" in error for error in errors)) + self.assertTrue(any("simdutf.sha256" in error for error in errors)) + self.assertTrue(any("simdutf.url" in error and "declared version" in error for error in errors)) def test_reports_missing_simdutf_fields_without_crashing(self) -> None: manifest = self._json("linux/packaging/native-inputs.json") @@ -143,20 +142,6 @@ class RuntimeInputVerifierTest(unittest.TestCase): self.assertTrue(any("simdutf.url" in error and "non-empty text" in error for error in errors)) self.assertTrue(any("simdutf.sha256" in error and "lowercase full SHA-256" in error for error in errors)) - def test_rejects_disconnected_production_acquisition(self) -> None: - path = self.root / "linux/packaging/build-libmpv.sh" - path.write_text( - path.read_text(encoding="utf-8").replace( - 'download_verified "$MPV_URL" "$MPV_SHA256"', - 'curl "$MPV_URL"', - ), - encoding="utf-8", - ) - - errors = CHECKER.validate(self.root) - - self.assertTrue(any("MPV_URL" in error and "manifest-backed" in error for error in errors)) - def test_rejects_binding_source_or_output_drift(self) -> None: schema = self.root / "packages/wakelock_plus/pigeons/messages.dart" schema.write_text(schema.read_text(encoding="utf-8") + "// changed\n", encoding="utf-8") @@ -214,7 +199,7 @@ class RuntimeInputVerifierTest(unittest.TestCase): def test_accepts_benign_prose_contract_edits(self) -> None: native = self._json("linux/packaging/native-inputs.json") native["refreshContract"] = {"rules": ["Reworded maintainer guidance."]} - native["inputs"]["ffmpeg"]["provenance"] = "Reviewed release evidence." + native["inputs"]["simdutf"]["provenance"] = "Reviewed release evidence." self._write_json("linux/packaging/native-inputs.json", native) provenance = self._json("packages/wakelock_plus/provenance.json") diff --git a/scripts/checks/verify_runtime_inputs.py b/scripts/checks/verify_runtime_inputs.py index 4471f556e..883e62565 100755 --- a/scripts/checks/verify_runtime_inputs.py +++ b/scripts/checks/verify_runtime_inputs.py @@ -13,7 +13,7 @@ from typing import Any HEX_256 = re.compile(r"^[0-9a-f]{64}$") HEX_COMMIT = re.compile(r"^[0-9a-f]{40}$") -NATIVE_NAMES = {"dav1d", "ffmpeg", "shaderc", "libplacebo", "mpv", "simdutf"} +NATIVE_NAMES = {"simdutf"} BINDING_ARTIFACTS = { "pigeons/messages.dart", "android/src/main/kotlin/dev/fluttercommunity/plus/wakelock/WakelockPlusMessages.g.kt", @@ -82,37 +82,18 @@ def _validate_native(root: Path, errors: list[str]) -> None: if not isinstance(value, dict): errors.append(f"{label}: must be an object") continue - kind = value.get("kind") version = _require_text(value.get("version"), f"{label}.version", errors) url = _require_text(value.get("url"), f"{label}.url", errors) _require_text(value.get("provenance"), f"{label}.provenance", errors) if url and not url.startswith("https://"): errors.append(f"{label}.url: production source must use HTTPS") - # A fallback source is optional, but it is a production source when it is - # used, so it answers to the same rule as the primary. - mirror = value.get("mirror") - if mirror is not None: - if not isinstance(mirror, str) or not mirror.startswith("https://"): - errors.append(f"{label}.mirror: production source must use HTTPS") - if version and url and name in {"ffmpeg", "mpv", "simdutf"} and version not in url: + if version and url and version not in url: errors.append(f"{label}.url: must identify declared version {version}") - if kind == "archive": - checksum = value.get("sha256") - if not isinstance(checksum, str) or HEX_256.fullmatch(checksum) is None: - errors.append(f"{label}.sha256: must be a lowercase full SHA-256") - elif kind == "git": - ref = value.get("ref") - commit = value.get("commit") - # dav1d tags releases as bare versions ("1.5.4"); the other pinned - # Git inputs tag them "v{version}". Either way the ref is verified - # against the recorded commit, which is the actual pin. - expected_ref = version if name == "dav1d" else f"v{version}" - if not isinstance(ref, str) or ref != expected_ref: - errors.append(f"{label}.ref: must be {expected_ref}") - if not isinstance(commit, str) or HEX_COMMIT.fullmatch(commit) is None: - errors.append(f"{label}.commit: must be a lowercase full Git commit") - else: - errors.append(f"{label}.kind: must be archive or git") + if value.get("kind") != "archive": + errors.append(f"{label}.kind: must be archive") + checksum = value.get("sha256") + if not isinstance(checksum, str) or HEX_256.fullmatch(checksum) is None: + errors.append(f"{label}.sha256: must be a lowercase full SHA-256") cmake_path = root / "linux/CMakeLists.txt" try: @@ -133,27 +114,6 @@ def _validate_native(root: Path, errors: list[str]) -> None: ): errors.append(f"{cmake_path}: simdutf SHA-256 differs from native-inputs.json") - builder_path = root / "linux/packaging/build-libmpv.sh" - try: - builder = builder_path.read_text(encoding="utf-8") - except OSError as error: - errors.append(f"{builder_path}: cannot read: {error}") - return - required_builder_contracts = ( - "native-inputs.json", - 'download_verified "$FFMPEG_URL" "$FFMPEG_SHA256"', - 'download_verified "$MPV_URL" "$MPV_SHA256"', - '"$DAV1D_URL" "$DAV1D_REF" "$DAV1D_COMMIT"', - '"$SHADERC_URL" "$SHADERC_REF" "$SHADERC_COMMIT"', - '"$LIBPLACEBO_URL" "$LIBPLACEBO_REF" "$LIBPLACEBO_COMMIT"', - 'git submodule update --init --recursive', - ) - for contract_text in required_builder_contracts: - if contract_text not in builder: - errors.append(f"{builder_path}: missing manifest-backed acquisition contract {contract_text!r}") - if re.search(r"curl[^\n]*\|[^\n]*tar", builder): - errors.append(f"{builder_path}: archive extraction must not consume a curl stream") - def _validate_wakelock(root: Path, errors: list[str]) -> None: package = root / "packages/wakelock_plus" diff --git a/scripts/format_native.sh b/scripts/format_native.sh index 11a8d158c..2c6e486b8 100755 --- a/scripts/format_native.sh +++ b/scripts/format_native.sh @@ -182,6 +182,7 @@ append_native_files() { while IFS= read -r -d '' file; do case "$file" in android/app/src/main/cpp/include/*) continue ;; + android/libmpv/src/main/cpp/include/*) continue ;; android/app/src/main/java/io/flutter/plugins/*) continue ;; ios/Flutter/*|macos/Flutter/*|tvos/Flutter/*) continue ;; linux/flutter/*|windows/flutter/*) continue ;; diff --git a/scripts/refresh_apple_spm.sh b/scripts/refresh_apple_spm.sh index 866f82b2d..84b77d260 100755 --- a/scripts/refresh_apple_spm.sh +++ b/scripts/refresh_apple_spm.sh @@ -17,7 +17,7 @@ # without those flags updates the mirror, materializes the checkout, and leaves # the tracked locks untouched. # -# Run this after scripts/set_mpvkit_revision.sh, or after pulling someone else's +# Run this after scripts/set_native_revision.sh, or after pulling someone else's # pin bump, whenever a macOS build reports a commit it cannot find. # # Usage: diff --git a/scripts/set_mpvkit_revision.sh b/scripts/set_mpvkit_revision.sh deleted file mode 100755 index f19f858b0..000000000 --- a/scripts/set_mpvkit_revision.sh +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/bin/env bash -# Move Plezy's MPVKit dependency to an exact upstream commit. -# -# Why this exists: the MPVKit fork publishes content-addressed binaries on every -# push to main -- each xcframework asset is named after a hash of the inputs that -# produced it, so the artifacts for any commit stay downloadable forever and are -# never overwritten. A commit, not a semver tag, is therefore the unit Plezy -# pins: picking up an mpv or FFmpeg patch no longer requires cutting a release -# upstream, and the pin names the exact bytes we ship. -# -# Nine tracked files carry that pin and must move together: -#

/Runner.xcodeproj/project.pbxproj the requirement -#

/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/... the SwiftPM lock -#

/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved Xcode's duplicate lock -# for p in ios, macos, tvos. The duplicate locks are not redundant to us: -# scripts/checks/check_apple_spm_locks.py fails the build when a pair drifts. -# -# Nothing else needs editing: tvos/scripts/wire_mpv.rb reads the sha back out of -# the tvOS lock, so re-wiring the tvOS project cannot revert a bump made here, -# and tvos/scripts/test_wire_mpv.rb asserts all nine sites name one commit. -# -# Usage: -# scripts/set_mpvkit_revision.sh -# -# Rerunning with the same sha is a no-op and says so. Edits are targeted text -# replacements on purpose: `plutil -convert` round-trips would reformat an entire -# pbxproj, and re-serializing Package.resolved would churn every unrelated pin. -# Each file must match exactly once; anything else aborts before a byte is -# written. The locks name the new revision, but no local SwiftPM mirror fetches -# it on its own: a macOS Flutter build resolves with `-skipPackageUpdates` and -# aborts with "could not find the commit " until the mirror catches up. Run -# scripts/refresh_apple_spm.sh afterwards (or open the project in Xcode once). -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -cd "$ROOT" - -if [ "$#" -ne 1 ]; then - echo "usage: scripts/set_mpvkit_revision.sh " >&2 - exit 2 -fi - -REVISION="$1" -if [[ ! "$REVISION" =~ ^[0-9a-f]{40}$ ]]; then - echo "error: '$REVISION' is not a full 40-character lowercase commit sha" >&2 - echo "hint: git -C ../MPVKit rev-parse main" >&2 - exit 2 -fi - -PROJECTS=() -LOCKS=() -MISSING=() -for platform in ios macos tvos; do - PROJECTS+=("$platform/Runner.xcodeproj/project.pbxproj") - LOCKS+=("$platform/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved") - LOCKS+=("$platform/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved") -done - -for target in "${PROJECTS[@]}" "${LOCKS[@]}"; do - if [ ! -f "$target" ]; then - MISSING+=("$target") - fi -done -if [ "${#MISSING[@]}" -gt 0 ]; then - echo "error: missing MPVKit pin site(s); refusing to run:" >&2 - printf ' %s\n' "${MISSING[@]}" >&2 - exit 1 -fi - -MPVKIT_REVISION="$REVISION" python3 - "${#PROJECTS[@]}" "${PROJECTS[@]}" "${LOCKS[@]}" <<'PY' -"""Rewrite the MPVKit requirement and SwiftPM pins in place. - -Every file is parsed and rewritten in memory first; nothing is written unless -all nine edits are unambiguous, so a malformed file can never leave the pin -half-moved. -""" - -from __future__ import annotations - -import json -import os -import re -import sys - -revision = os.environ["MPVKIT_REVISION"] -project_count = int(sys.argv[1]) -projects = sys.argv[2 : 2 + project_count] -locks = sys.argv[2 + project_count :] - -# The `*/ = {` suffix is what makes this anchor unique: the same comment appears -# in packageReferences lists and product dependencies, but only the object -# definition opens a brace. -REQUIREMENT = re.compile( - r'/\* XCRemoteSwiftPackageReference "MPVKit" \*/ = \{\n' - r"(?:[^\n]*\n)*?" - r"(?P[\t ]*)requirement = \{\n" - r"(?P(?:[^\n]*\n)*?)" - r"(?P=indent)\};\n" -) -PIN_STATE = re.compile( - r'"identity"[ \t]*:[ \t]*"mpvkit",\n' - r"(?:[^\n]*\n)*?" - r'(?P[ \t]*)"state"[ \t]*:[ \t]*\{\n' - r"(?P(?:[^\n]*\n)*?)" - r"(?P=indent)\}" -) - -errors: list[str] = [] -writes: list[tuple[str, str]] = [] -unchanged: list[str] = [] - - -def replace_once(pattern: re.Pattern[str], text: str, path: str, render) -> str | None: - matches = list(pattern.finditer(text)) - if len(matches) != 1: - errors.append(f"{path}: expected exactly 1 MPVKit pin, found {len(matches)}") - return None - match = matches[0] - return text[: match.start()] + render(match) + text[match.end() :] - - -def check_lock_schema(path: str, text: str) -> bool: - try: - payload = json.loads(text) - except json.JSONDecodeError as error: - errors.append(f"{path}: not valid JSON ({error})") - return False - version = payload.get("version") if isinstance(payload, dict) else None - if version not in (2, 3): - errors.append(f"{path}: unsupported SwiftPM lock schema version {version!r}") - return False - pins = payload.get("pins") - if not isinstance(pins, list): - errors.append(f"{path}: missing pins array") - return False - pin = next( - ( - item - for item in pins - if isinstance(item, dict) and item.get("identity") == "mpvkit" - ), - None, - ) - if pin is None: - errors.append(f"{path}: no mpvkit pin") - return False - if pin.get("kind") != "remoteSourceControl": - errors.append(f"{path}: mpvkit pin is {pin.get('kind')!r}, expected remoteSourceControl") - return False - return True - - -for path in projects: - with open(path, encoding="utf-8") as handle: - original = handle.read() - - def render(match: re.Match[str]) -> str: - indent = match.group("indent") - head = match.group(0)[: match.start("body") - match.start()] - return ( - f"{head}" - f"{indent}\tkind = revision;\n" - f"{indent}\trevision = {revision};\n" - f"{indent}}};\n" - ) - - updated = replace_once(REQUIREMENT, original, path, render) - if updated is None: - continue - if updated == original: - unchanged.append(path) - else: - writes.append((path, updated)) - -for path in locks: - with open(path, encoding="utf-8") as handle: - original = handle.read() - if not check_lock_schema(path, original): - continue - - def render(match: re.Match[str]) -> str: - indent = match.group("indent") - return ( - match.group(0)[: match.start("body") - match.start()] - + f'{indent} "revision" : "{revision}"\n' - + f"{indent}}}" - ) - - updated = replace_once(PIN_STATE, original, path, render) - if updated is None: - continue - if updated == original: - unchanged.append(path) - else: - writes.append((path, updated)) - -if errors: - for error in errors: - print(f"error: {error}", file=sys.stderr) - sys.exit(1) - -for path, content in writes: - with open(path, "w", encoding="utf-8") as handle: - handle.write(content) - print(f" updated {path}") -for path in unchanged: - print(f" unchanged {path}") - -short = revision[:12] -if writes: - print(f"\nMPVKit pinned to {short} ({len(writes)} file(s) rewritten, {len(unchanged)} already correct).") -else: - print(f"\nMPVKit was already pinned to {short}; nothing to do.") -PY diff --git a/scripts/set_native_revision.sh b/scripts/set_native_revision.sh new file mode 100755 index 000000000..f956c364a --- /dev/null +++ b/scripts/set_native_revision.sh @@ -0,0 +1,590 @@ +#!/usr/bin/env bash +# Move Plezy's native mpv dependency to an exact commit of the unified +# mpv-build repository (github.com/edde746/mpv-build). +# +# Why this exists: the unified repo publishes content-addressed binaries on +# every push to main -- each asset is named after a hash of the inputs that +# produced it, so the artifacts for any commit stay downloadable forever and +# are never overwritten. A commit, not a semver tag, is therefore the unit +# Plezy pins: picking up an mpv or FFmpeg patch no longer requires cutting a +# release upstream, and the pin names the exact bytes we ship on every +# platform, not just Apple. +# +# Ten tracked files carry that pin and must move together: +#

/Runner.xcodeproj/project.pbxproj the requirement +#

/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/... the SwiftPM lock +#

/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved Xcode's duplicate lock +# for p in ios, macos, tvos, plus the root mpv-build.lock.json. The duplicate +# SwiftPM locks are not redundant to us: scripts/checks/check_apple_spm_locks.py +# fails the build when a pair drifts, and tvos/scripts/test_wire_mpv.rb asserts +# all ten sites name one commit. +# +# mpv-build.lock.json is how the non-Apple platforms consume the same pin. +# JSON cannot carry comments, so its schema lives here: +# +# { +# "formatVersion": 1, +# "repo": "edde746/mpv-build", the GitHub repo the commit lives in +# "commit": "", must equal the nine Apple pin sites +# "artifacts": { one entry per published non-apple group +# "": { android | linux | windows +# "key": "<12-hex>", the group's content-address key +# "assetBase": "https://...", release download base for the assets +# "assets": { one entry per platform variant +# "": { e.g. an Android ABI +# "asset": "", downloaded as / +# "checksum": "" of the complete asset file +# } +# } +# } +# } +# } +# +# The artifacts map is extracted from artifacts.json at the pinned commit; +# groups that commit has not published yet are omitted, and each omission is +# noted on stdout. Serialization is deterministic: two-space indent, sorted +# keys, trailing newline. Consumers must fail when their group is missing +# rather than fall back to an unpinned source. +# +# Usage: +# scripts/set_native_revision.sh [--repo ] +# +# The commit's artifacts.json and versions.json are read from, in order: the +# --repo override (a local checkout or an https URL), a local checkout at +# ../mpv-build that contains the commit, else +# https://raw.githubusercontent.com/edde746/mpv-build. A commit without those +# manifests is refused: it predates the unified repo and cannot be pinned by +# this script. +# +# The pin names a repository as well as a commit. The target repo is derived +# from the source actually used: a GitHub --repo URL names it directly, a +# local checkout is asked for its origin remote, and anything else falls back +# to edde746/mpv-build. When the target differs from the repo the pin sites +# currently carry (e.g. the first flip away from edde746/MPVKit), the same +# all-or-nothing pass also rewrites each pbxproj repositoryURL and the +# package-name comments Xcode derives from it, and each Package.resolved +# location plus the identity SwiftPM derives from the URL's last path +# component. +# +# Rerunning with the same sha is a no-op and says so. Edits to the Apple pin +# sites are targeted text replacements on purpose: `plutil -convert` +# round-trips would reformat an entire pbxproj, and re-serializing +# Package.resolved would churn every unrelated pin. Each file must match +# exactly once; anything else aborts before a byte is written -- the lock file +# included. The locks name the new revision, but no local SwiftPM mirror +# fetches it on its own: a macOS Flutter build resolves with +# `-skipPackageUpdates` and aborts with "could not find the commit " +# until the mirror catches up. Run scripts/refresh_apple_spm.sh afterwards (or +# open the project in Xcode once). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +cd "$ROOT" + +usage() { + echo "usage: scripts/set_native_revision.sh [--repo ]" >&2 + exit 2 +} + +REVISION="" +REPO_ARG="" +while [ "$#" -gt 0 ]; do + case "$1" in + --repo) + [ "$#" -ge 2 ] || usage + REPO_ARG="$2" + shift 2 + ;; + --*) + usage + ;; + *) + [ -z "$REVISION" ] || usage + REVISION="$1" + shift + ;; + esac +done +[ -n "$REVISION" ] || usage + +if [[ ! "$REVISION" =~ ^[0-9a-f]{40}$ ]]; then + echo "error: '$REVISION' is not a full 40-character lowercase commit sha" >&2 + echo "hint: git -C ../mpv-build rev-parse HEAD" >&2 + exit 2 +fi + +# ---- locate the commit's manifests ---------------------------------------- + +MANIFEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/set-native-revision.XXXXXX")" +trap 'rm -rf "$MANIFEST_DIR"' EXIT + +local_has_commit() { + git -C "$1" rev-parse --git-dir >/dev/null 2>&1 \ + && git -C "$1" cat-file -e "$REVISION^{commit}" 2>/dev/null +} + +# Extract one manifest file from the resolved source into MANIFEST_DIR. +# A missing file means the commit predates the unified repo; refuse it. +fetch_manifest() { + local name="$1" + case "$SOURCE_KIND" in + local) + if ! git -C "$SOURCE" cat-file blob "$REVISION:$name" >"$MANIFEST_DIR/$name" 2>/dev/null; then + echo "error: $REVISION has no $name in $SOURCE; not a unified mpv-build commit" >&2 + exit 1 + fi + ;; + remote) + if ! curl -fsSL "$SOURCE/$REVISION/$name" -o "$MANIFEST_DIR/$name"; then + echo "error: could not fetch $SOURCE/$REVISION/$name; not a unified mpv-build commit?" >&2 + exit 1 + fi + ;; + esac +} + +# GitHub repo URLs serve files through raw.githubusercontent.com; anything +# else is taken as a base already serving //. +remote_base() { + local url="${1%/}" + url="${url%.git}" + case "$url" in + https://github.com/*) + echo "https://raw.githubusercontent.com/${url#https://github.com/}" + ;; + *) + echo "$url" + ;; + esac +} + +# owner/name from a GitHub remote URL (https, ssh, or raw form); empty when +# the URL does not name a GitHub repo. +github_slug() { + local url="${1%/}" + url="${url%.git}" + case "$url" in + https://github.com/*/*) url="${url#https://github.com/}" ;; + https://raw.githubusercontent.com/*/*) url="${url#https://raw.githubusercontent.com/}" ;; + ssh://git@github.com/*/*) url="${url#ssh://git@github.com/}" ;; + git@github.com:*/*) url="${url#git@github.com:}" ;; + *) return 0 ;; + esac + local owner="${url%%/*}" rest="${url#*/}" + echo "$owner/${rest%%/*}" +} + +SOURCE_KIND="" +SOURCE="" +if [ -n "$REPO_ARG" ]; then + case "$REPO_ARG" in + http://*|https://*) + SOURCE_KIND="remote" + SOURCE="$(remote_base "$REPO_ARG")" + ;; + *) + if [ ! -d "$REPO_ARG" ]; then + echo "error: --repo '$REPO_ARG' is neither a directory nor an https URL" >&2 + exit 2 + fi + if ! local_has_commit "$REPO_ARG"; then + echo "error: $REPO_ARG does not contain commit $REVISION" >&2 + echo "hint: git -C $REPO_ARG fetch" >&2 + exit 1 + fi + SOURCE_KIND="local" + SOURCE="$REPO_ARG" + ;; + esac +else + if [ -d ../mpv-build ] && local_has_commit ../mpv-build; then + SOURCE_KIND="local" + SOURCE="../mpv-build" + else + SOURCE_KIND="remote" + SOURCE="https://raw.githubusercontent.com/edde746/mpv-build" + fi +fi + +# The GitHub repo the pins will name, derived from the actual source used. +CANONICAL_REPO="edde746/mpv-build" +TARGET_REPO="" +case "$SOURCE_KIND" in + local) + TARGET_REPO="$(github_slug "$(git -C "$SOURCE" remote get-url origin 2>/dev/null || true)")" + ;; + remote) + TARGET_REPO="$(github_slug "$SOURCE")" + ;; +esac +[ -n "$TARGET_REPO" ] || TARGET_REPO="$CANONICAL_REPO" + +echo "reading manifests for ${REVISION:0:12} from $SOURCE" +fetch_manifest artifacts.json +fetch_manifest versions.json + +# ---- collect the Apple pin sites ------------------------------------------ + +PROJECTS=() +LOCKS=() +MISSING=() +for platform in ios macos tvos; do + PROJECTS+=("$platform/Runner.xcodeproj/project.pbxproj") + LOCKS+=("$platform/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved") + LOCKS+=("$platform/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved") +done + +for target in "${PROJECTS[@]}" "${LOCKS[@]}"; do + if [ ! -f "$target" ]; then + MISSING+=("$target") + fi +done +if [ "${#MISSING[@]}" -gt 0 ]; then + echo "error: missing native pin site(s); refusing to run:" >&2 + printf ' %s\n' "${MISSING[@]}" >&2 + exit 1 +fi + +MPV_BUILD_REVISION="$REVISION" MPV_BUILD_MANIFEST_DIR="$MANIFEST_DIR" MPV_BUILD_REPO="$TARGET_REPO" \ + python3 - "${#PROJECTS[@]}" "${PROJECTS[@]}" "${LOCKS[@]}" <<'PY' +"""Rewrite the native requirement, SwiftPM pins, and mpv-build.lock.json. + +Every file is parsed and rewritten in memory first; nothing is written unless +all nine Apple edits are unambiguous and the lock can be derived completely, +so a malformed file can never leave the pin half-moved. When the target repo +differs from the one the pin sites carry, the pbxproj repositoryURL and its +package-name comments, the Package.resolved location, and the identity SwiftPM +derives from the URL move in the same pass. +""" + +from __future__ import annotations + +import json +import os +import re +import sys +from pathlib import Path + +revision = os.environ["MPV_BUILD_REVISION"] +manifest_dir = Path(os.environ["MPV_BUILD_MANIFEST_DIR"]) +project_count = int(sys.argv[1]) +projects = sys.argv[2 : 2 + project_count] +locks = sys.argv[2 + project_count :] + +LOCK_PATH = "mpv-build.lock.json" +LOCK_REPO = os.environ["MPV_BUILD_REPO"] +TARGET_URL = f"https://github.com/{LOCK_REPO}" +# Xcode names the package after the URL's last path component; SwiftPM +# lowercases that same component into the pin identity. +TARGET_NAME = LOCK_REPO.rsplit("/", 1)[-1] +TARGET_IDENTITY = TARGET_NAME.lower() +LEGACY_IDENTITY = "mpvkit" # the pre-flip edde746/MPVKit pin +ACCEPTED_IDENTITIES = {LEGACY_IDENTITY, TARGET_IDENTITY} +EXPECTED_GROUPS = ("android", "linux", "windows") +KEY_RE = re.compile(r"\A[0-9a-f]{12}\Z") +CHECKSUM_RE = re.compile(r"\A[0-9a-f]{64}\Z") + + +def url_identity(url: str) -> str: + """The identity SwiftPM derives from a repository URL.""" + tail = url.rstrip("/") + if tail.endswith(".git"): + tail = tail[:-4] + return tail.rsplit("/", 1)[-1].lower() + + +# The `*/ = {` suffix is what makes this anchor unique: the same comment appears +# in packageReferences lists and product dependencies, but only the object +# definition opens a brace. The package name is not anchored -- it tracks the +# repo and moves with it -- so matches are filtered by the URL's identity. +PACKAGE_REFERENCE = re.compile( + r'/\* XCRemoteSwiftPackageReference "(?P[^"]+)" \*/ = \{\n' + r"(?:[^\n]*\n)*?" + r'[\t ]*repositoryURL = "(?P[^"]+)";\n' + r"(?:[^\n]*\n)*?" + r"(?P[\t ]*)requirement = \{\n" + r"(?P(?:[^\n]*\n)*?)" + r"(?P=indent)\};\n" +) +PIN = re.compile( + r'"identity"[ \t]*:[ \t]*"(?P[^"]+)",\n' + r"(?:[^\n]*\n)*?" + r'[ \t]*"location"[ \t]*:[ \t]*"(?P[^"]+)",\n' + r"(?:[^\n]*\n)*?" + r'(?P[ \t]*)"state"[ \t]*:[ \t]*\{\n' + r"(?P(?:[^\n]*\n)*?)" + r"(?P=indent)\}" +) + +errors: list[str] = [] +notes: list[str] = [] +writes: list[tuple[str, str]] = [] +unchanged: list[str] = [] + + +def sole_pin(pattern: re.Pattern[str], text: str, path: str) -> re.Match[str] | None: + """The one match that is the native pin, judged by its URL's identity.""" + matches = [ + match + for match in pattern.finditer(text) + if url_identity(match.group("url")) in ACCEPTED_IDENTITIES + ] + if len(matches) != 1: + errors.append(f"{path}: expected exactly 1 native pin, found {len(matches)}") + return None + return matches[0] + + +def splice(text: str, match: re.Match[str], replacements: list[tuple[str, str]]) -> str: + """text with each named group's matched span replaced by new content.""" + parts = [] + cursor = 0 + for group, new in sorted(replacements, key=lambda item: match.start(item[0])): + start, end = match.span(group) + parts.append(text[cursor:start]) + parts.append(new) + cursor = end + parts.append(text[cursor:]) + return "".join(parts) + + +def check_lock_schema(path: str, text: str) -> bool: + try: + payload = json.loads(text) + except json.JSONDecodeError as error: + errors.append(f"{path}: not valid JSON ({error})") + return False + version = payload.get("version") if isinstance(payload, dict) else None + if version not in (2, 3): + errors.append(f"{path}: unsupported SwiftPM lock schema version {version!r}") + return False + pins = payload.get("pins") + if not isinstance(pins, list): + errors.append(f"{path}: missing pins array") + return False + pin = next( + ( + item + for item in pins + if isinstance(item, dict) and item.get("identity") in ACCEPTED_IDENTITIES + ), + None, + ) + if pin is None: + errors.append(f"{path}: no native pin") + return False + if pin.get("kind") != "remoteSourceControl": + errors.append(f"{path}: native pin is {pin.get('kind')!r}, expected remoteSourceControl") + return False + return True + + +def load_manifest(name: str, label: str) -> dict | None: + try: + payload = json.loads((manifest_dir / name).read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as error: + errors.append(f"{label} at {revision[:12]}: not valid JSON ({error})") + return None + if not isinstance(payload, dict): + errors.append(f"{label} at {revision[:12]}: expected a JSON object") + return None + return payload + + +def build_lock() -> str | None: + """The lock file's content for this commit, or None with errors recorded. + + Schema documented in this script's header comment. The versions.json read + is a guard, not a data source: a commit without formatVersion 1 predates + the unified repo, and pinning it would name artifacts that do not exist. + """ + versions = load_manifest("versions.json", "versions.json") + manifest = load_manifest("artifacts.json", "artifacts.json") + if versions is None or manifest is None: + return None + if versions.get("formatVersion") != 1: + errors.append( + f"versions.json at {revision[:12]}: formatVersion is " + f"{versions.get('formatVersion')!r}, expected 1" + ) + return None + if manifest.get("schema") != 2: + errors.append( + f"artifacts.json at {revision[:12]}: schema is " + f"{manifest.get('schema')!r}, expected 2" + ) + return None + platforms = manifest.get("platforms") + if not isinstance(platforms, dict): + errors.append(f"artifacts.json at {revision[:12]}: no platforms object") + return None + + artifacts: dict[str, dict] = {} + for group in sorted(platforms): + if group == "apple": + continue # Apple consumes the SwiftPM pin sites, not the lock. + section = platforms[group] + label = f"artifacts.json platforms.{group}" + if not isinstance(section, dict): + errors.append(f"{label}: expected an object") + continue + asset_base = section.get("assetBase") + if not isinstance(asset_base, str) or not asset_base: + errors.append(f"{label}.assetBase: missing") + continue + libraries = section.get("libraries") + if not isinstance(libraries, dict): + errors.append(f"{label}.libraries: expected an object") + continue + if not libraries: + notes.append( + f"note: {group} has published no libraries at this commit; " + f"omitted from {LOCK_PATH}" + ) + continue + if len(libraries) != 1: + errors.append( + f"{label}: {LOCK_PATH} formatVersion 1 records exactly one " + f"library per group, found {sorted(libraries)}; bump the lock format" + ) + continue + ((library, entry),) = libraries.items() + label = f"{label}.libraries.{library}" + if not isinstance(entry, dict): + errors.append(f"{label}: expected an object") + continue + key = entry.get("key") + if not isinstance(key, str) or not KEY_RE.fullmatch(key): + errors.append(f"{label}.key: {key!r} is not a 12-hex content key") + continue + prebuilt = entry.get("prebuilt") + if not isinstance(prebuilt, dict) or not prebuilt: + errors.append(f"{label}.prebuilt: no per-variant assets recorded") + continue + assets: dict[str, dict[str, str]] = {} + for variant in sorted(prebuilt): + value = prebuilt[variant] + if not isinstance(value, dict): + errors.append( + f"{label}.prebuilt.{variant}: {value!r} carries no checksum; " + f"refusing an unverifiable pin" + ) + continue + asset = value.get("asset") + checksum = value.get("checksum") + if not isinstance(asset, str) or not asset: + errors.append(f"{label}.prebuilt.{variant}.asset: missing") + continue + if not isinstance(checksum, str) or not CHECKSUM_RE.fullmatch(checksum): + errors.append( + f"{label}.prebuilt.{variant}.checksum: {checksum!r} is not a " + f"full lowercase SHA-256" + ) + continue + assets[variant] = {"asset": asset, "checksum": checksum} + if len(assets) != len(prebuilt): + continue + artifacts[group] = {"assetBase": asset_base, "assets": assets, "key": key} + + for group in EXPECTED_GROUPS: + if group not in artifacts and group not in platforms: + notes.append( + f"note: no {group} artifacts published at this commit; " + f"omitted from {LOCK_PATH}" + ) + + lock = { + "artifacts": artifacts, + "commit": revision, + "formatVersion": 1, + "repo": LOCK_REPO, + } + return json.dumps(lock, indent=2, sort_keys=True) + "\n" + + +for path in projects: + with open(path, encoding="utf-8") as handle: + original = handle.read() + + match = sole_pin(PACKAGE_REFERENCE, original, path) + if match is None: + continue + indent = match.group("indent") + updated = splice( + original, + match, + [ + ("url", TARGET_URL), + ("body", f"{indent}\tkind = revision;\n{indent}\trevision = {revision};\n"), + ], + ) + # Xcode derives the `XCRemoteSwiftPackageReference ""` comments from + # the URL; every mention of the old name refers to this one reference, so + # renaming them all keeps the file exactly as Xcode would regenerate it. + old_name = match.group("name") + if old_name != TARGET_NAME: + updated = updated.replace( + f'/* XCRemoteSwiftPackageReference "{old_name}" */', + f'/* XCRemoteSwiftPackageReference "{TARGET_NAME}" */', + ) + if updated == original: + unchanged.append(path) + else: + writes.append((path, updated)) + +for path in locks: + with open(path, encoding="utf-8") as handle: + original = handle.read() + if not check_lock_schema(path, original): + continue + + match = sole_pin(PIN, original, path) + if match is None: + continue + indent = match.group("indent") + updated = splice( + original, + match, + [ + ("identity", TARGET_IDENTITY), + ("url", TARGET_URL), + ("body", f'{indent} "revision" : "{revision}"\n'), + ], + ) + if updated == original: + unchanged.append(path) + else: + writes.append((path, updated)) + +lock_content = build_lock() +if lock_content is not None: + try: + existing_lock = Path(LOCK_PATH).read_text(encoding="utf-8") + except OSError: + existing_lock = None + if lock_content == existing_lock: + unchanged.append(LOCK_PATH) + else: + writes.append((LOCK_PATH, lock_content)) + +if errors: + for error in errors: + print(f"error: {error}", file=sys.stderr) + sys.exit(1) + +for path, content in writes: + with open(path, "w", encoding="utf-8") as handle: + handle.write(content) + print(f" updated {path}") +for path in unchanged: + print(f" unchanged {path}") +for note in notes: + print(note) + +short = f"{LOCK_REPO}@{revision[:12]}" +if writes: + print(f"\nNative pin moved to {short} ({len(writes)} file(s) rewritten, {len(unchanged)} already correct).") +else: + print(f"\nNative pin was already at {short}; nothing to do.") +PY diff --git a/scripts/test_set_native_revision.py b/scripts/test_set_native_revision.py new file mode 100755 index 000000000..d0f94609a --- /dev/null +++ b/scripts/test_set_native_revision.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Behavior tests for scripts/set_native_revision.sh. + +The script moves ten pin sites at once and promises all-or-nothing: either +every Apple requirement, every SwiftPM lock, and mpv-build.lock.json move to +the new commit together, or nothing is written. These tests drive the real +script end to end against a synthetic Plezy tree and a real (temporary) git +checkout of the unified mpv-build repo, because the failure that matters -- +a half-moved pin -- can only happen across process and file boundaries. + +The pin-site fixtures reproduce the exact anchors the rewrites key on: the +pbxproj carries the `/* XCRemoteSwiftPackageReference "MPVKit" */ = {` object +plus the same comment inside a packageReferences list and a product +dependency (which must NOT match), and the SwiftPM locks are version-3 files +with an unrelated pin that must survive untouched. The fixtures are staged at +the pre-flip edde746/MPVKit state, so every successful run also exercises the +repo flip to edde746/mpv-build: repositoryURL, SwiftPM identity, and the +pbxproj comment strings move with the revision in one all-or-nothing pass. +""" + +import json +import http.server +import os +import shutil +import subprocess +import tempfile +import threading +import unittest +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +SCRIPT = SCRIPT_DIR / "set_native_revision.sh" + +OLD_SHA = "b" * 40 +OLD_URL = "https://github.com/edde746/MPVKit" +NEW_REPO = "edde746/mpv-build" +NEW_URL = f"https://github.com/{NEW_REPO}" +NEW_KEY_ANDROID = "aa11bb22cc33" +NEW_KEY_LINUX = "dd44ee55ff66" + +PBXPROJ_TEMPLATE = """\ +// !$*UTF8*$! +{{ +\tobjects = {{ +\t\t97C146E61CF9000F007C117D /* Project object */ = {{ +\t\t\tisa = PBXProject; +\t\t\tpackageReferences = ( +\t\t\t\tCEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "MPVKit" */, +\t\t\t); +\t\t}}; +\t\tCEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "MPVKit" */ = {{ +\t\t\tisa = XCRemoteSwiftPackageReference; +\t\t\trepositoryURL = "https://github.com/edde746/MPVKit"; +\t\t\trequirement = {{ +\t\t\t\tkind = revision; +\t\t\t\trevision = {revision}; +\t\t\t}}; +\t\t}}; +\t\tEA0F4263E7B912702C490108 /* MPVKit */ = {{ +\t\t\tisa = XCSwiftPackageProductDependency; +\t\t\tpackage = CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "MPVKit" */; +\t\t\tproductName = MPVKit; +\t\t}}; +\t}}; +\trootObject = 97C146E61CF9000F007C117D /* Project object */; +}} +""" + +RESOLVED_TEMPLATE = { + "originHash": "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee", + "pins": [ + { + "identity": "mpvkit", + "kind": "remoteSourceControl", + "location": "https://github.com/edde746/MPVKit", + "state": {"revision": OLD_SHA}, + }, + { + "identity": "unrelated", + "kind": "remoteSourceControl", + "location": "https://example.invalid/unrelated", + "state": {"revision": "c" * 40}, + }, + ], + "version": 3, +} + +VERSIONS_FIXTURE = {"formatVersion": 1, "components": {"mpv": {"version": "0.40.0"}}} + + +def android_section() -> dict: + return { + "assetBase": "https://github.com/edde746/MPVKit/releases/download/binaries-android", + "libraries": { + "libmpv-android": { + "key": NEW_KEY_ANDROID, + "prebuilt": { + abi: { + "asset": f"libmpv-android-{NEW_KEY_ANDROID}-{abi}.tar.gz", + "checksum": format(index, "x") * 64, + } + for index, abi in enumerate( + ("arm64-v8a", "armeabi-v7a", "x86", "x86_64"), start=1 + ) + }, + } + }, + } + + +def linux_section() -> dict: + return { + "assetBase": "https://github.com/edde746/MPVKit/releases/download/binaries-linux", + "libraries": { + "libmpv-linux": { + "key": NEW_KEY_LINUX, + "prebuilt": { + "x86_64": { + "asset": f"libmpv-linux-{NEW_KEY_LINUX}-x86_64.tar.gz", + "checksum": "5" * 64, + } + }, + } + }, + } + + +def apple_section() -> dict: + return { + "assetBase": "https://github.com/edde746/MPVKit/releases/download/binaries-apple", + "libraries": { + "libmpv": { + "frameworks": { + "Libmpv": { + "asset": "Libmpv-e73a34ad67f2.xcframework.zip", + "checksum": "6" * 64, + } + }, + "key": "e73a34ad67f2", + "prebuilt": {"ios": "libmpv-all-e73a34ad67f2-ios.zip"}, + } + }, + } + + +def artifacts_fixture() -> dict: + # windows deliberately absent: its omission note is part of the contract. + return { + "platforms": { + "apple": apple_section(), + "android": android_section(), + "linux": linux_section(), + }, + "schema": 2, + } + + +class SetNativeRevisionTest(unittest.TestCase): + def setUp(self) -> None: + self.temporary = Path(tempfile.mkdtemp(prefix="set-native-revision-test.")) + self.addCleanup(shutil.rmtree, self.temporary, ignore_errors=True) + self.root = self.temporary / "plezy" + self._stage_plezy_tree() + + # ---- fixtures --------------------------------------------------------- + + def _stage_plezy_tree(self) -> None: + scripts = self.root / "scripts" + scripts.mkdir(parents=True) + shutil.copy2(SCRIPT, scripts / SCRIPT.name) + for platform in ("ios", "macos", "tvos"): + base = self.root / platform + (base / "Runner.xcodeproj").mkdir(parents=True) + self._pbxproj(platform).write_text( + PBXPROJ_TEMPLATE.format(revision=OLD_SHA), encoding="utf-8" + ) + for lock in self._resolved(platform): + lock.parent.mkdir(parents=True) + lock.write_text( + json.dumps(RESOLVED_TEMPLATE, indent=2) + "\n", encoding="utf-8" + ) + + def _pbxproj(self, platform: str) -> Path: + return self.root / platform / "Runner.xcodeproj" / "project.pbxproj" + + def _resolved(self, platform: str) -> list[Path]: + return [ + self.root + / platform + / "Runner.xcodeproj" + / "project.xcworkspace" + / "xcshareddata" + / "swiftpm" + / "Package.resolved", + self.root + / platform + / "Runner.xcworkspace" + / "xcshareddata" + / "swiftpm" + / "Package.resolved", + ] + + def _pin_sites(self) -> list[Path]: + sites = [] + for platform in ("ios", "macos", "tvos"): + sites.append(self._pbxproj(platform)) + sites.extend(self._resolved(platform)) + return sites + + def _make_mpv_build( + self, name: str = "mpv-build", *, artifacts: dict | None = None, manifests: bool = True + ) -> tuple[Path, str]: + """A real git checkout carrying the manifests, and its HEAD commit.""" + repo = self.temporary / name + repo.mkdir() + if manifests: + (repo / "artifacts.json").write_text( + json.dumps(artifacts or artifacts_fixture(), indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + (repo / "versions.json").write_text( + json.dumps(VERSIONS_FIXTURE, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + else: + (repo / "README.md").write_text("pre-migration MPVKit\n", encoding="utf-8") + git = self._git(repo) + subprocess.run(git[:3] + ["init", "-q"], check=True) + subprocess.run(git + ["add", "-A"], check=True) + subprocess.run(git + ["commit", "-q", "-m", "fixture"], check=True) + head = subprocess.run( + git[:3] + ["rev-parse", "HEAD"], check=True, capture_output=True, text=True + ).stdout.strip() + return repo, head + + def _git(self, repo: Path) -> list[str]: + return [ + "git", + "-C", + str(repo), + "-c", + "user.name=fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + ] + + def _advance(self, repo: Path) -> str: + """A second commit in the fixture repo, so the pin can move again.""" + (repo / "CHANGELOG").write_text("moved\n", encoding="utf-8") + git = self._git(repo) + subprocess.run(git + ["add", "-A"], check=True) + subprocess.run(git + ["commit", "-q", "-m", "fixture 2"], check=True) + return subprocess.run( + git[:3] + ["rev-parse", "HEAD"], check=True, capture_output=True, text=True + ).stdout.strip() + + def _run(self, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["bash", str(self.root / "scripts" / SCRIPT.name), *args], + check=False, + capture_output=True, + text=True, + ) + + def _snapshot(self) -> dict[Path, str]: + """Byte content of every pin site that exists right now.""" + return { + site: site.read_text(encoding="utf-8") + for site in self._pin_sites() + if site.exists() + } + + def _expected_lock(self, commit: str, repo: str = NEW_REPO) -> str: + artifacts = {} + for group, section in (("android", android_section()), ("linux", linux_section())): + ((_, entry),) = section["libraries"].items() + artifacts[group] = { + "assetBase": section["assetBase"], + "assets": entry["prebuilt"], + "key": entry["key"], + } + lock = { + "artifacts": artifacts, + "commit": commit, + "formatVersion": 1, + "repo": repo, + } + return json.dumps(lock, indent=2, sort_keys=True) + "\n" + + # ---- the pin moves as one unit ---------------------------------------- + + def _assert_pinned(self, commit: str, url: str = NEW_URL) -> None: + """All nine Apple sites name url@commit with coherent names/identities.""" + name = url.rsplit("/", 1)[-1] + for platform in ("ios", "macos", "tvos"): + pbxproj = self._pbxproj(platform).read_text(encoding="utf-8") + self.assertIn(f"revision = {commit};", pbxproj) + self.assertIn(f'repositoryURL = "{url}";', pbxproj) + # Xcode derives these comments from the URL's last path component; + # all three mentions (packageReferences list, object definition, + # product dependency) must carry the same name. + self.assertEqual( + pbxproj.count(f'/* XCRemoteSwiftPackageReference "{name}" */'), 3 + ) + # The product name comes from Package.swift, not the URL. + self.assertIn("productName = MPVKit;", pbxproj) + for lock in self._resolved(platform): + resolved = json.loads(lock.read_text(encoding="utf-8")) + by_identity = {pin["identity"]: pin for pin in resolved["pins"]} + pin = by_identity[name.lower()] + self.assertEqual(pin["location"], url) + self.assertEqual(pin["state"]["revision"], commit) + # Targeted edit: the unrelated pin and originHash never churn. + self.assertEqual(by_identity["unrelated"]["state"]["revision"], "c" * 40) + self.assertEqual( + by_identity["unrelated"]["location"], "https://example.invalid/unrelated" + ) + self.assertEqual(resolved["originHash"], RESOLVED_TEMPLATE["originHash"]) + + def test_the_flip_rewrites_every_pin_site_and_derives_the_lock(self) -> None: + # The tree starts at the pre-flip edde746/MPVKit pin; a run against the + # unified repo must move URL, identity, comments, and revision at all + # nine Apple sites and derive the lock's repo from the source used. + repo, commit = self._make_mpv_build() + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 0, result.stderr) + self._assert_pinned(commit) + for platform in ("ios", "macos", "tvos"): + pbxproj = self._pbxproj(platform).read_text(encoding="utf-8") + self.assertNotIn(OLD_SHA, pbxproj) + self.assertNotIn(OLD_URL, pbxproj) + self.assertNotIn('XCRemoteSwiftPackageReference "MPVKit"', pbxproj) + self.assertEqual( + (self.root / "mpv-build.lock.json").read_text(encoding="utf-8"), + self._expected_lock(commit), + ) + self.assertIn( + "note: no windows artifacts published at this commit; " + "omitted from mpv-build.lock.json", + result.stdout, + ) + + def test_default_source_is_the_sibling_checkout(self) -> None: + # No --repo: the ../mpv-build convention must find the checkout + # sitting next to the Plezy tree. + _, commit = self._make_mpv_build() + + result = self._run(commit) + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("../mpv-build", result.stdout) + self.assertIn(f"revision = {commit};", self._pbxproj("ios").read_text(encoding="utf-8")) + + def test_remote_source_serves_the_manifests_by_commit(self) -> None: + docroot = self.temporary / "raw" + commit = "d" * 40 + (docroot / commit).mkdir(parents=True) + (docroot / commit / "artifacts.json").write_text( + json.dumps(artifacts_fixture()), encoding="utf-8" + ) + (docroot / commit / "versions.json").write_text( + json.dumps(VERSIONS_FIXTURE), encoding="utf-8" + ) + handler = lambda *args, **kwargs: http.server.SimpleHTTPRequestHandler( # noqa: E731 + *args, directory=str(docroot), **kwargs + ) + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + + result = self._run(commit, "--repo", f"http://127.0.0.1:{server.server_address[1]}") + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + (self.root / "mpv-build.lock.json").read_text(encoding="utf-8"), + self._expected_lock(commit), + ) + + def test_rerun_with_the_same_commit_is_a_reported_noop(self) -> None: + repo, commit = self._make_mpv_build() + first = self._run(commit, "--repo", str(repo)) + self.assertEqual(first.returncode, 0, first.stderr) + before = self._snapshot() + lock_before = (self.root / "mpv-build.lock.json").read_text(encoding="utf-8") + + second = self._run(commit, "--repo", str(repo)) + + self.assertEqual(second.returncode, 0, second.stderr) + self.assertIn("nothing to do", second.stdout) + self.assertEqual(self._snapshot(), before) + self.assertEqual( + (self.root / "mpv-build.lock.json").read_text(encoding="utf-8"), lock_before + ) + + def test_a_move_within_the_target_repo_only_touches_revisions(self) -> None: + # Once flipped, a later pin move must not churn URLs, identities, or + # comment names -- only the revisions and the lock's commit change. + repo, first_commit = self._make_mpv_build() + first = self._run(first_commit, "--repo", str(repo)) + self.assertEqual(first.returncode, 0, first.stderr) + second_commit = self._advance(repo) + + result = self._run(second_commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 0, result.stderr) + self._assert_pinned(second_commit) + self.assertEqual( + (self.root / "mpv-build.lock.json").read_text(encoding="utf-8"), + self._expected_lock(second_commit), + ) + + def test_lock_repo_derives_from_the_local_checkouts_origin_remote(self) -> None: + # The pin names whichever GitHub repo actually served the commit, so a + # checkout cloned from a fork flips every site to that fork. + repo, commit = self._make_mpv_build() + subprocess.run( + self._git(repo)[:3] + + ["remote", "add", "origin", "git@github.com:someone/mpv-build.git"], + check=True, + ) + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 0, result.stderr) + self._assert_pinned(commit, url="https://github.com/someone/mpv-build") + self.assertEqual( + (self.root / "mpv-build.lock.json").read_text(encoding="utf-8"), + self._expected_lock(commit, repo="someone/mpv-build"), + ) + + # ---- refusals leave every byte alone ---------------------------------- + + def test_refuses_a_malformed_sha(self) -> None: + before = self._snapshot() + + result = self._run("deadbeef") + + self.assertEqual(result.returncode, 2) + self.assertIn("not a full 40-character lowercase commit sha", result.stderr) + self.assertEqual(self._snapshot(), before) + + def test_refuses_when_a_pin_site_is_missing(self) -> None: + repo, commit = self._make_mpv_build() + removed = self._resolved("macos")[1] + removed.unlink() + before = self._snapshot() + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 1) + self.assertIn("missing native pin site(s)", result.stderr) + self.assertIn(str(removed.relative_to(self.root)), result.stderr) + self.assertEqual(self._snapshot(), before) + self.assertFalse((self.root / "mpv-build.lock.json").exists()) + + def test_an_ambiguous_edit_aborts_before_any_write(self) -> None: + repo, commit = self._make_mpv_build() + pbxproj = self._pbxproj("tvos") + content = pbxproj.read_text(encoding="utf-8") + anchor = '/* XCRemoteSwiftPackageReference "MPVKit" */ = {' + duplicated = content.replace( + "\trootObject", + "\t\tDUPLICATE " + anchor + "\n" + '\t\t\trepositoryURL = "https://github.com/edde746/MPVKit";\n' + "\t\t\trequirement = {\n" + "\t\t\t\tkind = revision;\n" + f"\t\t\t\trevision = {OLD_SHA};\n" + "\t\t\t};\n" + "\t\t};\n" + "\trootObject", + ) + pbxproj.write_text(duplicated, encoding="utf-8") + before = self._snapshot() + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 1) + self.assertIn("expected exactly 1 native pin, found 2", result.stderr) + # All-or-nothing: the eight unambiguous sites must not have moved, and + # no lock may appear alongside a refused pin. + self.assertEqual(self._snapshot(), before) + self.assertFalse((self.root / "mpv-build.lock.json").exists()) + + def test_refuses_a_commit_that_predates_the_unified_repo(self) -> None: + repo, commit = self._make_mpv_build(name="MPVKit", manifests=False) + before = self._snapshot() + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 1) + self.assertIn("not a unified mpv-build commit", result.stderr) + self.assertEqual(self._snapshot(), before) + + def test_refuses_a_checksumless_prebuilt_asset(self) -> None: + artifacts = artifacts_fixture() + android = artifacts["platforms"]["android"]["libraries"]["libmpv-android"] + android["prebuilt"]["arm64-v8a"] = f"libmpv-android-{NEW_KEY_ANDROID}-arm64-v8a.tar.gz" + repo, commit = self._make_mpv_build(artifacts=artifacts) + before = self._snapshot() + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 1) + self.assertIn("carries no checksum", result.stderr) + self.assertEqual(self._snapshot(), before) + self.assertFalse((self.root / "mpv-build.lock.json").exists()) + + def test_a_group_with_no_published_libraries_is_omitted_with_a_note(self) -> None: + artifacts = artifacts_fixture() + artifacts["platforms"]["linux"]["libraries"] = {} + repo, commit = self._make_mpv_build(artifacts=artifacts) + + result = self._run(commit, "--repo", str(repo)) + + self.assertEqual(result.returncode, 0, result.stderr) + lock = json.loads((self.root / "mpv-build.lock.json").read_text(encoding="utf-8")) + self.assertEqual(sorted(lock["artifacts"]), ["android"]) + self.assertIn("linux has published no libraries", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tvos/Runner.xcodeproj/project.pbxproj b/tvos/Runner.xcodeproj/project.pbxproj index a7daa8875..c78d1a267 100644 --- a/tvos/Runner.xcodeproj/project.pbxproj +++ b/tvos/Runner.xcodeproj/project.pbxproj @@ -459,7 +459,7 @@ ); mainGroup = 97C146E51CF9000F007C117D; packageReferences = ( - CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "MPVKit" */, + CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "mpv-build" */, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; @@ -1160,12 +1160,12 @@ /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ - CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "MPVKit" */ = { + CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "mpv-build" */ = { isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/edde746/MPVKit"; + repositoryURL = "https://github.com/edde746/mpv-build"; requirement = { kind = revision; - revision = b8b922ec74b84ac3a496e29e226a3a3e91491045; + revision = d7c3d559c91b689407daafe580b758f8b7df6078; }; }; /* End XCRemoteSwiftPackageReference section */ @@ -1173,7 +1173,7 @@ /* Begin XCSwiftPackageProductDependency section */ EA0F4263E7B912702C490108 /* MPVKit */ = { isa = XCSwiftPackageProductDependency; - package = CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "MPVKit" */; + package = CEE842A5A25923620300AB90 /* XCRemoteSwiftPackageReference "mpv-build" */; productName = MPVKit; }; /* End XCSwiftPackageProductDependency section */ diff --git a/tvos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/tvos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 1a4d479df..b085d1fec 100644 --- a/tvos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/tvos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -2,11 +2,11 @@ "originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee", "pins" : [ { - "identity" : "mpvkit", + "identity" : "mpv-build", "kind" : "remoteSourceControl", - "location" : "https://github.com/edde746/MPVKit", + "location" : "https://github.com/edde746/mpv-build", "state" : { - "revision" : "b8b922ec74b84ac3a496e29e226a3a3e91491045" + "revision" : "d7c3d559c91b689407daafe580b758f8b7df6078" } } ], diff --git a/tvos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/tvos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved index 1a4d479df..b085d1fec 100644 --- a/tvos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/tvos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -2,11 +2,11 @@ "originHash" : "c535d3cdb62bd4e11e67f3c9e68290fa7ee9306634c5f56d2b0396eb75ed41ee", "pins" : [ { - "identity" : "mpvkit", + "identity" : "mpv-build", "kind" : "remoteSourceControl", - "location" : "https://github.com/edde746/MPVKit", + "location" : "https://github.com/edde746/mpv-build", "state" : { - "revision" : "b8b922ec74b84ac3a496e29e226a3a3e91491045" + "revision" : "d7c3d559c91b689407daafe580b758f8b7df6078" } } ], diff --git a/tvos/scripts/test_wire_mpv.rb b/tvos/scripts/test_wire_mpv.rb index c96f3d188..c602ea653 100755 --- a/tvos/scripts/test_wire_mpv.rb +++ b/tvos/scripts/test_wire_mpv.rb @@ -22,8 +22,14 @@ class WireMpvTest < Minitest::Test MpvAudioPlayerCore.swift MpvAudioPlayerPlugin.swift ].freeze - MPVKIT_LOCATION = 'https://github.com/edde746/MPVKit' - MPVKIT_REVISION = /\A[0-9a-f]{40}\z/.freeze + # Without a lock the pin may sit on either side of the MPVKit -> mpv-build + # repo flip, as long as every site names the same repo; with a lock, the + # lock names the repo and every site must match it. + NATIVE_LOCATIONS = [ + 'https://github.com/edde746/MPVKit', + 'https://github.com/edde746/mpv-build', + ].freeze + NATIVE_REVISION = /\A[0-9a-f]{40}\z/.freeze def setup @temporary_root = Dir.mktmpdir('wire-mpv-test') @@ -72,12 +78,61 @@ class WireMpvTest < Minitest::Test assert_complete_source_graph end - # MPVKit is pinned by commit so any upstream commit is consumable without a - # release. Assert the shape and that every pin site agrees, rather than a - # literal sha: scripts/set_mpvkit_revision.sh is the only thing that writes - # one, and it must stay the only file to edit when the pin moves. - def test_all_apple_targets_pin_mpvkit_to_one_commit + # After scripts/set_native_revision.sh flips the repo, a Flutter-regenerated + # project still carries the old package reference; wire_mpv.rb must update it + # in place from the lock instead of hardcoding one repo or adding a second + # reference. + def test_wire_updates_the_package_reference_across_the_repo_flip + revision = flip_swiftpm_pin_to('edde746/mpv-build') + write_repo_lock('edde746/mpv-build', revision) + + run_wire_mpv + + project = Xcodeproj::Project.open(project_path) + references = project.root_object.package_references.select do |candidate| + (candidate.repositoryURL rescue nil) + end + assert_equal 1, references.count, 'expected exactly one remote package reference' + assert_equal 'https://github.com/edde746/mpv-build', references.first.repositoryURL + assert_equal({ 'kind' => 'revision', 'revision' => revision }, references.first.requirement) + assert_complete_source_graph + end + + def test_wire_refuses_a_lock_that_disagrees_with_the_swiftpm_pin + # Whichever side of the flip the copied pin sits on, name the other one. + lock = JSON.parse(File.read(swiftpm_lock_path)) + pin = lock.fetch('pins').find { |candidate| %w[mpvkit mpv-build].include?(candidate['identity']) } + refute_nil pin, 'copied lock has no native package pin' + other = pin['identity'] == 'mpvkit' ? 'edde746/mpv-build' : 'edde746/MPVKit' + write_repo_lock(other, 'f' * 40) + + output = run_wire_mpv_failure + assert_match(/no #{Regexp.escape(File.basename(other).downcase)} pin/, output) + end + + # The native package is pinned by commit so any upstream commit is + # consumable without a release. Assert the shape and that every pin site + # agrees, rather than a literal sha or repo: scripts/set_native_revision.sh + # is the only thing that writes one, and it must stay the only file to edit + # when the pin moves. The root mpv-build.lock.json is the same pin's + # non-Apple carrier; once it exists it is the tenth site: it names the repo + # every Apple site must point at and the commit they must all pin. + def test_all_apple_targets_pin_the_native_package_to_one_commit repository_root = File.expand_path('../..', __dir__) + lock_path = File.join(repository_root, 'mpv-build.lock.json') + lock = File.exist?(lock_path) ? JSON.parse(File.read(lock_path)) : nil + + expected_locations = + if lock + assert_equal 1, lock['formatVersion'], "#{lock_path} formatVersion" + assert_match %r{\A[\w.-]+/[\w.-]+\z}, lock['repo'].to_s, "#{lock_path} repo must name owner/name" + assert_match NATIVE_REVISION, lock['commit'].to_s, "#{lock_path} commit" + ["https://github.com/#{lock['repo']}"] + else + NATIVE_LOCATIONS + end + + locations = {} revisions = {} %w[ios macos tvos].each do |platform| @@ -90,28 +145,34 @@ class WireMpvTest < Minitest::Test ] lock_paths.each do |resolved_path| resolved = JSON.parse(File.read(resolved_path)) - pin = resolved.fetch('pins').find { |candidate| candidate.fetch('identity') == 'mpvkit' } - refute_nil pin, "#{resolved_path} must resolve MPVKit" - assert_equal MPVKIT_LOCATION, pin['location'], "#{resolved_path} MPVKit source" + pin = resolved.fetch('pins').find { |candidate| expected_locations.include?(candidate['location']) } + refute_nil pin, "#{resolved_path} must resolve the native package from #{expected_locations.join(' or ')}" + assert_equal 'remoteSourceControl', pin['kind'], "#{resolved_path} native pin kind" + assert_equal File.basename(pin['location']).downcase, pin['identity'], + "#{resolved_path} native pin identity must derive from its location" state = pin.fetch('state') - assert_match MPVKIT_REVISION, state['revision'].to_s, "#{resolved_path} MPVKit revision" - refute state.key?('version'), "#{resolved_path} pins MPVKit by version; it must pin a commit" - refute state.key?('branch'), "#{resolved_path} pins MPVKit by branch; it must pin a commit" + assert_match NATIVE_REVISION, state['revision'].to_s, "#{resolved_path} native pin revision" + refute state.key?('version'), "#{resolved_path} pins the native package by version; it must pin a commit" + refute state.key?('branch'), "#{resolved_path} pins the native package by branch; it must pin a commit" + locations[resolved_path] = pin['location'] revisions[resolved_path] = state['revision'] end project = Xcodeproj::Project.open(File.join(repository_root, platform, 'Runner.xcodeproj')) package = project.root_object.package_references.find do |candidate| - (candidate.repositoryURL rescue nil) == MPVKIT_LOCATION + expected_locations.include?((candidate.repositoryURL rescue nil)) end - refute_nil package, "#{platform} must reference MPVKit" + refute_nil package, "#{platform} must reference the native package from #{expected_locations.join(' or ')}" requirement = package.requirement - assert_equal 'revision', requirement['kind'], "#{platform} MPVKit requirement kind" - assert_match MPVKIT_REVISION, requirement['revision'].to_s, "#{platform} MPVKit requirement revision" + assert_equal 'revision', requirement['kind'], "#{platform} native requirement kind" + assert_match NATIVE_REVISION, requirement['revision'].to_s, "#{platform} native requirement revision" + locations[File.join(platform, 'Runner.xcodeproj')] = package.repositoryURL revisions[File.join(platform, 'Runner.xcodeproj')] = requirement['revision'] end - assert_equal 1, revisions.values.uniq.count, "Apple targets disagree on the MPVKit commit: #{revisions}" + revisions[lock_path] = lock['commit'] if lock + assert_equal 1, locations.values.uniq.count, "Apple targets disagree on the native repo: #{locations}" + assert_equal 1, revisions.values.uniq.count, "Apple targets disagree on the native commit: #{revisions}" end private @@ -134,6 +195,38 @@ class WireMpvTest < Minitest::Test assert status.success?, output end + def run_wire_mpv_failure + script = File.join(@tvos_root, 'scripts', 'wire_mpv.rb') + output, status = Open3.capture2e(RbConfig.ruby, script) + refute status.success?, "wire_mpv.rb unexpectedly succeeded:\n#{output}" + output + end + + def swiftpm_lock_path + File.join(project_path, 'project.xcworkspace', 'xcshareddata', 'swiftpm', 'Package.resolved') + end + + # Rewrites the copied project's SwiftPM pin to the given repo, returning the + # pin's revision. Mirrors what set_native_revision.sh does to the real lock. + def flip_swiftpm_pin_to(repo) + lock = JSON.parse(File.read(swiftpm_lock_path)) + pin = lock.fetch('pins').find { |candidate| %w[mpvkit mpv-build].include?(candidate['identity']) } + refute_nil pin, 'copied lock has no native package pin' + pin['identity'] = File.basename(repo, '.git').downcase + pin['location'] = "https://github.com/#{repo}" + File.write(swiftpm_lock_path, JSON.pretty_generate(lock)) + pin.fetch('state').fetch('revision') + end + + # The temp root stands in for the repository root: wire_mpv.rb resolves + # mpv-build.lock.json two directories above itself. + def write_repo_lock(repo, commit) + File.write( + File.join(@temporary_root, 'mpv-build.lock.json'), + JSON.pretty_generate('formatVersion' => 1, 'repo' => repo, 'commit' => commit, 'artifacts' => {}) + ) + end + def assert_complete_source_graph project = Xcodeproj::Project.open(project_path) runner = project.targets.find { |target| target.name == 'Runner' } diff --git a/tvos/scripts/wire_mpv.rb b/tvos/scripts/wire_mpv.rb index 3cb1765b2..6fe382d88 100755 --- a/tvos/scripts/wire_mpv.rb +++ b/tvos/scripts/wire_mpv.rb @@ -1,5 +1,5 @@ #!/usr/bin/env ruby -# Adds the Plezy MpvPlayer Swift sources and the MPVKit Swift Package +# Adds the Plezy MpvPlayer Swift sources and the native mpv Swift Package # dependency to tvos/Runner.xcodeproj so it matches the iOS project's # linkage. Idempotent: re-running skips already-added entries. @@ -47,37 +47,71 @@ sources.each do |src| end end -# Swift Package: MPVKit. Restore each graph edge independently so a project -# with a surviving package reference cannot silently omit the Runner linkage. +# Swift Package: the native mpv package. Restore each graph edge independently +# so a project with a surviving package reference cannot silently omit the +# Runner linkage. # -# MPVKit is pinned by commit, not by version: the fork publishes +# The package is pinned by commit, not by version: the build repo publishes # content-addressed binaries on every push to main, so a sha names the exact # artifacts we link. The committed SwiftPM lock is the source of truth for that # sha, so re-wiring can never revert a bump made by -# scripts/set_mpvkit_revision.sh. -pkg_url = 'https://github.com/edde746/MPVKit' +# scripts/set_native_revision.sh. +# +# The repo itself is not hardcoded: mpv-build.lock.json names it when present +# (the same source of truth set_native_revision.sh writes); without one the +# script accepts either side of the MPVKit -> mpv-build flip, as long as the +# SwiftPM lock carries exactly one such pin. The SwiftPM identity of a pin is +# its URL basename, .git stripped, lowercased. +KNOWN_IDENTITIES = %w[mpvkit mpv-build].freeze + lock_path = File.join(PROJECT_PATH, 'project.xcworkspace', 'xcshareddata', 'swiftpm', 'Package.resolved') -raise "MPVKit lock not found at #{lock_path}" unless File.exist?(lock_path) -lock_pin = JSON.parse(File.read(lock_path)).fetch('pins', []).find do |candidate| - candidate['identity'] == 'mpvkit' +raise "native package lock not found at #{lock_path}" unless File.exist?(lock_path) +pins = JSON.parse(File.read(lock_path)).fetch('pins', []) + +repo_lock_path = File.expand_path('../../mpv-build.lock.json', __dir__) +if File.exist?(repo_lock_path) + repo = JSON.parse(File.read(repo_lock_path)).fetch('repo') + pkg_url = "https://github.com/#{repo}" + pkg_identity = File.basename(repo, '.git').downcase + lock_pin = pins.find { |candidate| candidate['identity'] == pkg_identity } + raise "no #{pkg_identity} pin in #{lock_path} (mpv-build.lock.json names #{repo})" unless lock_pin + location = lock_pin['location'] + unless location == pkg_url + raise "#{lock_path} pins #{pkg_identity} at #{location}, but mpv-build.lock.json names #{pkg_url}" + end +else + candidates = pins.select { |candidate| KNOWN_IDENTITIES.include?(candidate['identity']) } + raise "no native package pin in #{lock_path}" if candidates.empty? + if candidates.size > 1 + raise "ambiguous native package pins in #{lock_path}: #{candidates.map { |c| c['identity'] }.join(', ')}" + end + lock_pin = candidates.first + pkg_url = lock_pin.fetch('location') + pkg_identity = lock_pin.fetch('identity') end -raise "no mpvkit pin in #{lock_path}" unless lock_pin +pkg_name = File.basename(pkg_url, '.git') pkg_revision = lock_pin.dig('state', 'revision') unless pkg_revision.to_s.match?(/\A[0-9a-f]{40}\z/) - raise "mpvkit pin in #{lock_path} has no full commit revision" + raise "#{pkg_identity} pin in #{lock_path} has no full commit revision" end +# Find the reference by the identity of its URL so a re-wire after the repo +# flip updates the surviving reference in place instead of adding a second one. pkg = project.root_object.package_references.find do |candidate| - candidate.repositoryURL == pkg_url rescue false + url = (candidate.repositoryURL rescue nil) + url && KNOWN_IDENTITIES.include?(File.basename(url, '.git').downcase) end -unless pkg +if pkg.nil? pkg = project.new(Xcodeproj::Project::Object::XCRemoteSwiftPackageReference) pkg.repositoryURL = pkg_url project.root_object.package_references << pkg - puts "[add ] MPVKit SPM package reference" + puts "[add ] #{pkg_name} SPM package reference" +elsif pkg.repositoryURL != pkg_url + pkg.repositoryURL = pkg_url + puts "[set ] #{pkg_name} SPM package URL #{pkg_url}" end pkg.requirement = { 'kind' => 'revision', 'revision' => pkg_revision } -puts "[set ] MPVKit SPM package revision #{pkg_revision[0, 12]}" +puts "[set ] #{pkg_name} SPM package revision #{pkg_revision[0, 12]}" product = runner_target.package_product_dependencies.find do |candidate| candidate.product_name == 'MPVKit' diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index ecb618323..e6407e9cd 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -1,55 +1,42 @@ cmake_minimum_required(VERSION 3.14) project(plezy LANGUAGES CXX) -set(MPV_VERSION "20260809") -set(MPV_GIT_HASH "dd5d17d328") - +# libmpv comes from our unified build repository +# (https://github.com/edde746/mpv-build), which publishes per-commit, +# content-addressed dev packages in the classic mpv-dev shape: +# libmpv-2.dll, libmpv.dll.a and include/mpv/*.h at the archive root. The +# key in the asset name is derived from the pinned sources (mpv v0.41.0, +# ffmpeg n8.0.1, our libass fork, the winbuild toolchain); assets are +# immutable, so bumping mpv there yields a new key and a new URL. The +# checksums come from artifacts.json at the pinned mpv-build commit. +set(MPV_KEY "1da76841036d") +set(MPV_ASSET_BASE "https://github.com/edde746/mpv-build/releases/download/binaries-windows") if(CMAKE_SYSTEM_PROCESSOR STREQUAL "ARM64") - # ARM64: use file(DOWNLOAD) + 7z extraction (CMake's built-in libarchive - # can't handle LZMA2 on ARM64) - set(MPV_FILENAME "mpv-dev-aarch64-${MPV_VERSION}-git-${MPV_GIT_HASH}.7z") - set(MPV_URL "https://sourceforge.net/projects/mpv-player-windows/files/libmpv/${MPV_FILENAME}/download") - set(MPV_DOWNLOAD_DIR "${CMAKE_BINARY_DIR}/mpv-dev-arm64") - set(MPV_ARCHIVE "${MPV_DOWNLOAD_DIR}/${MPV_FILENAME}") - - if(NOT EXISTS "${MPV_DOWNLOAD_DIR}/libmpv-2.dll") - message(STATUS "Downloading MPV for ARM64...") - file(DOWNLOAD "${MPV_URL}" "${MPV_ARCHIVE}" SHOW_PROGRESS STATUS MPV_DL_STATUS) - list(GET MPV_DL_STATUS 0 MPV_DL_RESULT) - if(NOT MPV_DL_RESULT EQUAL 0) - message(FATAL_ERROR "Failed to download MPV: ${MPV_DL_STATUS}") - endif() - - find_program(7Z_EXECUTABLE 7z REQUIRED HINTS "C:/Program Files/7-Zip") - message(STATUS "Extracting MPV with ${7Z_EXECUTABLE}...") - execute_process( - COMMAND "${7Z_EXECUTABLE}" x "${MPV_ARCHIVE}" "-o${MPV_DOWNLOAD_DIR}" -y - RESULT_VARIABLE MPV_EXTRACT_RESULT - ) - if(NOT MPV_EXTRACT_RESULT EQUAL 0) - message(FATAL_ERROR "Failed to extract MPV archive") - endif() - file(REMOVE "${MPV_ARCHIVE}") - endif() - - set(MPV_INCLUDE_DIR "${MPV_DOWNLOAD_DIR}/include") - set(MPV_LIB_DIR "${MPV_DOWNLOAD_DIR}") + set(MPV_ARCH "aarch64") + set(MPV_SHA256 "94c0e4d27794fb3bb754b0c62409c6b0cf17161fbafa16c3213d0239821a6836") else() - # x64 (AMD64): use FetchContent (existing behavior) - include(FetchContent) - FetchContent_Declare( - mpv_dev - URL https://sourceforge.net/projects/mpv-player-windows/files/libmpv/mpv-dev-x86_64-${MPV_VERSION}-git-${MPV_GIT_HASH}.7z/download - DOWNLOAD_EXTRACT_TIMESTAMP TRUE - ) - FetchContent_MakeAvailable(mpv_dev) - - set(MPV_INCLUDE_DIR "${mpv_dev_SOURCE_DIR}/include") - set(MPV_LIB_DIR "${mpv_dev_SOURCE_DIR}") + set(MPV_ARCH "x86_64") + set(MPV_SHA256 "6a927cbbb7d44ecbefa3643ef0b435e3fa521b6a1123bb8c5d6349441ed3a760") endif() -# libmpv >= 20260809 dynamically links the Khronos Vulkan loader instead of -# statically linking it, so libmpv-2.dll hard-imports vulkan-1.dll. On x64 +# Plain zips extract with CMake's built-in libarchive on every host arch, so +# both arches share the FetchContent path (the old mpv-dev 7z needed a +# 7-Zip binary on ARM64, whose libarchive lacks LZMA2). +include(FetchContent) +FetchContent_Declare( + mpv_dev + URL "${MPV_ASSET_BASE}/libmpv-windows-${MPV_KEY}-${MPV_ARCH}.zip" + URL_HASH SHA256=${MPV_SHA256} + DOWNLOAD_EXTRACT_TIMESTAMP TRUE +) +FetchContent_MakeAvailable(mpv_dev) + +set(MPV_INCLUDE_DIR "${mpv_dev_SOURCE_DIR}/include") +set(MPV_LIB_DIR "${mpv_dev_SOURCE_DIR}") + +# The winbuild toolchain dynamically links the Khronos Vulkan loader (since +# 2026-08, and true of our pinned build), so libmpv-2.dll hard-imports +# vulkan-1.dll. On x64 # the GPU driver normally installs the loader into System32, but # Windows-on-ARM Adreno drivers (and driverless x64 machines such as VMs) # do not ship it, which made the process fail before WinMain (#2110).