mirror of
https://github.com/storytold/soundcraft.git
synced 2026-11-16 15:22:28 +00:00
* test(cli): pin today's argument handling
Run the real binary and record how the hand-written parser behaves for every
subcommand: help and version spellings, no arguments, unknown subcommands and
flags, value flags in both spellings, missing and repeated values, positional
order, exit codes and which stream carries each message.
No behaviour change. Later parser changes update these assertions on purpose.
* refactor(cli): split main.rs into modules
Move only: args, error, output, convert, info, session, catalog, app and
mcp each get their functions and unit tests; main.rs keeps the usage doc,
help_text and the dispatch. Moved items become pub(crate) where other
modules call them. No behaviour change.
* refactor(cli): typed errors and run(args, out, err)
soundcraft-cli is now a library plus a thin binary. `soundcraft_cli::run(args,
out, err) -> i32` is the whole program; main.rs only passes the real streams
and shuts the plugin hosts down afterwards (process teardown, not part of run,
which tests call repeatedly in one process). Subcommands write to the given
writers, return `Result<(), CliError>`, and `fail` is gone. CliError wraps
engine, audio-io, io (with the path), serde_json and the control channel
errors; UsageError, ConvertError and RootFlagError cover the subcommands' own
failures. No Result<_, String> is left except where a dependency reports a
string (control-channel call, AutomationRoots::new), wrapped in a variant.
The tests that need no files, working directory, environment or stdin now call
`run` in-process (tests/it/run.rs); the rest still run the binary.
Behaviour changes:
- Error messages start with `error: ` instead of `soundcraft-cli: `.
- A script line that stops the run now prints `error: FILE:N: ID: ...` (it had
no prefix). With --keep-going the line stays bare.
- A convert encode or write failure now names the output path.
- An empty or help-less call still prints the one-line usage to stderr without
a prefix and exits 1; `files confined:` keeps its `soundcraft-cli:` prefix
(it is a note, not an error).
* refactor(cli): parse arguments with clap
Replace the hand parser (arg_value, check_options, ENGINE_OPTIONS, the
lib.rs dispatch, the per-subcommand positional handling and the root
flags' consume) with clap derive types in args.rs: a Parser, a
Subcommand enum and one Args struct per subcommand, with the run/script
engine flags flattened. main passes args_os(); run takes OsString-like
arguments and renders clap's help, version and usage errors (help and
version on stdout, exit 0; usage errors on stderr, exit 2). Add
command() returning the clap definition. The usage block in the module
doc and help_text are gone: the doc comments are the help.
Behaviour changes:
- Usage errors exit 2 with clap's message and the --help hint on
stderr, instead of exit 1 with hand-written text: unknown subcommand,
unknown flag, missing value, missing or extra positional, a value on
a boolean flag (--demo=1, --normalize=1).
- No arguments prints the help to stderr, exit 2 (was a one-line usage,
exit 1).
- --help, -h and help print clap's generated help, and every subcommand
has its own (SUB --help, SUB -h, help SUB). Before, info and script
read --help as a file name, describe as an id, commands as a filter,
run rejected --help and ignored -h, convert and app printed their
usage error, mcp, parity and plugins ignored it, and app --port P -h
called the method -h.
- --help or -h before -- shows the subcommand's help even after a
mistake on the same line (run --bounce --help).
- --version, -V and version print "soundcraft-cli X.Y.Z" (was
"SoundCraft CLI X.Y.Z").
- Unknown flags on info, commands, describe, app, mcp, parity and
plugins are usage errors; they were ignored or read as a positional.
mcp --automation-bogus exits 2 (was exit 1).
- Extra positionals are usage errors on every subcommand (were ignored).
- A single-dash word (-x) is a flag, so an unknown one is a usage
error; a value starting with - is written --flag=-value.
- Flags may come before or between the positionals: convert IN --rate
44100 OUT, convert --rate 44100 IN OUT and script --keep-going FILE
parse (the flag word was taken as a file name).
- A repeated single-value flag keeps its last value (was the first):
--rate, --bit-depth, --save, --port and the others.
- parity --write without a value is a usage error (printed the report).
- mcp --connect without a value, or followed by a flag, is a usage
error (was exit 1, or took the flag as the port).
- mcp --demo=1 is a usage error (was ignored, without the demo).
- A root flag without a folder, with an empty one, or followed by a
flag is a usage error with clap's message (was exit 1).
- A non-Unicode argument is a usage error where text is expected and
accepted as a root folder (std::env::args panicked).
- The help lists --sample as --demo's alias.
Unchanged: --dither with --no-dither, bad --rate and --bit-depth values,
the roots with --connect and the SOUNDCRAFT_CONTROL_PORT fallback are
still checked after parsing (exit 1).
* refactor(cli): reject repeated flags, clap --version (photocraft#7071 decisions)
Behaviour changes:
- A flag given twice is a usage error (exit 2), in either spelling, including
an alias pair such as --demo and --sample. Before, the last one won. Only
run's --cmd and mcp's --automation-read-root / --automation-write-root
repeat; they accumulate in order.
- --version and -V print the long version, "soundcraft-cli 0.13.1 (linux
x86_64)": the version and the platform the binary was built for.
- The hidden `version` subcommand is gone; `soundcraft-cli version` is an
unrecognized-subcommand usage error.
- --start and --end accept a negative number (`--start -1`, as the engine
counts positions before 0); any other value starting with `-` needs `=`
and otherwise is an unexpected-argument usage error. No flag has
allow_hyphen_values.
- `help <subcommand>` is unchanged (tested).
* refactor(cli): typed values and flag relations
Handlers receive typed values: convert --bit-depth is a ValueEnum, --rate a
NonZeroU32, file arguments PathBuf, --start/--end a TimeArg, --cmd a parsed
(id, JSON) spec, app's JSON a serde_json::Value, app --port and mcp --connect
a validated port or host:port. Relations (--dither/--no-dither, --in/--demo,
--start/--end needing --bounce) are declared on the flags. describe ID,
commands FILTER and app METHOD refuse an empty string. parse_rate,
parse_bit_depth, parse_dither, parse_cmd_spec, time_arg and the Rate,
BitDepth, DitherConflict and CmdJson errors are gone.
Behaviour changes:
- --dither with --no-dither is a usage error (exit 2) instead of exit 1.
- --rate 0 / non-numeric and an unknown --bit-depth are usage errors (exit 2)
with clap's wording, naming the flag. --bit-depth help lists the values.
- --in with --demo (or --sample) is a usage error; --in used to win silently.
- --start/--end without --bounce are a usage error; they used to be ignored.
- Malformed JSON in --cmd ID=JSON and in app's JSON argument is a usage error
(exit 2) at parse time. Before, run opened the engine and executed every
earlier --cmd (printing their results) before the bad one failed with exit 1.
- An empty --start/--end, an empty command id (--cmd =1), and an empty
describe ID, commands FILTER or app METHOD are usage errors. An empty
commands FILTER used to list everything.
- app --port and mcp --connect accept only a port (0-65535) or host:port;
junk used to be accepted and failed at connect time (exit 1).
- Non-Unicode file names are accepted wherever the callee takes a Path (info
audio files, convert, script, parity --write). Session and bounce/save paths
go to the engine as text, so a non-Unicode one fails with exit 1, "the path
is not valid Unicode", after any earlier --cmd ran.
* refactor(cli): shared launch flags and SOUNDCRAFT_CONTROL_PORT as clap env
soundcraft_automation::args holds the launch flags as clap Args structs:
ControlClientArgs (`app --port`, env SOUNDCRAFT_CONTROL_PORT, default
7979), ControlServerArgs (the desktop `--control`, same variable, wired
in a later step; its ControlPort value is a port, also from a loopback
host:port, or another host's host:port, which the app decides on, so one
export serves both), AutomationArgs (the two root flags, repeatable, flags
only), the ControlTarget value parser, and the blank_env_is_unset,
name_env_vars and conflict helpers. The module and its clap/thiserror
dependencies are left out of the wasm build. `app` and `mcp` flatten
them; the hand fallback to the variable in `app` is gone.
Behaviour changes:
- An empty or blank SOUNDCRAFT_CONTROL_PORT counts as unset, so `app`
uses 7979; before, it tried to connect to `127.0.0.1:` (exit 1).
- A bad SOUNDCRAFT_CONTROL_PORT is a usage error naming the variable
(exit 2); before, the connection failed (exit 1).
- Spaces around the `app --port` or `mcp --connect` value, or the
variable's, are ignored; before, the connection failed (exit 1).
- An IPv6 host in `app --port`, `mcp --connect` or the variable goes in
brackets (`[::1]:7979`); `::1:7979` is a usage error (exit 2), as the
host and port can't be told apart; before, the connection failed
(exit 1).
- `app --help` shows `[env: SOUNDCRAFT_CONTROL_PORT=]` and
`[default: 7979]` instead of the hand-written default note.
- `mcp` with a root flag and --connect is clap's conflict error (exit 2,
"the argument '...' cannot be used with '...'"), reported before any
root folder is opened; before, a custom message with exit 1, after the
roots were opened.
* refactor(app): move launch flag parsing into launch_args
The parsing moves out of main unchanged, into a LaunchArgs struct and a
parse function that takes SOUNDCRAFT_CONTROL_PORT as a parameter. Tests pin
the flags, the file list, ignored unknown flags and the fallback of a bad
--control to the variable. No behaviour change.
* refactor(app): parse launch flags with clap
soundcraft --help now comes from the LaunchArgs doc comments and ends with the
environment variables the app reads, and the shared ControlServerArgs supplies
--control and SOUNDCRAFT_CONTROL_PORT. Process tests cover the variable (bad
value, blank value, loopback host:port, another host).
Behaviour changes:
- An unknown flag (--bogus, -x) is a usage error on stderr, exit 2. It was
ignored, and a single-dash word was opened as a file; after `--` it is a file.
- A bad --control (out of range, not a number, missing value) is a usage error,
exit 2. It was ignored and the variable used instead.
- A bad SOUNDCRAFT_CONTROL_PORT is a usage error naming the variable, exit 2.
It was ignored. An empty or blank variable still counts as unset.
- A loopback host:port (127.0.0.1, localhost or [::1]) in --control or
SOUNDCRAFT_CONTROL_PORT gives its port, so the value `soundcraft-cli app`
takes from the variable works for both. The control server listens on
127.0.0.1 only, so another host in --control is a usage error. In the
variable, which may point `soundcraft-cli app` at another machine, it is
ignored with a log warning and the app opens without a control server.
Both were ignored before.
- A repeated flag is a usage error (--demo twice, --control twice).
- --control=PORT and a port with surrounding spaces are accepted; a value that
starts with `-` is not taken as the value, except a negative number, which is
a bad port (`--control -1`).
- --help ends with an Environment section listing SOUNDCRAFT_CONTROL_PORT,
SOUNDCRAFT_CONFIG_DIR, SOUNDCRAFT_NO_PREFS, SOUNDCRAFT_NO_SYSTEM_FONTS,
SOUNDCRAFT_WAYLAND (Linux) and RUST_LOG.
- --help and -h print the help, exit 0. They were ignored.
- --version and -V print `soundcraft 0.13.1 (linux x86_64)`, as soundcraft-cli
does. It printed `SoundCraft 0.13.1`.
- -V and --version are read in order with the other arguments: an earlier
error comes first.
- macOS -psn_… process serial numbers are dropped, as before they were
opened as files.
- A file whose name is not valid Unicode is skipped with a log warning. It
used to panic in std::env::args.
* feat(cli): shell completions and man pages
An example, `cargo run -p soundcraft-cli --example man-and-completions -- <out-dir>`,
writes bash, zsh, fish, elvish and PowerShell completions and soundcraft-cli.1 plus a
page per subcommand, using clap_complete and clap_mangen (dev-dependencies of
soundcraft-cli only, not in the binary).
The Linux package (deb, rpm, tar.gz, AppImage) installs the pages in
/usr/share/man/man1 and the bash, zsh and fish completions in their standard
directories; the deb also links the zsh completion into Debian's
vendor-completions. A cross build runs the example through $EMULATOR and
leaves the files out without one. The FreeBSD tarball carries them in the
ports layout; a cross build builds the example for the host as well.
No change to the CLI's behaviour. A test pins the files the example writes.
* ci(cli): check the command-line code with ast-grep rules
Adds lint/ast-grep (rules for clap errors built from strings, String as an
error type, and std::env::args) and a workflow that runs the rule tests and a
scan over the CLI code through the shared craft-common-actions workflow. No
behaviour change; the scan has no hits.
* docs(cli): document soundcraft-cli and RFC-0012
Add docs/cli.md: the subcommands, exit codes, environment variables, the
desktop app's launch flags, man pages and completions, and the RFC-0012 rules
not followed yet (convert can overwrite its input; no --compact/--json).
Link it from the README and the MCP and control-protocol guides. No code change.
* feat(cli): refuse an output that replaces an input
An output that is one of the subcommand's inputs is a usage error (exit 2,
`error: …` on stderr, clap's usage line), reported while parsing, before
the engine loads or any --cmd runs. Paths are compared by file identity
(device and inode, through same-file), or, when neither exists yet, by
where they would be created, so `a.wav`, `./a.wav`, an absolute path and a
symbolic or hard link all count as the same file.
Inputs and outputs per subcommand:
- convert: input IN, output OUT. --in-place lets OUT replace IN.
- run: input --in, outputs --bounce and --save. --in-place lets --save
replace the --in session; it requires --in. A --bounce naming the --in
session is always refused.
- script: inputs FILE and --in, outputs --bounce and --save. --in-place
lets --save replace the --in session; a --bounce naming it is always
refused, and neither may ever replace FILE.
- run and script: --bounce and --save naming one file is refused with or
without --in-place (the save would replace the bounce).
- info, commands, describe, app, mcp, plugins write no file; parity
--write has no input. Paths inside --cmd parameters are not checked.
With --in-place, an output that is a symbolic link to the input is written
to the file the link names, so convert and --save both replace the input
and leave the link in place (a save renames a new file over its path,
which would otherwise replace the link and leave the input unchanged).
Behaviour changes:
- `convert a.wav a.wav`, `run --in s.scraft --save s.scraft`,
`run --in s.scraft --bounce s.scraft` and the other cases above exit 2
instead of replacing the input.
- New flag --in-place on convert, run and script.
- An existing file that is not an input is still replaced without asking.
* feat(cli): --compact for JSON output
RFC-0012 rule 1.3: JSON is pretty-printed by default and --compact prints
one line. Every pretty-printed JSON output now goes through
output::print_json.
Changed outputs:
- info <audio file>, describe, app: new --compact flag.
- run and script: new --compact flag, which requires --inspect and applies
to the --inspect JSON only.
Unchanged on purpose:
- The `ID: JSON` result lines of run and script and the --bounce and --save
results stay one line each. The prefix makes them text records, and the
RFC lets a command document its own layout; scripts that parse them keep
working.
- commands, plugins, parity and the .scraft summary of info are text and get
no --json flag (an open question in the RFC); mcp speaks JSON-RPC lines.
Pretty output is byte-identical to before.
* fix(app): one Switch parser for boolean environment switches
SOUNDCRAFT_NO_PREFS, SOUNDCRAFT_NO_SYSTEM_FONTS and SOUNDCRAFT_WAYLAND each
counted any value, including 0, as on. They now share
soundcraft_ui_egui::switch::Switch: 1/on/true/yes is On, 0/off/false/no is
Off (case- and space-insensitive), unset or blank is Default, and any other
value is Default and logged with the variable name. The ENVIRONMENT help
text, docs/cli.md and the README say the same.
Behaviour changes (old -> new):
- SOUNDCRAFT_NO_PREFS=0 disabled preferences (any value did); now only On
does.
- SOUNDCRAFT_NO_SYSTEM_FONTS=0 disabled system fonts (any value did); now
only On does.
- SOUNDCRAFT_WAYLAND=0 kept native Wayland (any value did); now only On does.
- An empty value of any of the three counted as set; it now means the
default (off).
- An unknown value of any of the three is logged.
* refactor(app): read the environment once into Env
The desktop app reads SOUNDCRAFT_CONFIG_DIR, SOUNDCRAFT_NO_PREFS,
SOUNDCRAFT_NO_SYSTEM_FONTS and SOUNDCRAFT_WAYLAND once at startup into
env::Env (typed fields, Switch for the on/off ones), after the logger is
installed so malformed switches are logged. The --help Environment
section is generated from the same VARS table, with a test that it lists
every name.
ui-egui no longer reads the app's variables: fonts::install and
definitions take system_fonts, set through SoundApp::set_system_fonts
(default on, so the web app is unchanged). The XWayland and prefs
decisions are methods on Env, tested on literals. logging::install takes
the RUST_LOG value, which stays outside Env because the logger needs it
before anything can log.
No behaviour change beyond help column spacing.
* refactor(cli): one long_version for both binaries
* refactor(audio-io): one FileFormat table for extensions
FileFormat gains the extension table every caller matches on:
from_extension / from_path (ASCII case-insensitive) over extensions,
from_write_extension over write_extensions, default_extension, name,
mime_type, the READ and WRITE lists, and readable_extensions /
writable_extensions for dialog filters, help and messages. Reading
takes every extension the decoder knows; writing takes only the names
whose readers expect what the encoder writes (no rf64 or aifc, whose
files would get plain RIFF and AIFF headers).
detect_format, bounce (mix and stems), convert, the bounce dialog, the
desktop and web file pickers, the workspace browser, the Sampler, web
downloads and the MCP bounce schema all use it; ENCODE_EXTENSIONS and
encode_format_for are gone. convert's IN/OUT and info's FILE help name
the extensions from the read and write lists.
Behaviour changes, where the lists disagreed:
- The bounce dialog's Browse result, the bounce save filter and the MCP
bounce enum take wav, wave, bwf, aif, aiff and flac: wave and bwf are
new to all three, and aif is new to the MCP enum. convert and
file.bounce_mix already took these. The "supported:" list in the
cannot-write errors is "wav, wave, bwf, aif, aiff, flac".
- file.bounce_stems reads its format name case-insensitively: `AIFF`
or `FLAC` meant WAV before. Unknown names still mean WAV.
- The bounce dialog sends the format as its file extension (aif for
AIFF); the engine accepts both spellings.
- File pickers, the workspace browser and the Sampler's drop and Load
Sample filter list every extension the decoder reads: the workspace
browser gains wave, bwf, rf64, aifc, mp1, mp2, oga, aac, mp4, adts,
mkv and webm; the Sampler gains rf64, mp1, mp2, m4b, adts, mkv and
webm; the desktop and web open filters gain rf64, mp1, mp2 and adts.
- Web downloads get a media type for every audio format, not only WAV,
AIFF and FLAC.
* refactor(app): resolve the settings folder once in Env
* fix(app): keep paths as paths until the engine needs text
A path is text only where an engine command takes `"path": string`; a
name that is not valid Unicode is reported there instead of being opened
under a lossy rendering (another file, or a confusing "can't read").
- ui-egui: dialogs::unicode() and NotUnicode ("<path:?> is not valid
Unicode"); dialogs::open_path(app, &Path), moved from the desktop app,
is the one open-by-extension path for dropped, command-line and
Workspace files.
- Services: the file dialogs return PathBuf (pick_save and pick_folder
start from a &Path); callers convert where the text field or command
takes the path.
- Sampler drops and Load Sample pass the path to mix.sampler_load
through unicode(); the audio test checks the Path.
- Workspace panel keeps entry paths; names are shown lossily only as
labels. workspace_dir stays a String (serialized preferences).
- soundcraft-cli: utf8() is unicode(), CliError::NonUnicodePath is
NotUnicode; it is called only for info's session, --in, --bounce and
--save. convert's output format test no longer treats a non-Unicode
extension as "no extension".
- docs/cli.md: sessions and bounces the engine opens or writes must be
valid Unicode.
Behaviour changes:
- A dropped, command-line, picked or Workspace file whose name is not
valid Unicode is not opened: the status line (and log) says
"<path:?> is not valid Unicode", with the bytes escaped. Dropped files
used to be opened under a U+FFFD rendering.
- A file dialog result that is not valid Unicode leaves the path field
unchanged and shows the same warning.
- Double-clicking a Workspace file opens it like a dropped file:
.MID/.MIDI/.SCRAFT in any case open as MIDI/session (they used to
import as audio), and a failed open is logged.
- convert OUT with an extension that is not valid Unicode is refused as
an unsupported format instead of being written as WAV.
* fix(app): read Env after the launch flags; tidy Switch and Env
* fix(audio-io): decode every extension the format table lists
* fix(cli): write convert output atomically; tighten --connect and loopback
- convert writes every output to a new file in the output's folder, flushes it and renames it
over the target, removing the new file on failure. A failed write (disk full, unwritable
folder) no longer truncates the input under --in-place (RFC-0012 rule 1.6). A link output
still writes the linked file.
- --save in place already goes through the engine's replace_file (tmp + rename), and
file.bounce_mix renders to <name>.part and renames it when complete, so both are atomic.
- The desktop's --control / SOUNDCRAFT_CONTROL_PORT no longer treat [::1] as loopback: the
control server binds 127.0.0.1 only. [::1]:P is a usage error from the flag and is ignored
with a warning from the variable. The CLI's --connect / app --port still accept [::1]:P.
Error tip and docs/cli.md updated.
- mcp --connect conflicts with --demo (exit 2): the demo session belongs to the in-process
server. Help and docs/cli.md say so.
* test(audio-io): list the decode fixtures in ATTRIBUTION.md
cargo xtask assets needs a row for every committed audio file; one
directory row covers crates/audio-io/tests/fixtures/.
* fix(cli): refuse non-finite --start and --end values
* refactor(cli): parse the control target once; open sessions by path; keep error sources
- A1: ControlTarget { host, port } is parsed once by args::control_target; is_loopback() replaces
control_port/ControlPort, and Remote::new takes &ControlTarget.
- A2: engine::io::open_session takes impl AsRef<Path>; the CLI no longer requires a Unicode path
to open a session, only for the --bounce and --save paths that go into JSON.
- A3: ValueError::Json keeps the serde_json::Error; Remote::request returns RemoteError and
AutomationRoots::new returns RootError, both carried by CliError.
* test(engine): pass session paths to open_session without a borrow
* test(cli): info opens a session at a non-Unicode path
* refactor(app): log the shared long version; info: session extension in any case; Switch beside Env
720 lines
32 KiB
Rust
720 lines
32 KiB
Rust
//! Crash-recovery copies of open sessions, one folder each, written in the background, and the
|
|
//! recovery of the ones left behind with unsaved work.
|
|
|
|
use crate::io::{Recording, open_session_linked, sanitize_name};
|
|
use crate::{Engine, EngineError, Result};
|
|
use soundcraft_audio_io::{BitDepth, EncodeOptions, FileFormat};
|
|
use soundcraft_model::{Session, SourceAudio, SourceId};
|
|
use std::collections::BTreeMap;
|
|
use std::io::Write;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
|
|
use std::sync::{Arc, Mutex, PoisonError, Weak};
|
|
use std::time::{Duration, Instant, SystemTime};
|
|
|
|
const SESSION: &str = "session.scraft";
|
|
const ORIGIN: &str = "origin";
|
|
const LOCK: &str = "lock";
|
|
/// The plan of a recording still running when the folder was written.
|
|
const RECORDING: &str = "recording.json";
|
|
/// While changes keep coming, the newest is written at most this often.
|
|
const INTERVAL: Duration = Duration::from_secs(1);
|
|
const STOPPED: &str = "the autosave thread stopped";
|
|
|
|
/// Writes autosaves on a thread of its own, so the UI never waits on the disk.
|
|
pub struct Autosaver {
|
|
jobs: Option<Sender<Job>>,
|
|
thread: Option<std::thread::JoinHandle<()>>,
|
|
failure: Arc<Mutex<Option<String>>>,
|
|
}
|
|
|
|
enum Job {
|
|
Write(Arc<Session>, Option<String>, Option<Recording>),
|
|
/// Done with the session's folder: keep it for the next launch, or delete it.
|
|
Close(bool),
|
|
Flush(Sender<std::result::Result<(), String>>),
|
|
}
|
|
|
|
impl Autosaver {
|
|
/// A writer for autosave folders under `root`.
|
|
pub fn new(root: PathBuf) -> Autosaver {
|
|
let (tx, rx) = channel();
|
|
let failure = Arc::new(Mutex::new(None));
|
|
let writer = Writer { root, failure: Arc::clone(&failure), folder: None, pending: None, last: None, written: Ok(()) };
|
|
let thread = std::thread::Builder::new().name("soundcraft-autosave".into()).spawn(move || writer.run(&rx));
|
|
if let Err(e) = &thread {
|
|
report(&failure, format!("{STOPPED}: {e}"));
|
|
}
|
|
Autosaver { jobs: Some(tx), thread: thread.ok(), failure }
|
|
}
|
|
|
|
/// Autosave `session`, opened from the session file `origin`, soon, with the plan of the
|
|
/// recording running in it.
|
|
pub fn write(&self, session: Arc<Session>, origin: Option<String>, recording: Option<Recording>) {
|
|
self.send(Job::Write(session, origin, recording));
|
|
}
|
|
|
|
/// Done with the open session's folder: keep it for the next launch, or delete it.
|
|
pub fn close(&self, keep: bool) {
|
|
self.send(Job::Close(keep));
|
|
}
|
|
|
|
/// Wait until everything handed over so far is done. A failure returned here isn't reported
|
|
/// again by `failure`.
|
|
pub fn flush(&self) -> Result<()> {
|
|
let (tx, rx) = channel();
|
|
self.send(Job::Flush(tx));
|
|
let done = rx.recv().unwrap_or_else(|_| Err(STOPPED.into()));
|
|
if done.is_err() {
|
|
self.failure();
|
|
}
|
|
done.map_err(EngineError::Io)
|
|
}
|
|
|
|
/// The newest failure since the last call.
|
|
pub fn failure(&self) -> Option<String> {
|
|
self.failure.lock().unwrap_or_else(PoisonError::into_inner).take()
|
|
}
|
|
|
|
fn send(&self, job: Job) {
|
|
if self.jobs.as_ref().is_none_or(|tx| tx.send(job).is_err()) {
|
|
report(&self.failure, STOPPED.into());
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for Autosaver {
|
|
/// What was handed over is written, and an open folder stays for the next launch.
|
|
fn drop(&mut self) {
|
|
drop(self.jobs.take());
|
|
if let Some(t) = self.thread.take() {
|
|
let _ = t.join();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The writer thread.
|
|
struct Writer {
|
|
root: PathBuf,
|
|
failure: Arc<Mutex<Option<String>>>,
|
|
/// The open session's folder.
|
|
folder: Option<Autosave>,
|
|
/// The newest session not written yet.
|
|
pending: Option<(Arc<Session>, Option<String>, Option<Recording>)>,
|
|
last: Option<Instant>,
|
|
/// How the newest write into the open folder went, for `Flush`.
|
|
written: std::result::Result<(), String>,
|
|
}
|
|
|
|
impl Writer {
|
|
fn run(mut self, jobs: &Receiver<Job>) {
|
|
loop {
|
|
let wait = match (&self.pending, self.last) {
|
|
(None, _) => Duration::MAX,
|
|
(Some(_), last) => last.map_or(Duration::ZERO, |t| INTERVAL.saturating_sub(t.elapsed())),
|
|
};
|
|
match jobs.recv_timeout(wait) {
|
|
Ok(Job::Write(session, origin, recording)) => self.pending = Some((session, origin, recording)),
|
|
Ok(Job::Flush(reply)) => {
|
|
self.write_pending();
|
|
let _ = reply.send(self.written.clone());
|
|
}
|
|
Ok(Job::Close(keep)) => {
|
|
if keep {
|
|
self.write_pending();
|
|
}
|
|
self.pending = None;
|
|
self.written = Ok(());
|
|
if let Some(a) = self.folder.take()
|
|
&& !keep
|
|
{
|
|
a.discard();
|
|
}
|
|
}
|
|
Err(RecvTimeoutError::Timeout) => self.write_pending(),
|
|
Err(RecvTimeoutError::Disconnected) => {
|
|
self.write_pending();
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn write_pending(&mut self) {
|
|
let Some((session, origin, recording)) = self.pending.take() else { return };
|
|
self.last = Some(Instant::now());
|
|
let written = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
|
|
if self.folder.is_none() {
|
|
self.folder = Some(Autosave::create(&self.root, &session.name)?);
|
|
}
|
|
self.folder.as_mut().map_or(Ok(()), |a| a.write(&session, origin.as_deref(), recording.as_ref()))
|
|
}));
|
|
self.written = match written {
|
|
Ok(written) => written.map_err(|e| e.to_string()),
|
|
Err(_) => Err("internal error (see the log)".into()),
|
|
};
|
|
if let Err(e) = &self.written {
|
|
report(&self.failure, e.clone());
|
|
}
|
|
}
|
|
}
|
|
|
|
fn report(failure: &Mutex<Option<String>>, e: String) {
|
|
log::warn!("autosave failed: {e}");
|
|
*failure.lock().unwrap_or_else(PoisonError::into_inner) = Some(e);
|
|
}
|
|
|
|
/// An open session's autosave folder, locked while the session is open so a later launch can tell
|
|
/// it from one a crash left behind.
|
|
struct Autosave {
|
|
dir: PathBuf,
|
|
lock: Option<std::fs::File>,
|
|
copies: BTreeMap<SourceId, (Weak<SourceAudio>, String)>,
|
|
next: u64,
|
|
/// A recording's plan is in the folder.
|
|
recording: bool,
|
|
}
|
|
|
|
impl Autosave {
|
|
/// A new folder under `root` for the session called `name`. Two sessions started within the
|
|
/// same millisecond get folders of their own, never a shared one.
|
|
fn create(root: &Path, name: &str) -> Result<Autosave> {
|
|
let stamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default().as_millis();
|
|
let base = format!("{} {stamp}-{}", sanitize_name(name), std::process::id());
|
|
create_folder(root).map_err(|err| io_error(root, err))?;
|
|
let mut dir = root.join(&base);
|
|
let mut n = 1;
|
|
loop {
|
|
// Not recursive, so a folder that already exists is reported and the next name tried.
|
|
#[cfg_attr(not(unix), allow(unused_mut))]
|
|
let mut builder = std::fs::DirBuilder::new();
|
|
#[cfg(unix)]
|
|
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
|
match builder.create(&dir) {
|
|
Ok(()) => break,
|
|
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
|
|
n += 1;
|
|
dir = root.join(format!("{base}-{n}"));
|
|
}
|
|
Err(err) => return Err(io_error(&dir, err)),
|
|
}
|
|
}
|
|
let lock = std::fs::File::create(dir.join(LOCK)).map_err(|err| io_error(&dir, err))?;
|
|
lock.try_lock().map_err(|err| EngineError::Io(format!("{}: {err}", dir.display())))?;
|
|
Ok(Autosave { dir, lock: Some(lock), copies: BTreeMap::new(), next: 1, recording: false })
|
|
}
|
|
|
|
/// Write `session`, opened from the session file `origin`, and the plan of the `recording`
|
|
/// running in it. Audio saved with it is referenced where it is; audio that exists only in
|
|
/// memory is copied, once per recording or render.
|
|
fn write(&mut self, session: &Session, origin: Option<&str>, recording: Option<&Recording>) -> Result<()> {
|
|
let base = origin.and_then(|p| Path::new(p).parent()).and_then(|p| std::path::absolute(p).ok());
|
|
let audio_dir = self.dir.join("Audio Files");
|
|
let mut s = session.clone();
|
|
let mut copies = BTreeMap::new();
|
|
for src in &mut s.sources {
|
|
let file = if Path::new(&src.path).is_absolute() { Some(PathBuf::from(&src.path)) } else { base.as_ref().map(|b| b.join(&src.path)) };
|
|
let audio = s.pool.get(src.id);
|
|
if let Some(f) = &file
|
|
&& (audio.is_none() || !src.unsaved && f.is_file())
|
|
{
|
|
src.path = f.to_string_lossy().into_owned();
|
|
continue;
|
|
}
|
|
let Some(audio) = audio else { continue };
|
|
let name = match self.copies.remove(&src.id) {
|
|
Some((copy, name)) if copy.upgrade().is_some_and(|a| Arc::ptr_eq(&a, audio)) => name,
|
|
_ => {
|
|
let name = format!("{} {}.wav", sanitize_name(&src.name), self.next);
|
|
self.next += 1;
|
|
let opts = EncodeOptions { format: FileFormat::Wav, bit_depth: BitDepth::Float32, dither: false, bwf: None };
|
|
let bytes = soundcraft_audio_io::encode(&audio.buffer, &opts).map_err(|err| EngineError::Io(err.to_string()))?;
|
|
create_folder(&audio_dir).and_then(|()| write_synced(&audio_dir.join(&name), &bytes)).map_err(|err| io_error(&audio_dir, err))?;
|
|
name
|
|
}
|
|
};
|
|
src.path = audio_dir.join(&name).to_string_lossy().into_owned();
|
|
src.unsaved = true;
|
|
copies.insert(src.id, (Arc::downgrade(audio), name));
|
|
}
|
|
let text = s.to_json().map_err(|err| EngineError::Io(err.to_string()))?;
|
|
write_atomically(&self.dir.join(ORIGIN), origin.unwrap_or_default().as_bytes())?;
|
|
write_atomically(&self.dir.join(SESSION), text.as_bytes())?;
|
|
for (_, name) in std::mem::replace(&mut self.copies, copies).into_values() {
|
|
let _ = std::fs::remove_file(audio_dir.join(name));
|
|
}
|
|
if let Some(r) = recording {
|
|
let plan = serde_json::to_string(r).map_err(|err| EngineError::Io(err.to_string()))?;
|
|
write_atomically(&self.dir.join(RECORDING), plan.as_bytes())?;
|
|
} else if self.recording {
|
|
let _ = std::fs::remove_file(self.dir.join(RECORDING));
|
|
}
|
|
self.recording = recording.is_some();
|
|
Ok(())
|
|
}
|
|
|
|
/// Delete the folder: the session closed with nothing left to recover.
|
|
fn discard(mut self) {
|
|
drop(self.lock.take());
|
|
let _ = std::fs::remove_dir_all(&self.dir);
|
|
}
|
|
}
|
|
|
|
/// Unsaved work left behind in an autosave folder.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Leftover {
|
|
pub dir: PathBuf,
|
|
/// The session's name.
|
|
pub name: String,
|
|
/// The session file it was autosaved from, if it had one.
|
|
pub origin: Option<String>,
|
|
pub saved: SystemTime,
|
|
/// A recording was still running in it.
|
|
pub recording: bool,
|
|
}
|
|
|
|
/// Leftover autosaves under `root`, newest first: folders no open session holds, written after the
|
|
/// session file they came from or holding a recording. Empty and outdated ones are deleted.
|
|
pub fn leftovers(root: &Path) -> Vec<Leftover> {
|
|
let mut out = Vec::new();
|
|
for dir in std::fs::read_dir(root).into_iter().flatten().flatten().map(|d| d.path()) {
|
|
let Ok(lock) = std::fs::OpenOptions::new().write(true).open(dir.join(LOCK)) else { continue };
|
|
if lock.try_lock().is_err() {
|
|
continue;
|
|
}
|
|
let origin = std::fs::read_to_string(dir.join(ORIGIN)).ok().filter(|o| !o.is_empty());
|
|
let origin_saved = origin.as_ref().and_then(|o| std::fs::metadata(o).and_then(|m| m.modified()).ok());
|
|
let saved = std::fs::metadata(dir.join(SESSION)).and_then(|m| m.modified());
|
|
let recording = dir.join(RECORDING).is_file();
|
|
drop(lock);
|
|
match saved {
|
|
Ok(saved) if recording || origin_saved.is_none_or(|o| saved > o) => {
|
|
let text = std::fs::read_to_string(dir.join(SESSION)).unwrap_or_default();
|
|
let named = serde_json::from_str::<serde_json::Value>(&text).ok().and_then(|v| v.get("name")?.as_str().map(str::to_string));
|
|
let name = named.unwrap_or_else(|| dir.file_name().unwrap_or_default().to_string_lossy().into_owned());
|
|
out.push(Leftover { dir, name, origin, saved, recording });
|
|
}
|
|
_ => {
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
}
|
|
}
|
|
out.sort_by_key(|l| std::cmp::Reverse(l.saved));
|
|
out
|
|
}
|
|
|
|
/// Open `left` as an unsaved version of the session it came from, so Save writes it back there,
|
|
/// with the takes of a recording that never finished placed as Stop would have. Returns the
|
|
/// media that couldn't be loaded.
|
|
pub fn recover(e: &mut Engine, left: &Leftover) -> Result<Vec<String>> {
|
|
let mut r = Engine::default();
|
|
let session = left.dir.join(SESSION);
|
|
let links = left.origin.as_deref().map_or(session.as_path(), Path::new);
|
|
let mut missing = open_session_linked(&mut r, &session, links)?;
|
|
let mut s = r.session().clone();
|
|
let unfinished = unfinished_takes(left, &s, &mut missing);
|
|
if let Some(home) = left.origin.as_deref().and_then(|o| Path::new(o).parent()) {
|
|
for src in s.sources.iter_mut().filter(|src| !src.unsaved) {
|
|
if let Ok(rel) = Path::new(&src.path).strip_prefix(home) {
|
|
src.path = rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/");
|
|
}
|
|
}
|
|
}
|
|
e.replace_session(Session::default());
|
|
*e.session_mut() = s;
|
|
e.path = left.origin.clone();
|
|
if let Some((plan, takes)) = unfinished {
|
|
crate::io::place_recording(e, &plan, takes);
|
|
}
|
|
Ok(missing)
|
|
}
|
|
|
|
/// The takes of the recording `left` holds the plan of, repaired, minus those already in `s`.
|
|
/// A take the plan names that isn't a take file SoundCraft recorded, in a folder it records into,
|
|
/// is left untouched and added to `skipped`.
|
|
fn unfinished_takes(left: &Leftover, s: &Session, skipped: &mut Vec<String>) -> Option<(Recording, Vec<(soundcraft_model::TrackId, PathBuf)>)> {
|
|
let plan: Recording = serde_json::from_str(&std::fs::read_to_string(left.dir.join(RECORDING)).ok()?).ok()?;
|
|
let known: Vec<PathBuf> =
|
|
s.sources.iter().filter(|src| s.pool.get(src.id).is_some()).filter_map(|src| std::fs::canonicalize(&src.path).ok()).collect();
|
|
let folders = take_folders(left);
|
|
let mut takes = Vec::new();
|
|
for t in &plan.takes {
|
|
if std::fs::canonicalize(&t.path).is_ok_and(|p| known.contains(&p)) {
|
|
continue;
|
|
}
|
|
match repair_take(&t.path, &folders, t.channels, plan.rate) {
|
|
Ok(frames) if frames > 0 => takes.push((t.track, t.path.clone())),
|
|
Ok(_) => {}
|
|
Err(err) => {
|
|
log::warn!("recovery skipped the take {}: {err}", t.path.display());
|
|
skipped.push(format!("{}: {err}", t.path.display()));
|
|
}
|
|
}
|
|
}
|
|
Some((plan, takes))
|
|
}
|
|
|
|
/// The folders a recording in `left`'s session writes its takes into: the `Audio Files` next to
|
|
/// the session file, or, never saved, the one in its folder under the autosave root.
|
|
fn take_folders(left: &Leftover) -> Vec<PathBuf> {
|
|
let saved = left.origin.as_deref().and_then(|o| Path::new(o).parent()).map(|d| d.join("Audio Files"));
|
|
let unsaved = left.dir.parent().map(|root| root.join(sanitize_name(&left.name)).join("Audio Files"));
|
|
saved.into_iter().chain(unsaved).filter_map(|d| std::fs::canonicalize(d).ok()).collect()
|
|
}
|
|
|
|
/// Make a take file's header cover all the audio in it; returns its frames. The recorder
|
|
/// rewrites the header only every second, so a crash leaves up to a second uncovered. Only a
|
|
/// regular file in one of `folders` that starts with the header the recorder writes is touched.
|
|
fn repair_take(path: &Path, folders: &[PathBuf], channels: usize, rate: u32) -> std::io::Result<u64> {
|
|
let refuse = |why: &str| std::io::Error::new(std::io::ErrorKind::InvalidData, why.to_string());
|
|
if !std::fs::symlink_metadata(path)?.file_type().is_file() {
|
|
return Err(refuse("not a regular file"));
|
|
}
|
|
let folder = path.parent().and_then(|d| std::fs::canonicalize(d).ok());
|
|
if !folder.is_some_and(|d| folders.contains(&d)) {
|
|
return Err(refuse("not in a folder SoundCraft records into"));
|
|
}
|
|
let header = |frames| soundcraft_audio_io::wav_float_header(channels, rate, frames).map_err(std::io::Error::other);
|
|
let expected = header(0)?;
|
|
let mut f = std::fs::OpenOptions::new().read(true).write(true).open(path)?;
|
|
let mut head = vec![0u8; expected.len()];
|
|
if std::io::Read::read_exact(&mut f, &mut head).is_err() || !is_take_header(&head, &expected) {
|
|
return Err(refuse("not a take SoundCraft recorded"));
|
|
}
|
|
let audio = f.metadata()?.len().saturating_sub(expected.len() as u64);
|
|
let frames = audio / (channels.max(1) as u64 * 4);
|
|
std::io::Seek::rewind(&mut f)?;
|
|
f.write_all(&header(frames)?)?;
|
|
f.sync_all()?;
|
|
Ok(frames)
|
|
}
|
|
|
|
/// `head` is a take header like `expected` (the recorder's header for no frames yet): RIFF or
|
|
/// RF64 WAVE, the same format chunk at the same place, and the data chunk right after it all.
|
|
/// Only the sizes and frame counts may differ.
|
|
fn is_take_header(head: &[u8], expected: &[u8]) -> bool {
|
|
let magic = matches!(head.get(..4), Some(b"RIFF" | b"RF64")) && head.get(8..12) == Some(b"WAVE");
|
|
let fmt = expected.windows(4).position(|w| w == b"fmt ");
|
|
let fmt_len = fmt.and_then(|at| expected.get(at + 4..at + 8)).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
|
|
let same_fmt = match (fmt, fmt_len) {
|
|
(Some(at), Some(n)) => {
|
|
let end = at.saturating_add(8).saturating_add(n as usize);
|
|
expected.get(at..end).is_some_and(|chunk| head.get(at..end) == Some(chunk))
|
|
}
|
|
_ => false,
|
|
};
|
|
let data = expected.len().checked_sub(8).and_then(|at| head.get(at..at + 4)) == Some(b"data");
|
|
magic && same_fmt && data
|
|
}
|
|
|
|
/// Delete a leftover autosave.
|
|
pub fn discard(left: &Leftover) {
|
|
let _ = std::fs::remove_dir_all(&left.dir);
|
|
}
|
|
|
|
/// Create `dir` and its missing parents under the autosave root. On Unix every folder made here is
|
|
/// owner-only (`0o700`): autosaves and the takes of a session never saved are unsaved work, and
|
|
/// with the default mode other accounts on the machine could read them. A folder that already
|
|
/// exists keeps its mode.
|
|
pub fn create_folder(dir: &Path) -> std::io::Result<()> {
|
|
let mut builder = std::fs::DirBuilder::new();
|
|
builder.recursive(true);
|
|
#[cfg(unix)]
|
|
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
|
builder.create(dir)
|
|
}
|
|
|
|
fn write_synced(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
|
let mut f = std::fs::File::create(path)?;
|
|
f.write_all(bytes)?;
|
|
f.sync_all()
|
|
}
|
|
|
|
fn write_atomically(path: &Path, bytes: &[u8]) -> Result<()> {
|
|
let tmp = path.with_extension("tmp");
|
|
write_synced(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|err| {
|
|
let _ = std::fs::remove_file(&tmp);
|
|
io_error(path, err)
|
|
})
|
|
}
|
|
|
|
fn io_error(path: &Path, err: std::io::Error) -> EngineError {
|
|
EngineError::Io(format!("{}: {err}", path.display()))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::io::open_session;
|
|
use serde_json::json;
|
|
use soundcraft_audio_io::AudioBuffer;
|
|
use soundcraft_model::{ChannelFormat, Clip, TrackKind};
|
|
|
|
fn folder(name: &str) -> PathBuf {
|
|
let dir = std::env::temp_dir().join(format!("soundcraft-{name}-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
dir
|
|
}
|
|
|
|
/// Moves a saved session file's mtime a second into the past. Filesystems with coarse
|
|
/// timestamps (tmpfs) can give it and an autosave written right after it the same mtime,
|
|
/// and `leftovers` only offers autosaves strictly newer than the file they came from.
|
|
fn backdate(path: &Path) {
|
|
let then = SystemTime::now() - Duration::from_secs(1);
|
|
std::fs::File::options().write(true).open(path).unwrap().set_modified(then).unwrap();
|
|
}
|
|
|
|
fn record(e: &mut Engine, level: f32) {
|
|
let before = e.session_arc();
|
|
let s = e.session_mut();
|
|
let t = match s.tracks.first() {
|
|
Some(t) => t.id,
|
|
None => s.add_track(TrackKind::Audio, ChannelFormat::Mono, None),
|
|
};
|
|
let src =
|
|
crate::io::add_source(s, "Audio 1_01", AudioBuffer { sample_rate: 48_000, channels: vec![vec![level; 4_800]] }, None, FileFormat::Wav);
|
|
let id = s.new_clip_id();
|
|
crate::edit::place_clip(s, t, Clip::audio(id, "Audio 1_01", src, 0, 0, 4_800));
|
|
e.push_undo("Record", before);
|
|
}
|
|
|
|
fn levels(e: &Engine) -> Vec<f32> {
|
|
let s = e.session();
|
|
s.sources.iter().map(|src| s.pool.get(src.id).map_or(f32::NAN, |a| a.buffer.channels[0][0])).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn saved_audio_is_referenced_and_takes_are_copied_once() {
|
|
let dir = folder("autosave-copies");
|
|
let path = dir.join("Song/Song.scraft");
|
|
let mut e = Engine::default();
|
|
record(&mut e, 0.5);
|
|
crate::io::save_session(&mut e, &path.to_string_lossy()).unwrap();
|
|
backdate(&path);
|
|
record(&mut e, -0.25);
|
|
let mut a = Autosave::create(&dir.join("Autosave"), "Song").unwrap();
|
|
a.write(e.session(), e.path.as_deref(), None).unwrap();
|
|
a.write(e.session(), e.path.as_deref(), None).unwrap();
|
|
assert_eq!(std::fs::read_dir(a.dir.join("Audio Files")).unwrap().count(), 1);
|
|
drop(a);
|
|
let left = leftovers(&dir.join("Autosave"));
|
|
let mut r = Engine::default();
|
|
assert_eq!(recover(&mut r, &left[0]).unwrap(), Vec::<String>::new());
|
|
let paths: Vec<_> = r.session().sources.iter().map(|s| (s.path.starts_with("Audio Files/"), s.unsaved)).collect();
|
|
assert_eq!(paths, [(true, false), (false, true)]);
|
|
assert_eq!(levels(&r), [0.5, -0.25]);
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn a_take_recorded_after_undo_gets_its_own_copy() {
|
|
let dir = folder("autosave-undo");
|
|
let mut e = Engine::default();
|
|
record(&mut e, 0.5);
|
|
let mut a = Autosave::create(&dir, "Untitled").unwrap();
|
|
a.write(e.session(), None, None).unwrap();
|
|
e.execute("edit.undo", &json!({})).unwrap();
|
|
record(&mut e, -0.25);
|
|
a.write(e.session(), None, None).unwrap();
|
|
drop(a);
|
|
let mut r = Engine::default();
|
|
recover(&mut r, &leftovers(&dir)[0]).unwrap();
|
|
assert_eq!(levels(&r), [-0.25]);
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn the_writer_saves_the_newest_change_and_drops_the_folder_when_done() {
|
|
let root = folder("autosave-writer");
|
|
let w = Autosaver::new(root.clone());
|
|
let mut e = Engine::default();
|
|
for _ in 0..5 {
|
|
record(&mut e, 0.5);
|
|
w.write(e.session_arc(), None, None);
|
|
}
|
|
w.flush().unwrap();
|
|
let file = std::fs::read_dir(&root).unwrap().flatten().map(|d| d.path().join(SESSION)).collect::<Vec<_>>();
|
|
let mut r = Engine::default();
|
|
open_session(&mut r, &file[0]).unwrap();
|
|
assert_eq!((file.len(), r.session().sources.len()), (1, 5));
|
|
w.close(false);
|
|
w.flush().unwrap();
|
|
assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0);
|
|
record(&mut e, 0.5);
|
|
w.write(e.session_arc(), None, None);
|
|
drop(w);
|
|
let mut r = Engine::default();
|
|
recover(&mut r, &leftovers(&root)[0]).unwrap();
|
|
assert_eq!(r.session().sources.len(), 6);
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
}
|
|
|
|
/// Autosaves are unsaved work: on Unix the folders the autosaver makes are owner-only, and an
|
|
/// autosave root that already exists keeps its mode.
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn the_autosaver_makes_owner_only_folders() {
|
|
use std::os::unix::fs::PermissionsExt as _;
|
|
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
|
|
let base = folder("autosave-modes");
|
|
let mut e = Engine::default();
|
|
record(&mut e, 0.5);
|
|
// A root that doesn't exist yet is made with the first autosave, owner-only like the
|
|
// session's folder and the audio copied into it.
|
|
let new = base.join("Autosave");
|
|
let w = Autosaver::new(new.clone());
|
|
w.write(e.session_arc(), None, None);
|
|
w.flush().unwrap();
|
|
let session = std::fs::read_dir(&new).unwrap().flatten().map(|d| d.path()).next().unwrap();
|
|
assert_eq!((mode(&new), mode(&session), mode(&session.join("Audio Files"))), (0o700, 0o700, 0o700));
|
|
w.close(false);
|
|
w.flush().unwrap();
|
|
// A root that already exists keeps its mode; the folders made inside it are owner-only.
|
|
let old = base.join("old");
|
|
std::fs::create_dir_all(&old).unwrap();
|
|
std::fs::set_permissions(&old, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
let w = Autosaver::new(old.clone());
|
|
w.write(e.session_arc(), None, None);
|
|
w.flush().unwrap();
|
|
let session = std::fs::read_dir(&old).unwrap().flatten().map(|d| d.path()).next().unwrap();
|
|
assert_eq!((mode(&old), mode(&session)), (0o755, 0o700));
|
|
// A session never saved records its takes into `<name>/Audio Files` under the root. Both
|
|
// are made owner-only, and so is `Audio Files` in a take folder an earlier version left.
|
|
let takes = old.join("Untitled").join("Audio Files");
|
|
create_folder(&takes).unwrap();
|
|
assert_eq!((mode(&old.join("Untitled")), mode(&takes)), (0o700, 0o700));
|
|
let earlier = old.join("Earlier");
|
|
std::fs::create_dir_all(&earlier).unwrap();
|
|
std::fs::set_permissions(&earlier, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
create_folder(&earlier.join("Audio Files")).unwrap();
|
|
assert_eq!((mode(&earlier), mode(&earlier.join("Audio Files"))), (0o755, 0o700));
|
|
w.close(false);
|
|
w.flush().unwrap();
|
|
let _ = std::fs::remove_dir_all(&base);
|
|
}
|
|
|
|
#[test]
|
|
fn a_take_still_recording_at_a_crash_is_placed_on_recovery() {
|
|
use crate::io::Take;
|
|
let dir = folder("autosave-take");
|
|
let root = dir.join("Autosave");
|
|
let mut e = Engine::default();
|
|
let track =
|
|
soundcraft_model::TrackId(e.execute("track.new", &json!({"name": "Vox", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap());
|
|
let take = root.join(sanitize_name(&e.session().name)).join("Audio Files/Vox_01.wav");
|
|
std::fs::create_dir_all(take.parent().unwrap()).unwrap();
|
|
let audio: Vec<u8> = (0..480).flat_map(|i| (i as f32 / 1000.0).to_le_bytes()).collect();
|
|
std::fs::write(&take, [soundcraft_audio_io::wav_float_header(1, 48_000, 100).unwrap(), audio].concat()).unwrap();
|
|
let plan = Recording { start: 48_000, pass: None, punch: None, rate: 48_000, takes: vec![Take { track, path: take, channels: 1 }] };
|
|
let clips = |e: &Engine| e.session().track(track).unwrap().clips().iter().map(|c| (c.start, c.length)).collect::<Vec<_>>();
|
|
let w = Autosaver::new(root.clone());
|
|
w.write(e.session_arc(), None, Some(plan.clone()));
|
|
drop(w);
|
|
let left = leftovers(&root);
|
|
assert!(left[0].recording);
|
|
let mut r = Engine::default();
|
|
recover(&mut r, &left[0]).unwrap();
|
|
assert_eq!(clips(&r), [(48_000, 480)], "all of the take, its last second included");
|
|
discard(&left[0]);
|
|
let w = Autosaver::new(root.clone());
|
|
w.write(r.session_arc(), None, Some(plan));
|
|
drop(w);
|
|
let mut again = Engine::default();
|
|
recover(&mut again, &leftovers(&root)[0]).unwrap();
|
|
assert_eq!((clips(&again), again.session().sources.len()), (vec![(48_000, 480)], 1), "placed once");
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn recovery_never_writes_a_file_that_isnt_a_take_in_a_take_folder() {
|
|
use crate::io::Take;
|
|
let dir = folder("autosave-hostile-take");
|
|
let root = dir.join("Autosave");
|
|
let mut e = Engine::default();
|
|
let track =
|
|
soundcraft_model::TrackId(e.execute("track.new", &json!({"name": "Vox", "format": "mono"})).unwrap()["tracks"][0].as_u64().unwrap());
|
|
let takes = root.join(sanitize_name(&e.session().name)).join("Audio Files");
|
|
std::fs::create_dir_all(&takes).unwrap();
|
|
let wav = [soundcraft_audio_io::wav_float_header(1, 48_000, 0).unwrap(), vec![0; 4_000]].concat();
|
|
let text = b"not audio at all, but long enough to be mistaken for a header if nobody looked at it ......".repeat(4);
|
|
let files =
|
|
[(takes.join("notes.wav"), text.clone()), (dir.join("Elsewhere/Vox_01.wav"), wav.clone()), (takes.join("../Vox_02.wav"), wav.clone())];
|
|
for (path, bytes) in &files {
|
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
|
std::fs::write(path, bytes).unwrap();
|
|
}
|
|
// Only the symlink case below adds to it, and symlinks are a Unix-only part of the test.
|
|
#[cfg_attr(not(unix), allow(unused_mut))]
|
|
let mut paths: Vec<PathBuf> = files.iter().map(|(p, _)| p.clone()).collect();
|
|
#[cfg(unix)]
|
|
{
|
|
let link = takes.join("Vox_03.wav");
|
|
std::os::unix::fs::symlink(&files[1].0, &link).unwrap();
|
|
paths.push(link);
|
|
}
|
|
let plan = Recording {
|
|
start: 0,
|
|
pass: None,
|
|
punch: None,
|
|
rate: 48_000,
|
|
takes: paths.iter().map(|p| Take { track, path: p.clone(), channels: 1 }).collect(),
|
|
};
|
|
let w = Autosaver::new(root.clone());
|
|
w.write(e.session_arc(), None, Some(plan));
|
|
drop(w);
|
|
let mut r = Engine::default();
|
|
let skipped = recover(&mut r, &leftovers(&root)[0]).unwrap();
|
|
assert_eq!(skipped.len(), paths.len(), "{skipped:?}");
|
|
assert!(r.session().sources.is_empty());
|
|
for (path, bytes) in &files {
|
|
assert_eq!(&std::fs::read(path).unwrap(), bytes, "{} untouched", path.display());
|
|
}
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn sessions_started_together_get_folders_of_their_own() {
|
|
// #579: the folder name has millisecond resolution, so two sessions created back to back
|
|
// shared one folder and the second overwrote the first's unsaved work.
|
|
let dir = folder("autosave-unique");
|
|
let root = dir.join("Autosave");
|
|
let made: Vec<Autosave> = (0..20).map(|_| Autosave::create(&root, "Song").unwrap()).collect();
|
|
let mut dirs: Vec<&PathBuf> = made.iter().map(|a| &a.dir).collect();
|
|
dirs.sort();
|
|
dirs.dedup();
|
|
assert_eq!(dirs.len(), made.len());
|
|
drop(made);
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
|
|
#[test]
|
|
fn unsaved_work_is_offered_once_its_session_closes() {
|
|
let dir = folder("autosave-leftovers");
|
|
let path = dir.join("Song.scraft").to_string_lossy().into_owned();
|
|
let root = dir.join("Autosave");
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let mut e = Engine::default();
|
|
crate::io::save_session(&mut e, &path).unwrap();
|
|
backdate(Path::new(&path));
|
|
record(&mut e, 0.5);
|
|
let mut a = Autosave::create(&root, "Song").unwrap();
|
|
a.write(e.session(), e.path.as_deref(), None).unwrap();
|
|
assert!(leftovers(&root).is_empty());
|
|
drop(a);
|
|
let left = leftovers(&root);
|
|
assert_eq!((left.len(), left[0].name.as_str(), left[0].origin.as_deref()), (1, "Song", Some(path.as_str())));
|
|
let mut r = Engine::default();
|
|
recover(&mut r, &left[0]).unwrap();
|
|
assert!(r.is_dirty());
|
|
r.execute("session.save", &json!({})).unwrap();
|
|
assert!(leftovers(&root).is_empty());
|
|
assert!(!left[0].dir.exists());
|
|
let mut reopened = Engine::default();
|
|
open_session(&mut reopened, &path).unwrap();
|
|
assert_eq!(levels(&reopened), [0.5]);
|
|
Autosave::create(&root, "Song").unwrap().discard();
|
|
assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0);
|
|
let _ = std::fs::remove_dir_all(&dir);
|
|
}
|
|
}
|