StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
docs: track VOD chapter implementation
David Nashash202a76ff8fa6
diff --git a/docs/superpowers/plans/2026-09-11-vod-overlay-chapters.md b/docs/superpowers/plans/2026-09-11-vod-overlay-chapters.mdindex 692cdd86..8d2f50de 100644--- a/docs/superpowers/plans/2026-09-11-vod-overlay-chapters.md+++ b/docs/superpowers/plans/2026-09-11-vod-overlay-chapters.md@@ -34,11 +34,11 @@- Produces `internal fun mapChapterMetadata(metadata: Metadata?, windowOffsetMs: Long, durationMs: Long): List<PlayerChapter>`.- Media3 chapter input is `androidx.media3.extractor.metadata.Chapter`; feature code will consume only `PlayerChapter`.-- [ ] **Step 1: Write failing mapper tests.**+- [x] **Step 1: Write failing mapper tests.**Cover unordered entries, period-to-window offset subtraction, hidden entries, unset/negative starts, missing titles (`Chapter N`), missing ends derived from the next entry or duration, duplicate entries, and duration clamping. Build test entries with `Chapter.Builder` and `Label`/`Cue` values available in Media3 1.11.-- [ ] **Step 2: Run the mapper tests and verify the expected missing-symbol failure.**+- [x] **Step 2: Run the mapper tests and verify the expected missing-symbol failure.**Run:@@ -48,15 +48,15 @@Expected: compilation fails because `PlayerChapter` and `mapChapterMetadata` do not exist.-- [ ] **Step 3: Implement the immutable model and mapper.**+- [x] **Step 3: Implement the immutable model and mapper.**Flatten `Metadata` entries, filter hidden/unset data, subtract `windowOffsetMs`, sort by start, deduplicate by normalized start/title, derive missing ends, clamp to `durationMs` when positive, and assign one-based indexes after filtering. Return an empty list for null metadata or malformed input.-- [ ] **Step 4: Run the mapper tests and verify they pass.**+- [x] **Step 4: Run the mapper tests and verify they pass.**Re-run the focused command. Expected: all mapper tests pass with no playback-side effects.-- [ ] **Step 5: Refactor only while green and commit the isolated task.**+- [x] **Step 5: Refactor only while green and commit the isolated task.**```powershellgit add player/src/main/java/com/streamvault/player/PlayerChapter.kt player/src/main/java/com/streamvault/player/ChapterMetadataMapper.kt player/src/test/java/com/streamvault/player/ChapterMetadataMapperTest.kt@@ -75,11 +75,11 @@- Adds `val chapters: StateFlow<List<PlayerChapter>>` to `PlayerEngine`.- `Media3PlayerEngine` owns a `MutableStateFlow<List<PlayerChapter>>`, clears it at prepare/stop/release, and updates it from `Tracks` metadata and current timeline.-- [ ] **Step 1: Add a failing contract test for initial and reset state.**+- [x] **Step 1: Add a failing contract test for initial and reset state.**Assert a fake engine exposes an empty chapter list before preparation and after `stop`/`release`. Add a test fixture that supplies a `Tracks` object containing a `Format` with `Metadata` chapter entries and expects normalized chapters.-- [ ] **Step 2: Run the focused player tests to verify the missing contract failure.**+- [x] **Step 2: Run the focused player tests to verify the missing contract failure.**Run:@@ -89,11 +89,11 @@Expected: compile failures for the missing `PlayerEngine.chapters` contract and production publication.-- [ ] **Step 3: Add the state contract and lifecycle publication.**+- [x] **Step 3: Add the state contract and lifecycle publication.**Add the `StateFlow` to the interface and all fakes. In `Media3PlayerEngine`, invoke the mapper from `onTracksChanged` using the selected media-period metadata and `Timeline.Window.positionInFirstPeriodUs`. Refresh after timeline changes, clear stale state before a new media item, and never throw when metadata is absent.-- [ ] **Step 4: Run player chapter tests and the existing player suite.**+- [x] **Step 4: Run player chapter tests and the existing player suite.**```powershell.\gradlew.bat :player:testDebugUnitTest --tests '*Chapter*' --no-daemon@@ -102,7 +102,7 @@Expected: chapter tests and all existing player tests pass.-- [ ] **Step 5: Commit only the engine contract/publication changes.**+- [x] **Step 5: Commit only the engine contract/publication changes.**```powershellgit add player/src/main/java/com/streamvault/player/PlayerEngine.kt player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt player/src/test@@ -124,25 +124,25 @@- Produces `fun nextChapterTarget(chapters: List<PlayerChapter>, positionMs: Long): Long?`.- Produces `data class VodOverlayState(... chapters: List<PlayerChapter>, currentChapter: PlayerChapter?, canShowChapterAction: Boolean, canSeekPreviousChapter: Boolean, canSeekNextChapter: Boolean, ...)`.-- [ ] **Step 1: Write failing policy tests.**+- [x] **Step 1: Write failing policy tests.**Assert current chapter at boundaries, previous-chapter restart when more than three seconds into the current chapter, previous-chapter navigation when within three seconds, first/last chapter disabling, gaps, and empty chapters. Add overlay-action tests for movie versus series episode, missing tracks, cast-connected state, and hidden chapter action.-- [ ] **Step 2: Run focused feature tests and verify they fail for missing policies.**+- [x] **Step 2: Run focused feature tests and verify they fail for missing policies.**```powershell.\gradlew.bat :feature:playback:testDebugUnitTest --tests '*VodChapterNavigationTest' --tests '*VodOverlayStateTest' --no-daemon```-- [ ] **Step 3: Implement the smallest pure policies.**+- [x] **Step 3: Implement the smallest pure policies.**Keep chapter math independent of Compose and player implementations. Use window-relative `startTimeMs`, preserve the three-second threshold, and make action visibility depend on content type, chapter availability, track counts, and Cast state.-- [ ] **Step 4: Run focused tests and the existing playback unit suite.**+- [x] **Step 4: Run focused tests and the existing playback unit suite.**Expected: all new policy tests pass and no existing playback tests regress.-- [ ] **Step 5: Commit the pure policies.**+- [x] **Step 5: Commit the pure policies.**```powershellgit add feature/playback/src/main/java/com/streamvault/feature/playback/player/VodChapterNavigation.kt feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt feature/playback/src/test@@ -166,11 +166,11 @@- `VodChapterSheet` consumes `List<PlayerChapter>` and a selected index and emits seek/dismiss events.- `VodPlaybackSettingsSheet` consumes action availability/state and emits existing action callbacks.-- [ ] **Step 1: Add failing Compose/golden fixtures for the approved visual states.**+- [x] **Step 1: Add failing Compose/golden fixtures for the approved visual states.**Create deterministic preview state and assertions for no-chapter controls, chapter controls, seeking preview, chapter sheet, settings sheet, and focus on the primary action. Replace the old VOD golden expectation only in the new test fixture; retain live goldens.-- [ ] **Step 2: Run the new golden tests and verify missing-composable failures.**+- [x] **Step 2: Run the new golden tests and verify missing-composable failures.**Run:@@ -180,19 +180,19 @@Expected: compilation fails because the new overlay composables do not exist.-- [ ] **Step 3: Implement the visual hierarchy.**+- [x] **Step 3: Implement the visual hierarchy.**Use a bottom `Brush.verticalGradient` over the video, title/current chapter metadata, elapsed/remaining time, full-width chapter-aware timeline, centered transport, and compact contextual actions. Use semantic theme colors, localized strings, minimum 48 dp targets, explicit focus properties, and no floating VOD card.-- [ ] **Step 4: Implement the chapter sheet and settings sheet.**+- [x] **Step 4: Implement the chapter sheet and settings sheet.**Use the existing exclusive modal pattern, dim the video, focus the current chapter/settings row, restore focus to the originating action on dismissal, and delegate detail actions to existing track/speed/timer dialogs.-- [ ] **Step 5: Run and review the new golden states at TV and compact widths.**+- [x] **Step 5: Run and review the new golden states at TV and compact widths.**Expected: the approved visual direction is visible, no controls clip, focus rings are high contrast, and the chapter list is readable from TV distance.-- [ ] **Step 6: Commit the standalone UI slice.**+- [x] **Step 6: Commit the standalone UI slice.**```powershellgit add feature/playback/src/main/java/com/streamvault/feature/playback/player/Vod*.kt feature/playback/src/androidTest@@ -215,28 +215,28 @@- Add `PlayerModal.ChapterSelection` and `PlayerModal.PlaybackSettings` only if the existing modal state needs explicit ownership beyond the sheet composables.- Add `PlayerViewModel.seekToPreviousChapter()` and `seekToNextChapter()` wrappers that call the pure targets and existing `seekTo`.-- [ ] **Step 1: Write failing wiring tests.**+- [x] **Step 1: Write failing wiring tests.**Assert chapter modal/back transitions, focus restoration state, previous/next chapter callbacks, and VOD-only gating. Assert live content continues to select the existing live overlay path.-- [ ] **Step 2: Run focused feature tests and verify the missing state/callback failures.**+- [x] **Step 2: Run focused feature tests and verify the missing state/callback failures.**-- [ ] **Step 3: Wire chapter state and all existing VOD callbacks.**+- [x] **Step 3: Wire chapter state and all existing VOD callbacks.**Keep `contentType == LIVE` on the existing live branch. For VOD/movie/series episode, replace `PlayerVodInfo` with `VodPlayerControlsOverlay`, pass the existing track, timer, Cast, PiP, aspect ratio, external-player, and episode callbacks, and hide chapter actions while Cast is connected.-- [ ] **Step 4: Implement back/focus/auto-hide integration.**+- [x] **Step 4: Implement back/focus/auto-hide integration.**Ensure opening a sheet suspends auto-hide, Back closes detail then sheet then controls, and changing media clears chapters without leaving stale focus or current-chapter text.-- [ ] **Step 5: Run feature playback tests and screenshot tests.**+- [x] **Step 5: Run feature playback tests and screenshot tests.**```powershell.\gradlew.bat :feature:playback:testDebugUnitTest --no-daemon.\gradlew.bat :feature:playback:connectedDebugAndroidTest --tests '*VodPlayerControlsOverlayGoldenTest' --no-daemon```-- [ ] **Step 6: Commit the wiring slice.**+- [x] **Step 6: Commit the wiring slice.**```powershellgit add feature/playback/src/main/java/com/streamvault/feature/playback/player feature/playback/src/test feature/playback/src/androidTest@@ -264,7 +264,7 @@Review controls, seeking, chapters, settings, compact, RTL, and live goldens. The old card must no longer be rendered.-- [ ] **Step 4: Update `docs/upgrade.txt`.**+- [x] **Step 4: Update `docs/upgrade.txt`.**Mark the VOD chapter navigation item `DONE`, describe the new UI entry points, and leave sliding-window preloading and telemetry-driven follow-ups pending.@@ -310,4 +310,3 @@- [ ] **Step 5: Report the worktree state without merging it.**Confirm the implementation remains in `chore/media3-1.11-upgrade`, the original `develop` checkout is untouched, and provide the user the test commands/results and any device-validation gap.-diff --git a/docs/upgrade.txt b/docs/upgrade.txtnew file mode 100644index 00000000..67c49ab1--- /dev/null+++ b/docs/upgrade.txt@@ -0,0 +1,96 @@+# Media3 1.9 -> 1.11 upgrade audit++This audit covers the complete jump from the app's previous Media3 1.9.2+dependencies through Media3 1.10.x and 1.11.0. Items are classified as:++- DONE: implemented in this worktree.+- AUTOMATIC: provided by the Media3 upgrade; no app code is required.+- ADD: a worthwhile app capability or targeted improvement that is not yet implemented.+- NOT NEEDED: technically available, but not a fit for StreamVault's current architecture.+- WATCH: useful only if future telemetry or product requirements justify it.++Primary source: https://developer.android.com/jetpack/androidx/releases/media3++## Work already completed in this worktree++These items are complete and should not remain in the pending migration list:++- DONE - Upgraded all Maven Media3 dependencies from 1.9.2 to 1.11.0.+- DONE - Replaced the bundled FFmpeg decoder AAR with the matching Media3 1.11.0 artifact, including checksum and ABI/decoder verification.+- DONE - Replaced the legacy `SingleSampleMediaSource` external-subtitle path with `MediaItem.SubtitleConfiguration` plus extraction-based subtitle loading. Optional subtitle I/O failures remain non-fatal to video playback.+- DONE - Migrated the custom PCM tap to `AudioSink.AudioSinkConfig`, preserving audio format, timeline/period context, and tap behavior.+- DONE - Migrated the custom video renderer construction to `MediaCodecVideoRenderer.Builder`, preserving the decoder-reuse workaround.+- DONE - Migrated `setViewportSizeToPhysicalDisplaySize` to the current API.+- DONE - Enabled `DefaultExtractorsFactory.setDisableArtworkMetadata(true)` for playback extractors to reduce unnecessary cover-art memory use on TV devices.+- DONE - Added regression/unit coverage for external subtitles, audio-sink configuration, decoder reuse, and the FFmpeg artifact.++## Media3 1.10.x findings++### Automatic benefits already received by upgrading to 1.11.0++- AUTOMATIC - `ProgressiveMediaSource` timeline propagation fix. The app uses progressive sources for VOD and side-loaded subtitles, so the fix is inherited without an app change.+- AUTOMATIC - Decoder-error recovery/prewarming fixes, AV1 Dolby Vision initialization fixes, codec-reuse improvements, RTSP packet parsing fixes, HLS fallback/`EXT-X-MAP` fixes, DASH seek/timeline fixes, and audio-output retry improvements.+- AUTOMATIC - Dynamic video scheduling introduced in 1.10 and enabled by default at the ExoPlayer level in 1.11. No explicit opt-in is required for the current player.+- AUTOMATIC - VobSub cue-duration handling and 1.11 TTML parser fixes. These improve subtitle timing/availability but are not a guaranteed fix for the reported subtitle-freeze issue.+- AUTOMATIC - HLS redundant-location fallback, HLS `QUERYPARAM`/`X-PLAYOUT-LIMIT` handling, HLS ID3 metadata-track exposure, and DASH CEA caption grouping/location fallback.+- AUTOMATIC - Dolby Vision Profile 10, VVC container parsing, larger MP4 `uuid` boxes, and other extractor/codec compatibility fixes where the device decoder supports the format.+- AUTOMATIC - Media3 1.10's stable track-selection preferences and Media3 1.11's continued track-selection fixes are available to the existing `PlayerTrackController`.++### 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.+- 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++- NOT NEEDED - `Player.mute()`/`unmute()`. They became stable in 1.10, but the app's `PlayerAudioFocusController` preserves volume, coordinates focus/ducking, and exposes state; replacing it would lose behavior.+- NOT NEEDED - Media3 Compose `Player`, `ProgressSlider`, and playback-speed composables. StreamVault has custom TV/DPAD controls, overlays, subtitle styling, surfaces, and a `PlayerEngine` boundary that intentionally hides Media3 from `:feature:playback`.+- NOT NEEDED - `RemoteCastPlayer.Builder.setTrackSelector`. StreamVault uses the Google Cast SDK directly through `CastManager`, not Media3 `CastPlayer`.+- NOT NEEDED - Transformer, IMA, IAMF, Lottie-effect, widget, download, and muxer additions. The app does not currently use those Media3 product areas.++## Media3 1.11.0 findings++### Automatic benefits already received++- AUTOMATIC - ExoPlayer concurrency, codec operating-rate, codec-flush, audio-session, scrubbing, and dynamic-scheduling fixes.+- AUTOMATIC - `DefaultLoadControl` low-memory protection, audio-renderer underrun grace period, fixed PCM buffer sizing, explicit decoder channel-mask handling, and MPEG-TS DTS-HD/DTS Express extraction fixes.+- AUTOMATIC - TTML region/style cue fixes, improved MP4/Matroska chapter parsing, fragmented-MP4 `mfra` seeking, Matroska ALAC/color/chapter handling, and MPEG-TS last-frame handling.+- AUTOMATIC - HLS Content Steering/Pathway Cloning support and HLS `SCORE` parsing into `Format.selectionPriority`. No app code is required for manifests that provide these features.+- AUTOMATIC - Safer default `MediaSession` controller access and the 1.11 session-threading/deadlock fixes. The app creates a basic `MediaSession` without a custom callback, so there is no `onConnect` migration to perform.+- AUTOMATIC - `Format.channelMask` and the corresponding audio-channel configuration logic. The custom audio sink now receives the richer `AudioSinkConfig`.++### Worth adding as new capabilities or targeted improvements++- 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.+- 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.++### 1.11 capabilities not suitable for the current app++- NOT NEEDED - Media3 Compose `PlayerDefaults`, control slots, `MiniController`, `PlayerPool`, and Compose state holders. These would duplicate StreamVault's custom player UI and lifecycle rather than extend it.+- NOT NEEDED - `media3-datasource-ktor`. The player depends on custom OkHttp headers, TLS policy, proxy behavior, timeouts, and transfer accounting; switching stacks provides no feature benefit.+- NOT NEEDED - `CastParams`/SystemUI Output Switcher migration for now. It would require moving or bridging the existing Google Cast implementation to Media3 Cast and would create a large parallel playback path.+- NOT NEEDED - HAGC/Eclipsa timed HDR metadata. It targets progressive media on API 37+ devices and has no current product requirement; the project currently compiles against API 36.+- NOT NEEDED - Ogg/WAV muxers, track-reference muxing, Transformer, IMA, and other authoring APIs. StreamVault is a playback application.++## Subtitle-freeze relevance++The upgrade includes automatic subtitle-parser improvements from both 1.10 and 1.11, and the external subtitle path is DONE above. There is still no Media3 1.10/1.11 switch that guarantees recovery from a frozen embedded subtitle track. Embedded-subtitle behavior remains unverified on the affected device/content and should be instrumented separately if the report persists.++## Remaining implementation backlog++1. Design and test VOD-only sliding-window preloading before replacing the current single-source preload path.+2. Keep custom variant ordering and Media3 Cast migration as telemetry-driven follow-ups, not automatic parts of the 1.11 upgrade.++## Verification status for the completed migration++- 414 player/playback unit tests passed (239 in `:player`, 175 in `:feature:playback`).+- The adaptive startup bitrate policy unit tests pass, including network fallbacks, discounted history, and safety bounds.+- Debug APK assembled successfully.+- FFmpeg AAR checksum matched its manifest.+- Targeted deprecated usages: zero.+- Independent review: no critical or important issues after the subtitle-path fix.+- DONE - Repository-wide `testDebugUnitTest` task passed successfully across all modules (270 actionable tasks, zero test failures).