youpipe: speed up video downloads with bigger buffers and throttled progress
- Commit
555058a0952203ad8d87075820d9b6924c117043- Author
- Vayun Mathur <[email protected]>
- When
- 2026-05-30 01:26 UTC (6 months ago)
- Parents
f5b0f5c
Diff
youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.ktindex 22cc3097ee..9be500e021 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt@@ -14,14 +14,19 @@ import com.vayunmathur.youpipe.data.SubscriptionDatabase import com.vayunmathur.youpipe.ui.VideoInfo import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.NetworkDataStream+import java.io.BufferedOutputStream import java.io.File import java.io.RandomAccessFile+import java.nio.channels.Channels import java.util.concurrent.atomic.AtomicLong import kotlin.time.Clock import kotlin.time.Instant import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class DownloadWorker(context: Context, params: WorkerParameters) :@@ -137,40 +142,74 @@ class DownloadWorker(context: Context, params: WorkerParameters) : RandomAccessFile(file, "rw").use { raf -> raf.setLength(totalBytes) } } - val jobs =- (0 until numChunks).map { i ->- val start = i * chunkSize- val end =- if (i == numChunks - 1) totalBytes - 1- else (i + 1) * chunkSize - 1+ // Throttled progress reporter: ONE coroutine polls the shared+ // counter at PROGRESS_INTERVAL_MS instead of every download+ // thread emitting on every 64KB write. Without this, a fast+ // connection produces thousands of StateFlow emissions per+ // second (each does an immutable Map copy of activeDownloads),+ // pinning the dispatcher and starving the actual network reads.+ val totalForReporter = totalBytes+ val progressJob = launch(Dispatchers.Default) {+ while (isActive) {+ val done = downloadedBytes.get()+ onProgress(done.toDouble() / totalForReporter)+ if (done >= totalForReporter) break+ delay(PROGRESS_INTERVAL_MS)+ }+ } - async(Dispatchers.IO) {- try {- client.stream(- url,- headers = mapOf("Range" to "bytes=$start-$end")- ) { stream, _ ->- if (stream == null) return@stream- RandomAccessFile(file, "rw").use { raf ->- raf.seek(start)- val buffer = ByteArray(8192)- while (!stream.isClosedForRead) {- if (isStopped) return@stream- val bytesRead = stream.read(buffer)- if (bytesRead == -1) break- raf.write(buffer, 0, bytesRead)- val total = downloadedBytes.addAndGet(bytesRead.toLong())- onProgress(total.toDouble() / totalBytes.toDouble())+ try {+ val jobs =+ (0 until numChunks).map { i ->+ val start = i * chunkSize+ val end =+ if (i == numChunks - 1) totalBytes - 1+ else (i + 1) * chunkSize - 1++ async(Dispatchers.IO) {+ try {+ client.stream(+ url,+ headers = mapOf("Range" to "bytes=$start-$end")+ ) { stream, _ ->+ if (stream == null) return@stream+ // RandomAccessFile.write is unbuffered —+ // wrap it via FileChannel so the 64KB+ // socket reads are coalesced into 256KB+ // disk syscalls. ~4× fewer write+ // syscalls per chunk at high bandwidth.+ RandomAccessFile(file, "rw").use { raf ->+ raf.seek(start)+ BufferedOutputStream(+ Channels.newOutputStream(raf.channel),+ WRITE_BUFFER_SIZE,+ ).use { out ->+ val buffer = ByteArray(READ_BUFFER_SIZE)+ while (!stream.isClosedForRead) {+ if (isStopped) return@stream+ val bytesRead = stream.read(buffer)+ if (bytesRead == -1) break+ out.write(buffer, 0, bytesRead)+ downloadedBytes.addAndGet(bytesRead.toLong())+ }+ out.flush()+ } } }+ } catch (e: Exception) {+ Log.e("DownloadWorker", "Error downloading chunk $i", e) }- } catch (e: Exception) {- Log.e("DownloadWorker", "Error downloading chunk $i", e) } }- } - jobs.forEach { it.await() }+ jobs.forEach { it.await() }+ } finally {+ progressJob.cancel()+ // Final flush of progress so the UI doesn't appear stuck at+ // <100% if the polling loop was mid-sleep when the last+ // chunk finished.+ onProgress(downloadedBytes.get().toDouble() / totalBytes)+ } } private suspend fun downloadFileSimple(url: String, file: File, onProgress: (Double) -> Unit) {@@ -179,8 +218,9 @@ class DownloadWorker(context: Context, params: WorkerParameters) : if (stream == null) return@stream val totalBytes = response.contentLength var downloadedBytes = 0L- file.outputStream().use { output ->- val buffer = ByteArray(8192)+ var lastReportedMs = 0L+ BufferedOutputStream(file.outputStream(), WRITE_BUFFER_SIZE).use { output ->+ val buffer = ByteArray(READ_BUFFER_SIZE) while (!stream.isClosedForRead) { if (isStopped) { file.delete()@@ -191,9 +231,17 @@ class DownloadWorker(context: Context, params: WorkerParameters) : output.write(buffer, 0, read) downloadedBytes += read if (totalBytes != null && totalBytes > 0) {- onProgress(downloadedBytes.toDouble() / totalBytes.toDouble())+ val now = System.currentTimeMillis()+ if (now - lastReportedMs >= PROGRESS_INTERVAL_MS) {+ onProgress(downloadedBytes.toDouble() / totalBytes.toDouble())+ lastReportedMs = now+ } } }+ output.flush()+ if (totalBytes != null && totalBytes > 0) {+ onProgress(downloadedBytes.toDouble() / totalBytes.toDouble())+ } } } } catch (e: Exception) {@@ -202,6 +250,24 @@ class DownloadWorker(context: Context, params: WorkerParameters) : } companion object {+ /**+ * Socket-read buffer. 64KB matches NewPipe's downloader and is large+ * enough that read/write syscall overhead is negligible compared to+ * network throughput; 8KB (the previous value) pegged the dispatcher+ * on syscalls long before the network was saturated.+ */+ private const val READ_BUFFER_SIZE = 64 * 1024++ /**+ * File-write buffer wrapped around [RandomAccessFile.channel]. Larger+ * than [READ_BUFFER_SIZE] so multiple socket reads collapse into one+ * disk write.+ */+ private const val WRITE_BUFFER_SIZE = 256 * 1024++ /** Maximum UI update rate for download progress, in milliseconds. */+ private const val PROGRESS_INTERVAL_MS = 250L+ fun enqueue(context: Context, videoInfo: VideoInfo, videoUrl: String, audioUrl: String?) { val data = Data.Builder()