feat(desktop): package oTunes with custom EAC-3 Electron

This commit is contained in:
joshuafhiggins committed 2026-11-20 00:14:36 -05:00 Verified
1 parent df2d230abe
commit 4a9e471c77
25 files changed
+2594 -13

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
name: Desktop builds
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
build:
# Native host runners, not the Docker-image runner. See the desktop README.
name: Desktop ${{ matrix.target }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 720
strategy:
fail-fast: false
matrix:
include:
- target: windows-x64
runner: desktop-windows-x64
arch: x64
source: ${{ vars.DESKTOP_ELECTRON_SOURCE_WINDOWS_X64 }}
- target: windows-arm64
runner: desktop-windows-arm64
arch: arm64
source: ${{ vars.DESKTOP_ELECTRON_SOURCE_WINDOWS_ARM64 }}
- target: linux-x64
runner: desktop-linux-x64
arch: x64
source: ${{ vars.DESKTOP_ELECTRON_SOURCE_LINUX_X64 }}
- target: linux-arm64
runner: desktop-linux-arm64
arch: arm64
source: ${{ vars.DESKTOP_ELECTRON_SOURCE_LINUX_ARM64 }}
- target: macos-universal
runner: desktop-macos
arch: universal
source: ${{ vars.DESKTOP_ELECTRON_SOURCE_MACOS }}
env:
OTUNES_DESKTOP_ARCH: ${{ matrix.arch }}
OTUNES_ELECTRON_SOURCE: ${{ matrix.source }}
OTUNES_DESKTOP_REF: ${{ gitea.ref }}
DEPOT_TOOLS_WIN_TOOLCHAIN: "0"
defaults:
run:
shell: bash
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up pnpm
uses: pnpm/action-setup@v4
with:
version: 10.1.0
run_install: false
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "24"
- name: Install desktop and web dependencies
run: pnpm --filter @otunes/desktop --filter @otunes/web... install --frozen-lockfile
- name: Check desktop scripts
run: pnpm --filter @otunes/desktop typecheck
- name: Test runtime validation and shared UI packaging
run: pnpm --filter @otunes/desktop test
- name: Build custom Electron and desktop installers
run: pnpm --filter @otunes/desktop build:ci
# Gitea's artifact service uses the v3 protocol, not GitHub's v4 service.
- name: Upload installers
uses: actions/upload-artifact@v3
with:
name: otunes-desktop-${{ matrix.target }}
path: |
apps/desktop/dist/*.exe
apps/desktop/dist/*.flatpak
apps/desktop/dist/*.dmg
apps/desktop/dist/*.blockmap
if-no-files-found: error
+7
View File
@@ -47,3 +47,10 @@ docker-compose.yml
**/credentials/
**/*.ipa
**/*.apk
# Electron desktop build artifacts
apps/desktop/.package/
apps/desktop/dist/
apps/desktop/runtime/
apps/web/.next-desktop/
apps/desktop/web/
+5
View File
@@ -9,6 +9,7 @@ This project uses [pnpm workspaces](https://pnpm.io/workspaces):
| Package | Path | Description |
| --- | --- | --- |
| `@otunes/web` | `apps/web` | Next.js web app |
| `@otunes/desktop` | `apps/desktop` | Electron client with a custom EAC-3 runtime |
| `@otunes/mobile` | `apps/mobile` | Expo React Native mobile app |
| `@otunes/convex` | `packages/convex` | Shared Convex backend and client types |
@@ -94,3 +95,7 @@ If Convex has to live somewhere else, set `PUBLIC_CONVEX_URL` on the container t
## Downloads
Check the releases tab for the latest downloads for apps: [Releases](https://git.abunchofknowitalls.com/joshuafhiggins/otunes/releases)
## Desktop builds
See [the desktop build guide](apps/desktop/README.md) to compile Electron with EAC-3 support and package the web player for macOS, Windows or Linux. The UI is bundled locally, and users choose their oTunes server before signing in. Platform decoding and spatial Atmos output require separate validation.
+100
View File
@@ -0,0 +1,100 @@
# oTunes desktop
The desktop app bundles the web UI and runs its standalone Next.js server on loopback using Electron's Node utility process. It never loads the UI hosted on your music server. On first launch, enter the oTunes server domain, then sign in. The address is saved in the app's user data directory, not compiled into the package.
For `music.example.com`, Convex connects to `https://convex.music.example.com`. Local hosts follow the mobile convention and use port 3210. The selected oTunes server provides streaming audio and cover art through the desktop's local gateway. Authentication routes stay local and connect to the selected Convex backend. The desktop app does not bundle Convex, FFmpeg or a music library.
The server-entry view uses the web app's controls, colors and logos, with the system theme by default. Use **Server > Change server** to select another server. Switching servers clears the local login session and cached data.
## Build the custom runtime
Stock Electron does not meet this build's requirements. `runtime.gn` enables Chromium's `enable_platform_ac3_eac3_audio` with proprietary codecs and Chrome FFmpeg branding. This is a compile-time setting, not an Electron command-line switch. Electron and its embedded Chromium must be rebuilt together.
Install the platform prerequisites and `depot_tools` described in [Electron's source build instructions](https://www.electronjs.org/docs/latest/development/build-instructions-gn). Use a dedicated build machine with enough disk space for Chromium and its dependencies. From a separate, empty source checkout directory:
```sh
gclient config --name "src/electron" --unmanaged https://github.com/electron/electron
gclient sync --with_branch_heads --with_tags
cd src/electron
git checkout v45.3.0
gclient sync -f --with_branch_heads --with_tags
```
Back in the oTunes repository:
```sh
pnpm install
export OTUNES_ELECTRON_SOURCE=/absolute/path/to/checkout/src
pnpm build:desktop:runtime
```
This generates `src/out/otunes-<arch>/args.gn`, runs GN and Ninja, and extracts `dist.zip` into `apps/desktop/runtime/45.3.0-<platform>-<arch>`. It writes a runtime marker recording the version, platform, architecture and codec build setting. Packaging requires that marker and never downloads stock Electron as a fallback. The marker records build provenance, not a successful decoding test. Keep it with the extracted runtime.
Build natively for Windows and Linux. On macOS, `OTUNES_ELECTRON_ARCH=x64` or `arm64` selects the target CPU, allowing both slices to be compiled on one Mac. The scripts pin Electron 45.3.0. Update `electronVersion` in `scripts/config.mjs` and the checkout tag together when upgrading. The runtime output directory must not already exist. Move or remove a previous output before rebuilding.
## Run and package
```sh
export OTUNES_ELECTRON_DIST=/absolute/path/to/otunes/apps/desktop/runtime/45.3.0-darwin-arm64
pnpm dev:desktop
# Or create an installer:
pnpm build:desktop
```
Both commands first build and bundle the local web UI. `pnpm --filter @otunes/desktop build:web` builds that bundle alone without needing an Electron runtime. Desktop builds use `apps/web/.next-desktop` and copy the standalone output, static assets and public assets into `apps/desktop/web`. Relative pnpm symlinks are preserved so the bundled Next.js dependencies remain resolvable. The web app's normal `.next` output is separate. On Windows, enable Developer Mode or symlink permissions before building. The build rejects absolute junctions or links outside the standalone directory because they cannot be relocated into an installer.
The desktop gateway binds only to `127.0.0.1:47836`. A single instance owns that port. The bundled Next.js process uses a separate OS-assigned loopback port and restarts when the server selection changes. No external Node.js installation is required by the installed app. `dev:desktop` uses the packaged production UI; it does not start or connect to a web preview channel.
`build:desktop` creates a native package in `apps/desktop/dist`: DMG on macOS, NSIS on Windows, Flatpak on Linux. The same installer can connect to different servers. Signing and macOS notarization use electron-builder's standard environment configuration and require your own credentials. The build does not publish artifacts.
## Gitea builds
`.gitea/workflows/desktop-build.yml` runs manually through `workflow_dispatch` and on `v*` tags, matching the Docker workflow. It builds the custom Electron runtime before each installer and uploads installers to the Actions run with `actions/upload-artifact@v3`. It does not create releases or publish to Flathub. Tags set the installer version, so use semantic version tags such as `v1.2.3`. Manual runs use the desktop package version.
Register these **native host** Gitea runner labels with `:host` execution, not Docker execution:
| Runner label | Native Node architecture | Repository Actions variable for the Electron `src` path | Output |
| --- | --- | --- | --- |
| `desktop-windows-x64` | x64 | `DESKTOP_ELECTRON_SOURCE_WINDOWS_X64` | x64 NSIS installer |
| `desktop-windows-arm64` | arm64 | `DESKTOP_ELECTRON_SOURCE_WINDOWS_ARM64` | ARM64 NSIS installer |
| `desktop-linux-x64` | x64 | `DESKTOP_ELECTRON_SOURCE_LINUX_X64` | x86-64 Flatpak |
| `desktop-linux-arm64` | arm64 | `DESKTOP_ELECTRON_SOURCE_LINUX_ARM64` | AArch64 Flatpak |
| `desktop-macos` | x64 or arm64 | `DESKTOP_ELECTRON_SOURCE_MACOS` | Universal DMG |
Here x86 means x86-64, not 32-bit IA-32. The workflow installs Node.js 24 and pnpm 10.1.0. The runner and its bootstrap Node.js must themselves be native to the requested architecture. Each runner also needs Git, Bash, Electron's platform build prerequisites, `depot_tools` on PATH, and a synced Electron v45.3.0 checkout prepared as described above. The source path is an absolute path outside the disposable Actions checkout. Separate build machines or checkouts avoid concurrent source-tree builds. GN/Ninja outputs remain in that source tree for incremental rebuilds. The workflow does not update that shared checkout or run `gclient sync` automatically.
Windows runners need Visual Studio's Electron/Chromium build components and SDK, plus Developer Mode or symlink permissions. The ARM64 runner needs the ARM64 compiler tools. Mac runners need Xcode, its command-line tools, and both macOS SDK architectures. Linux runners need a native Chromium build environment, Flatpak >= 1.12.4, flatpak-builder >= 1.2.2, and a working user session with unprivileged sandbox support. Add Flathub for the runner user before the first build:
```sh
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
```
Flatpaks pin `org.freedesktop.Platform`, its SDK and `org.electronjs.Electron2.BaseApp` to `25.08`. Network, audio, graphics and display access are enabled. Home-directory access is not needed. Builds can install the matching runtime/SDK/BaseApp from Flathub for their architecture.
The Universal job compiles separate x64 and ARM64 Electron distributions, validates each marker, and gives electron-builder the corresponding runtime for each slice before merging the app. The bundled UI is shared between slices. Since desktop images bypass Next's optimizer, the bundle excludes unused Sharp native libraries. Any other native library makes the build fail so a host-specific dependency cannot silently enter the Universal app.
To reproduce the CI build on a prepared runner:
```sh
export OTUNES_ELECTRON_SOURCE=/absolute/path/to/electron/src
export OTUNES_DESKTOP_ARCH=universal # macOS; use x64 or arm64 on other hosts
pnpm --filter @otunes/desktop build:ci
```
Signing/notarization credentials are not configured by this workflow. Configure electron-builder's signing environment on trusted runners if signed installers are required. Without credentials the resulting installers are unsigned, and macOS may require approval to open them.
## EAC-3 and Atmos limits
The build flag enables EAC-3 media handling. A platform decoder is still required. Chromium's [decoder support checks](https://chromium.googlesource.com/chromium/src/+/main/media/base/supported_types.cc) consult platform codec support on macOS and Windows. Linux does not gain a software EAC-3 decoder just by enabling this flag. Linux packaging is available, but EAC-3 playback is not promised there.
EAC-3 decoding and spatial Dolby Atmos rendering are separate capabilities. Decoding may produce channel-based PCM without preserving Atmos object metadata. The flag does not add Dolby licensing, guarantee HDMI passthrough, or guarantee spatial output on any OS or audio device. Review codec distribution requirements before distributing a custom runtime.
Validate on each target OS and output device before releasing:
1. Open the desktop client against a test server with a known EAC-3 track.
2. Confirm the existing playback settings allow the Atmos preference, enable it, and play the track. The app uses browser codec detection, with no desktop override that forces support to true.
3. Confirm the stream contains EAC-3 and playback advances with audible output. MIME support alone is not a decode test.
4. Verify spatial output separately using the OS or receiver's output diagnostics. A track badge does not prove Atmos rendering.
5. Check normal AAC/lossless playback and seeking too.
The source build is intentionally separate from app packaging because rebuilding Chromium is expensive. No custom runtime binary is checked into this repository.
+303
View File
@@ -0,0 +1,303 @@
const {
app,
BrowserWindow,
Menu,
nativeTheme,
session,
utilityProcess,
} = require("electron")
const { createServer, request: httpRequest } = require("node:http")
const { request: httpsRequest } = require("node:https")
const { readFile, mkdir, writeFile, rename } = require("node:fs/promises")
const path = require("node:path")
const { parseServer } = require("./server-config.cjs")
const origin = "http://127.0.0.1:47836"
let window,
gateway,
nextProcess,
config,
changingServer = false
let nextPort
const configPath = () => path.join(app.getPath("userData"), "server.json")
const webRoot = path.join(
app.isPackaged ? process.resourcesPath : __dirname,
"web",
"apps",
"web"
)
async function startWeb() {
if (nextProcess) {
const previous = nextProcess
nextProcess = undefined
await new Promise((resolve) => {
previous.once("exit", resolve)
previous.kill()
})
}
// Let the OS allocate a private port for the bundled Next.js server.
const reservation = createServer()
await new Promise((resolve, reject) => {
reservation.once("error", reject)
reservation.listen(0, "127.0.0.1", resolve)
})
nextPort = reservation.address().port
await new Promise((resolve) => reservation.close(resolve))
nextProcess = utilityProcess.fork(path.join(webRoot, "server.js"), [], {
cwd: webRoot,
env: {
...process.env,
NODE_ENV: "production",
HOSTNAME: "127.0.0.1",
PORT: String(nextPort),
OTUNES_DESKTOP: "1",
OTUNES_DESKTOP_HOSTNAME: config?.hostname ?? "",
PUBLIC_CONVEX_URL: config?.convexUrl ?? "",
CONVEX_INTERNAL_URL: config?.convexUrl ?? "http://127.0.0.1:3210",
NEXT_PUBLIC_CONVEX_URL: config?.convexUrl ?? "",
},
stdio: "pipe",
})
nextProcess.stdout.on("data", (data) => console.log(data.toString()))
nextProcess.stderr.on("data", (data) => console.error(data.toString()))
let exited = false
const child = nextProcess
child.once("exit", () => {
exited = true
if (nextProcess === child) nextProcess = undefined
})
for (let attempt = 0; attempt < 150; attempt++) {
if (exited) throw new Error("The packaged web server exited during startup")
try {
const response = await fetch(`http://127.0.0.1:${nextPort}/desktop`, {
signal: AbortSignal.timeout(1000),
})
if (!response.ok) throw new Error("Server entry page did not load")
await response.body?.cancel()
return
} catch {
await new Promise((resolve) => setTimeout(resolve, 200))
}
}
throw new Error("The packaged web server did not start")
}
async function saveServer(request, response) {
if (
request.headers.origin !== origin ||
request.headers["content-type"] !== "application/json"
) {
response.writeHead(403).end()
return
}
if (changingServer) {
response.writeHead(409).end()
return
}
changingServer = true
try {
let body = ""
for await (const chunk of request) {
body += chunk
if (body.length > 2048) throw new Error("Server address is too long.")
}
const selected = parseServer(JSON.parse(body).hostname)
// Validate against Convex before replacing the current server and session.
const check = await fetch(`${selected.convexUrl}/version`, {
signal: AbortSignal.timeout(10000),
})
if (!check.ok)
throw new Error(
"Could not reach the Convex server. Check the address and try again."
)
const previous = config
config = selected
try {
await startWeb()
} catch (error) {
config = previous
await startWeb()
throw error
}
await mkdir(app.getPath("userData"), { recursive: true })
await writeFile(`${configPath()}.tmp`, JSON.stringify(selected), {
mode: 0o600,
})
await rename(`${configPath()}.tmp`, configPath())
if (previous?.hostname !== selected.hostname) {
await session.defaultSession.clearStorageData()
await session.defaultSession.clearCache()
}
response
.writeHead(200, {
"Content-Type": "application/json",
"Cache-Control": "no-store",
})
.end("{}")
} catch (error) {
response.writeHead(400, { "Content-Type": "application/json" }).end(
JSON.stringify({
error:
error instanceof TypeError
? "Could not reach the server. Check the address and try again."
: error.message,
})
)
} finally {
changingServer = false
}
}
function handleRequest(request, response) {
if (request.headers.host !== new URL(origin).host) {
response.writeHead(403).end()
return
}
const url = new URL(request.url, origin)
if (url.pathname === "/__desktop/server" && request.method === "POST") {
void saveServer(request, response)
return
}
if (changingServer) {
response.writeHead(503).end("Switching server")
return
}
// Only data routes go to the remote server. All UI and auth routes stay local.
const remote =
config && /^\/api\/(song|album|artist|playlist)\//.test(url.pathname)
const target = new URL(
`${url.pathname}${url.search}`,
remote ? config.serverUrl : `http://127.0.0.1:${nextPort}`
)
const headers = {
...request.headers,
host: remote ? target.host : request.headers.host,
}
if (remote) {
delete headers.origin
// Convex Auth uses __Host- cookie names on public HTTPS servers.
// Forward only the access token, never the local refresh token.
const token = request.headers.cookie
?.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith("__convexAuthJWT="))
?.slice("__convexAuthJWT=".length)
delete headers.cookie
if (token) {
const prefix = /(localhost|127\.0\.0\.1):\d+/.test(target.host)
? ""
: "__Host-"
headers.cookie = `${prefix}__convexAuthJWT=${token}`
}
}
delete headers.connection
const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(
target,
{
method: request.method,
headers,
},
(incoming) => {
// Never redirect the window to remote HTML or accept remote session cookies.
const resultHeaders = { ...incoming.headers }
if (remote) delete resultHeaders["set-cookie"]
response.writeHead(incoming.statusCode ?? 502, resultHeaders)
incoming.on("error", () => response.destroy())
incoming.pipe(response)
}
)
upstream.on("error", () => {
if (!response.headersSent) response.writeHead(502)
response.end("Server unavailable")
})
request.on("aborted", () => upstream.destroy())
response.on("close", () => upstream.destroy())
request.pipe(upstream)
}
function openWindow() {
window = new BrowserWindow({
title: "oTunes",
width: 1280,
height: 850,
backgroundColor: nativeTheme.shouldUseDarkColors ? "#000000" : "#ffffff",
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
},
})
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
const restrictNavigation = (event, target) => {
if (new URL(target).origin !== origin) event.preventDefault()
}
window.webContents.on("will-navigate", restrictNavigation)
window.webContents.on("will-redirect", restrictNavigation)
session.defaultSession.setPermissionRequestHandler(
(_contents, _permission, callback) => callback(false)
)
session.defaultSession.setPermissionCheckHandler(() => false)
window.loadURL(`${origin}${config ? "/" : "/desktop"}`).catch(console.error)
window.on("closed", () => {
window = undefined
})
}
if (!app.requestSingleInstanceLock()) app.quit()
else {
app.on("second-instance", () => {
window?.show()
window?.focus()
})
app
.whenReady()
.then(async () => {
try {
config = parseServer(
JSON.parse(await readFile(configPath(), "utf8")).hostname
)
} catch {
config = undefined
}
await startWeb()
gateway = createServer(handleRequest)
await new Promise((resolve, reject) => {
gateway.once("error", reject)
gateway.listen(47836, "127.0.0.1", resolve)
})
Menu.setApplicationMenu(
Menu.buildFromTemplate([
...(process.platform === "darwin" ? [{ role: "appMenu" }] : []),
{
label: "Server",
submenu: [
{
label: "Change server…",
click: () => window?.loadURL(`${origin}/desktop`),
},
],
},
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" },
])
)
openWindow()
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) openWindow()
})
})
.catch((error) => {
console.error(error)
app.quit()
})
}
app.on("before-quit", () => {
nextProcess?.kill()
gateway?.close()
})
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit()
})
+21
View File
@@ -0,0 +1,21 @@
{
"name": "@otunes/desktop",
"version": "0.0.1",
"private": true,
"description": "oTunes desktop client with a custom EAC-3 Electron runtime",
"author": "oTunes contributors",
"main": "main.cjs",
"scripts": {
"start": "pnpm build:web && node scripts/start.mjs",
"build": "pnpm build:web && node scripts/package.mjs",
"build:runtime": "node scripts/build-runtime.mjs",
"typecheck": "node --check main.cjs && node --check scripts/config.mjs && node --check scripts/start.mjs && node --check scripts/package.mjs && node --check scripts/build-runtime.mjs && node --check server-config.cjs && node --check scripts/build-web.mjs && node --check scripts/ci-build.mjs && node --check scripts/prune-native-images.mjs",
"build:web": "node scripts/build-web.mjs",
"build:ci": "node scripts/ci-build.mjs",
"test": "node --test scripts/build.test.mjs"
},
"devDependencies": {
"electron-builder": "26.18.0",
"extract-zip": "2.0.1"
}
}
+5
View File
@@ -0,0 +1,5 @@
import("//electron/build/args/release.gn")
proprietary_codecs = true
ffmpeg_branding = "Chrome"
enable_platform_ac3_eac3_audio = true
+66
View File
@@ -0,0 +1,66 @@
import { execFileSync } from "node:child_process"
import { mkdir, readFile, writeFile, access } from "node:fs/promises"
import path from "node:path"
import extract from "extract-zip"
import { desktopRoot, electronVersion } from "./config.mjs"
if (!process.env.OTUNES_ELECTRON_SOURCE) {
throw new Error(
"Set OTUNES_ELECTRON_SOURCE to a synced Electron src directory. See apps/desktop/README.md."
)
}
const source = path.resolve(process.env.OTUNES_ELECTRON_SOURCE)
const tag = execFileSync(
"git",
["describe", "--tags", "--exact-match", "HEAD"],
{
cwd: path.join(source, "electron"),
encoding: "utf8",
}
).trim()
if (tag !== `v${electronVersion}`)
throw new Error(`Check out and sync Electron v${electronVersion} first`)
await access(path.join(source, "media", "media_options.gni"))
const arch = process.env.OTUNES_ELECTRON_ARCH ?? process.arch
if (!["x64", "arm64"].includes(arch))
throw new Error("Electron target must be x64 or arm64")
const outputName = `out/otunes-${arch}`
const output = path.join(source, outputName)
await mkdir(output, { recursive: true })
await writeFile(
path.join(output, "args.gn"),
`${await readFile(path.join(desktopRoot, "runtime.gn"), "utf8")}\ntarget_cpu = "${arch}"\n`
)
for (const [command, args] of [
["gn", ["gen", outputName, "--fail-on-unused-args"]],
["ninja", ["-C", outputName, "electron:electron_dist_zip"]],
]) {
execFileSync(command, args, {
cwd: source,
stdio: "inherit",
shell: process.platform === "win32",
})
}
// Use a fresh directory so stale files cannot enter a packaged runtime.
const distribution = path.join(
desktopRoot,
"runtime",
`${electronVersion}-${process.platform}-${arch}`
)
await mkdir(path.dirname(distribution), { recursive: true })
await mkdir(distribution)
await extract(path.join(output, "dist.zip"), { dir: distribution })
await writeFile(
path.join(distribution, "otunes-runtime.json"),
JSON.stringify(
{
version: electronVersion,
platform: process.platform,
arch,
enable_platform_ac3_eac3_audio: true,
},
null,
2
)
)
console.log(`Custom runtime ready. Set OTUNES_ELECTRON_DIST=${distribution}`)
+68
View File
@@ -0,0 +1,68 @@
import { execFileSync } from "node:child_process"
import { createRequire } from "node:module"
import { cp, mkdir, rm, readdir, readlink, realpath } from "node:fs/promises"
import path from "node:path"
import { pruneNativeImages } from "./prune-native-images.mjs"
import { desktopRoot } from "./config.mjs"
const web = path.resolve(desktopRoot, "../web")
const webRequire = createRequire(path.join(web, "package.json"))
execFileSync(
process.execPath,
[webRequire.resolve("next/dist/bin/next"), "build"],
{
cwd: web,
stdio: "inherit",
env: {
...process.env,
OTUNES_DESKTOP_BUILD: "1",
NEXT_PUBLIC_CONVEX_URL: "",
},
}
)
// Junction fallbacks on Windows can point back into the developer's checkout.
// Reject them rather than shipping an installer that only works on that machine.
const standalone = path.join(web, ".next-desktop/standalone")
async function checkLinks(directory) {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name)
if (entry.isSymbolicLink()) {
const target = await readlink(file)
const resolved = await realpath(file)
const relative = path.relative(standalone, resolved)
if (
path.isAbsolute(target) ||
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative)
) {
throw new Error(
"The standalone bundle contains a non-relocatable link. Enable symlink permissions or Windows Developer Mode and rebuild."
)
}
} else if (entry.isDirectory()) {
await checkLinks(file)
}
}
}
await checkLinks(standalone)
const destination = path.join(desktopRoot, "web")
await rm(destination, { recursive: true, force: true })
await cp(standalone, destination, {
recursive: true,
verbatimSymlinks: true,
filter: (file) => !path.basename(file).startsWith(".env"),
})
const app = path.join(destination, "apps/web")
await mkdir(path.join(app, ".next-desktop"), { recursive: true })
await cp(
path.join(web, ".next-desktop/static"),
path.join(app, ".next-desktop/static"),
{ recursive: true }
)
await cp(path.join(web, "public"), path.join(app, "public"), {
recursive: true,
})
await pruneNativeImages(destination)
+95
View File
@@ -0,0 +1,95 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import {
mkdtemp,
mkdir,
writeFile,
readFile,
rm,
access,
} from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { customRuntime, electronVersion } from "./config.mjs"
import { pruneNativeImages } from "./prune-native-images.mjs"
async function fixture(run) {
const directory = await mkdtemp(path.join(os.tmpdir(), "otunes-build-"))
try {
await run(directory)
} finally {
await rm(directory, { recursive: true, force: true })
}
}
test("runtime validation uses the target architecture and requires the EAC-3 build marker", async () => {
await fixture(async (directory) => {
const arch = process.arch === "x64" ? "arm64" : "x64"
const executable =
process.platform === "darwin"
? "Electron.app/Contents/MacOS/Electron"
: process.platform === "win32"
? "electron.exe"
: "electron"
await mkdir(path.dirname(path.join(directory, executable)), {
recursive: true,
})
await writeFile(path.join(directory, executable), "fixture")
const manifest = {
version: electronVersion,
platform: process.platform,
arch,
enable_platform_ac3_eac3_audio: true,
}
const marker = path.join(directory, "otunes-runtime.json")
await writeFile(marker, JSON.stringify(manifest))
assert.equal((await customRuntime(arch, directory)).directory, directory)
await assert.rejects(
customRuntime(process.arch, directory),
/with EAC-3 enabled/
)
await writeFile(
marker,
JSON.stringify({ ...manifest, enable_platform_ac3_eac3_audio: false })
)
await assert.rejects(customRuntime(arch, directory), /with EAC-3 enabled/)
})
})
test("the shared UI drops unused Sharp binaries but keeps JavaScript and package metadata", async () => {
await fixture(async (directory) => {
const lib = path.join(
directory,
"node_modules",
"@img",
"sharp-darwin-arm64",
"lib"
)
await mkdir(lib, { recursive: true })
for (const file of [
"sharp.node",
"libvips.dylib",
"index.js",
"debug.node.js",
"package.json",
])
await writeFile(path.join(lib, file), file)
await pruneNativeImages(directory)
for (const file of ["sharp.node", "libvips.dylib"])
await assert.rejects(access(path.join(lib, file)))
assert.equal(await readFile(path.join(lib, "index.js"), "utf8"), "index.js")
await access(path.join(lib, "debug.node.js"))
await access(path.join(lib, "package.json"))
})
})
test("new native dependencies fail the shared UI build instead of shipping a host-only binary", async () => {
await fixture(async (directory) => {
await writeFile(path.join(directory, "new-dependency.node"), "fixture")
await assert.rejects(
pruneNativeImages(directory),
/Unexpected native dependency/
)
await access(path.join(directory, "new-dependency.node"))
})
})
+42
View File
@@ -0,0 +1,42 @@
import { execFileSync } from "node:child_process"
import path from "node:path"
import { desktopRoot, electronVersion } from "./config.mjs"
const target = process.env.OTUNES_DESKTOP_ARCH
if (
!(["x64", "arm64"].includes(target) && target === process.arch) &&
!(process.platform === "darwin" && target === "universal")
) {
throw new Error(
"Use a native x64/arm64 Node.js runner, or a Mac for universal builds"
)
}
if (!process.env.OTUNES_ELECTRON_SOURCE)
throw new Error(
"Configure the runner's Electron source path. See apps/desktop/README.md."
)
function run(script, env = {}) {
execFileSync(process.execPath, [path.join(desktopRoot, "scripts", script)], {
stdio: "inherit",
env: { ...process.env, ...env },
})
}
const architectures = target === "universal" ? ["x64", "arm64"] : [target]
for (const arch of architectures)
run("build-runtime.mjs", { OTUNES_ELECTRON_ARCH: arch })
run("build-web.mjs")
const distribution = (arch) =>
path.join(
desktopRoot,
"runtime",
`${electronVersion}-${process.platform}-${arch}`
)
run(
"package.mjs",
target === "universal"
? {
OTUNES_ELECTRON_DIST_X64: distribution("x64"),
OTUNES_ELECTRON_DIST_ARM64: distribution("arm64"),
}
: { OTUNES_ELECTRON_DIST: distribution(target) }
)
+42
View File
@@ -0,0 +1,42 @@
import { readFile, access } from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
export const desktopRoot = fileURLToPath(new URL("../", import.meta.url))
export const electronVersion = "45.3.0"
// The build recipe writes this marker only after the custom runtime compiles.
export async function customRuntime(
arch = process.arch,
location = process.env.OTUNES_ELECTRON_DIST
) {
if (!location) {
throw new Error(
"Set OTUNES_ELECTRON_DIST to the extracted custom Electron distribution. Stock Electron is not supported."
)
}
const directory = path.resolve(location)
const manifest = JSON.parse(
await readFile(path.join(directory, "otunes-runtime.json"), "utf8")
)
if (
manifest.version !== electronVersion ||
manifest.platform !== process.platform ||
manifest.arch !== arch ||
manifest.enable_platform_ac3_eac3_audio !== true
) {
throw new Error(
`Custom runtime must be Electron ${electronVersion} with EAC-3 enabled for ${process.platform}/${arch}`
)
}
const executable = path.join(
directory,
process.platform === "darwin"
? "Electron.app/Contents/MacOS/Electron"
: process.platform === "win32"
? "electron.exe"
: "electron"
)
await access(executable)
return { directory, executable }
}
+93
View File
@@ -0,0 +1,93 @@
import { build, Platform, Arch } from "electron-builder"
import { mkdir, copyFile, writeFile, rm, readFile } from "node:fs/promises"
import path from "node:path"
import { customRuntime, desktopRoot, electronVersion } from "./config.mjs"
const arch = process.env.OTUNES_DESKTOP_ARCH ?? process.arch
if (
!["x64", "arm64", "universal"].includes(arch) ||
(arch === "universal" && process.platform !== "darwin")
) {
throw new Error("Supported targets are x64, arm64 and macOS universal")
}
const runtimes =
arch === "universal"
? {
x64: await customRuntime("x64", process.env.OTUNES_ELECTRON_DIST_X64),
arm64: await customRuntime(
"arm64",
process.env.OTUNES_ELECTRON_DIST_ARM64
),
}
: { [arch]: await customRuntime(arch) }
const platform =
process.platform === "darwin"
? Platform.MAC
: process.platform === "win32"
? Platform.WINDOWS
: Platform.LINUX
const staging = path.join(desktopRoot, ".package")
await rm(staging, { recursive: true, force: true })
await mkdir(staging, { recursive: true })
await copyFile(
path.join(desktopRoot, "main.cjs"),
path.join(staging, "main.cjs")
)
const pkg = JSON.parse(
await readFile(path.join(desktopRoot, "package.json"), "utf8")
)
const ref = process.env.OTUNES_DESKTOP_REF ?? ""
if (ref.startsWith("refs/tags/"))
pkg.version = ref.slice("refs/tags/".length).replace(/^v/, "")
delete pkg.devDependencies
delete pkg.scripts
await writeFile(
path.join(staging, "package.json"),
JSON.stringify(pkg, null, 2)
)
await copyFile(
path.join(desktopRoot, "server-config.cjs"),
path.join(staging, "server-config.cjs")
)
await build({
targets: platform.createTarget(undefined, Arch[arch]),
config: {
appId: "com.otunes.desktop",
productName: "oTunes",
electronVersion,
// Return a missing path for unexpected architectures so builder fails closed.
// Throwing inside this hook lets electron-builder fall back to stock Electron.
electronDist: ({ arch: runtimeArch }) =>
runtimes[runtimeArch]?.directory ??
path.join(desktopRoot, "runtime", `unsupported-${runtimeArch}`),
artifactName: "oTunes-${version}-${os}-${arch}.${ext}",
directories: { app: staging, output: path.join(desktopRoot, "dist") },
files: ["main.cjs", "server-config.cjs", "package.json"],
extraResources: [
{ from: path.join(desktopRoot, "web"), to: "web", filter: ["**/*"] },
],
npmRebuild: false,
mac: { category: "public.app-category.music", target: ["dmg"] },
win: { target: ["nsis"] },
linux: {
category: "AudioVideo",
target: ["flatpak"],
icon: path.resolve(desktopRoot, "../web/public/logo.png"),
},
flatpak: {
runtimeVersion: "25.08",
baseVersion: "25.08",
finishArgs: [
"--socket=wayland",
"--socket=fallback-x11",
"--share=ipc",
"--device=dri",
"--socket=pulseaudio",
"--share=network",
],
},
publish: null,
},
publish: "never",
})
@@ -0,0 +1,19 @@
import { readdir, rm } from "node:fs/promises"
import path from "node:path"
// Desktop images bypass Next's optimizer. Its traced Sharp binaries are unused
// and would otherwise make the shared web bundle specific to the build host.
export async function pruneNativeImages(directory) {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name)
if (entry.isDirectory()) await pruneNativeImages(file)
else if (entry.isFile() && /\.(node|dylib|dll)$|\.so(?:\.\d+)*$/.test(entry.name)) {
if (!file.includes(`${path.sep}@img${path.sep}sharp-`)) {
throw new Error(
`Unexpected native dependency in the desktop web bundle: ${file}`
)
}
await rm(file)
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import { spawn } from "node:child_process"
import { customRuntime, desktopRoot } from "./config.mjs"
const runtime = await customRuntime()
const child = spawn(runtime.executable, [desktopRoot], {
stdio: "inherit",
env: process.env,
})
child.on("error", (error) => {
throw error
})
child.on("exit", (code) => process.exit(code ?? 1))
+26
View File
@@ -0,0 +1,26 @@
// Match mobile's public-domain and local-network Convex conventions.
function parseServer(input) {
if (typeof input !== "string" || !input.trim())
throw new Error("Enter your server address.")
const raw = input
.trim()
.replace(/^https?:\/\//i, "")
.replace(/\/+$/, "")
if (/[\s/@?#\\]/.test(raw))
throw new Error("Enter a hostname, without a path or credentials.")
const parsed = new URL(`https://${raw}`)
const local =
parsed.hostname === "localhost" ||
parsed.hostname.endsWith(".local") ||
/^\d{1,3}(\.\d{1,3}){3}$/.test(parsed.hostname)
const protocol = local ? "http:" : "https:"
const hostname = parsed.host
return {
hostname,
serverUrl: `${protocol}//${hostname}`,
convexUrl: local
? `${protocol}//${parsed.hostname}:3210`
: `${protocol}//convex.${hostname}`,
}
}
module.exports = { parseServer }
+11
View File
@@ -0,0 +1,11 @@
import { notFound } from "next/navigation"
import { connection } from "next/server"
import { DesktopServerForm } from "@/components/desktop-server-form"
export default async function DesktopServerPage() {
await connection()
if (process.env.OTUNES_DESKTOP !== "1") notFound()
return (
<DesktopServerForm hostname={process.env.OTUNES_DESKTOP_HOSTNAME ?? ""} />
)
}
+18 -8
View File
@@ -70,6 +70,15 @@ export default function RootLayout({
}: Readonly<{
children: React.ReactNode
}>) {
const desktop = process.env.OTUNES_DESKTOP === "1"
const needsServer = desktop && !process.env.PUBLIC_CONVEX_URL
const content = (
<ThemeProvider defaultTheme="system">
{children}
<Toaster />
</ThemeProvider>
)
return (
<html
lang="en"
@@ -82,14 +91,15 @@ export default function RootLayout({
)}
>
<body className={"overflow-x-hidden"}>
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
<ThemeProvider>
{children}
<Toaster />
</ThemeProvider>
</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
{needsServer ? (
content
) : (
<ConvexAuthNextjsServerProvider storageNamespace="otunes">
<ConvexClientProvider convexUrl={process.env.PUBLIC_CONVEX_URL}>
{content}
</ConvexClientProvider>
</ConvexAuthNextjsServerProvider>
)}
</body>
</html>
)
+107
View File
@@ -0,0 +1,107 @@
"use client"
import { useState, type FormEvent } from "react"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
} from "@/components/ui/field"
export function DesktopServerForm({ hostname }: { hostname: string }) {
const [address, setAddress] = useState(hostname)
const [error, setError] = useState<string | null>(null)
const [submitting, setSubmitting] = useState(false)
async function connect(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setError(null)
setSubmitting(true)
try {
const response = await fetch("/__desktop/server", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ hostname: address }),
})
if (!response.ok) {
const result: { error?: string } = await response.json()
throw new Error(result.error ?? "Could not connect to the server.")
}
window.location.replace("/signin")
} catch (error) {
setError(
error instanceof Error ? error.message : "Could not save the server."
)
setSubmitting(false)
}
}
return (
<main className="grid min-h-svh bg-background text-foreground md:grid-cols-2">
<aside className="flex flex-col justify-between gap-12 border-b border-border bg-muted/30 p-8 md:border-r md:border-b-0 md:p-12">
<div className="flex items-center gap-3">
<Image
src="/logo.png"
alt=""
width={48}
height={48}
unoptimized
className="dark:hidden"
/>
<Image
src="/logo-dark.png"
alt=""
width={48}
height={48}
unoptimized
className="hidden dark:block"
/>
<span className="text-xl font-semibold">oTunes</span>
</div>
<h1 className="text-4xl font-semibold tracking-tight lg:text-5xl">
Your server.
<br />
Your music.
</h1>
</aside>
<section className="flex items-center justify-center p-8 md:p-12">
<form onSubmit={connect} className="w-full max-w-sm">
<h2 className="mb-8 text-2xl font-semibold tracking-tight">
Connect to a server
</h2>
<FieldGroup>
<Field>
<FieldLabel htmlFor="server-address">Server address</FieldLabel>
<Input
id="server-address"
name="hostname"
value={address}
onChange={(event) => setAddress(event.target.value)}
placeholder="music.example.com"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
autoComplete="url"
required
disabled={submitting}
aria-invalid={!!error}
aria-describedby={error ? "server-error" : undefined}
/>
{error && (
<FieldError id="server-error" role="alert">
{error}
</FieldError>
)}
</Field>
<Button type="submit" disabled={submitting}>
{submitting ? "Connecting…" : "Continue"}
</Button>
</FieldGroup>
</form>
</section>
</main>
)
}
+5 -2
View File
@@ -1,4 +1,4 @@
const EC3_MIME = 'audio/x-m4a; codecs="ec-3"'
const EC3_MIMES = ['audio/mp4; codecs="ec-3"', 'audio/x-m4a; codecs="ec-3"']
const AC4_MIME = 'audio/x-m4a; codecs="ac-4"'
function canPlayMime(audio: HTMLAudioElement, mime: string): boolean {
@@ -6,5 +6,8 @@ function canPlayMime(audio: HTMLAudioElement, mime: string): boolean {
}
export function supportsDolbyAtmosPlayback(audio: HTMLAudioElement): boolean {
return canPlayMime(audio, EC3_MIME) || canPlayMime(audio, AC4_MIME)
return (
EC3_MIMES.some((mime) => canPlayMime(audio, mime)) ||
canPlayMime(audio, AC4_MIME)
)
}
+2
View File
@@ -3,6 +3,7 @@ import type { NextConfig } from "next"
const nextConfig: NextConfig = {
output: "standalone",
distDir: process.env.OTUNES_DESKTOP_BUILD === "1" ? ".next-desktop" : ".next",
outputFileTracingRoot: path.join(__dirname, "../../"),
experimental: {
// Failed navigations wait for the connection instead of reloading the
@@ -15,6 +16,7 @@ const nextConfig: NextConfig = {
},
},
images: {
unoptimized: process.env.OTUNES_DESKTOP_BUILD === "1",
minimumCacheTTL: 60,
dangerouslyAllowSVG: true,
contentDispositionType: "attachment",
+16 -1
View File
@@ -3,6 +3,11 @@ import {
createRouteMatcher,
nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server"
import {
NextResponse,
type NextRequest,
type NextFetchEvent,
} from "next/server"
import { getConvexServerUrl } from "@/lib/convex-server"
const isAuthPage = createRouteMatcher(["/signin", "/signup"])
@@ -18,7 +23,7 @@ const isPublic = createRouteMatcher([
"/playlist/:id",
])
export default convexAuthNextjsMiddleware(
const authMiddleware = convexAuthNextjsMiddleware(
async (request, { convexAuth }) => {
if (isPublic(request)) {
return
@@ -37,6 +42,16 @@ export default convexAuthNextjsMiddleware(
{ convexUrl: getConvexServerUrl() }
)
export default function proxy(request: NextRequest, event: NextFetchEvent) {
if (process.env.OTUNES_DESKTOP === "1") {
if (request.nextUrl.pathname === "/desktop") return NextResponse.next()
if (!process.env.PUBLIC_CONVEX_URL) {
return NextResponse.redirect(new URL("/desktop", request.url))
}
}
return authMiddleware(request, event)
}
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
}
+3 -1
View File
@@ -29,7 +29,9 @@
"**/*.tsx",
"**/*.mts",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
".next/dev/types/**/*.ts",
".next-desktop/types/**/*.ts",
".next-desktop/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}
+4 -1
View File
@@ -12,7 +12,10 @@
"start": "pnpm --filter @otunes/web start",
"lint": "pnpm -r lint",
"format": "prettier --write \"**/*.{ts,tsx}\"",
"typecheck": "pnpm -r typecheck"
"typecheck": "pnpm -r typecheck",
"dev:desktop": "pnpm --filter @otunes/desktop start",
"build:desktop": "pnpm --filter @otunes/desktop build",
"build:desktop:runtime": "pnpm --filter @otunes/desktop build:runtime"
},
"devDependencies": {
"prettier": "^3.8.3",
+1440
View File
File diff suppressed because it is too large. Load diff