Files
otunes/apps/web/lib/server-lossless.ts
T

83 lines
2.3 KiB
TypeScript

import { spawn } from "node:child_process"
import { createHash } from "node:crypto"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
const conversions = new Map<string, Promise<string>>()
// A completed FLAC file has a duration and supports byte ranges. Piped FLAC does not.
export async function seekableLosslessFile(source: string): Promise<string> {
if (path.extname(source).toLowerCase() === ".flac") return source
const stat = await fs.stat(source)
const key = createHash("sha256")
.update(`${source}:${stat.size}:${stat.mtimeMs}`)
.digest("hex")
const existing = conversions.get(key)
if (existing) return existing
const conversion = convert(source, key)
conversions.set(key, conversion)
try {
return await conversion
} finally {
conversions.delete(key)
}
}
async function convert(source: string, key: string): Promise<string> {
const dir = path.join(os.tmpdir(), "otunes-lossless")
await fs.mkdir(dir, { recursive: true })
const cutoff = Date.now() - 30 * 60 * 1000
await Promise.all(
(await fs.readdir(dir))
.filter((name) => name.endsWith(".flac"))
.map(async (name) => {
const file = path.join(dir, name)
const stat = await fs.stat(file).catch(() => null)
if (stat && stat.mtimeMs < cutoff) await fs.rm(file, { force: true })
})
)
const output = path.join(dir, `${key}.flac`)
try {
await fs.access(output)
return output
} catch {
// Publish only completed conversions so range requests always see a complete file.
}
const temporary = path.join(
await fs.mkdtemp(path.join(dir, "convert-")),
"audio.flac"
)
try {
await new Promise<void>((resolve, reject) => {
const child = spawn(
"ffmpeg",
[
"-nostdin",
"-v",
"error",
"-i",
source,
"-map",
"0:a:0",
"-c:a",
"flac",
temporary,
],
{ stdio: "ignore" }
)
child.on("error", reject)
child.on("close", (code) => {
if (code === 0) resolve()
else reject(new Error(`Lossless conversion failed: ${code}`))
})
})
await fs.rename(temporary, output)
return output
} finally {
await fs.rm(path.dirname(temporary), { recursive: true, force: true })
}
}