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

72 lines
2.0 KiB
TypeScript

import { createHash } from "node:crypto"
import fs from "node:fs/promises"
import path from "node:path"
import {
CACHE_ORPHAN_PREFIX,
cacheDir,
pinCacheEntry,
pruneCache,
touchCacheEntry,
unpinCacheEntry,
} from "@/lib/server-cache"
import { spawnFfmpeg } from "@/lib/server-ffmpeg"
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 = cacheDir("lossless")
await fs.mkdir(dir, { recursive: true })
const output = path.join(dir, `${key}.flac`)
try {
// Every range request touches the file so it stays cached while playing.
await touchCacheEntry(output)
return output
} catch {
// Publish only completed conversions so range requests always see a complete file.
}
const temporaryDir = await fs.mkdtemp(path.join(dir, CACHE_ORPHAN_PREFIX))
const temporary = path.join(temporaryDir, "audio.flac")
pinCacheEntry(temporaryDir)
try {
const ffmpeg = await spawnFfmpeg([
"-i",
source,
"-map",
"0:a:0",
"-c:a",
"flac",
temporary,
])
const code = await ffmpeg.exited
if (code !== 0) {
throw new Error(`Lossless conversion failed: ${code}: ${ffmpeg.stderrTail()}`)
}
await fs.rename(temporary, output)
} finally {
unpinCacheEntry(temporaryDir)
await fs.rm(temporaryDir, { recursive: true, force: true })
}
void pruneCache()
return output
}