diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 50e3bf0..5528139 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1867,6 +1867,15 @@ impl Player { cx.notify(); return; } + // The format row can be refused *after* it was picked -- mp4 is the + // default and an audio-only timeline (or a second audio lane) is one + // edit away -- so the button asks again rather than starting a worker + // that will only settle with the same refusal minutes later. + if let (Format::Mp4, Some(why)) = (self.format, mp4_refusal(session)) { + self.notice = Some(format!("NOT EXPORTED — {why}").into()); + cx.notify(); + return; + } session.pause(); self.export = Some(session.export_to_with(&self.export_path, &settings)); // The card has been answered; the progress line takes the panel from @@ -4735,7 +4744,19 @@ fn is_bare_modifier(key: &str) -> bool { /// timeline whose sound is spread over more than one audio lane is refused by /// the engine (`export::run`). Said on the row, before a destination has been /// picked, rather than after the write has started. +/// +/// An audio-only timeline is the other one: every frame of it is a gap, so the +/// mp4 would be a black picture over the sound. The engine refuses it too +/// (`export::start`); this is what greys the row before a destination has been +/// picked. fn mp4_refusal(session: &PlaybackSession) -> Option { + let picture = session + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); + if !picture { + return Some("no picture — an mp4 would be black; export WAV or FLAC".to_string()); + } let lanes = session .lanes() .into_iter() @@ -5304,6 +5325,57 @@ mod tests { assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90); } + /// The window opened on a song and nothing else -- the launch argument, the + /// drop on an empty window and the Import button all end in the same + /// `PlaybackSession::open`. The library lists it placeable, the lane door + /// the Add button and a drag share puts it on `A1`, and the one format that + /// needs a picture says so on its own row instead of failing at the end of + /// an export. + #[test] + fn a_song_opens_the_window_by_itself() { + let mut session = + PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline"); + session.set_gain(0.0); + // The source's own path, which is the canonical one a row carries. + let path = session.sources()[0].path.clone(); + assert!(session.lane_clips(Lane::V1).is_empty(), "no picture"); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + + // The library row: probed like any other source, and not greyed -- + // `unusable` is what the panel dims a row with. + let streams = HashMap::from([( + path.clone(), + engine::AudioSession::probe_streams(&path).expect("probe the song"), + )]); + let rate = streams[&path] + .iter() + .find(|s| s.index == session.sources()[0].audio_stream) + .map(|s| (s.sample_rate, s.channels)); + let frames = source_frames(lane_clips(&session), session.sources(), &path); + let rows = library_rows(session.sources(), &streams, rate, |_| frames); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].name, "test_tone.mp3"); + assert_eq!(rows[0].unusable, None, "the row is placeable"); + assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps"); + + // ...and it places, on the audio lane, through the door `insert_source` + // uses: a second copy of the song at the playhead. + session.seek(1.0); + assert!( + session + .place_stream_at(1.0, &path, 0, frames, Some(Lane::A1)) + .expect("its own file is on this timeline") + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); + + // The mp4 row carries the reason rather than the format's detail line. + assert_eq!( + mp4_refusal(&session).as_deref(), + Some("no picture — an mp4 would be black; export WAV or FLAC") + ); + } + fn info( index: usize, rate: u32, diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index b626490..c85eda6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -31,7 +31,7 @@ use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; -use crate::project::Project; +use crate::project::{LaneKind, Project}; use crate::scale::Composer; /// Progress is reported in permille: an atomic integer the render loop can read @@ -173,10 +173,20 @@ pub fn start( // left to write a file of no frames that nothing opens. Every caller of // `start` comes through this, the app's own door // (`PlaybackSession::is_empty`) being only the first fence. + // + // An audio-only timeline is the other legal project no mp4 can be made + // of: every frame of it is a gap, so the file would be black picture + // over the sound -- minutes of encoding for a video of nothing. Refused + // by name, with the two formats that *are* that timeline, rather than + // written; the app says the same on the format row before a destination + // is even picked (`mp4_refusal`). let written = match settings.format { _ if project.timeline_frames() == 0 => { Err("the timeline is empty: there is nothing to export".into()) } + Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \ + an mp4 would be black. Export WAV or FLAC, which are the sound itself" + .into()), Format::Mp4 => run(&project, &meta, &part, &worker, &settings), format => run_audio(&project, &meta, &part, &worker, format), }; @@ -193,6 +203,17 @@ pub fn start( ExportHandle { shared } } +/// Whether any video lane holds anything at all -- what tells an audio-only +/// timeline from one that merely opens on a gap. Asked of the *lanes* rather +/// than of the sources, because a project may name a video file no clip plays +/// from any more. +fn has_picture(project: &Project) -> bool { + project + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) +} + fn settle(shared: &Shared, result: crate::Result<()>) { *shared.outcome.lock().unwrap() = Some(result); // Published last: a caller that sees the flag is guaranteed the outcome. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index c0a5423..c9b83f7 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; use crate::decode::{DecodeSession, Frame, Worker}; -use crate::demux::{Demuxer, VideoMeta}; +use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span}; use crate::scale::{Composer, FitPolicy}; @@ -32,6 +32,20 @@ use crate::scale::{Composer, FitPolicy}; /// only has to be short next to that; it costs one wakeup per 10 ms of audio. const RING_FULL_WAIT: Duration = Duration::from_millis(10); +/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- +/// nothing was shot on it, so it is the canvas a *later* import meets rather +/// than a description of the song. H.264 because it is the one codec that +/// decodes without the plugin, 30 fps because a rounded-up audio length is what +/// the frame count means and a whole number of frames per second keeps it +/// honest; both are what a video imported onto such a timeline is held to +/// ([`matches_timeline`]). +/// +/// ponytail: a 25 fps video refused by an audio-only timeline it could have +/// defined is the ceiling here. Upgrade path is adopting the first *picture's* +/// rate and codec on import, which means retiming every audio clip already +/// placed in frames. +const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); + /// The output half of a session: the device, plus what the feeder has handed it. /// Cloned into the feeder thread; every field that matters is shared. #[derive(Clone)] @@ -153,16 +167,12 @@ impl PlaybackSession { /// a file we cannot hear is still a file we can watch. pub fn open(path: impl AsRef) -> crate::Result { let path = path.as_ref().to_path_buf(); - // A timeline is scaffolded from source 0's picture -- its size, its - // frame rate, its clock. A song has none of that, so it joins a - // timeline (`import`) rather than starting one, and saying so beats - // failing in the demuxer's words. + // A timeline is normally scaffolded from source 0's picture -- its size, + // its frame rate, its clock. A song has none of that, so it scaffolds + // the *canvas* instead and its own sound keeps the clock: an audio-only + // project is a project like any other, it simply plays black. if crate::is_audio(&path) { - return Err(format!( - "{} has no picture: open a video first, then import it onto the audio lane", - path.display() - ) - .into()); + return Self::open_audio_only(&path); } // `open_worker` rather than `open` purely for the worker handle: the // field has to exist from the start for the first seek to use it. @@ -206,6 +216,77 @@ impl PlaybackSession { }) } + /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its + /// own: one clip on `A1`, nothing on the video lane, and a picture that is + /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as + /// the song runs. Its own sound keeps the clock, exactly as a video's does. + /// + /// Refused when the file has no sound to time it by: a source with neither a + /// picture nor a playable length is not a timeline, and that is what + /// [`audio_frames`] answers -- the *device* is a different question, and a + /// machine without one opens this like any other session, silently. + fn open_audio_only(path: &Path) -> crate::Result { + let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; + let meta = VideoMeta { + width, + height, + frame_rate, + // Rounded up to whole frames, which is the only frame count a + // source with no picture has -- the same length `import_audio` + // gives a song joining a timeline of video. The demuxer's words are + // named with the file, since this is the door a file that is not + // really audio at all comes to. + frame_count: audio_frames(path, frame_rate) + .map_err(|e| format!("{}: {e}", path.display()))?, + codec: Codec::H264, + }; + let (audio, audio_disabled) = open_audio(path, 0); + // Through `from_parts` rather than `Project::single`, which is the + // *video* open's pair of grouped clips: here there is no picture to + // group the sound with, so the video lane starts empty. + let clip = Clip { + start: 0, + in_frame: 0, + out_frame: meta.frame_count, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + }; + let project = Project::from_parts( + vec![Source::new(path, 0)], + vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])], + Vec::new(), + Vec::new(), + )?; + // Every frame of this timeline is a gap, since no video lane covers + // anything: `composite_span_at` says so and the black worker + // `start_span` would open is opened here instead, for the reason `open` + // opens its decoder inline -- the field has to exist for the first seek. + let span = project.composite_span_at(0); + let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len)); + Ok(Self { + meta, + native: (width, height), + frames: stream.frames, + worker: stream.worker, + retired: Vec::new(), + // The song keeps the clock, as a video's own sound does -- and wall + // time keeps it on a machine with no device, where the picture + // (black) still has to move at some rate. + clock: PlaybackClock::new(match audio { + Some(_) => ClockSource::Audio, + None => ClockSource::Wall, + }), + audio, + audio_disabled, + project, + span, + eos: false, + }) + } + /// Opens a project file written by [`save_project`](Self::save_project): /// the whole timeline, restored to where its playhead stood, paused like /// [`open`](Self::open). @@ -239,14 +320,33 @@ impl PlaybackSession { // Ungraded, and superseded before a frame of it is shown: the `seek` at // the end of this function reopens the playhead's span through // `start_span`, which is where a saved grade reaches the picture. - let (mut meta, stream) = DecodeSession::open_worker( - &first.path, - 0, - u32::MAX, - ColorParams::default(), - Composer::passthrough(), - ) - .map_err(|e| format!("source {}: {e}", first.path.display()))?; + // ...unless it has no picture to open: a project whose source 0 is a + // song scaffolds the canvas the same way a fresh audio-only open does + // ([`open_audio_only`](Self::open_audio_only)), and the placeholder + // black stream is superseded by the `seek` at the end of this function + // like every other worker opened here. + let (mut meta, stream) = match crate::is_audio(&first.path) { + true => { + let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; + let meta = VideoMeta { + width, + height, + frame_rate, + frame_count: audio_frames(&first.path, frame_rate) + .map_err(|e| format!("source {}: {e}", first.path.display()))?, + codec: Codec::H264, + }; + (meta, DecodeSession::open_black(width, height, 1)) + } + false => DecodeSession::open_worker( + &first.path, + 0, + u32::MAX, + ColorParams::default(), + Composer::passthrough(), + ) + .map_err(|e| format!("source {}: {e}", first.path.display()))?, + }; // The project's own resolution, which is source 0's picture unless the // file says otherwise -- every dialect before v7 had no way to say it, // and that default is exactly what those projects meant. diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index 6b180b2..c68c113 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -1,7 +1,8 @@ //! Standalone audio files as sources: every container we claim to read decodes -//! to the same tone, a song joins a timeline of video on the audio lane, and -//! the three things it cannot do -- start a timeline, play on the video lane, -//! be copied into an mp4 -- are refusals that say so. +//! to the same tone, a song joins a timeline of video on the audio lane, a song +//! *is* a timeline on its own (canvas scaffolded, picture black, sound exported) +//! and the two things it cannot do -- play on the video lane, be copied into an +//! mp4 -- are refusals that say so. //! //! ```text //! cargo test -p engine --release --test audio_files @@ -9,6 +10,7 @@ use std::path::{Path, PathBuf}; +use engine::export::{ExportSettings, Format}; use engine::project::Lane; use engine::{AudioSession, Clip, PlaybackSession}; @@ -154,13 +156,178 @@ fn a_rate_the_device_cannot_mix_is_refused_at_the_door() { assert_eq!(session.lane_clips(Lane::A1).len(), 1); } +/// A song *is* a timeline: it scaffolds the canvas a video would have defined, +/// its own length is the timeline's, the video lane starts empty and the picture +/// is the black of an uncovered canvas. #[test] -fn a_song_cannot_be_a_timeline_of_its_own() { - let e = refusal(PlaybackSession::open(asset("test_tone.mp3"))); +fn a_song_is_a_timeline_of_its_own() { + let mut session = open(asset("test_tone.mp3")); + let meta = *session.meta(); + assert_eq!( + (meta.width, meta.height), + (1920, 1080), + "the default canvas" + ); + assert_eq!(meta.frame_rate, 30.0); + // 3 s of tone at 30 fps, rounded up: the only frame count a file with no + // picture has, and it is the timeline's length too. + assert_eq!(meta.frame_count, 90); + assert!((session.timeline_duration() - 3.0).abs() < 0.05); + assert!(!session.is_empty(), "a song is not an empty timeline"); assert!( - e.ends_with("has no picture: open a video first, then import it onto the audio lane"), - "{e}" + session.lane_clips(Lane::V1).is_empty(), + "no picture anywhere" + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + let clip = session.lane_clips(Lane::A1)[0]; + assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90)); + assert_eq!(session.sources().len(), 1); + + // And it shows black rather than nothing: the whole timeline is a gap, so + // the black worker feeds it at the canvas size. + session.seek(1.0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let frame = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + assert!(std::time::Instant::now() < deadline, "no frame at 1 s"); + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + assert_eq!((frame.width, frame.height), (1920, 1080)); + assert_eq!(frame.index, 30, "the gap is indexed in timeline frames"); + assert!( + frame.bgra.chunks_exact(4).all(|p| p[..3] == [0, 0, 0]), + "the picture over a song is black" + ); +} + +/// A file that is neither a picture nor a sound this engine can play is not a +/// timeline: refused at the door, in the words of whatever refused it. +#[test] +fn a_file_with_no_picture_and_no_sound_is_still_refused() { + let dir = std::env::temp_dir().join(format!("ve_audio_bad_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let fake = dir.join("not_really.mp3"); + std::fs::write(&fake, b"this is not an mp3").expect("write"); + let e = refusal(PlaybackSession::open(&fake)); + assert!(e.starts_with(&fake.display().to_string()), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The whole audio-only round trip a user makes: open a song, place a second +/// one, save, reopen, export the sound -- and be told, by name, that the one +/// format that needs a picture cannot have one. +#[test] +fn an_audio_only_project_saves_reloads_and_exports_its_sound() { + let dir = std::env::temp_dir().join(format!("ve_audio_only_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + + let mut session = open(asset("test_tone.mp3")); + // A second song joins it, the same way one joins a timeline of video: no + // picture is needed for the import to have something to hold it to. + session + .import(&asset("test_tone.flac")) + .expect("a song joins a song"); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + assert!(session.lane_clips(Lane::V1).is_empty()); + assert!((session.timeline_duration() - 6.0).abs() < 0.1); + + // mp4 is refused by name, before a byte is written; WAV writes the sound. + let mp4 = dir.join("song.mp4"); + let e = wait(&session.export_to_with( + &mp4, + &ExportSettings { + format: Format::Mp4, + ..ExportSettings::default() + }, + )) + .expect_err("an audio-only timeline is not an mp4"); + assert_eq!( + e.to_string(), + "the timeline has no picture: an mp4 would be black. \ + Export WAV or FLAC, which are the sound itself" + ); + assert!(!mp4.exists(), "the refusal wrote a file anyway"); + + let wav = dir.join("song.wav"); + wait(&session.export_to_with( + &wav, + &ExportSettings { + format: Format::Wav, + ..ExportSettings::default() + }, + )) + .expect("wav export of an audio-only timeline"); + let (rate, channels, samples) = decode(&wav); + assert_eq!((rate, channels), (44100, 2)); + let secs = samples.len() as f64 / f64::from(rate) / f64::from(channels); + assert!((secs - 6.0).abs() < 0.1, "{secs:.3} s of exported audio"); + let peak = samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs())); + assert!(peak > 0.05, "the export is silent: peak {peak}"); + + // Saved and reopened: an .edith naming nothing but songs loads. + let project = dir.join("songs.edith"); + let before = ( + session.lane_spans_by_source(Lane::A1), + session.sources().to_vec(), + session.timeline_duration(), + ); + session.save_project(&project).expect("save"); + drop(session); + let reloaded = PlaybackSession::open_project(&project).expect("reload an audio-only project"); + reloaded.set_gain(0.0); + assert_eq!( + ( + reloaded.lane_spans_by_source(Lane::A1), + reloaded.sources().to_vec(), + reloaded.timeline_duration() + ), + before ); + assert_eq!(reloaded.meta().frame_rate, 30.0, "the canvas came back"); + assert_eq!( + (reloaded.meta().width, reloaded.meta().height), + (1920, 1080) + ); + assert!(reloaded.lane_clips(Lane::V1).is_empty()); + drop(reloaded); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The other half of the door: a *video* joining a timeline a song scaffolded. +/// It is held to the canvas the song set (H.264, 30 fps), so a matching file +/// brings its picture in -- and the timeline stops being audio-only, mp4 export +/// included. +#[test] +fn a_video_joins_a_timeline_a_song_started() { + let mut session = open(asset("test_tone.mp3")); + session + .import(&asset("test_av.mp4")) + .expect("30 fps H.264 matches the audio-only canvas"); + assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + // And a file at another rate is refused in the timeline's own words rather + // than silently retiming the song already on the lane. + let e = refusal(session.import(&asset("test_tone_48k.wav"))); + assert_eq!( + e, + "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" + ); +} + +/// Blocks until the export settles, whichever way it settled. +fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + loop { + if let Some(result) = handle.result() { + return result; + } + assert!(std::time::Instant::now() < deadline, "export never settled"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } } /// The export copies AAC packets and has no encoder, so a timeline carrying an