Modern Apps git

← Modern-Apps.git

youpipe: speed up video downloads

Commit
429caa5c987889d183a856e15948412bc9c09b91
Author
Vayun Mathur <[email protected]>
When
2026-05-06 13:53 UTC (7 months ago)
Parents
483a902

Diff

youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadManager.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadManager.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadManager.ktindex ade63c746b..a1fe0e5a65 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadManager.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadManager.kt@@ -6,6 +6,7 @@ import com.vayunmathur.youpipe.ui.VideoInfo import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update  data class DownloadStatus(     val videoInfo: VideoInfo,@@ -22,17 +23,19 @@ object DownloadManager {     }      fun updateProgress(videoID: Long, progress: Double) {-        _activeDownloads.value = _activeDownloads.value[videoID]?.let {-            _activeDownloads.value + (videoID to it.copy(progress = progress))-        } ?: _activeDownloads.value+        _activeDownloads.update { current ->+            current[videoID]?.let {+                current + (videoID to it.copy(progress = progress))+            } ?: current+        }     }      fun finishDownload(videoID: Long) {-        _activeDownloads.value = _activeDownloads.value - videoID+        _activeDownloads.update { it - videoID }     }      fun cancelDownload(context: Context, videoID: Long) {         WorkManager.getInstance(context).cancelUniqueWork("download_$videoID")-        _activeDownloads.value = _activeDownloads.value - videoID+        _activeDownloads.update { it - videoID }     } }
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 a3d2592535..f93505c4ec 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt@@ -11,71 +11,186 @@ import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.youpipe.data.DownloadedVideo import com.vayunmathur.youpipe.data.SubscriptionDatabase import com.vayunmathur.youpipe.ui.VideoInfo+import java.io.File+import java.io.RandomAccessFile+import java.util.concurrent.TimeUnit+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.withContext import okhttp3.OkHttpClient import okhttp3.Request import okio.buffer import okio.sink-import java.io.File-import kotlin.time.Clock-import kotlin.time.Instant -class DownloadWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {+class DownloadWorker(context: Context, params: WorkerParameters) :+        CoroutineWorker(context, params) { -    override suspend fun doWork(): Result {+    override suspend fun doWork(): Result = coroutineScope {         val videoID = inputData.getLong("videoID", -1L)-        val videoUrl = inputData.getString("videoUrl") ?: return Result.failure()+        val videoUrl = inputData.getString("videoUrl") ?: return@coroutineScope Result.failure()         val audioUrl = inputData.getString("audioUrl")-        -        val videoInfo = VideoInfo(-            name = inputData.getString("name") ?: "",-            videoID = videoID,-            duration = inputData.getLong("duration", 0L),-            views = inputData.getLong("views", 0L),-            uploadDate = Instant.fromEpochSeconds(inputData.getLong("uploadDate", 0L)),-            thumbnailURL = inputData.getString("thumbnailURL") ?: "",-            author = inputData.getString("author") ?: ""-        )++        val videoInfo =+                VideoInfo(+                        name = inputData.getString("name") ?: "",+                        videoID = videoID,+                        duration = inputData.getLong("duration", 0L),+                        views = inputData.getLong("views", 0L),+                        uploadDate = Instant.fromEpochSeconds(inputData.getLong("uploadDate", 0L)),+                        thumbnailURL = inputData.getString("thumbnailURL") ?: "",+                        author = inputData.getString("author") ?: ""+                )          val db = applicationContext.buildDatabase<SubscriptionDatabase>()-        -        return try {-            val client = OkHttpClient()-            val dir = File(applicationContext.getExternalFilesDir(null), "downloads")-            if (!dir.exists()) dir.mkdirs()+        val dir = File(applicationContext.getExternalFilesDir(null), "downloads")+        if (!dir.exists()) dir.mkdirs() -            val videoFile = File(dir, "$videoID.mp4")-            val audioFile = if (audioUrl != null) File(dir, "$videoID.m4a") else null+        val videoFile = File(dir, "$videoID.mp4")+        val audioFile = if (audioUrl != null) File(dir, "$videoID.m4a") else null -            val videoWeight = if (audioUrl != null) 0.5 else 1.0-            -            downloadFile(client, videoUrl, videoFile) { p ->-                DownloadManager.updateProgress(videoID, p * videoWeight)-            }+        val createdFiles = mutableListOf<File>()+        createdFiles.add(videoFile)+        audioFile?.let { createdFiles.add(it) } -            audioUrl?.let { url ->-                downloadFile(client, url, audioFile!!) { p ->-                    DownloadManager.updateProgress(videoID, 0.5 + (p * 0.5))-                }-            }+        try {+            val videoWeight = if (audioUrl != null) 0.5 else 1.0 -            val download = DownloadedVideo(-                id = videoID,-                videoItem = videoInfo,-                filePath = videoFile.absolutePath,-                audioPath = audioFile?.absolutePath,-                timestamp = Clock.System.now()-            )+            // Simplified progress reporting for parallel:+            var videoP = 0.0+            var audioP = 0.0++            val vJob =+                    async(Dispatchers.IO) {+                        downloadFileChunked(videoUrl, videoFile) { p ->+                            videoP = p+                            DownloadManager.updateProgress(+                                    videoID,+                                    (videoP * videoWeight) + (audioP * (1.0 - videoWeight))+                            )+                        }+                    }++            val aJob =+                    audioUrl?.let { url ->+                        async(Dispatchers.IO) {+                            downloadFileChunked(url, audioFile!!) { p ->+                                audioP = p+                                DownloadManager.updateProgress(+                                        videoID,+                                        (videoP * videoWeight) + (audioP * (1.0 - videoWeight))+                                )+                            }+                        }+                    }++            vJob.await()+            aJob?.await()++            val download =+                    DownloadedVideo(+                            id = videoID,+                            videoItem = videoInfo,+                            filePath = videoFile.absolutePath,+                            audioPath = audioFile?.absolutePath,+                            timestamp = Clock.System.now()+                    )              db.downloadedVideoDao().upsert(download)             Result.success()         } catch (e: Exception) {+            // Cleanup on error or cancellation+            createdFiles.forEach { if (it.exists()) it.delete() }             Result.failure()         } finally {+            if (isStopped) {+                createdFiles.forEach { if (it.exists()) it.delete() }+            }             DownloadManager.finishDownload(videoID)         }     } -    private fun downloadFile(client: OkHttpClient, url: String, file: File, onProgress: (Double) -> Unit) {+    private suspend fun downloadFileChunked(url: String, file: File, onProgress: (Double) -> Unit) =+            coroutineScope {+                val request = Request.Builder().url(url).head().build()+                val totalBytes =+                        client.newCall(request).execute().use { response ->+                            if (!response.isSuccessful) {+                                // If HEAD fails, try GET with a small range to get content length+                                val getRequest =+                                        Request.Builder()+                                                .url(url)+                                                .header("Range", "bytes=0-0")+                                                .build()+                                client.newCall(getRequest).execute().use { getResponse ->+                                    if (!getResponse.isSuccessful) return@coroutineScope+                                    val contentRange = getResponse.header("Content-Range")+                                    contentRange?.substringAfterLast("/")?.toLongOrNull()+                                            ?: getResponse.body.contentLength()+                                }+                            } else {+                                response.body.contentLength()+                            }+                        }++                if (totalBytes <= 0) {+                    // Fallback to simple download if size unknown+                    downloadFileSimple(url, file, onProgress)+                    return@coroutineScope+                }++                val numChunks = 4+                val chunkSize = totalBytes / numChunks+                val downloadedBytes = AtomicLong(0)++                // Pre-allocate file+                withContext(Dispatchers.IO) {+                    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++                            async(Dispatchers.IO) {+                                val chunkRequest =+                                        Request.Builder()+                                                .url(url)+                                                .addHeader("Range", "bytes=$start-$end")+                                                .build()++                                client.newCall(chunkRequest).execute().use { response ->+                                    if (!response.isSuccessful) return@async++                                    val source = response.body.source()+                                    RandomAccessFile(file, "rw").use { raf ->+                                        raf.seek(start)+                                        val buffer = ByteArray(8192)+                                        var bytesRead: Int+                                        while (true) {+                                            if (isStopped) return@async+                                            bytesRead = source.read(buffer)+                                            if (bytesRead == -1) break+                                            raf.write(buffer, 0, bytesRead)+                                            val total =+                                                    downloadedBytes.addAndGet(bytesRead.toLong())+                                            onProgress(total.toDouble() / totalBytes.toDouble())+                                        }+                                    }+                                }+                            }+                        }++                jobs.forEach { it.await() }+            }++    private fun downloadFileSimple(url: String, file: File, onProgress: (Double) -> Unit) {         val request = Request.Builder().url(url).build()         client.newCall(request).execute().use { response ->             if (!response.isSuccessful) return@@ -107,28 +222,34 @@ class DownloadWorker(context: Context, params: WorkerParameters) : CoroutineWork     }      companion object {+        private val client =+                OkHttpClient.Builder()+                        .connectTimeout(30, TimeUnit.SECONDS)+                        .readTimeout(30, TimeUnit.SECONDS)+                        .build()+         fun enqueue(context: Context, videoInfo: VideoInfo, videoUrl: String, audioUrl: String?) {-            val data = Data.Builder()-                .putLong("videoID", videoInfo.videoID)-                .putString("name", videoInfo.name)-                .putLong("duration", videoInfo.duration)-                .putLong("views", videoInfo.views)-                .putLong("uploadDate", videoInfo.uploadDate.epochSeconds)-                .putString("thumbnailURL", videoInfo.thumbnailURL)-                .putString("author", videoInfo.author)-                .putString("videoUrl", videoUrl)-                .putString("audioUrl", audioUrl)-                .build()--            val request = OneTimeWorkRequestBuilder<DownloadWorker>()-                .setInputData(data)-                .build()--            WorkManager.getInstance(context).enqueueUniqueWork(-                "download_${videoInfo.videoID}",-                ExistingWorkPolicy.KEEP,-                request-            )+            val data =+                    Data.Builder()+                            .putLong("videoID", videoInfo.videoID)+                            .putString("name", videoInfo.name)+                            .putLong("duration", videoInfo.duration)+                            .putLong("views", videoInfo.views)+                            .putLong("uploadDate", videoInfo.uploadDate.epochSeconds)+                            .putString("thumbnailURL", videoInfo.thumbnailURL)+                            .putString("author", videoInfo.author)+                            .putString("videoUrl", videoUrl)+                            .putString("audioUrl", audioUrl)+                            .build()++            val request = OneTimeWorkRequestBuilder<DownloadWorker>().setInputData(data).build()++            WorkManager.getInstance(context)+                    .enqueueUniqueWork(+                            "download_${videoInfo.videoID}",+                            ExistingWorkPolicy.KEEP,+                            request+                    )         }     } }
youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.ktindex 157bbc19c7..aa4af290fc 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt@@ -13,6 +13,10 @@ fun videoURLtoID(url: String): Long {     return ByteBuffer.wrap(Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).decode(url.toUri().getQueryParameter("v")!!)).long } +fun channelURLtoID(url: String): String {+    return url.substringAfterLast("/")+}+ fun encodeVideoID(id: String): Long {     return ByteBuffer.wrap(Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).decode(id)).long }@@ -40,7 +44,7 @@ suspend fun getVideoInfo(videoId: Long): VideoInfo = coroutineScope {     VideoInfo(         ex.name,         videoId,-        ex.duration,+        ex.length,         ex.viewCount,         ex.uploadDate!!.instant.toKotlinInstant(),         ex.thumbnails.first().url,