commit
AAA
diff --git a/Dockerfile b/Dockerfile
index bf8f106..80773d3 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,6 +1,12 @@
FROM oven/bun:1 AS base
WORKDIR /app
+# ffmpeg powers the background Opus transcode (lib/media.ts). Without it the
+# app still runs — transcoding just no-ops and /stream serves the master.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ffmpeg \
+ && rm -rf /var/lib/apt/lists/*
+
COPY . .
RUN bun install
diff --git a/apps/server/package.json b/apps/server/package.json
index 6a5117a..5c18f81 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -7,6 +7,7 @@
"dev": "bun run --hot src/server.ts",
"start": "NODE_ENV=production bun run src/server.ts",
"migrate": "bun run src/db/migrate.ts",
+ "backfill:opus": "bun run src/db/backfill-opus.ts",
"typecheck": "tsc --noEmit"
},
"dependencies": {
diff --git a/apps/server/src/auth/session.ts b/apps/server/src/auth/session.ts
index ce41812..0cbd9cc 100644
--- a/apps/server/src/auth/session.ts
+++ b/apps/server/src/auth/session.ts
@@ -49,16 +49,28 @@ export async function createSession(userId: string): Promise<string> {
return id;
}
-// Returns the userId, refreshing the TTL (sliding expiry). Fails open to null.
+// Returns the userId, refreshing the TTL (sliding expiry).
+//
+// The lookup that matters is the GET. The EXPIRE that renews the sliding
+// window is deliberately fire-and-forget: previously it was awaited inside
+// the same try/catch, so a single transient Redis hiccup on the *refresh*
+// would throw and make a perfectly valid session read as null — i.e. the user
+// got logged out mid-playback (every stream range request hits this) for no
+// reason. Now a failed renewal can't invalidate a session we already resolved.
export async function readSession(id: string): Promise<string | null> {
+ let userId: string | null;
try {
- const userId = await redis.get(sessKey(id));
- if (!userId) return null;
- await redis.expire(sessKey(id), SESSION_TTL_SEC);
- return userId;
+ userId = await redis.get(sessKey(id));
} catch {
+ // A genuine Redis read failure — we can't confirm the session right now.
+ // ioredis retries the command internally; the next request will try again.
return null;
}
+ if (!userId) return null;
+
+ // Best-effort renewal: never let its failure affect the resolved session.
+ redis.expire(sessKey(id), SESSION_TTL_SEC).catch(() => {});
+ return userId;
}
export async function destroySession(id: string): Promise<void> {
diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts
index b787e5c..38870ad 100644
--- a/apps/server/src/config.ts
+++ b/apps/server/src/config.ts
@@ -92,6 +92,16 @@ export const config = {
mediaDir: optional("MUSIC_MEDIA_DIR", "./data/media"),
maxUploadBytes: Number(optional("MUSIC_MAX_UPLOAD_MB", "200")) * 1024 * 1024,
+ // On upload, lossless masters (FLAC/WAV/AIFF) get a small Ogg-Opus copy
+ // transcoded in the background (needs ffmpeg on PATH — it's in the Docker
+ // image). The master is always kept; /stream just prefers the Opus when it
+ // exists, so mobile isn't pulling full FLACs. Set MUSIC_OPUS_TRANSCODE=false
+ // to disable and always stream the master. Bitrate is Opus VBR target.
+ opus: {
+ enabled: optional("MUSIC_OPUS_TRANSCODE", "true") !== "false",
+ bitrate: optional("MUSIC_OPUS_BITRATE", "128k"),
+ },
+
// Offload audio/cover byte-serving to nginx via X-Accel-Redirect. When set
// (e.g. "/_media"), /stream and /cover just authenticate then hand the file
// to nginx by internal-redirect, so the app never streams the bytes and
diff --git a/apps/server/src/db/backfill-opus.ts b/apps/server/src/db/backfill-opus.ts
new file mode 100644
index 0000000..33f0a64
--- /dev/null
+++ b/apps/server/src/db/backfill-opus.ts
@@ -0,0 +1,43 @@
+// One-off backfill: transcode existing lossless masters to Ogg-Opus and set
+// songs.stream_path, so tracks uploaded before Opus streaming existed get the
+// smaller mobile stream too. Safe to re-run — it only touches rows that don't
+// have a stream_path yet, and skips masters that aren't lossless.
+//
+// Run it once after deploying (ffmpeg must be on PATH):
+// bun run --filter @musicapp/server backfill:opus
+// or from apps/server:
+// bun run src/db/backfill-opus.ts
+
+import { sql, type Song } from "./index.ts";
+import { isLosslessMaster, transcodeToOpus } from "../lib/media.ts";
+
+const songs = await sql<Song[]>`
+ SELECT * FROM songs WHERE stream_path IS NULL ORDER BY created_at ASC
+`;
+
+const targets = songs.filter((s) => isLosslessMaster(s.file_path));
+console.log(
+ `${songs.length} songs without a stream copy; ${targets.length} are lossless masters to transcode.`,
+);
+
+let done = 0;
+let failed = 0;
+
+for (const song of targets) {
+ const label = `${song.artist} — ${song.title}`;
+ process.stdout.write(`[${done + failed + 1}/${targets.length}] ${label} … `);
+
+ const streamPath = await transcodeToOpus(song.file_path).catch(() => null);
+ if (!streamPath) {
+ failed++;
+ console.log("skipped (transcode failed)");
+ continue;
+ }
+
+ await sql`UPDATE songs SET stream_path = ${streamPath} WHERE id = ${song.id}`;
+ done++;
+ console.log("done");
+}
+
+console.log(`\nBackfill complete: ${done} transcoded, ${failed} failed.`);
+await sql.end();
diff --git a/apps/server/src/db/index.ts b/apps/server/src/db/index.ts
index 688ca64..e444806 100644
--- a/apps/server/src/db/index.ts
+++ b/apps/server/src/db/index.ts
@@ -28,7 +28,8 @@ export type Song = {
artist: string;
album: string | null;
cover_path: string | null;
- file_path: string;
+ file_path: string; // the uploaded master (e.g. FLAC)
+ stream_path: string | null; // optional transcoded Ogg-Opus copy for streaming
mime: string | null;
duration_s: number | null;
size_bytes: string; // bigint comes back as string
diff --git a/apps/server/src/db/schema.sql b/apps/server/src/db/schema.sql
index e48f3db..7e98ae8 100644
--- a/apps/server/src/db/schema.sql
+++ b/apps/server/src/db/schema.sql
@@ -40,6 +40,13 @@ CREATE TABLE IF NOT EXISTS songs (
-- Added after initial release; safe on existing databases.
ALTER TABLE songs ADD COLUMN IF NOT EXISTS explicit boolean NOT NULL DEFAULT false;
+-- Optional transcoded stream (Ogg-Opus) generated from the uploaded master.
+-- file_path stays the lossless/original master; stream_path, when set, is a
+-- small Opus copy the /stream endpoint prefers so mobile isn't pulling full
+-- FLACs. NULL means "no transcode yet" -> fall back to streaming the master.
+-- See lib/media.ts (transcodeToOpus) and routes/songs.ts.
+ALTER TABLE songs ADD COLUMN IF NOT EXISTS stream_path text;
+
-- Used by duplicate detection (src/lib/duplicates.ts). New rows get a
-- properly normalised value from the app; this backfill is a coarser
-- approximation for rows that predate the column, just so nothing is NULL.
diff --git a/apps/server/src/lib/media.ts b/apps/server/src/lib/media.ts
index 8dd7863..f0a44e8 100644
--- a/apps/server/src/lib/media.ts
+++ b/apps/server/src/lib/media.ts
@@ -3,6 +3,7 @@
import {
mkdir,
writeFile,
+ rm,
} from "node:fs/promises";
import {
join,
@@ -28,10 +29,22 @@ const AUDIO_MIME: Record<string, string> = {
".wav": "audio/wav",
".ogg": "audio/ogg",
".oga": "audio/ogg",
- ".opus": "audio/opus",
+ // Our transcodes (and typical .opus files) are Opus-in-Ogg. "audio/ogg" is
+ // the container type browsers reliably accept for that; "audio/opus" is not
+ // a registered file type and some players refuse it.
+ ".opus": "audio/ogg",
".weba": "audio/webm",
};
+// Uploaded formats worth transcoding to Opus: the big lossless ones. Already-
+// compressed uploads (mp3/aac/m4a/ogg/opus) are left as-is — re-encoding them
+// would just lose quality for little size win.
+const LOSSLESS_EXTS = new Set([".flac", ".wav", ".aif", ".aiff"]);
+
+export function isLosslessMaster(relPath: string): boolean {
+ return LOSSLESS_EXTS.has(extname(relPath).toLowerCase());
+}
+
const IMAGE_MIME: Record<string, string> = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
@@ -126,6 +139,65 @@ export async function saveAudio(
return rel;
}
+// Transcode a stored master to Ogg-Opus and persist it alongside. Returns the
+// relative path of the new .opus file, or null if transcoding is disabled or
+// ffmpeg failed (caller then just keeps streaming the master).
+//
+// -vn drops any embedded cover art (we serve covers separately, and art in an
+// Opus stream trips up some players). libopus with VBR at the configured
+// bitrate is transparent for music at 128k+ while being ~5-10x smaller than a
+// FLAC.
+export async function transcodeToOpus(
+ masterRelPath: string,
+): Promise<string | null> {
+ if (!config.opus.enabled) return null;
+
+ const inAbs = resolveMedia(masterRelPath);
+ const outRel = join("audio", `${randomName()}.opus`);
+ const outAbs = resolveMedia(outRel);
+
+ try {
+ const proc = Bun.spawn(
+ [
+ "ffmpeg",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ "-i",
+ inAbs,
+ "-vn",
+ "-c:a",
+ "libopus",
+ "-b:a",
+ config.opus.bitrate,
+ "-vbr",
+ "on",
+ "-application",
+ "audio",
+ "-f",
+ "opus",
+ outAbs,
+ ],
+ { stdout: "ignore", stderr: "pipe" },
+ );
+
+ const exit = await proc.exited;
+ if (exit !== 0) {
+ const err = await new Response(proc.stderr).text();
+ console.error(`ffmpeg transcode failed (exit ${exit}): ${err.trim()}`);
+ await rm(outAbs, { force: true }).catch(() => {});
+ return null;
+ }
+ return outRel;
+ } catch (err) {
+ // ffmpeg missing from PATH, spawn failure, etc. — never fatal.
+ console.error("transcodeToOpus error:", err);
+ await rm(outAbs, { force: true }).catch(() => {});
+ return null;
+ }
+}
+
// Persist a cover image. Returns the relative path stored in the DB.
export async function saveCover(
bytes: Uint8Array,
diff --git a/apps/server/src/routes/duplicates.ts b/apps/server/src/routes/duplicates.ts
index cac303a..67f69d8 100644
--- a/apps/server/src/routes/duplicates.ts
+++ b/apps/server/src/routes/duplicates.ts
@@ -80,6 +80,9 @@ duplicateRoutes.post("/:id/duplicate", async (c) => {
if (song) {
await sql`DELETE FROM songs WHERE id = ${song.id}`;
await unlink(resolveMedia(song.file_path)).catch(() => {});
+ if (song.stream_path) {
+ await unlink(resolveMedia(song.stream_path)).catch(() => {});
+ }
if (song.cover_path) {
await unlink(resolveMedia(song.cover_path)).catch(() => {});
}
diff --git a/apps/server/src/routes/songs.ts b/apps/server/src/routes/songs.ts
index dd196f6..8e66b28 100644
--- a/apps/server/src/routes/songs.ts
+++ b/apps/server/src/routes/songs.ts
@@ -27,6 +27,8 @@ import {
saveCover,
mimeForAudioPath,
mimeForCoverPath,
+ isLosslessMaster,
+ transcodeToOpus,
} from "../lib/media.ts";
export const songRoutes = new Hono<AppEnv>();
@@ -136,6 +138,20 @@ songRoutes.post(
console.error("duplicate detection failed:", err),
);
+ // Kick off the Opus transcode in the background for lossless masters. The
+ // upload returns immediately; until stream_path lands, /stream falls back to
+ // the master, so nothing waits on ffmpeg. Fire-and-forget, like dupes above.
+ if (isLosslessMaster(song.file_path)) {
+ transcodeToOpus(song.file_path)
+ .then(async (streamPath) => {
+ if (!streamPath) return;
+ await sql`
+ UPDATE songs SET stream_path = ${streamPath} WHERE id = ${song.id}
+ `;
+ })
+ .catch((err) => console.error("opus transcode failed:", err));
+ }
+
return c.json(toPublicSong(song), 201);
});
@@ -144,8 +160,17 @@ songRoutes.get("/:id/stream", requireAuth, async (c) => {
const song = await getSong(c.req.param("id")!);
if (!song) return c.json({ error: "not_found" }, 404);
- const abs = resolveMedia(song.file_path);
- const info = await stat(abs).catch(() => null);
+ // Prefer the transcoded Opus copy when it exists (smaller = far better on
+ // mobile); otherwise stream the original master. If the Opus file is somehow
+ // missing on disk, fall back to the master rather than 404.
+ let servePath = song.stream_path ?? song.file_path;
+ let abs = resolveMedia(servePath);
+ let info = await stat(abs).catch(() => null);
+ if (!info && song.stream_path) {
+ servePath = song.file_path;
+ abs = resolveMedia(servePath);
+ info = await stat(abs).catch(() => null);
+ }
if (!info) return c.json({ error: "file_missing" }, 404);
const total = info.size;
@@ -153,7 +178,7 @@ songRoutes.get("/:id/stream", requireAuth, async (c) => {
// type (song.mime is often "audio/x-flac", "application/ogg", or empty,
// which can make players refuse or mis-handle FLAC/OGG). Fall back to the
// stored type only if the extension is unrecognised.
- const extMime = mimeForAudioPath(song.file_path);
+ const extMime = mimeForAudioPath(servePath);
const mime =
extMime !== "application/octet-stream"
? extMime
@@ -179,7 +204,7 @@ songRoutes.get("/:id/stream", requireAuth, async (c) => {
"content-type": mime,
"cache-control": cacheControl,
"accept-ranges": "bytes",
- "x-accel-redirect": `${config.xaccelPrefix}/${encodeURI(song.file_path)}`,
+ "x-accel-redirect": `${config.xaccelPrefix}/${encodeURI(servePath)}`,
},
});
}
@@ -332,6 +357,9 @@ songRoutes.delete("/:id", requireAuth, async (c) => {
await sql`DELETE FROM songs WHERE id = ${song.id}`;
await unlink(resolveMedia(song.file_path)).catch(() => {});
+ if (song.stream_path) {
+ await unlink(resolveMedia(song.stream_path)).catch(() => {});
+ }
if (song.cover_path) {
await unlink(resolveMedia(song.cover_path)).catch(() => {});
}
diff --git a/packages/player/src/player.ts b/packages/player/src/player.ts
index 8be506c..7d9251f 100644
--- a/packages/player/src/player.ts
+++ b/packages/player/src/player.ts
@@ -26,6 +26,11 @@ export class Player {
private index = -1;
private lastTrackChangeId: string | null = null;
private playToken = 0; // bumped on every load(); see tryPlay()
+ // Auto-recovery for a stream that drops mid-play (network blip, a transient
+ // server hiccup, mobile dropping the media buffer). See recoverPlayback().
+ private recoverAttempts = 0;
+ private readonly maxRecoverAttempts = 4;
+ private stallTimer: ReturnType<typeof setTimeout> | null = null;
private prefs: Prefs;
private ctx: AudioContext | null = null;
private analyser: AnalyserNode | null = null;
@@ -53,9 +58,29 @@ export class Player {
this.audio.addEventListener("play", () => this.events.emit("change"));
this.audio.addEventListener("pause", () => this.events.emit("change"));
this.audio.addEventListener("volumechange", () => this.events.emit("change"));
+
+ // Playback made progress -> the stream is healthy again: clear any pending
+ // stall watchdog and reset the recovery counter.
+ this.audio.addEventListener("playing", () => {
+ this.recoverAttempts = 0;
+ this.clearStallTimer();
+ });
+ this.audio.addEventListener("canplay", () => this.clearStallTimer());
+
+ // `stalled`/`waiting` fire when the buffer starves. Usually the browser
+ // recovers on its own, so we don't act immediately — we arm a watchdog and
+ // only force a reload if it's still starved after a grace period.
+ this.audio.addEventListener("stalled", () => this.armStallWatchdog());
+ this.audio.addEventListener("waiting", () => this.armStallWatchdog());
+
this.audio.addEventListener("error", () => {
const err = this.audio.error;
- if (err) this.events.emit("error", `Audio error (code ${err.code})`);
+ if (!err) return;
+ // MEDIA_ERR_ABORTED (1) is us changing tracks on purpose — ignore.
+ // NETWORK (2) / DECODE (3) / SRC_NOT_SUPPORTED (4, what a dropped or
+ // 401'd stream often surfaces as) are recoverable: re-fetch and resume.
+ if (err.code === 1) return;
+ this.recoverPlayback();
});
this.setupMediaSession();
@@ -250,6 +275,10 @@ export class Player {
if (!song) return;
const changed = song.id !== this.lastTrackChangeId;
+ // Fresh track: drop any recovery state carried over from the last one.
+ this.recoverAttempts = 0;
+ this.clearStallTimer();
+
// Each load supersedes any in-flight play(). This token lets tryPlay()
// tell "my play() was interrupted because a newer track started" (an
// expected AbortError we should ignore) apart from a real failure.
@@ -374,6 +403,68 @@ export class Player {
});
}
+ // Arm a one-shot watchdog for a stall. If we're still supposed to be playing
+ // but the buffer is starved after the grace period, force a recovery. No-op
+ // if a timer is already pending (repeated stalled/waiting events coalesce).
+ private armStallWatchdog(): void {
+ if (this.stallTimer) return;
+ this.stallTimer = setTimeout(() => {
+ this.stallTimer = null;
+ // readyState < HAVE_FUTURE_DATA (3) means it can't keep playing.
+ if (!this.audio.paused && this.audio.readyState < 3) {
+ this.recoverPlayback();
+ }
+ }, 8000);
+ }
+
+ private clearStallTimer(): void {
+ if (this.stallTimer !== null) {
+ clearTimeout(this.stallTimer);
+ this.stallTimer = null;
+ }
+ }
+
+ // Re-fetch the current stream and resume from where it dropped. Bounded and
+ // backed off so a genuinely dead source can't loop forever, and guarded by
+ // playToken so a track change during the wait cancels the retry cleanly.
+ private recoverPlayback(): void {
+ const song = this.current;
+ if (!song) return;
+
+ this.clearStallTimer();
+
+ if (this.recoverAttempts >= this.maxRecoverAttempts) {
+ this.recoverAttempts = 0;
+ this.events.emit("error", "Playback stopped — tap play to retry");
+ return;
+ }
+
+ const attempt = ++this.recoverAttempts;
+ const wasPlaying = !this.audio.paused;
+ const position = this.audio.currentTime || 0;
+ const delay = Math.min(500 * 2 ** (attempt - 1), 4000); // 0.5s,1s,2s,4s
+ const token = ++this.playToken; // supersede any in-flight play()
+
+ setTimeout(() => {
+ if (token !== this.playToken) return; // a real track change won the race
+ // Reassigning src forces a fresh request for the same bytes.
+ this.audio.src = song.streamUrl;
+ const onMeta = () => {
+ this.audio.removeEventListener("loadedmetadata", onMeta);
+ try {
+ if (position > 0 && Number.isFinite(this.audio.duration)) {
+ this.audio.currentTime = position;
+ }
+ } catch {
+ /* seeking may be unavailable until more buffers in — best effort */
+ }
+ if (wasPlaying) this.tryPlay(token);
+ };
+ this.audio.addEventListener("loadedmetadata", onMeta, { once: true });
+ this.audio.load();
+ }, delay);
+ }
+
private save(): void {
this.storage.save(this.prefs);
}