StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Implement player preload window management and frame thumbnail extraction
David Nashash7d4cb75ebdd8
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 99e464c5..cff9acd8 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -7,45 +7,49 @@ All notable product changes are recorded in this document.### Added- Added an optional Live TV clock overlay with configurable corner placement, size, digital/clean/serif fonts, and System, 12-hour, or 24-hour time formatting.+- Added VOD chapter navigation with timeline markers, chapter selection, and previous/next chapter actions.+- Added adaptive startup bitrate selection using network-class defaults and recent bandwidth measurements.+- Added selectable Classic blue, M3 purple, and Light app themes, with persistent settings and backup/restore support.+- Added persistent VOD audio and subtitle track choices: selections are saved per movie, shared across all episodes in the same series, and used as a global fallback for other VOD titles when a matching track is available; language and label matching survives provider track-ID changes, and explicit subtitle-off choices are preserved.+- Added an opt-in Live TV setting to auto-hide the category sidebar after selection, with Back-button and focus-aware restoration.+- Added VOD category pinning for Movies and Series, with pin-first browsing, Android TV pin controls, and pinned category content shelves on the Home dashboard.+- Added measured frame-rate and stream-bitrate diagnostics for IPTV playback, including MPEG-TS streams that omit these values from their metadata.+- Added portal-backed Stalker VOD search with mixed movie/series results, persisted result IDs, paging, parental/hidden-category filtering, and a Browsing setting to disable it.++### Fixed++- Fixed VOD “More Like This” movie posters opening movie information instead of starting playback directly.+- Fixed native EPG resolution for large channel lineups by chunking program lookups to stay below SQLite bind-variable limits on older Android devices.+- Fixed EPG collisions for channels sharing an EPG identifier by keying resolved guide data by the provider stream ID when available, while preserving legacy EPG-ID fallback queries.+- Fixed grouped VOD browse pagination and infinite scroll by using cursor windows, deduplicating before offset/limit application, and handling zero-timestamp catalog entries consistently.+- Fixed provider configuration decoding after typed-provider migrations that omitted the embedded configuration type, preserving access to existing provider settings and credentials.+- Fixed Stalker compatibility discovery treating every tokenless HTTP 200 response as a rate limit; generic endpoint or recipe responses now continue through fallback discovery.+- Fixed Stalker VOD playback on portals that reject bare movie commands by resolving movie file rows and trying validated `/media/file_<fileId>.mpg` fallback commands while preserving existing playback behavior.+- Fixed Stalker VOD category layout drift by retargeting stale stored category types before synchronization instead of forcing an unnecessary catalog re-download.+- Fixed Stalker guide synchronization continuing through dead per-channel EPG endpoints after both bulk and first per-channel responses are confirmed empty.+- Fixed Stalker channel logos returned as bare or portal-relative paths by resolving them against the portal logo directory, including channels imported before the fix.### Changed- Updated the AndroidX Media3 playback stack from 1.9.2 to 1.11.0:- - Added VOD chapter navigation with timeline markers, chapter selection, and previous/next chapter actions.- - Added adaptive startup bitrate selection using network-class defaults and recent bandwidth measurements.- Improved external subtitle loading and preferred subtitle-language selection, while keeping optional subtitle I/O failures non-fatal to playback.- Updated the bundled FFmpeg decoder artifact to the matching Media3 release.- Inherited playback reliability fixes for decoder recovery and prewarming, codec reuse and flushing, audio-output retries, low-memory load control, and HLS, DASH, and MPEG-TS seeking and timeline handling.- Inherited subtitle timing and parser fixes for TTML and VobSub content.- Inherited compatibility improvements for HLS Content Steering, DASH/HLS metadata, AV1 and Dolby Vision, VVC, Matroska, and MP4 formats when supported by the device.- Reduced unnecessary artwork metadata extraction during playback to lower memory use on TV devices.-- Added selectable Classic blue, M3 purple, and Light app themes, with persistent settings and backup/restore support.- Improved Android TV navigation, focus handling, and Back-button behavior across Live TV, player controls, provider setup, and Settings.- Improved playback quick-action readability by using shared theme-aware content colors across focused and unfocused controls, keeping contrast consistent across all playback buttons.-- Added persistent VOD audio and subtitle track choices: selections are saved per movie, shared across all episodes in the same series, and used as a global fallback for other VOD titles when a matching track is available; language and label matching survives provider track-ID changes, and explicit subtitle-off choices are preserved.-- Added an opt-in Live TV setting to auto-hide the category sidebar after selection, with Back-button and focus-aware restoration.- Improved Live TV control reliability, including timeshift seeking and rewind interactions.- Improved reliability when configuring providers, importing settings, and preserving playback preferences.- Updated Italian translations across the app and feature modules, including previously missing strings and corrected resource ownership.- Improved Stalker EPG synchronization by increasing channel batch sizes from 500 to 5,000, reducing request overhead for large channel lineups while retaining bounded processing.-- Fixed native EPG resolution for large channel lineups by chunking program lookups to stay below SQLite bind-variable limits on older Android devices.-- Fixed EPG collisions for channels sharing an EPG identifier by keying resolved guide data by the provider stream ID when available, while preserving legacy EPG-ID fallback queries.- Reduced storage usage by limiting the shared HTTP cache to 16 MiB and pruning past EPG entries after 12 hours when a provider does not require a longer catch-up window.-- Added VOD category pinning for Movies and Series, with pin-first browsing, Android TV pin controls, and pinned category content shelves on the Home dashboard.- Improved device orientation behavior by allowing portrait rotation on phones and tablets while keeping Android TV and Fire TV interfaces locked to landscape.- Improved grouped VOD deduplication performance by moving movie and series presentation work off the main thread, adding bounded normalization caches, and avoiding unnecessary ICU normalization for ASCII titles.-- Fixed grouped VOD browse pagination and infinite scroll by using cursor windows, deduplicating before offset/limit application, and handling zero-timestamp catalog entries consistently.-- Fixed provider configuration decoding after typed-provider migrations that omitted the embedded configuration type, preserving access to existing provider settings and credentials.-- Added measured frame-rate and stream-bitrate diagnostics for IPTV playback, including MPEG-TS streams that omit these values from their metadata.- Improved Stalker authentication resilience by stopping repeated handshakes after explicit soft-throttle signals, reusing short-lived encrypted sessions across provider instances and process restarts, and restoring session cookies for resumed API requests.-- Fixed Stalker compatibility discovery treating every tokenless HTTP 200 response as a rate limit; generic endpoint or recipe responses now continue through fallback discovery.-- Fixed Stalker VOD playback on portals that reject bare movie commands by resolving movie file rows and trying validated `/media/file_<fileId>.mpg` fallback commands while preserving existing playback behavior.-- Fixed Stalker VOD category layout drift by retargeting stale stored category types before synchronization instead of forcing an unnecessary catalog re-download.- Improved Stalker on-demand guide loading by preferring numeric short-EPG lookups, pacing prefetch requests, and publishing guide results in bounded chunks.- Reduced repeated empty Stalker guide requests by sharing provider-scoped, expiring empty-key cache state between the Guide and Home now-playing fallbacks.-- Fixed Stalker guide synchronization continuing through dead per-channel EPG endpoints after both bulk and first per-channel responses are confirmed empty.-- Fixed Stalker channel logos returned as bare or portal-relative paths by resolving them against the portal logo directory, including channels imported before the fix.-- Added portal-backed Stalker VOD search with mixed movie/series results, persisted result IDs, paging, parental/hidden-category filtering, and a Browsing setting to disable it.- Improved new Stalker provider onboarding by importing a capped live preview and category shells first, then scheduling a generation-aware background sync for the complete catalog and guide.## [1.0.17]diff --git a/docs/superpowers/plans/2026-09-13-frame-extractor-thumbnail-pilot.md b/docs/superpowers/plans/2026-09-13-frame-extractor-thumbnail-pilot.mdindex aad6b0b0..d0233610 100644--- a/docs/superpowers/plans/2026-09-13-frame-extractor-thumbnail-pilot.md+++ b/docs/superpowers/plans/2026-09-13-frame-extractor-thumbnail-pilot.md@@ -31,7 +31,7 @@## Implementation Steps-- [ ] **Step 1: Add the player-side thumbnail extraction contract and VOD request context.**+- [x] **Step 1: Add the player-side thumbnail extraction contract and VOD request context.****Files:**@@ -56,7 +56,7 @@**Tests:** Verify that the request carries stream metadata and explicit live/VOD state without introducing a Media3 dependency into feature code.-- [ ] **Step 2: Refactor `PlayerMediaSourceFactory` so the same media-source rules can be supplied to `FrameExtractor`.**+- [x] **Step 2: Refactor `PlayerMediaSourceFactory` so the same media-source rules can be supplied to `FrameExtractor`.****Files:**@@ -75,7 +75,7 @@**Tests:** Confirm existing media-source tests still pass and add assertions that the reusable factory receives the expected resolved type, preload mode, and media item URI/media ID. Keep the MPEG-TS playback policy tests intact.-- [ ] **Step 3: Add the Media3 `FrameExtractor` implementation and dependency.**+- [x] **Step 3: Add the Media3 `FrameExtractor` implementation and dependency.****Files:**@@ -108,7 +108,7 @@- Test extraction failure, timeout, and coroutine cancellation return `null` and release/cancel the extractor operation. Use a small injectable test seam for the future/session boundary if direct `FrameExtractor` construction cannot be exercised in a JVM test.- Do not make JVM tests depend on a real provider URL or a decoder installed on the developer machine.-- [ ] **Step 4: Turn `PlayerThumbnailCoordinator` into the Media3-first/legacy-fallback selector.**+- [x] **Step 4: Turn `PlayerThumbnailCoordinator` into the Media3-first/legacy-fallback selector.****Files:**@@ -142,7 +142,7 @@**Tests:** Verify Media3 success prevents a legacy call, Media3 unsupported/failure invokes legacy when supported, neither backend returns `null`, and cache clearing reaches both implementations. Verify the current URL and stream metadata are forwarded correctly.-- [ ] **Step 5: Connect the coordinator to seek preview and thumbnail preloading without changing UI behavior.**+- [x] **Step 5: Connect the coordinator to seek preview and thumbnail preloading without changing UI behavior.****Files:**@@ -159,7 +159,7 @@**Tests:** Retain the existing preload-position and preload-key tests. Add coverage that VOD calls use the resolved stream metadata, live calls do not start extraction, and a late Media3 result cannot overwrite a newer seek-preview request.-- [ ] **Step 6: Verify module boundaries, build output, and fallback behavior.**+- [x] **Step 6: Verify module boundaries, build output, and fallback behavior.****Commands:**diff --git a/docs/superpowers/plans/2026-09-13-vod-sliding-window-preloading.md b/docs/superpowers/plans/2026-09-13-vod-sliding-window-preloading.mdnew file mode 100644index 00000000..09e3723d--- /dev/null+++ b/docs/superpowers/plans/2026-09-13-vod-sliding-window-preloading.md@@ -0,0 +1,321 @@+# VOD Sliding-Window Preloading Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Add a bounded Media3 `DefaultPreloadManager` path for non-live VOD/series-episode and catch-up navigation, while preserving direct playback and the existing guarded single-item live preload path.++**Architecture:** Keep Media3 preload details inside `:player` and expose a small `PlayerEngine` preload-window contract to `:feature:playback`. The feature layer selects and resolves adjacent candidates; the player layer creates per-item media sources with the existing custom data-source provider, ranks them with `SimpleRankingDataComparator`, and returns a managed `MediaSource` when playback switches to an item that was preloaded. The manager is recreated together with the player so every returned source is consumed by an `ExoPlayer` created from the same `DefaultPreloadManager.Builder`.++**Tech Stack:** Kotlin, AndroidX Media3 1.11.0 `DefaultPreloadManager`, `SimpleRankingDataComparator`, `TargetPreloadStatusControl`, custom OkHttp-backed `DataSource.Factory`, Media3 `MediaSource`, coroutines, Hilt, JUnit/Truth/Mockito, Robolectric, Android TV device validation.++**Spec:** `docs/upgrade.txt`, the `ADD (P2) - VOD/episode sliding-window preloading` item and the remaining-backlog instruction to design and test VOD-only preloading before replacing the current single-source path.++## Global Constraints++- Scope is this one upgrade item only. Do not implement custom adaptive variant ordering, Media3 Cast migration, explicit playlist progression, or embedded-subtitle recovery.+- Work directly on the current `develop` worktree. Preserve unrelated existing changes, including the current `docs/CHANGELOG.md` edit and the completed FrameExtractor pilot changes.+- The new manager is opt-in by content policy: normal `LIVE` channel playback is never added to the sliding window. The existing `PlayerEngine.preload(StreamInfo?)` behavior remains available for the guarded adjacent-channel zap path and recovery code.+- The initial window is at most three managed items: the current item, one previous item, and one next item. At most two non-current items may cause preload I/O. Do not preload the entire series, category, or EPG history.+- The initial target status for each adjacent item is `DefaultPreloadManager.PreloadStatus.specifiedRangeLoaded(0L, 3_000L)`. The current item and all items outside the one-item distance are returned as `null` by the target status control. Do not configure persistent disk caching in this pilot.+- VOD/series-episode and catch-up candidates must be resolved through existing feature/provider code and must retain headers, user-agent, proxy, TLS policy, transport policy, container metadata, DRM metadata, and expiration information. Candidate resolution or preload failure only removes that candidate; it must never fail foreground playback.+- Do not preload a candidate with a blank/invalid URL, an expired `StreamInfo`, `PlayerPreloadContentType.LIVE`, an unknown stream type, or DRM during the initial pilot. DRM stays on the normal direct-playback path because early license acquisition has side effects and a separate cost profile.+- Use the existing `PlayerDataSourceFactoryProvider.createFactory(..., preload = true)` for every preload source. Preload transfers must not attach the foreground transfer listeners used for measured playback bitrate and statistics.+- Media3 preload APIs are `@UnstableApi`; keep the `@OptIn` localized to `:player`. `:feature:playback` must continue to depend only on `PlayerEngine` and player-domain preload value types, never on `androidx.media3` classes.+- All `DefaultPreloadManager` calls, source reconciliation, and manager release happen on the same engine/main thread. A released manager or builder must never be reused.+- Keep URLs and request metadata sanitized in logs. Log only candidate kind/key, resolved stream class, rank/distance, source count, skip/failure category, preload completion, and playback-source reuse.+- Keep direct playback as the fallback whenever a candidate is not managed, has expired, has changed identity, or the manager cannot return a source. The current `PreloadCoordinator` remains responsible for the legacy single-source path.++## Existing Code to Preserve++- `player/src/main/java/com/streamvault/player/playback/PreloadCoordinator.kt` remains the compatibility cache for the existing single-item `preload(StreamInfo?)` API, especially live zapping and recovery.+- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerZapActions.kt` keeps its current connection-limit/cooldown checks and adjacent live-channel behavior. It must not be silently migrated to the VOD window.+- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerRecoveryActions.kt` continues to clear preload state through `preload(null)`; the new implementation must make that clear both the legacy cache and the window manager.+- `player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt` remains the source of custom headers, user-agent handling, timeout profiles, proxy/TLS behavior, and foreground-transfer exclusion.+- `player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt` remains the source of HLS, DASH, Smooth Streaming, progressive, MPEG-TS, RTSP, DRM, extractor, retry-policy, and subtitle-format decisions.+- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerContentResolver.kt` remains the feature boundary for resolving episode/VOD and provider playback metadata.+- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerEpgCoordinator.kt` and `PlayerGuideTimelineCoordinator.kt` remain responsible for fetching and projecting the EPG timeline used by catch-up selection.+- `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerAutoPlayActions.kt` keeps the existing ten-second next-episode countdown and auto-play preference behavior. Preloading must not auto-start or change that UI flow.++## Implementation Steps++- [x] **Step 1: Define the player-boundary preload-window contract and deterministic window policy.**++ **Files:**++ - Add `player/src/main/java/com/streamvault/player/PlayerPreload.kt`.+ - Modify `player/src/main/java/com/streamvault/player/PlayerEngine.kt`.+ - Add `player/src/test/java/com/streamvault/player/PlayerPreloadWindowPolicyTest.kt`.++ **Changes:**++ - Define the Media3-free value types:++ ```kotlin+ enum class PlayerPreloadContentType { VOD, CATCH_UP, LIVE }++ data class PlayerPreloadItem(+ val key: String,+ val streamInfo: StreamInfo,+ val contentType: PlayerPreloadContentType+ )++ data class PlayerPreloadWindow(+ val items: List<PlayerPreloadItem>,+ val currentIndex: Int+ )+ ```++ - Add default-safe methods to `PlayerEngine` so existing test doubles and auxiliary engines remain source-compatible:++ ```kotlin+ fun preloadWindow(window: PlayerPreloadWindow) {}+ fun clearPreloadWindow() = preload(null)+ ```++ - Add a pure `normalizePlayerPreloadWindow(window, maxManagedItems = 3)` helper. It must trim blank keys/URLs, remove duplicate keys while retaining the first occurrence, reject `LIVE` items, keep the current item when its index is valid, and retain only the closest previous/next entries around the current item.+ - Keep the current index meaningful after filtering. If the requested current item is removed, return an empty window instead of silently treating an adjacent candidate as current.+ - Do not make `PlayerPreloadItem` contain Media3 `MediaItem`, `MediaSource`, `Uri`, or `DataSource` values.++ **Tests:**++ - A three-item `[previous, current, next]` window remains unchanged and indexes current correctly.+ - Four or more candidates are reduced to current plus one item on each side.+ - Duplicate keys retain the first item and the current index is adjusted.+ - Live candidates, blank keys, blank URLs, and an invalid current index produce the documented filtered/empty result.+ - A VOD item and a catch-up item remain eligible even when their underlying Media3 stream class is HLS or DASH.++- [x] **Step 2: Add the Media3 manager session with ranking, target status, reconciliation, and source lookup.**++ **Files:**++ - Add `player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt`.+ - Add `player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.kt`.++ **Required production surface:**++ ```kotlin+ @UnstableApi+ internal class Media3PreloadWindowManager(+ private val context: Context,+ private val mediaSourceFactory: PlayerMediaSourceFactory,+ private val dataSourceFactoryProvider: PlayerDataSourceFactoryProvider,+ private val bandwidthMeter: BandwidthMeter+ ) {+ fun createPlayer(+ renderersFactory: RenderersFactory,+ loadControl: LoadControl,+ preloadDataSourceFactory: DataSource.Factory,+ configure: (ExoPlayer.Builder) -> Unit+ ): ExoPlayer++ fun updateWindow(window: PlayerPreloadWindow)+ fun getMediaSource(streamInfo: StreamInfo): MediaSource?+ fun clearWindow()+ fun release()+ }+ ```++ **Changes:**++ - In `createPlayer`, construct one `DefaultPreloadManager.SimpleRankingDataComparator` and one `TargetPreloadStatusControl<Int, DefaultPreloadManager.PreloadStatus>`.+ - Return `specifiedRangeLoaded(0L, 3_000L)` only when the ranking index is exactly one position away from the current index. Return `null` for the current item, unset current index, or any item farther away.+ - Build `DefaultPreloadManager.Builder(context, rankingComparator, targetStatusControl)`, call `setDataSourceFactory(preloadDataSourceFactory)`, set the same renderers factory/load control/bandwidth meter used by foreground playback, build the manager, then create the foreground `ExoPlayer` with `builder.buildExoPlayer(ExoPlayer.Builder(...).apply(configure))`.+ - Do not create an independent foreground `ExoPlayer` with `.build()` after a preload manager has been created. The manager-returned sources must be played only by the player created from this builder.+ - `updateWindow` must call the Step 1 normalization policy, set the manager’s current index through `setCurrentPlayingIndex`, and reconcile by key/media identity rather than blindly calling `reset()` on every update. Keep an existing current source alive when it remains in the new window; remove only stale/changed entries with `removeMediaItems` or `remove`.+ - For each new item, resolve its stream type with `buildPlaybackPreparationPlan(..., preload = true)`, create its source through `PlayerMediaSourceFactory.create(..., preload = true)`, and add it with `add(mediaSource, rankingIndex)` or `addMediaSources` using its list index as ranking data.+ - Use the per-item source path so each candidate retains its own custom request properties. Also pass the preload-scoped factory from `PlayerDataSourceFactoryProvider` into `DefaultPreloadManager.Builder.setDataSourceFactory` as the manager/player factory fallback. When no stream is known yet (for example, a render surface is bound before playback), use a non-foreground fallback factory; actual managed candidates must still be created with the per-item `preload = true` provider path.+ - Store a map from the stable `PlayerPreloadItem.key` and the factory’s media identity to the managed `MediaItem`. `getMediaSource(streamInfo)` must return the manager’s source for the exact matching media identity, or `null` when no managed source exists.+ - `clearWindow` must remove/release all managed sources without releasing the foreground player. `release` must release the `DefaultPreloadManager`, clear maps, and make all later methods no-ops or safe failures.+ - Attach a `PreloadManagerListener` for sanitized completion/error logs. A preload error removes only that candidate and never emits a foreground `PlayerError`.++ **Tests:**++ - Verify target status is `null` for current/far items and three seconds loaded for adjacent items.+ - Verify `SimpleRankingDataComparator` is updated when the current index moves and the nearer candidate is ranked first.+ - Verify reconciliation retains the current source, removes stale candidates, replaces changed stream identity, and never exceeds three managed items.+ - Verify live candidates are rejected before any Media3 source is created.+ - Verify sources are created with `preload = true`, the configured `setDataSourceFactory` receives the preload factory, and the foreground transfer listener is not attached to preload data sources.+ - Verify a missing manager source returns `null` so the caller can create a direct source, and verify release/clear calls do not throw.+ - Use an injectable/fake manager seam for deterministic JVM tests where real Media3 preload threads are not suitable; keep one Robolectric construction test for the 1.11 API wiring.++- [x] **Step 3: Integrate manager lifecycle and managed-source reuse into `Media3PlayerEngine`.**++ **Files:**++ - Modify `player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt`.+ - Extend `player/src/test/java/com/streamvault/player/PlayerEngineFeatureConfigurationTest.kt` or add `player/src/test/java/com/streamvault/player/Media3PlayerEnginePreloadTest.kt`.+ - Extend `player/src/test/java/com/streamvault/player/playback/PreloadCoordinatorTest.kt` only for the unchanged legacy-path contract.++ **Changes:**++ - Replace the single `preloadCoordinator` field arrangement with the existing `PreloadCoordinator` plus a nullable `Media3PreloadWindowManager` session and a stored, data-only pending window for calls made before the player exists.+ - In `createPlayer`, build the current `DefaultLoadControl` and renderers exactly as today, create the manager session, and create the foreground player through `Media3PreloadWindowManager.createPlayer`. Preserve all current audio/video renderer customization, analytics listeners, live-speed control, seek increments, audio attributes, surface behavior, and MediaSession setup.+ - Derive `preloadDataSourceFactory` from the current `lastStreamInfo` with `PlayerDataSourceFactoryProvider.createFactory(..., preload = true)` when possible. If a player is created before any stream is known, pass a non-foreground fallback factory and rely on per-item source creation for later windows.+ - In `preloadWindow`, normalize and store the request if the manager session does not yet exist; otherwise update the manager immediately. Clear the legacy single-item cache when a VOD/catch-up window is accepted so stale live-zap data cannot be reused for a different content class.+ - In `prepareInternal`, look up a managed source by the exact current `StreamInfo` before trying `PreloadCoordinator.tryReuse`. If no managed source exists, preserve the existing direct factory path. Keep `preloadCoordinator.onPlaybackStarted(mediaId)` for its existing invalidation semantics.+ - When `preload(null)` is called, clear both the legacy coordinator and the sliding window. This preserves the behavior required by live recovery and channel changes.+ - When `recreatePlayer` or `resetEngineState` releases the current `ExoPlayer`, release the manager session and never reuse a `MediaSource` created by the old session. Retain only the data-only pending window if it is safe to re-add after a new player session; otherwise clear it and let the feature refresh after `READY`.+ - Preserve manager/source lifecycle across content switches without clearing the window before a next-episode or catch-up candidate can be consumed. Clear the old window only when the new content class is ineligible or when the feature submits a replacement window.+ - Add logs distinguishing `preload-window accepted`, `preload-window skipped`, `preload-source reused`, and `preload-source direct-fallback`, with sanitized identity fields.++ **Tests:**++ - A matching managed VOD/catch-up item is selected before direct source creation.+ - A changed URL, headers/DRM identity, expired item, or absent manager source uses the direct source path.+ - `preload(null)` clears both paths.+ - Recreating/resetting the engine releases the manager and does not return an old-session source.+ - Existing live `preload(StreamInfo)` behavior and live recovery clearing remain unchanged.+ - Existing player configuration tests continue to verify decoder, surface, audio-focus, buffer, and MediaSession behavior.++- [x] **Step 4: Add deterministic episode and catch-up candidate selection in `:feature:playback`.**++ **Files:**++ - Add `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupport.kt`.+ - Add `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinator.kt`.+ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerEpisodePlaybackSupport.kt`.+ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerProgramTimelineSupport.kt`.+ - Add `feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupportTest.kt`.+ - Add `feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinatorTest.kt`.++ **Changes:**++ - Add pure episode helpers that flatten sanitized series seasons in season/episode order and return previous/current/next entries across season boundaries. Keep `findNextEpisode` behavior unchanged and add `findPreviousEpisode` plus a bounded `buildEpisodeWindow` helper.+ - Add pure catch-up helpers that sort programs by start time, locate the selected program, and return the closest previous/next programs that are archive-playable for the current channel. Keep the existing EPG history/upcoming limits; do not query a second unbounded EPG list just for preloading.+ - Generate stable, sanitized keys such as `episode:<providerId>:<playbackEpisodeIdentity>` and `catchup:<providerId>:<channelId>:<startTime>:<endTime>`. Keys must not contain complete signed URLs, credentials, or headers.+ - `PlayerPreloadWindowCoordinator` must expose these exact operations:++ ```kotlin+ suspend fun buildEpisodeWindow(+ current: PlayerPreloadItem,+ series: Series,+ currentEpisode: Episode,+ providerId: Long,+ isCurrent: () -> Boolean+ ): PlayerPreloadWindow?++ suspend fun buildCatchUpWindow(+ current: PlayerPreloadItem,+ selectedProgram: Program,+ channel: Channel,+ timelinePrograms: List<Program>,+ providerId: Long,+ isCurrent: () -> Boolean+ ): PlayerPreloadWindow?+ ```++ - Use the already resolved current `StreamInfo` as the current item. Resolve adjacent episode streams through `PlayerContentResolver.resolvePlaybackStream` with `ContentType.SERIES_EPISODE`; resolve catch-up URLs through `PlayerProviderCoordinator.buildCatchUpUrls`, then pass each candidate through the shared playback resolver so custom provider metadata is retained.+ - Add a no-player-mutation helper to `PlayerPreparationCoordinator` named `prepareStreamForPreload(streamInfo: StreamInfo): StreamInfo?`. It may run the existing `PlaybackStreamPreparer`, must reject expired results, must not call `PlayerEngine.prepare`, and must not perform the foreground probe-before-playback step.+ - For a candidate with multiple catch-up URL variants, attempt them in provider order until one resolves; keep alternate URLs only in the normal playback/recovery path. The window contains one candidate per adjacent program.+ - Return `null` when the current item or required provider/channel context is unavailable. Skip individual unresolved neighbors, preserve order, and never fail the current playback session because a neighbor cannot be resolved.+ - Do not invent an ordering for standalone movies or generic VOD rows when the caller has no explicit ordered queue. The player contract supports future VOD queues, but this first integration covers the existing ordered series-episode and catch-up flows.++ **Tests:**++ - Episode selection covers same-season, cross-season, first-episode, and last-episode cases.+ - Catch-up selection returns chronological previous/next programs, excludes non-archive-playable programs, and handles a missing selected program.+ - Resolution preserves headers, user-agent, proxy/TLS/transport fields, stream type, DRM metadata where applicable to direct resolution, and expiration time.+ - Resolver failures skip only the failed neighbor; a current-only window remains valid.+ - Cancellation/stale-session checks stop candidate resolution and prevent a stale window from being returned.+ - Feature tests contain no Media3 imports and `verifyFeaturePlaybackBoundary` remains clean.++- [x] **Step 5: Connect window refreshes to episode and catch-up playback without changing UI behavior.**++ **Files:**++ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt`.+ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinator.kt`.+ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerAutoPlayActions.kt`.+ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerCatchUpActions.kt`.+ - Modify `feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerGuideTimelineCoordinator.kt` only if a bounded ordered timeline snapshot is needed by the pure catch-up helper.+ - Extend `feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerCatchUpActionsTest.kt` and add focused ViewModel/coordinator interaction tests using a fake `PlayerEngine`.++ **Changes:**++ - Inject `PlayerPreloadWindowCoordinator` into `PlayerViewModel`.+ - Add a private `refreshPreloadWindow(requestVersion: Long)` that launches in the current playback session, snapshots the current resolved stream/context, builds an episode or catch-up window, checks `isActivePlaybackSession(requestVersion)`, and calls `playerEngine.preloadWindow(window)`.+ - Trigger refresh after the player has successfully prepared the current non-live item and after asynchronous series context resolution completes. Use a fingerprint of current key plus neighboring keys/stream identities to avoid duplicate network resolution and repeated manager reconciliation.+ - In `playCatchUp(program)`, store the selected `Program` in the playback context before starting candidate playback. Clear it when leaving catch-up or starting a new unrelated content session. This is required because `currentProgram` represents live wall-clock time and is not necessarily the program selected for replay.+ - Build the catch-up timeline from the existing bounded guide snapshot (`programHistory`, `currentProgram`, and `upcomingPrograms`) and the selected program. Do not change guide refresh cadence or visible history/upcoming limits.+ - Keep `PlayerAutoPlayActions`’s completion persistence, watched-state refresh, countdown, cancel action, and `playEpisode` call unchanged. The next episode should consume the manager source opportunistically through `PlayerEngine.prepare`; if unavailable, it continues through the existing direct path.+ - Clear the window when playback changes to ordinary live TV, when the catch-up context is abandoned, and during final lifecycle cleanup. Do not clear it at the beginning of every session, because that would discard the preloaded next episode before it is consumed.+ - Keep thumbnail preloading separate. `startThumbnailPreload()` remains its current six-position image-preview path and must not call the video preload manager.++ **Tests:**++ - A ready series episode requests current/previous/next candidates once and sends the expected current index.+ - A last episode sends a current-only window and does not attempt an out-of-range next episode.+ - Catch-up selection stores the selected program, resolves adjacent replay candidates, and clears the window when returning to live.+ - A stale session or newer playback request prevents a completed resolver job from updating the active engine.+ - `playNextEpisodeNow()` and automatic countdown still call the existing `playEpisode` path and do not add a second auto-play transition.+ - Live channel changes still call the legacy clear/single-item path and never send a live item to `preloadWindow`.++- [x] **Step 6: Add observability and verify the module/build contracts.**++ **Files:**++ - Extend the player preload tests and feature coordinator tests from Steps 2–5.+ - Modify `docs/upgrade.txt` only after implementation evidence exists; keep the item marked as an active pilot until the device gate in Step 7 passes.++ **Required diagnostics:**++ - Count window submissions, accepted item count, skipped live/DRM/expired/invalid count, candidate resolution failures, manager preload completions/errors, managed-source reuse, direct fallback, manager resets, and manager recreation.+ - Include content kind and resolved stream class. Include stable candidate keys only; sanitize URL-like values with `PlaybackLogSanitizer` and never log headers/cookies/tokens.+ - Keep preloading out of foreground bitrate accounting. Verify the foreground `PlayerTransferByteCounter` and its measured bitrate do not include preload bytes.++ **Commands:**++ ```powershell+ .\gradlew.bat :player:testDebugUnitTest --tests "com.streamvault.player.*Preload*" --tests "com.streamvault.player.playback.*Preload*" --no-daemon --console=plain+ .\gradlew.bat :feature:playback:testDebugUnitTest --tests "com.streamvault.feature.playback.player.*Preload*" --tests "com.streamvault.feature.playback.player.PlayerCatchUpActionsTest" --no-daemon --console=plain+ .\gradlew.bat :player:compileDebugKotlin :feature:playback:compileDebugKotlin verifyFeaturePlaybackBoundary --no-daemon --console=plain+ .\gradlew.bat :player:testDebugUnitTest :feature:playback:testDebugUnitTest :app:testDebugUnitTest --no-daemon --console=plain+ .\gradlew.bat :app:assembleDebug --no-daemon --console=plain+ git diff --check+ ```++ **Expected results:**++ - All focused and module unit tests pass.+ - `verifyFeaturePlaybackBoundary` reports no Media3 reference from `:feature:playback`.+ - The app compiles with Media3 1.11.0’s `DefaultPreloadManager` API and no deprecated preload-manager calls.+ - The debug APK assembles successfully.+ - `git diff --check` reports no whitespace errors and the diff contains only the planned player/feature tests, implementation files, and the eventual upgrade-audit update.++- [ ] **Step 7: Run the device/content pilot and make the keep/remove decision.**++ **Validation matrix:**++ - One series with at least three playable episodes, including a cross-season boundary if available.+ - One provider-backed episode whose resolved playback requires custom headers, user-agent, proxy, TLS, or transport policy.+ - One catch-up channel with at least three adjacent archive-playable EPG programs.+ - One standalone movie/VOD item to confirm no invented ordering and unchanged direct playback.+ - The affected Android TV/device/content combination if it is non-live and non-DRM.++ **For each applicable item:**++ - Capture logs from window submission through the first foreground frame for current playback, next/previous selection, manager source reuse, and direct fallback.+ - Confirm the manager never reports more than three managed sources and never starts for ordinary live-channel playback.+ - Compare the source-reuse path with a controlled direct-playback run of the same item. Record time to `READY`, time to first rendered frame, preload completion/error, and whether the resolved request shape matches the direct baseline.+ - Exercise next episode, previous/next catch-up selection, rapid content switching, recovery/error handling, app background/foreground, engine recreation, and final release.+ - Confirm no preload request changes foreground measured bitrate, decoder selection, subtitle/track behavior, proxy/TLS behavior, or playback history.++ **Acceptance gate before removing or weakening the legacy path:**++ - All eligible series-episode and catch-up cases either reuse a managed source or cleanly fall back to direct playback with no user-visible error.+ - No eligible window exceeds three managed items or two adjacent preload transfers.+ - No ordinary live channel is added to the window manager.+ - Manager lifecycle survives content switches, engine recreation, cancellation, and release without leaked threads, stale source reuse, or foreground playback errors.+ - Median and p95 start-to-ready/first-frame latency do not regress against the direct baseline on the same device/content sample. Record the measured threshold and sample size in the audit.+ - Custom headers, proxy/TLS/transport policy, URL renewal, DRM exclusion, track selection, and foreground transfer accounting remain correct.+ - Logs are sanitized and sufficient to distinguish manager reuse, successful preload with direct fallback, skipped candidate, and manager failure.++ **Documentation:** Update the second `ADD` item in `docs/upgrade.txt` with the implementation state, window cap, supported candidate sources, device/content matrix, measured latency, fallback/error counts, and the decision to retain or remove the legacy single-source path. Do not mark the item `DONE` until the acceptance gate is met.++## Reference++Media3’s official documentation states that `DefaultPreloadManager` ranks one-dimensional media items by distance from the current playing index, queries a `TargetPreloadStatusControl` for the amount to load, returns managed `MediaSource` instances for playback, and requires the returned source to be played by an `ExoPlayer` created from the same builder. The relevant APIs are [DefaultPreloadManager](https://developer.android.com/reference/androidx/media3/exoplayer/source/preload/DefaultPreloadManager), [DefaultPreloadManager.Builder](https://developer.android.com/reference/androidx/media3/exoplayer/source/preload/DefaultPreloadManager.Builder), [preload-manager concepts](https://developer.android.com/media/media3/exoplayer/preloading-media/preloadmanager/concepts), [create/configure](https://developer.android.com/media/media3/exoplayer/preloading-media/preloadmanager/create), and [manage/play](https://developer.android.com/media/media3/exoplayer/preloading-media/preloadmanager/manage-play).++## Completion Definition++The implementation is complete only when Steps 1–6 are implemented and verified, Step 7 has real device/content evidence, and `docs/upgrade.txt` records the supported scope and keep/remove decision. Until then, the existing single-item coordinator remains in place as the live/recovery compatibility path and direct playback remains the fallback for every preload miss.diff --git a/docs/upgrade.txt b/docs/upgrade.txtindex 67c49ab1..7f0d7857 100644--- a/docs/upgrade.txt+++ b/docs/upgrade.txt@@ -39,7 +39,7 @@ These items are complete and should not remain in the pending migration list:### Existing app functions worth evaluating against 1.10 APIs- DONE - Preferred subtitle-language selection. Media3 text-selection parameters now use the saved VOD subtitle language as the automatic fallback (`preferredTextLanguage` plus `selectTextByDefault`), while the app-owned persisted track ID/label resolver remains authoritative when it can match a track and explicit disabled choices remain disabled.-- ADD - Media3 `FrameExtractor` pilot for VOD seek thumbnails. Media3 1.10 moved this API to the `media3-inspector-frame` module. The current `SeekThumbnailProvider` uses Android `MediaMetadataRetriever`, can block on remote URLs, and excludes HLS/DASH. Pilot behind the existing provider interface; do not remove the current implementation until device coverage and performance are proven.+- ADD - Media3 `FrameExtractor` pilot for VOD seek thumbnails. Media3 1.10 moved this API to the `media3-inspector-frame` module. The current `SeekThumbnailProvider` uses Android `MediaMetadataRetriever`, can block on remote URLs, and excludes HLS/DASH. Pilot implementation is now behind the existing provider interface: Media3 is first for supported non-live, non-DRM VOD, with the current provider retained as a fallback. Player/feature tests, the dependency boundary, app Hilt wiring, and a debug APK build pass. Emulator smoke playback remains healthy, but the controlled device/content latency matrix is still pending; do not remove the legacy implementation yet.- WATCH - `DefaultPreloadManager.Builder.setDataSourceFactory`. This is useful only if the app adopts Media3's preload manager; it allows the app's custom headers, timeouts, and proxy behavior to be reused by preloading.### 1.10 APIs that should not replace current code@@ -64,7 +64,7 @@ These items are complete and should not remain in the pending migration list:- DONE (P1) - VOD chapter navigation. Media3 `Chapter` metadata is normalized into the player boundary, exposed as chapter state, and surfaced in the new video-first VOD overlay with timeline markers, chapter sheet selection, and previous/next chapter actions. Live and catch-up overlays remain on their existing path; chapter actions are hidden while Cast is connected.- DONE - Adaptive startup bitrate. `DefaultBandwidthMeter.InitialBitrateSupplier` now uses Media3's network-class defaults when no history exists, or a discounted/capped estimate from the previous provider measurement when the player is recreated. The bandwidth meter is wired into the existing foreground data-source transfer listener and resets on network changes; user quality settings are unchanged.-- ADD (P2) - VOD/episode sliding-window preloading. Extend the current single-item `PreloadCoordinator` with `DefaultPreloadManager` and `SimpleRankingDataComparator` for next/previous VOD or catch-up items. Use the app's custom data source factory, cap the window, and do not preload live channels by default because of bandwidth and memory cost.+- ADD (P2) - VOD/episode sliding-window preloading — IMPLEMENTED PILOT. `DefaultPreloadManager` with `SimpleRankingDataComparator` now manages a maximum of three current/adjacent series-episode or catch-up candidates. Candidates use the app's preload-scoped data source path, preserve resolved provider metadata, skip live/DRM/expired/unsupported entries, and fall back to direct playback on a miss. The feature layer refreshes after `READY` and asynchronous episode/channel context resolution, fingerprints unchanged windows, guards stale sessions, and keeps the existing legacy single-item path for ordinary live zapping and recovery. Player/feature/app unit tests, the feature boundary check, and a debug APK build pass. The real-device/content latency, request-shape, lifecycle, and foreground-transfer-accounting matrix is still pending; do not remove the legacy path until that gate passes.- WATCH (P2) - Custom adaptive variant ordering. Media3 now exposes `Format.selectionPriority` and `AdaptiveTrackSelection.Factory.setTrackFormatComparator`. The default HLS `SCORE` mapping is already automatic; add a custom comparator only after telemetry shows provider scores or user quality preferences need different ordering.- WATCH (P3) - Explicit per-stream media progression. `ExoPlayer.Builder.enablePerStreamMediaProgression()` can reduce transitions between queued short items, but the app normally replaces one media source at a time rather than playing a Media3 playlist. Do not enable it globally yet.diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerCatchUpActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerCatchUpActions.ktindex 72f34c2a..5a9332ac 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerCatchUpActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerCatchUpActions.kt@@ -143,6 +143,7 @@ fun PlayerViewModel.playCatchUp(program: Program) {}if (!isActivePlaybackSession(requestVersion)) return@launchif (catchUpUrls.isNotEmpty()) {+ playerPlaybackContextCoordinator.storeSelectedCatchUpProgram(program)startCatchUpPlayback(urls = catchUpUrls,title = "${channel.name}: ${program.title}",diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerEpisodePlaybackSupport.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerEpisodePlaybackSupport.ktindex 82c7c0ec..50ba00e1 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerEpisodePlaybackSupport.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerEpisodePlaybackSupport.kt@@ -21,10 +21,7 @@ internal fun resolveEpisode(}internal fun findNextEpisode(series: Series, episode: Episode): Episode? {- val orderedEpisodes = series.seasons- .sanitizedForPlayer()- .sortedBy { it.seasonNumber }- .flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }+ val orderedEpisodes = orderedEpisodesForPlayer(series)val currentIndex = orderedEpisodes.indexOfFirst {it.id == episode.id ||it.playbackEpisodeIdentity() == episode.playbackEpisodeIdentity() ||@@ -33,6 +30,21 @@ internal fun findNextEpisode(series: Series, episode: Episode): Episode? {return orderedEpisodes.getOrNull(currentIndex + 1)}+internal fun findPreviousEpisode(series: Series, episode: Episode): Episode? {+ val orderedEpisodes = orderedEpisodesForPlayer(series)+ val currentIndex = orderedEpisodes.indexOfFirst {+ it.id == episode.id ||+ it.playbackEpisodeIdentity() == episode.playbackEpisodeIdentity() ||+ (it.seasonNumber == episode.seasonNumber && it.episodeNumber == episode.episodeNumber)+ }+ return orderedEpisodes.getOrNull(currentIndex - 1)+}++internal fun orderedEpisodesForPlayer(series: Series): List<Episode> = series.seasons+ .sanitizedForPlayer()+ .sortedBy { it.seasonNumber }+ .flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }+internal fun Episode.playbackEpisodeIdentity(): Long =episodeId.takeIf { it > 0L } ?: id@@ -50,4 +62,4 @@ internal fun Episode.matchesPlaybackEpisode(}internal fun buildEpisodePlaybackTitle(episode: Episode): String =- "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}"\ No newline at end of file+ "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}"diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.ktindex d73cd481..905e74b1 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt@@ -132,6 +132,8 @@ fun PlayerViewModel.onAppForegrounded() {fun PlayerViewModel.onPlayerScreenDisposed(): Job? {val progressFlush = queueForcedProgressFlush()+ clearPreloadWindow()+ playerPlaybackContextCoordinator.clearSelectedCatchUpProgram()playerEngine.stopLiveTimeshift()stopLiveTranslationSession()clearPlaybackTimers()@@ -152,6 +154,8 @@ internal fun PlayerViewModel.clearPlaybackTimers() {fun PlayerViewModel.handOffPlaybackToMultiView(): Job? {val progressFlush = queueForcedProgressFlush()+ clearPreloadWindow()+ playerPlaybackContextCoordinator.clearSelectedCatchUpProgram()playerEngine.stopLiveTimeshift()stopLiveTranslationSession()playerPreviewCoordinator.clear(playerEngine)diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinator.ktindex 1c92fd25..e5a984ad 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinator.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinator.kt@@ -1,6 +1,7 @@package com.streamvault.feature.playback.playerimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Programimport com.streamvault.domain.model.StreamInfoimport javax.inject.Inject@@ -15,6 +16,15 @@ class PlayerPlaybackContextCoordinator @Inject constructor() {internal var currentTitle: String = ""internal var currentArtworkUrl: String? = nullinternal var pendingCatchUpUrls: List<String> = emptyList()+ internal var selectedCatchUpProgram: Program? = null++ internal fun storeSelectedCatchUpProgram(program: Program) {+ selectedCatchUpProgram = program+ }++ internal fun clearSelectedCatchUpProgram() {+ selectedCatchUpProgram = null+ }internal fun clearResolvedStream() {currentResolvedPlaybackUrl = ""diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.ktindex 0f5cf16e..68192ba7 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPlaybackPreferenceActions.kt@@ -366,7 +366,13 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {val previewPositionMs = positionMs.coerceAtLeast(0L)val previewUrl = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }- val canExtractFrame = previewUrl.isNotBlank() && playerThumbnailCoordinator.supportsFrameExtraction(previewUrl)+ val previewStreamInfo = currentResolvedStreamInfo+ val isLive = currentContentType == ContentType.LIVE+ val canExtractFrame = previewUrl.isNotBlank() && playerThumbnailCoordinator.supportsFrameExtraction(+ streamUrl = previewUrl,+ streamInfo = previewStreamInfo,+ isLive = isLive+ )_seekPreview.update { current ->current.copy(@@ -387,7 +393,12 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {val requestVersion = ++seekPreviewRequestVersionseekPreviewJob = viewModelScope.launch {delay(120)- val bitmap = playerThumbnailCoordinator.loadFrame(previewUrl, previewPositionMs)+ val bitmap = playerThumbnailCoordinator.loadFrame(+ streamUrl = previewUrl,+ streamInfo = previewStreamInfo,+ isLive = isLive,+ positionMs = previewPositionMs+ )if (requestVersion != seekPreviewRequestVersion) return@launch_seekPreview.update { current ->@@ -407,7 +418,9 @@ fun PlayerViewModel.updateSeekPreview(positionMs: Long?) {internal fun PlayerViewModel.startThumbnailPreload() {val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }- if (url.isBlank() || !playerThumbnailCoordinator.supportsFrameExtraction(url)) return+ val streamInfo = currentResolvedStreamInfo+ val isLive = currentContentType == ContentType.LIVE+ if (url.isBlank() || !playerThumbnailCoordinator.supportsFrameExtraction(url, streamInfo, isLive)) returnif (!shouldStartThumbnailPreload(url, lastCompletedThumbnailPreloadKey, inFlightThumbnailPreloadKey)) returnval durationMs = playerEngine.duration.valueif (durationMs <= 0L) return@@ -423,7 +436,12 @@ internal fun PlayerViewModel.startThumbnailPreload() {try {preloadPositions.forEach { positionMs ->ensureActive()- playerThumbnailCoordinator.loadFrame(url, positionMs)+ playerThumbnailCoordinator.loadFrame(+ streamUrl = url,+ streamInfo = streamInfo,+ isLive = isLive,+ positionMs = positionMs+ )}lastCompletedThumbnailPreloadKey = url} finally {diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinator.ktnew file mode 100644index 00000000..a95300f2--- /dev/null+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinator.kt@@ -0,0 +1,180 @@+package com.streamvault.feature.playback.player++import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Result+import com.streamvault.player.PlayerPreloadContentType+import com.streamvault.player.PlayerPreloadItem+import com.streamvault.player.PlayerPreloadWindow+import android.util.Log+import javax.inject.Inject++/** Resolves only the bounded neighbors needed by the player preload window. */+class PlayerPreloadWindowCoordinator @Inject constructor(+ private val playerContentResolver: PlayerContentResolver,+ private val playerProviderCoordinator: PlayerProviderCoordinator,+ private val playerPreparationCoordinator: PlayerPreparationCoordinator+) {++ internal suspend fun buildEpisodeWindow(+ current: PlayerPreloadItem,+ series: Series,+ currentEpisode: Episode,+ providerId: Long,+ isCurrent: () -> Boolean+ ): PlayerPreloadWindow? {+ if (!isCurrent()) return null+ val neighbors = buildEpisodePreloadNeighbors(series, currentEpisode) ?: return null+ val items = mutableListOf<PlayerPreloadItem>()++ neighbors.forEach { episode ->+ if (!isCurrent()) return null+ val key = episodePreloadKey(providerId, episode)+ if (episodeMatches(episode, currentEpisode)) {+ items += current.copy(+ key = key,+ contentType = PlayerPreloadContentType.VOD+ )+ return@forEach+ }++ val logicalUrl = episode.streamUrl.trim()+ val resolution = playerContentResolver.resolvePlaybackStream(+ logicalUrl = logicalUrl,+ internalContentId = episode.id,+ providerId = providerId,+ contentType = ContentType.SERIES_EPISODE,+ currentTitle = buildEpisodePlaybackTitle(episode),+ currentSeries = series,+ currentEpisode = episode+ )+ val streamInfo = resolution.streamInfo ?: run {+ logCandidateFailure(key, PlayerPreloadContentType.VOD, "unresolved")+ return@forEach+ }+ if (!isCurrent()) return null+ val preparedStreamInfo = playerPreparationCoordinator+ .prepareStreamForPreload(streamInfo)+ ?: run {+ logCandidateFailure(key, PlayerPreloadContentType.VOD, "preparation-failed")+ return@forEach+ }+ if (!isCurrent()) return null+ items += PlayerPreloadItem(+ key = key,+ streamInfo = preparedStreamInfo,+ contentType = PlayerPreloadContentType.VOD+ )+ }++ val currentIndex = items.indexOfFirst { it.key == episodePreloadKey(providerId, currentEpisode) }+ if (currentIndex < 0) return null+ return PlayerPreloadWindow(items = items, currentIndex = currentIndex)+ }++ internal suspend fun buildCatchUpWindow(+ current: PlayerPreloadItem,+ selectedProgram: Program,+ channel: Channel,+ timelinePrograms: List<Program>,+ providerId: Long,+ isCurrent: () -> Boolean+ ): PlayerPreloadWindow? {+ if (!isCurrent()) return null+ val neighbors = buildCatchUpPreloadNeighbors(+ selectedProgram = selectedProgram,+ channel = channel,+ timelinePrograms = timelinePrograms,+ now = System.currentTimeMillis()+ ) ?: return null+ val items = mutableListOf<PlayerPreloadItem>()++ neighbors.forEach { program ->+ if (!isCurrent()) return null+ val key = catchUpPreloadKey(providerId, channel, program)+ if (program.samePlaybackProgramAs(selectedProgram)) {+ items += current.copy(+ key = key,+ contentType = PlayerPreloadContentType.CATCH_UP+ )+ return@forEach+ }+ if (channel.streamId <= 0L) {+ logCandidateFailure(key, PlayerPreloadContentType.CATCH_UP, "missing-stream-id")+ return@forEach+ }++ val urls = when (+ val result = playerProviderCoordinator.buildCatchUpUrls(+ providerId = providerId,+ streamId = channel.id,+ start = program.startTime / 1_000L,+ end = program.endTime / 1_000L+ )+ ) {+ is Result.Success -> result.data+ is Result.Error -> {+ logCandidateFailure(key, PlayerPreloadContentType.CATCH_UP, "url-build-failed")+ emptyList()+ }+ is Result.Loading -> {+ logCandidateFailure(key, PlayerPreloadContentType.CATCH_UP, "url-build-loading")+ emptyList()+ }+ }+ var resolvedCandidate = false+ for (url in urls) {+ if (!isCurrent()) return null+ val resolved = playerContentResolver.resolvePlaybackStream(+ logicalUrl = url,+ internalContentId = channel.id,+ providerId = providerId,+ contentType = ContentType.LIVE,+ currentTitle = program.title,+ currentSeries = null,+ currentEpisode = null+ ).streamInfo ?: continue+ if (!isCurrent()) return null+ val prepared = playerPreparationCoordinator.prepareStreamForPreload(resolved) ?: continue+ if (!isCurrent()) return null+ items += PlayerPreloadItem(+ key = key,+ streamInfo = prepared,+ contentType = PlayerPreloadContentType.CATCH_UP+ )+ resolvedCandidate = true+ break+ }+ if (!resolvedCandidate && urls.isNotEmpty()) {+ logCandidateFailure(key, PlayerPreloadContentType.CATCH_UP, "unresolved")+ }+ }++ val currentIndex = items.indexOfFirst {+ it.key == catchUpPreloadKey(providerId, channel, selectedProgram)+ }+ if (currentIndex < 0) return null+ return PlayerPreloadWindow(items = items, currentIndex = currentIndex)+ }++ private fun episodeMatches(left: Episode, right: Episode): Boolean =+ left.id == right.id ||+ left.playbackEpisodeIdentity() == right.playbackEpisodeIdentity() ||+ (left.seasonNumber == right.seasonNumber && left.episodeNumber == right.episodeNumber)+}++private fun logCandidateFailure(key: String, contentType: PlayerPreloadContentType, reason: String) {+ runCatching {+ Log.w(+ "PlayerPreloadWindow",+ "candidate failed key=${key.take(80)} kind=$contentType reason=$reason"+ )+ }+}++private fun Program.samePlaybackProgramAs(other: Program): Boolean =+ (id > 0L && other.id > 0L && id == other.id) ||+ (channelId == other.channelId && startTime == other.startTime && endTime == other.endTime)diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupport.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupport.ktnew file mode 100644index 00000000..529ef9a9--- /dev/null+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupport.kt@@ -0,0 +1,126 @@+package com.streamvault.feature.playback.player++import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.Series+import com.streamvault.domain.playback.isArchivePlayable+import com.streamvault.domain.model.StreamInfo+import com.streamvault.player.PlayerPreloadContentType+import com.streamvault.player.PlayerPreloadItem+import com.streamvault.player.PlayerPreloadWindow++internal fun buildEpisodePreloadNeighbors(+ series: Series,+ currentEpisode: Episode+): List<Episode>? {+ val orderedEpisodes = orderedEpisodesForPlayer(series)+ val currentIndex = orderedEpisodes.indexOfFirst {+ it.id == currentEpisode.id ||+ it.playbackEpisodeIdentity() == currentEpisode.playbackEpisodeIdentity() ||+ (it.seasonNumber == currentEpisode.seasonNumber &&+ it.episodeNumber == currentEpisode.episodeNumber)+ }+ if (currentIndex < 0) return null++ return buildList {+ orderedEpisodes.getOrNull(currentIndex - 1)?.let(::add)+ add(orderedEpisodes[currentIndex])+ orderedEpisodes.getOrNull(currentIndex + 1)?.let(::add)+ }+}++internal fun buildCatchUpPreloadNeighbors(+ selectedProgram: Program,+ channel: Channel,+ timelinePrograms: List<Program>,+ now: Long+): List<Program>? {+ val sortedPrograms = timelinePrograms.sortedBy { it.startTime }+ val selectedIndex = sortedPrograms.indexOfFirst { it.samePlaybackProgram(selectedProgram) }+ if (selectedIndex < 0) return null++ return buildList {+ sortedPrograms+ .subList(0, selectedIndex)+ .asReversed()+ .firstOrNull { channel.isArchivePlayable(it, now) }+ ?.let(::add)+ add(sortedPrograms[selectedIndex])+ sortedPrograms+ .drop(selectedIndex + 1)+ .firstOrNull { channel.isArchivePlayable(it, now) }+ ?.let(::add)+ }+}++internal fun buildCatchUpPreloadTimeline(+ programHistory: List<Program>,+ currentProgram: Program?,+ upcomingPrograms: List<Program>,+ selectedProgram: Program+): List<Program> {+ val candidates = buildList {+ addAll(programHistory)+ currentProgram?.let(::add)+ addAll(upcomingPrograms)+ add(selectedProgram)+ }.filter { it.channelId == selectedProgram.channelId }++ return candidates+ .sortedBy { it.startTime }+ .fold(mutableListOf()) { unique, program ->+ if (unique.none { it.samePlaybackProgram(program) }) {+ unique += program+ }+ unique+ }+}++internal fun episodePreloadKey(providerId: Long, episode: Episode): String =+ "episode:$providerId:${episode.playbackEpisodeIdentity()}"++internal fun catchUpPreloadKey(providerId: Long, channel: Channel, program: Program): String =+ "catchup:$providerId:${channel.id}:${program.startTime}:${program.endTime}"++internal fun buildPreloadWindowRefreshFingerprint(+ contentType: PlayerPreloadContentType,+ providerId: Long,+ currentKey: String,+ neighborKeys: List<String>,+ currentStreamInfo: StreamInfo+): String = listOf(+ contentType.name,+ providerId,+ currentKey,+ neighborKeys.joinToString(","),+ currentStreamInfo.hashCode()+).joinToString("|")++internal fun buildEpisodePreloadWindow(+ current: PlayerPreloadItem,+ series: Series,+ currentEpisode: Episode,+ providerId: Long,+ resolvedNeighbors: Map<Long, PlayerPreloadItem>+): PlayerPreloadWindow? {+ val neighbors = buildEpisodePreloadNeighbors(series, currentEpisode) ?: return null+ val items = neighbors.map { episode ->+ if (episode.playbackEpisodeIdentity() == currentEpisode.playbackEpisodeIdentity()) {+ current.copy(+ key = episodePreloadKey(providerId, episode),+ contentType = PlayerPreloadContentType.VOD+ )+ } else {+ resolvedNeighbors[episode.playbackEpisodeIdentity()] ?: return null+ }+ }+ return PlayerPreloadWindow(+ items = items,+ currentIndex = items.indexOfFirst { it.key == episodePreloadKey(providerId, currentEpisode) }+ )+}++private fun Program.samePlaybackProgram(other: Program): Boolean =+ (id > 0L && other.id > 0L && id == other.id) ||+ (channelId == other.channelId && startTime == other.startTime && endTime == other.endTime)diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationContextActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationContextActions.ktindex 42d05458..468b95c9 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationContextActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationContextActions.kt@@ -2,6 +2,7 @@ package com.streamvault.feature.playback.playerimport androidx.lifecycle.viewModelScopeimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Programimport com.streamvault.domain.model.Resultimport kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.collect@@ -37,6 +38,17 @@ internal fun PlayerViewModel.finalizePreparedPlaybackContext(}if (currentContentType == ContentType.LIVE && hasArchiveRequest) {+ val selectedArchiveProgram = Program(+ channelId = currentProgram.value?.channelId+ ?: currentChannelFlow.value?.epgChannelId+ ?: currentContentId.toString(),+ title = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle,+ startTime = archiveStartMs ?: 0L,+ endTime = archiveEndMs ?: 0L,+ hasArchive = true,+ providerId = currentProviderId+ )+ playerPlaybackContextCoordinator.storeSelectedCatchUpProgram(selectedArchiveProgram)playerEngine.stopLiveTimeshift()playbackSessionScope(requestVersion)?.launch {contentSwitchFlush?.join()@@ -131,6 +143,9 @@ internal fun PlayerViewModel.finalizePreparedPlaybackContext()}updateChannelDiagnostics(channel)+ if (isCatchUpPlayback() && currentResolvedStreamInfo != null) {+ refreshPreloadWindow(requestVersion)+ }}}}diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.ktindex ee44045a..b92e3782 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt@@ -105,6 +105,28 @@ class PlayerPreparationCoordinator @Inject constructor()}+ /**+ * Applies provider/plugin stream preparation without touching the foreground player.+ * Preload candidates use this path so request metadata is retained while probes,+ * preference changes, and foreground preparation remain side-effect free.+ */+ internal suspend fun prepareStreamForPreload(streamInfo: StreamInfo): StreamInfo? {+ val expiry = streamInfo.expirationTime+ if (expiry != null && expiry > 0L && expiry < System.currentTimeMillis()) {+ return null+ }+ val prepared = when (val result = streamPreparer.prepare(streamInfo)) {+ is DomainResult.Error -> return null+ DomainResult.Loading -> streamInfo+ is DomainResult.Success -> result.data+ }+ val preparedExpiry = prepared.expirationTime+ if (preparedExpiry != null && preparedExpiry > 0L && preparedExpiry < System.currentTimeMillis()) {+ return null+ }+ return prepared+ }+internal suspend fun applyPlaybackPreferences(engine: PlayerEngine,contentType: ContentType,diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationSetupActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationSetupActions.ktindex 06edb9d0..47a84b4b 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationSetupActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationSetupActions.kt@@ -74,6 +74,15 @@ internal fun PlayerViewModel.applyPrepareSessionState(combinedSourceFilterProviderId != previousCombinedSourceFilterProviderId)+ val requestedContentType = try {+ ContentType.valueOf(contentType)+ } catch (_: Exception) {+ ContentType.LIVE+ }+ if (requestedContentType == ContentType.LIVE && !hasArchiveRequest) {+ clearPreloadWindow()+ }+clearSeekPreview()currentResolvedPlaybackUrl = ""currentResolvedStreamInfo = null@@ -82,11 +91,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(currentTitle = titleplaybackTitleFlow.value = titlecurrentArtworkUrl = artworkUrl- currentContentType = try {- ContentType.valueOf(contentType)- } catch (_: Exception) {- ContentType.LIVE- }+ currentContentType = requestedContentTypecurrentProviderId = providerIdcurrentCombinedProfileId = combinedProfileId?.takeIf { it > 0L }currentCombinedSourceFilterProviderId = combinedSourceFilterProviderId?.takeIf { it > 0L }@@ -113,6 +118,7 @@ internal fun PlayerViewModel.applyPrepareSessionState(if (!hasArchiveRequest) {pendingCatchUpUrls = emptyList()+ playerPlaybackContextCoordinator.clearSelectedCatchUpProgram()}if (currentContentType != ContentType.SERIES_EPISODE || providerId <= 0 || currentSeriesId == null) {clearSeriesEpisodeContext()diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerRecoveryActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerRecoveryActions.ktindex 19e4447d..7639172b 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerRecoveryActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerRecoveryActions.kt@@ -31,7 +31,7 @@ internal fun PlayerViewModel.cooldownLivePreloadForCurrentProvider(reason: Strinval providerId = currentProviderId.takeIf { it > 0L } ?: returnif (playerRecoveryCoordinator.markLivePreloadCoolingDown(providerId)) {appendRecoveryAction("Disabled live preload for provider: $reason")- playerEngine.preload(null)+ clearPreloadWindow()}}@@ -67,7 +67,7 @@ internal suspend fun PlayerViewModel.tryRefreshXtreamPlaybackAfterAuthError(delay(PROVIDER_AUTH_RETRY_GRACE_MS)if (!isActivePlaybackSession(requestVersion, playbackUrl)) return trueclearResolvedStream()- playerEngine.preload(null)+ clearPreloadWindow()if (!preparePlayer(refreshedStreamInfo, requestVersion, probeBeforePlayback = false)) return trueplayerEngine.play()return truediff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinator.ktindex a6343b8b..7ce199df 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinator.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinator.kt@@ -1,19 +1,86 @@package com.streamvault.feature.playback.playerimport android.graphics.Bitmap+import android.util.Log+import com.streamvault.domain.model.StreamInfo+import com.streamvault.player.playback.FrameThumbnailExtractor+import com.streamvault.player.playback.FrameThumbnailRequest+import com.streamvault.player.playback.Media3FrameThumbnailExtractor+import dagger.Binds+import dagger.Module+import dagger.hilt.InstallIn+import dagger.hilt.components.SingletonComponentimport javax.inject.Inject/** Feature boundary for seek-frame extraction and its shared cache. */class PlayerThumbnailCoordinator @Inject constructor(- private val provider: SeekThumbnailProvider+ private val media3Extractor: FrameThumbnailExtractor,+ private val legacyProvider: SeekThumbnailProvider) {- internal fun supportsFrameExtraction(streamUrl: String): Boolean =- provider.supportsFrameExtraction(streamUrl)+ private companion object {+ private const val TAG = "PlayerThumbnail"+ }++ internal fun supportsFrameExtraction(+ streamUrl: String,+ streamInfo: StreamInfo?,+ isLive: Boolean+ ): Boolean {+ val request = buildRequest(streamUrl, streamInfo, isLive)+ return (request != null && media3Extractor.supports(request)) ||+ legacyProvider.supportsFrameExtraction(streamUrl)+ }- internal suspend fun loadFrame(streamUrl: String, positionMs: Long): Bitmap? =- provider.loadFrame(streamUrl, positionMs)+ internal suspend fun loadFrame(+ streamUrl: String,+ streamInfo: StreamInfo?,+ isLive: Boolean,+ positionMs: Long+ ): Bitmap? {+ val request = buildRequest(streamUrl, streamInfo, isLive)+ if (request != null && media3Extractor.supports(request)) {+ media3Extractor.loadFrame(request, positionMs)?.let { return it }+ Log.d(TAG, "frame-thumbnail backend=legacy reason=media3-failure")+ } else {+ Log.d(TAG, "frame-thumbnail backend=legacy reason=media3-unsupported")+ }+ if (!legacyProvider.supportsFrameExtraction(streamUrl)) {+ Log.d(TAG, "frame-thumbnail backend=none reason=legacy-unsupported")+ return null+ }+ return legacyProvider.loadFrame(streamUrl, positionMs)+ }internal fun clearCache() {- provider.clearCache()+ media3Extractor.clearCache()+ legacyProvider.clearCache()}++ private fun buildRequest(+ streamUrl: String,+ streamInfo: StreamInfo?,+ isLive: Boolean+ ): FrameThumbnailRequest? {+ val normalizedUrl = streamUrl.trim()+ val resolvedInfo = streamInfo ?: return null+ if (normalizedUrl.isBlank()) return null+ val requestInfo = if (resolvedInfo.url == normalizedUrl) {+ resolvedInfo+ } else {+ resolvedInfo.copy(url = normalizedUrl)+ }+ return FrameThumbnailRequest(+ streamInfo = requestInfo,+ isLive = isLive+ )+ }+}++@Module+@InstallIn(SingletonComponent::class)+internal abstract class PlayerThumbnailModule {+ @Binds+ abstract fun bindFrameThumbnailExtractor(+ extractor: Media3FrameThumbnailExtractor+ ): FrameThumbnailExtractor}diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.ktindex 048467af..75e1342f 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt@@ -31,6 +31,8 @@ import com.streamvault.player.AUDIO_VIDEO_OFFSET_MIN_MSimport com.streamvault.player.PlaybackStateimport com.streamvault.player.PlayerEngineimport com.streamvault.player.PlayerError+import com.streamvault.player.PlayerPreloadContentType+import com.streamvault.player.PlayerPreloadItemimport com.streamvault.player.PlayerSubtitleStyleimport com.streamvault.player.timeshift.LiveTimeshiftBackendimport com.streamvault.player.timeshift.LiveTimeshiftState@@ -70,6 +72,7 @@ class PlayerViewModel @Inject constructor(internal val playerCastCoordinator: PlayerCastCoordinator,internal val playerTranslationCoordinator: PlayerTranslationCoordinator,internal val playerContentResolver: PlayerContentResolver,+ internal val playerPreloadWindowCoordinator: PlayerPreloadWindowCoordinator,internal val playerPlaybackContextCoordinator: PlayerPlaybackContextCoordinator,internal val playerRecoveryCoordinator: PlayerRecoveryCoordinator,internal val playerRecoveryExecutionCoordinator: PlayerRecoveryExecutionCoordinator,@@ -372,6 +375,9 @@ class PlayerViewModel @Inject constructor(internal var controlsHideJob: Job? = nullinternal var seekPreviewJob: Job? = nullinternal var thumbnailPreloadJob: Job? = null+ private var preloadWindowJob: Job? = null+ private var preloadWindowInFlightFingerprint: String? = null+ private var acceptedPreloadWindowFingerprint: String? = nullinternal var inFlightThumbnailPreloadKey: String? = nullinternal var lastCompletedThumbnailPreloadKey: String? = nullprivate var lowBandwidthMonitorJob: Job? = null@@ -508,7 +514,7 @@ class PlayerViewModel @Inject constructor(if (state == PlaybackState.READY && readySideEffectsRequestVersion == prepareRequestVersion) {zapBufferWatchdogJob?.cancel()dismissRecoveredNoticeIfPresent()- if (currentContentType == ContentType.LIVE) {+ if (currentContentType == ContentType.LIVE && !isCatchUpPlayback()) {livePlaybackReadyForCurrentSession = truerecordActiveLivePlayback()currentChannelFlow.value?.sanitizedForPlayer()?.let { channel ->@@ -520,8 +526,11 @@ class PlayerViewModel @Inject constructor(}}} else {- recordMovieVariantSuccessObservation()- startThumbnailPreload()+ if (currentContentType != ContentType.LIVE) {+ recordMovieVariantSuccessObservation()+ startThumbnailPreload()+ }+ refreshPreloadWindow(prepareRequestVersion)}}}@@ -904,6 +913,9 @@ class PlayerViewModel @Inject constructor(playerRecoveryCoordinator.beginSession(sessionId)playerRecoveryExecutionCoordinator.cancel()thumbnailPreloadJob?.cancel()+ preloadWindowJob?.cancel()+ preloadWindowJob = null+ preloadWindowInFlightFingerprint = nulltokenRenewalJob?.cancel()zapBufferWatchdogJob?.cancel()stopLiveTranslationSession()@@ -915,6 +927,137 @@ class PlayerViewModel @Inject constructor(return sessionId}+ internal fun clearPreloadWindow() {+ preloadWindowJob?.cancel()+ preloadWindowJob = null+ preloadWindowInFlightFingerprint = null+ acceptedPreloadWindowFingerprint = null+ playerEngine.clearPreloadWindow()+ }++ private data class PreloadWindowSnapshot(+ val providerId: Long,+ val current: PlayerPreloadItem,+ val neighborKeys: List<String>,+ val series: Series? = null,+ val episode: Episode? = null,+ val selectedProgram: Program? = null,+ val channel: com.streamvault.domain.model.Channel? = null,+ val timelinePrograms: List<Program> = emptyList()+ )++ private fun buildPreloadWindowSnapshot(): PreloadWindowSnapshot? {+ val streamInfo = currentResolvedStreamInfo ?: return null+ val providerId = currentProviderId.takeIf { it > 0L } ?: return null++ if (currentContentType == ContentType.SERIES_EPISODE) {+ val series = currentSeries.value ?: return null+ val episode = currentEpisode.value ?: return null+ val neighbors = buildEpisodePreloadNeighbors(series, episode) ?: return null+ val currentKey = episodePreloadKey(providerId, episode)+ return PreloadWindowSnapshot(+ providerId = providerId,+ current = PlayerPreloadItem(+ key = currentKey,+ streamInfo = streamInfo,+ contentType = PlayerPreloadContentType.VOD+ ),+ neighborKeys = neighbors.map { episodePreloadKey(providerId, it) },+ series = series,+ episode = episode+ )+ }++ if (!isCatchUpPlayback()) return null+ val selectedProgram = playerPlaybackContextCoordinator.selectedCatchUpProgram ?: return null+ val channel = currentChannelFlow.value ?: return null+ val timelinePrograms = buildCatchUpPreloadTimeline(+ programHistory = programHistory.value,+ currentProgram = currentProgram.value,+ upcomingPrograms = upcomingPrograms.value,+ selectedProgram = selectedProgram+ )+ val neighbors = buildCatchUpPreloadNeighbors(+ selectedProgram = selectedProgram,+ channel = channel,+ timelinePrograms = timelinePrograms,+ now = System.currentTimeMillis()+ ) ?: return null+ return PreloadWindowSnapshot(+ providerId = providerId,+ current = PlayerPreloadItem(+ key = catchUpPreloadKey(providerId, channel, selectedProgram),+ streamInfo = streamInfo,+ contentType = PlayerPreloadContentType.CATCH_UP+ ),+ neighborKeys = neighbors.map { catchUpPreloadKey(providerId, channel, it) },+ selectedProgram = selectedProgram,+ channel = channel,+ timelinePrograms = timelinePrograms+ )+ }++ internal fun refreshPreloadWindow(requestVersion: Long) {+ if (!isActivePlaybackSession(requestVersion)) return+ val snapshot = buildPreloadWindowSnapshot() ?: return+ val fingerprint = buildPreloadWindowRefreshFingerprint(+ contentType = snapshot.current.contentType,+ providerId = snapshot.providerId,+ currentKey = snapshot.current.key,+ neighborKeys = snapshot.neighborKeys,+ currentStreamInfo = snapshot.current.streamInfo+ )+ if (+ fingerprint == acceptedPreloadWindowFingerprint ||+ fingerprint == preloadWindowInFlightFingerprint+ ) {+ return+ }++ preloadWindowJob?.cancel()+ preloadWindowInFlightFingerprint = fingerprint+ preloadWindowJob = playbackSessionScope(requestVersion)?.launch {+ val window = when {+ snapshot.series != null && snapshot.episode != null ->+ playerPreloadWindowCoordinator.buildEpisodeWindow(+ current = snapshot.current,+ series = snapshot.series,+ currentEpisode = snapshot.episode,+ providerId = snapshot.providerId,+ isCurrent = { isActivePlaybackSession(requestVersion) }+ )++ snapshot.selectedProgram != null && snapshot.channel != null ->+ playerPreloadWindowCoordinator.buildCatchUpWindow(+ current = snapshot.current,+ selectedProgram = snapshot.selectedProgram,+ channel = snapshot.channel,+ timelinePrograms = snapshot.timelinePrograms,+ providerId = snapshot.providerId,+ isCurrent = { isActivePlaybackSession(requestVersion) }+ )++ else -> null+ }+ if (window == null || !isActivePlaybackSession(requestVersion)) {+ if (preloadWindowInFlightFingerprint == fingerprint) {+ preloadWindowInFlightFingerprint = null+ }+ return@launch+ }+ playerEngine.preloadWindow(window)+ android.util.Log.i(+ "PlayerVM",+ "preload-window submitted kind=${snapshot.current.contentType} " ++ "currentKey=${snapshot.current.key} sourceCount=${window.items.size}"+ )+ if (preloadWindowInFlightFingerprint == fingerprint) {+ acceptedPreloadWindowFingerprint = fingerprint+ preloadWindowInFlightFingerprint = null+ }+ }+ }+/*** Launches work owned by a playback session. UI-only jobs should continue to use* [viewModelScope]; preparation, recovery, renewal, and other session work belongs here.@@ -973,6 +1116,9 @@ class PlayerViewModel @Inject constructor(currentContentId = resolvedId}}+ if (currentResolvedStreamInfo != null) {+ refreshPreloadWindow(requestVersion)+ }}resolution.resolvedEpisode}diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerZapActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerZapActions.ktindex ba798af0..8a6291e0 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerZapActions.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerZapActions.kt@@ -279,7 +279,7 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =releaseOutgoingLiveZapPlayback(stopPlayback = playerEngine::stop,stopLiveTimeshift = playerEngine::stopLiveTimeshift,- clearPreload = { playerEngine.preload(null) }+ clearPreload = ::clearPreloadWindow)clearResolvedStream()val channel = channelList[index]@@ -289,6 +289,7 @@ internal fun PlayerViewModel.changeChannel(index: Int, isAutoFallback: Boolean =playbackTitleFlow.value = currentTitlecurrentStreamUrl = channel.streamUrlpendingCatchUpUrls = emptyList()+ playerPlaybackContextCoordinator.clearSelectedCatchUpProgram()updateStreamClass("Primary")currentChannelFlow.value = channelrefreshCurrentChannelRecording()@@ -341,7 +342,7 @@ internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {val nextIndex = (currentIndex + 1) % channelList.sizeval nextChannel = channelList[nextIndex]if (nextChannel.streamUrl.isBlank()) {- playerEngine.preload(null)+ clearPreloadWindow()return}playbackSessionScope()?.launch {@@ -353,7 +354,7 @@ internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {preloadCoolingDown = playerRecoveryCoordinator.isLivePreloadCoolingDown(nextChannel.providerId))) {- playerEngine.preload(null)+ clearPreloadWindow()return@launch}val streamInfo = resolvePlaybackStreamInfo(diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinatorTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinatorTest.ktindex ff167ab9..13528c1c 100644--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinatorTest.kt+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPlaybackContextCoordinatorTest.kt@@ -2,6 +2,7 @@ package com.streamvault.feature.playback.playerimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Programimport com.streamvault.domain.model.StreamInfoimport org.junit.Test@@ -27,4 +28,24 @@ class PlayerPlaybackContextCoordinatorTest {assertThat(coordinator.currentResolvedPlaybackUrl).isEmpty()assertThat(coordinator.currentResolvedStreamInfo).isNull()}++ @Test+ fun `selected catch-up program can be retained independently of live guide program`() {+ val selected = Program(+ id = 7L,+ channelId = "channel-1",+ title = "Selected replay",+ startTime = 1_000L,+ endTime = 2_000L+ )+ val coordinator = PlayerPlaybackContextCoordinator()++ coordinator.storeSelectedCatchUpProgram(selected)++ assertThat(coordinator.selectedCatchUpProgram).isEqualTo(selected)++ coordinator.clearSelectedCatchUpProgram()++ assertThat(coordinator.selectedCatchUpProgram).isNull()+ }}diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinatorTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinatorTest.ktnew file mode 100644index 00000000..0efe47a9--- /dev/null+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowCoordinatorTest.kt@@ -0,0 +1,250 @@+package com.streamvault.feature.playback.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.Season+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.StreamInfo+import com.streamvault.player.PlayerPreloadContentType+import com.streamvault.player.PlayerPreloadItem+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.anyOrNull+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.whenever++class PlayerPreloadWindowCoordinatorTest {++ @Test+ fun `episode window resolves adjacent streams and keeps current between them`() = runTest {+ val previous = episode(id = 1L, number = 1)+ val currentEpisode = episode(id = 2L, number = 2)+ val next = episode(id = 3L, number = 3)+ val series = Series(+ id = 10L,+ name = "Example",+ seasons = listOf(+ Season(seasonNumber = 1, episodes = listOf(previous, currentEpisode, next))+ )+ )+ val resolver = mock<PlayerContentResolver>()+ val provider = mock<PlayerProviderCoordinator>()+ val preparation = mock<PlayerPreparationCoordinator>()+ whenever(+ resolver.resolvePlaybackStream(+ logicalUrl = any(),+ internalContentId = any(),+ providerId = any(),+ contentType = eq(ContentType.SERIES_EPISODE),+ currentTitle = any(),+ currentSeries = anyOrNull(),+ currentEpisode = anyOrNull()+ )+ ).thenAnswer { invocation ->+ PlayerPlaybackStreamResolution(+ streamInfo = StreamInfo(+ url = invocation.getArgument<String>(0),+ title = invocation.getArgument<String>(4)+ )+ )+ }+ whenever(preparation.prepareStreamForPreload(any()))+ .thenAnswer { invocation -> invocation.getArgument(0) }++ val coordinator = PlayerPreloadWindowCoordinator(resolver, provider, preparation)+ val current = PlayerPreloadItem(+ key = "old-current-key",+ streamInfo = StreamInfo("https://example.com/current.mp4"),+ contentType = PlayerPreloadContentType.VOD+ )++ val window = coordinator.buildEpisodeWindow(+ current = current,+ series = series,+ currentEpisode = currentEpisode,+ providerId = 7L,+ isCurrent = { true }+ )++ assertThat(window?.items?.map(PlayerPreloadItem::key))+ .containsExactly("episode:7:1", "episode:7:2", "episode:7:3")+ .inOrder()+ assertThat(window?.currentIndex).isEqualTo(1)+ assertThat(window?.items?.get(1)?.streamInfo?.url)+ .isEqualTo("https://example.com/current.mp4")+ }++ @Test+ fun `catch up window skips an unresolved neighbor without failing current`() = runTest {+ val channel = archiveChannel()+ val previous = program(1L, 30_000L, 40_000L)+ val selected = program(2L, 50_000L, 60_000L)+ val next = program(3L, 70_000L, 80_000L)+ val resolver = mock<PlayerContentResolver>()+ val provider = mock<PlayerProviderCoordinator>()+ val preparation = mock<PlayerPreparationCoordinator>()+ val requestedStreamIds = mutableListOf<Long>()+ whenever(provider.buildCatchUpUrls(any(), any(), any(), any()))+ .thenAnswer { invocation ->+ requestedStreamIds += invocation.getArgument<Long>(1)+ Result.success(listOf("https://example.com/catchup.m3u8"))+ }+ whenever(+ resolver.resolvePlaybackStream(+ logicalUrl = any(),+ internalContentId = any(),+ providerId = any(),+ contentType = eq(ContentType.LIVE),+ currentTitle = any(),+ currentSeries = anyOrNull(),+ currentEpisode = anyOrNull()+ )+ ).thenReturn(+ PlayerPlaybackStreamResolution(streamInfo = null, resolutionFailureMessage = "unavailable")+ ).thenReturn(+ PlayerPlaybackStreamResolution(+ streamInfo = StreamInfo("https://example.com/next.m3u8")+ )+ )+ whenever(preparation.prepareStreamForPreload(any()))+ .thenAnswer { invocation -> invocation.getArgument(0) }++ val coordinator = PlayerPreloadWindowCoordinator(resolver, provider, preparation)+ val current = PlayerPreloadItem(+ key = "catchup:7:1:50000:60000",+ streamInfo = StreamInfo("https://example.com/current.m3u8"),+ contentType = PlayerPreloadContentType.CATCH_UP+ )++ val window = coordinator.buildCatchUpWindow(+ current = current,+ selectedProgram = selected,+ channel = channel,+ timelinePrograms = listOf(previous, selected, next),+ providerId = 7L,+ isCurrent = { true }+ )++ assertThat(window?.items?.map(PlayerPreloadItem::key))+ .containsExactly("catchup:7:1:50000:60000", "catchup:7:1:70000:80000")+ .inOrder()+ assertThat(window?.currentIndex).isEqualTo(0)+ assertThat(requestedStreamIds).containsExactly(1L, 1L).inOrder()+ }++ @Test+ fun `stale session stops neighbor resolution before publishing a window`() = runTest {+ val previous = episode(id = 1L, number = 1)+ val currentEpisode = episode(id = 2L, number = 2)+ val series = Series(+ id = 10L,+ name = "Example",+ seasons = listOf(Season(seasonNumber = 1, episodes = listOf(previous, currentEpisode)))+ )+ val resolver = mock<PlayerContentResolver>()+ val provider = mock<PlayerProviderCoordinator>()+ val preparation = mock<PlayerPreparationCoordinator>()+ var isCurrent = true+ whenever(+ resolver.resolvePlaybackStream(+ logicalUrl = any(),+ internalContentId = any(),+ providerId = any(),+ contentType = eq(ContentType.SERIES_EPISODE),+ currentTitle = any(),+ currentSeries = anyOrNull(),+ currentEpisode = anyOrNull()+ )+ ).thenReturn(+ PlayerPlaybackStreamResolution(+ streamInfo = StreamInfo("https://example.com/previous.mp4")+ )+ )+ whenever(preparation.prepareStreamForPreload(any())).thenAnswer {+ isCurrent = false+ it.getArgument(0)+ }++ val window = PlayerPreloadWindowCoordinator(resolver, provider, preparation)+ .buildEpisodeWindow(+ current = PlayerPreloadItem(+ key = "current",+ streamInfo = StreamInfo("https://example.com/current.mp4"),+ contentType = PlayerPreloadContentType.VOD+ ),+ series = series,+ currentEpisode = currentEpisode,+ providerId = 7L,+ isCurrent = { isCurrent }+ )++ assertThat(window).isNull()+ }++ @Test+ fun `last episode produces a current-only window`() = runTest {+ val lastEpisode = episode(id = 9L, number = 9)+ val series = Series(+ id = 10L,+ name = "Example",+ seasons = listOf(Season(seasonNumber = 1, episodes = listOf(lastEpisode)))+ )+ val resolver = mock<PlayerContentResolver>()+ val provider = mock<PlayerProviderCoordinator>()+ val preparation = mock<PlayerPreparationCoordinator>()+ val current = PlayerPreloadItem(+ key = "current",+ streamInfo = StreamInfo("https://example.com/current.mp4"),+ contentType = PlayerPreloadContentType.VOD+ )++ val window = PlayerPreloadWindowCoordinator(resolver, provider, preparation)+ .buildEpisodeWindow(+ current = current,+ series = series,+ currentEpisode = lastEpisode,+ providerId = 7L,+ isCurrent = { true }+ )++ assertThat(window?.items).containsExactly(+ current.copy(key = "episode:7:9")+ )+ assertThat(window?.currentIndex).isEqualTo(0)+ }++ private fun episode(id: Long, number: Int) = Episode(+ id = id,+ title = "Episode $id",+ episodeNumber = number,+ seasonNumber = 1,+ streamUrl = "https://example.com/$id.mp4",+ providerId = 7L,+ seriesId = 10L+ )++ private fun archiveChannel() = Channel(+ id = 1L,+ name = "Example TV",+ streamUrl = "xtream://provider/live/1",+ streamId = 42L,+ providerId = 7L,+ catchUpSupported = true,+ catchUpDays = 2+ )++ private fun program(id: Long, start: Long, end: Long) = Program(+ id = id,+ channelId = "channel-1",+ title = "Program $id",+ startTime = start,+ endTime = end,+ hasArchive = true+ )+}diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupportTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupportTest.ktnew file mode 100644index 00000000..5cc17223--- /dev/null+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreloadWindowSupportTest.kt@@ -0,0 +1,175 @@+package com.streamvault.feature.playback.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.Season+import com.streamvault.domain.model.Series+import org.junit.Test++class PlayerPreloadWindowSupportTest {++ @Test+ fun `catch-up timeline includes selected program and sorts the bounded guide slices`() {+ val selected = program(id = 2L, start = 2_000L, end = 3_000L)++ val timeline = buildCatchUpPreloadTimeline(+ programHistory = listOf(program(id = 1L, start = 1_000L, end = 2_000L)),+ currentProgram = program(id = 3L, start = 3_000L, end = 4_000L),+ upcomingPrograms = listOf(program(id = 4L, start = 4_000L, end = 5_000L)),+ selectedProgram = selected+ )++ assertThat(timeline.map { it.id }).containsExactly(1L, 2L, 3L, 4L).inOrder()+ }++ @Test+ fun `refresh fingerprint changes when current stream or neighbor keys change`() {+ val stream = com.streamvault.domain.model.StreamInfo(url = "https://example.com/current.m3u8")+ val baseline = buildPreloadWindowRefreshFingerprint(+ contentType = com.streamvault.player.PlayerPreloadContentType.VOD,+ providerId = 7L,+ currentKey = "current",+ neighborKeys = listOf("previous", "next"),+ currentStreamInfo = stream+ )++ assertThat(+ buildPreloadWindowRefreshFingerprint(+ contentType = com.streamvault.player.PlayerPreloadContentType.VOD,+ providerId = 7L,+ currentKey = "current",+ neighborKeys = listOf("previous", "other"),+ currentStreamInfo = stream+ )+ ).isNotEqualTo(baseline)+ assertThat(+ buildPreloadWindowRefreshFingerprint(+ contentType = com.streamvault.player.PlayerPreloadContentType.VOD,+ providerId = 7L,+ currentKey = "current",+ neighborKeys = listOf("previous", "next"),+ currentStreamInfo = stream.copy(url = "https://example.com/refreshed.m3u8")+ )+ ).isNotEqualTo(baseline)+ }++ @Test+ fun `episode neighbors cross season boundaries in playback order`() {+ val first = episode(id = 1, season = 1, number = 1)+ val second = episode(id = 2, season = 1, number = 2)+ val third = episode(id = 3, season = 2, number = 1)+ val series = Series(+ id = 10L,+ name = "Example",+ seasons = listOf(+ Season(seasonNumber = 2, episodes = listOf(third)),+ Season(seasonNumber = 1, episodes = listOf(second, first))+ )+ )++ val neighbors = buildEpisodePreloadNeighbors(series, third)++ assertThat(neighbors?.map(Episode::id)).containsExactly(2L, 3L).inOrder()+ }++ @Test+ fun `episode neighbor helper handles first and last episodes`() {+ val first = episode(id = 1, season = 1, number = 1)+ val second = episode(id = 2, season = 1, number = 2)+ val series = Series(+ id = 10L,+ name = "Example",+ seasons = listOf(Season(seasonNumber = 1, episodes = listOf(first, second)))+ )++ assertThat(buildEpisodePreloadNeighbors(series, first)?.map(Episode::id))+ .containsExactly(1L, 2L)+ .inOrder()+ assertThat(buildEpisodePreloadNeighbors(series, second)?.map(Episode::id))+ .containsExactly(1L, 2L)+ .inOrder()+ }++ @Test+ fun `catch up neighbors are chronological and archive playable`() {+ val channel = archiveChannel()+ val previous = program(id = 1L, start = 30_000L, end = 40_000L, hasArchive = true)+ val selected = program(id = 2L, start = 50_000L, end = 60_000L, hasArchive = true)+ val future = program(id = 3L, start = 130_000L, end = 140_000L, hasArchive = false)+ val next = program(id = 4L, start = 90_000L, end = 100_000L, hasArchive = true)++ val neighbors = buildCatchUpPreloadNeighbors(+ selectedProgram = selected,+ channel = channel,+ timelinePrograms = listOf(next, future, selected, previous),+ now = 120_000L+ )++ assertThat(neighbors?.map(Program::id)).containsExactly(1L, 2L, 4L).inOrder()+ }++ @Test+ fun `catch up neighbor helper returns null when selected program is absent`() {+ val channel = archiveChannel()+ val selected = program(id = 2L, start = 50_000L, end = 60_000L, hasArchive = true)++ assertThat(+ buildCatchUpPreloadNeighbors(+ selectedProgram = selected,+ channel = channel,+ timelinePrograms = emptyList(),+ now = 120_000L+ )+ ).isNull()+ }++ @Test+ fun `preload keys are stable and do not contain stream urls`() {+ val episodeKey = episodePreloadKey(providerId = 7L, episode = episode(episodeId = 42L))+ val catchUpKey = catchUpPreloadKey(+ providerId = 7L,+ channel = archiveChannel(id = 8L),+ program = program(id = 9L, start = 50_000L, end = 60_000L, hasArchive = true)+ )++ assertThat(episodeKey).isEqualTo("episode:7:42")+ assertThat(catchUpKey).isEqualTo("catchup:7:8:50000:60000")+ assertThat(episodeKey).doesNotContain("http")+ assertThat(catchUpKey).doesNotContain("http")+ }++ private fun episode(+ id: Long = 1L,+ season: Int = 1,+ number: Int = 1,+ episodeId: Long = 0L+ ) = Episode(+ id = id,+ title = "Episode $id",+ episodeNumber = number,+ seasonNumber = season,+ streamUrl = "https://example.com/$id.mp4",+ episodeId = episodeId+ )++ private fun archiveChannel(id: Long = 1L) = Channel(+ id = id,+ name = "Example TV",+ streamUrl = "xtream://provider/live/$id",+ streamId = id,+ providerId = 7L,+ catchUpSupported = true,+ catchUpDays = 2+ )++ private fun program(id: Long, start: Long, end: Long, hasArchive: Boolean = false) = Program(+ id = id,+ channelId = "channel-1",+ title = "Program $id",+ startTime = start,+ endTime = end,+ hasArchive = hasArchive+ )+}diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinatorPreloadTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinatorPreloadTest.ktnew file mode 100644index 00000000..0e482ac0--- /dev/null+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinatorPreloadTest.kt@@ -0,0 +1,65 @@+package com.streamvault.feature.playback.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.feature.playback.api.PlaybackStreamPreparer+import com.streamvault.player.PlayerEngine+import kotlinx.coroutines.test.runTest+import okhttp3.OkHttpClient+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++class PlayerPreparationCoordinatorPreloadTest {++ @Test+ fun `preload preparation preserves prepared stream without touching foreground engine`() = runTest {+ val preparer = mock<PlaybackStreamPreparer>()+ val engine = mock<PlayerEngine>()+ val input = StreamInfo("https://example.com/logical.m3u8")+ val prepared = input.copy(+ url = "https://cdn.example.com/prepared.m3u8",+ headers = mapOf("Authorization" to "Bearer redacted")+ )+ whenever(preparer.prepare(input)).thenReturn(Result.success(prepared))+ val coordinator = PlayerPreparationCoordinator(+ streamPreparer = preparer,+ playerPreferencesCoordinator = mock(),+ providerRepository = mock<ProviderRepository>(),+ okHttpClient = OkHttpClient(),+ playerEngineCoordinator = PlayerEngineCoordinator(engine),+ playerContentResolver = mock()+ )++ val result = coordinator.prepareStreamForPreload(input)++ assertThat(result).isEqualTo(prepared)+ verify(engine, never()).prepare(any())+ verify(engine, never()).setMuted(any())+ }++ @Test+ fun `expired preload stream is rejected before provider preparation`() = runTest {+ val preparer = mock<PlaybackStreamPreparer>()+ val input = StreamInfo(+ url = "https://example.com/expired.mp4",+ expirationTime = System.currentTimeMillis() - 1L+ )+ val coordinator = PlayerPreparationCoordinator(+ streamPreparer = preparer,+ playerPreferencesCoordinator = mock(),+ providerRepository = mock<ProviderRepository>(),+ okHttpClient = OkHttpClient(),+ playerEngineCoordinator = PlayerEngineCoordinator(mock()),+ playerContentResolver = mock()+ )++ assertThat(coordinator.prepareStreamForPreload(input)).isNull()+ verify(preparer, never()).prepare(any())+ }+}diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinatorTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinatorTest.ktnew file mode 100644index 00000000..5a424eee--- /dev/null+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerThumbnailCoordinatorTest.kt@@ -0,0 +1,93 @@+package com.streamvault.feature.playback.player++import android.graphics.Bitmap+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import com.streamvault.player.playback.FrameThumbnailExtractor+import com.streamvault.player.playback.FrameThumbnailRequest+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class PlayerThumbnailCoordinatorTest {++ private val media3Extractor: FrameThumbnailExtractor = mock()+ private val legacyProvider: SeekThumbnailProvider = mock()+ private val coordinator = PlayerThumbnailCoordinator(media3Extractor, legacyProvider)+ private val streamInfo = StreamInfo(+ url = "https://example.test/video.mp4",+ streamType = StreamType.PROGRESSIVE+ )++ @Test+ fun `returns Media3 frame without invoking legacy backend`() = runTest {+ val bitmap: Bitmap = mock()+ whenever(media3Extractor.supports(any())).thenReturn(true)+ whenever(media3Extractor.loadFrame(any(), eq(10_000L))).thenReturn(bitmap)++ val result = coordinator.loadFrame(+ streamUrl = streamInfo.url,+ streamInfo = streamInfo,+ isLive = false,+ positionMs = 10_000L+ )++ assertThat(result).isSameInstanceAs(bitmap)+ verify(legacyProvider, never()).loadFrame(any(), any())+ }++ @Test+ fun `falls back to legacy backend when Media3 extraction fails`() = runTest {+ val bitmap: Bitmap = mock()+ whenever(media3Extractor.supports(any())).thenReturn(true)+ whenever(media3Extractor.loadFrame(any(), eq(10_000L))).thenReturn(null)+ whenever(legacyProvider.supportsFrameExtraction(streamInfo.url)).thenReturn(true)+ whenever(legacyProvider.loadFrame(streamInfo.url, 10_000L)).thenReturn(bitmap)++ val result = coordinator.loadFrame(+ streamUrl = streamInfo.url,+ streamInfo = streamInfo,+ isLive = false,+ positionMs = 10_000L+ )++ assertThat(result).isSameInstanceAs(bitmap)+ verify(legacyProvider).loadFrame(streamInfo.url, 10_000L)+ }++ @Test+ fun `falls back to legacy backend when Media3 does not support the request`() = runTest {+ val bitmap: Bitmap = mock()+ whenever(media3Extractor.supports(any())).thenReturn(false)+ whenever(legacyProvider.supportsFrameExtraction(streamInfo.url)).thenReturn(true)+ whenever(legacyProvider.loadFrame(streamInfo.url, 10_000L)).thenReturn(bitmap)++ val result = coordinator.loadFrame(+ streamUrl = streamInfo.url,+ streamInfo = streamInfo,+ isLive = false,+ positionMs = 10_000L+ )++ assertThat(result).isSameInstanceAs(bitmap)+ verify(media3Extractor, never()).loadFrame(any(), any())+ verify(legacyProvider).loadFrame(streamInfo.url, 10_000L)+ }++ @Test+ fun `clears both thumbnail backend caches`() {+ coordinator.clearCache()++ verify(media3Extractor).clearCache()+ verify(legacyProvider).clearCache()+ }+}diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 131c9605..9159f958 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -71,6 +71,7 @@ media3-exoplayer-dash = { group = "androidx.media3", name = "media3-exoplayer-damedia3-exoplayer-smoothstreaming = { group = "androidx.media3", name = "media3-exoplayer-smoothstreaming", version.ref = "media3" }media3-exoplayer-rtsp = { group = "androidx.media3", name = "media3-exoplayer-rtsp", version.ref = "media3" }media3-datasource-okhttp = { group = "androidx.media3", name = "media3-datasource-okhttp", version.ref = "media3" }+media3-inspector-frame = { group = "androidx.media3", name = "media3-inspector-frame", version.ref = "media3" }media3-session = { group = "androidx.media3", name = "media3-session", version.ref = "media3" }media3-ui = { group = "androidx.media3", name = "media3-ui", version.ref = "media3" }diff --git a/player/build.gradle.kts b/player/build.gradle.ktsindex cf82c465..427c6ec1 100644--- a/player/build.gradle.kts+++ b/player/build.gradle.kts@@ -197,6 +197,7 @@ dependencies {implementation(libs.media3.exoplayer.smoothstreaming)implementation(libs.media3.exoplayer.rtsp) // PE-H03: RTSP stream supportimplementation(libs.media3.datasource.okhttp)+ implementation(libs.media3.inspector.frame)implementation(libs.media3.session)implementation(libs.media3.ui)diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex d200759d..0138ee46 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -66,6 +66,7 @@ import com.streamvault.player.playback.PlaybackRetryContextimport com.streamvault.player.playback.PlayerDataSourceFactoryProviderimport com.streamvault.player.playback.PlayerErrorClassifierimport com.streamvault.player.playback.PlayerMediaSourceFactory+import com.streamvault.player.playback.Media3PreloadWindowManagerimport com.streamvault.player.playback.PlayerRetryPolicyimport com.streamvault.player.playback.PlayerTimeoutProfileimport com.streamvault.player.playback.PreloadCoordinator@@ -348,6 +349,8 @@ class Media3PlayerEngine @Inject constructor()private val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceFactoryProvider)private val preloadCoordinator = PreloadCoordinator()+ private var preloadWindowManager: Media3PreloadWindowManager? = null+ private var pendingPreloadWindow: PlayerPreloadWindow? = nullprivate val compatibilityProfile: PlaybackCompatibilityProfile = DefaultPlaybackCompatibilityProfileprivate val audioDecoderPreferencePolicy = DefaultDecoderPreferencePolicy()private val videoDecoderPreferencePolicy = DefaultDecoderPreferencePolicy()@@ -845,6 +848,9 @@ class Media3PlayerEngine @Inject constructor(override fun preload(streamInfo: StreamInfo?) {if (streamInfo == null) {preloadCoordinator.invalidate("cleared")+ preloadWindowManager?.clearWindow()+ pendingPreloadWindow = null+ Log.i(TAG, "preload-window reset reason=legacy-clear")return}if (streamInfo.url == lastStreamInfo?.url) return@@ -865,6 +871,27 @@ class Media3PlayerEngine @Inject constructor(preloadCoordinator.store(mediaId, streamInfo, playbackPlan.resolvedStreamType, mediaSource)}+ override fun preloadWindow(window: PlayerPreloadWindow) {+ val normalized = normalizePlayerPreloadWindow(window)+ if (normalized.items.isEmpty()) {+ preloadWindowManager?.clearWindow()+ pendingPreloadWindow = null+ Log.i(TAG, "preload-window skipped reason=empty-or-invalid")+ return+ }++ // The legacy cache is intended for adjacent live-channel zapping. A VOD or+ // catch-up window must not accidentally reuse that source for another class.+ preloadCoordinator.invalidate("sliding-window")+ pendingPreloadWindow = normalized+ preloadWindowManager?.updateWindow(normalized)+ Log.i(+ TAG,+ "preload-window accepted currentIndex=${normalized.currentIndex} " ++ "sourceCount=${normalized.items.size} manager=${preloadWindowManager != null}"+ )+ }+override fun createRenderView(context: Context,resizeMode: PlayerSurfaceResizeMode,@@ -915,6 +942,7 @@ class Media3PlayerEngine @Inject constructor(retryJob?.cancel()retryJob = nullpreloadCoordinator.release()+ pendingPreloadWindow = nullstatsCollector.stop()audioFocusController.release()mediaSession?.release()@@ -922,6 +950,11 @@ class Media3PlayerEngine @Inject constructor(viewBinder.clear()exoPlayer?.release()exoPlayer = null+ preloadWindowManager?.release()+ if (preloadWindowManager != null) {+ Log.i(TAG, "preload-window manager-released reason=engine-reset")+ }+ preloadWindowManager = nulllastStreamInfo = nulllastMediaId = nullcurrentRetryPolicy = null@@ -1134,14 +1167,22 @@ class Media3PlayerEngine @Inject constructor(}player.playbackParameters = PlaybackParameters(_playbackSpeed.value)- val mediaSource = preloadCoordinator.tryReuse(mediaId, streamInfo, currentResolvedStreamType)- ?: mediaSourceFactory.create(- streamInfo = streamInfo,- resolvedStreamType = currentResolvedStreamType,- retryPolicy = currentRetryPolicy!!,- vodHttpProtocolMode = requestedVodHttpProtocolMode,- preload = false- ).second+ val managedMediaSource = preloadWindowManager?.getMediaSource(streamInfo)+ val mediaSource = managedMediaSource+ ?: preloadCoordinator.tryReuse(mediaId, streamInfo, currentResolvedStreamType)+ ?: run {+ Log.i(TAG, "preload-source direct-fallback mediaId=$mediaId")+ mediaSourceFactory.create(+ streamInfo = streamInfo,+ resolvedStreamType = currentResolvedStreamType,+ retryPolicy = currentRetryPolicy!!,+ vodHttpProtocolMode = requestedVodHttpProtocolMode,+ preload = false+ ).second+ }+ if (managedMediaSource != null) {+ Log.i(TAG, "preload-source reused mediaId=$mediaId source=window")+ }preloadCoordinator.onPlaybackStarted(mediaId)player.setMediaSource(mediaSource)player.prepare()@@ -1183,6 +1224,11 @@ class Media3PlayerEngine @Inject constructor(mediaSession = nullexisting.release()exoPlayer = null+ preloadWindowManager?.release()+ if (preloadWindowManager != null) {+ Log.i(TAG, "preload-window manager-recreated reason=player-recreate")+ }+ preloadWindowManager = nullviewBinder.attachPlayer(null)// The caller (prepareInternal) will create a fresh player and set it up fully.}@@ -1193,6 +1239,7 @@ class Media3PlayerEngine @Inject constructor(exoPlayer = playerstatsCollector.bind { exoPlayer }audioFocusController.reapplyVolume()+ pendingPreloadWindow?.let { preloadWindowManager?.updateWindow(it) }if (enableMediaSession) {mediaSession = MediaSession.Builder(context, player).setId(mediaSessionId)@@ -1227,20 +1274,31 @@ class Media3PlayerEngine @Inject constructor(.setFallbackMaxPlaybackSpeed(1.0f).build()- return ExoPlayer.Builder(context, renderersFactory)- .setLoadControl(loadControl)- .setBandwidthMeter(bandwidthMeter)- .setLivePlaybackSpeedControl(livePlaybackSpeedControl)- .setSeekBackIncrementMs(10_000)- .setSeekForwardIncrementMs(10_000)- .setAudioAttributes(- Media3AudioAttributes.Builder()- .setUsage(C.USAGE_MEDIA)- .setContentType(C.AUDIO_CONTENT_TYPE_UNKNOWN)- .build(),- false- )- .build()+ val preloadManager = Media3PreloadWindowManager(+ context = context,+ mediaSourceFactory = mediaSourceFactory,+ dataSourceFactoryProvider = dataSourceFactoryProvider,+ bandwidthMeter = bandwidthMeter+ )+ preloadWindowManager = preloadManager+ return preloadManager.createPlayer(+ renderersFactory = renderersFactory,+ loadControl = loadControl,+ preloadDataSourceFactory = createPreloadDataSourceFactory(),+ configure = { builder ->+ builder+ .setLivePlaybackSpeedControl(livePlaybackSpeedControl)+ .setSeekBackIncrementMs(10_000)+ .setSeekForwardIncrementMs(10_000)+ .setAudioAttributes(+ Media3AudioAttributes.Builder()+ .setUsage(C.USAGE_MEDIA)+ .setContentType(C.AUDIO_CONTENT_TYPE_UNKNOWN)+ .build(),+ false+ )+ }+ ).apply {videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FITplaybackParameters = PlaybackParameters(_playbackSpeed.value)@@ -1253,6 +1311,25 @@ class Media3PlayerEngine @Inject constructor(}}+ private fun createPreloadDataSourceFactory(): androidx.media3.datasource.DataSource.Factory {+ val streamInfo = lastStreamInfo ?: return androidx.media3.datasource.DefaultDataSource.Factory(context)+ val resolvedType = runCatching {+ buildPlaybackPreparationPlan(+ streamInfo = streamInfo,+ preload = true,+ playbackStarted = { false }+ ).resolvedStreamType+ }.getOrNull() ?: return androidx.media3.datasource.DefaultDataSource.Factory(context)+ return runCatching {+ dataSourceFactoryProvider.createFactory(+ streamInfo = streamInfo,+ resolvedStreamType = resolvedType,+ vodHttpProtocolMode = requestedVodHttpProtocolMode,+ preload = true+ ).second+ }.getOrElse { androidx.media3.datasource.DefaultDataSource.Factory(context) }+ }+private fun PlaybackBufferPolicy.describeForLog(resolvedStreamType: ResolvedStreamType,bufferMode: PlaybackBufferModediff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.ktindex e4da8f20..55d8ea7a 100644--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt@@ -129,6 +129,15 @@ interface PlayerEngine {*/fun preload(streamInfo: StreamInfo?)+ /**+ * Preload a bounded VOD or catch-up navigation window. Implementations that+ * do not support sliding-window preloading may safely ignore this request.+ */+ fun preloadWindow(window: PlayerPreloadWindow) {}++ /** Clears both sliding-window and legacy single-item preload state. */+ fun clearPreloadWindow() = preload(null)+fun createRenderView(context: Context,resizeMode: PlayerSurfaceResizeMode,diff --git a/player/src/main/java/com/streamvault/player/PlayerPreload.kt b/player/src/main/java/com/streamvault/player/PlayerPreload.ktnew file mode 100644index 00000000..b908f65a--- /dev/null+++ b/player/src/main/java/com/streamvault/player/PlayerPreload.kt@@ -0,0 +1,98 @@+package com.streamvault.player++import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.util.StreamEntryUrlPolicy++enum class PlayerPreloadContentType {+ VOD,+ CATCH_UP,+ LIVE+}++data class PlayerPreloadItem(+ val key: String,+ val streamInfo: StreamInfo,+ val contentType: PlayerPreloadContentType+)++data class PlayerPreloadWindow(+ val items: List<PlayerPreloadItem>,+ val currentIndex: Int+)++/**+ * Keeps the player-facing preload window small and deterministic.+ *+ * Stream type, expiry, and DRM eligibility are deliberately left to the player+ * manager because they may require the resolved preparation plan and current+ * time. This policy only handles the data that can be checked at the boundary.+ */+fun normalizePlayerPreloadWindow(+ window: PlayerPreloadWindow,+ maxManagedItems: Int = 3+): PlayerPreloadWindow {+ if (maxManagedItems <= 0 || window.currentIndex !in window.items.indices) {+ return emptyPlayerPreloadWindow()+ }++ val candidates = mutableListOf<PlayerPreloadItem>()+ val firstIndexByKey = mutableMapOf<String, Int>()+ var currentKey: String? = null++ window.items.forEachIndexed { index, item ->+ val key = item.key.trim()+ val url = item.streamInfo.url.trim()+ val isEligible = key.isNotEmpty() &&+ StreamEntryUrlPolicy.isAllowed(url) &&+ item.contentType != PlayerPreloadContentType.LIVE++ if (index == window.currentIndex && !isEligible) {+ currentKey = null+ } else if (isEligible) {+ val normalizedItem = item.copy(+ key = key,+ streamInfo = item.streamInfo.copy(url = url)+ )+ if (index == window.currentIndex) {+ currentKey = key+ }+ if (key !in firstIndexByKey) {+ firstIndexByKey[key] = candidates.size+ candidates += normalizedItem+ }+ }+ }++ val currentPosition = currentKey?.let(firstIndexByKey::get) ?: return emptyPlayerPreloadWindow()+ val maxItems = minOf(maxManagedItems, 3)+ val startPosition: Int+ val endPosition: Int+ when (maxItems) {+ 1 -> {+ startPosition = currentPosition+ endPosition = currentPosition+ }+ 2 -> {+ if (currentPosition > 0) {+ startPosition = currentPosition - 1+ endPosition = currentPosition+ } else {+ startPosition = currentPosition+ endPosition = minOf(candidates.lastIndex, currentPosition + 1)+ }+ }+ else -> {+ startPosition = maxOf(0, currentPosition - 1)+ endPosition = minOf(candidates.lastIndex, currentPosition + 1)+ }+ }+ val selected = candidates.subList(startPosition, endPosition + 1).toList()++ return PlayerPreloadWindow(+ items = selected,+ currentIndex = currentPosition - startPosition+ )+}++private fun emptyPlayerPreloadWindow(): PlayerPreloadWindow =+ PlayerPreloadWindow(items = emptyList(), currentIndex = -1)diff --git a/player/src/main/java/com/streamvault/player/playback/FrameThumbnailExtractor.kt b/player/src/main/java/com/streamvault/player/playback/FrameThumbnailExtractor.ktnew file mode 100644index 00000000..2f943b1b--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/FrameThumbnailExtractor.kt@@ -0,0 +1,40 @@+package com.streamvault.player.playback++import android.graphics.Bitmap+import com.streamvault.domain.model.StreamInfo+import java.net.URI+import java.util.Locale++/** Stream metadata needed to decide whether a VOD frame can be extracted safely. */+data class FrameThumbnailRequest(+ val streamInfo: StreamInfo,+ val isLive: Boolean+)++/** Player-side boundary for decoded seek-preview frames. */+interface FrameThumbnailExtractor {+ fun supports(request: FrameThumbnailRequest): Boolean++ suspend fun loadFrame(request: FrameThumbnailRequest, positionMs: Long): Bitmap?++ fun clearCache()+}++internal fun supportsMedia3FrameThumbnail(request: FrameThumbnailRequest): Boolean {+ if (request.isLive || request.streamInfo.drmInfo != null) return false++ val resolvedStreamType = StreamTypeResolver.resolve(request.streamInfo)+ if (resolvedStreamType !in SUPPORTED_FRAME_THUMBNAIL_TYPES) return false++ val uri = runCatching { URI(request.streamInfo.url) }.getOrNull() ?: return false+ return uri.scheme?.lowercase(Locale.ROOT) in SUPPORTED_FRAME_THUMBNAIL_SCHEMES+}++private val SUPPORTED_FRAME_THUMBNAIL_TYPES = setOf(+ ResolvedStreamType.PROGRESSIVE,+ ResolvedStreamType.HLS,+ ResolvedStreamType.DASH,+ ResolvedStreamType.SMOOTH_STREAMING+)++private val SUPPORTED_FRAME_THUMBNAIL_SCHEMES = setOf("http", "https", "file", "content")diff --git a/player/src/main/java/com/streamvault/player/playback/Media3FrameThumbnailExtractor.kt b/player/src/main/java/com/streamvault/player/playback/Media3FrameThumbnailExtractor.ktnew file mode 100644index 00000000..f4c0bd92--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/Media3FrameThumbnailExtractor.kt@@ -0,0 +1,241 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import android.content.Context+import android.graphics.Bitmap+import android.util.Log+import androidx.media3.common.MediaItem+import androidx.media3.inspector.frame.FrameExtractor+import androidx.media3.common.util.UnstableApi+import androidx.media3.exoplayer.SeekParameters+import androidx.media3.exoplayer.source.MediaSource+import com.streamvault.domain.model.StreamInfo+import dagger.hilt.android.qualifiers.ApplicationContext+import java.util.concurrent.CancellationException+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import javax.inject.Inject+import javax.inject.Singleton+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import okhttp3.OkHttpClient+import com.google.common.util.concurrent.MoreExecutors++internal fun interface FrameThumbnailSessionFactory {+ fun create(request: FrameThumbnailRequest): FrameThumbnailSession+}++internal interface FrameThumbnailSession {+ suspend fun frameAt(positionMs: Long): Bitmap?++ fun close()+}++@Singleton+@UnstableApi+class Media3FrameThumbnailExtractor @Inject constructor(+ @param:ApplicationContext private val context: Context,+ private val okHttpClient: OkHttpClient+) : FrameThumbnailExtractor {+ private companion object {+ private const val TAG = "Media3FrameThumbnail"+ private const val FRAME_BUCKET_MS = 10_000L+ private const val MAX_PREVIEW_WIDTH = 480+ private const val EXTRACTION_TIMEOUT_MS = 8_000L+ }++ private val dataSourceFactoryProvider = PlayerDataSourceFactoryProvider(+ context = context,+ baseClient = okHttpClient+ )+ private val playerMediaSourceFactory = PlayerMediaSourceFactory(dataSourceFactoryProvider)+ private val extractionDispatcher: CoroutineDispatcher =+ Dispatchers.IO.limitedParallelism(1)+ private val bitmapCache = object : android.util.LruCache<String, Bitmap>(+ (Runtime.getRuntime().maxMemory() / 1024L / 24L).toInt()+ ) {+ override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount / 1024+ }+ private var sessionFactory: FrameThumbnailSessionFactory = FrameThumbnailSessionFactory(::createSession)++ internal constructor(+ context: Context,+ okHttpClient: OkHttpClient,+ sessionFactory: FrameThumbnailSessionFactory+ ) : this(context, okHttpClient) {+ this.sessionFactory = sessionFactory+ }++ override fun supports(request: FrameThumbnailRequest): Boolean =+ supportsMedia3FrameThumbnail(request)++ override suspend fun loadFrame(request: FrameThumbnailRequest, positionMs: Long): Bitmap? {+ if (!supports(request)) return null++ val bucketPositionMs = bucketPositionMs(positionMs)+ val cacheKey = cacheKey(request.streamInfo, bucketPositionMs)+ synchronized(bitmapCache) {+ bitmapCache.get(cacheKey)?.let {+ Log.d(+ TAG,+ "frame-thumbnail backend=media3 result=cache-hit " ++ "streamType=${StreamTypeResolver.resolve(request.streamInfo)} positionMs=$bucketPositionMs"+ )+ return it+ }+ }++ return withContext(extractionDispatcher) {+ synchronized(bitmapCache) {+ bitmapCache.get(cacheKey)?.let { return@withContext it }+ }++ val startedAt = System.nanoTime()+ val session = try {+ sessionFactory.create(request)+ } catch (error: Exception) {+ logFailure(request, bucketPositionMs, startedAt, error)+ return@withContext null+ }++ try {+ withTimeoutOrNull(EXTRACTION_TIMEOUT_MS) {+ val rawBitmap = session.frameAt(bucketPositionMs) ?: return@withTimeoutOrNull null+ val scaledBitmap = rawBitmap.scaleDown(MAX_PREVIEW_WIDTH)+ synchronized(bitmapCache) {+ bitmapCache.put(cacheKey, scaledBitmap)+ }+ Log.d(+ TAG,+ "frame-thumbnail backend=media3 result=success " ++ "streamType=${StreamTypeResolver.resolve(request.streamInfo)} " ++ "positionMs=$bucketPositionMs elapsedMs=${elapsedMs(startedAt)}"+ )+ scaledBitmap+ } ?: run {+ Log.w(+ TAG,+ "frame-thumbnail backend=media3 result=timeout " ++ "streamType=${StreamTypeResolver.resolve(request.streamInfo)} " ++ "positionMs=$bucketPositionMs elapsedMs=${elapsedMs(startedAt)}"+ )+ null+ }+ } catch (error: CancellationException) {+ Log.d(+ TAG,+ "frame-thumbnail backend=media3 result=cancelled " ++ "streamType=${StreamTypeResolver.resolve(request.streamInfo)} positionMs=$bucketPositionMs"+ )+ throw error+ } catch (error: Exception) {+ logFailure(request, bucketPositionMs, startedAt, error)+ null+ } finally {+ runCatching { session.close() }+ }+ }+ }++ override fun clearCache() {+ synchronized(bitmapCache) {+ bitmapCache.evictAll()+ }+ }++ private fun createSession(request: FrameThumbnailRequest): FrameThumbnailSession {+ val resolvedStreamType = StreamTypeResolver.resolve(request.streamInfo)+ val timeoutProfile = PlayerTimeoutProfile.PRELOAD+ val retryPolicy = PlayerRetryPolicy(+ streamContext = PlaybackRetryContext(+ resolvedStreamType = resolvedStreamType,+ timeoutProfile = timeoutProfile+ ),+ playbackStarted = { false }+ )+ val (_, mediaSourceFactory) = playerMediaSourceFactory.createMediaSourceFactory(+ streamInfo = request.streamInfo,+ resolvedStreamType = resolvedStreamType,+ retryPolicy = retryPolicy,+ preload = true+ )+ return Media3FrameThumbnailSession(+ context = context,+ mediaItem = playerMediaSourceFactory.mediaItemFor(request.streamInfo),+ mediaSourceFactory = mediaSourceFactory+ )+ }++ private fun cacheKey(streamInfo: StreamInfo, bucketPositionMs: Long): String =+ "${playerMediaSourceFactory.mediaIdFor(streamInfo)}#$bucketPositionMs"++ private fun bucketPositionMs(positionMs: Long): Long =+ (positionMs.coerceAtLeast(0L) / FRAME_BUCKET_MS) * FRAME_BUCKET_MS++ private fun logFailure(+ request: FrameThumbnailRequest,+ bucketPositionMs: Long,+ startedAt: Long,+ error: Exception+ ) {+ Log.w(+ TAG,+ "frame-thumbnail backend=media3 result=failure " ++ "streamType=${StreamTypeResolver.resolve(request.streamInfo)} " ++ "positionMs=$bucketPositionMs elapsedMs=${elapsedMs(startedAt)} " ++ "error=${error::class.java.simpleName}"+ )+ }++ private fun elapsedMs(startedAt: Long): Long =+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt)++ private fun Bitmap.scaleDown(maxWidth: Int): Bitmap {+ if (width <= maxWidth || width <= 0 || height <= 0) return this+ val scaledHeight = (height * (maxWidth.toFloat() / width.toFloat()))+ .toInt()+ .coerceAtLeast(1)+ return Bitmap.createScaledBitmap(this, maxWidth, scaledHeight, true)+ }+}++@UnstableApi+private class Media3FrameThumbnailSession(+ context: Context,+ mediaItem: MediaItem,+ mediaSourceFactory: MediaSource.Factory+) : FrameThumbnailSession {+ private val extractor = FrameExtractor.Builder(context, mediaItem)+ .setMediaSourceFactory(mediaSourceFactory)+ .setSeekParameters(SeekParameters.CLOSEST_SYNC)+ .build()++ override suspend fun frameAt(positionMs: Long): Bitmap? =+ suspendCancellableCoroutine { continuation ->+ val future = extractor.getFrame(positionMs)+ future.addListener(+ {+ if (!continuation.isActive) return@addListener+ try {+ continuation.resume(future.get().bitmap)+ } catch (error: Throwable) {+ continuation.resumeWithException(error.cause ?: error)+ }+ },+ MoreExecutors.directExecutor()+ )+ continuation.invokeOnCancellation {+ future.cancel(true)+ }+ }++ override fun close() {+ extractor.close()+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt b/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.ktnew file mode 100644index 00000000..0df00837--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt@@ -0,0 +1,309 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import android.content.Context+import android.util.Log+import androidx.media3.common.MediaItem+import androidx.media3.common.util.UnstableApi+import androidx.media3.datasource.DataSource+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.LoadControl+import androidx.media3.exoplayer.RenderersFactory+import androidx.media3.exoplayer.source.MediaSource+import androidx.media3.exoplayer.source.preload.DefaultPreloadManager+import androidx.media3.exoplayer.source.preload.PreloadException+import androidx.media3.exoplayer.source.preload.PreloadManagerListener+import androidx.media3.exoplayer.source.preload.TargetPreloadStatusControl+import androidx.media3.exoplayer.upstream.BandwidthMeter+import com.streamvault.domain.model.StreamInfo+import com.streamvault.player.PlayerPreloadContentType+import com.streamvault.player.PlayerPreloadItem+import com.streamvault.player.PlayerPreloadWindow+import com.streamvault.player.normalizePlayerPreloadWindow+import kotlin.math.abs++internal const val PLAYER_PRELOAD_RANGE_MS = 3_000L++internal fun playerPreloadTargetStatus(+ currentIndex: Int?,+ rankingIndex: Int+): DefaultPreloadManager.PreloadStatus? {+ return if (currentIndex != null && abs(rankingIndex - currentIndex) == 1) {+ DefaultPreloadManager.PreloadStatus.specifiedRangeLoaded(+ 0L,+ PLAYER_PRELOAD_RANGE_MS+ )+ } else {+ null+ }+}++internal fun preloadStreamIdentity(streamInfo: StreamInfo): String {+ val headers = streamInfo.headers.entries+ .sortedBy { it.key }+ .joinToString("&") { "${it.key}=${it.value}" }+ val drm = streamInfo.drmInfo?.let { drmInfo ->+ val drmHeaders = drmInfo.headers.entries+ .sortedBy { it.key }+ .joinToString("&") { "${it.key}=${it.value}" }+ listOf(+ drmInfo.scheme,+ drmInfo.licenseUrl,+ drmHeaders,+ drmInfo.multiSession,+ drmInfo.forceDefaultLicenseUrl,+ drmInfo.playClearContentWithoutKey+ ).joinToString("|")+ }.orEmpty()+ return stableHash(+ listOf(+ streamInfo.url.trim(),+ streamInfo.title.orEmpty(),+ headers,+ streamInfo.userAgent.orEmpty(),+ streamInfo.playbackTransportPolicy,+ streamInfo.allowInvalidSsl,+ streamInfo.proxyHost.trim(),+ streamInfo.proxyPort,+ streamInfo.streamType,+ streamInfo.containerExtension.orEmpty(),+ streamInfo.catchUpUrl.orEmpty(),+ streamInfo.expirationTime,+ drm+ ).joinToString("|")+ )+}++@UnstableApi+internal class Media3PreloadWindowManager(+ private val context: Context,+ private val mediaSourceFactory: PlayerMediaSourceFactory,+ @Suppress("UNUSED_PARAMETER")+ private val dataSourceFactoryProvider: PlayerDataSourceFactoryProvider,+ private val bandwidthMeter: BandwidthMeter+) {++ private data class ManagedCandidate(+ val key: String,+ val streamInfo: StreamInfo,+ val mediaItem: MediaItem,+ val mediaSource: MediaSource,+ val rankingIndex: Int,+ val streamIdentity: String+ )++ private var preloadManager: DefaultPreloadManager? = null+ private var currentIndex: Int? = null+ private var released = false+ private val candidatesByKey = linkedMapOf<String, ManagedCandidate>()+ private val mediaItemsByStreamIdentity = mutableMapOf<String, MediaItem>()++ private val listener = object : PreloadManagerListener {+ override fun onCompleted(mediaItem: MediaItem) {+ safeLog(+ "preload completed mediaId=${mediaItem.mediaId} sourceCount=${candidatesByKey.size}"+ )+ }++ override fun onError(exception: PreloadException) {+ val failed = candidatesByKey.values.firstOrNull { it.mediaItem == exception.mediaItem }+ failed?.let { candidate ->+ preloadManager?.remove(candidate.mediaItem)+ candidatesByKey.remove(candidate.key)+ mediaItemsByStreamIdentity.remove(candidate.streamIdentity)+ }+ safeLog(+ "preload failed mediaId=${exception.mediaItem.mediaId} " ++ "candidateRemoved=${failed != null} sourceCount=${candidatesByKey.size}"+ )+ }+ }++ fun createPlayer(+ renderersFactory: RenderersFactory,+ loadControl: LoadControl,+ preloadDataSourceFactory: DataSource.Factory,+ configure: (ExoPlayer.Builder) -> Unit+ ): ExoPlayer {+ check(!released) { "Cannot create a preload player after release" }++ val rankingComparator = DefaultPreloadManager.SimpleRankingDataComparator()+ val targetStatusControl = object :+ TargetPreloadStatusControl<Int, DefaultPreloadManager.PreloadStatus> {+ override fun getTargetPreloadStatus(index: Int): DefaultPreloadManager.PreloadStatus =+ playerPreloadTargetStatus(currentIndex, index)+ ?: DefaultPreloadManager.PreloadStatus.PRELOAD_STATUS_NOT_PRELOADED+ }+ val builder = DefaultPreloadManager.Builder(+ context,+ rankingComparator,+ targetStatusControl+ )+ .setDataSourceFactory(preloadDataSourceFactory)+ .setRenderersFactory(renderersFactory)+ .setLoadControl(loadControl)+ .setBandwidthMeter(bandwidthMeter)++ preloadManager = builder.build().also { it.addListener(listener) }+ currentIndex = null+ safeLog("preload-window manager-created")++ return builder.buildExoPlayer(+ ExoPlayer.Builder(context, renderersFactory)+ .setLoadControl(loadControl)+ .setBandwidthMeter(bandwidthMeter)+ .apply(configure)+ )+ }++ fun updateWindow(window: PlayerPreloadWindow) {+ val manager = preloadManager ?: return+ if (released) return++ val normalized = normalizePlayerPreloadWindow(window)+ if (normalized.items.isEmpty()) {+ clearWindow()+ return+ }++ currentIndex = normalized.currentIndex+ manager.setCurrentPlayingIndex(normalized.currentIndex)++ val nextCandidates = linkedMapOf<String, ManagedCandidate>()+ normalized.items.forEachIndexed { rankingIndex, item ->+ val streamIdentity = preloadStreamIdentity(item.streamInfo)+ val existing = candidatesByKey[item.key]+ if (existing != null && existing.streamIdentity == streamIdentity) {+ nextCandidates[item.key] = existing.copy(rankingIndex = rankingIndex)+ return@forEachIndexed+ }+ existing?.let { manager.remove(it.mediaItem) }++ val candidate = createManagedCandidate(item, rankingIndex, streamIdentity)+ if (candidate != null) {+ manager.add(candidate.mediaSource, rankingIndex)+ nextCandidates[item.key] = candidate+ }+ }++ candidatesByKey.values+ .filter { it.key !in nextCandidates }+ .forEach { manager.remove(it.mediaItem) }+ candidatesByKey.clear()+ candidatesByKey.putAll(nextCandidates)+ mediaItemsByStreamIdentity.clear()+ candidatesByKey.values.forEach { candidate ->+ mediaItemsByStreamIdentity[candidate.streamIdentity] = candidate.mediaItem+ }+ manager.invalidate()+ safeLog(+ "preload-window accepted currentIndex=${normalized.currentIndex} " ++ "sourceCount=${candidatesByKey.size}"+ )+ }++ fun getMediaSource(streamInfo: StreamInfo): MediaSource? {+ val manager = preloadManager ?: return null+ if (released) return null+ val mediaItem = mediaItemsByStreamIdentity[preloadStreamIdentity(streamInfo)] ?: return null+ return manager.getMediaSource(mediaItem)+ }++ fun clearWindow() {+ val manager = preloadManager ?: return+ if (released) return+ manager.removeMediaItems(candidatesByKey.values.map(ManagedCandidate::mediaItem))+ candidatesByKey.clear()+ mediaItemsByStreamIdentity.clear()+ currentIndex = null+ manager.setCurrentPlayingIndex(-1)+ manager.invalidate()+ safeLog("preload-window reset reason=clear sourceCount=0")+ }++ fun release() {+ if (released) return+ released = true+ preloadManager?.clearListeners()+ preloadManager?.release()+ preloadManager = null+ candidatesByKey.clear()+ mediaItemsByStreamIdentity.clear()+ currentIndex = null+ safeLog("preload-window manager-released")+ }++ private fun createManagedCandidate(+ item: PlayerPreloadItem,+ rankingIndex: Int,+ streamIdentity: String+ ): ManagedCandidate? {+ if (item.contentType == PlayerPreloadContentType.LIVE || item.streamInfo.drmInfo != null) {+ logSkip(item, "ineligible-content")+ return null+ }+ if (item.streamInfo.expirationTime?.let { it <= System.currentTimeMillis() } == true) {+ logSkip(item, "expired")+ return null+ }++ val plan = runCatching {+ buildPlaybackPreparationPlan(+ streamInfo = item.streamInfo,+ preload = true,+ playbackStarted = { false }+ )+ }.getOrElse {+ logSkip(item, "plan-failed")+ return null+ }+ if (plan.resolvedStreamType == ResolvedStreamType.UNKNOWN ||+ plan.resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE ||+ plan.resolvedStreamType == ResolvedStreamType.RTSP+ ) {+ logSkip(item, "unsupported-stream")+ return null+ }++ val mediaSource = runCatching {+ mediaSourceFactory.create(+ streamInfo = item.streamInfo,+ resolvedStreamType = plan.resolvedStreamType,+ retryPolicy = plan.retryPolicy,+ preload = true+ ).second+ }.getOrElse {+ logSkip(item, "source-failed")+ return null+ }+ return ManagedCandidate(+ key = item.key,+ streamInfo = item.streamInfo,+ mediaItem = mediaSource.mediaItem,+ mediaSource = mediaSource,+ rankingIndex = rankingIndex,+ streamIdentity = streamIdentity+ )+ }++ private fun logSkip(item: PlayerPreloadItem, reason: String) {+ safeLog(+ "preload skipped key=${sanitizePreloadKey(item.key)} " ++ "kind=${item.contentType} reason=$reason"+ )+ }++ private fun sanitizePreloadKey(key: String): String =+ key.trim()+ .replace(Regex("[^A-Za-z0-9._:-]"), "_")+ .take(80)++ private fun safeLog(message: String) {+ runCatching { Log.i(TAG, message) }+ }++ private companion object {+ const val TAG = "Media3PreloadWindow"+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.ktindex 7956635d..73774c28 100644--- a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt@@ -62,24 +62,44 @@ class PlayerMediaSourceFactory(vodHttpProtocolMode: VodHttpProtocolMode = VodHttpProtocolMode.COMPATIBILITY_HTTP1,preload: Boolean = false): Pair<PlayerTimeoutProfile, MediaSource> {+ val (timeoutProfile, mediaSourceFactory) = createMediaSourceFactory(+ streamInfo = streamInfo,+ resolvedStreamType = resolvedStreamType,+ retryPolicy = retryPolicy,+ vodHttpProtocolMode = vodHttpProtocolMode,+ preload = preload+ )+ val mediaSource = mediaSourceFactory.createMediaSource(mediaItemFor(streamInfo))++ Log.i(+ TAG,+ "media-source streamType=$resolvedStreamType timeout=$timeoutProfile source=${mediaSource::class.java.simpleName} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"+ )+ return timeoutProfile to mediaSource+ }++ fun createMediaSourceFactory(+ streamInfo: StreamInfo,+ resolvedStreamType: ResolvedStreamType,+ retryPolicy: PlayerRetryPolicy,+ vodHttpProtocolMode: VodHttpProtocolMode = VodHttpProtocolMode.COMPATIBILITY_HTTP1,+ preload: Boolean = false+ ): Pair<PlayerTimeoutProfile, MediaSource.Factory> {val (timeoutProfile, dataSourceFactory) = dataSourceFactoryProvider.createFactory(streamInfo = streamInfo,resolvedStreamType = resolvedStreamType,vodHttpProtocolMode = vodHttpProtocolMode,preload = preload)- val mediaItem = buildMediaItem(streamInfo)- val mediaSource = when {+ val mediaSourceFactory = when {streamInfo.streamType == StreamType.RTSP || resolvedStreamType == ResolvedStreamType.RTSP ->- RtspMediaSource.Factory().createMediaSource(mediaItem)+ RtspMediaSource.Factory()resolvedStreamType == ResolvedStreamType.HLS -> HlsMediaSource.Factory(dataSourceFactory).setAllowChunklessPreparation(true).setLoadErrorHandlingPolicy(retryPolicy)- .createMediaSource(mediaItem)resolvedStreamType == ResolvedStreamType.DASH -> DashMediaSource.Factory(dataSourceFactory).setLoadErrorHandlingPolicy(retryPolicy)- .createMediaSource(mediaItem)resolvedStreamType == ResolvedStreamType.SMOOTH_STREAMING -> SsMediaSource.Factory(dataSourceFactory).apply {@@ -88,38 +108,29 @@ class PlayerMediaSourceFactory(}}.setLoadErrorHandlingPolicy(retryPolicy)- .createMediaSource(mediaItem)resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> ProgressiveMediaSource.Factory(dataSourceFactory,liveMpegTsExtractorsFactory()).setLoadErrorHandlingPolicy(retryPolicy)- .createMediaSource(mediaItem)resolvedStreamType == ResolvedStreamType.PROGRESSIVE -> ProgressiveMediaSource.Factory(dataSourceFactory,playbackExtractorsFactory()).setLoadErrorHandlingPolicy(retryPolicy)- .createMediaSource(mediaItem)else -> DefaultMediaSourceFactory(dataSourceFactory,playbackExtractorsFactory()).setLoadErrorHandlingPolicy(retryPolicy)- .createMediaSource(mediaItem)}-- Log.i(- TAG,- "media-source streamType=$resolvedStreamType timeout=$timeoutProfile source=${mediaSource::class.java.simpleName} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"- )- return timeoutProfile to mediaSource+ return timeoutProfile to mediaSourceFactory}- private fun buildMediaItem(streamInfo: StreamInfo): MediaItem {+ internal fun mediaItemFor(streamInfo: StreamInfo): MediaItem {return MediaItem.Builder().setUri(Uri.parse(streamInfo.url)).setMediaId(mediaIdFor(streamInfo))diff --git a/player/src/test/java/com/streamvault/player/Media3PlayerEnginePreloadTest.kt b/player/src/test/java/com/streamvault/player/Media3PlayerEnginePreloadTest.ktnew file mode 100644index 00000000..7d131bf5--- /dev/null+++ b/player/src/test/java/com/streamvault/player/Media3PlayerEnginePreloadTest.kt@@ -0,0 +1,69 @@+package com.streamvault.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackCompatibilityKey+import com.streamvault.domain.repository.PlaybackCompatibilityRepository+import com.streamvault.domain.model.StreamInfo+import okhttp3.OkHttpClient+import org.junit.After+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class Media3PlayerEnginePreloadTest {++ private val engine = Media3PlayerEngine(+ context = RuntimeEnvironment.getApplication(),+ okHttpClient = OkHttpClient(),+ playbackCompatibilityRepository = NoOpPlaybackCompatibilityRepository,+ audioCompatibilityMemoryStore = AudioCompatibilityMemoryStore(RuntimeEnvironment.getApplication()),+ playbackSupportSnapshotStore = PlaybackSupportSnapshotStore(RuntimeEnvironment.getApplication())+ )++ @After+ fun tearDown() {+ engine.release()+ }++ @Test+ fun `preload window submitted before player creation is retained as data only and can be cleared`() {+ val window = PlayerPreloadWindow(+ items = listOf(+ PlayerPreloadItem(+ key = "current",+ streamInfo = StreamInfo(url = "https://example.com/current.mp4"),+ contentType = PlayerPreloadContentType.VOD+ )+ ),+ currentIndex = 0+ )++ engine.preloadWindow(window)++ val pendingField = Media3PlayerEngine::class.java+ .getDeclaredField("pendingPreloadWindow")+ .apply { isAccessible = true }+ assertThat(pendingField.get(engine)).isEqualTo(window)++ engine.clearPreloadWindow()++ assertThat(pendingField.get(engine)).isNull()+ }++ private object NoOpPlaybackCompatibilityRepository : PlaybackCompatibilityRepository {+ override suspend fun getKnownBadRecords(+ deviceFingerprint: String,+ streamType: String,+ videoMimeType: String,+ resolutionBucket: String+ ) = emptyList<com.streamvault.domain.model.PlaybackCompatibilityRecord>()++ override suspend fun recordFailure(key: PlaybackCompatibilityKey, failureType: String, at: Long) = Unit++ override suspend fun recordSuccess(key: PlaybackCompatibilityKey, at: Long) = Unit++ override suspend fun prune(maxRecords: Int, olderThanMs: Long) = Unit+ }+}diff --git a/player/src/test/java/com/streamvault/player/PlayerPreloadWindowPolicyTest.kt b/player/src/test/java/com/streamvault/player/PlayerPreloadWindowPolicyTest.ktnew file mode 100644index 00000000..f8d8e2da--- /dev/null+++ b/player/src/test/java/com/streamvault/player/PlayerPreloadWindowPolicyTest.kt@@ -0,0 +1,157 @@+package com.streamvault.player++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import org.junit.Test++class PlayerPreloadWindowPolicyTest {++ @Test+ fun `three item window remains ordered around current item`() {+ val window = PlayerPreloadWindow(+ items = listOf(+ item("previous", "https://example.com/previous.mp4"),+ item("current", "https://example.com/current.mp4"),+ item("next", "https://example.com/next.mp4")+ ),+ currentIndex = 1+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items.map(PlayerPreloadItem::key))+ .containsExactly("previous", "current", "next")+ .inOrder()+ assertThat(normalized.currentIndex).isEqualTo(1)+ }++ @Test+ fun `window is capped to closest previous and next candidates`() {+ val window = PlayerPreloadWindow(+ items = (0..4).map { index -> item("item-$index", "https://example.com/$index.mp4") },+ currentIndex = 2+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items.map(PlayerPreloadItem::key))+ .containsExactly("item-1", "item-2", "item-3")+ .inOrder()+ assertThat(normalized.currentIndex).isEqualTo(1)+ }++ @Test+ fun `window at queue edge keeps only one adjacent candidate`() {+ val window = PlayerPreloadWindow(+ items = (0..4).map { index -> item("item-$index", "https://example.com/$index.mp4") },+ currentIndex = 0+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items.map(PlayerPreloadItem::key))+ .containsExactly("item-0", "item-1")+ .inOrder()+ assertThat(normalized.currentIndex).isEqualTo(0)+ }++ @Test+ fun `duplicate keys retain first item and adjust current index`() {+ val firstCurrent = item("current", "https://example.com/first.mp4")+ val duplicateCurrent = item(" current ", "https://example.com/duplicate.mp4")+ val window = PlayerPreloadWindow(+ items = listOf(+ item("previous", "https://example.com/previous.mp4"),+ firstCurrent,+ duplicateCurrent,+ item("next", "https://example.com/next.mp4")+ ),+ currentIndex = 2+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items.map(PlayerPreloadItem::key))+ .containsExactly("previous", "current", "next")+ .inOrder()+ assertThat(normalized.items[1].streamInfo.url).isEqualTo(firstCurrent.streamInfo.url)+ assertThat(normalized.currentIndex).isEqualTo(1)+ }++ @Test+ fun `live blank key and malformed url are filtered`() {+ val window = PlayerPreloadWindow(+ items = listOf(+ PlayerPreloadItem(+ key = "live",+ streamInfo = StreamInfo(+ url = "https://example.com/live.m3u8",+ streamType = StreamType.HLS+ ),+ contentType = PlayerPreloadContentType.LIVE+ ),+ item(" ", "https://example.com/blank-key.mp4"),+ item("malformed", "not-a-url"),+ item("current", "https://example.com/current.mp4")+ ),+ currentIndex = 3+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items.map(PlayerPreloadItem::key)).containsExactly("current")+ assertThat(normalized.currentIndex).isEqualTo(0)+ }++ @Test+ fun `invalid current index produces an empty window`() {+ val window = PlayerPreloadWindow(+ items = listOf(item("current", "https://example.com/current.mp4")),+ currentIndex = 4+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items).isEmpty()+ assertThat(normalized.currentIndex).isEqualTo(-1)+ }++ @Test+ fun `vod and catch up HLS or DASH items remain eligible`() {+ val window = PlayerPreloadWindow(+ items = listOf(+ item(+ key = "vod",+ url = "https://example.com/movie.m3u8",+ contentType = PlayerPreloadContentType.VOD,+ streamType = StreamType.HLS+ ),+ item(+ key = "catch-up",+ url = "https://example.com/program.mpd",+ contentType = PlayerPreloadContentType.CATCH_UP,+ streamType = StreamType.DASH+ )+ ),+ currentIndex = 0+ )++ val normalized = normalizePlayerPreloadWindow(window)++ assertThat(normalized.items.map(PlayerPreloadItem::key))+ .containsExactly("vod", "catch-up")+ .inOrder()+ }++ private fun item(+ key: String,+ url: String,+ contentType: PlayerPreloadContentType = PlayerPreloadContentType.VOD,+ streamType: StreamType = StreamType.PROGRESSIVE+ ): PlayerPreloadItem = PlayerPreloadItem(+ key = key,+ streamInfo = StreamInfo(url = url, streamType = streamType),+ contentType = contentType+ )+}diff --git a/player/src/test/java/com/streamvault/player/playback/Media3FrameThumbnailExtractorTest.kt b/player/src/test/java/com/streamvault/player/playback/Media3FrameThumbnailExtractorTest.ktnew file mode 100644index 00000000..18dcd7d0--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/Media3FrameThumbnailExtractorTest.kt@@ -0,0 +1,93 @@+package com.streamvault.player.playback++import android.graphics.Bitmap+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import kotlinx.coroutines.test.runTest+import okhttp3.OkHttpClient+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class Media3FrameThumbnailExtractorTest {++ @Test+ fun `loads one bucket once and closes the extraction session`() = runTest {+ val expectedBitmap = Bitmap.createBitmap(800, 400, Bitmap.Config.ARGB_8888)+ val sessionFactory = RecordingFrameThumbnailSessionFactory(expectedBitmap)+ val extractor = Media3FrameThumbnailExtractor(+ context = RuntimeEnvironment.getApplication(),+ okHttpClient = OkHttpClient(),+ sessionFactory = sessionFactory+ )+ val request = FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/video.mp4",+ streamType = StreamType.PROGRESSIVE+ ),+ isLive = false+ )++ val first = extractor.loadFrame(request, positionMs = 12_000L)+ val second = extractor.loadFrame(request, positionMs = 12_999L)++ assertThat(first).isNotNull()+ assertThat(second).isSameInstanceAs(first)+ assertThat(first!!.width).isEqualTo(480)+ assertThat(first.height).isEqualTo(240)+ assertThat(sessionFactory.createCount).isEqualTo(1)+ assertThat(sessionFactory.sessions.single().positions).containsExactly(10_000L)+ assertThat(sessionFactory.sessions.single().closeCount).isEqualTo(1)+ }++ @Test+ fun `returns null and closes the session when extraction fails`() = runTest {+ val sessionFactory = RecordingFrameThumbnailSessionFactory(frame = null)+ val extractor = Media3FrameThumbnailExtractor(+ context = RuntimeEnvironment.getApplication(),+ okHttpClient = OkHttpClient(),+ sessionFactory = sessionFactory+ )+ val request = FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/video.mp4",+ streamType = StreamType.PROGRESSIVE+ ),+ isLive = false+ )++ assertThat(extractor.loadFrame(request, positionMs = 0L)).isNull()+ assertThat(sessionFactory.sessions.single().closeCount).isEqualTo(1)+ }++ private class RecordingFrameThumbnailSessionFactory(+ private val frame: Bitmap?+ ) : FrameThumbnailSessionFactory {+ val sessions = mutableListOf<RecordingFrameThumbnailSession>()+ var createCount: Int = 0++ override fun create(request: FrameThumbnailRequest): FrameThumbnailSession {+ createCount+++ return RecordingFrameThumbnailSession(frame).also(sessions::add)+ }+ }++ private class RecordingFrameThumbnailSession(+ private val frame: Bitmap?+ ) : FrameThumbnailSession {+ val positions = mutableListOf<Long>()+ var closeCount: Int = 0++ override suspend fun frameAt(positionMs: Long): Bitmap? {+ positions += positionMs+ return frame+ }++ override fun close() {+ closeCount+++ }+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/Media3FrameThumbnailSupportPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/Media3FrameThumbnailSupportPolicyTest.ktnew file mode 100644index 00000000..3cdfa0fb--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/Media3FrameThumbnailSupportPolicyTest.kt@@ -0,0 +1,80 @@+package com.streamvault.player.playback++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import org.junit.Test++class Media3FrameThumbnailSupportPolicyTest {++ @Test+ fun `supports non-live video stream types`() {+ val supportedTypes = listOf(+ StreamType.PROGRESSIVE,+ StreamType.HLS,+ StreamType.DASH,+ StreamType.SMOOTH_STREAMING+ )++ supportedTypes.forEach { streamType ->+ val request = FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/video",+ streamType = streamType+ ),+ isLive = false+ )++ assertThat(supportsMedia3FrameThumbnail(request)).isTrue()+ }+ }++ @Test+ fun `rejects live unsupported drm and malformed thumbnail requests`() {+ val requests = listOf(+ FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/live.m3u8",+ streamType = StreamType.HLS+ ),+ isLive = true+ ),+ FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "rtsp://example.test/video",+ streamType = StreamType.RTSP+ ),+ isLive = false+ ),+ FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/video.ts",+ streamType = StreamType.MPEG_TS+ ),+ isLive = false+ ),+ FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/video",+ streamType = StreamType.UNKNOWN,+ drmInfo = com.streamvault.domain.model.DrmInfo(+ scheme = com.streamvault.domain.model.DrmScheme.WIDEVINE,+ licenseUrl = "https://example.test/license"+ )+ ),+ isLive = false+ ),+ FrameThumbnailRequest(+ streamInfo = StreamInfo(+ url = "https://example.test/video",+ streamType = StreamType.UNKNOWN+ ),+ isLive = false+ )+ )++ requests.forEach { request ->+ assertThat(supportsMedia3FrameThumbnail(request)).isFalse()+ }+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.kt b/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.ktnew file mode 100644index 00000000..daa0e621--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.kt@@ -0,0 +1,163 @@+package com.streamvault.player.playback++import androidx.media3.datasource.DefaultDataSource+import androidx.media3.exoplayer.DefaultLoadControl+import androidx.media3.exoplayer.DefaultRenderersFactory+import androidx.media3.exoplayer.upstream.DefaultBandwidthMeter+import androidx.media3.exoplayer.source.preload.DefaultPreloadManager+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamType+import com.streamvault.player.PlayerPreloadContentType+import com.streamvault.player.PlayerPreloadItem+import com.streamvault.player.PlayerPreloadWindow+import com.streamvault.domain.model.StreamInfo+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class Media3PreloadWindowManagerTest {++ @Test+ fun `target status preloads only immediate neighbors`() {+ val adjacent = DefaultPreloadManager.PreloadStatus.specifiedRangeLoaded(0L, 3_000L)++ assertThat(playerPreloadTargetStatus(currentIndex = 1, rankingIndex = 0))+ .isEqualTo(adjacent)+ assertThat(playerPreloadTargetStatus(currentIndex = 1, rankingIndex = 2))+ .isEqualTo(adjacent)+ assertThat(playerPreloadTargetStatus(currentIndex = 1, rankingIndex = 1)).isNull()+ assertThat(playerPreloadTargetStatus(currentIndex = 1, rankingIndex = 3)).isNull()+ assertThat(playerPreloadTargetStatus(currentIndex = null, rankingIndex = 0)).isNull()+ }++ @Test+ fun `ranking comparator prefers the nearer candidate after current moves`() {+ val comparator = DefaultPreloadManager.SimpleRankingDataComparator()++ comparator.setCurrentPlayingIndex(2)+ assertThat(comparator.compare(1, 4)).isLessThan(0)++ comparator.setCurrentPlayingIndex(4)+ assertThat(comparator.compare(3, 1)).isLessThan(0)+ }++ @Test+ fun `stream identity includes request metadata as well as media identity`() {+ val base = StreamInfo(url = "https://example.com/movie.mp4")+ val changedHeaders = base.copy(headers = mapOf("Authorization" to "Bearer different"))++ assertThat(preloadStreamIdentity(base)).isNotEqualTo(preloadStreamIdentity(changedHeaders))+ assertThat(preloadStreamIdentity(base)).isEqualTo(preloadStreamIdentity(base.copy()))+ }++ @Test+ fun `manager creates foreground player from the preload builder`() {+ val context = RuntimeEnvironment.getApplication()+ val dataSourceProvider = PlayerDataSourceFactoryProvider(+ context = context,+ baseClient = okhttp3.OkHttpClient()+ )+ val manager = Media3PreloadWindowManager(+ context = context,+ mediaSourceFactory = PlayerMediaSourceFactory(dataSourceProvider),+ dataSourceFactoryProvider = dataSourceProvider,+ bandwidthMeter = DefaultBandwidthMeter.Builder(context).build()+ )++ val player = manager.createPlayer(+ renderersFactory = DefaultRenderersFactory(context),+ loadControl = DefaultLoadControl(),+ preloadDataSourceFactory = DefaultDataSource.Factory(context)+ ) {+ it.setReleaseTimeoutMs(0L)+ }++ assertThat(player).isNotNull()+ player.release()+ manager.release()+ }++ @Test+ fun `manager looks up exact sources and replaces changed candidates`() {+ val context = RuntimeEnvironment.getApplication()+ val dataSourceProvider = PlayerDataSourceFactoryProvider(+ context = context,+ baseClient = okhttp3.OkHttpClient()+ )+ val manager = Media3PreloadWindowManager(+ context = context,+ mediaSourceFactory = PlayerMediaSourceFactory(dataSourceProvider),+ dataSourceFactoryProvider = dataSourceProvider,+ bandwidthMeter = DefaultBandwidthMeter.Builder(context).build()+ )+ val player = manager.createPlayer(+ renderersFactory = DefaultRenderersFactory(context),+ loadControl = DefaultLoadControl(),+ preloadDataSourceFactory = DefaultDataSource.Factory(context)+ ) {+ it.setReleaseTimeoutMs(0L)+ }++ val current = StreamInfo(+ url = "file:///managed-current.mp4",+ streamType = StreamType.PROGRESSIVE+ )+ val next = StreamInfo(+ url = "file:///managed-next.mp4",+ streamType = StreamType.PROGRESSIVE+ )+ val changedNext = next.copy(url = "file:///managed-next-replaced.mp4")++ manager.updateWindow(+ PlayerPreloadWindow(+ items = listOf(+ PlayerPreloadItem("current", current, PlayerPreloadContentType.VOD),+ PlayerPreloadItem("next", next, PlayerPreloadContentType.VOD),+ PlayerPreloadItem(+ "live",+ StreamInfo(+ url = "file:///live.ts",+ streamType = StreamType.MPEG_TS+ ),+ PlayerPreloadContentType.LIVE+ )+ ),+ currentIndex = 0+ )+ )++ val currentSource = manager.getMediaSource(current)+ val nextSource = manager.getMediaSource(next)+ assertThat(currentSource).isNotNull()+ assertThat(nextSource).isNotNull()+ assertThat(+ manager.getMediaSource(+ StreamInfo(url = "file:///not-managed.mp4", streamType = StreamType.PROGRESSIVE)+ )+ ).isNull()+ assertThat(+ manager.getMediaSource(+ StreamInfo(url = "file:///live.ts", streamType = StreamType.MPEG_TS)+ )+ ).isNull()++ manager.updateWindow(+ PlayerPreloadWindow(+ items = listOf(+ PlayerPreloadItem("current", current, PlayerPreloadContentType.VOD),+ PlayerPreloadItem("next", changedNext, PlayerPreloadContentType.VOD)+ ),+ currentIndex = 0+ )+ )++ assertThat(manager.getMediaSource(current)).isSameInstanceAs(currentSource)+ assertThat(manager.getMediaSource(next)).isNull()+ assertThat(manager.getMediaSource(changedNext)).isNotNull()++ player.release()+ manager.release()+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.ktindex 74e90c9b..70324fb8 100644--- a/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt@@ -1,9 +1,17 @@package com.streamvault.player.playback+import androidx.media3.exoplayer.source.ProgressiveMediaSourceimport androidx.media3.extractor.ts.TsExtractorimport com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import okhttp3.OkHttpClientimport org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+@RunWith(RobolectricTestRunner::class)class PlayerMediaSourceFactoryTest {@Test@@ -21,4 +29,35 @@ class PlayerMediaSourceFactoryTest {assertThat(DIRECT_LIVE_MPEG_TS_POLICY.media3ExtractorMode).isEqualTo(TsExtractor.MODE_SINGLE_PMT)}++ @Test+ fun `media source factory exposes preload timeout and progressive source`() {+ val dataSourceProvider = PlayerDataSourceFactoryProvider(+ context = RuntimeEnvironment.getApplication(),+ baseClient = OkHttpClient()+ )+ val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceProvider)+ val streamInfo = StreamInfo(+ url = "https://example.test/video.mp4",+ streamType = StreamType.PROGRESSIVE+ )+ val retryPolicy = PlayerRetryPolicy(+ streamContext = PlaybackRetryContext(+ resolvedStreamType = ResolvedStreamType.PROGRESSIVE,+ timeoutProfile = PlayerTimeoutProfile.PRELOAD+ ),+ playbackStarted = { false }+ )++ val (timeoutProfile, factory) = mediaSourceFactory.createMediaSourceFactory(+ streamInfo = streamInfo,+ resolvedStreamType = ResolvedStreamType.PROGRESSIVE,+ retryPolicy = retryPolicy,+ preload = true+ )+ val mediaSource = factory.createMediaSource(mediaSourceFactory.mediaItemFor(streamInfo))++ assertThat(timeoutProfile).isEqualTo(PlayerTimeoutProfile.PRELOAD)+ assertThat(mediaSource).isInstanceOf(ProgressiveMediaSource::class.java)+ }}