Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package xyz.libravault.core.storage

/**
* Shared SharedPreferences identifiers for the app-wide `libravault_prefs` file.
*
* The player feature module reads the user's skip-duration setting directly
* from this file rather than depending on `feature:settings`, so both modules
* MUST agree on the file name and key. Centralizing them here gives compile-time
* enforcement (any module that needs them transitively depends on `:core:storage`,
* which both `feature:player` and `feature:settings` already do).
*
* @see xyz.libravault.feature.settings.UserPreferencesRepository
* @see xyz.libravault.feature.player.service.SkipDurationPreference
*/
object LibravaultPreferences {
/** SharedPreferences file name. */
const val FILE_NAME = "libravault_prefs"

/** Skip-duration preference key. Integer seconds, 5–120. */
const val KEY_SKIP_DURATION_SEC = "skip_duration_sec"
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package xyz.libravault.feature.library

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.media3.common.Player
import androidx.media3.session.MediaController
import com.google.common.util.concurrent.ListenableFuture
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
Expand Down Expand Up @@ -39,6 +41,8 @@ import xyz.libravault.core.domain.usecase.DeleteBookmarkUseCase
import xyz.libravault.core.logger.LibravaultLogger
import com.google.common.util.concurrent.MoreExecutors
import xyz.libravault.feature.player.service.PlaybackStateHolder
import xyz.libravault.feature.player.service.SeekClamp
import xyz.libravault.feature.player.service.SkipDurationPreference
import javax.inject.Inject

data class LibraryUiState(
Expand Down Expand Up @@ -75,6 +79,7 @@ class LibraryViewModel @Inject constructor(
private val deleteBookmark: DeleteBookmarkUseCase,
private val controllerFuture: ListenableFuture<MediaController>,
private val supporterRepository: SupporterRepository,
@ApplicationContext private val appContext: Context,
) : ViewModel() {

private var controller: MediaController? = null
Expand Down Expand Up @@ -335,11 +340,28 @@ class LibraryViewModel @Inject constructor(
}
}

fun seekBack() { controller?.seekBack() }
fun seekForward() { controller?.seekForward() }
fun seekBack() { seekBy(-SkipDurationPreference.getSkipDurationMs(appContext)) }
fun seekForward() { seekBy( SkipDurationPreference.getSkipDurationMs(appContext)) }
fun skipPrevious() { controller?.seekToPreviousMediaItem() }
fun skipNext() { controller?.seekToNextMediaItem() }

/**
* Seeks [deltaMs] from the current position, clamped to the item duration.
* Uses an explicit `seekTo` rather than `MediaController.seekBack` /
* `MediaController.seekForward` so the user's runtime `defaultSkipDurationSec`
* preference is honored even after the ExoPlayer singleton has been built (the
* `seekBackIncrementMs` / `seekForwardIncrementMs` values on `ExoPlayer.Builder`
* are immutable past build).
*
* The `C.TIME_UNSET` clamp logic lives in
* [xyz.libravault.feature.player.service.SeekClamp.clamp] — see the unit tests
* there for boundary cases (currentPosition near 0 / duration, duration UNSET).
*/
private fun seekBy(deltaMs: Long) {
val ctrl = controller ?: return
ctrl.seekTo(SeekClamp.clamp(ctrl.currentPosition, deltaMs, ctrl.duration))
}

// ── Init ─────────────────────────────────────────────────────────────────

init {
Expand Down
1 change: 1 addition & 0 deletions feature/player/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ dependencies {
// Test dependencies
testImplementation("androidx.arch.core:core-testing:2.2.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.0")
testImplementation(libs.bundles.testing.jvm)
}
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ class PlayerViewModel @Inject constructor(
}

fun updateBookmarkNote(id: Long, note: String?) {
viewModelScope.launch { updateBookmarkNote(id, note) }
viewModelScope.launch { updateBookmarkNote.invoke(id, note) }
}

// ── Position polling & progress saving ────────────────────────────────────
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
@file:OptIn(androidx.media3.common.util.UnstableApi::class)

package xyz.libravault.feature.player.service

import android.annotation.SuppressLint
import android.content.Context
import androidx.media3.common.Player
import androidx.media3.session.CommandButton
Expand All @@ -12,85 +11,210 @@ import androidx.core.app.NotificationCompat
import com.google.common.collect.ImmutableList

/**
* Extends [DefaultMediaNotificationProvider] to pin exactly three buttons in
* the compact notification / lock-screen strip: seek-back | play/pause | seek-forward.
* Custom [DefaultMediaNotificationProvider] for the lockscreen / Quick-Settings media tile
* compact strip.
*
* ## What this renders
*
* On the Android 13+ system media tile (lockscreen "Live notifications" and Quick-Settings
* media output), this provider publishes a five-button strip:
*
* ```
* [ Prev ] [ − N s ] [ Play / Pause ] [ + N s ] [ Next ]
* ```
*
* Where `N` is the user's `defaultSkipDurationSec` preference (5–120 seconds, default 30 s,
* configured in Settings → Playback → Skip duration).
*
* ## Why a custom provider
*
* The default [DefaultMediaNotificationProvider] builds a maximum of three actions (and on
* a single-track audiobook playlist the right-hand seek action frequently ends up
* `isEnabled=false` and gets dropped — explaining the "only play/previous" layout reported by
* users). The previous build of this provider pinned exactly three compact-view slots and
* had an index-resolution bug (disabled buttons counted into the action index) that caused
* slot selection to land on the wrong command, which manifested as taps on the play/pause
* glyph appearing to do nothing. This implementation pins all five buttons in a stable order
* and returns the indices `[0..size)` so the platform tile receives the full strip.
*
* Any buttons the session publishes via `MediaSession.setCustomLayout(...)` are appended
* after the standard 5 — they show up in the expanded notification (and in the compact view
* when the total is 5 or fewer). Earlier versions of this provider silently dropped them.
*
* ## Runtime setting changes
*
* Two problems with stock behaviour that we fix:
* 1. [DefaultMediaNotificationProvider] doesn't set [COMMAND_KEY_COMPACT_VIEW_INDEX] extras
* reliably, so the compact-view slot selection is unpredictable.
* 2. ExoPlayer marks [Player.COMMAND_SEEK_BACK] (and sometimes [Player.COMMAND_SEEK_FORWARD])
* as disabled when the playback position is near the start or end. The default provider
* skips disabled buttons, so they get no action index and can't appear in the strip.
* The seek increment read by `Player.seekBack`/`seekForward` is fixed at ExoPlayer build
* time in [PlayerModule] and can't be mutated afterward. A change to
* `defaultSkipDurationSec` in Settings therefore takes effect on the lockscreen strip on
* the next app start, while reader and library mini-player ±seek buttons honor the
* preference live (see
* [xyz.libravault.feature.library.LibraryViewModel.seekBy] and the reader equivalent).
*
* Fix strategy:
* - [getMediaButtons]: force-enable every disabled button so all buttons become
* notification actions.
* - [addNotificationActions]: locate the play/pause action by scanning for
* [Player.COMMAND_PLAY_PAUSE], then return [ppIdx-1, ppIdx, ppIdx+1] as the
* three compact-view slots (seek-back | play/pause | seek-forward).
* ## Icon set (Media3 1.3.1 API surface)
*
* [CommandButton.Builder] in this Media3 release accepts a resource id via
* [CommandButton.Builder.setIconResId] rather than an icon-constant int. We resolve the
* icons from `androidx.media3.ui` which ships equivalent bitmaps for the standard
* transport actions.
*/
@OptIn(androidx.media3.common.util.UnstableApi::class)
@SuppressLint("UnsafeOptInUsageError")
internal class LibravaultNotificationProvider(context: Context) :
DefaultMediaNotificationProvider(context) {

/**
* Force-enable every button that is disabled so that all buttons are added as
* notification actions regardless of current playback position.
*/
private val context: Context = context.applicationContext

/** Bundled transport icons shipped by `androidx.media3.ui` as `exo_notification_*` resources. */
private object Icons {
val play = androidx.media3.ui.R.drawable.exo_notification_play
val pause = androidx.media3.ui.R.drawable.exo_notification_pause
val previous = androidx.media3.ui.R.drawable.exo_notification_previous
val next = androidx.media3.ui.R.drawable.exo_notification_next
val rewind = androidx.media3.ui.R.drawable.exo_notification_rewind
val ffwd = androidx.media3.ui.R.drawable.exo_notification_fastforward
}

override fun getMediaButtons(
session: MediaSession,
playerCommands: Player.Commands,
@Suppress("UNUSED_PARAMETER") playerCommands: Player.Commands,
customLayout: ImmutableList<CommandButton>,
showPauseButton: Boolean,
): ImmutableList<CommandButton> {
val base = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton)
val out = ImmutableList.Builder<CommandButton>()
for (button in base) {
out.add(
if (button.isEnabled) button
else CommandButton.Builder()
.setPlayerCommand(button.playerCommand)
.setIconResId(button.iconResId)
.setDisplayName(button.displayName)
.setEnabled(true)
.build()
val prevButton = CommandButton.Builder()
.setPlayerCommand(Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM)
.setIconResId(Icons.previous)
.setDisplayName(
context.getString(
androidx.media3.session.R.string.media3_controls_seek_to_previous_description
)
)
// Force-enable so the strip layout is stable across playlist shapes
// (single-track audiobooks report this command as unavailable). Taps on
// an unavailable prev/next route through the standard seek/transport path
// and are no-op'd by ExoPlayer; the system still renders the button.
.setEnabled(true)
.build()

val skipBackButton = CommandButton.Builder()
.setPlayerCommand(Player.COMMAND_SEEK_BACK)
.setIconResId(Icons.rewind)
.setDisplayName(
context.getString(
androidx.media3.session.R.string.media3_controls_seek_back_description
)
)
.setEnabled(true)
.build()

val skipForwardButton = CommandButton.Builder()
.setPlayerCommand(Player.COMMAND_SEEK_FORWARD)
.setIconResId(Icons.ffwd)
.setDisplayName(
context.getString(
androidx.media3.session.R.string.media3_controls_seek_forward_description
)
)
.setEnabled(true)
.build()

val playPauseButton = CommandButton.Builder()
.setPlayerCommand(Player.COMMAND_PLAY_PAUSE)
.setIconResId(if (showPauseButton) Icons.pause else Icons.play)
.setDisplayName(
context.getString(
if (showPauseButton)
androidx.media3.session.R.string.media3_controls_pause_description
else
androidx.media3.session.R.string.media3_controls_play_description
)
)
// The icon flips between play and pause via `showPauseButton`, which is
// decoupled from the underlying `COMMAND_PLAY_PAUSE` availability — a paused
// player still receives `COMMAND_PLAY_PAUSE` and the button is enabled,
// it just renders the play glyph. Tap target is identical either way.
.setEnabled(true)
.build()

val nextButton = CommandButton.Builder()
.setPlayerCommand(Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM)
.setIconResId(Icons.next)
.setDisplayName(
context.getString(
androidx.media3.session.R.string.media3_controls_seek_to_next_description
)
)
.setEnabled(true)
.build()

// Positional order: Prev | −seek | PlayPause | +seek | Next | (custom buttons).
// Custom buttons are appended so the pinned standard-5 strip is preserved
// (lockscreen tile always shows the same Prev/−seek/PlayPause/+seek/Next),
// but anything the session publishes via `MediaSession.setCustomLayout(...)`
// (e.g. bookmark, sleep timer, download) is honored instead of silently
// dropped.
//
// Mirrors `DefaultMediaNotificationProvider`'s own filter: only enabled
// buttons with a non-null `sessionCommand` survive into the action list —
// player-command buttons are not part of the custom layout contract.
val standardFive = ImmutableList.of(
prevButton, skipBackButton, playPauseButton, skipForwardButton, nextButton,
)
if (customLayout.isEmpty()) return standardFive

val customButtons = customLayout.filter {
it.sessionCommand != null && it.isEnabled
}
return if (customButtons.isEmpty()) {
standardFive
} else {
ImmutableList.builder<CommandButton>()
.addAll(standardFive)
.addAll(customButtons)
.build()
}
return out.build()
}

/**
* Adds every button from [mediaButtons] to the notification (delegated to super),
* then returns one compact-view index per action so the system tile renders the
* whole strip. The standard 5 occupy positions `[0..4]`; any custom buttons
* appended by [getMediaButtons] occupy positions `[5..N)` and fall through to the
* expanded notification (the platform caps visible compact slots at 5).
*
* Per `DefaultMediaNotificationProvider` source, `super.addNotificationActions(...)`
* calls `builder.addAction(...)` for every entry in [mediaButtons] regardless of
* `CommandButton.isEnabled`. Disabled buttons still occupy an action-list slot —
* they just render dimmed. So every index we hand back is in-bounds.
*
* The pure helper that produces the index array lives in [Companion.compactViewIndicesFor]
* and is unit-tested separately to make the invariant explicit.
*/
override fun addNotificationActions(
mediaSession: MediaSession,
mediaButtons: ImmutableList<CommandButton>,
builder: NotificationCompat.Builder,
actionFactory: MediaNotification.ActionFactory,
): IntArray {
// Let super add all actions to `builder`.
val superIndices = super.addNotificationActions(mediaSession, mediaButtons, builder, actionFactory)

// Count the total enabled buttons (= total notification actions added by super).
val totalActions = mediaButtons.count { it.isEnabled }

// Find the play/pause action index by scanning enabled buttons in order.
var playPauseIdx = -1
var actionIdx = 0
for (button in mediaButtons) {
if (!button.isEnabled) continue
if (button.playerCommand == Player.COMMAND_PLAY_PAUSE) {
playPauseIdx = actionIdx
break
}
actionIdx++
}

if (playPauseIdx < 0) return superIndices
super.addNotificationActions(mediaSession, mediaButtons, builder, actionFactory)
return compactViewIndicesFor(mediaButtons.size)
}

// Compact strip: the button to the left of play/pause and the one to the right.
// Typically this resolves to: seek-back | play/pause | seek-forward.
val compact = buildList {
if (playPauseIdx > 0) add(playPauseIdx - 1)
add(playPauseIdx)
if (playPauseIdx + 1 < totalActions) add(playPauseIdx + 1)
}
return compact.toIntArray()
companion object {
/**
* Pure helper that returns the compact-view indices for the strip.
*
* Always returns every index `[0, size)` so the system tile renders
* the entire action list — including any custom buttons appended after
* the standard 5 by [getMediaButtons]. The platform caps the visible
* compact slots at 5, so when the list grows beyond 5 the system still
* shows just the first 5 (the pinned Prev / −seek / PlayPause / +seek /
* Next) and the rest fall through to the expanded notification only.
* Returning all indices (rather than `[0..4]` hardcoded) keeps the
* helper in sync with the actual action-list size so callers that
* supply fewer than 5 buttons still get in-bounds indices handed back
* to `Notification.MediaStyle.setShowActionsInCompactView`.
*/
internal fun compactViewIndicesFor(actionListSize: Int): IntArray =
IntArray(actionListSize.coerceAtLeast(0)) { it }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@ import javax.inject.Inject
/**
* Foreground [MediaSessionService] — keeps audio playing when backgrounded or screen locked.
*
* Notification buttons are auto-generated by [LibravaultNotificationProvider] from the
* player's available commands (seek-back, play/pause, seek-forward). The provider
* override pins exactly those three as the compact-view slots for the lock screen.
* Notification buttons are auto-generated by [LibravaultNotificationProvider] which
* publishes a five-button compact strip to the Android 13+ system media tile
* (lockscreen "Live notifications" / Quick-Settings media output):
* `[ Prev | −N s | Play/Pause | +N s | Next ]`, where `N` is the user's
* `defaultSkipDurationSec` preference (default 30 s). See the provider class for
* details and the documented runtime-increment limitation.
*
* Seek increments (30 s) are configured on the ExoPlayer singleton in [PlayerModule].
* The seek increment is seeded from `defaultSkipDurationSec` on the ExoPlayer
* singleton in [PlayerModule] when the player is first built; in-app ± buttons in
* the reader and library mini-players read the preference live and therefore always
* honor runtime updates without restarting the service.
*/
@AndroidEntryPoint
class PlaybackService : MediaSessionService() {
Expand Down
Loading
Loading