Compare commits

...
12 Commits
Author SHA1 Message Date
edde746 805632efc1 chore: bump version to 2.17.1 2026-08-25 00:43:37 +02:00
edde746 fe9d9d5e7d test(player): cover saf reads and the demuxer's jni byte source under r8
The random-access demuxer added two surfaces with no gate behind them. A
download stored through SAF arrives as content://, where an index read has to
open a second descriptor while the loader holds one, and the AVIO callbacks
are reached only by name from C++, so R8 may rename them while every debug
check passes -- the shape #1703 shipped with.

FfmpegExtractorSeekTest now runs the cued fixture over a content:// URI
served by a test-only provider, and FfmpegDemuxerReachabilityTest drives
nativeOpen plus a seek through a media3-free byte source so it can run
minified. Wired into the existing R8 reachability target; verified it fails
when the FfmpegDemuxerJni$Input keep rule is removed.
2026-08-24 23:02:23 +02:00
edde746 1995fc6b75 refactor(player): demux through random-access IO instead of unwinding libavformat
Resuming or seeking a large MKV on the Android FFmpeg demux path buffered
for minutes with no error and no fallback. The cause was the seam, not the
container: libavformat's demuxers own their seeking — end-of-file index,
back to the header, binary search — while media3's Extractor is forward
only, so every backward jump had to abort the in-flight libavformat call
with a synthetic IO error and replay the whole open. matroskadec attempts
its deferred Cues parse exactly once per context, so that abort burned the
index for the session and every later seek fell back to libavformat's
linear generic scan, reading the file up to the target.

That protocol had produced a bug of this shape repeatedly (a NULL deref
resuming find_stream_info across an abort, a use-after-free on fallback
teardown, matroskadec resync skipping the keyframe cluster) and it was held
together by four empirical retry budgets whose exhaustion degraded silently
— which is why #2096 looked like an unbounded spinner instead of an error.

Give libavformat what it requires instead. FfmpegRandomAccessSource serves
any absolute position from a second DataSource built by the same factory
media3 uses, cloning the DataSpec media3 opened for the item so Cronet,
download caches, SAF and per-item request headers still apply. Reads that
the loader's ExtractorInput can serve still go through it, so sample
delivery keeps feeding media3's byte accounting, back-pressure and
load-error policy; the extractor nudges the loader to follow the demuxer
with one RESULT_SEEK, which is an optimization that can never stall
playback because the read succeeds either way.

Deleted with the protocol: the synthetic AVERROR_NEED_SEEK unwind, the
24 MB replay cache, the Cues priming seek and its read guard, the sticky
AVIO error clearing, and all four budgets (seekAttempts, stickyRecovers,
MAX_RECONCILES, MAX_OPEN_LOADER_ROUND_TRIPS). Opens run straight through,
seeks are one avformat_seek_file on the loader thread, and an IO failure is
an IOException that reaches media3's retry policy instead of a silent
degradation. The demuxer is now the only component that resolves seeks, so
the extractor's sample-derived seek index is gone too.

Verified on a SEI Robotics Android TV box against Jellyfin: the DV P8.1
28.4 GB MKV resume that started at a 4m28s spinner opens in 1.1 s and
resolves its seek in one call, a mid-playback scrub resolves in 1 ms from
the in-memory index, a 2 GB MKV resume opens in 0.5 s, fresh playback needs
no index read at all, and MP4/AVI still open and deliver. New coverage:
FfmpegRandomAccessSourceTest pins the read/reopen contract, and
FfmpegExtractorSeekTest asserts on-device that a cued seek lands on target
without walking the file and that a cueless file still reaches it.

close #2096
2026-08-24 23:02:23 +02:00
edde746 defb0f4983 fix(player): publish real dolby vision profiles from the ffmpeg demuxer
The demuxer JNI read AV_PKT_DATA_DOVI_CONF as the bit-packed dvcC/dvvC box
layout, but libavformat surfaces the unpacked
AVDOVIDecoderConfigurationRecord — one byte per field. Profile 8 level 6
streams therefore surfaced as "dvh1.04.00" plain HEVC (visible in #2096's
logs): DoviConvertingTrackOutput's profile 7 conversion could never engage,
and profile 8 was routed to the plain HEVC decoder instead of the Dolby
Vision decoder the media3 demux path selects.

