AI media harness for planning, generating, and editing locally
TypeScript
Add music export formats and preview
Bittic11179c9a107
diff --git a/README.md b/README.mdindex d651242..f945b41 100644--- a/README.md+++ b/README.md@@ -32,7 +32,7 @@ Slopus combines an AI assistant, local image, video and music generation, reusab- **Generators.** Manage model weights, supported LoRAs, attention and generation effects. Share [generator templates](docs/generator-weights.md#sharing-generator-templates) as `.slop` bundles or run jobs on LAN workers.- **Timeline.** Arrange video and audio with trimming, splitting, snapping, waveforms, transitions, chroma key and GPU effects.- **Motions.** Ask the agent to create JavaScript animations, edit elements and parameters, and render them on the timeline or as reference videos.-- **Export.** Save MP4 video with H.264, VP9 or AV1 where encoders are available, or export images as JPG or PNG. Exports run in the background.+- **Export.** Save MP4 video, JPG/PNG images, or music as WAV, AAC/M4A or Opus in WebM/Ogg. Compressed formats depend on available encoders. Exports run in the background.- **Project editing.** Timeline, Video, Image, Music, References and Export views share Save, Undo and Redo. Projects and media are stored locally; agent requests go to the selected provider. API keys stay outside project files.## Setupdiff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex 409c74f..bb6a33f 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -4,6 +4,7 @@ Changes since 0.3.2.## What's new+- **Music export.** Select and preview songs in Export, then save WAV, AAC/M4A or Opus/WebM/Ogg with device-supported encoders, bitrate controls and background export.- **Single Shot.** Generate a short ending first, then anchor a continuous shot to it. Supports references in both prompts and optional continuation from any generated scene.- **Music.** YuE2 and MiniMax Music3 generation with folders, drag-and-drop organization, grid/list views, background playback, references and timeline audio. Playback appears in the Music tab and pauses when Timeline, Video or Export playback starts. YuE2 selects BF16 above 8 GiB VRAM, otherwise INT8.- **Motions.** Create JavaScript animations with the agent, edit elements and parameters, and export them on the timeline or as reference videos.diff --git a/package-lock.json b/package-lock.jsonindex 6609772..19fd6c8 100644--- a/package-lock.json+++ b/package-lock.json@@ -14,6 +14,7 @@"@tauri-apps/plugin-process": "^2.3.1","@tauri-apps/plugin-updater": "^2.11.0","clipper-lib": "^6.4.2",+ "mediabunny": "^1.62.1","mp4-muxer": "^5.2.2","mp4box": "^2.4.1","react": "^18.3.1",@@ -1798,6 +1799,15 @@"dev": true,"license": "MIT"},+ "node_modules/@types/dom-mediacapture-transform": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",+ "license": "MIT",+ "dependencies": {+ "@types/dom-webcodecs": "*"+ }+ },"node_modules/@types/dom-webcodecs": {"version": "0.1.19","resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.19.tgz",@@ -2837,6 +2847,30 @@"node": ">= 0.4"}},+ "node_modules/mediabunny": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.62.1.tgz",+ "integrity": "sha512-lYzeerDwo9QLhBCipqQDXOSV7InvaIFplllZQviPO5rPwH+IUr8M1uvumk1olIUgMRGkPiInRriv25WFErUgMw==",+ "license": "MPL-2.0",+ "workspaces": [+ ".",+ "packages/*"+ ],+ "dependencies": {+ "@types/dom-mediacapture-transform": "^0.1.11",+ "@types/dom-webcodecs": "0.1.13"+ },+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ }+ },+ "node_modules/mediabunny/node_modules/@types/dom-webcodecs": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",+ "license": "MIT"+ },"node_modules/mime-db": {"version": "1.52.0","resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",diff --git a/package.json b/package.jsonindex 352ed4b..2f80a25 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"@tauri-apps/plugin-process": "^2.3.1","@tauri-apps/plugin-updater": "^2.11.0","clipper-lib": "^6.4.2",+ "mediabunny": "^1.62.1","mp4-muxer": "^5.2.2","mp4box": "^2.4.1","react": "^18.3.1",diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rsindex a2216e9..fddde1e 100644--- a/src-tauri/src/app.rs+++ b/src-tauri/src/app.rs@@ -270,6 +270,7 @@ pub fn run() {commands::artifacts::generated_audio,commands::artifacts::release_generated_frames,export::choose_export_destination,+ export::choose_music_export_destination,export::default_export_destination,export::export_destination_exists,export::open_export_file,diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rsindex 0b23d83..c95d016 100644--- a/src-tauri/src/export.rs+++ b/src-tauri/src/export.rs@@ -93,7 +93,7 @@ fn was_chosen_this_session(path: &Path) -> bool {.unwrap_or(false)}-/// Checks the SHAPE of a destination: absolute, `.mp4`, in a folder that+/// Checks the SHAPE of a destination: absolute, a supported video/audio extension, in a folder that/// exists, not itself a folder. Necessary and not sufficient — see/// [`authorized_destination`], which is what the write actually goes through.fn checked_destination(value: &str) -> Result<PathBuf, String> {@@ -105,8 +105,8 @@ fn checked_destination(value: &str) -> Result<PathBuf, String> {.extension().and_then(|value| value.to_str()).map(str::to_ascii_lowercase);- if extension.as_deref() != Some("mp4") {- return Err(format!("{value} does not end in .mp4."));+ if !matches!(extension.as_deref(), Some("mp4" | "m4a" | "webm" | "ogg" | "wav")) {+ return Err(format!("{value} must end in .mp4, .m4a, .webm, .ogg or .wav."));}let parent = path.parent()@@ -228,6 +228,35 @@ pub struct DefaultDestination {exists: bool,}+fn music_format(format: &str) -> Result<&'static str, String> {+ match format {+ "m4a" => Ok("M4A audio"), "webm" => Ok("WebM audio"),+ "ogg" => Ok("Ogg audio"), "wav" => Ok("WAV audio"),+ _ => Err("Choose M4A, WebM, Ogg or WAV for music export.".into()),+ }+}++#[tauri::command]+pub async fn choose_music_export_destination(app: AppHandle, suggested_name: String, format: String) -> Result<Option<String>, String> {+ let label = music_format(&format)?;+ tauri::async_runtime::spawn_blocking(move || {+ let name = safe_file_name(&suggested_name);+ let name = if name.to_ascii_lowercase().ends_with(&format!(".{format}")) { name } else { format!("{name}.{format}") };+ let mut dialog = app.dialog().file().set_title("Export music").set_file_name(name).add_filter(label, &[&format]);+ if let Some(folder) = starting_folder(&app) { dialog = dialog.set_directory(folder); }+ let Some(selected) = dialog.blocking_save_file() else { return Ok(None); };+ let path = selected.into_path().map_err(|error| format!("Could not use the selected path: {error}"))?;+ // Do not silently write one container under another format's extension.+ if !path.extension().is_some_and(|extension| extension.to_string_lossy().eq_ignore_ascii_case(&format)) {+ return Err(format!("Choose a file ending in .{format}."));+ }+ checked_destination(&path.to_string_lossy())?;+ remember_destination(&path);+ remember_export_folder(&app, &path);+ Ok(Some(path.to_string_lossy().into_owned()))+ }).await.map_err(|error| format!("The save dialog stopped unexpectedly: {error}"))?+}+/// The destination the Export screen shows before the user has opened any/// dialog: the suggested name in the last export folder (or Videos). Rust/// builds the whole path itself — the webview only supplies a name, which is@@ -321,7 +350,7 @@ pub fn read_lut_file(path: String) -> Result<String, String> {Ok(String::from_utf8_lossy(&bytes).into_owned())}-/// Writes the muxed MP4 to the chosen path and reports how many bytes landed,+/// Writes the finished video/audio file to the chosen path and reports how many bytes landed,/// so the frontend can state the size of a file that demonstrably exists rather/// than the size it hoped for.#[tauri::command]@@ -350,6 +379,22 @@ mod tests {use super::*;use std::fs;+ #[test]+ fn music_formats_require_supported_extensions_and_dialog_authorization() {+ let folder = tempfile::tempdir().unwrap();+ for extension in ["m4a", "webm", "ogg", "wav"] {+ assert!(music_format(extension).is_ok());+ let path = folder.path().join(format!("song.{extension}"));+ assert!(checked_destination(&path.to_string_lossy()).is_ok());+ assert!(authorized_destination(&path.to_string_lossy()).is_err());+ remember_destination(&path);+ assert_eq!(authorized_destination(&path.to_string_lossy()).unwrap(), path);+ let other = folder.path().join(format!("other.{extension}"));+ assert!(authorized_destination(&other.to_string_lossy()).is_err());+ }+ for extension in ["exe", "mp3", "../wav", "mp4"] { assert!(music_format(extension).is_err()); }+ }+#[test]fn percent_decode_restores_a_windows_path() {assert_eq!(diff --git a/src/components/ProjectWorkspace.music.test.tsx b/src/components/ProjectWorkspace.music.test.tsxindex 4358afe..650cf54 100644--- a/src/components/ProjectWorkspace.music.test.tsx+++ b/src/components/ProjectWorkspace.music.test.tsx@@ -72,17 +72,19 @@ it("keeps music and its playlist alive across tabs, preserves position and stopsexpect(audio.pause).toHaveBeenCalled();});-it.each([["Timeline", "Timeline preview"], ["Video", "Shot"], ["Video", "Popout"], ["Export", "Export preview"]])(+it.each([["Timeline", "Timeline preview"], ["Video", "Shot"], ["Video", "Popout"], ["Export", "Export preview"], ["Export", "Music export playback"]])("pauses background music when %s playback starts (%s), then allows manual resume", async (tab, preview) => {workspace();const audio = await start();audio.currentTime = 7;fireEvent.click(screen.getByRole("tab", { name: tab }));+ if (preview === "Export preview") fireEvent.click(within(screen.getByRole("tablist", { name: "Export type" })).getByRole("tab", { name: "Video" }));expect(screen.getByRole("tab", { name: "Music Playing" })).toBeInTheDocument();fireEvent.play(screen.getByLabelText(preview));- expect(within(screen.getByRole("tab", { name: "Music" })).queryByRole("img", { name: "Playing" })).not.toBeInTheDocument();+ const musicTab = within(screen.getByRole("tablist", { name: "Project views" })).getByRole("tab", { name: "Music" });+ expect(within(musicTab).queryByRole("img", { name: "Playing" })).not.toBeInTheDocument();expect(audio.currentTime).toBe(7);- fireEvent.click(screen.getByRole("tab", { name: "Music" }));+ fireEvent.click(musicTab);expect(screen.getByRole("button", { name: "Play music" })).toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Play music" }));expect(screen.getByRole("tab", { name: "Music Playing" })).toBeInTheDocument();diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsxindex 11366d9..1664aaf 100644--- a/src/components/ProjectWorkspace.tsx+++ b/src/components/ProjectWorkspace.tsx@@ -15,6 +15,7 @@ import { AgentDock } from "./workspace/AgentDock";import { generateAgentMedia } from "../lib/agentGeneration";import { ExportView } from "./workspace/ExportView";import { ImageExportView } from "./workspace/ImageExportView";+import { MusicExportView } from "./workspace/MusicExportView";import { GeneratorView } from "./workspace/GeneratorView";import { ReferencesView } from "./workspace/ReferencesView";import { TimelineView, type ConfigUpdate } from "./workspace/TimelineView";@@ -29,7 +30,7 @@ import { outputDimensions, videoDurationMs } from "../lib/export";* a project "on the agent" still means something: the pane opens with it. */export type ProjectView = "music" | "timeline" | "generator" | "references" | "agent" | "export" | "editor";type ShownView = Exclude<ProjectView, "agent">;-export interface WorkspaceNavigation { view: ShownView; sceneId?: string; imageId?: string; songId?: string; referenceId?: string; exportKind?: "video" | "image" }+export interface WorkspaceNavigation { view: ShownView; sceneId?: string; imageId?: string; songId?: string; referenceId?: string; exportKind?: "video" | "image" | "music" }/** The scene badge includes native generation and the final encoding step. */export const isGenerationOngoing = (job: GenerationJob) =>@@ -126,10 +127,11 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,const [view, setShownView] = useState<ShownView>(openingView);const [musicVisited, setMusicVisited] = useState(openingView === "music");const [musicPlaying, setMusicPlaying] = useState(false);- const [mediaMode, setMediaMode] = useState<"video" | "image">(() => openingView === "editor" || ((openingView === "references" || openingView === "export") && config.generationType === "image") ? "image" : "video");+ const [mediaMode, setMediaMode] = useState<"video" | "image" | "music">(() => openingView === "music" ? "music" : openingView === "editor" || ((openingView === "references" || openingView === "export") && config.generationType === "image") ? "image" : "video");const setView = (next: ShownView) => {if (next === "music") setMusicVisited(true);if (next === "editor") setMediaMode("image");+ else if (next === "music") setMediaMode("music");else if (next === "generator" || next === "timeline") setMediaMode("video");setShownView(next);};@@ -304,8 +306,8 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,{view === "generator" && <GeneratorView onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onSelectedJobChange={setSelectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}{view === "references" && <ReferencesView openReference={referenceNavigation} onReferenceOpened={() => setReferenceNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onRegenerateIcon={(id) => queue.regenerateReferenceIcon(session, id)} onExportRefmod={(id, outputPath) => queue.exportReferenceRefmod(session, id, outputPath)} onGenerateBuiltinIcons={() => queue.generateBuiltinReferenceIcons(session)} onRegenerateBuiltinIcon={(id) => queue.regenerateBuiltinReferenceIcon(session, id)} pendingBuiltinIconIds={queue.pendingBuiltinIconIds()} pendingIconIds={new Set(config.references.filter((reference) => queue.isReferenceIconPending(session, reference.id)).map((reference) => reference.id))} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}{view === "export" && <div className="project-export">- <SelectorBar aria-label="Export type" className="project-export__types" value={mediaMode} onChange={setMediaMode} items={[{ value: "video", label: "Video" }, { value: "image", label: "Image" }]} />- {mediaMode === "image"+ <SelectorBar aria-label="Export type" className="project-export__types" value={mediaMode} onChange={setMediaMode} items={[{ value: "video", label: "Video" }, { value: "image", label: "Image" }, { value: "music", label: "Music" }]} />+ {mediaMode === "music" ? <MusicExportView config={config} folderPath={project.folderPath} /> : mediaMode === "image"? <ImageExportView config={config} folderPath={project.folderPath} />: <ExportView config={config} folderPath={project.folderPath} onClose={() => setView("timeline")} />}</div>}@@ -315,7 +317,7 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,survive the pane being closed. */}<aside ref={agentPaneRef} id={`${panelId}-agent`} className="project-agent-pane" aria-label="Agent" hidden={!agentOpen}><AgentDock- mode={mediaMode}+ mode={mediaMode === "image" ? "image" : "video"}context={view === "music" ? "the music library" : view === "editor" ? "this image composition" : view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : view === "references" ? "project references" : "this export"}record={{ ...project, config }}providers={runtime?.providers ?? CHECKING_PROVIDERS}diff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsxindex 32fa816..7e212c6 100644--- a/src/components/WorkQueuePanel.tsx+++ b/src/components/WorkQueuePanel.tsx@@ -26,7 +26,7 @@ function StateGlyph({ item }: { item: WorkItem }) {export type WorkQueueTarget = { kind: "work"; item: WorkItem }| { kind: "download"; download: DownloadState }- | { kind: "export"; folderPath: string; exportKind?: "video" | "image" };+ | { kind: "export"; folderPath: string; exportKind?: "video" | "image" | "music" };export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClose, onNavigate }: {queue: WorkQueue;@@ -80,7 +80,7 @@ export function WorkQueuePanel({ queue, items, open = true, anchor = null, onClo{items.length === 0 && !download && !queuedDownloads.length && !exports.length && <div className="work-queue__empty"><WorkQueue32 aria-hidden="true" /><strong>No work yet</strong><span>Generation, exports, and downloads show up here.</span></div>}{current.length > 0 && <section aria-label="In progress"><ul>{current.map(row)}</ul></section>}{exports.length > 0 && <section aria-label="Export"><ul>{exports.map((exportJob) => {- const exportTitle = exportJob.kind === "image" ? `Export image · ${exportJob.projectName}` : `Export ${exportJob.projectName ?? ""}`;+ const exportTitle = exportJob.kind === "image" ? `Export image · ${exportJob.projectName}` : exportJob.kind === "music" ? `Export music · ${exportJob.projectName}` : `Export ${exportJob.projectName ?? ""}`;const exporting = exportJob.progress;const exportPercent = Math.floor(exportFraction(exporting) * 100);return <li key={exportJob.id} className={`work-queue__row${onNavigate && exportJob.folderPath ? " work-queue__row--navigable" : ""}`}>diff --git a/src/components/workspace/MusicExportView.test.tsx b/src/components/workspace/MusicExportView.test.tsxnew file mode 100644index 0000000..befae63--- /dev/null+++ b/src/components/workspace/MusicExportView.test.tsx@@ -0,0 +1,79 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom/vitest";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { invoke } from "@tauri-apps/api/core";+import { MusicExportView } from "./MusicExportView";+import { createProjectConfig } from "../../lib/project";+import { newSong } from "../../lib/music";+import { musicExportSupport } from "../../lib/musicExport";+import { startMusicExportJob } from "../../lib/exportJob";+import { readMediaFileUrl } from "../../lib/persistence";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));+vi.mock("../../lib/persistence", () => ({ isTauri: () => true, readMediaFileUrl: vi.fn(async () => "blob:music") }));+vi.mock("../../lib/musicExport", async (original) => ({ ...await original<typeof import("../../lib/musicExport")>(), musicExportSupport: vi.fn(async () => true) }));+vi.mock("../../lib/exportJob", () => ({ startMusicExportJob: vi.fn(), useExportJob: () => ({ status: "completed", progress: null, outcome: null }), isExportActive: () => false,+ dismissExportOutcome: vi.fn(), exportFraction: () => 0, cancelExportJob: vi.fn() }));+beforeEach(() => {+ localStorage.clear(); vi.clearAllMocks();+ vi.mocked(musicExportSupport).mockResolvedValue(true);+ vi.mocked(invoke).mockResolvedValue("D:/song.m4a");+ vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});+ vi.stubGlobal("URL", Object.assign(URL, { revokeObjectURL: vi.fn() }));+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });+function config() {+ const config = createProjectConfig({ name: "Music", prompt: "", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 });+ config.musicFolders = [{ id: "jazz", name: "Jazz" }];+ config.musicSongs = [{ ...newSong(), title: "Draft" }, { ...newSong("yue2", 32, "jazz"), title: "Evening", assetId: "audio" }, { ...newSong(), title: "Morning", assetId: "second" }];+ config.assets = ["audio", "second"].map((id) => ({ id, kind: "audio", name: id, mimeType: "audio/wav", relativePath: `media/${id}.wav`, createdAt: config.createdAt, durationMs: 30000 }));+ return config;+}++it("exports the selected generated song and format, remembering preferences", async () => {+ const project = config();+ render(<MusicExportView config={project} folderPath="D:/Music" />);+ expect(screen.queryByRole("button", { name: /Export song Draft/ })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Export song Jazz / Evening" })).toHaveAttribute("aria-pressed", "true");+ await waitFor(() => expect(screen.getByRole("button", { name: "Export…" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Export song Morning" }));+ fireEvent.click(screen.getByRole("combobox", { name: "Format" }));+ fireEvent.click(screen.getByRole("option", { name: "M4A · AAC" }));+ fireEvent.click(screen.getByRole("combobox", { name: "Bitrate" }));+ fireEvent.click(screen.getByRole("option", { name: "256 kbps" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Export…" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Export…" }));+ await waitFor(() => expect(startMusicExportJob).toHaveBeenCalledWith(expect.objectContaining({ title: "Morning", asset: project.assets[1], settings: { format: "m4a", bitrate: 256000 }, destination: "D:/song.m4a" })));+ expect(invoke).toHaveBeenCalledWith("choose_music_export_destination", { suggestedName: "Morning", format: "m4a" });+ expect(JSON.parse(localStorage.getItem("slopus.music-export.v1")!)).toEqual({ format: "m4a", bitrate: 256000 });+ expect(readMediaFileUrl).toHaveBeenCalledWith("D:/Music", project.assets[1], "audio/wav");+});++it("disables unsupported encoders and does not queue when the save dialog is cancelled", async () => {+ vi.mocked(musicExportSupport).mockImplementation(async (format) => format === "wav");+ vi.mocked(invoke).mockResolvedValue(null);+ render(<MusicExportView config={config()} folderPath="D:/Music" />);+ await waitFor(() => expect(screen.getByRole("button", { name: "Export…" })).toBeEnabled());+ fireEvent.click(screen.getByRole("combobox", { name: "Format" }));+ expect(screen.getByRole("option", { name: /M4A/ })).toHaveAttribute("aria-disabled", "true");+ expect(screen.getByRole("option", { name: /WebM/ })).toHaveAttribute("aria-disabled", "true");+ fireEvent.keyDown(screen.getByRole("combobox", { name: "Format" }), { key: "Escape" });+ fireEvent.click(screen.getByRole("button", { name: "Export…" }));+ await waitFor(() => expect(invoke).toHaveBeenCalled());+ expect(startMusicExportJob).not.toHaveBeenCalled();+});++it("has an empty state for drafts and stops preview playback on unmount", async () => {+ const draft = config(); draft.assets = [];+ const empty = render(<MusicExportView config={draft} folderPath="D:/Music" />);+ expect(screen.getByText("No music to export yet")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Export…" })).toBeDisabled();+ empty.unmount();+ const view = render(<MusicExportView config={config()} folderPath="D:/Music" />);+ await waitFor(() => expect(screen.getByLabelText("Music export playback")).toHaveAttribute("src", "blob:music"));+ const audio = screen.getByLabelText("Music export playback") as HTMLAudioElement;+ vi.mocked(audio.pause).mockClear(); view.unmount();+ expect(audio.pause).toHaveBeenCalled();+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:music");+});diff --git a/src/components/workspace/MusicExportView.tsx b/src/components/workspace/MusicExportView.tsxnew file mode 100644index 0000000..aa9d8cc--- /dev/null+++ b/src/components/workspace/MusicExportView.tsx@@ -0,0 +1,113 @@+import { invoke } from "@tauri-apps/api/core";+import { useEffect, useRef, useState } from "react";+import type { ProjectConfig } from "../../lib/project";+import { isTauri, readMediaFileUrl } from "../../lib/persistence";+import { MUSIC_EXPORT_BITRATES, MUSIC_EXPORT_FORMATS, musicExportSongs, musicExportSupport, type MusicExportFormat, type MusicExportSettings } from "../../lib/musicExport";+import { cancelExportJob, dismissExportOutcome, exportFraction, isExportActive, startMusicExportJob, useExportJob } from "../../lib/exportJob";+import { ComboBox, EmptyState, InfoBar, ProgressBar, PropRow, PropSection, Splitter, usePaneSize } from "../ui";+import { Audio16 } from "../ui/icons";++const STORAGE_KEY = "slopus.music-export.v1";+function loadPreferences(): MusicExportSettings {+ try {+ const value = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}");+ return { format: MUSIC_EXPORT_FORMATS.some((item) => item.value === value.format) ? value.format : "wav",+ bitrate: MUSIC_EXPORT_BITRATES.some((item) => Number(item.value) === value.bitrate) ? value.bitrate : 192000 };+ } catch { return { format: "wav", bitrate: 192000 }; }+}++export function MusicExportView({ config, folderPath }: { config: ProjectConfig; folderPath: string }) {+ const pane = usePaneSize("export.settings", 340, { min: 280, max: 560 });+ const songs = musicExportSongs(config);+ const [selectedId, setSelectedId] = useState<string>();+ const selected = songs.find(({ song }) => song.id === selectedId) ?? songs[0];+ const [settings, setSettings] = useState(loadPreferences);+ const [support, setSupport] = useState<Partial<Record<MusicExportFormat, boolean>>>({});+ const [choosing, setChoosing] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [url, setUrl] = useState<string | null>(null);+ const audio = useRef<HTMLAudioElement>(null);+ const job = useExportJob(folderPath, "music");+ const active = isExportActive(job);+ const choose = (patch: Partial<MusicExportSettings>) => {+ const next = { ...settings, ...patch }; setSettings(next);+ try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } catch { /* Keep the session preference. */ }+ };+ useEffect(() => {+ let disposed = false; setSupport({});+ void Promise.all(MUSIC_EXPORT_FORMATS.map(async ({ value }) => [value, await musicExportSupport(value, settings.bitrate)] as const))+ .then((entries) => { if (!disposed) setSupport(Object.fromEntries(entries)); });+ return () => { disposed = true; };+ }, [settings.bitrate]);+ useEffect(() => {+ let disposed = false, owned: string | null = null;+ const player = audio.current;+ player?.pause(); setUrl(null); setError(null);+ if (selected) void readMediaFileUrl(folderPath, selected.asset, selected.asset.mimeType ?? "audio/wav").then((value) => {+ if (disposed) { if (value) URL.revokeObjectURL(value); return; }+ owned = value; setUrl(value);+ if (!value) setError("This song's audio file is unavailable.");+ }).catch((reason) => { if (!disposed) setError(String(reason)); });+ return () => { disposed = true; player?.pause(); if (owned) URL.revokeObjectURL(owned); };+ }, [folderPath, selected?.asset.id, selected?.asset.relativePath]);+ const blocker = !selected ? "Generate a song in Music before exporting."+ : !isTauri() ? "Exporting is available in the Slopus desktop app."+ : support[settings.format] === undefined ? "Checking available audio formats…"+ : !support[settings.format] ? "This format is unavailable on this device. Choose another format." : null;+ const exportSong = async () => {+ if (!selected || blocker || choosing) return;+ setChoosing(true); setError(null);+ const captured = { folderPath, projectName: config.name, asset: structuredClone(selected.asset), title: selected.song.title, settings: { ...settings } };+ try {+ const destination = await invoke<string | null>("choose_music_export_destination", { suggestedName: captured.title, format: captured.settings.format });+ if (destination) void startMusicExportJob({ ...captured, destination });+ } catch (reason) { setError(String(reason)); }+ finally { setChoosing(false); }+ };++ return <div className="export-view" style={pane.style}>+ <h1 className="sr-only">Export music</h1>+ <div className="export-body">+ <section className="export-preview" aria-label="Music export preview">+ <div className="music-export-library">+ {songs.length ? <div className="music-songs music-songs--list" role="list" aria-label="Songs to export">+ {songs.map(({ song, asset, label }) => <div role="listitem" key={song.id} className={`music-song music-song--playable${selected?.song.id === song.id ? " music-song--selected" : ""}`}>+ <button type="button" className="music-song__select" aria-label={`Export song ${label}`} aria-pressed={selected?.song.id === song.id} onClick={() => setSelectedId(song.id)}>+ <span className="music-song__art" aria-hidden="true"><Audio16 /></span>+ <span className="music-song__info"><strong>{label}</strong><span>{song.style}</span></span>+ <span className="music-song__status">{((asset.durationMs ?? 0) / 1000).toFixed(1)} s</span>+ </button>+ </div>)}+ </div> : <EmptyState icon={<Audio16 />} title="No music to export yet" description="Generate a song in the Music tab first." />}+ </div>+ {selected && <div className="music-export-player"><span>{selected.song.title}</span><audio ref={audio} aria-label="Music export playback" controls src={url ?? undefined} preload="metadata" onError={() => { if (url) setError("This song could not be played."); }} /></div>}+ </section>+ <Splitter {...pane.splitterProps} reverse aria-label="Resize export settings" aria-controls="music-export-settings" />+ <section id="music-export-settings" className="export-settings" aria-label="Export settings">+ <div className="export-settings__scroll">+ <PropSection title="Output" persistKey="export.music.output">+ <PropRow label="Format" htmlFor="music-export-format"><ComboBox id="music-export-format" value={settings.format} disabled={choosing}+ onChange={(format) => choose({ format: format as MusicExportFormat })}+ options={MUSIC_EXPORT_FORMATS.map(({ value, label }) => ({ value, label, disabled: support[value] !== true,+ description: support[value] === false ? "Unavailable on this device" : support[value] === undefined ? "Checking support…" : undefined }))} /></PropRow>+ {settings.format !== "wav" && <PropRow label="Bitrate" htmlFor="music-export-bitrate"><ComboBox id="music-export-bitrate" value={String(settings.bitrate)} options={MUSIC_EXPORT_BITRATES} disabled={choosing} onChange={(value) => choose({ bitrate: Number(value) })} /></PropRow>}+ <PropRow label="Sample rate"><span>48 kHz</span></PropRow>+ </PropSection>+ <div className="export-messages">+ {blocker && <InfoBar message={blocker} />}+ {active && <InfoBar title={job.status === "queued" ? "Queued for export" : "Exporting music"} message={job.progress?.detail ?? "Waiting for the current export to finish."} />}+ {job.progress && <ProgressBar aria-label="Music export progress" value={exportFraction(job.progress) * 100} />}+ {job.outcome?.kind === "saved" && <InfoBar severity="success" title="Music exported" message={job.outcome.path} onClose={() => dismissExportOutcome(job.id)} />}+ {job.outcome?.kind === "failed" && <InfoBar severity="error" title="Couldn’t export music" message={job.outcome.message} onClose={() => dismissExportOutcome(job.id)} />}+ {job.outcome?.kind === "cancelled" && <InfoBar title="Export cancelled" onClose={() => dismissExportOutcome(job.id)} />}+ {error && <InfoBar severity="error" title="Couldn’t export music" message={error} onClose={() => setError(null)} />}+ </div>+ </div>+ <div className="export-settings__foot"><div className="export-settings__actions">+ {active && <button type="button" className="secondary-button" disabled={job.cancelling || job.progress?.phase === "writing"} onClick={() => cancelExportJob(job.id)}>Cancel export</button>}+ <button type="button" className="primary-button" disabled={Boolean(blocker) || choosing} onClick={() => void exportSong()}>{choosing ? "Choosing destination…" : "Export…"}</button>+ </div></div>+ </section>+ </div>+ </div>;+}diff --git a/src/lib/exportJob.test.ts b/src/lib/exportJob.test.tsindex 8c771d5..df4ad7c 100644--- a/src/lib/exportJob.test.ts+++ b/src/lib/exportJob.test.ts@@ -5,11 +5,13 @@ import { listen } from "@tauri-apps/api/event";import { createProjectConfig } from "./project";import { defaultExportSettings, buildExportPlan } from "./export";import { runExport, writeExportFile, type ExportProgress, type ExportResult } from "./exportPipeline";-import { cancelExportJob, clearFinishedExports, getExportJobs, resetExportJobForTests, startExportJob, startImageExportJob, startMotionReferenceJob } from "./exportJob";+import { cancelExportJob, clearFinishedExports, getExportJobs, resetExportJobForTests, startExportJob, startImageExportJob, startMotionReferenceJob, startMusicExportJob } from "./exportJob";+import { runMusicExport } from "./musicExport";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));vi.mock("./nativeShell", () => ({ setTaskbarProgress: vi.fn(async () => undefined) }));+vi.mock("./musicExport", () => ({ runMusicExport: vi.fn() }));vi.mock("./exportPipeline", async (original) => ({ ...await original<typeof import("./exportPipeline")>(), runExport: vi.fn(), writeExportFile: vi.fn(async () => 42) }));beforeEach(() => { resetExportJobForTests(); vi.clearAllMocks(); vi.mocked(invoke).mockResolvedValue(24); });@@ -21,6 +23,29 @@ const video = () => {return { folderPath: "D:/Movie", config, settings, plan: buildExportPlan(config, settings), bitrate: 1000, destination: "D:/movie.mp4" };};+it("queues music with other exports, snapshots the song and cancels before writing", async () => {+ let finishVideo!: (result: ExportResult) => void, finishMusic!: (bytes: Uint8Array) => void;+ vi.mocked(runExport).mockImplementation(() => new Promise((resolve) => { finishVideo = resolve; }));+ vi.mocked(runMusicExport).mockImplementation(() => new Promise((resolve) => { finishMusic = resolve; }));+ const first = startExportJob(video());+ const options = { folderPath: "D:/Music", projectName: "Music", title: "Evening", asset: { id: "audio", kind: "audio" as const, name: "Evening", mimeType: "audio/wav", relativePath: "media/song.wav", createdAt: "now" }, settings: { format: "wav" as const, bitrate: 192000 }, destination: "D:/evening.wav" };+ const second = startMusicExportJob(options);+ options.asset.relativePath = "changed.wav"; options.settings.bitrate = 96000;+ expect(getExportJobs().map((job) => [job.kind, job.status])).toEqual([["video", "running"], ["music", "queued"]]);+ finishVideo(result); await first;+ await vi.waitFor(() => expect(runMusicExport).toHaveBeenCalled());+ expect(runMusicExport).toHaveBeenCalledWith(expect.objectContaining({ asset: expect.objectContaining({ relativePath: "media/song.wav" }), settings: { format: "wav", bitrate: 192000 } }));+ cancelExportJob(getExportJobs()[1].id);+ expect(vi.mocked(runMusicExport).mock.calls[0][0].cancelled()).toBe(true);+ finishMusic(new Uint8Array([1, 2])); await second;+ expect(getExportJobs()[1].status).toBe("cancelled");+ expect(writeExportFile).toHaveBeenCalledTimes(1);+ vi.mocked(runMusicExport).mockResolvedValue(new Uint8Array([1, 2]));+ await startMusicExportJob(options);+ expect(writeExportFile).toHaveBeenLastCalledWith("D:/evening.wav", new Uint8Array([1, 2]));+ expect(getExportJobs()[2]).toMatchObject({ kind: "music", status: "completed", outcome: { kind: "saved", bytes: 42 } });+});+it("queues image and video exports together, snapshots settings, and retains their results", async () => {let finish!: (result: ExportResult) => void;vi.mocked(runExport).mockImplementation(() => new Promise((resolve) => { finish = resolve; }));diff --git a/src/lib/exportJob.ts b/src/lib/exportJob.tsindex 95c1f78..603e424 100644--- a/src/lib/exportJob.ts+++ b/src/lib/exportJob.ts@@ -1,4 +1,4 @@-/* Export jobs live independently of their views. Images and videos share one+/* Export jobs live independently of their views. Images, videos and music share oneserial queue, and retain their results in Work Queue after completion.The Export screen used to own its run, so leaving the tab unmounted the@@ -20,6 +20,7 @@ import type { ExportPlan, ExportSettings } from "./export";import { ExportCancelled, runExport, writeExportFile, type ExportProgress } from "./exportPipeline";import { setTaskbarProgress } from "./nativeShell";import type { ProjectConfig } from "./project";+import { runMusicExport, type RunMusicExportOptions } from "./musicExport";export type ExportOutcome =| { kind: "saved"; path: string; bytes: number; audioProblems: string[]; audioShortfalls: string[] }@@ -28,7 +29,7 @@ export type ExportOutcome =export interface ExportJobState {id: string | null;- kind: "video" | "image";+ kind: "video" | "image" | "music";status: "queued" | "running" | "completed" | "cancelled" | "failed";/** The project folder the run (or its outcome) belongs to. */folderPath: string | null;@@ -69,7 +70,7 @@ export function subscribeExportJob(listener: () => void): () => void {return () => { listeners.delete(listener); };}-export function useExportJob(folderPath?: string, kind?: "video" | "image"): ExportJobState {+export function useExportJob(folderPath?: string, kind?: ExportJobState["kind"]): ExportJobState {const snapshot = () => folderPath ? jobs.find((job) => job.folderPath === folderPath && job.kind === kind && isExportActive(job))?? [...jobs].reverse().find((job) => job.folderPath === folderPath && job.kind === kind) ?? IDLE : state;return useSyncExternalStore(subscribeExportJob, snapshot, snapshot);@@ -228,6 +229,30 @@ async function runVideoExport(options: StartExportOptions): Promise<void> {}export interface ImageExportOptions { format: "jpg" | "png"; width?: number; height?: number; quality?: number; upscale?: UpscaleConfig }++export interface StartMusicExportOptions extends Omit<RunMusicExportOptions, "cancelled" | "onProgress"> { projectName: string; destination: string }+export function startMusicExportJob(options: StartMusicExportOptions): Promise<void> {+ const snapshot = structuredClone(options);+ return enqueueExport({ folderPath: snapshot.folderPath, projectName: snapshot.projectName, destination: snapshot.destination, kind: "music" }, async () => {+ void setTaskbarProgress(0).catch(() => undefined);+ try {+ const bytes = await runMusicExport({ ...snapshot, cancelled: () => cancelRequested, onProgress: (progress) => {+ set({ progress });+ void setTaskbarProgress(exportFraction(progress)).catch(() => undefined);+ } });+ if (cancelRequested) throw new ExportCancelled();+ set({ progress: { phase: "writing", framesDone: 1, frameCount: 1, detail: "Writing audio file…" } });+ const written = await writeExportFile(snapshot.destination, bytes);+ set({ progress: null, outcome: { kind: "saved", path: snapshot.destination, bytes: written, audioProblems: [], audioShortfalls: [] } });+ void setTaskbarProgress(null).catch(() => undefined);+ } catch (reason) {+ const cancelled = cancelRequested || reason instanceof ExportCancelled;+ set({ progress: null, outcome: cancelled ? { kind: "cancelled" } : { kind: "failed", message: String(reason) } });+ void setTaskbarProgress(cancelled ? null : 1, cancelled ? undefined : "error").catch(() => undefined);+ }+ });+}+export interface StartImageExportOptions { folderPath: string; projectName: string; relativePath: string; destination: string; options: ImageExportOptions }export function startImageExportJob(options: StartImageExportOptions): Promise<void> {const snapshot = structuredClone(options);diff --git a/src/lib/musicExport.test.ts b/src/lib/musicExport.test.tsnew file mode 100644index 0000000..ae8bd14--- /dev/null+++ b/src/lib/musicExport.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { musicExportSongs, musicExportSupport, runMusicExport, type RunMusicExportOptions } from "./musicExport";+import { readMediaFileBytes } from "./persistence";+import { createProjectConfig } from "./project";+import { newSong } from "./music";+import { ExportCancelled } from "./exportPipeline";++vi.mock("./persistence", () => ({ readMediaFileBytes: vi.fn(async () => new ArrayBuffer(1)) }));+const frames = 20000;+const channels = [new Float32Array(frames).fill(0.25), new Float32Array(frames).fill(-0.5)];+beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("OfflineAudioContext", class { async decodeAudioData() { return { length: frames, sampleRate: 48000, numberOfChannels: 2, getChannelData: (index: number) => channels[index] }; } });+});+afterEach(() => vi.unstubAllGlobals());+const options = (): RunMusicExportOptions => ({ folderPath: "D:/Music", asset: { id: "audio", kind: "audio", name: "Song", mimeType: "audio/wav", relativePath: "media/song.wav", createdAt: "now" },+ title: "Song", settings: { format: "wav", bitrate: 192000 }, cancelled: () => false, onProgress: vi.fn() });++it("exports real stereo PCM WAV with complete samples and a valid header", async () => {+ const request = options();+ const bytes = await runMusicExport(request);+ const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const tag = (at: number) => new TextDecoder().decode(bytes.subarray(at, at + 4));+ expect(tag(0)).toBe("RIFF"); expect(tag(8)).toBe("WAVE");+ expect(data.getUint32(4, true)).toBe(bytes.length - 8);+ let format = false, samples = false;+ for (let at = 12; at + 8 <= bytes.length;) {+ const length = data.getUint32(at + 4, true), start = at + 8;+ if (tag(at) === "fmt ") {+ format = true;+ expect(data.getUint16(start, true)).toBe(1);+ expect(data.getUint16(start + 2, true)).toBe(2);+ expect(data.getUint32(start + 4, true)).toBe(48000);+ expect(data.getUint16(start + 14, true)).toBe(16);+ }+ if (tag(at) === "data") {+ samples = true; expect(length).toBe(frames * 4);+ expect(data.getInt16(start, true)).toBeCloseTo(8192, -1);+ expect(data.getInt16(start + 2, true)).toBeCloseTo(-16384, -1);+ expect(data.getInt16(start + length - 2, true)).toBeCloseTo(-16384, -1);+ }+ at = start + length + (length % 2);+ }+ expect(format && samples).toBe(true);+ expect(request.onProgress).toHaveBeenCalledWith(expect.objectContaining({ phase: "finishing", framesDone: frames }));+});++it("probes native encoding support at the selected bitrate and rejects unavailable compressed formats", async () => {+ vi.stubGlobal("AudioData", class {});+ const support = vi.fn(async (config: AudioEncoderConfig) => ({ supported: config.codec === "opus" && config.bitrate === 192000 }));+ vi.stubGlobal("AudioEncoder", class { static isConfigSupported = support; });+ expect(await musicExportSupport("m4a", 192000)).toBe(false);+ expect(await musicExportSupport("webm", 192000)).toBe(true);+ expect(await musicExportSupport("ogg", 192000)).toBe(true);+ expect(await musicExportSupport("webm", 320000)).toBe(false);+ expect(await musicExportSupport("wav", 192000)).toBe(true);+ expect(support).toHaveBeenCalledWith({ codec: "mp4a.40.2", sampleRate: 48000, numberOfChannels: 2, bitrate: 192000 });+ await expect(runMusicExport({ ...options(), settings: { format: "m4a", bitrate: 192000 } })).rejects.toThrow(/cannot be encoded/);+ expect(readMediaFileBytes).not.toHaveBeenCalled();+});++it("cancels before reading and during encoding without returning a partial file", async () => {+ await expect(runMusicExport({ ...options(), cancelled: () => true })).rejects.toBeInstanceOf(ExportCancelled);+ expect(readMediaFileBytes).not.toHaveBeenCalled();+ let cancelled = false;+ await expect(runMusicExport({ ...options(), cancelled: () => cancelled, onProgress: (progress) => { if (progress.phase === "rendering") cancelled = true; } })).rejects.toBeInstanceOf(ExportCancelled);+});++it("lists generated songs across folders, excluding drafts and missing audio", () => {+ const config = createProjectConfig({ name: "Music", prompt: "", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 });+ const song = { ...newSong("yue2", 32, "jazz"), title: "Evening", assetId: "audio" };+ config.musicFolders = [{ id: "jazz", name: "Jazz" }];+ config.musicSongs = [newSong(), song, { ...newSong(), assetId: "missing", status: "completed" }];+ config.assets = [options().asset];+ expect(musicExportSongs(config)).toEqual([{ song, asset: config.assets[0], label: "Jazz / Evening" }]);+});diff --git a/src/lib/musicExport.ts b/src/lib/musicExport.tsnew file mode 100644index 0000000..beb71bf--- /dev/null+++ b/src/lib/musicExport.ts@@ -0,0 +1,104 @@+import type { AudioCodec } from "mediabunny";+import type { ProjectAsset, ProjectConfig } from "./project";+import { musicFolderLabel } from "./music";+import { readMediaFileBytes } from "./persistence";+import { ExportCancelled, type ExportProgress } from "./exportPipeline";+import { finishCodec } from "./codecWait";++export type MusicExportFormat = "m4a" | "webm" | "ogg" | "wav";+export interface MusicExportSettings { format: MusicExportFormat; bitrate: number }+export const MUSIC_EXPORT_FORMATS: readonly { value: MusicExportFormat; label: string; codec: AudioCodec; nativeCodec?: string }[] = [+ { value: "m4a", label: "M4A · AAC", codec: "aac", nativeCodec: "mp4a.40.2" },+ { value: "webm", label: "WebM · Opus", codec: "opus", nativeCodec: "opus" },+ { value: "ogg", label: "Ogg · Opus", codec: "opus", nativeCodec: "opus" },+ { value: "wav", label: "WAV · 16-bit PCM", codec: "pcm-s16" },+];+export const MUSIC_EXPORT_BITRATES = [96, 128, 192, 256, 320].map((value) => ({ value: String(value * 1000), label: `${value} kbps` }));+export const MUSIC_EXPORT_SAMPLE_RATE = 48_000;++export function musicExportSongs(config: ProjectConfig) {+ return (config.musicSongs ?? []).flatMap((song) => {+ const asset = config.assets.find((asset) => asset.id === song.assetId && asset.kind === "audio" && asset.relativePath);+ if (!asset) return [];+ const folder = song.folderId ? musicFolderLabel(config.musicFolders ?? [], song.folderId) : "";+ return [{ song, asset, label: folder ? `${folder} / ${song.title}` : song.title }];+ });+}++/** Probe encoding, not decoding: a playable codec need not be exportable. */+export async function musicExportSupport(format: MusicExportFormat, bitrate: number, channels = 2): Promise<boolean> {+ const choice = MUSIC_EXPORT_FORMATS.find((item) => item.value === format);+ if (!choice || typeof OfflineAudioContext === "undefined") return false;+ if (!choice.nativeCodec) return true;+ if (typeof AudioEncoder === "undefined" || typeof AudioData === "undefined") return false;+ try {+ return Boolean((await AudioEncoder.isConfigSupported({ codec: choice.nativeCodec, sampleRate: MUSIC_EXPORT_SAMPLE_RATE,+ numberOfChannels: channels, bitrate })).supported);+ } catch { return false; }+}++export interface RunMusicExportOptions {+ folderPath: string; asset: ProjectAsset; title: string; settings: MusicExportSettings;+ cancelled: () => boolean; onProgress: (progress: ExportProgress) => void;+}++export async function runMusicExport(options: RunMusicExportOptions): Promise<Uint8Array> {+ const check = () => { if (options.cancelled()) throw new ExportCancelled(); };+ check();+ if (!MUSIC_EXPORT_BITRATES.some((item) => Number(item.value) === options.settings.bitrate)) throw new Error("Choose a supported music bitrate.");+ const choice = MUSIC_EXPORT_FORMATS.find((item) => item.value === options.settings.format);+ if (!choice || !await musicExportSupport(choice.value, options.settings.bitrate)) throw new Error("This audio format cannot be encoded on this device. Choose another format.");+ options.onProgress({ phase: "preparing", framesDone: 0, frameCount: 1, detail: "Reading song…" });+ const bytes = await readMediaFileBytes(options.folderPath, options.asset);+ check();+ options.onProgress({ phase: "mixing", framesDone: 0, frameCount: 1, detail: "Decoding audio…" });+ // Web Audio resamples to 48 kHz. This matches Opus's output clock and keeps+ // support probing and encoding on the same sample rate for every format.+ let decoded = await new OfflineAudioContext(2, 1, MUSIC_EXPORT_SAMPLE_RATE).decodeAudioData(bytes);+ check();+ if (!decoded.length) throw new Error("The song contains no audio samples.");+ if (decoded.numberOfChannels > 2) {+ const context = new OfflineAudioContext(2, decoded.length, decoded.sampleRate);+ const source = context.createBufferSource(); source.buffer = decoded; source.connect(context.destination); source.start();+ decoded = await context.startRendering();+ check();+ }+ if (!await musicExportSupport(choice.value, options.settings.bitrate, decoded.numberOfChannels)) throw new Error("This audio format cannot encode the song's channels. Choose another format.");+ const { Output, BufferTarget, Mp4OutputFormat, WebMOutputFormat, OggOutputFormat, WavOutputFormat, AudioSampleSource, AudioSample, Quality } = await import("mediabunny");+ check();+ const format = choice.value === "m4a" ? new Mp4OutputFormat({ fastStart: "in-memory" })+ : choice.value === "webm" ? new WebMOutputFormat() : choice.value === "ogg" ? new OggOutputFormat() : new WavOutputFormat();+ const output = new Output({ format, target: new BufferTarget() });+ let packets = 0;+ const source = new AudioSampleSource({ codec: choice.codec, ...(choice.nativeCodec ? { quality: new Quality({ bitrate: options.settings.bitrate }) } : {}), onEncodedPacket: () => { packets++; } });+ output.addAudioTrack(source, { name: options.title });+ output.setMetadataTags({ title: options.title });+ const waiting = { stage: "Music encoding", check, progress: () => packets };+ try {+ await output.start();+ const channels = Array.from({ length: decoded.numberOfChannels }, (_, index) => decoded.getChannelData(index));+ const block = 16_384;+ for (let offset = 0; offset < decoded.length; offset += block) {+ check();+ const count = Math.min(block, decoded.length - offset);+ const planar = new Float32Array(count * channels.length);+ channels.forEach((channel, index) => planar.set(channel.subarray(offset, offset + count), index * count));+ const sample = new AudioSample({ format: "f32-planar", sampleRate: decoded.sampleRate, numberOfChannels: channels.length,+ timestamp: offset / decoded.sampleRate, data: planar });+ try { await finishCodec(source.add(sample), waiting); } finally { sample.close(); }+ options.onProgress({ phase: "rendering", framesDone: offset + count, frameCount: decoded.length, detail: `Encoding ${choice.label}…` });+ // PCM encoding may resolve synchronously; yield for progress and Cancel.+ if (offset % (block * 8) === 0) await new Promise<void>((resolve) => setTimeout(resolve, 0));+ }+ check();+ source.close();+ options.onProgress({ phase: "finishing", framesDone: decoded.length, frameCount: decoded.length, detail: "Finishing audio file…" });+ await finishCodec(output.finalize(), waiting);+ check();+ if (!output.target.buffer?.byteLength) throw new Error("Audio export produced no data.");+ return new Uint8Array(output.target.buffer);+ } catch (reason) {+ await output.cancel().catch(() => undefined);+ throw reason;+ }+}diff --git a/src/styles/export.css b/src/styles/export.cssindex b46bab0..30ebf59 100644--- a/src/styles/export.css+++ b/src/styles/export.css@@ -53,6 +53,11 @@background: var(--surface-chrome);}+.music-export-library { flex: 1; min-height: 0; overflow: auto; padding: var(--space-3); }+.music-export-player { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-3); padding: var(--space-2) var(--space-3); border-top: 1px solid var(--line); background: var(--surface-pane); }+.music-export-player > span { flex: 1; min-width: 0; overflow-wrap: anywhere; }+.music-export-player audio { flex: 2; width: 100%; min-width: 160px; height: 40px; }+/* The stage is the screen plus its transport bar. It is also the element thatgoes fullscreen, so the bar comes along. */.export-stage {