59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
import { api } from "@/convex/_generated/api"
|
|
import type { Id } from "@/convex/_generated/dataModel"
|
|
import { getConvexClient } from "@/lib/convex-server"
|
|
import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls"
|
|
import { NextRequest } from "next/server"
|
|
|
|
function hlsSegmentUrl(request: NextRequest, index: number) {
|
|
const url = new URL(request.url)
|
|
url.pathname = `${url.pathname.replace(/\/$/, "")}/segment/${index}.ts`
|
|
return `${url.pathname}${url.search}`
|
|
}
|
|
|
|
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 quality = request.nextUrl.searchParams.get("quality")
|
|
const preferAtmos =
|
|
request.nextUrl.searchParams.get("preferAtmos") === "true"
|
|
const job = await ensureHlsJob(song, quality, preferAtmos)
|
|
const { duration, segmentCount } = job
|
|
const targetDuration = Math.ceil(HLS_SEGMENT_SECONDS)
|
|
|
|
const lines = [
|
|
"#EXTM3U",
|
|
"#EXT-X-VERSION:3",
|
|
`#EXT-X-TARGETDURATION:${targetDuration}`,
|
|
"#EXT-X-MEDIA-SEQUENCE:0",
|
|
"#EXT-X-PLAYLIST-TYPE:VOD",
|
|
]
|
|
|
|
for (let index = 0; index < segmentCount; index += 1) {
|
|
const start = index * HLS_SEGMENT_SECONDS
|
|
const segmentDuration = Math.min(HLS_SEGMENT_SECONDS, duration - start)
|
|
lines.push(`#EXTINF:${segmentDuration.toFixed(3)},`)
|
|
lines.push(hlsSegmentUrl(request, index))
|
|
}
|
|
|
|
lines.push("#EXT-X-ENDLIST")
|
|
|
|
return new Response(`${lines.join("\n")}\n`, {
|
|
status: 200,
|
|
headers: {
|
|
"Cache-Control": "no-cache",
|
|
"Content-Type": "application/vnd.apple.mpegurl",
|
|
},
|
|
})
|
|
} catch {
|
|
return new Response("Not found", { status: 404 })
|
|
}
|
|
}
|