167 lines
4.2 KiB
TypeScript
167 lines
4.2 KiB
TypeScript
import { api } from "@/convex/_generated/api"
|
|
import type { Id } from "@/convex/_generated/dataModel"
|
|
import { audioContentTypeForPath } from "@/lib/audio-content-type"
|
|
import { getConvexClient } from "@/lib/convex-server"
|
|
import { NextRequest, NextResponse } from "next/server"
|
|
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
|
|
import fs from "node:fs/promises"
|
|
|
|
const DATA_DIR = process.env.NEXT_PUBLIC_CONVEX_URL?.includes("127.0.0.1")
|
|
? "/Users/joshuafhiggins/Downloads/test"
|
|
: process.env.DATA || "/data"
|
|
|
|
function ffmpegToReadableStream(ffmpegProcess: ChildProcessWithoutNullStreams) {
|
|
let closed = false
|
|
|
|
return new ReadableStream({
|
|
start(controller) {
|
|
const finalize = (err?: Error) => {
|
|
if (closed) {
|
|
return
|
|
}
|
|
closed = true
|
|
|
|
try {
|
|
if (err) {
|
|
controller.error(err)
|
|
} else {
|
|
controller.close()
|
|
}
|
|
} catch {
|
|
// Consumer may have already closed the stream (e.g. track change).
|
|
}
|
|
}
|
|
|
|
ffmpegProcess.stdout.on("data", (chunk: Buffer) => {
|
|
if (closed) {
|
|
return
|
|
}
|
|
|
|
try {
|
|
controller.enqueue(new Uint8Array(chunk))
|
|
} catch {
|
|
closed = true
|
|
ffmpegProcess.kill("SIGKILL")
|
|
}
|
|
})
|
|
|
|
ffmpegProcess.stderr.on("data", (data) => {
|
|
//console.error(`FFmpeg log: ${data.toString()}`)
|
|
})
|
|
|
|
ffmpegProcess.stdout.on("end", () => finalize())
|
|
ffmpegProcess.stdout.on("error", (err) => finalize(err))
|
|
|
|
ffmpegProcess.on("close", (code) => {
|
|
if (code !== 0 && !closed) {
|
|
finalize(new Error(`ffmpeg exited with code ${code}`))
|
|
} else {
|
|
finalize()
|
|
}
|
|
})
|
|
|
|
ffmpegProcess.on("error", (err) => finalize(err))
|
|
},
|
|
cancel() {
|
|
if (closed) {
|
|
return
|
|
}
|
|
closed = true
|
|
ffmpegProcess.kill("SIGKILL")
|
|
},
|
|
})
|
|
}
|
|
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params
|
|
try {
|
|
const song = (await getConvexClient().query(api.library.getSong, {
|
|
id: id as Id<"songs">,
|
|
}))!
|
|
const album = (await getConvexClient().query(api.library.getAlbum, {
|
|
id: song.album,
|
|
}))!
|
|
const artist = (await getConvexClient().query(api.library.getArtist, {
|
|
id: song.albumArtist,
|
|
}))!
|
|
|
|
const quality = request.nextUrl.searchParams.get("quality") as
|
|
| "low"
|
|
| "medium"
|
|
| "high"
|
|
| "lossless"
|
|
| null
|
|
|
|
const preferAtmos =
|
|
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
|
|
|
let kbps = 0
|
|
if (quality === "low") {
|
|
kbps = 64
|
|
} else if (quality === "medium") {
|
|
kbps = 128
|
|
} else if (quality === "high") {
|
|
kbps = 256
|
|
}
|
|
|
|
let originalCodec = "lossless" in song.files ? "lossless" : "normal"
|
|
|
|
let transcodeNeeded = true
|
|
if (preferAtmos && "atmos" in song.files) {
|
|
originalCodec = "atmos"
|
|
transcodeNeeded = false
|
|
} else if (kbps === 0 && "lossless" in song.files) {
|
|
originalCodec = "lossless"
|
|
transcodeNeeded = false
|
|
} else if (kbps === 0) {
|
|
transcodeNeeded = false
|
|
}
|
|
|
|
const file = `${DATA_DIR}/${originalCodec}/${artist.name}/${album.name}/${song.files[originalCodec]}`
|
|
if (!transcodeNeeded) {
|
|
const data = await fs.readFile(file)
|
|
return new NextResponse(data, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": audioContentTypeForPath(file),
|
|
"Cache-Control": "no-cache",
|
|
},
|
|
})
|
|
}
|
|
|
|
const ffmpegArgs = [
|
|
"-nostdin",
|
|
"-i",
|
|
file,
|
|
"-c:a",
|
|
`${quality === "low" ? "libfdk_aac" : "aac"}`,
|
|
"-b:a",
|
|
`${kbps}k`,
|
|
"-f",
|
|
"adts",
|
|
"pipe:1",
|
|
]
|
|
|
|
try {
|
|
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
|
const stream = ffmpegToReadableStream(ffmpegProcess)
|
|
|
|
return new NextResponse(stream, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "audio/aac",
|
|
"Transfer-Encoding": "chunked",
|
|
"Cache-Control": "no-cache",
|
|
},
|
|
})
|
|
} catch {
|
|
return new Response("Server Error", { status: 500 })
|
|
}
|
|
} catch {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
}
|