package win.taptap.musicmanager.transcoding import java.nio.file.Path import java.util.concurrent.TimeUnit import org.slf4j.LoggerFactory /** * MP3-to-MP3 transcoding through ffmpeg. The source library is MP3-only for now, * so the target is always MP3 (`libmp3lame`); unsupported requested formats fall * back to MP3 as documented. */ class FfmpegTranscoder(private val ffmpegPath: String) { private val log = LoggerFactory.getLogger(FfmpegTranscoder::class.java) /** * Direct play is preferred whenever possible. We only invoke ffmpeg when the * requested bitrate is lower than the source, a time offset is requested, or * the client asked for a format we do not serve natively. */ fun shouldTranscode( sourceBitRate: Int, maxBitRate: Int?, format: String?, timeOffset: Int, ): Boolean { val target = maxBitRate?.takeIf { it > 0 } val needsBitRate = target != null && sourceBitRate > target val needsOffset = timeOffset > 0 val needsFormat = !format.isNullOrBlank() && !format.equals("mp3", ignoreCase = true) && !format.equals("raw", ignoreCase = true) return needsBitRate || needsOffset || needsFormat } /** Starts an ffmpeg process writing MP3 bytes to stdout. */ fun start(source: Path, maxBitRate: Int?, timeOffset: Int): Process { val command = buildList { add(ffmpegPath) add("-hide_banner") add("-loglevel") add("error") add("-nostdin") if (timeOffset > 0) { add("-ss") add(timeOffset.toString()) } add("-i") add(source.toString()) add("-vn") add("-map_metadata") add("-1") add("-c:a") add("libmp3lame") add("-f") add("mp3") maxBitRate?.takeIf { it > 0 }?.let { add("-b:a") add("${it.coerceIn(8, 320)}k") } add("pipe:1") } log.debug("Transcoding {} with: {}", source, command.joinToString(" ")) return ProcessBuilder(command) .redirectError(ProcessBuilder.Redirect.DISCARD) .start() } fun stop(process: Process) { runCatching { if (process.isAlive) process.destroy() if (!process.waitFor(2, TimeUnit.SECONDS)) process.destroyForcibly() } } }