Download Service and Task Execution
Overview
This flow turns a URL, playlist item, or custom command into an actual yt-dlp process and keeps the Android foreground service, notifications, UI state, media library, and download history in sync. There are two execution paths in the covered files:
- The legacy singleton path in app/…/Downloader.kt, which exposes UI-facing state flows (
downloaderState,taskState,playlistResult,errorState,processCount) and directly starts work from methods such asaddToDownloadQueue,getInfoAndDownload,downloadVideoWithInfo,downloadVideoInPlaylistByIndexList, andexecuteCommandWithUrl. - The queued task path in app/…/DownloaderV2.kt, which owns a
SnapshotStateMap<Task, Task.State>, restores unfinished tasks fromPreferenceUtil.decodeTaskListBackup, persists non-completed tasks throughPreferenceUtil.encodeTaskListBackup, and runs up to three fetching/downloading tasks at a time.
Both paths call into app/…/DownloadUtil.kt for command construction and process execution. DownloadUtil.fetchVideoInfoFromUrl builds a metadata request around YoutubeDLRequest, applying preference-derived options for output naming, extractor/audio mode, format sorting, cookies, proxy, IPv4, subtitles, playlist item selection, retry count, no-playlist behavior, and socket timeout before decoding the response as VideoInfo. DownloadUtil.getPlaylistOrVideoInfo is the playlist/video probe path: it uses --flat-playlist and --dump-single-json, then decodes either PlaylistResult or VideoInfo.
In the legacy path, Downloader.addToDownloadQueue either starts immediately or waits until downloaderState returns to Idle. getInfoAndDownload fetches VideoInfo first, then downloadVideo; downloadVideoWithInfo skips the fetch when the UI already has VideoInfo; downloadVideoInPlaylistByIndexList loops through selected playlist indices, fetches each selected entry with --playlist-items, updates the service notification with the current item count, and calls the same private downloadVideo helper for each item. That helper derives the UI task id from videoInfo.id + preferences.hashCode(), posts progress notifications through NotificationUtil.notifyProgress, forwards progress text into mutableTaskState, and on success uses FileUtil.createIntentForOpeningFile to make the completion notification open the first returned file.
In the queued path, app/…/Task.kt is the durable task model. Task.TypeInfo routes a task as a plain URL, playlist item, or custom command; the task id is url + type id + preferences.hashCode(). Task.DownloadState controls scheduling: Idle tasks fetch info, ReadyWithInfo tasks download, Running and FetchingInfo are cancelable, and Canceled/Error carry a restart action so DownloaderV2.restart can return them to Idle or ReadyWithInfo. app/…/TaskFactory.kt builds ready tasks from custom format selection (createWithConfigurations) or playlist entries (createWithPlaylistResult), including format ids, clips, subtitles, title overrides, playlist indices, and display-only ViewState fields.
DownloaderV2Impl drives queued execution from a snapshotFlow over the task map. Each state change calls doYourWork, which refuses to start more work when three tasks are already FetchingInfo or Running, sorts by DownloadState, then promotes one Idle task through fetchInfo or one ReadyWithInfo task through download. fetchInfo calls DownloadUtil.fetchVideoInfoFromUrl with the task id as yt-dlp process id and a playlist index when Task.TypeInfo.Playlist is present. download calls DownloadUtil.downloadVideo, updates Running progress as a 0.0-1.0 float while notifications receive integer percentages, marks success as Completed(pathList.firstOrNull()), and posts a completion notification with an open-file pending intent when possible. Custom command tasks are routed by prepare/download to execute, which calls DownloadUtil.executeCustomCommandTask instead of the normal media download path.
DownloadUtil.downloadVideo is where the actual download command is assembled. It chooses the source URL from an explicit playlist URL or VideoInfo.originalUrl/webpageUrl, then adds global options such as --no-mtime, cookies, restricted filenames, proxy, IPv4, verbose logging, download archive, rate limiting, playlist selection, aria2c or fragment concurrency, SponsorBlock, thumbnails, clip sections, title replacement, split chapters, and output templates. Path routing happens here:
- Audio extraction or audio-only videos use
App.audioDownloadDir, unlessprivateDirectoryroutes toApp.privateDownloadDir. - Video downloads use
App.videoDownloadDir, unlessprivateDirectoryroutes toApp.privateDownloadDir. subdirectoryExtractorappends the extractor key under the chosen audio/video/private directory.sdcardchanges yt-dlp's-Poutput toFileUtil.getSdcardTempDir(videoInfo.id)and later moves files into the user-selected SAF tree withFileUtil.moveFilesToSdcard.- On Android versions above 23 and non-SD-card downloads, a separate
-P temp:<external tmp>path is added viaFileUtil.getExternalTempDir. - Playlist-title subdirectories are represented in the output template prefix when
downloadPlaylist,playlistItem != 0, andsubdirectoryPlaylistTitleare enabled.
After yt-dlp returns, DownloadUtil.onFinishDownloading reconciles files and state. SD-card downloads are copied from the temp directory into the tree URI and the temp directory is deleted. Local downloads are discovered by FileUtil.scanFileToMediaLibraryPostDownload, which walks the selected download directory, scans matching paths into Android's media library, and removes thumbnail/subtitle sidecar files from the returned list. Non-private downloads insert rows into the history database via DatabaseUtil.insertInfo; split-by-chapter downloads use the resulting filename as the history title. Private-mode downloads deliberately return an empty file list, which causes completion notifications to say only that the task completed and not expose an open-file intent.
Custom commands share the same notification/cancel infrastructure but use config files instead of built-in option assembly. DownloadUtil.executeCustomCommandTask and executeCommandInBackground split the provided URL string on whitespace/newlines, apply command-directory, newline, aria2c, download archive, restricted filenames, cookies, and write the CommandTemplate.template content into a cache config file passed with --config-locations. The legacy command runner also updates Downloader.mutableTaskList, increments/decrements processCount, writes line-by-line output, and scans the command directory into the media library when the command completes.
app/…/DownloadService.kt is intentionally thin: binding it creates a foreground notification from NotificationUtil.makeServiceNotification, and unbinding stops foreground mode and self-stops the service. Service lifetime is not driven by the service itself. In the legacy path, Downloader combines downloaderState, processCount, and quick download count to call App.startService() while work exists and App.stopService() when it does not. In the queued path, DownloaderV2Impl counts tasks in Running or FetchingInfo and starts/stops the same service when that count changes.
Notifications and actions are centralized in app/…/NotificationUtil.kt and app/…/NotificationActionReceiver.kt. NotificationUtil.notifyProgress and makeNotificationForCustomCommand attach a cancel broadcast when they have a task id; finishNotification replaces progress notifications with auto-cancel completion notifications; notifyError attaches a copy-error-report broadcast. NotificationActionReceiver dispatches cancel actions first to DownloaderV2.cancel(taskId) and, if no queued task matches, falls back to YoutubeDL.destroyProcessById(taskId) plus Downloader.onProcessCanceled for legacy/custom-command processes. Error-report actions copy the report to the app clipboard, toast success, and cancel the notification.
app/…/FileUtil.kt owns post-download file operations: it creates view/share intents from either SAF document URIs or FileProvider file paths, scans local files into MediaScannerConnection, copies SD-card temp output into SAF destinations, creates cache files for yt-dlp configs/cookies/archive, and resolves the app's public Download/Seal and private Download/.Seal directories. app/…/TextUtil.kt supports this flow with URL extraction from clipboard/shared text, HTTPS thumbnail normalization, numeric range checks for rate limits, delimiter joining for format sorters, toast helpers, and error report text.
Coupling
- If task id construction changes in app/…/Task.kt or app/…/Downloader.kt, also verify cancellation in app/…/NotificationActionReceiver.kt and notification ids in app/…/NotificationUtil.kt; cancel broadcasts depend on the task id matching the yt-dlp process id passed to
YoutubeDL.execute/destroyProcessById. - If a new
Task.DownloadStateis added in app/…/Task.kt, updateDownloaderV2Impl.doYourWork,countRunning,enqueueFromBackup,cancelImpl, andrestartImplin app/…/DownloaderV2.kt; scheduling, service lifetime, persistence restore, cancellation, and restart all switch on the sealed states separately. - If download preferences or output template behavior change in app/…/DownloadUtil.kt, verify both
TaskFactory.createWithConfigurationsin app/…/TaskFactory.kt and legacy task ids in app/…/Downloader.kt; both useDownloadPreferences.hashCode()as part of task identity, so preference fields influence duplicate detection, process ids, and notifications. - If notification extras change in app/…/NotificationUtil.kt, update app/…/NotificationActionReceiver.kt at the same time; the receiver reads
ACTION_KEY,TASK_ID_KEY,NOTIFICATION_ID_KEY, andERROR_REPORT_KEYdirectly from notification intents. - If path routing changes in
DownloadUtil.downloadVideo, verifyFileUtil.scanFileToMediaLibraryPostDownloadandFileUtil.moveFilesToSdcardin app/…/FileUtil.kt; local downloads are rediscovered by walking the selected directory for the expected title, while SD-card downloads only return URIs created during the temp-directory copy. - If private-mode behavior changes in app/…/DownloadUtil.kt, verify completion notification creation in both app/…/Downloader.kt and app/…/DownloaderV2.kt; private-mode currently returns an empty path list so those callers avoid exposing an open-file action.
Risks
- app/…/DownloadUtil.kt uses
DownloadPreferences.hashCode()in task ids through app/…/Downloader.kt and app/…/Task.kt. Adding or reordering serialized preference fields can change ids for otherwise identical user-visible tasks, which can break cancellation/restart matching for restored queued tasks and create different notification ids. - app/…/DownloadUtil.kt adds
-Pmore than once for some local downloads: first for the destination directory and later fortemp:on Android versions above 23. If yt-dlp option precedence changes or another-Pis added, files may be written somewhere that app/…/FileUtil.kt does not scan, causing completion notifications and download history to miss the output. - app/…/DownloaderV2.kt reports normal download failures with
R.string.fetch_info_error_msgin thedownloadfailure branch, while legacy app/…/Downloader.kt distinguishes fetch and download failures. If UI or support workflows key off that message, a download-phase failure in the queued path can be misclassified as a metadata-fetch problem.