package win.taptap.musicmanager.download import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.TimeUnit import kotlin.concurrent.thread /** * Downloads a single YouTube video as an MP3 with embedded metadata, so the * scanner can derive artist and title from the file itself. */ class YtDlpDownloader( private val executable: String, private val timeoutSeconds: Long = 600, ) : AudioDownloader { override fun download(videoId: String, title: String, artist: String, targetDir: Path): Path { Files.createDirectories(targetDir) val process = ProcessBuilder( executable, "-x", "--audio-format", "mp3", "--audio-quality", "0", "--embed-metadata", "--embed-thumbnail", "--convert-thumbnails", "jpg", "--no-playlist", "--no-cache-dir", "--no-progress", "--print", "after_move:filepath", "-o", targetDir.resolve("%(id)s.%(ext)s").toString(), "https://www.youtube.com/watch?v=$videoId", ) .redirectErrorStream(true) .start() val output = StringBuilder() val reader = thread(isDaemon = true, name = "yt-dlp-download") { process.inputStream.bufferedReader().useLines { lines -> lines.forEach { output.appendLine(it) } } } if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) { process.destroyForcibly() reader.join(2_000) throw IllegalStateException("yt-dlp download timed out after ${timeoutSeconds}s") } reader.join(2_000) if (process.exitValue() != 0) { throw IllegalStateException( "yt-dlp exited with ${process.exitValue()}: ${output.toString().take(400).trim()}", ) } val printed = output.lines() .map { it.trim() } .lastOrNull { it.endsWith(".mp3", ignoreCase = true) } val file = printed?.let { Path.of(it) } ?: targetDir.resolve("$videoId.mp3") if (!Files.isRegularFile(file)) { throw IllegalStateException("yt-dlp did not produce an MP3 file") } return file } }