Files
AudioManager/src/main/kotlin/win/taptap/musicmanager/Application.kt
T
TapTap 18a1d7cd19 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
2026-11-13 12:53:06 +00:00

128 lines
4.8 KiB
Kotlin

package win.taptap.musicmanager
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.autohead.AutoHeadResponse
import io.ktor.server.plugins.calllogging.CallLogging
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.plugins.partialcontent.PartialContent
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.request.path
import io.ktor.server.response.respondRedirect
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.job
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import org.slf4j.LoggerFactory
import win.taptap.musicmanager.config.AppConfig
import win.taptap.musicmanager.config.LibraryConfig
import win.taptap.musicmanager.config.UsersConfig
import win.taptap.musicmanager.db.ConfigRepository
import win.taptap.musicmanager.db.DatabaseFactory
import win.taptap.musicmanager.db.MediaRepository
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")
fun main() {
val config = AppConfig.fromEnv()
val library = LibraryConfig.load(config.libraryConfigPath).also { it.validatePaths() }
val users = UsersConfig.load(config.usersFile).also { it.validateAgainst(library) }
val db = DatabaseFactory.connect(config)
try {
ConfigRepository.sync(library, users)
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")
scanner.start(applicationScope)
}
val webUiHtml = if (config.webUiEnabled) {
AppConfig::class.java.getResource("/web/index.html")?.readText()
} else {
null
}
val server = embeddedServer(Netty, port = config.port, host = "0.0.0.0") {
install(ContentNegotiation) {
json(
Json {
ignoreUnknownKeys = true
encodeDefaults = true
explicitNulls = false
},
)
}
install(PartialContent)
install(AutoHeadResponse)
install(CallLogging)
install(StatusPages) {
exception<Throwable> { call, cause ->
log.error("Unhandled exception for ${call.request.path()}", cause)
if (call.request.path().startsWith("/rest/")) {
call.respondSubsonicError(0, "Internal server error")
} else {
call.respondText("Internal server error", status = HttpStatusCode.InternalServerError)
}
}
}
routing {
get("/health") { call.respondText("ok") }
if (webUiHtml != null) {
get("/") { call.respondRedirect("/ui") }
get("/ui") { call.respondText(webUiHtml, ContentType.Text.Html) }
}
subsonicRoutes(
users = users,
library = library,
coverArtService = coverArtService,
transcoder = transcoder,
startScan = { scanner.start(applicationScope) },
scanStatus = { scanner.status() },
)
}
}
val scopeJob = applicationScope.coroutineContext.job
Runtime.getRuntime().addShutdownHook(
Thread {
runBlocking { scopeJob.cancelAndJoin() }
runCatching { server.stop(1_000, 5_000) }
runCatching { db.close() }
},
)
log.info(
"Starting MusicManager on port {} with {} library folders and {} users",
config.port,
library.folders.size,
users.users.size,
)
server.start(wait = true)
} catch (t: Throwable) {
runCatching { db.close() }
throw t
}
}