250 lines
6.0 KiB
TypeScript
250 lines
6.0 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 { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
|
|
import { NextRequest, NextResponse, userAgent } from "next/server"
|
|
import { spawn } from "node:child_process"
|
|
import fs from "node:fs/promises"
|
|
import * as music from "music-metadata"
|
|
|
|
function parseByteRange(rangeHeader: string | null, fileSize: number) {
|
|
if (!rangeHeader) {
|
|
return null
|
|
}
|
|
|
|
if (!rangeHeader.startsWith("bytes=")) {
|
|
return "invalid" as const
|
|
}
|
|
|
|
const rangeSpec = rangeHeader.slice("bytes=".length)
|
|
if (rangeSpec.includes(",")) {
|
|
return "invalid" as const
|
|
}
|
|
|
|
const [startText, endText] = rangeSpec.split("-")
|
|
if (startText === undefined || endText === undefined) {
|
|
return "invalid" as const
|
|
}
|
|
|
|
if (startText === "" && endText === "") {
|
|
return "invalid" as const
|
|
}
|
|
|
|
let start: number
|
|
let end: number
|
|
|
|
if (startText === "") {
|
|
const suffixLength = Number(endText)
|
|
if (!Number.isInteger(suffixLength) || suffixLength <= 0) {
|
|
return "invalid" as const
|
|
}
|
|
|
|
start = Math.max(fileSize - suffixLength, 0)
|
|
end = fileSize - 1
|
|
} else {
|
|
start = Number(startText)
|
|
end = endText === "" ? fileSize - 1 : Number(endText)
|
|
|
|
if (
|
|
!Number.isInteger(start) ||
|
|
!Number.isInteger(end) ||
|
|
start < 0 ||
|
|
end < start
|
|
) {
|
|
return "invalid" as const
|
|
}
|
|
}
|
|
|
|
if (start >= fileSize) {
|
|
return "invalid" as const
|
|
}
|
|
|
|
return {
|
|
start,
|
|
end: Math.min(end, fileSize - 1),
|
|
}
|
|
}
|
|
|
|
async function streamFileResponse(
|
|
request: NextRequest,
|
|
path: string,
|
|
contentType: string
|
|
) {
|
|
const { size } = await fs.stat(path)
|
|
const range = parseByteRange(request.headers.get("range"), size)
|
|
|
|
if (range === "invalid") {
|
|
return new Response(null, {
|
|
status: 416,
|
|
headers: {
|
|
"Accept-Ranges": "bytes",
|
|
"Cache-Control": "no-cache",
|
|
"Content-Range": `bytes */${size}`,
|
|
},
|
|
})
|
|
}
|
|
|
|
const headers = new Headers({
|
|
"Accept-Ranges": "bytes",
|
|
"Cache-Control": "no-cache",
|
|
"Content-Type": contentType,
|
|
})
|
|
|
|
if (range) {
|
|
headers.set("Content-Length", String(range.end - range.start + 1))
|
|
headers.set("Content-Range", `bytes ${range.start}-${range.end}/${size}`)
|
|
|
|
return new NextResponse(streamFile(path, range), {
|
|
status: 206,
|
|
headers,
|
|
})
|
|
}
|
|
|
|
headers.set("Content-Length", String(size))
|
|
|
|
return new NextResponse(streamFile(path), {
|
|
status: 200,
|
|
headers,
|
|
})
|
|
}
|
|
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params
|
|
const { browser } = userAgent(request)
|
|
|
|
try {
|
|
const song = (await getConvexClient().query(api.library.getSong, {
|
|
id: id as Id<"songs">,
|
|
}))!
|
|
|
|
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 || (kbps === 256 && "normal" in song.files)) {
|
|
originalCodec = "normal"
|
|
transcodeNeeded = false
|
|
}
|
|
|
|
const metadata = await music.parseFile(song.files[originalCodec])
|
|
|
|
if (!transcodeNeeded && originalCodec === "lossless") {
|
|
if (browser.name === "Safari" && metadata.format.codec === "ALAC") {
|
|
try {
|
|
return await streamFileResponse(
|
|
request,
|
|
song.files[originalCodec],
|
|
audioContentTypeForPath(song.files[originalCodec])
|
|
)
|
|
} catch {
|
|
return new Response("Server Error", { status: 500 })
|
|
}
|
|
}
|
|
|
|
const ffmpegArgs = [
|
|
"-nostdin",
|
|
"-i",
|
|
song.files[originalCodec],
|
|
"-f",
|
|
"flac",
|
|
"pipe:1",
|
|
]
|
|
|
|
try {
|
|
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
|
const stream = ffmpegToReadableStream(ffmpegProcess)
|
|
|
|
return new NextResponse(stream, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "audio/flac",
|
|
"Cache-Control": "no-cache",
|
|
},
|
|
})
|
|
} catch {
|
|
return new Response("Server Error", { status: 500 })
|
|
}
|
|
}
|
|
|
|
if (
|
|
!transcodeNeeded &&
|
|
(originalCodec === "atmos" || originalCodec === "normal")
|
|
) {
|
|
// TODO: Dolby Atmos doesn't work on Google Chrome
|
|
console.log(
|
|
metadata.format.codec,
|
|
metadata.format.container,
|
|
metadata.format.codecProfile
|
|
)
|
|
try {
|
|
return await streamFileResponse(
|
|
request,
|
|
song.files[originalCodec],
|
|
audioContentTypeForPath(song.files[originalCodec])
|
|
)
|
|
} catch {
|
|
return new Response("Server Error", { status: 500 })
|
|
}
|
|
}
|
|
|
|
const ffmpegArgs = [
|
|
"-nostdin",
|
|
"-i",
|
|
song.files[originalCodec],
|
|
"-c:a",
|
|
"aac",
|
|
"-b:a",
|
|
`${kbps}k`,
|
|
"-f",
|
|
"adts",
|
|
"pipe:1",
|
|
]
|
|
|
|
try {
|
|
// TODO: Fix seeking for this
|
|
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
|
const stream = ffmpegToReadableStream(ffmpegProcess)
|
|
|
|
return new NextResponse(stream, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "audio/aac",
|
|
"Cache-Control": "no-cache",
|
|
},
|
|
})
|
|
} catch {
|
|
return new Response("Server Error", { status: 500 })
|
|
}
|
|
} catch {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
}
|