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,7 @@
## Improved
- Shuffle on a long YouTube playlist starts at once and mixes in the rest of the playlist as it loads
- The video queue survives an app restart without saving thousands of videos each time it moves on

## Fixed
- Playing a long YouTube playlist no longer stops after the videos that had loaded when you tapped Play
- A link to a video inside a playlist starts playing right away and carries on through the whole playlist
9 changes: 9 additions & 0 deletions .github/nightly-notes/2026-11-23-feat-queue-sheet-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
## New
- The queue's repeat button now cycles off, repeat all and repeat one
- TalkBack can move a playlist video one place up or down and reads its position

## Improved
- The queue opens with the two videos before the current one still in view, and scrolls smoothly when the video changes

## Fixed
- The drag handle in playlists is easier to grab and picks a video up after a short touch instead of a long press
8 changes: 8 additions & 0 deletions .github/nightly-notes/2026-11-23-perf-playlist-paging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## Improved
- Long YouTube playlists open faster and load more videos as you scroll, instead of reading the whole playlist at once
- A playlist shows YouTube's full video count while it is still loading
- Downloaded playlists open from your device first, even with no connection
- A downloaded playlist shows a button to download the videos added since

## Fixed
- Saving a YouTube playlist while it was still loading saved only part of it
5 changes: 5 additions & 0 deletions app/src/main/java/io/github/aedev/flow/FlowApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import io.github.aedev.flow.data.profile.ProfileSlices
import io.github.aedev.flow.data.profile.ProfileWebView
import io.github.aedev.flow.data.profile.ProfileWorkReconciler
import io.github.aedev.flow.data.recommendation.FlowNeuroEngine
import io.github.aedev.flow.data.repository.YouTubePlaylistRepository
import io.github.aedev.flow.data.repository.YouTubeRepository
import io.github.aedev.flow.discord.DiscordPresenceRuntime
import io.github.aedev.flow.innertube.YouTube
Expand Down Expand Up @@ -74,6 +75,9 @@ class FlowApplication :
@Inject
lateinit var okHttpClient: OkHttpClient

@Inject
lateinit var playlistRepository: YouTubePlaylistRepository

@Inject
lateinit var vpnStateMonitor: VpnStateMonitor

Expand Down Expand Up @@ -312,6 +316,7 @@ class FlowApplication :
}

