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
6 changes: 6 additions & 0 deletions .github/nightly-notes/2026-11-16-merge-issues-1633-2167.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
## New
- DeArrow thumbnails only: never show the uploader's thumbnail (#1633)

## Fixed
- With DeArrow, new videos show a frame from the video instead of the original thumbnail (#1633)
- Seeking in a song no longer pauses to load it again (#2167)
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ class PlayerPreferences(
val DEARROW_ENABLED = booleanPreferencesKey("dearrow_enabled")
val DEARROW_BADGE_ENABLED = booleanPreferencesKey("dearrow_badge_enabled")
val DEARROW_RANDOM_FRAME = booleanPreferencesKey("dearrow_random_frame")
val DEARROW_THUMBNAILS_ONLY = booleanPreferencesKey("dearrow_thumbnails_only")

// AI channel list
val AI_LIST_BLOCK_ENABLED = booleanPreferencesKey("ai_list_block_enabled")
Expand Down Expand Up @@ -2502,6 +2503,17 @@ class PlayerPreferences(
}
}

/** Never load the uploader's thumbnail: DeArrow's, or else a frame YouTube takes from the video (#1633). */
val deArrowThumbnailsOnly: Flow<Boolean> =
context.playerPreferencesDataStore.data
.map { preferences -> preferences[Keys.DEARROW_THUMBNAILS_ONLY] ?: false }

suspend fun setDeArrowThumbnailsOnly(enabled: Boolean) {
context.playerPreferencesDataStore.edit { preferences ->
preferences[Keys.DEARROW_THUMBNAILS_ONLY] = enabled
}
}

// AI channel list
val aiListBlockEnabled: Flow<Boolean> =
context.playerPreferencesDataStore.data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ data class DeArrowContent(

/**
* The resolved deArrow overrides for a video. Non-null fields should replace the originals.
* [youTubeFrames] means DeArrow wants a frame here: until its own loads (or when it has no time to
* place one), YouTube's automatic frames stand in rather than the uploader's thumbnail (#1633).
*/
data class DeArrowResult(
val title: String? = null,
val thumbnailUrl: String? = null,
val youTubeFrames: Boolean = false,
)
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import okhttp3.HttpUrl.Companion.toHttpUrl
* Turns a branding answer into what a card shows, the way the DeArrow extension does: the server's
* first usable submission wins, a winning "original" keeps YouTube's version, and a video with no
* thumbnail submission shows the frame at the server's random time for it, so every DeArrow user
* sees the same one.
* sees the same one. When that frame cannot be shown yet, YouTube's own frames stand in.
*/
internal object DeArrowBrandingPolicy {
const val THUMBNAIL_URL = "https://dearrow-thumb.ajay.app/api/v1/getThumbnail"
Expand All @@ -29,15 +29,19 @@ internal object DeArrowBrandingPolicy {
?.takeIf { it.isNotBlank() }

val thumbnail = content.thumbnails.firstOrNull { it.locked || it.votes >= 0 }
val wantsRandomFrame = thumbnail == null && useRandomFrame && !isLiveOrUpcoming
val frameTime =
when {
thumbnail != null -> thumbnail.takeUnless { it.original }?.timestamp
useRandomFrame && !isLiveOrUpcoming -> randomFrameTime(content, fallbackDurationSeconds)
wantsRandomFrame -> randomFrameTime(content, fallbackDurationSeconds)
else -> null
}
val thumbnailUrl = frameTime?.let { frameUrl(videoId, it) }
// A new upload has no length on DeArrow's side and often none on the card (RSS), so the
// random frame can't be placed; it still wants a frame rather than the uploader's thumbnail.
val youTubeFrames = thumbnailUrl != null || wantsRandomFrame

return if (title == null && thumbnailUrl == null) null else DeArrowResult(title, thumbnailUrl)
return if (title == null && !youTubeFrames) null else DeArrowResult(title, thumbnailUrl, youTubeFrames)
}

private fun randomFrameTime(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ class DeArrowRepository internal constructor(
/** What a request already answered, for a card's first frame. */
fun cached(videoId: String): DeArrowContent? = fresh(videoId)?.content

/** Whether a request already answered for [videoId], even when the answer was nothing. */
fun isCached(videoId: String): Boolean = fresh(videoId) != null

suspend fun branding(videoId: String): DeArrowContent? {
fresh(videoId)?.let { return it.content }
val mine = CompletableDeferred<DeArrowContent?>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,19 @@ object PlayerConfig {
const val SHORTS_BUFFER_FOR_REBUFFER_MS = 750
const val SHORTS_BACK_BUFFER_MS = 2_000

/** Music buffer window. Audio-only, so a long window is cheap and a low start threshold is safe. */
/**
* Music buffer window. [MUSIC_MAX_BUFFER_MS] is the lean window (crossfade tails, low-RAM devices
* and Data Saver); otherwise a song loads whole and what has played stays, so a seek is in memory (#2167).
*/
const val MUSIC_MIN_BUFFER_MS = 2_500
const val MUSIC_MAX_BUFFER_MS = 30_000
const val MUSIC_BUFFER_FOR_PLAYBACK_MS = 1_000
const val MUSIC_BUFFER_FOR_REBUFFER_MS = 1_500
const val MUSIC_WHOLE_SONG_BUFFER_MS = 10 * 60 * 1000
const val MUSIC_BACK_BUFFER_MS = 10 * 60 * 1000

/** Bounds a long mix and the music player's video mode, which would otherwise size the cap for video. */
const val MUSIC_TARGET_BUFFER_BYTES = 24 * 1024 * 1024

/** Preferred delay from the true live edge. Keeps YouTube live playback stable. */
const val LIVE_EDGE_GAP_MS = 10_000L
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,19 +128,19 @@ object LoadControlFactory {
)

/**
* Music service: audio-only, so a long window costs little memory and a low playback threshold
* gets the first note out quickly. No back buffer, and no byte cap — the duration window is the
* only budget it needs.
* Music: a low playback threshold gets the first note out quickly. With [wholeSong] the song loads
* to its end and what has played is kept, both inside one byte cap, so a seek either way stays in
* memory (#2167). Without it, the lean 30 s window with no back buffer.
*/
fun forMusic(): DefaultLoadControl =
fun forMusic(wholeSong: Boolean = false): DefaultLoadControl =
build(
minMs = PlayerConfig.MUSIC_MIN_BUFFER_MS,
maxMs = PlayerConfig.MUSIC_MAX_BUFFER_MS,
maxMs = if (wholeSong) PlayerConfig.MUSIC_WHOLE_SONG_BUFFER_MS else PlayerConfig.MUSIC_MAX_BUFFER_MS,
playbackMs = PlayerConfig.MUSIC_BUFFER_FOR_PLAYBACK_MS,
rebufferMs = PlayerConfig.MUSIC_BUFFER_FOR_REBUFFER_MS,
backBufferMs = 0,
retainBackBufferFromKeyframe = false,
targetBufferBytes = C.LENGTH_UNSET,
backBufferMs = if (wholeSong) PlayerConfig.MUSIC_BACK_BUFFER_MS else 0,
retainBackBufferFromKeyframe = wholeSong,
targetBufferBytes = if (wholeSong) PlayerConfig.MUSIC_TARGET_BUFFER_BYTES else C.LENGTH_UNSET,
)

/** A skipped song's tail plays for moments, so it starts on little audio and loads no more than it will play. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,8 @@ class Media3MusicService : MediaLibraryService() {

val renderersFactory = musicRenderers(equalizer)

val loadControl = LoadControlFactory.forMusic()
val isLowRamDevice = (getSystemService(ACTIVITY_SERVICE) as? ActivityManager)?.isLowRamDevice == true
val loadControl = MusicLoadControl(LoadControlFactory.forMusic(wholeSong = !isLowRamDevice), NetworkState.isDataSaverOn(this))

player =
ExoPlayer
Expand Down Expand Up @@ -600,7 +601,7 @@ class Media3MusicService : MediaLibraryService() {
// order, the player's shuffle flag reorders nothing on its own, whichever controller sets it.
player.setShuffleOrder(ShuffleOrder.UnshuffledShuffleOrder(0))
musicResume.attach(player)
MusicPreload(this, player).attach(lifecycleScope, prefs.bufferProfile)
MusicPreload(this, player) { loadControl.savesData = it }.attach(lifecycleScope, prefs.bufferProfile)
crossfader = MusicCrossfader(player, ::buildCrossfadeTail, ::crossfadeMoment, ::applyLoudnessGain).also { it.attach() }
lifecycleScope.launch {
combine(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package io.github.aedev.flow.service

import androidx.annotation.OptIn
import androidx.media3.common.Timeline
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.LoadControl
import androidx.media3.exoplayer.analytics.PlayerId
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.TrackGroupArray
import androidx.media3.exoplayer.trackselection.ExoTrackSelection
import androidx.media3.exoplayer.upstream.Allocator
import io.github.aedev.flow.player.config.PlayerConfig

/**
* The music player's load control: [base] loads the whole song, and while [savesData] is on it stops at
* the lean 30 s window instead. Media3 fixes a player's load control when the player is built, and
* 1.11 ships no forwarding one, so the Data Saver check wraps the stock control rather than rebuilding
* the player. The back buffer stays either way: it costs memory, not data.
*
* Every override is spelled out: Kotlin's `by` delegation skips Java default methods, and the
* interface's defaults throw. These are the ten overloads `ExoPlayerImplInternal` 1.11 calls.
*/
@OptIn(UnstableApi::class)
internal class MusicLoadControl(
private val base: DefaultLoadControl,
initiallySavesData: Boolean,
) : LoadControl {
@Volatile
var savesData: Boolean = initiallySavesData

private var capped = false

override fun shouldContinueLoading(parameters: LoadControl.Parameters): Boolean {
val baseWants = base.shouldContinueLoading(parameters)
if (!savesData) {
capped = false
return baseWants
}
// Same hysteresis as the stock window: fill to the cap, then wait until below the minimum, so
// the radio wakes in bursts rather than for every few kilobytes.
if (parameters.bufferedDurationUs >= LEAN_MAX_US) {
capped = true
} else if (parameters.bufferedDurationUs < LEAN_MIN_US) {
capped = false
}
return baseWants && !capped
}

override fun onPrepared(playerId: PlayerId) = base.onPrepared(playerId)

override fun onTracksSelected(
parameters: LoadControl.Parameters,
trackGroups: TrackGroupArray,
trackSelections: Array<out ExoTrackSelection?>,
) = base.onTracksSelected(parameters, trackGroups, trackSelections)

override fun onStopped(playerId: PlayerId) = base.onStopped(playerId)

override fun onReleased(playerId: PlayerId) = base.onReleased(playerId)

override fun getAllocator(playerId: PlayerId): Allocator = base.getAllocator(playerId)

override fun getBackBufferDurationUs(playerId: PlayerId): Long = base.getBackBufferDurationUs(playerId)

override fun retainBackBufferFromKeyframe(playerId: PlayerId): Boolean = base.retainBackBufferFromKeyframe(playerId)

override fun shouldStartPlayback(parameters: LoadControl.Parameters): Boolean = base.shouldStartPlayback(parameters)

override fun shouldContinuePreloading(
playerId: PlayerId,
timeline: Timeline,
mediaPeriodId: MediaSource.MediaPeriodId,
bufferedDurationUs: Long,
): Boolean = base.shouldContinuePreloading(playerId, timeline, mediaPeriodId, bufferedDurationUs)

private companion object {
const val LEAN_MAX_US = PlayerConfig.MUSIC_MAX_BUFFER_MS * 1_000L
const val LEAN_MIN_US = PlayerConfig.MUSIC_MIN_BUFFER_MS * 1_000L
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ import kotlinx.coroutines.launch
/**
* Loads the start of the next song while the current one plays, so a skip has audio to start from
* (#2076). Media3 does it only while the current song isn't loading, through the same sources and
* cache. Off while Android's Data Saver or the Data saver buffer profile is on, checked on each new song.
* cache. Off while Android's Data Saver or the Data saver buffer profile is on, checked on each new song;
* [onSavingData] hears the same answer, for the load control's own window.
*/
@OptIn(UnstableApi::class)
internal class MusicPreload(
private val context: Context,
private val player: ExoPlayer,
private val onSavingData: (Boolean) -> Unit = {},
) {
private var profileSavesData = false

Expand All @@ -46,8 +48,10 @@ internal class MusicPreload(
}

private fun refresh() {
val savesData = profileSavesData || NetworkState.isDataSaverOn(context)
onSavingData(savesData)
val wanted =
if (profileSavesData || NetworkState.isDataSaverOn(context)) {
if (savesData) {
ExoPlayer.PreloadConfiguration.DEFAULT
} else {
ExoPlayer.PreloadConfiguration(NEXT_SONG_US)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ object SettingsMapper {
Entry("sponsorblock_action_poi_highlight", "sb_action_poi_highlight", Ty.STRING),
Entry("dearrow_enabled", "dearrow_enabled", Ty.BOOL),
Entry("dearrow_badge_enabled", "dearrow_badge_enabled", Ty.BOOL),
Entry("dearrow_random_frame", "dearrow_random_frame", Ty.BOOL),
Entry("subtitles_enabled", "subtitles_enabled", Ty.BOOL),
// Another device must not switch this phone's UI language (#1277).
Entry("app_language", "app_language", Ty.STRING, applied = false),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.github.aedev.flow.ui.components

import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.key
import androidx.compose.runtime.produceState
import androidx.compose.runtime.staticCompositionLocalOf
Expand All @@ -14,6 +15,16 @@ import io.github.aedev.flow.data.repository.DeArrowRepository
/** The activity's DeArrow lookup, installed by `ProvideVideoCardState`; null in previews and tests. */
val LocalDeArrow = staticCompositionLocalOf<DeArrowRepository?> { null }

/**
* DeArrow's [result] for a video, and whether the lookup has [answered]: true once the server replied
* or failed, and at once when there is nothing to ask.
*/
@Immutable
internal data class DeArrowLookup(
val result: DeArrowResult?,
val answered: Boolean,
)

/**
* What DeArrow replaces on [video], or null to keep YouTube's: switched off, a local file, no lookup
* installed, or nothing to replace. An answer already fetched shows on the first frame.
Expand All @@ -23,7 +34,15 @@ internal fun rememberDeArrowResult(
video: Video,
enabled: Boolean,
useRandomFrame: Boolean,
): DeArrowResult? {
): DeArrowResult? = rememberDeArrowLookup(video, enabled, useRandomFrame).result

/** [rememberDeArrowResult], also saying whether the answer is in yet. */
@Composable
internal fun rememberDeArrowLookup(
video: Video,
enabled: Boolean,
useRandomFrame: Boolean,
): DeArrowLookup {
val repository = LocalDeArrow.current
val active = enabled && repository != null && !LocalMediaIds.isLocal(video.id)
val resolve = { content: DeArrowContent? ->
Expand All @@ -38,8 +57,14 @@ internal fun rememberDeArrowResult(
}
}
return key(video.id, active, useRandomFrame) {
produceState(initialValue = if (active) resolve(repository?.cached(video.id)) else null, video.id, active, useRandomFrame) {
if (active) value = resolve(repository?.branding(video.id))
val initial =
when {
!active || repository == null -> DeArrowLookup(null, answered = true)
repository.isCached(video.id) -> DeArrowLookup(resolve(repository.cached(video.id)), answered = true)
else -> DeArrowLookup(null, answered = false)
}
produceState(initialValue = initial, video.id, active, useRandomFrame) {
if (active && !initial.answered) value = DeArrowLookup(resolve(repository?.branding(video.id)), answered = true)
}.value
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ fun MediaThumbnail(
showWatchProgress: Boolean = false,
placeholder: ImageVector? = null,
onModelLoaded: ((Any) -> Unit)? = null,
youTubeFrames: Boolean = LocalYouTubeFramesOnly.current,
showImage: Boolean = true,
overlay: @Composable BoxScope.() -> Unit = {},
) {
val openOrigin = rememberMediaOpenOrigin(videoId, shape)
Expand All @@ -70,15 +72,18 @@ fun MediaThumbnail(
)
}

VideoThumbnailImage(
videoId = videoId,
model = thumbnailUrl,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
onImageKey = reportImageKey,
onModelLoaded = onModelLoaded,
)
if (showImage) {
VideoThumbnailImage(
videoId = videoId,
model = thumbnailUrl,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
onImageKey = reportImageKey,
onModelLoaded = onModelLoaded,
youTubeFrames = youTubeFrames,
)
}

if (durationSeconds != null && durationSeconds > 0) {
DurationBadge(
Expand Down
Loading
Loading