feat: transcode streams with ffmpeg
- FfmpegTranscoder with maxBitRate, format fallback to MP3 and timeOffset - direct play when no transcode is required, preserving HTTP Range support - transcoded responses are chunked audio/mpeg with process cleanup - unit tests for policy and real ffmpeg output - smoke test covers maxBitRate, timeOffset and format fallback
This commit is contained in:
1 parent
722f486c3a
commit
18a1d7cd19
9 files changed
+254
-4
No files matched your search
@@ -34,6 +34,7 @@ import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.MediaScanner
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
import win.taptap.musicmanager.subsonic.routes.subsonicRoutes
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.Application")
|
||||
|
||||
@@ -49,6 +50,7 @@ fun main() {
|
||||
|
||||
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
val coverArtService = CoverArtService(config.dataDir)
|
||||
val transcoder = FfmpegTranscoder(config.ffmpegPath)
|
||||
val scanner = MediaScanner(library, coverArtService)
|
||||
if (MediaRepository.countSongs() == 0L) {
|
||||
log.info("Song table is empty, starting initial library scan")
|
||||
@@ -95,6 +97,7 @@ fun main() {
|
||||
users = users,
|
||||
library = library,
|
||||
coverArtService = coverArtService,
|
||||
transcoder = transcoder,
|
||||
startScan = { scanner.start(applicationScope) },
|
||||
scanStatus = { scanner.status() },
|
||||
)
|
||||
|
||||
@@ -1,30 +1,56 @@
|
||||
package win.taptap.musicmanager.subsonic.routes
|
||||
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.response.respondFile
|
||||
import io.ktor.server.response.respondOutputStream
|
||||
import io.ktor.server.routing.Route
|
||||
import java.net.URLEncoder
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.slf4j.LoggerFactory
|
||||
import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.db.LibraryRepository
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.subsonic.respondSubsonicError
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
private val log = LoggerFactory.getLogger("win.taptap.musicmanager.MediaRoutes")
|
||||
|
||||
fun Route.mediaRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
transcoder: FfmpegTranscoder,
|
||||
) {
|
||||
|
||||
subsonicEndpoint(users, "/stream") { call, user ->
|
||||
val id = call.subsonicParams()["id"]
|
||||
val parameters = call.subsonicParams()
|
||||
val id = parameters["id"]
|
||||
if (id.isNullOrBlank()) {
|
||||
call.respondSubsonicError(10, "Required parameter is missing: id")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val rawMaxBitRate = parameters["maxBitRate"]
|
||||
val maxBitRate = rawMaxBitRate?.toIntOrNull()
|
||||
if (rawMaxBitRate != null && (maxBitRate == null || maxBitRate < 0)) {
|
||||
call.respondSubsonicError(10, "Invalid maxBitRate")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val rawTimeOffset = parameters["timeOffset"]
|
||||
val timeOffset = rawTimeOffset?.toIntOrNull()
|
||||
if (rawTimeOffset != null && (timeOffset == null || timeOffset < 0)) {
|
||||
call.respondSubsonicError(10, "Invalid timeOffset")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
val offset = timeOffset ?: 0
|
||||
val format = parameters["format"]
|
||||
|
||||
val resolved = LibraryRepository.resolveSong(
|
||||
id,
|
||||
user.visibleFolderIds(library),
|
||||
@@ -36,7 +62,30 @@ fun Route.mediaRoutes(
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
call.respondFile(resolved.file.toFile())
|
||||
if (!transcoder.shouldTranscode(resolved.song.bitRate, maxBitRate, format, offset)) {
|
||||
call.respondFile(resolved.file.toFile())
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
val process = try {
|
||||
transcoder.start(resolved.file, maxBitRate, offset)
|
||||
} catch (e: Exception) {
|
||||
log.error("Failed to start ffmpeg for {}", resolved.file, e)
|
||||
call.respondSubsonicError(0, "Transcoding failed")
|
||||
return@subsonicEndpoint
|
||||
}
|
||||
|
||||
try {
|
||||
call.response.headers.append(HttpHeaders.CacheControl, "no-store")
|
||||
call.respondOutputStream(ContentType.parse("audio/mpeg")) {
|
||||
val output = this
|
||||
withContext(Dispatchers.IO) {
|
||||
process.inputStream.use { input -> input.copyTo(output) }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
transcoder.stop(process)
|
||||
}
|
||||
}
|
||||
|
||||
subsonicEndpoint(users, "/download") { call, user ->
|
||||
|
||||
@@ -6,19 +6,21 @@ import win.taptap.musicmanager.config.LibraryConfig
|
||||
import win.taptap.musicmanager.config.UsersConfig
|
||||
import win.taptap.musicmanager.scanner.CoverArtService
|
||||
import win.taptap.musicmanager.scanner.ScanStatus
|
||||
import win.taptap.musicmanager.transcoding.FfmpegTranscoder
|
||||
|
||||
/** Authenticated `/rest` subtree. */
|
||||
fun Route.subsonicRoutes(
|
||||
users: UsersConfig,
|
||||
library: LibraryConfig,
|
||||
coverArtService: CoverArtService,
|
||||
transcoder: FfmpegTranscoder,
|
||||
startScan: () -> Boolean,
|
||||
scanStatus: () -> ScanStatus,
|
||||
) {
|
||||
route("/rest") {
|
||||
systemRoutes(users, library, startScan, scanStatus)
|
||||
browsingRoutes(users, library)
|
||||
mediaRoutes(users, library, coverArtService)
|
||||
mediaRoutes(users, library, coverArtService, transcoder)
|
||||
interactionRoutes(users, library)
|
||||
playlistRoutes(users, library)
|
||||
playQueueRoutes(users, library)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user