mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-26 04:20:56 +01:00
feat(audio): play sounds in sync, waveforms on the timeline, Sound properties and library sounds (M5)
Stage playback plays the movie's sounds through cpal (optional default feature sound-output) and the playhead follows the audio clock; a moved playhead plays a one-frame snippet of stream sounds (scrubbing). The device opens on first need, never in screenshot runs or tests, and a failure falls back to silent wall-clock playback. Timeline rows draw each keyframe's waveform over its span, repeats included. Frame Properties gain Sound, Sync and Repeat/Loop. The Library lists sounds with Preview, Place on timeline and Delete. Import to Stage and Import to Library take WAV, OGG and MP3; Export Audio writes the soundtrack.
This commit is contained in:
1 parent
30c121d269
commit
75eabe8527
14 files changed
+659
-15
No files matched your search
@@ -7,3 +7,6 @@
|
||||
*.png binary
|
||||
# shell hooks must keep LF endings or /bin/sh rejects them
|
||||
scripts/git-hooks/* text eol=lf
|
||||
*.wav binary
|
||||
*.ogg binary
|
||||
*.mp3 binary
|
||||
+1
-1
@@ -20,7 +20,7 @@ shaders or SDK code).
|
||||
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (10 files: align, distribute, mask and masked layer) | Align panel and layer-type icons | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (32 files: tools, transport, layer toggles, folders, guide, image, text, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
|
||||
| `docs/images/` (screenshots and `sample-animation.gif`) | README | AniCraft contributors | Original work: AniCraft's own screenshots (`--screenshot`) and sample animation (`anicraft-cli gif`) | MIT OR Apache-2.0 |
|
||||
| Library symbol-kind marks, selection handles, timeline marks | UI | AniCraft contributors | Original work, drawn in code (`src/panels.rs`, `src/timeline.rs`, `src/stage.rs`) | MIT OR Apache-2.0 |
|
||||
|
||||
Generated
+143
@@ -140,6 +140,28 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "alsa"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"
|
||||
dependencies = [
|
||||
"alsa-sys",
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alsa-sys"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android-activity"
|
||||
version = "0.6.1"
|
||||
@@ -178,10 +200,12 @@ dependencies = [
|
||||
name = "anicraft"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anicraft-audio",
|
||||
"anicraft-doc",
|
||||
"anicraft-engine",
|
||||
"anicraft-geom",
|
||||
"anicraft-render",
|
||||
"cpal",
|
||||
"eframe",
|
||||
"egui",
|
||||
"fontdb",
|
||||
@@ -822,6 +846,50 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "coreaudio-rs"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"libc",
|
||||
"objc2-audio-toolbox",
|
||||
"objc2-core-audio",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpal"
|
||||
version = "0.18.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"block2 0.6.2",
|
||||
"coreaudio-rs",
|
||||
"dasp_sample",
|
||||
"jni",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"mach2",
|
||||
"ndk",
|
||||
"ndk-context",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"objc2 0.6.5",
|
||||
"objc2-audio-toolbox",
|
||||
"objc2-avf-audio",
|
||||
"objc2-core-audio",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"web-sys",
|
||||
"windows",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.3"
|
||||
@@ -868,6 +936,12 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
|
||||
|
||||
[[package]]
|
||||
name = "dasp_sample"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
|
||||
|
||||
[[package]]
|
||||
name = "dispatch"
|
||||
version = "0.2.0"
|
||||
@@ -1794,6 +1868,12 @@ version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "mach2"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -1937,6 +2017,17 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -2024,6 +2115,32 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-audio-toolbox"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"libc",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-audio",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-avf-audio"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cloud-kit"
|
||||
version = "0.2.2"
|
||||
@@ -2048,6 +2165,29 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-audio"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-audio-types"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-data"
|
||||
version = "0.2.2"
|
||||
@@ -2067,7 +2207,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"dispatch2",
|
||||
"libc",
|
||||
"objc2 0.6.5",
|
||||
]
|
||||
|
||||
@@ -2135,6 +2277,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"libc",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
@@ -62,6 +62,11 @@ publish.workspace = true
|
||||
repository.workspace = true
|
||||
default-run = "anicraft"
|
||||
|
||||
[features]
|
||||
# Plays sound during stage playback. Off: playback is silent (for builders without ALSA headers).
|
||||
default = ["sound-output"]
|
||||
sound-output = ["dep:cpal"]
|
||||
|
||||
[[bin]]
|
||||
name = "anicraft"
|
||||
path = "src/main.rs"
|
||||
@@ -76,6 +81,9 @@ egui.workspace = true
|
||||
rfd.workspace = true
|
||||
serde.workspace = true
|
||||
fontdb.workspace = true
|
||||
anicraft-audio.workspace = true
|
||||
# Sound output (Apache-2.0): WASAPI on Windows, CoreAudio on macOS, ALSA on Linux and the BSDs.
|
||||
cpal = { version = "0.18", optional = true }
|
||||
serde_json.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z" />
|
||||
<path d="M16 9a5 5 0 0 1 0 6" />
|
||||
<path d="M19.364 18.364a9 9 0 0 0 0-12.728" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 476 B |
+123
-3
@@ -201,12 +201,13 @@ pub const SHOT_FRAMES: u32 = 120;
|
||||
pub enum LibraryItem {
|
||||
Symbol(anicraft_engine::doc::SymbolId),
|
||||
Bitmap(anicraft_engine::doc::BitmapId),
|
||||
Sound(anicraft_engine::doc::SoundId),
|
||||
}
|
||||
|
||||
impl LibraryItem {
|
||||
/// The first item in the Library: its first symbol, else its first bitmap.
|
||||
/// The first item in the Library: its first symbol, else its first bitmap, else sound.
|
||||
pub fn first(doc: &anicraft_engine::doc::Document) -> Option<LibraryItem> {
|
||||
doc.library.first().map(|s| LibraryItem::Symbol(s.id)).or_else(|| doc.bitmaps.first().map(|b| LibraryItem::Bitmap(b.id)))
|
||||
doc.library.first().map(|s| LibraryItem::Symbol(s.id)).or_else(|| doc.bitmaps.first().map(|b| LibraryItem::Bitmap(b.id))).or_else(|| doc.sounds.first().map(|s| LibraryItem::Sound(s.id)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +297,12 @@ pub struct App {
|
||||
pub key_capture: Option<dialogs::KeyCapture>,
|
||||
/// Crash-recovery autosave and the copies earlier sessions left behind (ADR 0015).
|
||||
pub recovery: autosave::Recovery,
|
||||
/// Sound output for playback, scrubbing and library previews.
|
||||
pub sound: crate::sound::SoundOut,
|
||||
/// Playback follows the sound's clock (the movie has sounds and the device plays them).
|
||||
audio_clock: bool,
|
||||
/// The scene and frame last heard, so a moved playhead plays a snippet (scrubbing).
|
||||
heard: Option<(usize, u32)>,
|
||||
}
|
||||
|
||||
/// How finished this version is, shown next to the version number (docs/release.md).
|
||||
@@ -387,8 +394,12 @@ impl App {
|
||||
shortcuts,
|
||||
key_capture: None,
|
||||
recovery,
|
||||
sound: crate::sound::SoundOut::new(),
|
||||
audio_clock: false,
|
||||
heard: None,
|
||||
};
|
||||
app.apply_prefs(&cc.egui_ctx);
|
||||
app.decode_sounds();
|
||||
app.status_ok("Welcome to AniCraft. Press Enter to play the sample animation.");
|
||||
if let Some(e) = recovery_err {
|
||||
app.status_err(e);
|
||||
@@ -584,6 +595,24 @@ impl App {
|
||||
self.bucket_gap = GapSize::Small;
|
||||
self.run("edit.deselect", json!({}));
|
||||
}
|
||||
Some("sound") => {
|
||||
// A two-second beat (made here: decaying 220 Hz pulses every half second)
|
||||
// imported to the stage, stream sync, its keyframe's Sound properties showing.
|
||||
let rate = 22_050u32;
|
||||
let beat: Vec<f32> = (0..rate * 2)
|
||||
.map(|i| {
|
||||
let t = i as f32 / rate as f32;
|
||||
let env = (-(t % 0.5) * 9.0).exp() * if ((t / 0.5) as u32).is_multiple_of(2) { 0.9 } else { 0.5 };
|
||||
env * (t * 220.0 * std::f32::consts::TAU).sin()
|
||||
})
|
||||
.collect();
|
||||
let path = std::env::temp_dir().join("anicraft-beat.wav");
|
||||
if std::fs::write(&path, anicraft_audio::wav::encode(rate, 1, &beat, anicraft_audio::wav::Bits::Int16)).is_ok() {
|
||||
self.perform("file.import", json!({"path": path.display().to_string()}));
|
||||
self.run("sound.set", json!({"frame": 0, "sync": "stream"}));
|
||||
self.run("timeline.goto", json!({"frame": 14}));
|
||||
}
|
||||
}
|
||||
Some("tlwide") => {
|
||||
// Zoomed in: wide frames, playhead on frame 1 and frame 4.
|
||||
self.tl_cell_w = 48.0;
|
||||
@@ -665,6 +694,7 @@ impl App {
|
||||
"file.new" | "file.new_sample" | "file.open" => {
|
||||
self.view.fit = true;
|
||||
self.library_sel = LibraryItem::first(&self.s.doc);
|
||||
self.decode_sounds();
|
||||
match v.get("report").and_then(Value::as_str) {
|
||||
// An imported file: say what came across and what didn't, and that saving
|
||||
// makes a new .anicraft document.
|
||||
@@ -694,6 +724,24 @@ impl App {
|
||||
self.allow_close = true;
|
||||
}
|
||||
}
|
||||
"file.import" | "file.import_to_library" if v.get("sound").is_some() => {
|
||||
let id = anicraft_engine::doc::SoundId(v["sound"].as_u64().unwrap_or(0));
|
||||
self.library_sel = Some(LibraryItem::Sound(id));
|
||||
let name = v["name"].as_str().unwrap_or("");
|
||||
let secs = v["seconds"].as_f64().unwrap_or(0.0);
|
||||
self.status_ok(if v.get("layer").is_some() {
|
||||
format!("{name} ({secs:.2} s) is on a new layer from frame {}. Set its sync in Properties. Ctrl+Z to undo.", self.s.frame + 1)
|
||||
} else {
|
||||
format!("{name} ({secs:.2} s) is in the Library. Select a keyframe and pick it under Sound in Properties.")
|
||||
});
|
||||
}
|
||||
"file.import_to_library" => self.status_ok("Image added to the Library"),
|
||||
"file.export_audio" => {
|
||||
let n = v["sounds"].as_u64().unwrap_or(0);
|
||||
let note = if n == 0 { " No sounds play in that range, so the file is silent." } else { "" };
|
||||
self.status_ok(format!("Exported {} ({:.2} s).{note}", v["written"].as_str().unwrap_or(""), v["seconds"].as_f64().unwrap_or(0.0)));
|
||||
}
|
||||
"sound.delete" => self.status_ok("Deleted sound — Ctrl+Z to undo"),
|
||||
"file.import" => {
|
||||
if let Some(b) = self.s.doc.bitmaps.last().filter(|b| v["bitmap"].as_u64() == Some(b.id.0)) {
|
||||
self.library_sel = Some(LibraryItem::Bitmap(b.id));
|
||||
@@ -796,7 +844,9 @@ impl App {
|
||||
"file.export_sprite_sheet" => Some(("Export sprite sheet (PNG + JSON frame map)", "path", "sprites.png".to_string())),
|
||||
"file.export_video" => Some(("Export video (.webm or .mp4, made with your ffmpeg)", "path", "animation.webm".to_string())),
|
||||
"file.export_lottie" => Some(("Export Lottie animation (JSON, for web and apps)", "path", "animation.json".to_string())),
|
||||
"file.import" => Some(("Import to stage (SVG, PNG or JPEG)", "path", "drawing.svg".to_string())),
|
||||
"file.export_audio" => Some(("Export audio (the movie's soundtrack as a WAV)", "path", "soundtrack.wav".to_string())),
|
||||
"file.import_to_library" => Some(("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)", "path", "sound.wav".to_string())),
|
||||
"file.import" => Some(("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)", "path", "drawing.svg".to_string())),
|
||||
"plugin.install" => Some(("Install plug-in (.wasm file)", "path", "plugin.wasm".to_string())),
|
||||
"modify.convert_to_symbol" => Some(("Convert to symbol — name", "name", format!("Symbol {}", self.s.doc.library.len() + 1))),
|
||||
_ => None,
|
||||
@@ -848,12 +898,80 @@ impl App {
|
||||
if self.playing && self.s.frame + 1 >= self.s.frame_count() {
|
||||
self.s.set_frame(0);
|
||||
}
|
||||
self.start_sound();
|
||||
}
|
||||
|
||||
/// The playhead as a movie frame (scenes in order).
|
||||
fn movie_frame(&self) -> u32 {
|
||||
self.s.doc.scene_start(self.s.scene).saturating_add(self.s.frame)
|
||||
}
|
||||
|
||||
/// Starts the sound from the playhead, or stops it; the playhead follows the sound's clock
|
||||
/// while it plays.
|
||||
fn start_sound(&mut self) {
|
||||
self.audio_clock = self.playing && self.shot.is_none() && self.sound.play(&self.s.doc, self.s.state, self.movie_frame());
|
||||
if !self.playing {
|
||||
self.sound.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the document's sounds on a background thread (each once; every copy of the
|
||||
/// document shares the result), so opening a file never waits on it.
|
||||
pub fn decode_sounds(&self) {
|
||||
let sounds = self.s.doc.sounds.clone();
|
||||
if !sounds.is_empty() {
|
||||
let _ = std::thread::Builder::new().name("anicraft-decode".into()).spawn(move || {
|
||||
for x in sounds {
|
||||
let _ = x.decoded();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrubbing: a moved playhead plays a frame's worth of the stream sounds there.
|
||||
fn scrub_sound(&mut self) {
|
||||
let here = (self.s.scene, self.s.frame);
|
||||
if !self.playing && self.shot.is_none() && self.heard.is_some_and(|h| h != here) {
|
||||
self.sound.scrub(&self.s.doc, self.s.state, self.movie_frame());
|
||||
}
|
||||
self.heard = Some(here);
|
||||
}
|
||||
|
||||
fn tick_playback(&mut self, ctx: &egui::Context) {
|
||||
if !self.playing {
|
||||
if self.audio_clock {
|
||||
self.sound.stop();
|
||||
self.audio_clock = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let n = self.s.frame_count();
|
||||
if self.audio_clock {
|
||||
// Picture follows sound: the frame is wherever the sound has got to (edits made
|
||||
// while playing are heard at once).
|
||||
self.sound.sync(&self.s.doc, self.s.state);
|
||||
if let Some(mf) = self.sound.frame(self.s.doc.stage.fps) {
|
||||
let local = mf.saturating_sub(self.s.doc.scene_start(self.s.scene));
|
||||
if local >= n {
|
||||
if self.looping {
|
||||
self.s.set_frame(0);
|
||||
self.start_sound();
|
||||
} else {
|
||||
self.s.set_frame(n.saturating_sub(1));
|
||||
self.playing = false;
|
||||
self.start_sound();
|
||||
}
|
||||
} else if local != self.s.frame {
|
||||
self.s.set_frame(local);
|
||||
}
|
||||
self.heard = Some((self.s.scene, self.s.frame));
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
// The device went away: carry on silently on the wall clock.
|
||||
self.audio_clock = false;
|
||||
self.play_acc = 0.0;
|
||||
}
|
||||
let fps = f64::from(self.s.doc.stage.fps.max(1.0));
|
||||
self.play_acc += f64::from(ctx.input(|i| i.stable_dt)).min(0.25);
|
||||
let n = self.s.frame_count();
|
||||
@@ -870,6 +988,7 @@ impl App {
|
||||
self.s.set_frame(self.s.frame + 1);
|
||||
}
|
||||
}
|
||||
self.heard = Some((self.s.scene, self.s.frame));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
@@ -1169,6 +1288,7 @@ impl eframe::App for App {
|
||||
}
|
||||
pathtools::upkeep(self);
|
||||
self.tick_playback(&ctx);
|
||||
self.scrub_sound();
|
||||
self.update_title(&ctx);
|
||||
if let Some(st) = &mut self.status
|
||||
&& st.at == 0.0 {
|
||||
|
||||
@@ -84,6 +84,7 @@ fn palette_meets_contrast_and_target_minimums() {
|
||||
assert!(contrast(T.ink, T.span) >= 4.5 && contrast(T.ink, T.tween) >= 4.5 && contrast(T.ink, T.tween_shape) >= 4.5 && contrast(T.ink, T.tween_motion) >= 4.5, "ink on blocks");
|
||||
assert!(contrast(T.text, T.span_empty) >= 4.5);
|
||||
assert!(contrast(T.span, T.panel) >= 3.0 && contrast(T.tween, T.panel) >= 3.0 && contrast(T.tween_shape, T.panel) >= 3.0 && contrast(T.tween_motion, T.panel) >= 3.0);
|
||||
assert!(contrast(T.waveform, T.span_empty) >= 4.5 && contrast(T.waveform, T.row_active) >= 4.5, "waveforms read on empty spans");
|
||||
// Focus and selection outlines, and checkbox edges, stand out from the panels (WCAG 1.4.11).
|
||||
assert!(contrast(T.control_edge, T.panel_alt) >= 3.0 && contrast(T.control_edge, T.panel) >= 3.0, "control edges");
|
||||
assert!(contrast(T.accent, T.panel) >= 3.0, "accent on panel: {:.2}", contrast(T.accent, T.panel));
|
||||
|
||||
+5
-1
@@ -58,11 +58,13 @@ pub enum Icon {
|
||||
Guide,
|
||||
Image,
|
||||
Type,
|
||||
Sound,
|
||||
}
|
||||
|
||||
impl Icon {
|
||||
#[cfg(test)]
|
||||
pub const ALL: [Icon; 44] = [
|
||||
pub const ALL: [Icon; 45] = [
|
||||
Icon::Sound,
|
||||
Icon::Guide,
|
||||
Icon::Image,
|
||||
Icon::Type,
|
||||
@@ -151,6 +153,7 @@ impl Icon {
|
||||
Icon::Guide => ("spline", false),
|
||||
Icon::Image => ("image", false),
|
||||
Icon::Type => ("type", false),
|
||||
Icon::Sound => ("volume-2", false),
|
||||
// Lucide's object-align icons aren't in the local set; these are AniCraft originals
|
||||
// drawn on the same 24 grid with the same 2-unit round strokes.
|
||||
Icon::AlignLeft => ("anicraft-align-left", false),
|
||||
@@ -193,6 +196,7 @@ static FILES: &[(&str, &str)] = &[
|
||||
("spline", include_str!("../assets/icons/spline.svg")),
|
||||
("image", include_str!("../assets/icons/image.svg")),
|
||||
("type", include_str!("../assets/icons/type.svg")),
|
||||
("volume-2", include_str!("../assets/icons/volume-2.svg")),
|
||||
("play", include_str!("../assets/icons/play.svg")),
|
||||
("pause", include_str!("../assets/icons/pause.svg")),
|
||||
("rotate-cw", include_str!("../assets/icons/rotate-cw.svg")),
|
||||
|
||||
@@ -18,6 +18,7 @@ mod pathtools;
|
||||
mod platform;
|
||||
mod plugins_ui;
|
||||
mod prefs;
|
||||
mod sound;
|
||||
mod stage;
|
||||
mod theme;
|
||||
mod timeline;
|
||||
|
||||
+98
-8
@@ -690,6 +690,7 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
|
||||
live(app, "Frame label", "timeline.set_label", json!({"label": label}));
|
||||
}
|
||||
});
|
||||
sound_rows(app, ui, k.sound);
|
||||
if let Some(m) = &k.motion {
|
||||
// A motion tween: what is keyed, and the way to its curves.
|
||||
row_prose(ui, "Tween", |ui| {
|
||||
@@ -762,6 +763,63 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyframe's sound, as Animate's Sound section: which sound (or none), its sync, and
|
||||
/// whether it repeats a number of times or loops.
|
||||
fn sound_rows(app: &mut App, ui: &mut egui::Ui, current: Option<anicraft_engine::doc::FrameSound>) {
|
||||
use anicraft_engine::doc::SoundSync;
|
||||
let sounds: Vec<(u64, String)> = app.s.doc.sounds.iter().map(|x| (x.id.0, x.name.clone())).collect();
|
||||
if sounds.is_empty() && current.is_none() {
|
||||
return;
|
||||
}
|
||||
let name = current.and_then(|f| app.s.doc.sound(f.sound)).map_or_else(|| "None".to_string(), |x| x.name.clone());
|
||||
row_prose(ui, "Sound", |ui| {
|
||||
egui::ComboBox::from_id_salt("prop_sound").width(150.0).selected_text(name).show_ui(ui, |ui| {
|
||||
if ui.selectable_label(current.is_none(), "None").clicked() && current.is_some() {
|
||||
app.run("sound.remove", json!({}));
|
||||
}
|
||||
for (id, n) in &sounds {
|
||||
if ui.selectable_label(current.is_some_and(|f| f.sound.0 == *id), n.as_str()).clicked() {
|
||||
app.run("sound.set", json!({"sound": id}));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let Some(f) = current else { return };
|
||||
row_prose(ui, "Sync", |ui| {
|
||||
egui::ComboBox::from_id_salt("prop_sync").width(150.0).selected_text(f.sync.label()).show_ui(ui, |ui| {
|
||||
for m in SoundSync::ALL {
|
||||
if ui.selectable_label(f.sync == m, m.label()).on_hover_text(m.hint()).clicked() {
|
||||
app.run("sound.set", json!({"sync": m.key()}));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if f.sync == SoundSync::Stop {
|
||||
return;
|
||||
}
|
||||
row_prose(ui, "Repeat", |ui| {
|
||||
egui::ComboBox::from_id_salt("prop_repeat").width(90.0).selected_text(if f.looping { "Loop" } else { "Repeat" }).show_ui(ui, |ui| {
|
||||
if ui.selectable_label(!f.looping, "Repeat").clicked() && f.looping {
|
||||
app.run("sound.set", json!({"loop": false}));
|
||||
}
|
||||
if ui.selectable_label(f.looping, "Loop").on_hover_text("Plays again and again: to the end of the movie (event) or of this span (stream)").clicked() && !f.looping {
|
||||
app.run("sound.set", json!({"loop": true}));
|
||||
}
|
||||
});
|
||||
if !f.looping {
|
||||
let mut n = f.repeat;
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut n).range(1..=anicraft_engine::doc::sound::MAX_REPEAT).suffix(" ×")));
|
||||
if r.on_hover_text("Times it plays in a row").changed() {
|
||||
live(app, "Sound repeat", "sound.set", json!({"repeat": n}));
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(x) = app.s.doc.sound(f.sound) {
|
||||
let ch = if x.channels == 2 { "stereo" } else { "mono" };
|
||||
ui.label(text(Type::Data, format!("{:.2} s · {:.1} kHz {ch} · {}", x.seconds(), f64::from(x.rate) / 1000.0, x.format.label())).color(T.text_faint));
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
if app.tool == Tool::Text {
|
||||
// What new text gets (the last style used, as in Animate).
|
||||
@@ -850,16 +908,19 @@ fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
kind: Some(sym.kind),
|
||||
})
|
||||
.chain(doc.bitmaps.iter().map(|b| LibraryRow { item: LibraryItem::Bitmap(b.id), name: b.name.clone(), detail: format!("Bitmap · {}×{}", b.width, b.height), kind: None }))
|
||||
.chain(doc.sounds.iter().map(|x| LibraryRow { item: LibraryItem::Sound(x.id), name: x.name.clone(), detail: format!("Sound · {:.1} s", x.seconds()), kind: None }))
|
||||
.collect();
|
||||
if rows.is_empty() {
|
||||
let key = |id: &str| app.keymap.primary(id).map(crate::platform::shortcut_label).unwrap_or_default();
|
||||
ui.label(text(Type::Caption, format!("No symbols or images yet. Select artwork and press {} to make a symbol, or import an image with {}.", key("modify.convert_to_symbol"), key("file.import"))));
|
||||
ui.label(text(Type::Caption, format!("No symbols, images or sounds yet. Select artwork and press {} to make a symbol, or import an image or a sound with {}.", key("modify.convert_to_symbol"), key("file.import"))));
|
||||
return;
|
||||
}
|
||||
ui.label(text(Type::Caption, format!("{} {}", rows.len(), if rows.len() == 1 { "item" } else { "items" })));
|
||||
// Sounds go on the active layer's keyframe at the playhead, their span grown to fit.
|
||||
let place = |app: &mut App, item: LibraryItem| match item {
|
||||
LibraryItem::Symbol(id) => app.run("library.place", json!({"symbol": id.0})),
|
||||
LibraryItem::Bitmap(id) => app.run("library.place", json!({"bitmap": id.0})),
|
||||
LibraryItem::Sound(id) => app.run("sound.place", json!({"sound": id.0, "extend": true})),
|
||||
};
|
||||
egui::ScrollArea::vertical().id_salt("lib").max_height(140.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
for row in &rows {
|
||||
@@ -872,8 +933,8 @@ fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
ui.painter().rect_filled(Rect::from_min_size(r.left_top(), vec2(3.0, r.height())), 0.0, T.accent);
|
||||
}
|
||||
let icon = Rect::from_center_size(r.left_center() + vec2(14.0, 0.0), vec2(14.0, 14.0));
|
||||
match row.kind {
|
||||
Some(kind) => {
|
||||
match (row.kind, row.item) {
|
||||
(Some(kind), _) => {
|
||||
let kind_color = match kind {
|
||||
SymbolKind::Graphic => T.kind_graphic,
|
||||
SymbolKind::MovieClip => T.kind_movie_clip,
|
||||
@@ -882,7 +943,8 @@ fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
ui.painter().rect_stroke(icon, 2.0, Stroke::new(1.5, kind_color), StrokeKind::Inside);
|
||||
ui.painter().circle_filled(icon.center(), 2.5, kind_color);
|
||||
}
|
||||
None => icons::paint(ui.painter(), icon.expand(1.0), Icon::Image, color(Type::Body)),
|
||||
(None, LibraryItem::Sound(_)) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Sound, color(Type::Body)),
|
||||
(None, _) => icons::paint(ui.painter(), icon.expand(1.0), Icon::Image, color(Type::Body)),
|
||||
}
|
||||
ui.painter().text(r.left_center() + vec2(30.0, 0.0), Align2::LEFT_CENTER, &row.name, font(Type::Body), color(Type::Body));
|
||||
ui.painter().text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, &row.detail, font(Type::Caption), color(Type::Caption));
|
||||
@@ -892,17 +954,45 @@ fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
if resp.double_clicked() {
|
||||
place(app, row.item);
|
||||
}
|
||||
if let LibraryItem::Sound(id) = row.item {
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button("Delete Sound").clicked() {
|
||||
ui.close();
|
||||
app.request("sound.delete", json!({"sound": id.0}));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let can_place = app.library_sel.filter(|sel| rows.iter().any(|r| r.item == *sel));
|
||||
if ui.add_enabled(can_place.is_some(), egui::Button::new("Place on stage")).on_hover_text("Adds it at the stage centre (or double-click an item)").clicked()
|
||||
&& let Some(item) = can_place {
|
||||
place(app, item);
|
||||
match can_place {
|
||||
Some(LibraryItem::Sound(id)) => {
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Preview").on_hover_text("Plays the sound on its own").clicked()
|
||||
&& let Some(dec) = app.s.doc.sound(id).and_then(|x| x.decoded())
|
||||
{
|
||||
app.playing = false;
|
||||
app.sound.preview(dec.pcm.clone());
|
||||
if let Some(e) = app.sound.error.take() {
|
||||
app.status_err(format!("No sound: {e}"));
|
||||
}
|
||||
}
|
||||
if ui.button("Place on timeline").on_hover_text("Puts it on the active layer's keyframe at the playhead (or double-click it)").clicked() {
|
||||
place(app, LibraryItem::Sound(id));
|
||||
}
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
if ui.add_enabled(can_place.is_some(), egui::Button::new("Place on stage")).on_hover_text("Adds it at the stage centre (or double-click an item)").clicked()
|
||||
&& let Some(item) = can_place {
|
||||
place(app, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One Library row: a symbol (with its kind) or a bitmap.
|
||||
/// One Library row: a symbol (with its kind), a bitmap or a sound.
|
||||
struct LibraryRow {
|
||||
item: LibraryItem,
|
||||
name: String,
|
||||
|
||||
+4
-2
@@ -152,7 +152,9 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
|
||||
"file.export_gif" => ("Animated GIF", &["gif"]),
|
||||
"file.export_svg" => ("SVG image", &["svg"]),
|
||||
"file.export_lottie" => ("Lottie animation", &["json"]),
|
||||
"file.import" => ("SVG drawing or image", &["svg", "png", "jpg", "jpeg"]),
|
||||
"file.import" => ("Drawing, image or sound", &["svg", "png", "jpg", "jpeg", "wav", "ogg", "mp3"]),
|
||||
"file.import_to_library" => ("Sound or image", &["wav", "ogg", "mp3", "png", "jpg", "jpeg"]),
|
||||
"file.export_audio" => ("WAV sound", &["wav"]),
|
||||
"file.export_sprite_sheet" => ("PNG sprite sheet", &["png"]),
|
||||
"file.export_video" => ("Video (WebM or MP4)", &["webm", "mp4"]),
|
||||
// Opening also imports .fla archives and .xfl packages.
|
||||
@@ -168,7 +170,7 @@ pub fn file_dialog(cmd: &str, title: &str, default_name: &str) -> Option<PathBuf
|
||||
let (label, exts) = filters(cmd);
|
||||
let d = rfd::FileDialog::new().set_title(title);
|
||||
match cmd {
|
||||
"file.open" | "plugin.install" => d.add_filter(label, exts).pick_file(),
|
||||
"file.open" | "plugin.install" | "file.import" | "file.import_to_library" => d.add_filter(label, exts).pick_file(),
|
||||
"file.export_png_sequence" => d.pick_folder(),
|
||||
_ => d.add_filter(label, exts).set_file_name(default_name).save_file(),
|
||||
}
|
||||
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
//! Sound during stage playback (ADR 0014). The movie's sounds are laid out by the engine
|
||||
//! (`doc::sound::voices`, pure), handed to an `anicraft_audio::Player` that the audio device's
|
||||
//! callback pulls from, and the playhead follows the player's clock while sound plays, so
|
||||
//! picture keeps time with sound.
|
||||
//!
|
||||
//! The device (cpal: WASAPI, CoreAudio, ALSA) opens on first need: never at start-up, never in
|
||||
//! `--screenshot` runs or tests. If it can't open, or fails later, playback carries on silently
|
||||
//! on the wall clock.
|
||||
|
||||
use anicraft_audio::{Pcm, Player, Voice, VoiceKind};
|
||||
use anicraft_engine::StateId;
|
||||
use anicraft_engine::doc::{Document, sound};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub struct SoundOut {
|
||||
player: Arc<Mutex<Player>>,
|
||||
failed: Arc<AtomicBool>,
|
||||
#[cfg(feature = "sound-output")]
|
||||
stream: Option<cpal::Stream>,
|
||||
tried: bool,
|
||||
rate: u32,
|
||||
/// The document state and frame rate the player's voices were laid out for.
|
||||
laid_out: Option<(StateId, u32)>,
|
||||
/// A library preview is loaded instead of the movie's sounds.
|
||||
previewing: bool,
|
||||
/// Why there is no sound, once.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl SoundOut {
|
||||
pub fn new() -> SoundOut {
|
||||
SoundOut {
|
||||
player: Arc::new(Mutex::new(Player::new(48_000))),
|
||||
failed: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(feature = "sound-output")]
|
||||
stream: None,
|
||||
tried: false,
|
||||
rate: 48_000,
|
||||
laid_out: None,
|
||||
previewing: false,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the output device (the first time only). Whether sound can be heard.
|
||||
fn ready(&mut self) -> bool {
|
||||
if !self.tried {
|
||||
self.tried = true;
|
||||
match open(&self.player, &self.failed) {
|
||||
#[cfg(feature = "sound-output")]
|
||||
Ok((stream, rate)) => {
|
||||
self.stream = Some(stream);
|
||||
self.rate = rate;
|
||||
if let Ok(mut p) = self.player.lock() {
|
||||
*p = Player::new(rate);
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "sound-output"))]
|
||||
Ok(rate) => self.rate = rate,
|
||||
Err(e) => self.error = Some(e),
|
||||
}
|
||||
}
|
||||
self.live()
|
||||
}
|
||||
|
||||
/// The device is open and working.
|
||||
fn live(&self) -> bool {
|
||||
#[cfg(feature = "sound-output")]
|
||||
let open = self.stream.is_some();
|
||||
#[cfg(not(feature = "sound-output"))]
|
||||
let open = false;
|
||||
open && !self.failed.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn with_player<R>(&self, f: impl FnOnce(&mut Player) -> R) -> Option<R> {
|
||||
self.player.lock().ok().map(|mut p| f(&mut p))
|
||||
}
|
||||
|
||||
/// Lays the document's sounds out again if it changed since (edits are heard at once,
|
||||
/// even mid-playback).
|
||||
pub fn sync(&mut self, doc: &Document, state: StateId) {
|
||||
let key = (state, doc.stage.fps.to_bits());
|
||||
if self.laid_out == Some(key) && !self.previewing {
|
||||
return;
|
||||
}
|
||||
let voices = Arc::new(sound::voices(doc, self.rate));
|
||||
self.previewing = false;
|
||||
self.laid_out = Some(key);
|
||||
self.with_player(|p| p.set_voices(voices));
|
||||
}
|
||||
|
||||
/// Starts sound from movie frame `frame`; whether it plays (the device is there and the
|
||||
/// movie has sounds), in which case the playhead should follow [`SoundOut::frame`].
|
||||
pub fn play(&mut self, doc: &Document, state: StateId, frame: u32) -> bool {
|
||||
if !sound::has_sounds(doc) || !self.ready() {
|
||||
return false;
|
||||
}
|
||||
self.sync(doc, state);
|
||||
let at = sound::frame_start(u64::from(frame), doc.stage.fps, self.rate);
|
||||
self.with_player(|p| p.play(at)).is_some()
|
||||
}
|
||||
|
||||
/// A one-frame snippet of the stream sounds at movie frame `frame` (scrubbing).
|
||||
pub fn scrub(&mut self, doc: &Document, state: StateId, frame: u32) {
|
||||
let streams = doc.scenes.iter().any(|s| s.timeline.layers.iter().any(|l| l.keyframes.iter().any(|k| k.sound.is_some_and(|f| f.sync == sound::SoundSync::Stream))));
|
||||
if !streams || !self.ready() {
|
||||
return;
|
||||
}
|
||||
self.sync(doc, state);
|
||||
let fps = doc.stage.fps;
|
||||
let at = sound::frame_start(u64::from(frame), fps, self.rate);
|
||||
let len = sound::frame_start(u64::from(frame) + 1, fps, self.rate).saturating_sub(at);
|
||||
self.with_player(|p| p.scrub(at, len));
|
||||
}
|
||||
|
||||
/// Plays a library sound on its own (the Library's preview button).
|
||||
pub fn preview(&mut self, pcm: Arc<Pcm>) {
|
||||
if !self.ready() {
|
||||
return;
|
||||
}
|
||||
let end = Voice::play_frames(&pcm, self.rate);
|
||||
let voices = Arc::new(vec![Voice { pcm, kind: VoiceKind::Event, at: 0, end, gain: 1.0 }]);
|
||||
self.previewing = true;
|
||||
self.with_player(|p| {
|
||||
p.set_voices(voices);
|
||||
p.play(0);
|
||||
});
|
||||
}
|
||||
|
||||
/// Fades out and goes quiet.
|
||||
pub fn stop(&mut self) {
|
||||
self.with_player(Player::stop);
|
||||
}
|
||||
|
||||
pub fn is_playing(&self) -> bool {
|
||||
self.live() && self.with_player(|p| p.is_playing()).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The movie frame the sound has reached while it plays (`None` when it doesn't: the
|
||||
/// playhead then runs on the wall clock).
|
||||
pub fn frame(&self, fps: f32) -> Option<u32> {
|
||||
if self.previewing || !self.is_playing() {
|
||||
return None;
|
||||
}
|
||||
let pos = self.with_player(|p| p.position())?;
|
||||
let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 24.0 };
|
||||
Some((pos as f64 * fps / f64::from(self.rate.max(1))).floor().min(f64::from(u32::MAX)) as u32)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "sound-output")]
|
||||
fn open(player: &Arc<Mutex<Player>>, failed: &Arc<AtomicBool>) -> Result<(cpal::Stream, u32), String> {
|
||||
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
let device = cpal::default_host().default_output_device().ok_or("no sound output device")?;
|
||||
let supported = device.default_output_config().map_err(|e| format!("the sound device has no usable format ({e})"))?;
|
||||
let config = supported.config();
|
||||
let rate = config.sample_rate;
|
||||
let stream = match supported.sample_format() {
|
||||
cpal::SampleFormat::F32 => build::<f32>(&device, config, player, failed),
|
||||
cpal::SampleFormat::I16 => build::<i16>(&device, config, player, failed),
|
||||
cpal::SampleFormat::U16 => build::<u16>(&device, config, player, failed),
|
||||
cpal::SampleFormat::I32 => build::<i32>(&device, config, player, failed),
|
||||
other => return Err(format!("the sound device wants {other:?} samples, which AniCraft doesn't write yet")),
|
||||
}
|
||||
.map_err(|e| format!("could not start sound ({e})"))?;
|
||||
stream.play().map_err(|e| format!("could not start sound ({e})"))?;
|
||||
Ok((stream, rate))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "sound-output"))]
|
||||
fn open(_: &Arc<Mutex<Player>>, _: &Arc<AtomicBool>) -> Result<u32, String> {
|
||||
Err("this build of AniCraft has no sound output".into())
|
||||
}
|
||||
|
||||
/// An output stream whose callback mixes from the player. The lock is held only while one
|
||||
/// buffer is mixed; the UI holds it only to change a few fields.
|
||||
#[cfg(feature = "sound-output")]
|
||||
fn build<T: cpal::SizedSample + cpal::FromSample<f32>>(device: &cpal::Device, config: cpal::StreamConfig, player: &Arc<Mutex<Player>>, failed: &Arc<AtomicBool>) -> Result<cpal::Stream, cpal::Error> {
|
||||
use cpal::traits::DeviceTrait;
|
||||
let channels = usize::from(config.channels);
|
||||
let (player, failed) = (player.clone(), failed.clone());
|
||||
let mut buf: Vec<f32> = Vec::new();
|
||||
device.build_output_stream::<T, _, _>(
|
||||
config,
|
||||
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
|
||||
buf.resize(data.len(), 0.0);
|
||||
match player.lock() {
|
||||
Ok(mut p) => p.fill(&mut buf, channels),
|
||||
Err(_) => buf.fill(0.0),
|
||||
}
|
||||
for (d, s) in data.iter_mut().zip(&buf) {
|
||||
*d = T::from_sample(*s);
|
||||
}
|
||||
},
|
||||
// A rerouted stream or a refused real-time boost still plays; anything else ends it.
|
||||
move |e: cpal::Error| {
|
||||
if !matches!(e.kind(), cpal::ErrorKind::DeviceChanged | cpal::ErrorKind::RealtimeDenied | cpal::ErrorKind::DeviceBusy) {
|
||||
failed.store(true, Ordering::Relaxed);
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -52,6 +52,8 @@ pub struct Tokens {
|
||||
pub tween: Color32,
|
||||
pub tween_shape: Color32,
|
||||
pub tween_motion: Color32,
|
||||
/// Timeline: a sound's waveform on an empty span (on artwork spans it is drawn in ink).
|
||||
pub waveform: Color32,
|
||||
pub tween_line: Color32,
|
||||
pub playhead: Color32,
|
||||
pub selection: Color32,
|
||||
@@ -107,6 +109,7 @@ pub const T: Tokens = Tokens {
|
||||
tween: Color32::from_rgb(0x8a, 0x5c, 0xff),
|
||||
tween_shape: Color32::from_rgb(0xf2, 0xa1, 0x3b),
|
||||
tween_motion: Color32::from_rgb(0x4c, 0xb8, 0xf5),
|
||||
waveform: Color32::from_rgb(0x7c, 0xc4, 0xff),
|
||||
tween_line: Color32::from_rgb(0x0e, 0x0e, 0x10),
|
||||
playhead: Color32::from_rgb(0xff, 0x4d, 0x3d),
|
||||
selection: Color32::from_rgb(0x2e, 0x66, 0xf0),
|
||||
|
||||
@@ -561,6 +561,12 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
};
|
||||
let mark = if empty && !tweened { T.text } else { T.ink };
|
||||
cp.rect_filled(span, SQUARE, fill);
|
||||
if let Some(fs) = k.sound
|
||||
&& !waveform(&cp, &app.s.doc, fs, span, x0, cell_w, if empty && !tweened { T.waveform } else { T.ink })
|
||||
{
|
||||
// Still decoding (just opened): draw it when it's ready.
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
let kc = pos2(x0 + cell_w * 0.5, y + ROW_H * 0.5);
|
||||
if let Some(m) = motion {
|
||||
// Property keyframes: small diamonds where any property has a key.
|
||||
@@ -913,6 +919,50 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
|
||||
/// Engine param for an easing preset.
|
||||
/// A keyframe's sound over its span: the waveform from the keyframe on, repeated as the sound
|
||||
/// repeats, as far as the span reaches (all a stream sound plays; an event sound plays on past
|
||||
/// it). One line per point column, from the lowest to the highest sample under it. `false`
|
||||
/// while the sound is still being decoded.
|
||||
fn waveform(p: &egui::Painter, doc: &anicraft_engine::doc::Document, fs: anicraft_engine::doc::FrameSound, span: Rect, x0: f32, cell_w: f32, color: Color32) -> bool {
|
||||
let Some(snd) = doc.sound(fs.sound) else { return true };
|
||||
let Some(dec) = snd.decoded_if_ready() else { return false };
|
||||
let len = dec.peaks.frames() as u64;
|
||||
if len == 0 || cell_w <= 0.0 {
|
||||
return true;
|
||||
}
|
||||
let total = if fs.looping { u64::MAX } else { len.saturating_mul(u64::from(fs.repeat.max(1))) };
|
||||
let per_point = f64::from(dec.pcm.rate) / f64::from(doc.stage.fps.max(1.0)) / f64::from(cell_w);
|
||||
let clip = p.clip_rect().intersect(span.shrink2(vec2(0.0, 1.0)));
|
||||
let (cy, h) = (clip.center().y, clip.height() * 0.5);
|
||||
let stroke = Stroke::new(1.0, color);
|
||||
let mut x = clip.left().floor().max(span.left());
|
||||
while x < clip.right() {
|
||||
let a = (f64::from(x - x0) * per_point).max(0.0) as u64;
|
||||
let b = (f64::from(x + 1.0 - x0) * per_point).max(0.0) as u64 + 1;
|
||||
if a >= total {
|
||||
break;
|
||||
}
|
||||
let b = b.min(total);
|
||||
// The source frames under this column, within one play of the sound.
|
||||
let (s, n) = ((a % len) as usize, (b - a).min(len) as usize);
|
||||
let range = if s + n <= len as usize {
|
||||
dec.peaks.range(s, s + n)
|
||||
} else {
|
||||
let (p1, p2) = (dec.peaks.range(s, len as usize), dec.peaks.range(0, s + n - len as usize));
|
||||
match (p1, p2) {
|
||||
(Some((l1, h1)), Some((l2, h2))) => Some((l1.min(l2), h1.max(h2))),
|
||||
(one, other) => one.or(other),
|
||||
}
|
||||
};
|
||||
if let Some((lo, hi)) = range {
|
||||
let (top, bottom) = (cy - hi.clamp(-1.0, 1.0) * h, cy - lo.clamp(-1.0, 1.0) * h);
|
||||
p.line_segment([pos2(x + 0.5, top.min(cy - 0.5)), pos2(x + 0.5, bottom.max(cy + 0.5))], stroke);
|
||||
}
|
||||
x += 1.0;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn easing_param(e: Easing) -> serde_json::Value {
|
||||
match e {
|
||||
Easing::Linear => json!("Linear"),
|
||||
|
||||
Reference in new issue
Block a user