diff --git a/app/api/song/[id]/play/route.ts b/app/api/song/[id]/play/route.ts new file mode 100644 index 0000000..351dd86 --- /dev/null +++ b/app/api/song/[id]/play/route.ts @@ -0,0 +1,117 @@ +import { api } from "@/convex/_generated/api" +import type { Id } from "@/convex/_generated/dataModel" +import { getConvexClient } from "@/lib/convex-server" +import { serveCoverFile } from "@/lib/serve-cover" +import { NextRequest, NextResponse } from "next/server" +import { spawn } from "node:child_process" +import fs from "node:fs/promises" +import * as music from "music-metadata" + +const DATA_DIR = process.env.NEXT_PUBLIC_CONVEX_URL?.includes("127.0.0.1") + ? "/Users/joshuafhiggins/Downloads/test" + : process.env.DATA || "/data" + +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") as + | boolean + | null + + 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 + } + + const file = `${DATA_DIR}/${originalCodec}/${artist.name}/${album.name}/${song.files[originalCodec]}` + if (!transcodeNeeded) { + const data = await fs.readFile(file) + const metadata = await music.parseFile(file, { skipCovers: true }) + return new NextResponse(data, { + status: 200, + headers: { + "Content-Type": `audio/${metadata.format.container || "aac"}`, + "Transfer-Encoding": "chunked", + "Cache-Control": "no-cache", + }, + }) + } + + let ffmpegArgs = ["-i", file, "-c:a", "aac", "-b:a", `${kbps}k`, "-f", "mpegts", "pipe:1"] + + try { + const ffmpegProcess = spawn("ffmpeg", ffmpegArgs) + + const stream = new ReadableStream({ + start(controller) { + ffmpegProcess.stdout.on("data", (chunk: Buffer) => { + controller.enqueue(new Uint8Array(chunk)) + }) + + ffmpegProcess.stdout.on("end", () => { + controller.close() + }) + + ffmpegProcess.stdout.on("error", (err) => { + controller.error(err) + }) + + ffmpegProcess.stderr.on("data", (data) => { + //console.error(`FFmpeg log: ${data.toString()}`) + }) + }, + cancel() { + ffmpegProcess.kill("SIGKILL") + }, + }) + + return new NextResponse(stream, { + status: 200, + headers: { + "Content-Type": "audio/mpegts", + "Transfer-Encoding": "chunked", + "Cache-Control": "no-cache", + }, + }) + } catch { + return new Response("Server Error", { status: 500 }) + } + } catch { + return new Response("Not found", { status: 404 }) + } +}