private fun releaseVolatileMemory() {
if (::playlistRepository.isInitialized) playlistRepository.trimMemory()
if (::imageLoader.isInitialized) {
imageLoader.memoryCache?.clear()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package io.github.aedev.flow.data.repository

import io.github.aedev.flow.player.queue.QueuePage
import io.github.aedev.flow.player.queue.QueuePageSource
import io.github.aedev.flow.player.queue.QueueSourceSpec
import javax.inject.Inject
import javax.inject.Singleton

/** Builds the sources that keep a playlist queue loading, and rebuilds them from a saved queue. */
@Singleton
class PlaylistQueueSources
@Inject
constructor(
private val playlists: YouTubePlaylistRepository,
private val repository: YouTubeRepository,
) {
/** The playlist's pages from browse continuation [token]. */
fun playlistPages(
playlistId: String,
token: String,
): QueuePageSource = PlaylistPagesSource(playlistId, token, playlists)

/** The watch panel's pages from its continuation [token]. */
fun watchPanel(
playlistId: String,
token: String,
): QueuePageSource = WatchPanelSource(playlistId, token, repository)

fun from(spec: QueueSourceSpec): QueuePageSource =
when (spec) {
is QueueSourceSpec.PlaylistPages -> playlistPages(spec.playlistId, spec.token)
is QueueSourceSpec.WatchPanel -> watchPanel(spec.playlistId, spec.token)
}
}

private class PlaylistPagesSource(
private val playlistId: String,
private var token: String,
private val playlists: YouTubePlaylistRepository,
) : QueuePageSource {
override val spec: QueueSourceSpec get() = QueueSourceSpec.PlaylistPages(playlistId, token)

override suspend fun next(): QueuePage? {
val (videos, next) = playlists.nextPage(playlistId, token) ?: return null
// A token YouTube already sent would read the same page again forever.
val more = next != null && next != token
next?.let { token = it }
return QueuePage(videos, hasMore = more)
}
}

private class WatchPanelSource(
private val playlistId: String,
private var token: String,
private val repository: YouTubeRepository,
) : QueuePageSource {
override val spec: QueueSourceSpec get() = QueueSourceSpec.WatchPanel(playlistId, token)

override suspend fun next(): QueuePage? {
val (videos, next) = repository.watchPlaylistContinuation(token) ?: return null
val more = next != null && next != token
next?.let { token = it }
return QueuePage(videos, hasMore = more)
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
package io.github.aedev.flow.data.repository

import android.app.ActivityManager
import android.content.Context
import android.util.Log
import android.util.LruCache
import dagger.hilt.android.qualifiers.ApplicationContext
import io.github.aedev.flow.data.model.Video
import io.github.aedev.flow.innertube.YouTube
import io.github.aedev.flow.innertube.pages.VideoPlaylistPage
import io.github.aedev.flow.innertube.pages.isMix
import io.github.aedev.flow.player.stream.InFlightRequestCoalescer
import io.github.aedev.flow.utils.PerformanceDispatcher
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton

private const val TAG = "YouTubePlaylistRepo"
private const val MAX_PAGES = 60
private const val FULL_LIST_TTL_MS = 10 * 60 * 1000L

// A few pages, so the playlist page and a queue playing from it read each page once.
private const val PAGE_CACHE_SIZE = 8

// Whole playlists kept for reopening, counted in videos; a low-RAM phone or TV keeps half.
private const val COMPLETE_LIST_VIDEOS = 6_000

/** A YouTube playlist as the page shows it: the first page now, the rest through [YouTubePlaylistRepository.nextPage]. */
data class RemotePlaylistPage(
val title: String,
Expand All @@ -41,25 +53,53 @@ data class RemotePlaylistPage(
@Singleton
class YouTubePlaylistRepository
@Inject
constructor() {
constructor(
@ApplicationContext context: Context,
) {
private data class CachedList(
val page: RemotePlaylistPage,
val loadedAtMs: Long,
)

private val completeLists = ConcurrentHashMap<String, CachedList>()
private val completeLists =
object : LruCache<String, CachedList>(
if (context.getSystemService(ActivityManager::class.java)?.isLowRamDevice ==
true
) {
COMPLETE_LIST_VIDEOS / 2
} else {
COMPLETE_LIST_VIDEOS
},
) {
override fun sizeOf(
key: String,
value: CachedList,
): Int =
value.page.videos.size
.coerceAtLeast(1)
}
private val pages = LruCache<String, Pair<List<Video>, String?>>(PAGE_CACHE_SIZE)
private val pagesInFlight = InFlightRequestCoalescer<String, Pair<List<Video>, String?>?>(CoroutineScope(SupervisorJob()))

/** The whole playlist if it was loaded recently, so the page can show it without a request. */
fun cachedComplete(playlistId: String): RemotePlaylistPage? =
completeLists[playlistId]
?.takeIf { System.currentTimeMillis() - it.loadedAtMs < FULL_LIST_TTL_MS }
?.page
fun cachedComplete(playlistId: String): RemotePlaylistPage? {
val cached = completeLists[playlistId] ?: return null
if (System.currentTimeMillis() - cached.loadedAtMs < FULL_LIST_TTL_MS) return cached.page
completeLists.remove(playlistId)
return null
}

/** Lets go of every kept list and page when the system runs low on memory. */
fun trimMemory() {
completeLists.evictAll()
pages.evictAll()
}

fun rememberComplete(
playlistId: String,
page: RemotePlaylistPage,
) {
completeLists[playlistId] = CachedList(page.copy(continuation = null), System.currentTimeMillis())
completeLists.put(playlistId, CachedList(page.copy(continuation = null), System.currentTimeMillis()))
}

suspend fun firstPage(playlistId: String): RemotePlaylistPage? {
Expand Down Expand Up @@ -97,7 +137,11 @@ class YouTubePlaylistRepository
suspend fun nextPage(
playlistId: String,
continuation: String,
): Pair<List<Video>, String?>? = fetch { YouTube.videoPlaylistPage(playlistId, continuation) }?.let { it.videos to it.continuation }
): Pair<List<Video>, String?>? =
pages[continuation] ?: pagesInFlight
.run(continuation) {
fetch { YouTube.videoPlaylistPage(playlistId, continuation) }?.let { it.videos to it.continuation }
}?.also { pages.put(continuation, it) }

/**
* Every video, page by page, for a caller that needs the whole list (syncing a saved copy).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ import io.github.aedev.flow.innertube.pages.LiveMetadataUpdate
import io.github.aedev.flow.innertube.pages.VideoCommentsSection
import io.github.aedev.flow.innertube.pages.VideoDescriptionPage
import io.github.aedev.flow.innertube.pages.WatchPageHeader
import io.github.aedev.flow.innertube.pages.WatchPlaylistWindow
import io.github.aedev.flow.innertube.pages.YouTubeCountParser
import io.github.aedev.flow.innertube.pages.channel.ChannelHeader
import io.github.aedev.flow.innertube.pages.parseYouTubeViewCount
import io.github.aedev.flow.innertube.pages.search.resultVideos
import io.github.aedev.flow.innertube.pages.toWatchPageHeader
import io.github.aedev.flow.innertube.pages.toWatchPlaylistWindow
import io.github.aedev.flow.player.stream.InFlightRequestCoalescer
import io.github.aedev.flow.utils.PerformanceDispatcher
import io.github.aedev.flow.utils.ThumbnailUrlResolver
Expand Down Expand Up @@ -82,9 +84,12 @@ class YouTubeRepository
WatchResponseCache<JsonElement>(
capacity = WATCH_NEXT_CACHE_SIZE,
scope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
fetch = { videoId -> YouTube.watchNextJson(videoId).getOrNull() },
fetch = { videoId -> YouTube.watchNextJson(videoId, watchPlaylistFor.remove(videoId)).getOrNull() },
)

// The playlist a video is about to play from, so its one watch request also brings the queue window.
private val watchPlaylistFor = java.util.concurrent.ConcurrentHashMap<String, String>()

// Cache for channel avatar URLs to avoid redundant network calls
private val channelAvatarCache = LruCache<String, String>(300)
private val videoAvatarStackCache = LruCache<String, List<String>>(300)
Expand Down Expand Up @@ -444,6 +449,29 @@ class YouTubeRepository
*/
suspend fun watchNextResponse(videoId: String): JsonElement? = watchResponses.forPlayer(videoId)

/**
* The part of [playlistId] around [videoId], read from the watch request the player makes for
* that video anyway. A watch response already cached without the playlist costs one request more.
*/
suspend fun watchPlaylistWindow(
videoId: String,
playlistId: String,
): WatchPlaylistWindow? {
fun JsonElement.window() = toWatchPlaylistWindow()?.takeIf { it.playlistId == null || it.playlistId == playlistId }
watchResponses.cached(videoId)?.window()?.let { return it }
if (watchResponses.cached(videoId) == null) {
watchPlaylistFor[videoId] = playlistId
val response = watchResponses.forPlayer(videoId)
watchPlaylistFor.remove(videoId)
response?.window()?.let { return it }
}
return YouTube.watchNextJson(videoId, playlistId).getOrNull()?.window()
}

/** The playlist panel's videos after continuation [token], and the token after them. */
suspend fun watchPlaylistContinuation(token: String): Pair<List<Video>, String?>? =
withContext(PerformanceDispatcher.networkIO) { YouTube.watchPlaylistContinuation(token).getOrNull() }

/**
* The typed watch response, off the one request the player already makes. Every watch
* request goes through that cache: a second `/next` for the same video, or one to the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package io.github.aedev.flow.data.video

/** Videos kept before the current one when a long queue is saved. */
private const val KEPT_BEFORE = 50

/** The most videos a saved queue holds; a playlist queue reloads the rest from its source. */
internal const val SAVED_QUEUE_LIMIT = 500

/**
* The part of a queue that is saved: [start] until [end] around the current video. A queue still
* loading its playlist keeps its source only when the saved part reaches the end of what has loaded,
* since the source carries on from there.
*/
internal data class SavedQueueWindow(
val start: Int,
val end: Int,
val keepsSource: Boolean,
) {
companion object {
fun around(
size: Int,
index: Int,
hasSource: Boolean,
): SavedQueueWindow {
val start = (index - KEPT_BEFORE).coerceIn(0, (size - 1).coerceAtLeast(0))
val end = (start + SAVED_QUEUE_LIMIT).coerceAtMost(size)
return SavedQueueWindow(start, end, keepsSource = hasSource && end == size)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import io.github.aedev.flow.data.local.safePreferencesDataStore
import io.github.aedev.flow.data.model.Video
import io.github.aedev.flow.data.profile.StoreScope
import io.github.aedev.flow.player.queue.QueueSourceSpec
import kotlinx.coroutines.flow.first
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
Expand All @@ -17,18 +18,23 @@ private val Context.videoQueueStore by safePreferencesDataStore(name = "video_qu
private val QueueKey = stringPreferencesKey("queue_json")
private val QueueJson = Json { ignoreUnknownKeys = true }

/** A video queue as it was left: its videos, the one playing and the title it was started under. */
/**
* A video queue as it was left: its videos, the one playing, the title it was started under, and
* where its later videos load from when it was still loading its playlist.
*/
data class SavedVideoQueue(
val videos: List<Video>,
val index: Int,
val title: String?,
val source: QueueSourceSpec? = null,
)

@Serializable
internal data class StoredQueue(
val items: List<StoredQueueItem>,
val index: Int,
val title: String? = null,
val source: QueueSourceSpec? = null,
)

@Serializable
Expand All @@ -54,21 +60,30 @@ class VideoQueueStore
videos: List<Video>,
index: Int,
title: String?,
source: QueueSourceSpec? = null,
) {
context.videoQueueStore.edit { prefs ->
if (videos.size < 2 || index !in videos.indices) {
if ((videos.size < 2 && source == null) || index !in videos.indices) {
prefs.remove(QueueKey)
} else {
prefs[QueueKey] =
QueueJson.encodeToString(StoredQueue.serializer(), StoredQueue(videos.map { it.toStored() }, index, title))
val window = SavedQueueWindow.around(videos.size, index, hasSource = source != null)
val stored =
StoredQueue(
items = videos.subList(window.start, window.end).map { it.toStored() },
index = index - window.start,
title = title,
source = source.takeIf { window.keepsSource },
)
prefs[QueueKey] = QueueJson.encodeToString(StoredQueue.serializer(), stored)
}
}
}

suspend fun load(): SavedVideoQueue? {
val raw = context.videoQueueStore.data.first()[QueueKey] ?: return null
val stored = runCatching { QueueJson.decodeFromString(StoredQueue.serializer(), raw) }.getOrNull() ?: return null
return SavedVideoQueue(stored.items.map { it.toVideo() }, stored.index, stored.title).takeIf { it.index in it.videos.indices }
return SavedVideoQueue(stored.items.map { it.toVideo() }, stored.index, stored.title, stored.source)
.takeIf { it.index in it.videos.indices }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ class DownloadedCollections

suspend fun collection(id: String): DownloadCollectionEntity? = find(id)?.asPage()

/** Every video the collection of playlist [id] knows, downloaded or left out. */
suspend fun memberIds(id: String): Set<String> {
val stored = find(id) ?: return emptySet()
return collectionDao.itemsOf(stored.id).mapTo(HashSet()) { it.videoId }
}

/** The videos left out of the collection of playlist [id] the last time it was downloaded. */
suspend fun excludedIds(id: String): Set<String> {
val stored = find(id) ?: return emptySet()
Expand Down
Loading