Read the struct fields verbatim and mirror media3's DolbyVisionConfig in
Kotlin: recognized profiles publish video/dolby-vision with the
dvhe/dvav/dav1 RFC 6381 codecs string, unrecognized profiles keep the base
codec's format. A DV P8.1 MKV on the FFmpeg path now reports "dvhe.08.10",
mime video/dolby-vision, and takes the DV P8 passthrough path exactly like
the media3 demuxer.
2026-08-24 23:02:23 +02:00
edde746 371eab8637 fix(downloads): stream from the server when a downloaded SAF copy is unreachable
Playing a downloaded movie or episode failed outright once the storage
holding it was gone — an SD card ejected, a USB volume unplugged, the
files deleted from outside the app (issue #2101). The item still played
fine from the server, but Plezy never tried: it committed to the local
copy and surfaced mpv's open failure.

Resolution already refused a missing local copy and let the caller
stream instead, but only for filesystem paths. SAF `content://` URIs
skipped the check on the premise that they are always playable as
written. They are not: an unmounted volume answers
`FileNotFoundException: No root for <volume>`, and a revoked grant is
just as dead, while the row still reads `completed`.

Probe the stored document through SAF before preferring it, so an
unreachable copy resolves to nothing and every consumer degrades the
way a missing file already did — the player streams, and both
external-player entry points launch against the server instead of a
dead URI.

close #2101
2026-08-24 19:27:20 +02:00
edde746 f357be4077 fix(tvos): match Siri Remote navigation to measured native focus-engine physics
Siri Remote navigation felt sluggish and then over-sensitive next to
native tvOS apps (issue #2006): swipes were priced at a fixed travel
per step, a single flick could glide into a second focus step, hard
lifts coasted several extrapolated steps, and rail scrolls snapped in
65-250ms where native glides.

Retuned the whole path against two hardware instrumentation passes on
an Apple TV 4K: committed-move telemetry through an experimental
UIFocusItem bridge (branch feat/tvos-native-focus-bridge), then a
dedicated native probe app logging every touch sample, pan velocity,
engine hint, focus step, and scroll tick across 101 swipe sessions on
160/230/300pt tiles. What the data showed, now encoded:

- step pricing follows geometry: one step costs the focused item's
  extent along the swipe axis plus ~155pt (measured 314/391/410pt on
  160/230/300pt tiles), not a fixed distance. Thresholds derive per
  axis from the primary focus rect, normalized so a wide-flat control
  steps vertically once the finger covers its height. Locked-focus
  rows (hub rows, the TV browse rail) vend their selected card's rect
  through the new LockedFocusRowNode so the row-wide focus node's
  screen-sized rect never prices the step. Scopes, the player's
  catch-all surfaces, and unbuilt cards fall back to a fixed 400pt.
- a lift never coasts more than one step: sessions with lift
  velocities up to ~11400pt/s never produced a second coast step. The
  glide is gated on a sustained drag (two consecutive same-direction
  steps), cancelled by reversal pivots and new touches, so a discrete
  flick moves exactly one item.
- the native 'inertia' feel is the scroll animation, not focus
  physics: the engine's scrollable containers settle over ~450-900ms
  of ease-out. TV rail and hub-row navigation scrolls now retarget a
  500ms easeOutCubic animation per step, so drags and hold-repeats
  chain into one continuous glide that catches up on release.
2026-08-24 13:41:44 +02:00
edde746 0fdc22b4fa fix(linux): make the render-executor completion handoff visible to TSan
GLib's GMutex is a raw futex, so ThreadSanitizer cannot see the
happens-before edge g_main_context_invoke_full provides and fails the
thread lane on plane_render_executor_test. Publish the completion
payload through an explicit release/acquire pair, and suppress the
remaining reports that originate wholly inside libglib's own source
bookkeeping. Races on repository memory still fail the run; verified
0/100 failing TSan runs in an ubuntu:24.04 container (20/20 before).
2026-08-24 12:42:23 +02:00
edde746 fb85bb279a style(android): apply ktlint to the ffmpeg audio csd code
The Native Formatting lane rejects the unbraced multiline if/else in
FfmpegExtractor and the wrapped expression body in FfmpegAudioCsdTest.
2026-08-24 12:42:23 +02:00
edde746andGitHub cc4eff98c0 build: migrate to Flutter 3.47.1 (#2092) 2026-08-24 12:32:05 +02:00
edde746 0fbf2e205c fix(profiles): skip the resume profile prompt during a live companion-remote session
With "Ask for profile on app open" enabled, every screen-off or app
switch on a phone re-pushed the profile picker and PIN on resume, burying
a companion-remote session that survives backgrounding since the
reconnect cycle was made lifecycle-aware. Suppress the resume prompt
while a companion session is live, mirroring the active-playback
exemption — the session already belongs to the profile that started it.

close #2087
2026-08-24 10:06:00 +02:00
edde746 a9f2c1ff99 fix(player): shape ffmpeg demuxer audio extradata into media3 csd layouts
VP9/WebM-origin files stalled at 0ms in ExoPlayer on 2.17.0 and fell
back to MPV after ~40s. The ffmpeg demuxer published raw extradata as
the only initializationData entry; Android's Opus decoders consume
their first three input buffers as OpusHead/codec-delay/seek-pre-roll,
so they ate the first two real packets as configuration and silently
discarded every decoded sample, pinning the audio-driven clock at 0.
Vorbis (unsplit Xiph lacing) and FLAC (unmarked STREAMINFO) had the
same shape divergence.

Shape audio extradata into the layouts media3's own extractors emit
before publishing the track format.

close #2088
2026-08-24 09:36:10 +02:00
github-actions[bot] fe4e53f912 chore: update cask to 2.17.0 2026-08-24 05:28:32 +00:00
72 changed files with 2628 additions and 823 deletions
+3 -3
View File
@@ -5,7 +5,7 @@ description: >-
subosito/flutter-action cannot resolve the release for arm64 (no arm64 entry
in the stable manifest) and `channel: master` would clone master HEAD, whose
engine is not the patched revision install-patched-engine.ps1 asserts
(4c525dac). This file is the only place that pin lives: the tag is fetched so
(5d531788). This file is the only place that pin lives: the tag is fetched so
the SDK reports its own version, then verified against the immutable commit
and against the version Flutter itself reports, so a moved tag fails the job
instead of quietly changing SDKs.
@@ -16,8 +16,8 @@ runs:
- name: Clone Flutter from its immutable commit
shell: pwsh
run: |
$version = "3.44.0"
$expectedCommit = "559ffa3f75e7402d65a8def9c28389a9b2e6fe42"
$version = "3.47.1"
$expectedCommit = "6655482ec06e547f90abf8ae7590466f4415978d"
$root = "$env:RUNNER_TEMP\flutter"
git init $root
git -C $root remote add origin https://github.com/flutter/flutter.git
+1 -1
View File
@@ -31,7 +31,7 @@ on:
env:
# Only place this workflow names the SDK; .github/actions/setup-flutter-git pins the same release.
FLUTTER_VERSION: "3.44.0"
FLUTTER_VERSION: "3.47.1"
# Shared by every release build command; SENTRY_DIST stays per-platform.
RELEASE_DART_DEFINES: --dart-define=ENABLE_UPDATE_CHECK=true ${{ github.repository == 'edde746/plezy' && '--dart-define=ENABLE_SENTRY=true' || '' }} --dart-define=GIT_COMMIT=${{ github.sha }} --dart-define=SENTRY_ENVIRONMENT=github --dart-define=ENABLE_DONATIONS=true
TRUSTED_BUILD_CACHE_VERSION: trusted-build-v1
+1 -1
View File
@@ -20,7 +20,7 @@ on:
env:
# Only place this workflow names the SDK; .github/actions/setup-flutter-git pins the same release.
FLUTTER_VERSION: "3.44.0"
FLUTTER_VERSION: "3.47.1"
jobs:
analyze:
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.16.0"
sha256 "87568115810fd627babfd05967fbc7d1bf9f40bd38eed319cf7b404b09e47162"
version "2.17.0"
sha256 "318b9ac0ff0d239b3edbad57a44c008e7aaf0c5623bc2c595407fce2987ba5e4"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+1 -1
View File
@@ -148,7 +148,7 @@ Package managers:
## Building from Source
### Prerequisites
- Flutter SDK 3.44.0+
- Flutter SDK 3.47.0+
- A Plex account, or a Jellyfin or Emby server with user credentials
### Setup
+7
View File
@@ -4,6 +4,13 @@ analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:
+4 -3
View File
@@ -20,11 +20,12 @@
-keep class androidx.media3.decoder.SimpleDecoderOutputBuffer { *; }
# ffmpeg_demuxer_jni.cc resolves the AVIO input proxy's callbacks by name
# (FindClass on the interface, GetMethodID for position/read/length). Keeping
# the interface members pins the names on every implementation, including the
# anonymous proxy inside FfmpegExtractor.
# (FindClass on the interface, GetMethodID for position/read/readAt/length).
# Keeping the interface members pins the names on every implementation,
# including the anonymous proxy inside FfmpegExtractor.
-keep interface com.edde746.plezy.exoplayer.FfmpegDemuxerJni$Input {
long position();
int read(byte[], int);
int readAt(long, byte[], int);
long length();
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Serves a test asset over content:// so instrumentation covers the
SAF/ContentDataSource read path. Exported because the test body
runs in the app's process while this provider lives in the
androidTest APK's own uid; it serves nothing but this APK's own
assets. Merged into the androidTest APK, never into the app. -->
<provider
android:name="com.edde746.plezy.exoplayer.FixtureContentProvider"
android:authorities="com.edde746.plezy.test.fixtures"
android:exported="true" />
</application>
</manifest>
@@ -0,0 +1,117 @@
package com.edde746.plezy.exoplayer;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Serves a test asset over a {@code content://} URI so instrumentation can exercise media3's
* {@code ContentDataSource} read path.
*
* <p>A download stored through SAF reaches the player as {@code content://} and is read with
* {@code openAssetFileDescriptor} — a different reopen story than a plain file:
* {@code FfmpegRandomAccessSource} has to open a <em>second</em> descriptor on the document while
* the loader still holds one. Nothing else in the app produces that shape on demand, and MediaStore
* would leave rows on the device.
*
* <p>The provider owns the whole fixture: a test body runs in the <em>app's</em> process and cannot
* write into this APK's data directory, so handing it a path could never work. It copies the named
* asset into its own cache and returns a read-only descriptor, which crosses the uid boundary fine.
*
* <p>Java rather than Kotlin on purpose: hosting this provider starts a process for the test APK
* alone, and the Kotlin stdlib the instrumentation normally borrows from the app is not on that
* process's classpath.
*/
public final class FixtureContentProvider extends ContentProvider {
public static final String AUTHORITY = "com.edde746.plezy.test.fixtures";
/** @param asset path inside this APK's assets, e.g. {@code ffmpeg/seek_cued.mkv}. */
public static Uri uriFor(String asset) {
return new Uri.Builder().scheme("content").authority(AUTHORITY).path(asset).build();
}
@Override
public boolean onCreate() {
return true;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String path = uri.getPath();
if (path == null || path.length() <= 1) {
throw new FileNotFoundException("no asset in " + uri);
}
String asset = path.substring(1);
Context context = getContext();
if (context == null) {
throw new FileNotFoundException("provider has no context");
}
File cached = new File(context.getCacheDir(), asset.replace('/', '-'));
if (!cached.isFile()) {
copyAsset(context, asset, cached);
}
return ParcelFileDescriptor.open(cached, ParcelFileDescriptor.MODE_READ_ONLY);
}
private static void copyAsset(Context context, String asset, File target) throws FileNotFoundException {
File staging = null;
try {
context.getCacheDir().mkdirs();
staging = File.createTempFile("fixture-", null, context.getCacheDir());
try (InputStream source = context.getAssets().open(asset);
OutputStream sink = new FileOutputStream(staging)) {
byte[] buffer = new byte[64 * 1024];
for (int read = source.read(buffer); read != -1; read = source.read(buffer)) {
sink.write(buffer, 0, read);
}
}
// Publish atomically so a concurrent open never sees a short file.
if (!staging.renameTo(target) && !target.isFile()) {
throw new IOException("could not publish " + target);
}
} catch (IOException e) {
FileNotFoundException failure = new FileNotFoundException("could not stage asset " + asset);
failure.initCause(e);
throw failure;
} finally {
if (staging != null && staging.isFile()) {
staging.delete();
}
}
}
@Override
public String getType(Uri uri) {
return "video/x-matroska";
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
}
@@ -0,0 +1,116 @@
package com.edde746.plezy.exoplayer
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import java.io.File
import java.io.RandomAccessFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Asserts the demuxer's JNI byte source stays reachable under R8.
*
* `ffmpeg_demuxer_jni.cc` resolves [FfmpegDemuxerJni.Input] by name — `FindClass`
* on the interface, then `GetMethodID` for `position`, `read`, `readAt` and
* `length`. Nothing in Kotlin calls those methods, so R8 may rename or remove
* them while every debug check still passes; the AVIO callbacks would then fail
* on the first read and every container would fall back to media3's extractors.
* That is the same failure shape as #1703, which shipped.
*
* Run against the `minified` build type (`-Pplezy.testBuildType=minified`); on an
* unminified variant it can only ever pass. Deliberately touches no media3 API,
* so the only keep rules it depends on are the ones under test.
*/
@RunWith(AndroidJUnit4::class)
class FfmpegDemuxerReachabilityTest {
@Test
fun avioCallbacksResolveAndServeBothSequentialAndIndexReads() {
assertTrue("ffmpeg demuxer JNI library is unavailable", FfmpegDemuxerJni.available)
val fixture = copyFixture()
val input = FileInput(fixture)
try {
// nativeOpen drives the whole handshake: FindClass on Input, GetMethodID
// for all four methods, then avio reads served back through them. A
// shrunk or renamed member makes this fail instead of returning streams.
val code = FfmpegDemuxerJni.nativeOpen(input)
assertEquals("nativeOpen failed (${input.lastError ?: "no java error"})", 0, code)
assertTrue("demuxer reported no streams", FfmpegDemuxerJni.nativeStreamCount() > 0)
assertTrue("position was never called", input.positionCalls > 0)
// Header parsing is sequential, so it only proves read()/position()/length().
// readAt() is the member nothing in the app calls except this interface's
// own implementation, and it is what an index seek runs on.
val durationUs = FfmpegDemuxerJni.nativeDurationUs()
assertTrue("fixture duration unknown", durationUs > 0)
val seek = FfmpegDemuxerJni.nativeSeek(durationUs / 2)
assertTrue("nativeSeek failed with $seek (${input.lastError ?: "no java error"})", seek >= 0)
assertTrue("readAt was never called for the index read", input.readAtCalls > 0)
} finally {
FfmpegDemuxerJni.nativeClose()
input.close()
fixture.delete()
}
}
private fun copyFixture(): File {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val cacheDir = instrumentation.targetContext.cacheDir.also { it.mkdirs() }
val output = File.createTempFile("ffmpeg-reachability-", ".mkv", cacheDir)
instrumentation.context.assets.open(FIXTURE).use { source ->
output.outputStream().use(source::copyTo)
}
return output
}
/** Byte source with no media3 involvement, so R8 has nothing else to keep. */
private class FileInput(file: File) : FfmpegDemuxerJni.Input {
private val handle = RandomAccessFile(file, "r")
private val total = file.length()
var readAtCalls = 0
private set
var positionCalls = 0
private set
override var lastError: String? = null
override fun position(): Long {
positionCalls++
return handle.filePointer
}
override fun read(buf: ByteArray, length: Int): Int {
val read = handle.read(buf, 0, length)
return if (read < 0) 0 else read
}
override fun readAt(position: Long, buf: ByteArray, length: Int): Int {
readAtCalls++
val restore = handle.filePointer
return try {
if (position >= total) return 0
handle.seek(position)
val read = handle.read(buf, 0, length)
if (read < 0) 0 else read
} finally {
handle.seek(restore)
}
}
override fun length(): Long = total
fun close() = handle.close()
}
private companion object {
/** The cued fixture from [FfmpegExtractorSeekTest]: a SeekHead plus Cues at the end. */
const val FIXTURE = "ffmpeg/seek_cued.mkv"
}
}
@@ -0,0 +1,135 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.HandlerThread
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.extractor.ExtractorsFactory
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.libass.media.AssHandler
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* End-to-end regression coverage for #2088: audio demuxed by FfmpegExtractor
* must reach MediaCodec with the per-codec csd shapes media3's own extractors
* emit. With raw ffmpeg extradata as the only csd buffer, Android's Opus
* decoders consume the first two real packets as codec delay / seek pre-roll
* and then silently discard every decoded sample — the player never leaves
* STATE_BUFFERING, which this test observes as a playback timeout.
*
* The extractors factory contains only FfmpegExtractor, so a fixture that
* falls back to media3's extractors fails instead of passing vacuously.
*/
@RunWith(AndroidJUnit4::class)
class FfmpegExtractorAudioCsdPlaybackTest {
@Test
fun opusPlaysToEnd() {
playToEnd("ffmpeg/stereo_opus.mka")
}
@Test
fun vorbisPlaysToEnd() {
playToEnd("ffmpeg/stereo_vorbis.mka")
}
@Test
fun flacPlaysToEnd() {
playToEnd("ffmpeg/stereo.flac")
}
private fun playToEnd(fixture: String) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val fixtureFile = copyFixture(instrumentation.context, context, fixture)
val playbackThread = HandlerThread("ffmpeg-csd-test").apply { start() }
val handler = Handler(playbackThread.looper)
val completed = CountDownLatch(1)
val playerReference = AtomicReference<ExoPlayer>()
val errorReference = AtomicReference<Throwable>()
handler.post {
try {
val fixtureUri = Uri.fromFile(fixtureFile)
val ffmpegOnlyExtractors = ExtractorsFactory {
val extractor = FfmpegExtractor.create(
{ FfmpegDemuxerPolicy.Preference.FFMPEG },
DvConversionMode.DISABLED,
DefaultSubtitleParserFactory(),
AssHandler(),
FfmpegRandomAccessSource(DefaultDataSource.Factory(context)) { DataSpec(fixtureUri) }
)
assertNotNull("FFmpeg demuxer JNI library is unavailable", extractor)
arrayOf(extractor!!)
}
val player = ExoPlayer.Builder(context, PlezyRenderersFactory(context))
.setLooper(playbackThread.looper)
.build()
playerReference.set(player)
player.addListener(object : Player.Listener {
override fun onPlayerError(error: PlaybackException) {
errorReference.set(error)
completed.countDown()
}
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_ENDED) {
completed.countDown()
}
}
})
val source = ProgressiveMediaSource.Factory(
DefaultDataSource.Factory(context),
ffmpegOnlyExtractors
).createMediaSource(MediaItem.fromUri(fixtureUri))
player.setMediaSource(source)
player.prepare()
player.play()
} catch (error: Throwable) {
errorReference.set(error)
completed.countDown()
}
}
val finished = completed.await(20, TimeUnit.SECONDS)
val released = CountDownLatch(1)
handler.post {
playerReference.get()?.release()
playbackThread.quitSafely()
released.countDown()
}
val teardownFinished = released.await(5, TimeUnit.SECONDS)
playbackThread.join(5_000)
val fixtureDeleted = fixtureFile.delete()
assertTrue("Player teardown timed out for $fixture", teardownFinished)
assertTrue("Playback timed out for $fixture", finished)
assertNull("Playback failed for $fixture", errorReference.get())
assertTrue("Fixture cleanup failed for $fixture", fixtureDeleted)
}
private fun copyFixture(instrumentationContext: Context, targetContext: Context, fixture: String): File {
val output = File.createTempFile("ffmpeg-csd-fixture-", null, targetContext.cacheDir)
instrumentationContext.assets.open(fixture).use { input ->
output.outputStream().use(input::copyTo)
}
return output
}
}
@@ -0,0 +1,357 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.TransferListener
import androidx.media3.extractor.DefaultExtractorInput
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.PositionHolder
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.libass.media.AssHandler
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Regression coverage for #2096 and for the seam that caused it.
*
* libavformat resolves seeks through its own index, reading it via
* [FfmpegRandomAccessSource]. When that read cannot be served, matroskadec
* burns its one-shot Cues parse and every later seek degrades to libavformat's
* linear generic scan — which is what buffered a resume for minutes. The cued
* fixture here has the same geometry as the file from the report (front
* SeekHead, Cues at 99.5% of the file), so a scan is trivially distinguishable
* from an index seek: it has to read most of the file.
*/
@RunWith(AndroidJUnit4::class)
class FfmpegExtractorSeekTest {
private companion object {
// Regenerate with:
// ffmpeg -f lavfi -i "testsrc=size=160x120:rate=10:duration=30" \
// -c:v libx264 -g 10 -pix_fmt yuv420p -preset veryfast seek_cued.mkv
// mkvmerge --no-cues -o seek_cueless.mkv seek_cued.mkv
// The cued fixture keeps ffmpeg's default layout: a SeekHead at byte 52
// pointing at Cues written after the clusters, at 99.5% of the file.
const val CUED = "ffmpeg/seek_cued.mkv"
const val CUELESS = "ffmpeg/seek_cueless.mkv"
/** The fixtures are 30 s at 10 fps with a keyframe every second. */
const val TARGET_US = 25_000_000L
const val KEYFRAME_TOLERANCE_US = 1_500_000L
}
@Test
fun cuedSeekLandsOnTheTargetWithoutWalkingTheFile() {
withHarness(CUED) { harness ->
harness.pumpUntilSampleDelivered()
assertTrue(
"playback should start at the beginning, got ${harness.lastSampleUs}us",
harness.lastSampleUs < 500_000L
)
harness.resetByteCounter()
harness.seekTo(TARGET_US)
val landed = harness.pumpUntilSampleAtLeast(TARGET_US - KEYFRAME_TOLERANCE_US)
assertTrue("no sample delivered after seeking to ${TARGET_US}us", landed)
assertTrue(
"seek landed at ${harness.lastSampleUs}us, expected within " +
"${KEYFRAME_TOLERANCE_US}us of ${TARGET_US}us",
harness.lastSampleUs <= TARGET_US + KEYFRAME_TOLERANCE_US
)
// An index seek reads the Cues plus the target cluster. A generic scan
// has to read everything up to 83% of the file to get here.
val budget = harness.fixtureSize / 3
assertTrue(
"seek read ${harness.bytesRead} bytes of a ${harness.fixtureSize}-byte file; " +
"expected under $budget (index seek, not a scan)",
harness.bytesRead < budget
)
// Reopening per read would mean one request per 64 KB in steady state.
assertTrue("random-access opens after seek: ${harness.randomAccessOpens}", harness.randomAccessOpens <= 4)
}
}
/**
* Without Cues libavformat falls back to its generic scan, exactly as media3's
* own MatroskaExtractor scans clusters. That is slow but it must still land on
* the target rather than stalling or silently delivering from the wrong place.
*/
@Test
fun cuelessSeekStillReachesTheTarget() {
withHarness(CUELESS) { harness ->
harness.pumpUntilSampleDelivered()
harness.seekTo(TARGET_US)
val landed = harness.pumpUntilSampleAtLeast(TARGET_US - KEYFRAME_TOLERANCE_US)
assertTrue("cueless seek to ${TARGET_US}us delivered nothing", landed)
assertTrue(
"cueless seek landed at ${harness.lastSampleUs}us",
harness.lastSampleUs <= TARGET_US + KEYFRAME_TOLERANCE_US
)
}
}
/**
* A download stored through SAF arrives as `content://`, which media3 reads
* with `openAssetFileDescriptor`. The demuxer's index reads therefore have to
* open a second descriptor on the same document while the loader still holds
* one — the case a `file://` fixture cannot prove.
*/
@Test
fun cuedSeekLandsOnTheTargetThroughAContentUri() {
withHarness(CUED, contentUri = true) { harness ->
harness.pumpUntilSampleDelivered()
harness.resetByteCounter()
harness.seekTo(TARGET_US)
val landed = harness.pumpUntilSampleAtLeast(TARGET_US - KEYFRAME_TOLERANCE_US)
assertTrue("no sample delivered after a content:// seek to ${TARGET_US}us", landed)
assertTrue(
"content:// seek landed at ${harness.lastSampleUs}us",
harness.lastSampleUs <= TARGET_US + KEYFRAME_TOLERANCE_US
)
assertTrue(
"content:// index read opened no descriptor of its own",
harness.randomAccessOpens > 0
)
val budget = harness.fixtureSize / 3
assertTrue(
"content:// seek read ${harness.bytesRead} bytes of a ${harness.fixtureSize}-byte file; " +
"expected under $budget (index seek, not a scan)",
harness.bytesRead < budget
)
}
}
@Test
fun playbackFromTheStartDeliversEverySampleFromTheBeginning() {
withHarness(CUED) { harness ->
val timestamps = harness.pumpSamples(count = 40)
assertTrue("expected samples from the start, got ${timestamps.size}", timestamps.size >= 40)
assertTrue("first sample at ${timestamps.first()}us", timestamps.first() < 500_000L)
// Delivery is in decode order, which is not presentation order once the
// encoder emits B-frames; what must hold is that the set of samples is
// gapless from zero (this fixture is a steady 10 fps).
val sorted = timestamps.sorted()
assertEquals(sorted.indices.map { it * 100_000L }, sorted)
}
}
private fun withHarness(fixture: String, contentUri: Boolean = false, block: (Harness) -> Unit) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val file = copyFixture(instrumentation.context, context, fixture)
// The content:// case reads the same asset back through the provider, which
// keeps its own copy: this process cannot write into the test APK's dirs.
val uri = if (contentUri) FixtureContentProvider.uriFor(fixture) else Uri.fromFile(file)
val harness = Harness(context, file, uri)
try {
harness.prepare()
block(harness)
} finally {
harness.close()
file.delete()
}
}
private fun copyFixture(instrumentationContext: Context, targetContext: Context, fixture: String): File {
val cacheDir = targetContext.cacheDir.also { it.mkdirs() }
val output = File.createTempFile("ffmpeg-seek-fixture-", ".mkv", cacheDir)
instrumentationContext.assets.open(fixture).use { input ->
output.outputStream().use(input::copyTo)
}
return output
}
/**
* Minimal stand-in for ProgressiveMediaPeriod's loader: it opens the data
* source, feeds an ExtractorInput, and honours RESULT_SEEK by re-opening —
* the same contract media3 implements in ExtractingLoadable.load().
*/
private class Harness(context: Context, fixture: File, private val uri: Uri) {
val fixtureSize = fixture.length()
private val counting = CountingDataSourceFactory(DefaultDataSource.Factory(context))
private val io = FfmpegRandomAccessSource(counting) { DataSpec(uri) }
private val output = CapturingOutput()
private val positionHolder = PositionHolder()
private val extractor = requireNotNull(
FfmpegExtractor.create(
{ FfmpegDemuxerPolicy.Preference.FFMPEG },
DvConversionMode.DISABLED,
DefaultSubtitleParserFactory(),
AssHandler(),
io
)
) { "native ffmpeg demuxer unavailable" }
private var dataSource: DataSource? = null
private var input: ExtractorInput? = null
private var opensBaseline = 0
val lastSampleUs: Long
get() = output.lastSampleUs
val bytesRead: Long
get() = counting.bytesRead
val randomAccessOpens: Int
get() = io.openCount - opensBaseline
fun prepare() {
openAt(0)
assertTrue("fixture should be sniffed by the ffmpeg demuxer", extractor.sniff(input!!))
input!!.resetPeekPosition()
extractor.init(output)
}
fun resetByteCounter() {
counting.reset()
opensBaseline = io.openCount
}
fun seekTo(timeUs: Long) {
// media3 restarts the load at the SeekMap's byte hint, then calls seek()
// on the loader thread before the next read.
val hint = output.seekMap?.getSeekPoints(timeUs)?.first?.position ?: 0L
openAt(hint)
extractor.seek(hint, timeUs)
}
fun pumpUntilSampleDelivered(): Boolean {
val before = output.sampleCount
return pump { output.sampleCount > before }
}
fun pumpUntilSampleAtLeast(timeUs: Long): Boolean = pump { output.lastSampleUs >= timeUs }
fun pumpSamples(count: Int): List<Long> {
pump { output.sampleTimestamps.size >= count }
return output.sampleTimestamps.toList()
}
private fun pump(until: () -> Boolean): Boolean {
repeat(200_000) {
if (until()) return true
when (extractor.read(input!!, positionHolder)) {
Extractor.RESULT_SEEK -> openAt(positionHolder.position)
Extractor.RESULT_END_OF_INPUT -> return until()
else -> Unit
}
}
return until()
}
private fun openAt(position: Long) {
dataSource?.close()
val source = counting.createDataSource()
val remaining = source.open(DataSpec.Builder().setUri(uri).setPosition(position).build())
dataSource = source
input = DefaultExtractorInput(
source,
position,
if (remaining == C.LENGTH_UNSET.toLong()) C.LENGTH_UNSET.toLong() else position + remaining
)
}
fun close() {
extractor.release()
dataSource?.close()
}
}
private class CapturingOutput : ExtractorOutput {
val sampleTimestamps = mutableListOf<Long>()
var seekMap: SeekMap? = null
private set
val sampleCount: Int
get() = sampleTimestamps.size
val lastSampleUs: Long
get() = sampleTimestamps.lastOrNull() ?: C.TIME_UNSET
override fun track(id: Int, type: Int): TrackOutput = CapturingTrack(type, sampleTimestamps)
override fun endTracks() = Unit
override fun seekMap(seekMap: SeekMap) {
this.seekMap = seekMap
}
}
private class CapturingTrack(private val type: Int, private val timestamps: MutableList<Long>) : TrackOutput {
private val scratch = ByteArray(64 * 1024)
override fun format(format: Format) = Unit
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean): Int = sampleData(input, length, allowEndOfInput, TrackOutput.SAMPLE_DATA_PART_MAIN)
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {
val read = input.read(scratch, 0, minOf(length, scratch.size))
return if (read == C.RESULT_END_OF_INPUT) 0 else read
}
override fun sampleData(data: ParsableByteArray, length: Int) {
sampleData(data, length, TrackOutput.SAMPLE_DATA_PART_MAIN)
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
data.skipBytes(length)
}
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
if (type == C.TRACK_TYPE_VIDEO) timestamps.add(timeUs)
}
}
/** Counts every byte the demuxer pulls, through either read path. */
private class CountingDataSourceFactory(private val delegate: DataSource.Factory) : DataSource.Factory {
@Volatile private var counter = 0L
val bytesRead: Long
get() = counter
fun reset() {
counter = 0L
}
override fun createDataSource(): DataSource = Counting(delegate.createDataSource())
private inner class Counting(private val inner: DataSource) : DataSource {
override fun open(dataSpec: DataSpec): Long = inner.open(dataSpec)
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
val read = inner.read(buffer, offset, length)
if (read > 0) counter += read
return read
}
override fun addTransferListener(transferListener: TransferListener) = inner.addTransferListener(transferListener)
override fun getUri(): Uri? = inner.uri
override fun getResponseHeaders(): Map<String, List<String>> = inner.responseHeaders
override fun close() = inner.close()
}
}
}
@@ -5,30 +5,33 @@
* is served by a media3 ExtractorInput, so FFmpeg parses the container while
* media3 keeps owning decoders, renderers, and the whole playback surface.
*
* The hard seam is seeking. media3's Extractor is a pull API: an extractor
* The seam used to be seeking. media3's Extractor is a pull API: an extractor
* cannot move the input; it returns RESULT_SEEK and the loader re-opens the
* data source at the requested position. libavformat expects a random-access
* AVIO layer and seeks whenever it pleases (MP4 moov at end of file, AVI idx1,
* MKV Cues, avformat_find_stream_info read-ahead). The bridge reconciles the
* two with a deferral protocol:
* data source. libavformat expects random access and seeks whenever it pleases
* (MP4 moov at end of file, AVI idx1, MKV Cues, MPEG-PS binary search), so
* serving it from the loader alone meant unwinding the in-flight libavformat
* call on every backward jump and replaying the whole open — which a
* one-shot lazy parse like matroska's Cues cannot survive (#2096).
*
* - The read callback only serves when the AVIO logical position equals the
* ExtractorInput position. Any divergence aborts the in-flight libavformat
* call with AVERROR_NEED_SEEK and records the wanted position.
* - Kotlin maps that to RESULT_SEEK (or, when the loader already moved the
* input to exactly that position, to a local resume). After the input is in
* place, resumeAfterSeek() runs avio_seek(), whose success invalidates the
* stale AVIO buffers, and the interrupted operation is retried.
* - During avformat_open_input/avformat_find_stream_info a block cache serves
* header re-reads from memory so each distinct seek position costs at most
* one loader round trip even though open restarts from zero.
* libavformat now gets what it actually requires: the Kotlin side hands this
* shim a random-access byte source (FfmpegRandomAccessSource), so every AVIO
* read succeeds at the position libavformat asked for and nothing is ever
* unwound. Two paths serve reads, chosen per read:
*
* - The loader's ExtractorInput when it already stands at that position. This
* is the steady state for sample delivery, and it keeps media3's byte
* accounting, back-pressure and load-error policy in charge of streaming.
* - The random-access source otherwise (header, index, post-seek jumps).
*
* Kotlin nudges the loader back into step after a jump by returning
* RESULT_SEEK to nativeLogicalPosition(); that is an optimization, never a
* correctness requirement, so no budgets or retries guard it.
*/
#include <android/log.h>
#include <jni.h>
#include <cmath>
#include <cstring>
#include <deque>
#include <vector>
extern "C" {
@@ -44,6 +47,7 @@ extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/dict.h>
#include <libavutil/display.h>
#include <libavutil/dovi_meta.h>
#include <libavutil/error.h>
#include <libavutil/rational.h>
}
@@ -55,18 +59,12 @@ extern "C" {
namespace {
// Returned by the AVIO callbacks to unwind into Java when the ExtractorInput
// cannot serve the requested position synchronously. FFERRTAG values are
// distinct from every real AVERROR code.
const int AVERROR_NEED_SEEK = FFERRTAG('P', 'L', 'Z', 'S');
// readPacket() result codes written to out[0]. Negative values are raw
// AVERROR codes; ERR_JAVA signals the ExtractorInput threw and Kotlin must
// AVERROR codes; ERR_JAVA signals the byte source threw and Kotlin must
// rethrow the stored IOException.
const jint CODE_PACKET = 0;
const jint CODE_EOF = 1;
const jint CODE_NEED_SEEK = 2;
const jint CODE_GROW = 3;
const jint CODE_GROW = 2;
const jint ERR_NOT_OPEN = -101;
const jint ERR_JAVA = -102;
@@ -107,21 +105,14 @@ const jint ROLE_FLAG_MAIN = 1;
const jint ROLE_FLAG_DESCRIPTION = 64; // C.ROLE_FLAG_DESCRIPTION
const jint ROLE_FLAG_HARD_OF_HEARING = 512; // C.ROLE_FLAG_HARD_OF_HEARING
constexpr int64_t kNoPendingSeek = -1;
constexpr int64_t kNoPendingTimeSeek = INT64_MIN;
constexpr size_t kMaxCacheBytes = 24u * 1024 * 1024;
constexpr jint kReadChunkBytes = 64 * 1024;
struct CacheBlock {
int64_t pos;
std::vector<uint8_t> data;
};
struct DemuxState {
JavaVM* vm = nullptr;
jobject input = nullptr;
jmethodID midPosition = nullptr;
jmethodID midRead = nullptr;
jmethodID midReadAt = nullptr;
jmethodID midLength = nullptr;
jbyteArray readBuffer = nullptr;
@@ -129,25 +120,14 @@ struct DemuxState {
AVIOContext* avio = nullptr;
bool opened = false;
// Byte position libavformat will read next. Authoritative: the AVIO seek
// callback moves it, and both read paths serve exactly this offset.
int64_t logicalPos = 0;
int64_t pendingSeek = kNoPendingSeek;
// Presentation-time seek requested via Extractor.seek(); executed by the
// next nativeReadPacket, where the input proxy is bound and deferrals can
// round-trip through the loader.
int64_t pendingTimeSeekUs = kNoPendingTimeSeek;
// Loader round trips consumed by the pending time seek; a seek whose
// avformat_seek_file keeps deferring past this budget is abandoned so
// playback continues instead of ping-ponging forever.
int seekAttempts = 0;
// format->start_time in microseconds; subtracted from delivered pts so
// media3's zero-based timeline matches the duration we report (MPEG-PS/TS
// containers commonly start at a nonzero PCR).
int64_t startTimeUs = 0;
bool cacheActive = true;
std::deque<CacheBlock> cache;
size_t cacheBytes = 0;
AVPacket* packet = nullptr;
AVPacket* filteredPacket = nullptr;
// A packet that outgrew the Java-side buffer: already read and filtered,
@@ -207,28 +187,16 @@ jint callRead(JNIEnv* env, DemuxState* s, jint length) {
return n;
}
void cacheClear(DemuxState* s) {
s->cache.clear();
s->cacheBytes = 0;
}
void cacheAppend(DemuxState* s, int64_t pos, const uint8_t* data, size_t size) {
if (!s->cacheActive) return;
s->cache.push_back(CacheBlock{pos, std::vector<uint8_t>(data, data + size)});
s->cacheBytes += size;
while (s->cacheBytes > kMaxCacheBytes && !s->cache.empty()) {
s->cacheBytes -= s->cache.front().data.size();
s->cache.pop_front();
// Same contract as callRead, but at an absolute position: the Kotlin source
// reopens its handle when the position is not where it stands.
jint callReadAt(JNIEnv* env, DemuxState* s, int64_t position, jint length) {
jint n = env->CallIntMethod(s->input, s->midReadAt, static_cast<jlong>(position), s->readBuffer, length);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return -1;
}
}
const CacheBlock* cacheFind(const DemuxState* s, int64_t pos) {
for (const CacheBlock& block : s->cache) {
if (pos >= block.pos && pos < block.pos + static_cast<int64_t>(block.data.size())) {
return &block;
}
}
return nullptr;
return n;
}
int avioReadPacket(void* opaque, uint8_t* buf, int bufSize) {
@@ -237,55 +205,22 @@ int avioReadPacket(void* opaque, uint8_t* buf, int bufSize) {
if (env == nullptr) return AVERROR(EIO);
if (bufSize <= 0) return 0;
// Cache-first: bytes already read are served at any logical position,
// which lets restarted header phases (probe → hdrl → idx1 at end of file
// → back to movi) replay through seeks that never touch the loader.
const CacheBlock* block = cacheFind(s, s->logicalPos);
if (block != nullptr) {
size_t offset = static_cast<size_t>(s->logicalPos - block->pos);
size_t n = std::min<size_t>(bufSize, block->data.size() - offset);
std::memcpy(buf, block->data.data() + offset, n);
s->logicalPos += static_cast<int64_t>(n);
return static_cast<int>(n);
}
// A read at or beyond the known end of file is EOF regardless of where the
// loader sits. EOF yields no bytes, so it can never enter the block cache;
// deferring it would let an open that alternates between low offsets and an
// end-of-file probe (avi idx1/ODML index scans) ping-pong against the
// loader forever, one round trip per attempt.
int64_t knownLength = callLength(env, s);
const jint want = bufSize < kReadChunkBytes ? bufSize : kReadChunkBytes;
// Prefer the loader's input when it already stands here: those bytes then
// count as media3's own load progress, which is what drives its buffering
// and back-pressure. Anywhere else, read at the absolute position.
const int64_t inputPos = callPosition(env, s);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return AVERROR(EIO);
}
if (knownLength >= 0 && s->logicalPos >= knownLength) return AVERROR_EOF;
// Uncached read: the input must be exactly where libavformat thinks it is.
// Any divergence aborts the in-flight call so Kotlin reconciles through
// avio_seek, which also invalidates the stale AVIO buffers.
if (s->logicalPos != callPosition(env, s)) {
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return AVERROR(EIO);
}
LOGW(
"read defer: logical=%lld input=%lld active=%d cacheBlocks=%zu cacheBytes=%zu first=%lld last=%lld",
(long long)s->logicalPos, (long long)callPosition(env, s), s->cacheActive ? 1 : 0, s->cache.size(),
s->cacheBytes, s->cache.empty() ? -1 : (long long)s->cache.front().pos,
s->cache.empty() ? -1 : (long long)s->cache.back().pos);
s->pendingSeek = s->logicalPos;
return AVERROR_NEED_SEEK;
}
jint n = callRead(env, s, bufSize < kReadChunkBytes ? bufSize : kReadChunkBytes);
const jint n = inputPos == s->logicalPos ? callRead(env, s, want) : callReadAt(env, s, s->logicalPos, want);
if (s->javaError) return AVERROR(EIO);
if (n <= 0) return AVERROR_EOF;
if (n < 0) return AVERROR(EIO);
if (n == 0) return AVERROR_EOF;
env->GetByteArrayRegion(s->readBuffer, 0, n, reinterpret_cast<jbyte*>(buf));
cacheAppend(s, s->logicalPos, buf, static_cast<size_t>(n));
s->logicalPos += n;
return n;
}
@@ -322,21 +257,23 @@ int64_t avioSeek(void* opaque, int64_t offset, int whence) {
target = offset;
}
// Seeks are pure bookkeeping and never touch the loader. Restarted header
// replays hop through cached regions for free; a seek into an uncached
// region surfaces as a deferral on the next uncached read, with the input
// still where the loader left it. avio invalidates its buffers after this
// successful callback.
//
// Deliberately does NOT touch s->pendingSeek: an unconsumed deferral target
// must survive the avformat unwind until Kotlin consumes it.
// Pure bookkeeping: the next read serves this position from whichever path
// can, so a seek can no longer fail or need reconciling. avio invalidates
// its own buffers after this successful callback.
s->logicalPos = target;
// A deferral leaves AVIOContext::error sticky; once a seek has been adopted
// it must not replay into later reads.
if (s->avio != nullptr) s->avio->error = 0;
return target;
}
// Probing (ffio_ensure_seekback) can swap the AVIO buffer for a larger
// allocation and free the original, so the pointer handed to
// avio_alloc_context may be stale. Free whichever buffer the context
// currently holds, exactly once.
void freeAvio(DemuxState* s) {
if (s->avio == nullptr) return;
av_freep(&s->avio->buffer);
avio_context_free(&s->avio);
}
void closeState() {
DemuxState* s = gState;
if (s == nullptr) return; // Close without (or after) an open is a no-op.
@@ -356,14 +293,7 @@ void closeState() {
if (s->format != nullptr) {
avformat_close_input(&s->format);
}
if (s->avio != nullptr) {
// Probing (ffio_ensure_seekback) can swap the AVIO buffer for a larger
// allocation and free the original, so the pointer handed to
// avio_alloc_context may be stale. Free whichever buffer the context
// currently holds, exactly once.
av_freep(&s->avio->buffer);
avio_context_free(&s->avio);
}
freeAvio(s);
if (env != nullptr && s->input != nullptr) {
if (s->readBuffer != nullptr) env->DeleteGlobalRef(s->readBuffer);
env->DeleteGlobalRef(s->input);
@@ -372,8 +302,6 @@ void closeState() {
gState = nullptr;
}
bool deferred(DemuxState* s, int err) { return err == AVERROR_NEED_SEEK || s->pendingSeek != kNoPendingSeek; }
const char* videoMime(AVCodecID id) {
switch (id) {
case AV_CODEC_ID_H264:
@@ -527,10 +455,9 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeProbeFormat(JNIEnv* env,
return env->NewStringUTF(format->name);
}
// Returns 0 on success, CODE_NEED_SEEK when a loader round trip is required,
// or a negative AVERROR. The stream count is NOT the return value: positive
// counts share the result-code namespace (CODE_NEED_SEEK == 2 would collide
// with every two-stream container), so callers use nativeStreamCount().
// Returns 0 on success or a negative AVERROR (ERR_JAVA when the byte source
// itself threw). The stream count is NOT the return value: positive counts
// would share the result-code namespace, so callers use nativeStreamCount().
JNIEXPORT jint JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobject thiz, jobject input) {
StateLock lock;
@@ -543,7 +470,6 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobjec
gState->vm = gVm;
}
DemuxState* s = gState;
if (s->avio != nullptr) s->avio->error = 0;
// FindClass on the declared interface (not GetObjectClass on the concrete
// proxy): JNI dispatches interface method IDs virtually, and the named
@@ -555,9 +481,10 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobjec
}
jmethodID midPosition = env->GetMethodID(inputClass, "position", "()J");
jmethodID midRead = env->GetMethodID(inputClass, "read", "([BI)I");
jmethodID midReadAt = env->GetMethodID(inputClass, "readAt", "(J[BI)I");
jmethodID midLength = env->GetMethodID(inputClass, "length", "()J");
env->DeleteLocalRef(inputClass);
if (midPosition == nullptr || midRead == nullptr || midLength == nullptr) {
if (midPosition == nullptr || midRead == nullptr || midReadAt == nullptr || midLength == nullptr) {
javaClear(env);
return ERR_NOT_OPEN;
}
@@ -572,6 +499,7 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobjec
s->input = env->NewGlobalRef(input);
s->midPosition = midPosition;
s->midRead = midRead;
s->midReadAt = midReadAt;
s->midLength = midLength;
jbyteArray readBuffer = env->NewByteArray(kReadChunkBytes);
s->readBuffer = static_cast<jbyteArray>(env->NewGlobalRef(readBuffer));
@@ -583,44 +511,29 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobjec
if (s->packet == nullptr || s->filteredPacket == nullptr) return AVERROR(ENOMEM);
}
// One AVIOContext per item: a stale buffer or a sticky error from the
// previous item must not leak into this open, and reallocating is cheaper
// than reasoning about which of libavformat's internal fields to reset.
freeAvio(s);
constexpr int kAvioBufferSize = 64 * 1024;
unsigned char* avioBuffer = static_cast<unsigned char*>(av_malloc(kAvioBufferSize));
if (avioBuffer == nullptr) return AVERROR(ENOMEM);
s->avio = avio_alloc_context(
avioBuffer, kAvioBufferSize, /*write_flag=*/0, s, avioReadPacket,
/*write_packet=*/nullptr, avioSeek);
if (s->avio == nullptr) {
constexpr int kAvioBufferSize = 64 * 1024;
unsigned char* avioBuffer = static_cast<unsigned char*>(av_malloc(kAvioBufferSize));
s->avio = avio_alloc_context(
avioBuffer, kAvioBufferSize, /*write_flag=*/0, s, avioReadPacket,
/*write_packet=*/nullptr, avioSeek);
if (s->avio == nullptr) return AVERROR(ENOMEM);
av_freep(&avioBuffer);
return AVERROR(ENOMEM);
}
s->javaError = false;
s->pendingSeek = kNoPendingSeek;
s->pendingTimeSeekUs = kNoPendingTimeSeek;
s->seekAttempts = 0;
s->packetPending = false;
// Every open attempt restarts from scratch and replays the header phase
// through the block cache. Resuming avformat_find_stream_info across
// synthetic IO aborts is not something libavformat contracts to survive
// (observed as a NULL deref inside avformat_find_stream_info), and with the
// cache a full replay costs nothing on the wire.
//
// The cache must survive retries within one open: matroska's header phase
// jumps backward twice (SeekHead -> Cues -> clusters), and clearing here —
// per attempt — makes every retry replay against an empty cache and
// ping-pong against the loader until the reconcile cap kills the open.
// Invalidation is per media item and lives in nativeResetCache, called
// from FfmpegExtractor.init when media3 binds a new source.
s->logicalPos = 0;
// Nothing is ever resumed across calls now: every read succeeds at the
// position libavformat asked for, so open_input and find_stream_info each
// run once, to completion.
avformat_close_input(&s->format);
s->opened = false;
s->cacheActive = true;
int64_t seekResult = avio_seek(s->avio, 0, SEEK_SET);
if (s->pendingSeek != kNoPendingSeek) {
return CODE_NEED_SEEK;
}
if (seekResult < 0) {
LOGW("open seek0 failed=%lld sticky=%d", (long long)seekResult, s->avio != nullptr ? s->avio->error : 0);
return static_cast<jint>(seekResult);
}
s->format = avformat_alloc_context();
if (s->format == nullptr) return AVERROR(ENOMEM);
@@ -630,33 +543,22 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobjec
s->format->flags |= AVFMT_FLAG_GENPTS;
int err = avformat_open_input(&s->format, "", nullptr, nullptr);
if (deferred(s, err)) {
LOGW("open_input defer pending=%lld err=%d", (long long)s->pendingSeek, err);
return CODE_NEED_SEEK;
}
if (s->javaError) return ERR_JAVA;
if (err < 0) {
LOGW("avformat_open_input failed: %d", err);
return err;
}
err = avformat_find_stream_info(s->format, nullptr);
if (deferred(s, err)) {
LOGW("find_info defer pending=%lld err=%d", (long long)s->pendingSeek, err);
return CODE_NEED_SEEK;
}
if (s->javaError) return ERR_JAVA;
if (err < 0) {
LOGW("avformat_find_stream_info failed: %d", err);
return err;
}
s->opened = true;
// Zero-base the timeline: delivered pts subtract this so media3 sees
// [0, duration] even when the container starts at a nonzero PCR/PTS.
s->startTimeUs = s->format->start_time != AV_NOPTS_VALUE ? s->format->start_time : 0;
// Header work is done: packet reads are sequential and every backward move
// goes through a real loader seek.
s->cacheActive = false;
cacheClear(s);
s->opened = true;
bool anySupported = false;
for (unsigned i = 0; i < s->format->nb_streams; i++) {
@@ -732,18 +634,6 @@ JNIEXPORT void JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeC
closeState();
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeResetCache(JNIEnv* env, jobject thiz) {
StateLock lock;
// Per-item boundary: media3 reuses extractor instances across sources, and
// a new item's header occupies the same low offsets as the previous item's.
// Serving those stale bytes would corrupt the new open, so drop everything;
// nativeOpen re-arms the active flag for its retry phase.
DemuxState* s = gState;
if (s == nullptr) return;
cacheClear(s);
s->cacheActive = true;
}
JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeStreamCount(JNIEnv* env, jobject thiz) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr) return ERR_NOT_OPEN;
@@ -830,16 +720,19 @@ JNIEXPORT jboolean JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nat
info[INFO_ROLE_FLAGS] = roleFlags;
info[INFO_BITRATE] = params->bit_rate > 0 ? params->bit_rate : -1;
// Dolby Vision configuration record (dvcC/dvvC), surfaced by libavformat as
// stream side data. Kotlin turns this into a dvh1.* codecs string so the
// DV conversion pipeline engages exactly as it does for Matroska.
// Dolby Vision configuration (dvcC/dvvC), surfaced by libavformat as an
// unpacked AVDOVIDecoderConfigurationRecord — one byte per field, not the
// bit-packed ISOBMFF box layout. Kotlin mirrors media3's DolbyVisionConfig
// to publish video/dolby-vision plus the RFC 6381 codecs string.
info[INFO_DOVI_PROFILE] = -1;
info[INFO_DOVI_LEVEL] = -1;
for (int i = 0; i < params->nb_coded_side_data; i++) {
AVPacketSideData* sd = &params->coded_side_data[i];
if (sd->type == AV_PKT_DATA_DOVI_CONF && sd->size >= 4) {
info[INFO_DOVI_PROFILE] = (sd->data[2] >> 1) & 0x7F; // 7-bit dv_profile
info[INFO_DOVI_LEVEL] = ((sd->data[2] & 0x01) << 5) | ((sd->data[3] >> 3) & 0x1F);
if (sd->type == AV_PKT_DATA_DOVI_CONF && sd->size >= sizeof(AVDOVIDecoderConfigurationRecord)) {
const AVDOVIDecoderConfigurationRecord* dovi =
reinterpret_cast<const AVDOVIDecoderConfigurationRecord*>(sd->data);
info[INFO_DOVI_PROFILE] = dovi->dv_profile;
info[INFO_DOVI_LEVEL] = dovi->dv_level;
break;
}
}
@@ -928,7 +821,6 @@ Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeAttachmentData(JNIEnv* e
// [1]=streamIndex [2]=ptsUs (start-time normalized; packets without any
// timestamp are dropped, media3 cannot schedule them) [3]=flags [4]=size
// [5]=packet position in input coordinates [6]=durationUs (-1 unknown).
// Deferral targets travel through nativeConsumePendingSeek, not this array.
JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeReadPacket(
JNIEnv* env, jobject thiz, jbyteArray buffer, jlongArray out) {
StateLock lock;
@@ -938,94 +830,7 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeR
jint capacity = env->GetArrayLength(buffer);
jlong result[7] = {};
s->javaError = false;
s->pendingSeek = kNoPendingSeek;
int stickyRecovers = 0;
while (true) {
// A presentation-time seek from Extractor.seek() runs here, where the
// input proxy is bound and a deferral can round-trip through the loader.
// The demuxer picks the byte position and resets its own parse state —
// jumping the AVIO position under it would leave demuxer-private state
// (avi->remaining, PES continuations) pointing into the old stream.
// avformat_seek_file restarts from scratch on every retry; the block
// cache is re-armed so index/probe reads replayed across loader round
// trips (matroska Cues, mpegps binary search) stay free on the wire.
if (s->pendingTimeSeekUs != kNoPendingTimeSeek) {
if (++s->seekAttempts > 64) {
// Non-converging seek (each attempt = one loader round trip):
// abandon it and keep delivering from the current position rather
// than ping-ponging forever.
LOGW(
"time seek to %lld abandoned after %d loader round trips", (long long)s->pendingTimeSeekUs,
s->seekAttempts - 1);
s->pendingTimeSeekUs = kNoPendingTimeSeek;
s->cacheActive = false;
cacheClear(s);
} else {
if (s->bsf != nullptr) {
for (unsigned i = 0; i < s->nbStreams; i++) {
if (s->bsf[i] != nullptr) av_bsf_flush(s->bsf[i]);
}
}
s->packetPending = false;
s->cacheActive = true;
int64_t ts = s->pendingTimeSeekUs + s->startTimeUs;
int err = avformat_seek_file(s->format, -1, INT64_MIN, ts, ts, 0);
LOGD(
"time seek to %lld: err=%d logical=%lld attempts=%d", (long long)ts, err, (long long)s->logicalPos,
s->seekAttempts);
if (deferred(s, err)) {
if (s->pendingSeek == kNoPendingSeek) {
if (++stickyRecovers > 16 || s->avio == nullptr) return ERR_JAVA;
s->avio->error = 0;
continue;
}
// pendingTimeSeekUs stays set: the retry after the loader round
// trip re-runs the whole seek.
result[0] = CODE_NEED_SEEK;
env->SetLongArrayRegion(out, 0, 7, result);
return CODE_NEED_SEEK;
}
if (s->javaError) {
result[0] = ERR_JAVA;
env->SetLongArrayRegion(out, 0, 7, result);
return ERR_JAVA;
}
s->pendingTimeSeekUs = kNoPendingTimeSeek;
if (err < 0) {
// Unseekable stream or demuxer refusal: keep playing from the
// current position instead of killing the session; media3 will
// decode-discard toward the target if it can.
LOGW("avformat_seek_file to %lld failed: %d", (long long)ts, err);
} else {
// Align the loader with the demuxer's chosen byte position BEFORE
// the first read. avformat_seek_file resolves in memory (cues) and
// typically leaves the AVIO position behind the loader's SeekMap
// guess; letting av_read_frame discover that and unwind with a
// synthetic IO error poisons matroskadec into resync, which skips
// the keyframe cluster — the video renderer then starves until the
// next keyframe while audio keeps advancing, and the resume-stall
// watchdog seeks in a loop. The cache stays armed across this round
// trip (until the first packet delivers) so replayed header bytes
// stay free.
int64_t inputPos = callPosition(env, s);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
result[0] = ERR_JAVA;
env->SetLongArrayRegion(out, 0, 7, result);
return ERR_JAVA;
}
if (inputPos >= 0 && inputPos != s->logicalPos) {
s->pendingSeek = s->logicalPos;
result[0] = CODE_NEED_SEEK;
env->SetLongArrayRegion(out, 0, 7, result);
return CODE_NEED_SEEK;
}
}
}
}
if (s->packetPending) {
// Oversized packet held across a CODE_GROW round trip: deliver it now
// instead of reading (and losing) a new frame.
@@ -1033,19 +838,6 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeR
} else {
av_packet_unref(s->packet);
int err = av_read_frame(s->format, s->packet);
if (deferred(s, err)) {
if (s->pendingSeek == kNoPendingSeek) {
// Sticky AVIO error replayed from a deferral Kotlin already
// reconciled: clear it and retry instead of surfacing a targetless
// seek.
if (++stickyRecovers > 16 || s->avio == nullptr) return ERR_JAVA;
s->avio->error = 0;
continue;
}
result[0] = CODE_NEED_SEEK;
env->SetLongArrayRegion(out, 0, 7, result);
return CODE_NEED_SEEK;
}
if (err == AVERROR_EOF) {
result[0] = CODE_EOF;
env->SetLongArrayRegion(out, 0, 7, result);
@@ -1107,13 +899,6 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeR
}
ptsUs -= s->startTimeUs;
// Post-seek convergence is over once a packet flows; steady-state packet
// reads are sequential, so drop the replay cache until the next seek.
if (s->cacheActive) {
s->cacheActive = false;
cacheClear(s);
}
result[0] = CODE_PACKET;
result[1] = s->packet->stream_index;
result[2] = ptsUs;
@@ -1128,42 +913,40 @@ JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeR
}
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeConsumePendingSeek(JNIEnv* env, jobject thiz) {
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeLogicalPosition(JNIEnv* env, jobject thiz) {
StateLock lock;
if (gState == nullptr) return -9223372036854775807L - 1; // Long.MIN_VALUE
int64_t pending = gState->pendingSeek;
gState->pendingSeek = kNoPendingSeek;
return pending;
DemuxState* s = gState;
if (s == nullptr || !s->opened) return -1;
return static_cast<jlong>(s->logicalPos);
}
// Re-establishes the AVIO position after the loader moved the input to
// `position`. Must only be called when the ExtractorInput is already there.
// Seeks to a presentation time (media3 timeline microseconds, start-time
// normalized). Called on the loader thread, where blocking IO belongs:
// libavformat reads its own index through the random-access source, so this
// either lands on the target keyframe or reports that the container has no
// usable index.
JNIEXPORT jint JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeResumeAfterSeek(JNIEnv* env, jobject thiz, jlong position) {
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeSeek(JNIEnv* env, jobject thiz, jlong timeUs) {
StateLock lock;
DemuxState* s = gState;
if (s == nullptr || s->avio == nullptr) return ERR_NOT_OPEN;
s->pendingSeek = kNoPendingSeek;
if (s == nullptr || !s->opened || s->format == nullptr) return ERR_NOT_OPEN;
s->javaError = false;
int64_t result = avio_seek(s->avio, position, SEEK_SET);
if (result >= 0) return 0;
if (s->pendingSeek != kNoPendingSeek) return CODE_NEED_SEEK;
return static_cast<jint>(result);
}
// Records a presentation-time seek (media3 timeline microseconds, i.e.
// start-time normalized). Executed by the next nativeReadPacket, which owns
// a bound input proxy and can defer through the loader; running
// avformat_seek_file here would read against a dead input.
JNIEXPORT void JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeSeekTo(JNIEnv* env, jobject thiz, jlong timeUs) {
StateLock lock;
DemuxState* s = gState;
if (s == nullptr || !s->opened) return;
s->pendingTimeSeekUs = timeUs;
s->seekAttempts = 0;
// Any packet parked for a CODE_GROW retry belongs to the pre-seek stream.
s->packetPending = false;
if (s->bsf != nullptr) {
for (unsigned i = 0; i < s->nbStreams; i++) {
if (s->bsf[i] != nullptr) av_bsf_flush(s->bsf[i]);
}
}
const int64_t ts = timeUs + s->startTimeUs;
const int err = avformat_seek_file(s->format, -1, INT64_MIN, ts, ts, 0);
if (s->javaError) return ERR_JAVA;
if (err < 0) {
LOGW("seek to %lld failed: %d", (long long)ts, err);
return err;
}
LOGD("seek to %lld: logical=%lld", (long long)ts, (long long)s->logicalPos);
return 0;
}
} // extern "C"
@@ -0,0 +1,26 @@
package com.edde746.plezy.exoplayer
/**
* RFC 6381 codecs strings for Dolby Vision tracks, mirroring media3's
* `DolbyVisionConfig.parse` profile table so the FFmpeg demux path publishes
* the same format media3's own MP4/Matroska extractors would: recognized
* profiles get `video/dolby-vision` plus this string, unrecognized profiles
* keep the base codec's format untouched.
*/
internal object DoviCodecs {
/**
* Codecs string for a DOVIDecoderConfigurationRecord's [profile]/[level],
* or null when media3 does not recognize the profile (the track then plays
* as its base codec).
*/
fun rfc6381(profile: Int, level: Int): String? {
val prefix = when (profile) {
4, 5, 7, 8 -> "dvhe"
9 -> "dvav"
10 -> "dav1"
else -> return null
}
return "%s.%02d.%02d".format(prefix, profile, level)
}
}
@@ -746,6 +746,11 @@ class ExoPlayerCore(private val activity: Activity) :
}
httpDataSourceFactory = httpFactory
dataSourceFactory = DefaultDataSource.Factory(activity, httpFactory)
// libavformat owns its own seeking, so the demuxer reads through a
// random-access source (FfmpegRandomAccessSource). Recording the DataSpec
// media3 opens lets it clone that spec — same URI, cache key, flags and
// request headers — instead of re-deriving one.
val recordingFactory = RecordingDataSourceFactory(dataSourceFactory!!)
val extractorsFactory = DefaultExtractorsFactory()
// High-bitrate Plex DVR MPEG-TS recordings can have sparse PCR packets; the default
// 600-packet window may leave duration unknown and seeking disabled.
@@ -773,55 +778,73 @@ class ExoPlayerCore(private val activity: Activity) :
// Reads this.dvMode and this.demuxerPreference each time (not captured) so
// DV7→8.1 retry and demuxer-mode changes can reload without
// reinitializing the player.
val wrappedExtractorsFactory = androidx.media3.extractor.ExtractorsFactory {
val currentDvMode = this.dvMode
val doviEnabled = currentDvMode != DvConversionMode.DISABLED
val currentDemuxerPreference = this.demuxerPreference
Log.i(TAG, "[init] extractors: demuxer=${currentDemuxerPreference.wireName}")
// media3 invokes the factory once per player session and reuses the
// extractor instances for every item, so the sniff reads the live
// preference instead of a captured one.
val liveDemuxerPreference = { this@ExoPlayerCore.demuxerPreference }
val ffmpegFirst =
listOfNotNull(
FfmpegExtractor.create(
liveDemuxerPreference,
currentDvMode,
subtitleParserFactory,
handler
)?.also { activeFfmpegExtractor = it }
val wrappedExtractorsFactory = object : androidx.media3.extractor.ExtractorsFactory {
// media3's progressive path always supplies the item URI. Without one
// the demuxer cannot be handed random access, so FFmpeg stays out
// rather than failing later on its first index jump.
override fun createExtractors(): Array<androidx.media3.extractor.Extractor> {
Log.w(TAG, "[init] extractors: no item uri, ffmpeg demuxer unavailable")
return buildExtractors(null)
}
override fun createExtractors(
uri: Uri,
responseHeaders: Map<String, List<String>>
): Array<androidx.media3.extractor.Extractor> = buildExtractors(uri)
private fun buildExtractors(uri: Uri?): Array<androidx.media3.extractor.Extractor> {
val currentDvMode = this@ExoPlayerCore.dvMode
val doviEnabled = currentDvMode != DvConversionMode.DISABLED
val currentDemuxerPreference = this@ExoPlayerCore.demuxerPreference
Log.i(TAG, "[init] extractors: demuxer=${currentDemuxerPreference.wireName}")
// media3 invokes the factory once per item and reuses the extractor
// instances, so the sniff reads the live preference instead of a
// captured one.
val liveDemuxerPreference = { this@ExoPlayerCore.demuxerPreference }
val ffmpegFirst = listOfNotNull(
uri?.let { itemUri ->
val io = FfmpegRandomAccessSource(dataSourceFactory!!) { recordingFactory.specFor(itemUri) }
FfmpegExtractor.create(
liveDemuxerPreference,
currentDvMode,
subtitleParserFactory,
handler,
io
)?.also { activeFfmpegExtractor = it }
}
)
(
ffmpegFirst + extractorsFactory.createExtractors().map { extractor ->
when {
extractor is MatroskaExtractor -> {
val withTextPipeline = OutputWrappingExtractor(extractor) { out ->
AssSubtitleExtractorOutput(SubtitleTranscodingExtractorOutput(out, subtitleParserFactory), handler)
return (
ffmpegFirst + extractorsFactory.createExtractors().map { extractor ->
when {
extractor is MatroskaExtractor -> {
val withTextPipeline = OutputWrappingExtractor(extractor) { out ->
AssSubtitleExtractorOutput(SubtitleTranscodingExtractorOutput(out, subtitleParserFactory), handler)
}
if (doviEnabled) {
DoviExtractorWrapper(withTextPipeline, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMkvWrapper = it
}
} else {
withTextPipeline
}
}
if (doviEnabled) {
DoviExtractorWrapper(withTextPipeline, currentDvMode) { level, prefix, message ->
doviEnabled && (extractor is Mp4Extractor || extractor is FragmentedMp4Extractor) -> {
DoviExtractorWrapper(extractor, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMkvWrapper = it
activeDoviMp4Wrapper = it
}
} else {
withTextPipeline
}
else -> extractor
}
doviEnabled && (extractor is Mp4Extractor || extractor is FragmentedMp4Extractor) -> {
DoviExtractorWrapper(extractor, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMp4Wrapper = it
}
}
else -> extractor
}
}
).toTypedArray()
).toTypedArray()
}
}
val mediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory!!, wrappedExtractorsFactory)
val mediaSourceFactory = DefaultMediaSourceFactory(recordingFactory, wrappedExtractorsFactory)
.setSubtitleParserFactory(subtitleParserFactory)
playbackMediaSourceFactory = mediaSourceFactory
@@ -0,0 +1,134 @@
package com.edde746.plezy.exoplayer
import androidx.annotation.OptIn
import androidx.media3.common.MimeTypes
import androidx.media3.common.ParserException
import androidx.media3.common.util.UnstableApi
import androidx.media3.container.OpusUtil
/**
* Shapes ffmpeg codec extradata into the per-codec initializationData layout
* media3's audio decode paths consume. MediaCodecAudioRenderer maps the list
* entries verbatim to MediaCodec csd-0/1/2 and the bundled FfmpegAudioDecoder
* rebuilds avcodec extradata from the same entries, so both expect the shapes
* media3's own extractors emit — not raw ffmpeg extradata:
*
* - Opus: [OpusHead, codec delay ns, seek pre-roll ns]. Android's Opus
* decoders consume their first three input buffers as exactly this
* configuration; given only OpusHead they read the first two real packets
* as delay/pre-roll and then silently discard every decoded sample, which
* stalled the audio clock at 0 until the MPV fallback fired (#2088).
* - Vorbis: [identification header, setup header], split out of the
* Xiph-laced blob the way MatroskaExtractor's parseVorbisCodecPrivate does.
* - FLAC: the "fLaC"-marked STREAMINFO stream MediaCodec documents; ffmpeg
* surfaces a bare or block-headed STREAMINFO depending on the container.
*
* Everything else (AAC ASC, ALAC cookie, passthrough codecs) already matches
* media3's single-entry shape and passes through. MP3's WAVEFORMATEX blob is
* dropped on the JNI side before it reaches this shaping.
*/
@OptIn(UnstableApi::class)
internal object FfmpegAudioCsd {
// RFC 7845 section 5.1: the identification header is at least 19 bytes;
// OpusUtil reads the pre-skip field at offsets 10-11.
private const val OPUS_HEADER_MIN_BYTES = 19
private val FLAC_STREAM_MARKER = byteArrayOf(0x66, 0x4C, 0x61, 0x43) // "fLaC"
private const val FLAC_STREAM_INFO_SIZE = 34
private const val FLAC_BLOCK_HEADER_SIZE = 4
private const val FLAC_LAST_BLOCK_FLAG = 0x80
fun initializationData(mime: String, extradata: ByteArray): List<ByteArray> = when (mime) {
MimeTypes.AUDIO_OPUS -> opus(extradata)
MimeTypes.AUDIO_VORBIS -> vorbis(extradata)
MimeTypes.AUDIO_FLAC -> flac(extradata)
else -> listOf(extradata)
}
private fun opus(extradata: ByteArray): List<ByteArray> {
if (extradata.size < OPUS_HEADER_MIN_BYTES) {
throw malformed("Opus extradata is not an identification header: ${extradata.size} bytes")
}
// [OpusHead, pre-skip ns, 80 ms default seek pre-roll ns] — the same
// shape media3's Matroska/Ogg/MP4 extractors publish.
return OpusUtil.buildInitializationData(extradata)
}
/**
* Splits the Xiph-laced header blob (identification, comment, setup) into
* media3's [identification header, setup header] pair, mirroring media3
* 1.11.0 MatroskaExtractor.parseVorbisCodecPrivate.
*/
private fun vorbis(extradata: ByteArray): List<ByteArray> {
try {
if (extradata[0].toInt() != 0x02) throw malformed("Vorbis extradata is not Xiph-laced headers")
var offset = 1
var idHeaderLength = 0
while (extradata[offset].toInt() and 0xFF == 0xFF) {
idHeaderLength += 0xFF
offset++
}
idHeaderLength += extradata[offset++].toInt() and 0xFF
var commentHeaderLength = 0
while (extradata[offset].toInt() and 0xFF == 0xFF) {
commentHeaderLength += 0xFF
offset++
}
commentHeaderLength += extradata[offset++].toInt() and 0xFF
if (extradata[offset].toInt() != 0x01) throw malformed("Vorbis identification header not found")
val idHeader = extradata.copyOfRange(offset, offset + idHeaderLength)
offset += idHeaderLength
if (extradata[offset].toInt() != 0x03) throw malformed("Vorbis comment header not found")
offset += commentHeaderLength
if (extradata[offset].toInt() != 0x05) throw malformed("Vorbis setup header not found")
return listOf(idHeader, extradata.copyOfRange(offset, extradata.size))
} catch (e: IndexOutOfBoundsException) {
throw malformed("Vorbis extradata truncated")
}
}
/**
* Normalizes to the "fLaC"-marked metadata stream. MediaCodec's decoder
* feeds csd-0 straight into libFLAC, which requires the stream marker;
* ffmpeg's canonical FLAC extradata is the bare 34-byte STREAMINFO, and
* some demuxers keep the 4-byte metadata block header in front of it.
*/
private fun flac(extradata: ByteArray): List<ByteArray> {
if (startsWithFlacMarker(extradata)) return listOf(extradata)
if (extradata.size == FLAC_STREAM_INFO_SIZE) {
val blockHeader = byteArrayOf(
(FLAC_LAST_BLOCK_FLAG or 0).toByte(), // last-metadata-block, type 0 = STREAMINFO
0x00,
0x00,
FLAC_STREAM_INFO_SIZE.toByte()
)
return listOf(FLAC_STREAM_MARKER + blockHeader + extradata)
}
val declaredLength = if (extradata.size >= FLAC_BLOCK_HEADER_SIZE) {
((extradata[1].toInt() and 0xFF) shl 16) or
((extradata[2].toInt() and 0xFF) shl 8) or
(extradata[3].toInt() and 0xFF)
} else {
-1
}
if (extradata[0].toInt() and 0x7F == 0 &&
declaredLength == FLAC_STREAM_INFO_SIZE &&
extradata.size >= FLAC_BLOCK_HEADER_SIZE + FLAC_STREAM_INFO_SIZE
) {
return listOf(FLAC_STREAM_MARKER + extradata)
}
throw malformed("FLAC extradata is not a STREAMINFO block: ${extradata.size} bytes")
}
private fun startsWithFlacMarker(extradata: ByteArray): Boolean {
if (extradata.size < FLAC_STREAM_MARKER.size) return false
for (i in FLAC_STREAM_MARKER.indices) {
if (extradata[i] != FLAC_STREAM_MARKER[i]) return false
}
return true
}
private fun malformed(message: String): ParserException = ParserException.createForMalformedContainer(message, null)
}
@@ -15,25 +15,32 @@ import androidx.media3.common.util.UnstableApi
*/
@OptIn(UnstableApi::class)
internal object FfmpegDemuxerJni {
/** Re-entry point for the AVIO callbacks while a native call is in flight. */
/** Byte source the AVIO callbacks read through while a native call is in flight. */
interface Input {
/** Current byte position of the underlying [androidx.media3.extractor.ExtractorInput]. */
/** Current byte position of the loader's [androidx.media3.extractor.ExtractorInput]. */
fun position(): Long
/**
* Reads up to [length] bytes into [buf]. Returns the number of bytes read,
* `0` at end of input, or `-1` after storing the failure in [lastError].
* Reads up to [length] bytes from the loader's input at its current
* position. Returns the number of bytes read, `0` at end of input, or `-1`
* after storing the failure in [lastError].
*/
fun read(buf: ByteArray, length: Int): Int
/**
* Reads up to [length] bytes at absolute [position], wherever the loader
* stands. Same return contract as [read]. This is what lets libavformat
* seek its own index without the shim unwinding the in-flight call.
*/
fun readAt(position: Long, buf: ByteArray, length: Int): Int
/** Total input length in bytes, or `-1` when unknown. */
fun length(): Long
var lastError: String?
}
// readPacket out[] indices. Deferral targets travel through
// [nativeConsumePendingSeek], not this array.
// readPacket out[] indices.
const val OUT_CODE = 0
const val OUT_STREAM_INDEX = 1
const val OUT_PTS_US = 2
@@ -46,8 +53,7 @@ internal object FfmpegDemuxerJni {
// Result codes written to out[OUT_CODE]; negative values are raw AVERRORs.
const val CODE_PACKET = 0
const val CODE_EOF = 1
const val CODE_NEED_SEEK = 2
const val CODE_GROW = 3
const val CODE_GROW = 2
const val ERR_JAVA = -102
// streamInfo long[] layout.
@@ -81,10 +87,10 @@ internal object FfmpegDemuxerJni {
external fun nativeProbeFormat(header: ByteArray): String?
/**
* Opens (and resumes opening) the demuxer against [input]. Returns 0 on
* success, [CODE_NEED_SEEK] when the loader must move the input first, or a
* negative AVERROR. The stream count is read separately via
* [nativeStreamCount]; it must not ride the same namespace as result codes.
* Opens the demuxer against [input]. Returns 0 on success or a negative
* AVERROR ([ERR_JAVA] when the input itself failed). The stream count is read
* separately via [nativeStreamCount]; it must not ride the same namespace as
* result codes.
*/
external fun nativeOpen(input: Input): Int
@@ -120,19 +126,14 @@ internal object FfmpegDemuxerJni {
*/
external fun nativeReadPacket(buffer: ByteArray, out: LongArray): Int
/** Returns the recorded seek target, or [Long.MIN_VALUE] when none. */
external fun nativeConsumePendingSeek(): Long
/** Adopts [position] as the AVIO position; the input must already be there. */
external fun nativeResumeAfterSeek(position: Long): Int
/** Byte position libavformat will read next, or -1 when not open. */
external fun nativeLogicalPosition(): Long
/**
* Records a presentation-time seek (media3 timeline microseconds). The next
* [nativeReadPacket] executes it via avformat_seek_file, deferring through
* the loader as needed; the demuxer picks the byte position itself.
* Seeks to [timeUs] (media3 timeline microseconds, i.e. start-time
* normalized). The demuxer resolves the byte position itself through its own
* index. Returns 0 on success, or a negative AVERROR when the container has
* no usable index and libavformat refused the seek.
*/
external fun nativeSeekTo(timeUs: Long)
/** Drops cached header blocks; called when the extractor binds a new source. */
external fun nativeResetCache()
external fun nativeSeek(timeUs: Long): Int
}
@@ -36,10 +36,10 @@ import java.io.IOException
* composed in [init] then feeds libass dialogue and transcodes cues the same
* way the media3 Matroska path does.
*
* Seeking protocol: see `ffmpeg_demuxer_jni.cc`. The extractor never moves the
* input itself; position divergences abort the native call, and Kotlin either
* returns RESULT_SEEK or resumes in place when the loader already positioned
* the input at the requested byte.
* Seeking: libavformat resolves seeks itself, reading its own index through
* [FfmpegRandomAccessSource]. media3's byte hints are ignored, nothing is ever
* unwound, and the loader is merely nudged to follow along so that sample
* delivery keeps streaming on its connection (see [alignLoader]).
*
* The instance sits before media3's extractors and sniffs everything FFmpeg
* can probe while [FfmpegDemuxerPolicy] enables it; media3's list behind it
@@ -50,28 +50,24 @@ internal class FfmpegExtractor private constructor(
private val preferenceSupplier: () -> FfmpegDemuxerPolicy.Preference,
private val dvMode: DvConversionMode,
private val subtitleParserFactory: SubtitleParser.Factory,
private val assHandler: AssHandler
private val assHandler: AssHandler,
private val io: FfmpegRandomAccessSource
) : Extractor {
companion object {
private const val TAG = "FfmpegExtractor"
private const val SNIFF_BYTES = 64 * 1024
private const val MAX_RECONCILES = 24
// Loader round trips (RESULT_SEEK) allowed for one item's whole open
// phase; matroska needs ~3, avi with an end-of-file index ~4.
private const val MAX_OPEN_LOADER_ROUND_TRIPS = 96
private const val INITIAL_PACKET_BUFFER_BYTES = 2 * 1024 * 1024
private const val AUDIO_INDEX_INTERVAL_US = 500_000L
/** Null when the native library is unavailable. */
fun create(
preferenceSupplier: () -> FfmpegDemuxerPolicy.Preference,
dvMode: DvConversionMode,
subtitleParserFactory: SubtitleParser.Factory,
assHandler: AssHandler
assHandler: AssHandler,
io: FfmpegRandomAccessSource
): FfmpegExtractor? = if (FfmpegDemuxerJni.available) {
FfmpegExtractor(preferenceSupplier, dvMode, subtitleParserFactory, assHandler)
FfmpegExtractor(preferenceSupplier, dvMode, subtitleParserFactory, assHandler, io)
} else {
null
}
@@ -94,10 +90,23 @@ internal class FfmpegExtractor private constructor(
}
}
override fun readAt(position: Long, buf: ByteArray, length: Int): Int {
lastError = null
return try {
io.readAt(position, buf, length)
} catch (e: IOException) {
lastError = e.message ?: "demuxer random access read failed"
-1
}
}
override fun length(): Long {
val input = currentInput ?: return -1L
val length = input.length
return if (length == C.LENGTH_UNSET.toLong()) -1L else length
val fromLoader = currentInput?.length ?: C.LENGTH_UNSET.toLong()
if (fromLoader != C.LENGTH_UNSET.toLong()) return fromLoader
// Length-less loader open (progressive live stream): fall back to
// whatever a random-access open already resolved.
val resolved = io.length()
return if (resolved == C.LENGTH_UNSET.toLong()) -1L else resolved
}
override var lastError: String? = null
@@ -107,8 +116,6 @@ internal class FfmpegExtractor private constructor(
private var doviOutputWrapper: DoviExtractorOutputWrapper? = null
private var durationUs = C.TIME_UNSET
private var trackOutputs: Array<TrackOutput?> = emptyArray()
private var primaryStreamIndex = -1
private var primaryStreamIsAudio = false
private var packetBytes = ByteArray(INITIAL_PACKET_BUFFER_BYTES)
private val packetParsable = ParsableByteArray()
private val packetOut = LongArray(FfmpegDemuxerJni.OUT_LENGTH)
@@ -122,12 +129,11 @@ internal class FfmpegExtractor private constructor(
// the loader thread, read by ExoPlayerCore.getStats on another thread.
@Volatile private var bitrateMeters: Array<StreamBitrateMeter?> = emptyArray()
// Seek index for the primary stream: (presentation time, input position) of
// video keyframes or periodic audio packets. The SeekMap reads it on the
// playback thread while the loader thread appends, hence the lock.
private val seekIndexTimes = ArrayList<Long>()
private val seekIndexPositions = ArrayList<Long>()
private val seekIndexLock = Any()
// Set by seek(), applied by the next read(): media3 calls both on the loader
// thread, but only read() is allowed to throw IOException and the demuxer's
// seek reads its index.
private var pendingSeekUs = C.TIME_UNSET
private var deliveredAnyPacket = false
private val sniffScratch = ByteArray(SNIFF_BYTES)
@@ -167,9 +173,8 @@ internal class FfmpegExtractor private constructor(
override fun init(output: ExtractorOutput) {
// media3 reuses extractor instances across sources; drop the previous
// item's header cache so this open cannot replay stale bytes.
FfmpegDemuxerJni.nativeResetCache()
openLoaderRoundTrips = 0
// item's demuxer and byte source so this open starts clean.
releaseDemuxer()
// Same composition as the MP4/MKV paths: DoviConvertingTrackOutput
// inspects each video track's codecs string and passes non-DV through.
val doviWrapped = if (dvMode != DvConversionMode.DISABLED) {
@@ -202,8 +207,16 @@ internal class FfmpegExtractor private constructor(
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
currentInput = input
try {
if (!opened && !openStreams(input, seekPosition)) return Extractor.RESULT_SEEK
return readPacket(input, seekPosition)
if (!opened) openStreams()
applyPendingSeek()
alignLoader(input)?.let { position ->
seekPosition.position = position
return Extractor.RESULT_SEEK
}
// Aligned: the loader serves the samples, so nothing needs a second
// handle open until the demuxer jumps again.
if (io.isOpen) io.close()
return readPacket()
} catch (e: Throwable) {
Log.w(TAG, "read threw at input=${input.position}", e)
throw e
@@ -213,28 +226,72 @@ internal class FfmpegExtractor private constructor(
}
/**
* Hands the presentation-time target to the demuxer: the next read runs
* avformat_seek_file, which picks the byte position and resets libavformat's
* parse state (jumping the AVIO position under the demuxer would leave
* demuxer-private state pointing into the old stream). The byte position
* media3 supplies is only its SeekMap guess; the loader converges on the
* demuxer's choice through the normal deferral round trip. The DV
* converter's buffered NAL state resets here as well.
* Byte position the loader should move to, or null when it already stands
* where libavformat reads.
*
* Reads outside the loader's window are served by [io] regardless, so this
* is an optimization, never a correctness requirement: it keeps sample
* delivery on media3's own connection, which is what drives its byte
* accounting, back-pressure (ProgressiveMediaPeriod watches the input
* position) and load-error policy. Nothing here needs a retry budget.
*/
private fun alignLoader(input: ExtractorInput): Long? {
val demuxerPosition = FfmpegDemuxerJni.nativeLogicalPosition()
if (demuxerPosition < 0 || demuxerPosition == input.position) return null
val length = input.length
// Opening a range at or past the end is a failed request, not an
// alignment; let the read report end of input instead.
if (length != C.LENGTH_UNSET.toLong() && demuxerPosition >= length) return null
return demuxerPosition
}
/**
* Records the target; [read] performs it. media3's byte position is its
* SeekMap guess and is deliberately ignored — libavformat picks the byte
* position from its own index.
*/
override fun seek(position: Long, timeUs: Long) {
Log.i(TAG, "extractor seek position=$position timeUs=$timeUs opened=$opened")
Log.i(TAG, "extractor seek timeUs=$timeUs opened=$opened")
doviOutputWrapper?.resetTracks()
// Buffered LOAS bytes belong to the pre-seek stream; the StreamMuxConfig
// survives so audio resumes without waiting for the next config.
for (latm in latmOutputs) latm.reset()
if (opened) FfmpegDemuxerJni.nativeSeekTo(timeUs)
pendingSeekUs = timeUs
}
private fun applyPendingSeek() {
val target = pendingSeekUs
if (target == C.TIME_UNSET) return
pendingSeekUs = C.TIME_UNSET
// media3 issues seek(0) before the first read of every item; a demuxer
// that has not delivered a packet yet is already at the start, and
// seeking would throw away find_stream_info's buffered packets and
// re-read the header region.
if (target == 0L && !deliveredAnyPacket) return
val code = FfmpegDemuxerJni.nativeSeek(target)
if (code == FfmpegDemuxerJni.ERR_JAVA) {
throw IOException(inputProxy.lastError ?: "demuxer input failed")
}
if (code != 0) {
// No usable index in this container: libavformat keeps delivering from
// where it stands and the renderers decode-discard toward the target,
// which is what media3's own extractors do for a cueless file.
Log.w(TAG, "demuxer refused seek to ${target}us: $code")
}
}
override fun release() {
releaseDemuxer()
}
private fun releaseDemuxer() {
if (opened) {
opened = false
FfmpegDemuxerJni.nativeClose()
}
io.close()
pendingSeekUs = C.TIME_UNSET
deliveredAnyPacket = false
// media3's extractors may demux a later item while this instance keeps
// the previous one's stream layout; a stale measurement must not leak
// into stats.
@@ -252,49 +309,15 @@ internal class FfmpegExtractor private constructor(
return bitrateMeters.getOrNull(index)?.bitrateBps()
}
// The in-call `reconciles` counter resets on every read() invocation, so it
// cannot bound RESULT_SEEK ping-pong across loader restarts. This budget
// spans the whole open of one item (reset in init) and turns a
// non-converging header phase into a clean fallback instead of a hang.
private var openLoaderRoundTrips = 0
/** Returns false when a loader seek was requested via [seekPosition]. */
private fun openStreams(input: ExtractorInput, seekPosition: PositionHolder): Boolean {
var reconciles = 0
while (true) {
when (val code = FfmpegDemuxerJni.nativeOpen(inputProxy)) {
0 -> {
prepareTracks()
opened = true
Log.i(TAG, "ffmpeg demuxer ready: ${trackOutputs.count { it != null }} tracks")
return true
}
FfmpegDemuxerJni.CODE_NEED_SEEK -> {
val target = FfmpegDemuxerJni.nativeConsumePendingSeek()
Log.i(TAG, "open: NEED_SEEK target=$target inputPos=${input.position}")
if (target == Long.MIN_VALUE || target < 0) {
// Sticky AVIO error replayed without a fresh deferral: re-sync at
// the loader's current position and continue (bounded below).
if (++reconciles > MAX_RECONCILES) {
throw malformed("demuxer produced an invalid seek target: $target")
}
if (FfmpegDemuxerJni.nativeResumeAfterSeek(input.position) != 0) {
throw malformed("demuxer resync failed at ${input.position}")
}
continue
}
if (++reconciles > MAX_RECONCILES) throw malformed("too many demuxer repositions")
if (!reconcile(input, seekPosition, target)) {
if (++openLoaderRoundTrips > MAX_OPEN_LOADER_ROUND_TRIPS) {
throw malformed("demuxer open did not converge after $openLoaderRoundTrips loader seeks")
}
return false
}
}
FfmpegDemuxerJni.ERR_JAVA ->
throw IOException(inputProxy.lastError ?: "demuxer input failed")
else -> throw malformed("ffmpeg demuxer open failed: $code")
private fun openStreams() {
when (val code = FfmpegDemuxerJni.nativeOpen(inputProxy)) {
0 -> {
prepareTracks()
opened = true
Log.i(TAG, "ffmpeg demuxer ready: ${trackOutputs.count { it != null }} tracks")
}
FfmpegDemuxerJni.ERR_JAVA -> throw IOException(inputProxy.lastError ?: "demuxer input failed")
else -> throw malformed("ffmpeg demuxer open failed: $code")
}
}
@@ -336,19 +359,35 @@ internal class FfmpegExtractor private constructor(
val extradata = FfmpegDemuxerJni.nativeStreamExtradata(index)
if (extradata != null) {
builder.setInitializationData(listOf(extradata))
// Audio csd is codec-specific in media3 (see FfmpegAudioCsd); raw
// extradata is only correct for video (already Annex-B via the JNI
// bitstream filter) and text tracks.
builder.setInitializationData(
if (trackType == C.TRACK_TYPE_AUDIO) {
FfmpegAudioCsd.initializationData(mime, extradata)
} else {
listOf(extradata)
}
)
}
when (trackType) {
C.TRACK_TYPE_VIDEO -> {
// A Dolby Vision config record rides the stream as side data; the
// codecs string is what DoviConvertingTrackOutput keys on, exactly
// as it does for Matroska's CodecPrivate.
// A Dolby Vision config record rides the stream as side data.
// Mirror media3's MP4/Matroska extractors: recognized profiles
// publish video/dolby-vision with the RFC 6381 codecs string, so
// DoviConvertingTrackOutput's P7 conversion, the P8 passthrough
// path, and the renderer's HEVC fallback engage exactly as they do
// on the media3 demux path.
val doviProfile = numbers[FfmpegDemuxerJni.INFO_DOVI_PROFILE].toInt()
Log.i(TAG, "video track $index: doviProfile=$doviProfile mime=$mime")
if (doviProfile >= 0) {
val doviLevel = numbers[FfmpegDemuxerJni.INFO_DOVI_LEVEL].toInt().coerceAtLeast(0)
builder.setCodecs("dvh1.%02d.%02d".format(doviProfile, doviLevel))
val doviCodecs = DoviCodecs.rfc6381(doviProfile, doviLevel)
if (doviCodecs != null) {
builder.setCodecs(doviCodecs)
builder.setSampleMimeType(MimeTypes.VIDEO_DOLBY_VISION)
}
Log.i(TAG, "video track $index: doviProfile=$doviProfile doviLevel=$doviLevel codecs=$doviCodecs baseMime=$mime")
}
val width = numbers[FfmpegDemuxerJni.INFO_WIDTH].toInt()
val height = numbers[FfmpegDemuxerJni.INFO_HEIGHT].toInt()
@@ -419,12 +458,6 @@ internal class FfmpegExtractor private constructor(
trackOutputs[index] = trackOutput
}
primaryStreamIndex = if (primaryVideo >= 0) primaryVideo else primaryAudio
primaryStreamIsAudio = primaryVideo < 0 && primaryAudio >= 0
synchronized(seekIndexLock) {
seekIndexTimes.clear()
seekIndexPositions.clear()
}
output.endTracks()
output.seekMap(SeekMapImpl())
}
@@ -452,8 +485,7 @@ internal class FfmpegExtractor private constructor(
}
}
private fun readPacket(input: ExtractorInput, seekPosition: PositionHolder): Int {
var reconciles = 0
private fun readPacket(): Int {
while (true) {
val code = FfmpegDemuxerJni.nativeReadPacket(packetBytes, packetOut)
when (code) {
@@ -505,24 +537,11 @@ internal class FfmpegExtractor private constructor(
/* cryptoData= */
null
)
recordSeekPoint(streamIndex, ptsUs, packetOut[FfmpegDemuxerJni.OUT_POSITION], isKeyframe)
deliveredAnyPacket = true
bitrateMeters.getOrNull(streamIndex)?.onPacket(ptsUs, size)
return Extractor.RESULT_CONTINUE
}
FfmpegDemuxerJni.CODE_EOF -> return Extractor.RESULT_END_OF_INPUT
FfmpegDemuxerJni.CODE_NEED_SEEK -> {
val target = FfmpegDemuxerJni.nativeConsumePendingSeek()
if (target == Long.MIN_VALUE || target < 0) {
// Sticky AVIO error replayed without a fresh deferral: resync in
// place (bounded by reconciles) instead of killing the stream.
if (++reconciles > MAX_RECONCILES || !reSync(input)) {
throw malformed("demuxer produced an invalid seek target: $target")
}
continue
}
if (++reconciles > MAX_RECONCILES) throw malformed("too many demuxer repositions")
if (!reconcile(input, seekPosition, target)) return Extractor.RESULT_SEEK
}
FfmpegDemuxerJni.CODE_GROW -> {
val required = packetOut[FfmpegDemuxerJni.OUT_SIZE].toInt()
packetBytes = ByteArray(required + 64 * 1024)
@@ -534,81 +553,22 @@ internal class FfmpegExtractor private constructor(
}
}
/** Re-establishes the AVIO position at the loader's current input position. */
private fun reSync(input: ExtractorInput): Boolean {
val position = input.position
return position >= 0 && FfmpegDemuxerJni.nativeResumeAfterSeek(position) == 0
}
/** Returns true when the input is already at [target] and native resumed. */
private fun reconcile(input: ExtractorInput, seekPosition: PositionHolder, target: Long): Boolean {
if (target == input.position) {
val code = FfmpegDemuxerJni.nativeResumeAfterSeek(target)
if (code != 0) throw malformed("demuxer resume failed: $code")
return true
}
seekPosition.position = target
return false
}
private fun recordSeekPoint(streamIndex: Int, timeUs: Long, position: Long, keyframe: Boolean) {
if (streamIndex != primaryStreamIndex || position <= 0) return
if (!primaryStreamIsAudio && !keyframe) return
synchronized(seekIndexLock) {
val lastIndex = seekIndexTimes.size - 1
if (lastIndex >= 0) {
if (timeUs <= seekIndexTimes[lastIndex]) return
if (primaryStreamIsAudio && timeUs - seekIndexTimes[lastIndex] < AUDIO_INDEX_INTERVAL_US) {
return
}
}
seekIndexTimes.add(timeUs)
seekIndexPositions.add(position)
}
}
private fun malformed(message: String): ParserException = ParserException.createForMalformedContainer(message, null)
private inner class SeekMapImpl : SeekMap {
// Seeks are executed by the demuxer (avformat_seek_file), so seekability
// does not depend on the sample-derived index below — that index only
// improves the loader's initial byte guess. The timeline is published
// from this value once, at prepare time, when the index is still empty.
override fun isSeekable(): Boolean = this@FfmpegExtractor.durationUs != C.TIME_UNSET
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
synchronized(seekIndexLock) {
if (seekIndexTimes.isEmpty()) return SeekMap.SeekPoints(SeekPoint(0, 0))
val index = seekIndexTimes.binarySearchFloor(timeUs)
if (index < 0) return SeekMap.SeekPoints(SeekPoint(seekIndexTimes[0], seekIndexPositions[0]))
val preceding = SeekPoint(seekIndexTimes[index], seekIndexPositions[index])
if (index + 1 >= seekIndexTimes.size || seekIndexTimes[index] == timeUs) {
return SeekMap.SeekPoints(preceding)
}
val following = SeekPoint(seekIndexTimes[index + 1], seekIndexPositions[index + 1])
return SeekMap.SeekPoints(preceding, following)
}
}
/**
* The demuxer owns seek resolution: it reads its own index and lands on
* the right keyframe by itself, so there is no second index here to keep
* consistent. The byte position exists only to satisfy the interface —
* [alignLoader] moves the loader to wherever libavformat actually ended
* up, on the read that follows the seek.
*/
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints = SeekMap.SeekPoints(SeekPoint(timeUs, 0))
// Qualified on purpose: bare `durationUs` binds to the inherited Java
// getter as a synthetic property (this.getDurationUs()) and recurses.
override fun getDurationUs(): Long = this@FfmpegExtractor.durationUs
}
}
/** Floor binary search over an ascending list; returns the greatest index with value <= target. */
private fun List<Long>.binarySearchFloor(value: Long): Int {
var low = 0
var high = size - 1
var result = -1
while (low <= high) {
val mid = (low + high) ushr 1
if (this[mid] <= value) {
result = mid
low = mid + 1
} else {
high = mid - 1
}
}
return result
}
@@ -0,0 +1,167 @@
package com.edde746.plezy.exoplayer
import android.net.Uri
import androidx.annotation.OptIn
import androidx.media3.common.C
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.TransferListener
import java.io.IOException
/**
* Random-access byte source for the libavformat demuxer.
*
* libavformat demuxers own their own IO: they jump to the end of the file for an
* index (matroska Cues, MP4 moov, AVI idx1), back to the header, and binary
* search (MPEG-PS) whenever they please. media3's [
* androidx.media3.extractor.ExtractorInput] is forward-only — an extractor may
* only ask the loader to re-open elsewhere and be invoked again — so serving
* libavformat from the loader alone means every backward jump has to unwind the
* in-flight libavformat call and replay it, which is what the demuxer shim used
* to do (and what made a matroska Cues read unrecoverable, #2096).
*
* This class removes the mismatch instead of working around it: reads outside
* the loader's window open a second [DataSource] from the same factory media3
* uses, positioned exactly where libavformat asked. Cronet, download caches,
* SAF and the item's own request headers therefore still apply, because the
* [DataSpec] is cloned from the one media3 opened for this item.
*
* Sequential sample delivery deliberately does not come through here: it stays
* on the loader's connection so media3 keeps its byte accounting, back-pressure
* and load-error policy (see [FfmpegExtractor]). This source is opened for
* header/index bursts and closed again as soon as the loader is back in step.
*/
@OptIn(UnstableApi::class)
internal class FfmpegRandomAccessSource(
private val factory: DataSource.Factory,
private val specProvider: () -> DataSpec?
) {
private var source: DataSource? = null
/** Absolute position the open handle returns next; [C.INDEX_UNSET] when closed. */
private var handlePosition = C.INDEX_UNSET.toLong()
private var resolvedLength = C.LENGTH_UNSET.toLong()
private var opens = 0
/** Handles opened so far; the tests assert an index seek does not walk the file. */
val openCount: Int
get() = synchronized(this) { opens }
val isOpen: Boolean
get() = synchronized(this) { source != null }
/**
* Reads up to [length] bytes at absolute [position]. Returns the number of
* bytes read, or 0 at end of input. Reopens the underlying source whenever
* the requested position is not where the current handle stands, which is the
* only way to move backwards on a byte stream.
*/
fun readAt(position: Long, buffer: ByteArray, length: Int): Int = synchronized(this) {
if (length <= 0) return 0
val handle = handleAt(position)
val read = handle.read(buffer, 0, length)
if (read == C.RESULT_END_OF_INPUT) return 0
handlePosition = position + read
read
}
/**
* Total resource length once some open has resolved it, else
* [C.LENGTH_UNSET]. Never performs IO of its own: the extractor prefers the
* length media3 already resolved for the loader.
*/
fun length(): Long = synchronized(this) { resolvedLength }
fun close() = synchronized(this) {
closeHandle()
handlePosition = C.INDEX_UNSET.toLong()
}
private fun handleAt(position: Long): DataSource {
val existing = source
if (existing != null && handlePosition == position) return existing
closeHandle()
val spec = specProvider() ?: throw IOException("ffmpeg demuxer has no data spec for random access")
// Clone rather than subrange: the recorded spec carries the loader's own
// position, and subrange() is relative to it.
val positioned = spec.buildUpon()
.setPosition(position)
.setLength(C.LENGTH_UNSET.toLong())
.build()
val created = factory.createDataSource()
val remaining = try {
created.open(positioned)
} catch (e: Throwable) {
closeQuietly(created)
throw e
}
source = created
handlePosition = position
opens++
if (remaining != C.LENGTH_UNSET.toLong()) resolvedLength = position + remaining
return created
}
private fun closeHandle() {
source?.let { closeQuietly(it) }
source = null
}
private fun closeQuietly(dataSource: DataSource) {
try {
dataSource.close()
} catch (_: IOException) {
// Closing a handle we are abandoning cannot fail the read that replaces it.
}
}
}
/**
* [DataSource.Factory] that remembers the [DataSpec] media3 opened for each
* item, so [FfmpegRandomAccessSource] can clone it — same URI, cache key, flags
* and request headers — instead of re-deriving one and silently losing, say, a
* download's cache key.
*
* Keyed by URI because ExoPlayer prepares the next item's period while the
* current one is still loading; the demuxer must never read the next item's
* bytes.
*/
@OptIn(UnstableApi::class)
internal class RecordingDataSourceFactory(private val delegate: DataSource.Factory) : DataSource.Factory {
private val specs = object : LinkedHashMap<Uri, DataSpec>(8, 0.75f, false) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Uri, DataSpec>): Boolean = size > MAX_TRACKED_ITEMS
}
fun specFor(uri: Uri): DataSpec? = synchronized(specs) { specs[uri] }
override fun createDataSource(): DataSource = RecordingDataSource(delegate.createDataSource())
private fun record(dataSpec: DataSpec) {
synchronized(specs) { specs[dataSpec.uri] = dataSpec }
}
private inner class RecordingDataSource(private val inner: DataSource) : DataSource {
override fun open(dataSpec: DataSpec): Long {
record(dataSpec)
return inner.open(dataSpec)
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int = inner.read(buffer, offset, length)
override fun addTransferListener(transferListener: TransferListener) = inner.addTransferListener(transferListener)
override fun getUri(): Uri? = inner.uri
override fun getResponseHeaders(): Map<String, List<String>> = inner.responseHeaders
override fun close() = inner.close()
}
private companion object {
const val MAX_TRACKED_ITEMS = 4
}
}
@@ -0,0 +1,41 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DoviCodecsTest {
@Test
fun hevcProfilesUseDvhePrefix() {
// Profile 8 level 6 is the stream from #2096: the record's dv_profile and
// dv_level bytes must surface verbatim, matching media3's
// DolbyVisionConfig output for the same file (dvhe.08.06).
assertEquals("dvhe.08.06", DoviCodecs.rfc6381(8, 6))
assertEquals("dvhe.04.09", DoviCodecs.rfc6381(4, 9))
assertEquals("dvhe.05.06", DoviCodecs.rfc6381(5, 6))
// Profile 7 keys DoviConvertingTrackOutput's P7 conversion.
assertEquals("dvhe.07.06", DoviCodecs.rfc6381(7, 6))
}
@Test
fun avcAndAv1ProfilesUseTheirOwnPrefixes() {
assertEquals("dvav.09.05", DoviCodecs.rfc6381(9, 5))
assertEquals("dav1.10.04", DoviCodecs.rfc6381(10, 4))
}
@Test
fun twoDigitLevelsAreNotZeroPadded() {
assertEquals("dvhe.08.10", DoviCodecs.rfc6381(8, 10))
}
@Test
fun unrecognizedProfilesReturnNullSoTheBaseCodecFormatSurvives() {
// Media3's DolbyVisionConfig table: anything it rejects must keep the
// track's plain HEVC/AVC format instead of publishing an unplayable
// video/dolby-vision variant.
assertNull(DoviCodecs.rfc6381(0, 6))
assertNull(DoviCodecs.rfc6381(2, 6))
assertNull(DoviCodecs.rfc6381(6, 6))
assertNull(DoviCodecs.rfc6381(20, 6))
}
}
@@ -0,0 +1,137 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.MimeTypes
import androidx.media3.common.ParserException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
/**
* Spec for the per-codec initializationData shapes the ffmpeg demuxer must
* publish so MediaCodec csd-0/1/2 and FfmpegAudioDecoder's extradata
* reconstruction both see what media3's own extractors emit. Regression
* coverage for #2088: Opus with a bare OpusHead csd made Android's decoders
* eat the first two real packets as configuration and discard all output.
*/
class FfmpegAudioCsdTest {
private fun opusHead(preSkip: Int): ByteArray {
val header = ByteArray(19)
"OpusHead".toByteArray(Charsets.US_ASCII).copyInto(header)
header[8] = 1 // version
header[9] = 2 // channel count
header[10] = (preSkip and 0xFF).toByte()
header[11] = (preSkip ushr 8).toByte()
return header
}
private fun nativeOrderLong(bytes: ByteArray): Long = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder()).long
@Test
fun opusBuildsThreeCsdBuffers() {
val header = opusHead(preSkip = 312)
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_OPUS, header)
assertEquals(3, csd.size)
assertArrayEquals(header, csd[0])
// Pre-skip converted to nanoseconds at the Opus 48 kHz clock.
assertEquals(312L * 1_000_000_000L / 48_000L, nativeOrderLong(csd[1]))
// media3's default seek pre-roll: 3840 samples = 80 ms.
assertEquals(80_000_000L, nativeOrderLong(csd[2]))
}
@Test
fun opusRejectsTruncatedHeader() {
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_OPUS, ByteArray(11))
}
}
private fun xiphLace(length: Int): ByteArray {
val bytes = ArrayList<Byte>()
var remaining = length
while (remaining >= 0xFF) {
bytes.add(0xFF.toByte())
remaining -= 0xFF
}
bytes.add(remaining.toByte())
return bytes.toByteArray()
}
private fun vorbisHeader(type: Int, payloadLength: Int): ByteArray = byteArrayOf(type.toByte()) + "vorbis".toByteArray(Charsets.US_ASCII) + ByteArray(payloadLength)
@Test
fun vorbisSplitsLacedHeadersIntoIdentificationAndSetup() {
val id = vorbisHeader(0x01, payloadLength = 23) // 30 bytes, the real identification header size
val comment = vorbisHeader(0x03, payloadLength = 300) // > 255 exercises the 0xFF lacing
val setup = vorbisHeader(0x05, payloadLength = 40)
val extradata = byteArrayOf(0x02) + xiphLace(id.size) + xiphLace(comment.size) + id + comment + setup
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_VORBIS, extradata)
assertEquals(2, csd.size)
assertArrayEquals(id, csd[0])
assertArrayEquals(setup, csd[1])
}
@Test
fun vorbisRejectsNonLacedExtradata() {
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_VORBIS, byteArrayOf(0x01, 0x02, 0x03))
}
}
@Test
fun vorbisRejectsTruncatedExtradata() {
val id = vorbisHeader(0x01, payloadLength = 23)
val truncated = byteArrayOf(0x02) + xiphLace(id.size) + xiphLace(64) + id // headers end early
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_VORBIS, truncated)
}
}
@Test
fun flacWrapsBareStreamInfoInMarkedStream() {
val streamInfo = ByteArray(34) { it.toByte() }
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, streamInfo)
assertEquals(1, csd.size)
assertArrayEquals(
"fLaC".toByteArray(Charsets.US_ASCII) + byteArrayOf(0x80.toByte(), 0x00, 0x00, 34) + streamInfo,
csd[0]
)
}
@Test
fun flacPrependsMarkerToBlockHeadedStreamInfo() {
val block = byteArrayOf(0x00, 0x00, 0x00, 34) + ByteArray(34) { it.toByte() }
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, block)
assertEquals(1, csd.size)
assertArrayEquals("fLaC".toByteArray(Charsets.US_ASCII) + block, csd[0])
}
@Test
fun flacKeepsMarkedStreamVerbatim() {
val marked = "fLaC".toByteArray(Charsets.US_ASCII) + byteArrayOf(0x80.toByte(), 0x00, 0x00, 34) + ByteArray(34)
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, marked)
assertEquals(1, csd.size)
assertSame(marked, csd[0])
}
@Test
fun flacRejectsUnrecognizedExtradata() {
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, ByteArray(10))
}
}
@Test
fun otherCodecsPassExtradataThroughAsSingleEntry() {
val asc = byteArrayOf(0x12, 0x10) // AAC-LC 44.1 kHz stereo AudioSpecificConfig
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_AAC, asc)
assertEquals(1, csd.size)
assertSame(asc, csd[0])
}
}
@@ -0,0 +1,222 @@
package com.edde746.plezy.exoplayer
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.TransferListener
import java.io.IOException
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
/**
* The demuxer's correctness now rests on this source answering any absolute
* position, so these pin the contract libavformat depends on: a read lands on
* the requested byte, a backward jump reopens rather than returning the wrong
* bytes, and sequential reads do not reopen (which would turn steady-state
* playback into one request per 64 KB).
*/
@RunWith(RobolectricTestRunner::class)
class FfmpegRandomAccessSourceTest {
private val content = ByteArray(4096) { (it % 251).toByte() }
private val uri: Uri = Uri.parse("https://example.test/movie.mkv")
private class FakeDataSource(private val content: ByteArray) : DataSource {
var openedAt: Long = -1
var closed = false
private var position = 0
override fun open(dataSpec: DataSpec): Long {
openedAt = dataSpec.position
position = dataSpec.position.toInt()
return (content.size - position).toLong()
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (position >= content.size) return C.RESULT_END_OF_INPUT
val count = minOf(length, content.size - position)
content.copyInto(buffer, offset, position, position + count)
position += count
return count
}
override fun addTransferListener(transferListener: TransferListener) = Unit
override fun getUri(): Uri? = null
override fun getResponseHeaders(): Map<String, List<String>> = emptyMap()
override fun close() {
closed = true
}
}
private inner class FakeFactory : DataSource.Factory {
val created = mutableListOf<FakeDataSource>()
override fun createDataSource(): DataSource = FakeDataSource(content).also { created.add(it) }
}
private fun sourceFor(factory: DataSource.Factory, spec: DataSpec? = DataSpec(uri)) = FfmpegRandomAccessSource(factory) { spec }
@Test
fun readsLandOnTheRequestedAbsolutePosition() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(16)
assertEquals(16, source.readAt(1000, buffer, 16))
assertArrayEquals(content.copyOfRange(1000, 1016), buffer)
assertEquals(1000L, factory.created.single().openedAt)
}
@Test
fun sequentialReadsReuseOneHandle() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(64)
source.readAt(0, buffer, 64)
source.readAt(64, buffer, 64)
source.readAt(128, buffer, 64)
assertEquals(1, source.openCount)
assertArrayEquals(content.copyOfRange(128, 192), buffer)
}
@Test
fun backwardJumpReopensAndReturnsTheRequestedBytes() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(32)
source.readAt(2048, buffer, 32)
// The jump libavformat makes for an index at the end of the file, then back.
assertEquals(32, source.readAt(16, buffer, 32))
assertArrayEquals(content.copyOfRange(16, 48), buffer)
assertEquals(2, source.openCount)
assertTrue("abandoned handle must be closed", factory.created.first().closed)
}
@Test
fun endOfInputReportsZeroWithoutAdvancing() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(8)
assertEquals(0, source.readAt(content.size.toLong(), buffer, 8))
}
@Test
fun lengthResolvesFromAnOpenAndStaysKnown() {
val factory = FakeFactory()
val source = sourceFor(factory)
assertEquals(C.LENGTH_UNSET.toLong(), source.length())
source.readAt(512, ByteArray(8), 8)
assertEquals(content.size.toLong(), source.length())
}
@Test
fun clonedSpecKeepsCacheKeyAndFlagsButTakesOurPosition() {
val recorded = DataSpec.Builder()
.setUri(uri)
.setPosition(9999)
.setLength(1234)
.setKey("download-cache-key")
.setFlags(DataSpec.FLAG_ALLOW_CACHE_FRAGMENTATION)
.setHttpRequestHeaders(mapOf("X-Test" to "1"))
.build()
var openedSpec: DataSpec? = null
val factory = DataSource.Factory {
object : DataSource {
override fun open(dataSpec: DataSpec): Long {
openedSpec = dataSpec
return C.LENGTH_UNSET.toLong()
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int = C.RESULT_END_OF_INPUT
override fun addTransferListener(transferListener: TransferListener) = Unit
override fun getUri(): Uri? = null
override fun getResponseHeaders(): Map<String, List<String>> = emptyMap()
override fun close() = Unit
}
}
sourceFor(factory, recorded).readAt(4242, ByteArray(4), 4)
val spec = requireNotNull(openedSpec)
assertEquals(4242L, spec.position)
assertEquals(C.LENGTH_UNSET.toLong(), spec.length)
assertEquals("download-cache-key", spec.key)
assertEquals(DataSpec.FLAG_ALLOW_CACHE_FRAGMENTATION, spec.flags)
assertEquals("1", spec.httpRequestHeaders["X-Test"])
assertEquals(uri, spec.uri)
}
@Test
fun readWithoutARecordedSpecFails() {
val source = sourceFor(FakeFactory(), spec = null)
assertThrows(IOException::class.java) { source.readAt(0, ByteArray(4), 4) }
}
@Test
fun closeReleasesTheHandle() {
val factory = FakeFactory()
val source = sourceFor(factory)
source.readAt(0, ByteArray(4), 4)
assertTrue(source.isOpen)
source.close()
assertFalse(source.isOpen)
assertTrue(factory.created.single().closed)
}
@Test
fun recordingFactoryReportsTheSpecMedia3OpenedPerUri() {
val delegate = FakeFactory()
val recorder = RecordingDataSourceFactory(delegate)
val other = Uri.parse("https://example.test/next-episode.mkv")
assertNull(recorder.specFor(uri))
recorder.createDataSource().open(DataSpec.Builder().setUri(uri).setPosition(64).setKey("a").build())
recorder.createDataSource().open(DataSpec.Builder().setUri(other).setPosition(128).build())
// Preloading the next item must not redirect the current demuxer's reads.
assertEquals(64L, recorder.specFor(uri)?.position)
assertEquals("a", recorder.specFor(uri)?.key)
assertEquals(128L, recorder.specFor(other)?.position)
}
@Test
fun recordingFactoryDelegatesReads() {
val delegate = FakeFactory()
val recorder = RecordingDataSourceFactory(delegate)
val buffer = ByteArray(16)
val dataSource = recorder.createDataSource()
dataSource.open(DataSpec.Builder().setUri(uri).setPosition(32).build())
assertEquals(16, dataSource.read(buffer, 0, 16))
assertArrayEquals(content.copyOfRange(32, 48), buffer)
assertSame(delegate.created.single(), delegate.created.first())
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/universal_gamepad/ios"
SPEC CHECKSUMS:
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
Flutter: 71a624a5bc0c04062bf19101d501e466baf2fb47
os_media_controls: 048eb9a75974191b2496d85575b6edcefc572d4e
universal_gamepad: 7c0cc0c2e3909dfb803d325387e42963b3ed842c
+3 -3
View File
@@ -38,7 +38,7 @@ class MediaServerAuthException extends MediaServerException {
/// Auth polling reached a terminal server-side expiry/rejection state before
/// the user completed the external sign-in flow.
class MediaServerPinExpiredException extends MediaServerAuthException {
const MediaServerPinExpiredException({String? display}) : super('PIN expired before sign-in', display: display);
const MediaServerPinExpiredException({super.display}) : super('PIN expired before sign-in');
}
/// HTTP transport / non-2xx errors. Carries the status code (when known),
@@ -57,11 +57,11 @@ class MediaServerHttpException extends MediaServerException {
MediaServerHttpException({
required this.type,
String? message,
String? display,
super.display,
this.statusCode,
this.responseData,
this.requestUri,
}) : super(message ?? '', display: display);
}) : super(message ?? '');
/// Map a caught exception to a [MediaServerHttpException].
factory MediaServerHttpException.from(Object error, {Uri? uri}) {
+20
View File
@@ -33,6 +33,26 @@ class DirectionalShortcutFocusNode extends FocusNode {
node is DirectionalShortcutFocusNode && node.consumesDirectionalKeys(key);
}
/// A [FocusNode] for a locked-focus row: the node spans the whole row while
/// its owner steps an internal selection index between the row's items.
///
/// Swipe-step pricing follows the focused *item's* geometry (see
/// `AppleTvRemoteTouchService`), and for a locked-focus row the node's own
/// rect is the row — screen-wide — which would price a swipe step at the
/// travel cap and make the row feel dead. The owner instead vends the
/// selected item's global rect here; a null return (item not built yet,
/// unknown geometry) falls back to the fixed step distance.
///
/// Like [DirectionalShortcutFocusNode], the fact rides on the node because it
/// depends on what has focus, not on where a widget sits.
class LockedFocusRowNode extends FocusNode {
LockedFocusRowNode({required this.focusedItemRect, super.debugLabel, super.skipTraversal});
/// Global rect of the row's currently selected item, evaluated per swipe
/// frame so selection moves need no syncing.
final Rect? Function() focusedItemRect;
}
/// Whether [event] is evidence that the viewer wants to navigate by focus.
///
/// This is the single answer to two questions that must never disagree:
+13 -2
View File
@@ -102,7 +102,10 @@ bool shouldHandleDesktopRootEscape({
/// mid-stream must resume the stream, not stack the root-navigator picker
/// over the live player route, whose focus self-heal fights the picker for
/// the remote (#2034) — the playback session already belongs to the profile
/// that started it.
/// that started it. Likewise never during a live companion-remote session:
/// a phone driving another device backgrounds and sleeps constantly, and
/// the picker + PIN would bury a session that already belongs to the
/// profile that started it (#2087).
@visibleForTesting
bool shouldShowProfileSelectionOnResume({
required bool resumedFromBackground,
@@ -110,12 +113,14 @@ bool shouldShowProfileSelectionOnResume({
required bool alreadyShowingProfileSelection,
required bool isMobilePlatform,
required bool hasActiveVideoPlayback,
required bool hasActiveCompanionRemoteSession,
}) {
return resumedFromBackground &&
!isOffline &&
!alreadyShowingProfileSelection &&
isMobilePlatform &&
!hasActiveVideoPlayback;
!hasActiveVideoPlayback &&
!hasActiveCompanionRemoteSession;
}
/// Latches whether the app has genuinely left the foreground since the last
@@ -1140,6 +1145,12 @@ class _MainScreenState extends State<MainScreen>
alreadyShowingProfileSelection: _isShowingProfileSelection,
isMobilePlatform: Platform.isAndroid || Platform.isIOS,
hasActiveVideoPlayback: VideoPlayerScreenState.activeGlobalKey != null,
// Short-circuit on resumedFromBackground: the provider is lazy and
// otherwise unused on phones, so an unconditional read would create it
// on the first lifecycle event for users who never open the remote.
// isInSession, not isConnected: on resume the held reconnect cycle
// means the session is typically still `reconnecting` (#2035).
hasActiveCompanionRemoteSession: resumedFromBackground && context.read<CompanionRemoteProvider>().isInSession,
)) {
_showProfileSelectionOnResume();
}
+125 -48
View File
@@ -1,7 +1,9 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import '../focus/focus_navigation_intent.dart';
import '../focus/input_mode_tracker.dart';
import '../utils/app_logger.dart';
import '../utils/key_event_simulator.dart' as key_sim;
@@ -17,31 +19,59 @@ class AppleTvRemotePlayPauseAction {
}
const double _axisSwitchDominanceRatio = 1.5;
// Retuned against the native tvOS focus engine, measured on-device on an
// Apple TV 4K (issue #2006), poster grid 230x345:
// - one focus step per ~400pt of indirect-touch travel (UITouch points — the
// same accelerated space the engine reports on this channel), measured
// identical for the 230pt and 345pt axes: the step distance does NOT
// follow the focused item's extent;
// - steps repeat every ~60ms (native median) during a committed drag;
// - a fast lift glides on: one extra step past ~2000pt/s, two past ~8000pt/s,
// landing within ~130ms of the lift.
// Small extents (chips, list rows) are unmeasured; the fixed step distance
// extrapolates the measured axis-independence to them.
// Tuned against the native tvOS focus engine. Two instrumentation passes on
// an Apple TV 4K (issue #2006):
// 1. committed-move telemetry through the experimental UIFocusItem bridge
// (branch feat/tvos-native-focus-bridge);
// 2. a dedicated native probe app logging every touch sample, pan velocity,
// engine hint, and focus step across 101 swipe sessions on 160/230/300pt
// tiles (FocusProbe, 2026-08).
// Findings these constants encode:
// - one focus step prices at the focused item's extent along the swipe axis
// plus ~155pt of indirect-touch travel (UITouch points — the accelerated
// space this channel reports): measured 314pt on a 160pt tile, 391pt on a
// 230pt poster, 410pt on a 300pt rail card. The earlier "fixed 400pt"
// reading came from a single poster grid whose two extents both happened
// to price near 400.
// - steps repeat at 40-120ms (mode ~80ms) during a committed drag; the 60ms
// cooldown only floors that cadence, travel does the pricing.
// - a lift never coasts more than ONE step: sessions with lift velocities
// up to ~11400pt/s produced 95 zero-coast lifts and 6 single-step coasts
// landing 4-101ms after the lift. Long flat-cadence step bursts in
// earlier logs were dpad hold-repeat key events, not swipe inertia. Do
// not reintroduce a multi-step momentum law.
const Duration _swipeRepeatInterval = Duration(milliseconds: 60);
// Fallback step travel when no usable focus geometry exists (a bare focus
// scope, the player's screen-sized catch-all surfaces, a detached node).
const double _swipeStepDistance = 400;
// Travel added to the focused item's extent to price one step.
const double _swipeStepExtraTravel = 155;
// Guards, not tuning: measured extents span 90-345pt; anything outside
// prices within sane bounds instead of extrapolating the affine law.
const double _minSwipeStepTravel = 200;
const double _maxSwipeStepTravel = 700;
const Duration _glideStepInterval = Duration(milliseconds: 70);
const double _glideVelocity = 2000;
const double _glideDoubleStepVelocity = 8000;
const Duration _liftVelocityWindow = Duration(milliseconds: 100);
// A glide only ever extends a sustained drag: the gesture must already have
// emitted this many consecutive steps in the lift direction. The velocity
// estimator runs in the same accelerated space as the step distance, and an
// ordinary discrete flick covers one step's travel at well past
// [_glideVelocity] there — ungated, every deliberate single swipe glided
// into a second step (issue #2006 follow-up reports).
const int _glideMinConsecutiveSteps = 2;
/// Bridges tvOS touch-surface events (Siri Remote and Apple's iOS Remote app)
/// into the focus-tree key events Plezy already handles for D-pad navigation.
///
/// One focus step costs a fixed [swipeThreshold] of touch travel regardless
/// of the focused control's size, steps repeat on a short cadence during a
/// sustained drag, and a fast lift "glides" one or two further steps — all
/// three tuned to on-device measurements of the native focus engine.
/// Like the native focus engine, one focus step prices by on-screen geometry:
/// the focused control's extent along the swipe axis plus a fixed travel
/// margin, falling back to [swipeThreshold] when no usable geometry exists.
/// Steps repeat on a short cadence during a sustained drag, and a fast lift
/// "glides" at most one further step — never more; the native engine has no
/// multi-step swipe inertia. A glide only extends a drag that already covered
/// [_glideMinConsecutiveSteps] steps in that direction, so a discrete flick
/// moves exactly one item.
class AppleTvRemoteTouchService {
static const String _channelName = 'flutter/gamepadtouchevent';
@@ -56,9 +86,14 @@ class AppleTvRemoteTouchService {
final StreamController<AppleTvRemotePlayPauseAction> _playPauseController =
StreamController<AppleTvRemotePlayPauseAction>.broadcast();
/// Touch travel that prices one focus step.
/// Fallback touch travel that prices one focus step when no usable focus
/// geometry exists.
final double swipeThreshold;
/// Global rect of the control that prices a focus step, or null when no
/// usable geometry exists. Injected so tests can supply fake geometry.
final Rect? Function() _focusedItemRect;
bool _listening = false;
bool _nativeKeyHandlerRegistered = false;
bool _touchActive = false;
@@ -69,6 +104,7 @@ class AppleTvRemoteTouchService {
_SwipeAxis? _lastSwipeAxis;
DateTime? _lastSwipeAt;
LogicalKeyboardKey? _lastSwipeKey;
int _consecutiveStepCount = 0;
final List<({DateTime t, double x, double y})> _moveSamples = [];
Timer? _glideTimer;
@@ -77,9 +113,11 @@ class AppleTvRemoteTouchService {
VoidCallback? scheduleFrame,
DateTime Function()? now,
this.swipeThreshold = _swipeStepDistance,
Rect? Function()? focusedItemRect,
}) : _simulateKeyPress = simulateKeyPress ?? key_sim.simulateKeyPress,
_scheduleFrame = scheduleFrame ?? key_sim.scheduleFrameIfIdle,
_now = now ?? DateTime.now,
_focusedItemRect = focusedItemRect ?? _defaultFocusedItemRect,
_duplicateInputGuard = GamepadDuplicateInputGuard(now: now);
Stream<AppleTvRemotePlayPauseAction> get playPauseActions => _playPauseController.stream;
@@ -177,6 +215,7 @@ class AppleTvRemoteTouchService {
_lastSwipeAxis = null;
_lastSwipeAt = null;
_lastSwipeKey = null;
_consecutiveStepCount = 0;
_moveSamples
..clear()
..add((t: _now(), x: x, y: y));
@@ -211,7 +250,8 @@ class AppleTvRemoteTouchService {
return;
}
final axis = _resolveSwipeAxis(x: x, y: y, deltaX: deltaX, deltaY: deltaY);
final thresholds = _stepThresholds();
final axis = _resolveSwipeAxis(x: x, y: y, deltaX: deltaX, deltaY: deltaY, thresholds: thresholds);
if (axis == null) return;
final logicalKey = axis == _SwipeAxis.horizontal
@@ -223,33 +263,39 @@ class AppleTvRemoteTouchService {
source: 'swipe',
detail:
'dx=${_formatDouble(deltaX)} dy=${_formatDouble(deltaY)} '
'th=${_formatDouble(swipeThreshold)}',
'thX=${_formatDouble(thresholds.horizontal)} thY=${_formatDouble(thresholds.vertical)}',
);
_anchorX = x;
_anchorY = y;
_lastSwipeAxis = axis;
_lastSwipeAt = now;
_consecutiveStepCount = logicalKey == _lastSwipeKey ? _consecutiveStepCount + 1 : 1;
_lastSwipeKey = logicalKey;
}
/// Resolves which axis, if any, covered a full step distance, with
/// hysteresis so incidental drift does not zig-zag an established swipe.
/// Resolves which axis, if any, covered a full step, with hysteresis so
/// incidental drift does not zig-zag an established swipe.
///
/// Distances are normalized by the per-axis thresholds so that, like the
/// native focus engine, a wide-flat control steps vertically once the
/// finger covers its height even while the raw horizontal delta is larger.
_SwipeAxis? _resolveSwipeAxis({
required double x,
required double y,
required double deltaX,
required double deltaY,
required ({double horizontal, double vertical}) thresholds,
}) {
final progressX = deltaX.abs() / swipeThreshold;
final progressY = deltaY.abs() / swipeThreshold;
final progressX = deltaX.abs() / thresholds.horizontal;
final progressY = deltaY.abs() / thresholds.vertical;
if (progressX < 1 && progressY < 1) return null;
final candidate = progressX >= progressY ? _SwipeAxis.horizontal : _SwipeAxis.vertical;
final lastAxis = _lastSwipeAxis;
if (lastAxis == null || candidate == lastAxis) return candidate;
final totalProgressX = (_startX - x).abs() / swipeThreshold;
final totalProgressY = (_startY - y).abs() / swipeThreshold;
final totalProgressX = (_startX - x).abs() / thresholds.horizontal;
final totalProgressY = (_startY - y).abs() / thresholds.vertical;
final candidateTotal = _axisValue(candidate, totalProgressX, totalProgressY);
final lastAxisTotal = _axisValue(lastAxis, totalProgressX, totalProgressY);
final candidateSegment = _axisValue(candidate, progressX, progressY);
@@ -266,6 +312,39 @@ class AppleTvRemoteTouchService {
return axis == _SwipeAxis.horizontal ? horizontal : vertical;
}
({double horizontal, double vertical}) _stepThresholds() {
final rect = _focusedItemRect();
if (rect == null) return (horizontal: swipeThreshold, vertical: swipeThreshold);
return (horizontal: _thresholdForExtent(rect.width), vertical: _thresholdForExtent(rect.height));
}
double _thresholdForExtent(double extent) {
if (!extent.isFinite || extent <= 0) return swipeThreshold;
return (extent + _swipeStepExtraTravel).clamp(_minSwipeStepTravel, _maxSwipeStepTravel).toDouble();
}
/// Reads the primary focus geometry, rejecting nodes whose rect cannot
/// meaningfully price a step: bare scopes (nothing real is focused yet) and
/// the player's catch-all [DirectionalShortcutFocusNode] surfaces are
/// screen-sized, and a detached or unlaid-out node has no rect at all. A
/// locked-focus row's node is also row-sized; it vends the selected item's
/// rect instead ([LockedFocusRowNode]).
static Rect? _defaultFocusedItemRect() {
final node = FocusManager.instance.primaryFocus;
if (node == null || node is FocusScopeNode || node is DirectionalShortcutFocusNode) return null;
if (node is LockedFocusRowNode) return _validRectOrNull(node.focusedItemRect());
final context = node.context;
if (context == null) return null;
final renderObject = context.findRenderObject();
if (renderObject is! RenderBox || !renderObject.attached || !renderObject.hasSize) return null;
return _validRectOrNull(node.rect);
}
static Rect? _validRectOrNull(Rect? rect) {
if (rect == null || !rect.isFinite || rect.isEmpty) return null;
return rect;
}
void _recordMoveSample(DateTime now, double x, double y) {
_moveSamples.add((t: now, x: x, y: y));
final cutoff = now.subtract(_liftVelocityWindow);
@@ -276,45 +355,42 @@ class AppleTvRemoteTouchService {
void _endTouch() {
final glideKey = _lastSwipeKey;
final glideSteps = _liftGlideSteps();
final shouldGlide = _liftShouldGlide();
_resetTouch();
if (glideKey != null && glideSteps > 0) _startGlide(glideKey, glideSteps);
if (glideKey != null && shouldGlide) _startGlide(glideKey);
}
/// Prices the post-lift glide from the finger's velocity over the last
/// [_liftVelocityWindow] of the gesture, measured along the established
/// swipe axis. A gesture that never produced a step has no established
/// direction and never glides; neither does a lift moving against the last
/// step (a reversal pivot).
int _liftGlideSteps() {
/// Decides whether the lift glides one — and only one — further step, from
/// the finger's velocity over the last [_liftVelocityWindow] of the
/// gesture, measured along the established swipe axis. Only a sustained
/// drag glides: the gesture must already have emitted
/// [_glideMinConsecutiveSteps] consecutive steps in the lift direction, so
/// a discrete one-step flick never overshoots its target. A gesture that
/// never produced a step has no established direction and never glides;
/// neither does a lift moving against the last step (a reversal pivot).
bool _liftShouldGlide() {
final key = _lastSwipeKey;
final axis = _lastSwipeAxis;
if (key == null || axis == null || _moveSamples.length < 2) return 0;
if (key == null || axis == null || _moveSamples.length < 2) return false;
if (_consecutiveStepCount < _glideMinConsecutiveSteps) return false;
final first = _moveSamples.first;
final last = _moveSamples.last;
final dt = last.t.difference(first.t).inMicroseconds / Duration.microsecondsPerSecond;
if (dt <= 0) return 0;
if (dt <= 0) return false;
final velocity = axis == _SwipeAxis.horizontal ? (last.x - first.x) / dt : (last.y - first.y) / dt;
final towardKey = axis == _SwipeAxis.horizontal
? (velocity < 0 ? LogicalKeyboardKey.arrowLeft : LogicalKeyboardKey.arrowRight)
: (velocity < 0 ? LogicalKeyboardKey.arrowUp : LogicalKeyboardKey.arrowDown);
if (towardKey != key) return 0;
final speed = velocity.abs();
if (speed < _glideVelocity) return 0;
return speed >= _glideDoubleStepVelocity ? 2 : 1;
if (towardKey != key) return false;
return velocity.abs() >= _glideVelocity;
}
void _startGlide(LogicalKeyboardKey key, int steps) {
void _startGlide(LogicalKeyboardKey key) {
_cancelGlide();
var remaining = steps;
_log('start glide key=${_keyName(key)} steps=$steps');
_glideTimer = Timer.periodic(_glideStepInterval, (timer) {
_log('start glide key=${_keyName(key)}');
_glideTimer = Timer(_glideStepInterval, () {
_glideTimer = null;
_emitKey(key, source: 'glide');
remaining -= 1;
if (remaining <= 0) {
timer.cancel();
if (identical(_glideTimer, timer)) _glideTimer = null;
}
});
}
@@ -341,6 +417,7 @@ class AppleTvRemoteTouchService {
_lastSwipeAxis = null;
_lastSwipeAt = null;
_lastSwipeKey = null;
_consecutiveStepCount = 0;
_moveSamples.clear();
}
@@ -1,4 +1,5 @@
import 'dart:convert';
import '../media/ids.dart';
import '../media/media_backend.dart';
@@ -21,7 +22,7 @@ class CachedPlaybackMetadataService {
int mediaIndex = 0,
}) async {
try {
return switch (backend) {
return await switch (backend) {
MediaBackend.plex => _fetchPlexMediaSourceInfo(ServerId(cacheServerId), itemId, mediaIndex: mediaIndex),
MediaBackend.jellyfin || MediaBackend.emby => _fetchJellyfinMediaSourceInfo(
cacheServerId,
@@ -45,7 +46,7 @@ class CachedPlaybackMetadataService {
bool forceChapterFallback = false,
}) async {
try {
return switch (backend) {
return await switch (backend) {
MediaBackend.plex => _fetchPlexPlaybackExtras(
ServerId(cacheServerId),
itemId,
+13 -5
View File
@@ -5,6 +5,7 @@ import '../models/download_models.dart';
import '../utils/app_logger.dart';
import '../utils/downloaded_version_match.dart';
import 'download_storage_service.dart';
import 'saf_storage_service.dart';
/// A downloaded copy resolved to a playable location, plus the version that is
/// actually on disk — which can differ from the requested one when
@@ -17,7 +18,7 @@ typedef DownloadedVideoSource = ({String path, int mediaIndex, String? mediaSour
/// Returns null when the row cannot back playback: the download is not
/// complete, it holds a different version than requested (unless
/// [allowAnyDownloadedVersion]), it has no stored video path, or the stored
/// file is gone from disk.
/// file is no longer reachable.
///
/// Version matching is strict by default so online flows keep streaming an
/// explicitly requested non-downloaded version (issue #1440). With
@@ -64,11 +65,18 @@ Future<DownloadedVideoSource?> resolveDownloadedVideoSource(
}
final storageService = DownloadStorageService.instance;
// SAF URIs (content://) are already playable and come back untouched; file
// paths may be stored relative, so resolve them and confirm they still exist.
// Reachability, not just presence in the row. A removable SAF volume can be
// unmounted — or its grant revoked — while the row still reads `completed`,
// and a stale content:// URI is indistinguishable from a live one until the
// player fails to open it (issue #2101). File paths may be stored relative,
// so resolve them first; SAF URIs are already playable as written.
final readablePath = await storageService.getReadablePath(storedPath);
if (!storageService.isSafUri(storedPath) && !await File(readablePath).exists()) {
appLogger.w('Offline video file not found: $readablePath (stored as: $storedPath)');
final isReachable = storageService.isSafUri(storedPath)
? await SafStorageService.ops.exists(storedPath, isDir: false)
: await File(readablePath).exists();
if (!isReachable) {
// Returning null is what lets the caller stream from the server instead.
appLogger.w('Offline video file not reachable: $readablePath (stored as: $storedPath)');
return null;
}
+3 -1
View File
@@ -55,7 +55,9 @@ class LocalPlaybackHistory {
static Future<Map<String, int>> snapshot() async {
try {
final settings = await SettingsService.getInstance();
return settings.read(SettingsService.localLastPlayedAt);
// Explicit type argument: the async return context would otherwise
// infer T = FutureOr and trip UNAWAITED_RETURN_IN_TRY_BLOCK; read is sync.
return settings.read<Map<String, int>>(SettingsService.localLastPlayedAt);
} catch (_) {
return const {};
}
+4 -1
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import '../media/ids.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
@@ -17,7 +18,9 @@ import '../utils/app_logger.dart';
import '../utils/media_server_timeouts.dart';
import '../utils/active_client_scope.dart';
import '../utils/future_extensions.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'plex_auth_service.dart';
import 'settings_service.dart';
import 'storage_service.dart';
@@ -675,7 +678,7 @@ class MultiServerManager {
// before closing it, so a client found here is never mid-close.
final existing = _jellyfinByCompoundId[connection.id];
if (existing != null && canReuseJellyfinClient(live: existing.connection, incoming: connection)) {
return _reuseJellyfinClient(existing);
return await _reuseJellyfinClient(existing);
}
var resolvedConnection = connection;
+4 -1
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import '../exceptions/media_server_exceptions.dart';
import '../media/ids.dart';
@@ -724,7 +725,9 @@ class PlaybackProgressTracker {
Future<bool> _shouldReportTrackSelections() async {
try {
final settings = await SettingsService.getInstance();
return settings.read(SettingsService.rememberTrackSelections);
// Explicit type argument: the async return context would otherwise
// infer T = FutureOr and trip UNAWAITED_RETURN_IN_TRY_BLOCK; read is sync.
return settings.read<bool>(SettingsService.rememberTrackSelections);
} catch (e) {
appLogger.d('Could not read track-selection persistence setting; reporting selected streams', error: e);
return true;
@@ -38,7 +38,7 @@ mixin _PlexCollectionMethods on _PlexClientInternals {
Future<List<PlexMetadataDto>> _getLibraryCollections(String sectionId) async {
try {
return _fetchAllPages(
return await _fetchAllPages(
(start, size, abort) => _getLibraryCollectionsPage(sectionId, start: start, size: size, abort: abort),
);
} catch (e, st) {
@@ -120,7 +120,7 @@ mixin _PlexPlayQueueMethods on _PlexClientInternals {
// the client-side choice in [sortEpisodesByWatchOrder].
final leaf = effectiveSpecialsOrdering() == SpecialsOrdering.specialsLast ? 'children' : 'allLeaves';
final uri = '${await buildMetadataUri(showRatingKey)}/$leaf';
return createPlayQueue(
return await createPlayQueue(
uri: uri,
type: 'video',
shuffle: shuffle,
+14
View File
@@ -1,5 +1,6 @@
import 'dart:io';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:saf_util/saf_util.dart';
import '../utils/app_logger.dart';
import '../utils/platform_detector.dart';
@@ -29,6 +30,19 @@ class SafStorageService implements SafStorageOperations {
static SafStorageService get instance => _instance ??= SafStorageService._();
SafStorageService._();
/// The SAF operations app code should use. Distinct from [instance] because
/// playback resolution runs from services the widget tree builds itself and
/// so cannot be handed a collaborator; tests substitute a fake here.
static SafStorageOperations get ops => _opsOverride ?? instance;
static SafStorageOperations? _opsOverride;
/// Substitute the operations returned by [ops]. Pass null to restore the
/// real service; suites that set this must reset it in teardown.
@visibleForTesting
static void setOpsForTesting(SafStorageOperations? ops) {
_opsOverride = ops;
}
final SafUtil _safUtil = SafUtil();
/// Check if SAF is available (Android only)
+20 -4
View File
@@ -216,6 +216,8 @@ void scrollListToIndex(
required double itemExtent,
double leadingPadding = 12.0,
bool animate = true,
Duration duration = const Duration(milliseconds: 150),
Curve curve = Curves.easeOut,
}) {
if (controller.positions.length != 1 || itemExtent <= 0) return;
@@ -226,7 +228,7 @@ void scrollListToIndex(
final desiredOffset = (targetCenter - (viewport / 2)).clamp(0.0, maxExtent);
if (animate) {
unawaited(controller.animateTo(desiredOffset, duration: const Duration(milliseconds: 150), curve: Curves.easeOut));
unawaited(controller.animateTo(desiredOffset, duration: duration, curve: curve));
} else {
controller.jumpTo(desiredOffset);
}
@@ -240,6 +242,8 @@ void scrollKeyedChildToHorizontalCenter(
bool animate = true,
int maxAttempts = 2,
bool Function()? isCurrent,
Duration duration = const Duration(milliseconds: 150),
Curve curve = Curves.easeOut,
}) {
void schedule(int attempt) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -251,7 +255,13 @@ void scrollKeyedChildToHorizontalCenter(
return;
}
final didResolve = _scrollContextToHorizontalCenterNow(controller, context, animate: animate);
final didResolve = _scrollContextToHorizontalCenterNow(
controller,
context,
animate: animate,
duration: duration,
curve: curve,
);
if (!didResolve && attempt < maxAttempts) schedule(attempt + 1);
});
}
@@ -259,7 +269,13 @@ void scrollKeyedChildToHorizontalCenter(
schedule(0);
}
bool _scrollContextToHorizontalCenterNow(ScrollController controller, BuildContext context, {required bool animate}) {
bool _scrollContextToHorizontalCenterNow(
ScrollController controller,
BuildContext context, {
required bool animate,
required Duration duration,
required Curve curve,
}) {
if (!context.mounted || controller.positions.length != 1) return false;
final position = controller.position;
@@ -286,7 +302,7 @@ bool _scrollContextToHorizontalCenterNow(ScrollController controller, BuildConte
if ((target - position.pixels).abs() < 0.5) return true;
if (animate) {
unawaited(controller.animateTo(target, duration: const Duration(milliseconds: 150), curve: Curves.easeOut));
unawaited(controller.animateTo(target, duration: duration, curve: curve));
} else {
controller.jumpTo(target);
}
+7 -1
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import '../media/ids.dart';
import 'package:flutter/material.dart';
@@ -310,6 +311,10 @@ Future<bool?> navigateToVideoPlayer(
}
}
// Deliberately not awaited inside the try: the route future completes when
// the player pops, but the in-flight guard must release once the push is
// committed. Returned after the finally so the guard timing is unchanged.
Future<bool?>? pushFuture;
try {
// Check if external player is enabled. The platform guard comes first so
// platforms that can never launch an external player skip the settings
@@ -386,12 +391,13 @@ Future<bool?> navigateToVideoPlayer(
),
);
return usePushReplacement ? navigator.pushReplacement<bool, bool>(route) : navigator.push<bool>(route);
pushFuture = usePushReplacement ? navigator.pushReplacement<bool, bool>(route) : navigator.push<bool>(route);
} finally {
if (markedInFlight) {
_videoPlayerNavigationInFlightGuard.finish(launchIdentity);
}
}
return pushFuture;
}
/// Navigates to the video player and optionally refreshes content when returning.
+21 -3
View File
@@ -6,6 +6,7 @@ import '../focus/dpad_navigator.dart';
import '../focus/dpad_select_long_press_controller.dart';
import '../focus/focus_theme.dart';
import '../focus/input_mode_tracker.dart';
import '../focus/focus_navigation_intent.dart';
import '../focus/key_event_utils.dart';
import '../services/settings_service.dart';
import 'settings_builder.dart';
@@ -149,12 +150,16 @@ class HubSectionState extends State<HubSection> with MountedSetStateMixin, Skele
return serverId == null ? widget.hub.id : '$serverId:${widget.hub.id}';
}
// Native tvOS focus-engine scroll settles over ~450-900ms of ease-out
// (FocusProbe capture, issue #2006); successive steps retarget the
// animation so a drag chains into one continuous glide.
static const _navigationScrollDuration = Duration(milliseconds: 500);
final _selectLongPress = DpadSelectLongPressController();
@override
void initState() {
super.initState();
_hubFocusNode = FocusNode(debugLabel: 'hub_${widget.hub.id}');
_hubFocusNode = LockedFocusRowNode(debugLabel: 'hub_${widget.hub.id}', focusedItemRect: _focusedItemRect);
_hubFocusNode.addListener(_onFocusChange);
}
@@ -261,8 +266,8 @@ class HubSectionState extends State<HubSection> with MountedSetStateMixin, Skele
Scrollable.ensureVisible(
context,
alignment: widget.focusScrollAlignment,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
duration: _navigationScrollDuration,
curve: Curves.easeOutCubic,
);
});
}
@@ -278,6 +283,8 @@ class HubSectionState extends State<HubSection> with MountedSetStateMixin, Skele
itemExtent: _itemExtent,
leadingPadding: _leadingPadding,
animate: animate,
duration: _navigationScrollDuration,
curve: Curves.easeOutCubic,
);
if (index >= 0 && index < _totalItemCount) {
scrollKeyedChildToHorizontalCenter(
@@ -285,6 +292,8 @@ class HubSectionState extends State<HubSection> with MountedSetStateMixin, Skele
_itemKeyFor(index),
animate: animate,
isCurrent: () => _focusedIndex == index && index < _totalItemCount,
duration: _navigationScrollDuration,
curve: Curves.easeOutCubic,
);
}
}
@@ -376,6 +385,15 @@ class HubSectionState extends State<HubSection> with MountedSetStateMixin, Skele
return _itemKeys.putIfAbsent(index, () => GlobalKey());
}
/// Global rect of the selected card, pricing one swipe step by the card's
/// geometry instead of the row-wide focus node's (see [LockedFocusRowNode]).
Rect? _focusedItemRect() {
final context = _itemKeys[_focusedIndex]?.currentContext;
final box = context?.findRenderObject();
if (box is! RenderBox || !box.attached || !box.hasSize) return null;
return box.localToGlobal(Offset.zero) & box.size;
}
GlobalKey<MediaCardState> _getMediaCardKey(int index) {
return _mediaCardKeys.putIfAbsent(index, () => GlobalKey<MediaCardState>());
}
+25 -11
View File
@@ -10,6 +10,7 @@ import '../focus/dpad_navigator.dart';
import '../focus/dpad_select_long_press_controller.dart';
import '../focus/focus_theme.dart';
import '../focus/key_event_utils.dart';
import '../focus/focus_navigation_intent.dart';
import '../focus/locked_hub_controller.dart';
import '../i18n/strings.g.dart';
import '../media/ids.dart';
@@ -359,14 +360,18 @@ class TvBrowseRail extends StatefulWidget {
}
class TvBrowseRailState extends State<TvBrowseRail> with TickerProviderStateMixin {
static const _navigationScrollDuration = Duration(milliseconds: 130);
static const _repeatNavigationScrollDuration = Duration(milliseconds: 65);
// Native tvOS focus-engine scroll settles over ~450-900ms of ease-out
// (FocusProbe capture, issue #2006). Successive steps — including
// hold-repeats — retarget the animation, so a sustained drag trails the
// focused index slightly and catches up in one continuous glide on
// release, exactly like the native engine's scrollable containers.
static const _navigationScrollDuration = Duration(milliseconds: 500);
static const _scrollCatchUpViewportDistance = 2.5;
// Equivalent to the former whole-rail Opacity(0.6) without keeping a
// full-viewport saveLayer alive.
static const _unfocusedRailDimAlpha = 0.4;
final FocusNode _focusNode = FocusNode(debugLabel: 'tv_browse_rail');
late final FocusNode _focusNode = LockedFocusRowNode(debugLabel: 'tv_browse_rail', focusedItemRect: _focusedCardRect);
final Map<String, ScrollController> _scrollControllers = {};
final ScrollController _verticalController = ScrollController();
final SnapshotController _verticalScrollSnapshotController = SnapshotController();
@@ -670,7 +675,7 @@ class TvBrowseRailState extends State<TvBrowseRail> with TickerProviderStateMixi
if (key.isLeftKey) {
if (_itemIndex > 0) {
_moveItem(-1, duration: event is KeyRepeatEvent ? _repeatNavigationScrollDuration : _navigationScrollDuration);
_moveItem(-1);
} else {
widget.onNavigateToSidebar?.call();
}
@@ -679,7 +684,7 @@ class TvBrowseRailState extends State<TvBrowseRail> with TickerProviderStateMixi
if (key.isRightKey) {
if (_itemIndex < _totalItemCount(hub) - 1) {
_moveItem(1, duration: event is KeyRepeatEvent ? _repeatNavigationScrollDuration : _navigationScrollDuration);
_moveItem(1);
}
return KeyEventResult.handled;
}
@@ -753,11 +758,8 @@ class TvBrowseRailState extends State<TvBrowseRail> with TickerProviderStateMixi
final target = _sectionOffsets[_hubIndex].clamp(0.0, _sectionMaxScrollExtent).toDouble();
if (animate) {
_startVerticalScrollAnimation(
() => _verticalController.animateTo(
target,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOutCubic,
),
() =>
_verticalController.animateTo(target, duration: _navigationScrollDuration, curve: Curves.easeOutCubic),
);
} else {
_verticalScrollGeneration++;
@@ -776,7 +778,7 @@ class TvBrowseRailState extends State<TvBrowseRail> with TickerProviderStateMixi
() => Scrollable.ensureVisible(
context,
alignment: 0,
duration: const Duration(milliseconds: 250),
duration: _navigationScrollDuration,
curve: Curves.easeOutCubic,
),
);
@@ -924,6 +926,18 @@ class TvBrowseRailState extends State<TvBrowseRail> with TickerProviderStateMixi
return _mediaCardKeys.putIfAbsent('${_hubKey(hub)}:$itemIndex', () => GlobalKey<MediaCardState>());
}
/// Global rect of the active hub's selected card, pricing one swipe step by
/// the card's geometry instead of the rail-wide focus node's (see
/// [LockedFocusRowNode]).
Rect? _focusedCardRect() {
final hub = _activeHub;
if (hub == null || _itemIndex < 0 || _itemIndex >= hub.items.length) return null;
final context = _cardKeyFor(hub, _itemIndex).currentContext;
final box = context?.findRenderObject();
if (box is! RenderBox || !box.attached || !box.hasSize) return null;
return box.localToGlobal(Offset.zero) & box.size;
}
bool _isContinueWatchingHub(MediaHub hub) => widget.isContinueWatchingHub?.call(hub) ?? false;
bool _usesContinueWatchingAction(MediaHub hub) {
+7
View File
@@ -232,4 +232,11 @@ if(PLEZY_BUILD_MPV_RELIABILITY_TESTS)
target_link_libraries(plane_render_executor_test PRIVATE PkgConfig::GTK Threads::Threads)
apply_mpv_reliability_sanitizer(plane_render_executor_test)
add_test(NAME plane_render_executor_test COMMAND plane_render_executor_test)
if(PLEZY_MPV_RELIABILITY_SANITIZER STREQUAL "thread")
# GLib's futex-based GMutex is invisible to TSan; suppress reports that
# originate inside libglib. Inert when the sanitizer probe fell back to an
# unsanitized build. See mpv/tsan_suppressions.txt.
set_tests_properties(plane_render_executor_test PROPERTIES ENVIRONMENT
"TSAN_OPTIONS=suppressions=${CMAKE_CURRENT_SOURCE_DIR}/mpv/tsan_suppressions.txt")
endif()
endif()
+19 -3
View File
@@ -1,5 +1,6 @@
#include "plane_render_executor.h"
#include <atomic>
#include <chrono>
namespace mpv {
@@ -9,15 +10,29 @@ namespace {
struct CompletionInvocation {
PlaneRenderExecutor::Completion completion;
bool result;
// The worker hands this struct to the main context through
// g_main_context_invoke_full, whose internal context lock is a GLib futex
// that ThreadSanitizer cannot observe. This release/acquire pair republishes
// that same happens-before edge in a form TSan models; GLib still provides
// the delivery ordering.
std::atomic<bool> published{false};
};
gboolean InvokeCompletion(gpointer data) {
auto* invocation = static_cast<CompletionInvocation*>(data);
// Pairs with the release store in Run(); see CompletionInvocation.
(void)invocation->published.load(std::memory_order_acquire);
invocation->completion(invocation->result);
return G_SOURCE_REMOVE;
}
void DestroyCompletionInvocation(gpointer data) { delete static_cast<CompletionInvocation*>(data); }
void DestroyCompletionInvocation(gpointer data) {
auto* invocation = static_cast<CompletionInvocation*>(data);
// The destroy notify can also be the first main-thread access when the
// source is torn down without dispatching; take the same edge.
(void)invocation->published.load(std::memory_order_acquire);
delete invocation;
}
} // namespace
@@ -84,9 +99,10 @@ void PlaneRenderExecutor::Run(const std::shared_ptr<Shared>& shared) {
const bool result = job ? job() : false;
if (completion) {
auto* invocation = new CompletionInvocation{std::move(completion), result};
invocation->published.store(true, std::memory_order_release);
g_main_context_invoke_full(
shared->completion_context, G_PRIORITY_DEFAULT, InvokeCompletion,
new CompletionInvocation{std::move(completion), result}, DestroyCompletionInvocation);
shared->completion_context, G_PRIORITY_DEFAULT, InvokeCompletion, invocation, DestroyCompletionInvocation);
}
{
+12
View File
@@ -0,0 +1,12 @@
# ThreadSanitizer suppressions for the focused mpv reliability tests.
#
# GLib's GMutex is a raw futex, not a pthread mutex, so TSan cannot observe
# the happens-before edges GMainContext provides. Any cross-thread handoff
# through g_main_context_invoke_full then reports races inside GLib's own
# source/queue bookkeeping (g_malloc vs free of idle sources, etc.).
#
# This only hides reports whose racing access originates inside libglib;
# races on this repository's memory still fail the run. The executor's own
# completion handoff carries an explicit release/acquire pair (see
# plane_render_executor.cc) precisely so it stays visible to TSan.
called_from_lib:libglib-2.0.so
+1 -1
View File
@@ -31,7 +31,7 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
auto_updater_macos: 3a42f1a06be6981f1a18be37e6e7bf86aa732118
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
FlutterMacOS: c232990155153907050900a2e175c7773903ba4e
os_media_controls: 20a765c7ebaae4fb3133cc47782eb99d7b50d851
Sparkle: f4355f9ebbe9b7d932df4980d70f13922ac97b2a
universal_gamepad: 5d5c2ad9be4eaafcdc0bdc536b51725fe058667f
+9
View File
@@ -1 +1,10 @@
analyzer:
exclude:
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
include: package:mgenware_dart_lints/flutter_lints.yaml
+8 -8
View File
@@ -103,10 +103,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -119,10 +119,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.0"
version: "1.19.0"
mgenware_dart_lints:
dependency: "direct dev"
description:
@@ -196,18 +196,18 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.11"
version: "0.7.12"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "2.4.2"
vm_service:
dependency: transitive
description:
@@ -103,10 +103,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -119,10 +119,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.0"
version: "1.19.0"
path:
dependency: "direct main"
description:
@@ -220,18 +220,18 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.11"
version: "0.7.12"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "2.4.2"
vm_service:
dependency: transitive
description:
@@ -249,5 +249,5 @@ packages:
source: hosted
version: "1.1.0"
sdks:
dart: ">=3.10.0 <4.0.0"
dart: ">=3.11.0-0 <4.0.0"
flutter: ">=3.38.0"
@@ -103,10 +103,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -119,10 +119,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.0"
version: "1.19.0"
path:
dependency: "direct main"
description:
@@ -220,18 +220,18 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.11"
version: "0.7.12"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "2.4.2"
vm_service:
dependency: transitive
description:
@@ -241,5 +241,5 @@ packages:
source: hosted
version: "15.2.0"
sdks:
dart: ">=3.10.0 <4.0.0"
dart: ">=3.11.0-0 <4.0.0"
flutter: ">=3.38.0"
+9 -9
View File
@@ -244,10 +244,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -260,10 +260,10 @@ packages:
dependency: "direct main"
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.0"
version: "1.19.0"
mocktail:
dependency: "direct dev"
description:
@@ -385,10 +385,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.11"
version: "0.7.12"
typed_data:
dependency: transitive
description:
@@ -401,10 +401,10 @@ packages:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "2.4.2"
vm_service:
dependency: transitive
description:
@@ -462,5 +462,5 @@ packages:
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.10.0 <4.0.0"
dart: ">=3.11.0-0 <4.0.0"
flutter: ">=3.38.0"
+11 -11
View File
@@ -591,10 +591,10 @@ packages:
dependency: "direct main"
description:
name: intl
sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5"
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
url: "https://pub.dev"
source: hosted
version: "0.20.2"
version: "0.20.3"
io:
dependency: transitive
description:
@@ -687,10 +687,10 @@ packages:
dependency: transitive
description:
name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.19"
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
@@ -711,10 +711,10 @@ packages:
dependency: transitive
description:
name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.18.0"
version: "1.19.0"
mgenware_dart_lints:
dependency: "direct dev"
description:
@@ -1274,10 +1274,10 @@ packages:
dependency: transitive
description:
name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.11"
version: "0.7.12"
typed_data:
dependency: transitive
description:
@@ -1402,10 +1402,10 @@ packages:
dependency: transitive
description:
name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev"
source: hosted
version: "2.2.0"
version: "2.4.2"
vm_service:
dependency: transitive
description:
@@ -1527,4 +1527,4 @@ packages:
version: "2.2.4"
sdks:
dart: ">=3.12.0 <4.0.0"
flutter: ">=3.44.0"
flutter: ">=3.47.0"
+4 -2
View File
@@ -1,11 +1,13 @@
name: plezy
description: "A beautiful Plex and Jellyfin client for Flutter"
publish_to: "none"
version: 2.17.0+145
version: 2.17.1+146
environment:
# Dart floor stays 3.12: freezed 3.x emits `final` constructor parameters,
# which language 3.13 removed. Raise together with a freezed 4 migration.
sdk: ">=3.12.0 <4.0.0"
flutter: ">=3.44.0"
flutter: ">=3.47.0"
dependencies:
flutter:
+2 -2
View File
@@ -10,8 +10,8 @@ from workflow_yaml import iter_uses_references, job_block
ROOT = Path(__file__).resolve().parents[2]
DEFAULT_WORKFLOW = ROOT / ".github/workflows/build.yml"
FLUTTER_VERSION = "3.44.0"
FLUTTER_COMMIT = "559ffa3f75e7402d65a8def9c28389a9b2e6fe42"
FLUTTER_VERSION = "3.47.1"
FLUTTER_COMMIT = "6655482ec06e547f90abf8ae7590466f4415978d"
if len(sys.argv) > 2:
raise SystemExit(f"Usage: {Path(sys.argv[0]).name} [workflow-path]")
WORKFLOW = Path(sys.argv[1]).resolve() if len(sys.argv) == 2 else DEFAULT_WORKFLOW
+1 -1
View File
@@ -49,7 +49,7 @@ class BuildWorkflowGuardTest(unittest.TestCase):
def test_windows_arm_flutter_without_release_tag_is_rejected(self) -> None:
action = self._action().replace(
'git -C $root fetch --depth 1 origin "refs/tags/${version}:refs/tags/${version}"',
"git -C $root fetch --depth 1 origin 559ffa3f75e7402d65a8def9c28389a9b2e6fe42",
"git -C $root fetch --depth 1 origin 6655482ec06e547f90abf8ae7590466f4415978d",
1,
)
self.assertNotEqual(action, self._action(), "fixture mutation no longer matches the action")
+6 -1
View File
@@ -17,7 +17,12 @@ ANDROID_15_INSTRUMENTATION_CLASSES = (
ANDROID_15_INSTRUMENTATION_TARGET = "android-15-instrumentation"
# Separate R8 reachability from instrumentation: these suites exercise APIs the app
# does not call directly, so shrinking them is expected. Covers name-based reachability (#1703).
ANDROID_R8_REACHABILITY_CLASSES = "androidx.media3.decoder.ffmpeg.FfmpegDecoderReachabilityTest"
ANDROID_R8_REACHABILITY_CLASSES = ",".join(
(
"androidx.media3.decoder.ffmpeg.FfmpegDecoderReachabilityTest",
"com.edde746.plezy.exoplayer.FfmpegDemuxerReachabilityTest",
)
)
ANDROID_R8_REACHABILITY_TARGET = "android-r8-reachability"
@@ -21,12 +21,14 @@ import 'package:plezy/services/download_storage_service.dart';
import 'package:plezy/services/jellyfin_api_cache.dart';
import 'package:plezy/services/plex_api_cache.dart';
import 'package:plezy/services/offline_mode_source.dart';
import 'package:plezy/services/saf_storage_service.dart';
import 'package:plezy/utils/deletion_notifier.dart';
import 'package:plezy/utils/notification_permission.dart';
import 'package:plezy/utils/watch_state_notifier.dart';
import 'package:plezy/utils/active_client_scope.dart';
import '../test_helpers/download_fixtures.dart';
import '../test_helpers/media_items.dart';
import '../test_helpers/saf_fakes.dart';
/// Implements only [fetchPlayableDescendants], the surface [collectEpisodes]
/// uses. Every other call reaches [noSuchMethod] and throws.
@@ -228,6 +230,9 @@ void main() {
PlexApiCache.initialize(db);
JellyfinApiCache.initialize(db);
testClientResolver = null;
// Local-path tests store SAF content:// URIs; resolution confirms such a
// copy is still reachable before returning it (issue #2101).
SafStorageService.setOpsForTesting(FakeSafStorage());
downloadManager = DownloadManagerService(
database: db,
storageService: DownloadStorageService.instance,
@@ -242,6 +247,7 @@ void main() {
tearDown(() async {
downloadManager.dispose();
await db.close();
SafStorageService.setOpsForTesting(null);
});
group('DownloadManagerService — platform support', () {
+6 -1
View File
@@ -147,13 +147,14 @@ void main() {
);
});
test('resume prompt is suppressed during active video playback (#2034)', () {
test('resume prompt is suppressed during playback (#2034) and companion sessions (#2087)', () {
bool should({
bool resumedFromBackground = true,
bool isOffline = false,
bool alreadyShowingProfileSelection = false,
bool isMobilePlatform = true,
bool hasActiveVideoPlayback = false,
bool hasActiveCompanionRemoteSession = false,
}) {
return shouldShowProfileSelectionOnResume(
resumedFromBackground: resumedFromBackground,
@@ -161,6 +162,7 @@ void main() {
alreadyShowingProfileSelection: alreadyShowingProfileSelection,
isMobilePlatform: isMobilePlatform,
hasActiveVideoPlayback: hasActiveVideoPlayback,
hasActiveCompanionRemoteSession: hasActiveCompanionRemoteSession,
);
}
@@ -168,6 +170,9 @@ void main() {
// Waking the device mid-stream resumes the stream; the picker would
// fight the player's focus self-heal for the remote.
expect(should(hasActiveVideoPlayback: true), isFalse);
// A phone driving another device backgrounds constantly; the picker +
// PIN would bury the live remote session.
expect(should(hasActiveCompanionRemoteSession: true), isFalse);
expect(should(resumedFromBackground: false), isFalse);
expect(should(isOffline: true), isFalse);
expect(should(alreadyShowingProfileSelection: true), isFalse);
@@ -17,6 +17,7 @@ import 'package:plezy/providers/user_profile_provider.dart';
import 'package:plezy/screens/video_player_screen.dart';
import 'package:plezy/services/download_storage_service.dart';
import 'package:plezy/services/offline_watch_sync_service.dart';
import 'package:plezy/services/saf_storage_service.dart';
import 'package:plezy/services/settings_service.dart';
import 'package:provider/provider.dart';
@@ -25,6 +26,7 @@ import '../../test_helpers/media_items.dart';
import '../../test_helpers/mock_player_channels.dart';
import '../../test_helpers/multi_server_fixtures.dart';
import '../../test_helpers/prefs.dart';
import '../../test_helpers/saf_fakes.dart';
import '../../test_helpers/watch_together_fakes.dart';
/// Regression coverage for the in-place reload rollback: a reload that fails
@@ -43,6 +45,10 @@ void main() {
resetSharedPreferencesForTest();
SettingsService.resetForTesting();
DownloadStorageService.resetForTesting();
// The reload target resolves offline from the content:// row below;
// resolution confirms that copy is still reachable before preferring it
// over streaming (issue #2101).
SafStorageService.setOpsForTesting(FakeSafStorage());
await SettingsService.getInstance();
tmpRoot = await Directory.systemTemp.createTemp('playback_reload_failure_test_');
previousPathProvider = PathProviderPlatform.instance;
@@ -54,6 +60,7 @@ void main() {
tearDown(() async {
await db.close();
DownloadStorageService.resetForTesting();
SafStorageService.setOpsForTesting(null);
SettingsService.resetForTesting();
PathProviderPlatform.instance = previousPathProvider;
if (await tmpRoot.exists()) {
@@ -2,7 +2,9 @@ import 'dart:async';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/focus/focus_navigation_intent.dart';
import 'package:plezy/services/apple_tv_remote_touch_service.dart';
void main() {
@@ -69,6 +71,60 @@ void main() {
expect(harness.keys, [LogicalKeyboardKey.arrowUp]);
});
test('prices a step by the focused item extent plus the travel margin', () async {
final harness = _Harness()..focusedRect = const Rect.fromLTWH(0, 0, 245, 10);
// Horizontal: 245pt extent + 155pt margin = 400pt per step.
await harness.send('started', x: 500, y: 500);
await harness.send('move', x: 101, y: 500);
expect(harness.keys, isEmpty);
await harness.send('move', x: 100, y: 500);
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
// Vertical: 10pt extent prices at the 200pt floor, not at 165pt.
harness.advance(const Duration(milliseconds: 61));
await harness.send('started', x: 500, y: 500);
await harness.send('move', x: 500, y: 301);
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
await harness.send('move', x: 500, y: 300);
expect(harness.keys, [LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowUp]);
});
test('a wide-flat control steps vertically once the finger covers its height', () async {
final harness = _Harness()..focusedRect = const Rect.fromLTWH(0, 0, 900, 45);
// Width prices at the 700pt cap; height at 45+155 = 200pt. A larger raw
// horizontal delta still resolves vertical because axis progress is
// normalized by the per-axis thresholds, like the native engine.
await harness.send('started', x: 500, y: 500);
await harness.send('move', x: 250, y: 290);
expect(harness.keys, [LogicalKeyboardKey.arrowUp]);
});
testWidgets('a locked-focus row prices by its selected item, not its row-wide node', (tester) async {
final node = LockedFocusRowNode(debugLabel: 'row', focusedItemRect: () => const Rect.fromLTWH(0, 0, 245, 345));
addTearDown(node.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Focus(focusNode: node, child: const SizedBox(width: 1700, height: 400)),
),
);
node.requestFocus();
await tester.pump();
final keys = <LogicalKeyboardKey>[];
// No injected geometry: exercises the default primary-focus resolution,
// which must consult the node's item rect (245+155 = 400pt per step)
// instead of its 1700pt-wide row rect (the 700pt travel cap).
final service = AppleTvRemoteTouchService(simulateKeyPress: keys.add, scheduleFrame: () {});
await service.handleMessage({'type': 'started', 'x': 500.0, 'y': 500.0});
await service.handleMessage({'type': 'move', 'x': 101.0, 'y': 500.0});
expect(keys, isEmpty);
await service.handleMessage({'type': 'move', 'x': 100.0, 'y': 500.0});
expect(keys, [LogicalKeyboardKey.arrowLeft]);
});
test('keeps horizontal axis through non-decisive vertical drift', () async {
final harness = _Harness();
@@ -192,40 +248,44 @@ void main() {
expect(harness.keys, isEmpty);
});
test('a fast lift glides one extra step', () {
fakeAsync((async) {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 50));
// 120pt in 50ms = 2400pt/s at lift: past the glide velocity, below
// the double-step velocity.
harness.sendSync('move', x: 380, y: 500);
harness.sendSync('ended', x: 380, y: 500);
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
async.elapse(const Duration(milliseconds: 70));
expect(harness.keys, [LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft]);
async.elapse(const Duration(milliseconds: 300));
expect(harness.keys, [LogicalKeyboardKey.arrowLeft, LogicalKeyboardKey.arrowLeft]);
});
});
test('a violent flick glides two extra steps', () {
test('a fast single-step flick does not glide', () {
fakeAsync((async) {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 8));
// 120pt in 8ms = 15000pt/s at lift: past the double-step velocity.
// 120pt in 8ms = 15000pt/s: far past both glide velocities, but the
// gesture emitted only one step. Ungated, every deliberate single
// swipe glided into a second step (issue #2006).
harness.sendSync('move', x: 380, y: 500);
harness.sendSync('ended', x: 380, y: 500);
async.elapse(const Duration(milliseconds: 500));
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
});
});
async.elapse(const Duration(milliseconds: 140));
test('a fast lift after a sustained drag glides one extra step', () {
fakeAsync((async) {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 50));
harness.sendSync('move', x: 380, y: 500);
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 260, y: 500);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
// 120pt in the last 8ms: ~3500pt/s over the velocity window — past
// the glide velocity, below the double-step velocity.
harness.advance(const Duration(milliseconds: 8));
harness.sendSync('move', x: 140, y: 500);
harness.sendSync('ended', x: 140, y: 500);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
async.elapse(const Duration(milliseconds: 70));
expect(harness.keys, List.filled(3, LogicalKeyboardKey.arrowLeft));
async.elapse(const Duration(milliseconds: 300));
@@ -233,18 +293,56 @@ void main() {
});
});
test('a slow lift does not glide', () {
test('a violent lift after a sustained drag still glides only one extra step', () {
fakeAsync((async) {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 1));
harness.sendSync('move', x: 380, y: 500);
harness.advance(const Duration(milliseconds: 61));
harness.sendSync('move', x: 260, y: 500);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
// The drag steps age out of the velocity window; the final
// sub-threshold segment covers 64pt in 5ms = 12800pt/s. The native
// engine never coasts more than one step no matter how violent the
// lift (FocusProbe capture: 101 sessions, lifts up to ~11400pt/s,
// never a second coast step).
harness.advance(const Duration(milliseconds: 103));
harness.sendSync('move', x: 244, y: 500);
harness.advance(const Duration(milliseconds: 5));
harness.sendSync('move', x: 180, y: 500);
harness.sendSync('ended', x: 180, y: 500);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
async.elapse(const Duration(milliseconds: 500));
expect(harness.keys, List.filled(3, LogicalKeyboardKey.arrowLeft));
});
});
test('a slow lift after a sustained drag does not glide', () {
fakeAsync((async) {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 60));
// 100pt in 60ms = 1667pt/s at lift: below the glide velocity.
harness.sendSync('move', x: 400, y: 500);
harness.sendSync('ended', x: 400, y: 500);
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 300, y: 500);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
// Sub-threshold 90pt in 60ms = 1500pt/s at lift: the drag satisfies
// the glide gate, but the lift stays below the glide velocity.
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 210, y: 500);
harness.sendSync('ended', x: 210, y: 500);
async.elapse(const Duration(milliseconds: 500));
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
});
});
@@ -253,13 +351,17 @@ void main() {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 8));
harness.advance(const Duration(milliseconds: 50));
harness.sendSync('move', x: 380, y: 500);
harness.sendSync('ended', x: 380, y: 500);
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 260, y: 500);
harness.advance(const Duration(milliseconds: 8));
harness.sendSync('move', x: 140, y: 500);
harness.sendSync('ended', x: 140, y: 500);
harness.sendSync('started', x: 500, y: 500);
async.elapse(const Duration(milliseconds: 500));
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
});
});
@@ -285,17 +387,46 @@ void main() {
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 50));
harness.sendSync('move', x: 380, y: 500);
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 260, y: 500);
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
// Reversal pivot inside the cooldown: net window velocity points
// right, against the emitted arrowLeft.
harness.advance(const Duration(milliseconds: 8));
harness.sendSync('move', x: 620, y: 500);
harness.sendSync('ended', x: 620, y: 500);
harness.sendSync('move', x: 500, y: 500);
harness.sendSync('ended', x: 500, y: 500);
async.elapse(const Duration(milliseconds: 500));
expect(harness.keys, [LogicalKeyboardKey.arrowLeft]);
expect(harness.keys, List.filled(2, LogicalKeyboardKey.arrowLeft));
});
});
test('a direction reversal resets the glide gate', () {
fakeAsync((async) {
final harness = _Harness();
harness.sendSync('started', x: 500, y: 500);
harness.advance(const Duration(milliseconds: 50));
harness.sendSync('move', x: 380, y: 500);
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 260, y: 500);
// Reverse: one fast rightward step, then a fast rightward lift. The
// gesture emitted three steps, but only one in the lift direction,
// so a correction never glides past its target.
harness.advance(const Duration(milliseconds: 60));
harness.sendSync('move', x: 380, y: 500);
harness.advance(const Duration(milliseconds: 8));
harness.sendSync('move', x: 500, y: 500);
harness.sendSync('ended', x: 500, y: 500);
async.elapse(const Duration(milliseconds: 500));
expect(harness.keys, [
LogicalKeyboardKey.arrowLeft,
LogicalKeyboardKey.arrowLeft,
LogicalKeyboardKey.arrowRight,
]);
});
});
});
@@ -305,6 +436,7 @@ class _Harness {
_Harness();
DateTime now = DateTime(2026, 5, 5, 12);
Rect? focusedRect;
final List<LogicalKeyboardKey> keys = [];
late final AppleTvRemoteTouchService service = AppleTvRemoteTouchService(
@@ -312,6 +444,7 @@ class _Harness {
scheduleFrame: () {},
now: () => now,
swipeThreshold: 100,
focusedItemRect: () => focusedRect,
);
Future<void> send(String type, {double x = 0, double y = 0}) {
@@ -123,31 +123,27 @@ void main() {
expect(dir.path, p.join(tmpRoot.path, 'support', 'downloads'));
});
test(
'resolves under POSIX chmod restrictions (environment-dependent smoke)',
() async {
final settings = await SettingsService.getInstance();
final readOnlyParent = Directory(p.join(tmpRoot.path, 'readonly'))..createSync(recursive: true);
try {
await Process.run('chmod', ['000', readOnlyParent.path]);
final blocked = p.join(readOnlyParent.path, 'forbidden');
await settings.write(SettingsService.customDownloadPathType, 'file');
await settings.write(SettingsService.customDownloadPath, blocked);
test('resolves under POSIX chmod restrictions (environment-dependent smoke)', () async {
final settings = await SettingsService.getInstance();
final readOnlyParent = Directory(p.join(tmpRoot.path, 'readonly'))..createSync(recursive: true);
try {
await Process.run('chmod', ['000', readOnlyParent.path]);
final blocked = p.join(readOnlyParent.path, 'forbidden');
await settings.write(SettingsService.customDownloadPathType, 'file');
await settings.write(SettingsService.customDownloadPath, blocked);
final dss = DownloadStorageService.instance;
await dss.initialize(settings);
final dss = DownloadStorageService.instance;
await dss.initialize(settings);
final dir = await dss.getDownloadsDirectory();
// The host may honor or ignore mode bits; either resolved root is
// valid for this smoke test as long as it exists.
expect(dir.existsSync(), isTrue);
expect(dir.path, anyOf(blocked, p.join(tmpRoot.path, 'support', 'downloads')));
} finally {
await Process.run('chmod', ['755', readOnlyParent.path]);
}
},
skip: Platform.isWindows ? 'Windows does not provide chmod permission semantics' : false,
);
final dir = await dss.getDownloadsDirectory();
// The host may honor or ignore mode bits; either resolved root is
// valid for this smoke test as long as it exists.
expect(dir.existsSync(), isTrue);
expect(dir.path, anyOf(blocked, p.join(tmpRoot.path, 'support', 'downloads')));
} finally {
await Process.run('chmod', ['755', readOnlyParent.path]);
}
}, skip: Platform.isWindows ? 'Windows does not provide chmod permission semantics' : false);
test('refreshCustomPath picks up settings changes', () async {
final settings = await SettingsService.getInstance();
@@ -0,0 +1,118 @@
import 'dart:io';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plezy/database/app_database.dart';
import 'package:plezy/database/download_operations.dart';
import 'package:plezy/media/ids.dart';
import 'package:plezy/models/download_models.dart';
import 'package:plezy/services/download_storage_service.dart';
import 'package:plezy/services/downloaded_video_source.dart';
import 'package:plezy/services/saf_storage_service.dart';
import 'package:plezy/services/settings_service.dart';
import '../test_helpers/download_fixtures.dart';
import '../test_helpers/io_fakes.dart';
import '../test_helpers/prefs.dart';
import '../test_helpers/saf_fakes.dart';
/// A downloaded row only backs playback while its stored copy is actually
/// reachable. Returning null is what lets the caller stream from the server
/// instead of handing the player a dead path (issue #2101): a removable SAF
/// volume can be unmounted, and its documents disappear with it, while the row
/// still reads `completed`.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late AppDatabase db;
late Directory tmpRoot;
late PathProviderPlatform previousPathProvider;
setUp(() async {
resetSharedPreferencesForTest();
SettingsService.resetForTesting();
DownloadStorageService.resetForTesting();
tmpRoot = await Directory.systemTemp.createTemp('downloaded_video_source_test_');
previousPathProvider = PathProviderPlatform.instance;
PathProviderPlatform.instance = FakePathProvider(tmpRoot);
db = AppDatabase.forTesting(NativeDatabase.memory());
});
tearDown(() async {
await db.close();
DownloadStorageService.resetForTesting();
SafStorageService.setOpsForTesting(null);
SettingsService.resetForTesting();
PathProviderPlatform.instance = previousPathProvider;
if (await tmpRoot.exists()) {
await tmpRoot.delete(recursive: true);
}
});
Future<DownloadedMediaItem> completedRow(String storedPath) async {
const globalKey = 'srv-1:movie-1';
await db.insertDownload(
serverId: ServerId('srv-1'),
ratingKey: 'movie-1',
globalKey: globalKey,
type: 'movie',
status: DownloadStatus.completed.index,
mediaIndex: 0,
mediaSourceId: 'source-a',
);
await db.updateVideoFilePath(globalKey, storedPath);
return (db.select(db.downloadedMedia)..where((t) => t.globalKey.equals(globalKey))).getSingle();
}
group('SAF copies', () {
const safUri = 'content://com.android.externalstorage.documents/tree/79F7-B648%3A/document/movie-1.mkv';
test('an unmounted volume yields no source so the caller can stream', () async {
final row = await completedRow(safUri);
final saf = FakeSafStorage(reachable: false);
SafStorageService.setOpsForTesting(saf);
expect(await resolveDownloadedVideoSource(row, requestedMediaIndex: 0), isNull);
expect(saf.existsCalls, [safUri], reason: 'the stored document URI is what must be probed');
});
test('a reachable document plays from the stored URI', () async {
final row = await completedRow(safUri);
SafStorageService.setOpsForTesting(FakeSafStorage(existing: {safUri}));
final source = await resolveDownloadedVideoSource(row, requestedMediaIndex: 0);
expect(source?.path, safUri);
expect(source?.mediaIndex, 0);
expect(source?.mediaSourceId, 'source-a');
});
test('reachability is not consulted for a version that would be skipped anyway', () async {
final row = await completedRow(safUri);
final saf = FakeSafStorage();
SafStorageService.setOpsForTesting(saf);
expect(await resolveDownloadedVideoSource(row, requestedMediaIndex: 1), isNull);
expect(saf.existsCalls, isEmpty);
});
});
group('file copies', () {
test('a deleted file yields no source', () async {
final row = await completedRow('${tmpRoot.path}/gone.mkv');
expect(await resolveDownloadedVideoSource(row, requestedMediaIndex: 0), isNull);
});
test('a present file resolves to its absolute path', () async {
final video = File('${tmpRoot.path}/movie-1.mkv');
await video.writeAsBytes(const <int>[0]);
final row = await completedRow(video.path);
final source = await resolveDownloadedVideoSource(row, requestedMediaIndex: 0);
expect(source?.path, video.path);
});
});
}
@@ -158,11 +158,10 @@ void main() {
['GET /Users/user-1/Items/Resume'],
reason: embyRequests.log.join('\n'),
);
expect(
jellyfinRequests.requests.map((request) => '${request.method} ${request.url.path}').toList(),
['GET /UserItems/Resume', 'GET /Shows/NextUp'],
reason: jellyfinRequests.log.join('\n'),
);
expect(jellyfinRequests.requests.map((request) => '${request.method} ${request.url.path}').toList(), [
'GET /UserItems/Resume',
'GET /Shows/NextUp',
], reason: jellyfinRequests.log.join('\n'));
final embyResume = embyRequests.requests.first;
final jellyfinResume = jellyfinRequests.requests.first;
expect(embyResume.url.queryParameters, {
@@ -1233,11 +1232,10 @@ void main() {
final video = await client.fetchPlaylistsPage(playlistType: 'video');
final audio = await client.fetchPlaylistsPage(playlistType: 'audio');
expect(
requests.requests.map((request) => '${request.method} ${request.url.path}').toList(),
['GET /Items', 'GET /Items'],
reason: requests.log.join('\n'),
);
expect(requests.requests.map((request) => '${request.method} ${request.url.path}').toList(), [
'GET /Items',
'GET /Items',
], reason: requests.log.join('\n'));
for (final request in requests.requests) {
expect(request.url.queryParameters, {
'userId': 'user-1',
@@ -1304,11 +1302,10 @@ void main() {
final video = await client.fetchPlaylistsPage(playlistType: 'video');
final audio = await client.fetchPlaylistsPage(playlistType: 'audio');
expect(
requests.requests.map((request) => '${request.method} ${request.url.path}').toList(),
['GET /Items', 'GET /Items'],
reason: requests.log.join('\n'),
);
expect(requests.requests.map((request) => '${request.method} ${request.url.path}').toList(), [
'GET /Items',
'GET /Items',
], reason: requests.log.join('\n'));
expect(requests.requests.map((request) => request.url.queryParameters['MediaTypes']).toList(), [
'Video',
'Audio',
@@ -1528,11 +1525,9 @@ void main() {
final extras = await client.fetchPlaybackExtras('item-1');
expect(
requests.requests.map((request) => '${request.method} ${request.url.path}').toList(),
['GET /Users/user-1/Items/item-1'],
reason: requests.log.join('\n'),
);
expect(requests.requests.map((request) => '${request.method} ${request.url.path}').toList(), [
'GET /Users/user-1/Items/item-1',
], reason: requests.log.join('\n'));
expect(requests.requests.where((request) => request.url.path == '/MediaSegments/item-1'), isEmpty);
expect(extras.markers.map((marker) => marker.type).toList(), ['intro', 'credits']);
expect(extras.markers.first.startTimeOffset, 10000);
@@ -1560,11 +1555,10 @@ void main() {
final extras = await client.fetchPlaybackExtras('item-1');
expect(
requests.requests.map((request) => '${request.method} ${request.url.path}').toList(),
['GET /Users/user-1/Items/item-1', 'GET /MediaSegments/item-1'],
reason: requests.log.join('\n'),
);
expect(requests.requests.map((request) => '${request.method} ${request.url.path}').toList(), [
'GET /Users/user-1/Items/item-1',
'GET /MediaSegments/item-1',
], reason: requests.log.join('\n'));
expect(requests.requests.last.url.query, isEmpty);
expect(extras.markers.map((marker) => marker.type).toList(), ['intro']);
expect(extras.markers.single.startTimeOffset, 5000);
@@ -19,11 +19,13 @@ import 'package:plezy/services/jellyfin_media_info_mapper.dart';
import 'package:plezy/services/playback_initialization_service.dart';
import 'package:plezy/services/plex_api_cache.dart';
import 'package:plezy/services/plex_mappers.dart';
import 'package:plezy/services/saf_storage_service.dart';
import 'package:plezy/services/settings_service.dart';
import '../test_helpers/io_fakes.dart';
import '../test_helpers/prefs.dart';
import '../test_helpers/media_items.dart';
import '../test_helpers/saf_fakes.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -36,6 +38,10 @@ void main() {
resetSharedPreferencesForTest();
SettingsService.resetForTesting();
DownloadStorageService.resetForTesting();
// Downloaded rows below store SAF content:// URIs. Playback resolution
// confirms such a copy is still reachable before preferring it over
// streaming (issue #2101), so report them as present.
SafStorageService.setOpsForTesting(FakeSafStorage());
tmpRoot = await Directory.systemTemp.createTemp('playback_init_test_');
previousPathProvider = PathProviderPlatform.instance;
PathProviderPlatform.instance = FakePathProvider(tmpRoot);
@@ -47,6 +53,7 @@ void main() {
tearDown(() async {
await db.close();
DownloadStorageService.resetForTesting();
SafStorageService.setOpsForTesting(null);
SettingsService.resetForTesting();
PathProviderPlatform.instance = previousPathProvider;
expect(PathProviderPlatform.instance, same(previousPathProvider));
+6 -10
View File
@@ -457,11 +457,9 @@ void main() {
);
await _drainAsync();
expect(
player.selectedSecondarySubtitle.map((track) => track.id),
['10'],
reason: 'the wait stayed armed, so the late secondary still landed',
);
expect(player.selectedSecondarySubtitle.map((track) => track.id), [
'10',
], reason: 'the wait stayed armed, so the late secondary still landed');
});
test('a sidecar-backed secondary source row resolves against its loaded track', () async {
@@ -508,11 +506,9 @@ void main() {
);
await _drainAsync();
expect(
player.selectedSecondarySubtitle.map((track) => track.id),
['1'],
reason: 'the extracted file is the secondary row, however the two sides label it',
);
expect(player.selectedSecondarySubtitle.map((track) => track.id), [
'1',
], reason: 'the extracted file is the secondary row, however the two sides label it');
});
test('complete metadata-free direct catalog applies tracks without the five-second fallback', () async {
+50
View File
@@ -0,0 +1,50 @@
import 'package:plezy/services/saf_storage_service.dart';
import 'package:saf_util/saf_util_platform_interface.dart';
/// Narrow [SafStorageOperations] fake for suites that only need SAF
/// reachability answers — chiefly "is this downloaded `content://` copy still
/// there", which decides local playback versus streaming.
///
/// Every other operation throws: a suite that reaches one of them wants the
/// richer fake beside `download_manager_service_test.dart`, not this one.
class FakeSafStorage implements SafStorageOperations {
FakeSafStorage({this.reachable = true, this.existing});
/// Answer for every URI when [existing] was not supplied.
final bool reachable;
/// When supplied, the authoritative set of reachable URIs; membership alone
/// decides and [reachable] is ignored.
final Set<String>? existing;
/// URIs passed to [exists], in call order.
final List<String> existsCalls = [];
@override
Future<bool> exists(String uri, {required bool isDir}) async {
existsCalls.add(uri);
return existing?.contains(uri) ?? reachable;
}
@override
Future<SafDocumentFile?> getChild(String parentUri, List<String> names) => throw UnsupportedError('getChild');
@override
Future<String?> createNestedDirectories(String parentUri, List<String> pathComponents) =>
throw UnsupportedError('createNestedDirectories');
@override
Future<bool> delete(String uri, {required bool isDir}) => throw UnsupportedError('delete');
@override
Future<List<SafDocumentFile>?> list(String uri) => throw UnsupportedError('list');
@override
Future<String?> resolvePersistedPermissionUri(String uri) => throw UnsupportedError('resolvePersistedPermissionUri');
@override
Future<List<String>?> getPersistedPermissionUris() => throw UnsupportedError('getPersistedPermissionUris');
@override
Future<bool> releasePersistedPermission(String uri) => throw UnsupportedError('releasePersistedPermission');
}
+1 -1
View File
@@ -1 +1 @@
c9d14e12e35d15b0dc958662e51153291292ea24b08c9bd34825199929ae6041
1cc6e4f1441ea2288512036f46589057eb54228732a27baf2e1419354d173c7c
+1 -1
View File
@@ -1 +1 @@
3.44.0+6
3.47.1
+6
View File
@@ -410,7 +410,10 @@ BuildAppDebug() {
# overwrite kernel_blob.bin and both snapshot blobs below with versions
# from our tvOS engine so the tvOS VM can load them.
(
# Flutter 3.47's tool rejects FLUTTER_BUILD_NAME/NUMBER in the environment;
# they are consumed by this script's plist sync, not by `build bundle`.
cd "$FLUTTER_APPLICATION_PATH" && \
env -u FLUTTER_BUILD_NAME -u FLUTTER_BUILD_NUMBER \
"$FLUTTER_BIN" build bundle \
--asset-dir="$OUTDIR/App.framework/flutter_assets" \
--no-tree-shake-icons \
@@ -568,7 +571,10 @@ BuildAppRelease() {
echo " └─Generate flutter_assets via flutter build bundle (release)"
mkdir -p "$OUTDIR/App.framework/flutter_assets"
(
# Flutter 3.47's tool rejects FLUTTER_BUILD_NAME/NUMBER in the environment;
# they are consumed by this script's plist sync, not by `build bundle`.
cd "$FLUTTER_APPLICATION_PATH" && \
env -u FLUTTER_BUILD_NAME -u FLUTTER_BUILD_NUMBER \
"$FLUTTER_BIN" build bundle \
--release \
--asset-dir="$OUTDIR/App.framework/flutter_assets" \
+4 -4
View File
@@ -20,15 +20,15 @@
# flutter precache --windows
# windows/tool/install-patched-engine.ps1
param(
# Engine zip published at flutter-plezy release windows-v3.44.0+1 - x64 + arm64
# Engine zip published at flutter-plezy release windows-v3.47.1 - x64 + arm64
# (cache dirs windows-{x64,arm64}{,-release}). The asset name is the same across
# tags, so a version bump only changes the tag segment of the URL.
[string]$Url = 'https://github.com/edde746/flutter-plezy/releases/download/windows-v3.44.0+1/flutter-plezy-windows-3.44.0.zip',
[string]$Sha256 = '8de498d28f314c33971226856bea7aa54099e08e60cd7d208cbaf04693dc8274',
[string]$Url = 'https://github.com/edde746/flutter-plezy/releases/download/windows-v3.47.1/flutter-plezy-windows-3.47.1.zip',
[string]$Sha256 = '8ce715978b50cee636bacfca018ad2d5bfc53d6509e2b49c1a167266f2b16877',
# Engine revision the artifacts were built from. Must match the SDK's
# engine.stamp (gen_snapshot/dart in the SDK must come from the same
# checkout), or the swapped binaries are ABI-incompatible with the build.
[string]$ExpectedEngine = '4c525dac5ebe5971c5708ef73558ed8edcf4a362'
[string]$ExpectedEngine = '5d531788691ec3404cac0cee66ead4007b177363'
)
$ErrorActionPreference = 'Stop'
+1 -1
View File
@@ -16,7 +16,7 @@ param(
[switch]$Restore,
# Engine revision these artifacts were built from. Guards against swapping
# into a mismatched SDK (gen_snapshot/dart must come from the same checkout).
[string]$ExpectedEngine = '4c525dac5ebe5971c5708ef73558ed8edcf4a362'
[string]$ExpectedEngine = '5d531788691ec3404cac0cee66ead4007b177363'
)
$ErrorActionPreference = 'Stop'