- Replace mobile placeholder with Expo Router app (tabs, playback, auth, library) - Move Convex backend to @otunes/convex for web and mobile reuse - Update web app imports and API routes to use shared package
188 lines
4.3 KiB
TypeScript
188 lines
4.3 KiB
TypeScript
import type { Doc } from "@otunes/convex/_generated/dataModel"
|
|
import crypto from "node:crypto"
|
|
import fs from "node:fs/promises"
|
|
import os from "node:os"
|
|
import path from "node:path"
|
|
import { spawn } from "node:child_process"
|
|
import * as music from "music-metadata"
|
|
|
|
export const HLS_SEGMENT_SECONDS = 6
|
|
|
|
type HlsJob = {
|
|
dir: string
|
|
duration: number
|
|
segmentCount: number
|
|
startedAt: number
|
|
processExited: boolean
|
|
processExitCode: number | null
|
|
}
|
|
|
|
const jobs = new Map<string, HlsJob>()
|
|
|
|
export function qualityKbps(quality: string | null) {
|
|
if (quality === "low") {
|
|
return 64
|
|
}
|
|
|
|
if (quality === "high") {
|
|
return 256
|
|
}
|
|
|
|
return 128
|
|
}
|
|
|
|
export function selectHlsSourceCodec(
|
|
song: Doc<"songs">,
|
|
quality: string | null,
|
|
preferAtmos: boolean
|
|
) {
|
|
let sourceCodec = "lossless" in song.files ? "lossless" : "normal"
|
|
if (preferAtmos && "atmos" in song.files) {
|
|
sourceCodec = "atmos"
|
|
} else if (quality === "high" && "normal" in song.files) {
|
|
sourceCodec = "normal"
|
|
}
|
|
|
|
return sourceCodec
|
|
}
|
|
|
|
function hlsCacheRoot() {
|
|
return "/tmp/otunes"
|
|
}
|
|
|
|
async function hlsJobKey(
|
|
song: Doc<"songs">,
|
|
sourcePath: string,
|
|
kbps: number
|
|
) {
|
|
const stat = await fs.stat(sourcePath)
|
|
return crypto
|
|
.createHash("sha256")
|
|
.update(song._id)
|
|
.update("\0")
|
|
.update(sourcePath)
|
|
.update("\0")
|
|
.update(String(stat.size))
|
|
.update("\0")
|
|
.update(String(stat.mtimeMs))
|
|
.update("\0")
|
|
.update(String(kbps))
|
|
.digest("hex")
|
|
}
|
|
|
|
export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
|
|
return path.join(job.dir, `segment_${segmentIndex.toString().padStart(5, "0")}.ts`)
|
|
}
|
|
|
|
async function touchHlsJob(job: HlsJob) {
|
|
const now = new Date()
|
|
await fs.utimes(job.dir, now, now).catch(() => {})
|
|
}
|
|
|
|
export async function waitForHlsSegment(
|
|
job: HlsJob,
|
|
segmentIndex: number,
|
|
timeoutMs = 30000
|
|
) {
|
|
await touchHlsJob(job)
|
|
const segmentPath = hlsSegmentPath(job, segmentIndex)
|
|
const startedAt = Date.now()
|
|
|
|
while (Date.now() - startedAt < timeoutMs) {
|
|
try {
|
|
const firstStat = await fs.stat(segmentPath)
|
|
if (firstStat.size > 0) {
|
|
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
const secondStat = await fs.stat(segmentPath)
|
|
if (firstStat.size === secondStat.size) {
|
|
return segmentPath
|
|
}
|
|
}
|
|
} catch {
|
|
if (job.processExited && job.processExitCode !== 0) {
|
|
throw new Error(`HLS transcode failed with code ${job.processExitCode}`)
|
|
}
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
}
|
|
|
|
throw new Error("Timed out waiting for HLS segment")
|
|
}
|
|
|
|
export async function ensureHlsJob(
|
|
song: Doc<"songs">,
|
|
quality: string | null,
|
|
preferAtmos: boolean
|
|
) {
|
|
const kbps = qualityKbps(quality)
|
|
const sourceCodec = selectHlsSourceCodec(song, quality, preferAtmos)
|
|
const sourcePath = song.files[sourceCodec]
|
|
const key = await hlsJobKey(song, sourcePath, kbps)
|
|
const existingJob = jobs.get(key)
|
|
|
|
if (existingJob) {
|
|
await touchHlsJob(existingJob)
|
|
return existingJob
|
|
}
|
|
|
|
const metadata = await music.parseFile(sourcePath)
|
|
const duration = metadata.format.duration ?? song.length
|
|
const segmentCount = Math.max(1, Math.ceil(duration / HLS_SEGMENT_SECONDS))
|
|
const dir = path.join(hlsCacheRoot(), key)
|
|
await fs.mkdir(dir, { recursive: true })
|
|
|
|
const job: HlsJob = {
|
|
dir,
|
|
duration,
|
|
segmentCount,
|
|
startedAt: Date.now(),
|
|
processExited: false,
|
|
processExitCode: null,
|
|
}
|
|
jobs.set(key, job)
|
|
await touchHlsJob(job)
|
|
|
|
const ffmpegArgs = [
|
|
"-nostdin",
|
|
"-i",
|
|
sourcePath,
|
|
"-vn",
|
|
"-c:a",
|
|
"aac",
|
|
"-b:a",
|
|
`${kbps}k`,
|
|
"-ac",
|
|
"2",
|
|
"-f",
|
|
"hls",
|
|
"-hls_time",
|
|
String(HLS_SEGMENT_SECONDS),
|
|
"-hls_playlist_type",
|
|
"vod",
|
|
"-hls_list_size",
|
|
"0",
|
|
"-hls_segment_type",
|
|
"mpegts",
|
|
"-hls_segment_filename",
|
|
path.join(dir, "segment_%05d.ts"),
|
|
path.join(dir, "index.m3u8"),
|
|
]
|
|
const ffmpegProcess = spawn("ffmpeg", ffmpegArgs)
|
|
|
|
ffmpegProcess.stderr.on("data", (data) => {
|
|
console.error(`FFmpeg HLS log: ${data.toString()}`)
|
|
})
|
|
|
|
ffmpegProcess.on("close", (code) => {
|
|
job.processExited = true
|
|
job.processExitCode = code
|
|
})
|
|
|
|
ffmpegProcess.on("error", () => {
|
|
job.processExited = true
|
|
job.processExitCode = 1
|
|
})
|
|
|
|
return job
|
|
}
|