forge
Explore
Log in

Don't you dare go Hollow

A song opens as a timeline of its own

Browse files at this commit

eb9a278a46a20b746493ea4d23abf2ec77e7290dAhmet Kaan GümüşParent: 2dd4b74
  • feat
    • a song opens as a timeline of its own
Show full message
✨ feat(audio): a song opens as a timeline of its own

An audio file could not start a project: `PlaybackSession::open` refused
every `is_audio` path because a timeline was scaffolded from source 0's
*picture*. It now scaffolds the canvas instead -- 1080p at 30 fps H.264,
the rate a later video import is held to -- takes its length from the
audio, puts the one clip on `A1` and leaves the video lane empty, so the
existing gap path plays it black while the song keeps the clock.

`open_project` does the same when source 0 has no picture, so an
audio-only `.edith` loads. An mp4 of such a timeline is refused by name
in `export::start` (it would be black over the sound) and the export
card says so on the MP4 row before a destination is picked; WAV and FLAC
export as they always did. The Export button now re-asks that question
too, since mp4 is the default and a timeline can lose its picture after
the format was chosen.
crates/app/src/main.rsmodified+72 -0
@@ -1619,6 +1619,15 @@ impl Player {
1619 cx.notify();1619 cx.notify();
1620 return;1620 return;
1621 }1621 }
1622+ // The format row can be refused *after* it was picked -- mp4 is the
1623+ // default and an audio-only timeline (or a second audio lane) is one
1624+ // edit away -- so the button asks again rather than starting a worker
1625+ // that will only settle with the same refusal minutes later.
1626+ if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) {
1627+ self.notice = Some(format!("NOT EXPORTED — {why}").into());
1628+ cx.notify();
1629+ return;
1630+ }
1622 session.pause();1631 session.pause();
1623 self.export = Some(session.export_to_with(&self.export_path, &settings));1632 self.export = Some(session.export_to_with(&self.export_path, &settings));
1624 // The card has been answered; the progress line takes the panel from1633 // The card has been answered; the progress line takes the panel from
@@ -4403,7 +4412,19 @@ fn is_bare_modifier(key: &str) -> bool {
4403 /// timeline whose sound is spread over more than one audio lane is refused by4412 /// timeline whose sound is spread over more than one audio lane is refused by
4404 /// the engine (`export::run`). Said on the row, before a destination has been4413 /// the engine (`export::run`). Said on the row, before a destination has been
4405 /// picked, rather than after the write has started.4414 /// picked, rather than after the write has started.
4415+///
4416+/// An audio-only timeline is the other one: every frame of it is a gap, so the
4417+/// mp4 would be a black picture over the sound. The engine refuses it too
4418+/// (`export::start`); this is what greys the row before a destination has been
4419+/// picked.
4406 fn mp4_refusal(session: &PlaybackSession) -> Option<String> {4420 fn mp4_refusal(session: &PlaybackSession) -> Option<String> {
4421+ let picture = session
4422+ .lanes()
4423+ .into_iter()
4424+ .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
4425+ if !picture {
4426+ return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string());
4427+ }
4407 let lanes = session4428 let lanes = session
4408 .lanes()4429 .lanes()
4409 .into_iter()4430 .into_iter()
@@ -4904,6 +4925,57 @@ mod tests {
4904 assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);4925 assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);
4905 }4926 }
4906 4927
4928+ /// The window opened on a song and nothing else -- the launch argument, the
4929+ /// drop on an empty window and the Import button all end in the same
4930+ /// `PlaybackSession::open`. The library lists it placeable, the lane door
4931+ /// the Add button and a drag share puts it on `A1`, and the one format that
4932+ /// needs a picture says so on its own row instead of failing at the end of
4933+ /// an export.
4934+ #[test]
4935+ fn a_song_opens_the_window_by_itself() {
4936+ let mut session =
4937+ PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline");
4938+ session.set_gain(0.0);
4939+ // The source's own path, which is the canonical one a row carries.
4940+ let path = session.sources()[0].path.clone();
4941+ assert!(session.lane_clips(Lane::V1).is_empty(), "no picture");
4942+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
4943+
4944+ // The library row: probed like any other source, and not greyed --
4945+ // `unusable` is what the panel dims a row with.
4946+ let streams = HashMap::from([(
4947+ path.clone(),
4948+ engine::AudioSession::probe_streams(&path).expect("probe the song"),
4949+ )]);
4950+ let rate = streams[&path]
4951+ .iter()
4952+ .find(|s| s.index == session.sources()[0].audio_stream)
4953+ .map(|s| (s.sample_rate, s.channels));
4954+ let frames = source_frames(lane_clips(&session), session.sources(), &path);
4955+ let rows = library_rows(session.sources(), &streams, rate, |_| frames);
4956+ assert_eq!(rows.len(), 1);
4957+ assert_eq!(rows[0].name, "test_tone.mp3");
4958+ assert_eq!(rows[0].unusable, None, "the row is placeable");
4959+ assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps");
4960+
4961+ // ...and it places, on the audio lane, through the door `insert_source`
4962+ // uses: a second copy of the song at the playhead.
4963+ session.seek(1.0);
4964+ assert!(
4965+ session
4966+ .place_stream_at(1.0, &path, 0, frames, Some(Lane::A1))
4967+ .expect("its own file is on this timeline")
4968+ );
4969+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
4970+ assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
4971+
4972+ // The mp4 row carries the reason rather than the format's detail line.
4973+ assert_eq!(
4974+ mp4_refusal(&session).as_deref(),
4975+ Some("no picture — an mp4 would be black; export WAV or FLAC")
4976+ );
4977+ }
4978+
4907 fn info(4979 fn info(
4908 index: usize,4980 index: usize,
4909 rate: u32,4981 rate: u32,
crates/engine/src/export.rsmodified+22 -1
@@ -31,7 +31,7 @@ use crate::audio::{AudioMeta, AudioSession};
31 use crate::demux::{Demuxer, VideoMeta};31 use crate::demux::{Demuxer, VideoMeta};
32 use crate::hw::{HwEncoder, HwSession};32 use crate::hw::{HwEncoder, HwSession};
33 use crate::mux::{AudioParams, Mp4Muxer, VideoParams};33 use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
34-use crate::project::Project;34+use crate::project::{LaneKind, Project};
35 use crate::scale::Composer;35 use crate::scale::Composer;
36 36
37 /// Progress is reported in permille: an atomic integer the render loop can read37 /// Progress is reported in permille: an atomic integer the render loop can read
@@ -173,10 +173,20 @@ pub fn start(
173 // left to write a file of no frames that nothing opens. Every caller of173 // left to write a file of no frames that nothing opens. Every caller of
174 // `start` comes through this, the app's own door174 // `start` comes through this, the app's own door
175 // (`PlaybackSession::is_empty`) being only the first fence.175 // (`PlaybackSession::is_empty`) being only the first fence.
176+ //
177+ // An audio-only timeline is the other legal project no mp4 can be made
178+ // of: every frame of it is a gap, so the file would be black picture
179+ // over the sound -- minutes of encoding for a video of nothing. Refused
180+ // by name, with the two formats that *are* that timeline, rather than
181+ // written; the app says the same on the format row before a destination
182+ // is even picked (`mp4_refusal`).
176 let written = match settings.format {183 let written = match settings.format {
177 _ if project.timeline_frames() == 0 => {184 _ if project.timeline_frames() == 0 => {
178 Err("the timeline is empty: there is nothing to export".into())185 Err("the timeline is empty: there is nothing to export".into())
179 }186 }
187+ Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \
188+ an mp4 would be black. Export WAV or FLAC, which are the sound itself"
189+ .into()),
180 Format::Mp4 => run(&project, &meta, &part, &worker, &settings),190 Format::Mp4 => run(&project, &meta, &part, &worker, &settings),
181 format => run_audio(&project, &meta, &part, &worker, format),191 format => run_audio(&project, &meta, &part, &worker, format),
182 };192 };
@@ -193,6 +203,17 @@ pub fn start(
193 ExportHandle { shared }203 ExportHandle { shared }
194 }204 }
195 205
206+/// Whether any video lane holds anything at all -- what tells an audio-only
207+/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
208+/// than of the sources, because a project may name a video file no clip plays
209+/// from any more.
210+fn has_picture(project: &Project) -> bool {
211+ project
212+ .lanes()
213+ .into_iter()
214+ .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
215+}
216+
196 fn settle(shared: &Shared, result: crate::Result<()>) {217 fn settle(shared: &Shared, result: crate::Result<()>) {
197 *shared.outcome.lock().unwrap() = Some(result);218 *shared.outcome.lock().unwrap() = Some(result);
198 // Published last: a caller that sees the flag is guaranteed the outcome.219 // Published last: a caller that sees the flag is guaranteed the outcome.
crates/engine/src/playback.rsmodified+118 -18
@@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24 use crate::color::ColorParams;24 use crate::color::ColorParams;
25 use crate::decode::{DecodeSession, Frame, Worker};25 use crate::decode::{DecodeSession, Frame, Worker};
26-use crate::demux::{Demuxer, VideoMeta};26+use crate::demux::{Codec, Demuxer, VideoMeta};
27 use crate::eq::EqParams;27 use crate::eq::EqParams;
28 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};28 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
29 use crate::scale::{Composer, FitPolicy};29 use crate::scale::{Composer, FitPolicy};
@@ -32,6 +32,20 @@ use crate::scale::{Composer, FitPolicy};
32 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.32 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
33 const RING_FULL_WAIT: Duration = Duration::from_millis(10);33 const RING_FULL_WAIT: Duration = Duration::from_millis(10);
34 34
35+/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
36+/// nothing was shot on it, so it is the canvas a *later* import meets rather
37+/// than a description of the song. H.264 because it is the one codec that
38+/// decodes without the plugin, 30 fps because a rounded-up audio length is what
39+/// the frame count means and a whole number of frames per second keeps it
40+/// honest; both are what a video imported onto such a timeline is held to
41+/// ([`matches_timeline`]).
42+///
43+/// ponytail: a 25 fps video refused by an audio-only timeline it could have
44+/// defined is the ceiling here. Upgrade path is adopting the first *picture's*
45+/// rate and codec on import, which means retiming every audio clip already
46+/// placed in frames.
47+const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
48+
35 /// The output half of a session: the device, plus what the feeder has handed it.49 /// The output half of a session: the device, plus what the feeder has handed it.
36 /// Cloned into the feeder thread; every field that matters is shared.50 /// Cloned into the feeder thread; every field that matters is shared.
37 #[derive(Clone)]51 #[derive(Clone)]
@@ -144,16 +158,12 @@ impl PlaybackSession {
144 /// a file we cannot hear is still a file we can watch.158 /// a file we cannot hear is still a file we can watch.
145 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {159 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
146 let path = path.as_ref().to_path_buf();160 let path = path.as_ref().to_path_buf();
147- // A timeline is scaffolded from source 0's picture -- its size, its161+ // A timeline is normally scaffolded from source 0's picture -- its size,
148- // frame rate, its clock. A song has none of that, so it joins a162+ // its frame rate, its clock. A song has none of that, so it scaffolds
149- // timeline (`import`) rather than starting one, and saying so beats163+ // the *canvas* instead and its own sound keeps the clock: an audio-only
150- // failing in the demuxer's words.164+ // project is a project like any other, it simply plays black.
151 if crate::is_audio(&path) {165 if crate::is_audio(&path) {
152- return Err(format!(166+ return Self::open_audio_only(&path);
153- "{} has no picture: open a video first, then import it onto the audio lane",
154- path.display()
155- )
156- .into());
157 }167 }
158 // `open_worker` rather than `open` purely for the worker handle: the168 // `open_worker` rather than `open` purely for the worker handle: the
159 // field has to exist from the start for the first seek to use it.169 // field has to exist from the start for the first seek to use it.
@@ -196,6 +206,77 @@ impl PlaybackSession {
196 })206 })
197 }207 }
198 208
209+ /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its
210+ /// own: one clip on `A1`, nothing on the video lane, and a picture that is
211+ /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as
212+ /// the song runs. Its own sound keeps the clock, exactly as a video's does.
213+ ///
214+ /// Refused when the file has no sound to time it by: a source with neither a
215+ /// picture nor a playable length is not a timeline, and that is what
216+ /// [`audio_frames`] answers -- the *device* is a different question, and a
217+ /// machine without one opens this like any other session, silently.
218+ fn open_audio_only(path: &Path) -> crate::Result<Self> {
219+ let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
220+ let meta = VideoMeta {
221+ width,
222+ height,
223+ frame_rate,
224+ // Rounded up to whole frames, which is the only frame count a
225+ // source with no picture has -- the same length `import_audio`
226+ // gives a song joining a timeline of video. The demuxer's words are
227+ // named with the file, since this is the door a file that is not
228+ // really audio at all comes to.
229+ frame_count: audio_frames(path, frame_rate)
230+ .map_err(|e| format!("{}: {e}", path.display()))?,
231+ codec: Codec::H264,
232+ };
233+ let (audio, audio_disabled) = open_audio(path, 0);
234+ // Through `from_parts` rather than `Project::single`, which is the
235+ // *video* open's pair of grouped clips: here there is no picture to
236+ // group the sound with, so the video lane starts empty.
237+ let clip = Clip {
238+ start: 0,
239+ in_frame: 0,
240+ out_frame: meta.frame_count,
241+ source: 0,
242+ link: None,
243+ eq: None,
244+ color: None,
245+ fit: FitPolicy::default(),
246+ };
247+ let project = Project::from_parts(
248+ vec![Source::new(path, 0)],
249+ vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])],
250+ Vec::new(),
251+ Vec::new(),
252+ )?;
253+ // Every frame of this timeline is a gap, since no video lane covers
254+ // anything: `composite_span_at` says so and the black worker
255+ // `start_span` would open is opened here instead, for the reason `open`
256+ // opens its decoder inline -- the field has to exist for the first seek.
257+ let span = project.composite_span_at(0);
258+ let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len));
259+ Ok(Self {
260+ meta,
261+ native: (width, height),
262+ frames: stream.frames,
263+ worker: stream.worker,
264+ retired: Vec::new(),
265+ // The song keeps the clock, as a video's own sound does -- and wall
266+ // time keeps it on a machine with no device, where the picture
267+ // (black) still has to move at some rate.
268+ clock: PlaybackClock::new(match audio {
269+ Some(_) => ClockSource::Audio,
270+ None => ClockSource::Wall,
271+ }),
272+ audio,
273+ audio_disabled,
274+ project,
275+ span,
276+ eos: false,
277+ })
278+ }
279+
199 /// Opens a project file written by [`save_project`](Self::save_project):280 /// Opens a project file written by [`save_project`](Self::save_project):
200 /// the whole timeline, restored to where its playhead stood, paused like281 /// the whole timeline, restored to where its playhead stood, paused like
201 /// [`open`](Self::open).282 /// [`open`](Self::open).
@@ -229,14 +310,33 @@ impl PlaybackSession {
229 // Ungraded, and superseded before a frame of it is shown: the `seek` at310 // Ungraded, and superseded before a frame of it is shown: the `seek` at
230 // the end of this function reopens the playhead's span through311 // the end of this function reopens the playhead's span through
231 // `start_span`, which is where a saved grade reaches the picture.312 // `start_span`, which is where a saved grade reaches the picture.
232- let (mut meta, stream) = DecodeSession::open_worker(313+ // ...unless it has no picture to open: a project whose source 0 is a
233- &first.path,314+ // song scaffolds the canvas the same way a fresh audio-only open does
234- 0,315+ // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
235- u32::MAX,316+ // black stream is superseded by the `seek` at the end of this function
236- ColorParams::default(),317+ // like every other worker opened here.
237- Composer::passthrough(),318+ let (mut meta, stream) = match crate::is_audio(&first.path) {
238- )319+ true => {
239- .map_err(|e| format!("source {}: {e}", first.path.display()))?;320+ let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
321+ let meta = VideoMeta {
322+ width,
323+ height,
324+ frame_rate,
325+ frame_count: audio_frames(&first.path, frame_rate)
326+ .map_err(|e| format!("source {}: {e}", first.path.display()))?,
327+ codec: Codec::H264,
328+ };
329+ (meta, DecodeSession::open_black(width, height, 1))
330+ }
331+ false => DecodeSession::open_worker(
332+ &first.path,
333+ 0,
334+ u32::MAX,
335+ ColorParams::default(),
336+ Composer::passthrough(),
337+ )
338+ .map_err(|e| format!("source {}: {e}", first.path.display()))?,
339+ };
240 // The project's own resolution, which is source 0's picture unless the340 // The project's own resolution, which is source 0's picture unless the
241 // file says otherwise -- every dialect before v7 had no way to say it,341 // file says otherwise -- every dialect before v7 had no way to say it,
242 // and that default is exactly what those projects meant.342 // and that default is exactly what those projects meant.
crates/engine/tests/audio_files.rsmodified+174 -7
@@ -1,7 +1,8 @@
1 //! Standalone audio files as sources: every container we claim to read decodes1 //! Standalone audio files as sources: every container we claim to read decodes
2-//! to the same tone, a song joins a timeline of video on the audio lane, and2+//! to the same tone, a song joins a timeline of video on the audio lane, a song
3-//! the three things it cannot do -- start a timeline, play on the video lane,3+//! *is* a timeline on its own (canvas scaffolded, picture black, sound exported)
4-//! be copied into an mp4 -- are refusals that say so.4+//! and the two things it cannot do -- play on the video lane, be copied into an
5+//! mp4 -- are refusals that say so.
5 //!6 //!
6 //! ```text7 //! ```text
7 //! cargo test -p engine --release --test audio_files8 //! cargo test -p engine --release --test audio_files
@@ -9,6 +10,7 @@
9 10
10 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
11 12
13+use engine::export::{ExportSettings, Format};
12 use engine::project::Lane;14 use engine::project::Lane;
13 use engine::{AudioSession, Clip, PlaybackSession};15 use engine::{AudioSession, Clip, PlaybackSession};
14 16
@@ -154,13 +156,178 @@ fn a_rate_the_device_cannot_mix_is_refused_at_the_door() {
154 assert_eq!(session.lane_clips(Lane::A1).len(), 1);156 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
155 }157 }
156 158
159+/// A song *is* a timeline: it scaffolds the canvas a video would have defined,
160+/// its own length is the timeline's, the video lane starts empty and the picture
161+/// is the black of an uncovered canvas.
157 #[test]162 #[test]
158-fn a_song_cannot_be_a_timeline_of_its_own() {163+fn a_song_is_a_timeline_of_its_own() {
159- let e = refusal(PlaybackSession::open(asset("test_tone.mp3")));164+ let mut session = open(asset("test_tone.mp3"));
165+ let meta = *session.meta();
166+ assert_eq!(
167+ (meta.width, meta.height),
168+ (1920, 1080),
169+ "the default canvas"
170+ );
171+ assert_eq!(meta.frame_rate, 30.0);
172+ // 3 s of tone at 30 fps, rounded up: the only frame count a file with no
173+ // picture has, and it is the timeline's length too.
174+ assert_eq!(meta.frame_count, 90);
175+ assert!((session.timeline_duration() - 3.0).abs() < 0.05);
176+ assert!(!session.is_empty(), "a song is not an empty timeline");
160 assert!(177 assert!(
161- e.ends_with("has no picture: open a video first, then import it onto the audio lane"),178+ session.lane_clips(Lane::V1).is_empty(),
162- "{e}"179+ "no picture anywhere"
180+ );
181+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
182+ let clip = session.lane_clips(Lane::A1)[0];
183+ assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90));
184+ assert_eq!(session.sources().len(), 1);
185+
186+ // And it shows black rather than nothing: the whole timeline is a gap, so
187+ // the black worker feeds it at the canvas size.
188+ session.seek(1.0);
189+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
190+ let frame = loop {
191+ if let Some(frame) = session.try_frame() {
192+ break frame;
193+ }
194+ assert!(std::time::Instant::now() < deadline, "no frame at 1 s");
195+ std::thread::sleep(std::time::Duration::from_millis(10));
196+ };
197+ assert_eq!((frame.width, frame.height), (1920, 1080));
198+ assert_eq!(frame.index, 30, "the gap is indexed in timeline frames");
199+ assert!(
200+ frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]),
201+ "the picture over a song is black"
202+ );
203+}
204+
205+/// A file that is neither a picture nor a sound this engine can play is not a
206+/// timeline: refused at the door, in the words of whatever refused it.
207+#[test]
208+fn a_file_with_no_picture_and_no_sound_is_still_refused() {
209+ let dir = std::env::temp_dir().join(format!("ve_audio_bad_{}", std::process::id()));
210+ let _ = std::fs::remove_dir_all(&dir);
211+ std::fs::create_dir_all(&dir).expect("scratch dir");
212+ let fake = dir.join("not_really.mp3");
213+ std::fs::write(&fake, b"this is not an mp3").expect("write");
214+ let e = refusal(PlaybackSession::open(&fake));
215+ assert!(e.starts_with(&fake.display().to_string()), "{e}");
216+ let _ = std::fs::remove_dir_all(&dir);
217+}
218+
219+/// The whole audio-only round trip a user makes: open a song, place a second
220+/// one, save, reopen, export the sound -- and be told, by name, that the one
221+/// format that needs a picture cannot have one.
222+#[test]
223+fn an_audio_only_project_saves_reloads_and_exports_its_sound() {
224+ let dir = std::env::temp_dir().join(format!("ve_audio_only_{}", std::process::id()));
225+ let _ = std::fs::remove_dir_all(&dir);
226+ std::fs::create_dir_all(&dir).expect("scratch dir");
227+
228+ let mut session = open(asset("test_tone.mp3"));
229+ // A second song joins it, the same way one joins a timeline of video: no
230+ // picture is needed for the import to have something to hold it to.
231+ session
232+ .import(&asset("test_tone.flac"))
233+ .expect("a song joins a song");
234+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
235+ assert!(session.lane_clips(Lane::V1).is_empty());
236+ assert!((session.timeline_duration() - 6.0).abs() < 0.1);
237+
238+ // mp4 is refused by name, before a byte is written; WAV writes the sound.
239+ let mp4 = dir.join("song.mp4");
240+ let e = wait(&session.export_to_with(
241+ &mp4,
242+ &ExportSettings {
243+ format: Format::Mp4,
244+ ..ExportSettings::default()
245+ },
246+ ))
247+ .expect_err("an audio-only timeline is not an mp4");
248+ assert_eq!(
249+ e.to_string(),
250+ "the timeline has no picture: an mp4 would be black. \
251+ Export WAV or FLAC, which are the sound itself"
252+ );
253+ assert!(!mp4.exists(), "the refusal wrote a file anyway");
254+
255+ let wav = dir.join("song.wav");
256+ wait(&session.export_to_with(
257+ &wav,
258+ &ExportSettings {
259+ format: Format::Wav,
260+ ..ExportSettings::default()
261+ },
262+ ))
263+ .expect("wav export of an audio-only timeline");
264+ let (rate, channels, samples) = decode(&wav);
265+ assert_eq!((rate, channels), (44100, 2));
266+ let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels);
267+ assert!((secs - 6.0).abs() < 0.1, "{secs:.3} s of exported audio");
268+ let peak = samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs()));
269+ assert!(peak > 0.05, "the export is silent: peak {peak}");
270+
271+ // Saved and reopened: an .edith naming nothing but songs loads.
272+ let project = dir.join("songs.edith");
273+ let before = (
274+ session.lane_spans_by_source(Lane::A1),
275+ session.sources().to_vec(),
276+ session.timeline_duration(),
277+ );
278+ session.save_project(&project).expect("save");
279+ drop(session);
280+ let reloaded = PlaybackSession::open_project(&project).expect("reload an audio-only project");
281+ reloaded.set_gain(0.0);
282+ assert_eq!(
283+ (
284+ reloaded.lane_spans_by_source(Lane::A1),
285+ reloaded.sources().to_vec(),
286+ reloaded.timeline_duration()
287+ ),
288+ before
163 );289 );
290+ assert_eq!(reloaded.meta().frame_rate, 30.0, "the canvas came back");
291+ assert_eq!(
292+ (reloaded.meta().width, reloaded.meta().height),
293+ (1920, 1080)
294+ );
295+ assert!(reloaded.lane_clips(Lane::V1).is_empty());
296+ drop(reloaded);
297+ let _ = std::fs::remove_dir_all(&dir);
298+}
299+
300+/// The other half of the door: a *video* joining a timeline a song scaffolded.
301+/// It is held to the canvas the song set (H.264, 30 fps), so a matching file
302+/// brings its picture in -- and the timeline stops being audio-only, mp4 export
303+/// included.
304+#[test]
305+fn a_video_joins_a_timeline_a_song_started() {
306+ let mut session = open(asset("test_tone.mp3"));
307+ session
308+ .import(&asset("test_av.mp4"))
309+ .expect("30 fps H.264 matches the audio-only canvas");
310+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");
311+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
312+ // And a file at another rate is refused in the timeline's own words rather
313+ // than silently retiming the song already on the lane.
314+ let e = refusal(session.import(&asset("test_tone_48k.wav")));
315+ assert_eq!(
316+ e,
317+ "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"
318+ );
319+}
320+
321+/// Blocks until the export settles, whichever way it settled.
322+fn wait(handle: &engine::ExportHandle) -> engine::Result<()> {
323+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
324+ loop {
325+ if let Some(result) = handle.result() {
326+ return result;
327+ }
328+ assert!(std::time::Instant::now() < deadline, "export never settled");
329+ std::thread::sleep(std::time::Duration::from_millis(20));
330+ }
164 }331 }
165 332
166 /// The export copies AAC packets and has no encoder, so a timeline carrying an333 /// The export copies AAC packets and has no encoder, so a timeline carrying an