diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 310a09b..50f1ed8 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -78,7 +78,7 @@ use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; use crate::mux::{ AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, }; -use crate::project::{LaneKind, Project, Rate}; +use crate::project::{Lane, LaneKind, Project, Rate}; use crate::scale::Composer; use crate::subtitle::{Cue, SubtitleTrack}; use crate::tonemap::{self, ToneMapper}; @@ -813,6 +813,21 @@ fn export_subtitles( if !settings.format.has_video() { return Vec::new(); } + // A timeline with words *placed* on it writes those and nothing else: the + // lanes are the edit, and a pick list built from the palette would write the + // same track twice over. + // + // corner-cut, transitional: a project with no placement anywhere keeps the + // old behaviour, every picked track carried through the picture's spans, + // because nothing in the app can place one yet -- so every project that + // exists today takes that door and exports the file it always did. Ceiling: + // two maps for one question. Upgrade path: once the timeline places + // subtitles (T5/T6) and the format carries them, an import puts its tracks + // on lanes and this whole branch, `timeline_cues` and + // [`ExportSettings::subtitles`] go with it. + if !placed_lanes(project).is_empty() { + return lane_subtitles(project, meta.frame_rate); + } settings .subtitles .iter() @@ -839,6 +854,76 @@ fn export_subtitles( .collect() } +/// The project's subtitle lanes in display order, and empty where **nothing is +/// placed on any of them** -- an empty list is what the export and the card both +/// read as "this project does not use lanes yet", so a project holding a bare +/// `S1` nobody dropped a caption on still exports by the pick list. +fn placed_lanes(project: &Project) -> Vec { + let lanes = project.subtitle_lanes(); + match lanes.iter().any(|&l| !project.sub_lane(l).is_empty()) { + true => lanes, + false => Vec::new(), + } +} + +/// One track per subtitle *lane*, in lane order -- so the file declares them +/// top-down as the timeline shows them and a player's subtitle menu lists them +/// in that order. +/// +/// The cues are [`Project::sub_lane_cues`]: each placement's window of its +/// palette track, on the timeline's own clock. Clipped again here to what the +/// export *writes*, which ends with the last picture or sound +/// ([`Project::media_frames`]) -- a caption hanging past both holds the +/// timeline open ([`Project::timeline_frames`]) but there is no picture under +/// it to write, so a cue out there is dropped and one straddling the end keeps +/// the half that is inside. [`planned_subtitles`] says so before the button is +/// pressed. +/// +/// A lane is dropped whole -- no track at all in the file -- where any +/// placement on it is a picture ([`SubtitleTrack::is_bitmap`]), a track that +/// could not be read, or a palette row that has since gone: the muxers write +/// words, and half a lane's cues under the other half's name would be worse +/// than none. Its language and title are the lane's *first* placement's track, +/// which is the one thing the whole lane is named by. +fn lane_subtitles(project: &Project, fps: f64) -> Vec { + let end = (f64::from(project.media_frames()) / fps * 1e6).round() as i64; + placed_lanes(project) + .into_iter() + .filter_map(|lane| { + let placed = project.sub_lane(lane); + let first = placed.first()?; + let writable = |track: usize| { + project + .subtitles() + .get(track) + .filter(|t| t.refused.is_none() && !t.is_bitmap()) + }; + let named = writable(first.track)?; + if placed.iter().any(|s| writable(s.track).is_none()) { + return None; + } + let cues: Vec = project + .sub_lane_cues(lane, fps) + .into_iter() + .filter_map(|cue| { + let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); + (end_us > start_us).then(|| Cue { + start_us, + end_us, + text: cue.text, + image: cue.image, + }) + }) + .collect(); + (!cues.is_empty()).then(|| SubParams { + language: named.language.clone(), + name: named.name.clone(), + cues, + }) + }) + .collect() +} + /// The track's cues where the *exported* timeline puts them, which is the only /// clock the file has: the export writes timeline frame 0 onwards and nothing /// else, exactly as the sound is mixed from frame 0 and resized to the @@ -945,6 +1030,13 @@ pub fn planned_subtitles( let mut embedded: Vec<&str> = Vec::new(); let mut dropped: Vec = Vec::new(); let picks: Vec = picks.into_iter().collect(); + // The lanes are the answer wherever anything is placed on one, exactly as + // [`export_subtitles`] writes them then -- the picks a front-end still hands + // are the palette's rows and say nothing about what the timeline holds. + let lanes = placed_lanes(project); + if !lanes.is_empty() { + return planned_lanes(project, format, &lanes); + } // One statement about the *file*, said before any about a track: a format // that is the sound alone has nowhere to put a single one of them, and the // reason a pick would not have travelled anyway (a picture track, no cues) @@ -993,6 +1085,75 @@ pub fn planned_subtitles( } } +/// [`planned_subtitles`] for a timeline that *places* its words: one clause per +/// subtitle lane, named by the lane and by the palette row it shows, in the +/// order the file will declare them ([`lane_subtitles`]). +/// +/// Every reason a lane does not travel is said here rather than found in the +/// file: a picture track placed on it, a track that could not be read, a palette +/// row that has since gone, a lane sitting entirely past the last picture, and +/// -- before a byte is written -- more lanes than a Matroska block can number +/// ([`crate::mux::MAX_SUB_TRACKS`], which the muxer refuses again). +fn planned_lanes(project: &Project, format: Format, lanes: &[Lane]) -> String { + if !format.has_video() { + return "none — this format is the sound alone".into(); + } + let end = project.media_frames(); + let (mut embedded, mut dropped, mut trailing) = (Vec::new(), Vec::new(), false); + for &lane in lanes { + let placed = project.sub_lane(lane); + // An empty lane is a lane nobody has used yet, not a refusal. + let Some(first) = placed.first() else { + continue; + }; + let row = |s: &crate::project::SubClip| project.subtitles().get(s.track); + let (label, head) = (lane.label(), row(first)); + let name = head.map_or_else(String::new, |t| format!("{} ", t.label)); + if let Some(gone) = placed.iter().find(|s| row(s).is_none()) { + dropped.push(format!("{label} — #{} is no longer a track", gone.track)); + } else if let Some((t, why)) = placed + .iter() + .find_map(|s| row(s).and_then(|t| t.refused.as_ref().map(|why| (t, why)))) + { + dropped.push(format!("{label} {} — {why}", t.label)); + } else if let Some(t) = placed.iter().find_map(|s| row(s).filter(|t| t.is_bitmap())) { + // Drawn over the picture, written into no file -- the same sentence + // a picked track gets, because it is the track and not the lane that + // cannot be carried. + dropped.push(format!("{label} {} — pictures; drawn, not written", t.label)); + } else if first.start >= end { + dropped.push(format!("{label} {name}— past the last picture")); + } else { + embedded.push(format!("{label} {}", name.trim_end())); + // Something on it hangs past the end of the media: the timeline is + // held open under it ([`Project::timeline_frames`]) but the file + // stops with the last picture, so those cues are cut off there. + trailing |= placed.last().is_some_and(|s| s.end() > end); + } + } + if format.is_mkv() && embedded.len() > crate::mux::MAX_SUB_TRACKS { + return format!( + "{} subtitle lanes: a Matroska block writes its track number in one byte, so one file \ + carries at most {}", + embedded.len(), + crate::mux::MAX_SUB_TRACKS + ); + } + let mut parts = match embedded.len() { + 0 => Vec::new(), + 1 => vec![format!("{} → embedded", embedded[0])], + n => vec![format!("{n} lanes → embedded ({})", embedded.join(", "))], + }; + parts.extend(dropped); + if trailing { + parts.push("cues past the last picture are cut off there".into()); + } + match parts.is_empty() { + true => "none".into(), + false => parts.join("; "), + } +} + /// What [`start`] would encode the picture with, probed the way the export /// probes it -- the very encoder is opened and closed again -- so this is a /// measurement and not a promise. `None` for a format that carries no picture. @@ -1462,7 +1623,7 @@ fn encode_audio( // whole samples on its own, so the sum can miss by a sample or two and a // source that ran out early would leave the track short under a picture // that is not. One resize settles both, as [`run_audio`]'s does. - let total = (f64::from(project.timeline_frames()) / meta.frame_rate + let total = (f64::from(project.media_frames()) / meta.frame_rate * f64::from(audio.sample_rate)) .round() as usize * channels; @@ -1866,7 +2027,14 @@ fn run( shared: &Arc, settings: &ExportSettings, ) -> crate::Result<()> { - let total = project.timeline_frames(); + // The media's length and not the timeline's: a caption placed past the last + // picture holds the *timeline* open ([`Project::timeline_frames`]) and there + // is nothing to write under it -- the picture loop walks the composite spans + // and stops with them, so a file padded to the caption's end would be + // trailing silence over a frozen last frame. The export ends with the last + // picture or sound, the cues are cut off there ([`lane_subtitles`]), and + // [`planned_subtitles`] says so before the button is pressed. + let total = project.media_frames(); // The two preview switches are the H.264 mp4 pair's alone. Only that // container carries a colour of its own back out ([`write_video`] tags it // there), so asking any other for a source-space file would write pictures @@ -2496,7 +2664,7 @@ fn run_audio( // by the line above, so this names the encoder writing it. *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string()); let channels = usize::from(audio.channels); - let frames = (f64::from(project.timeline_frames()) / meta.frame_rate + let frames = (f64::from(project.media_frames()) / meta.frame_rate * f64::from(audio.sample_rate)) .round() as u64; let total = frames as usize * channels; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 50d95f7..0e91a30 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2194,6 +2194,25 @@ impl Project { .unwrap_or(0) } + /// The same, counting the *media* alone: where the last picture or sound + /// runs out, with the captions over them ignored. + /// + /// What an export actually writes ends here -- the picture loop walks the + /// composite spans and the file stops with them -- so this is the length a + /// cue has to be inside of to be written at all (what + /// [`crate::export::planned_subtitles`] clips a lane's cues to). Equal to + /// [`timeline_frames`](Self::timeline_frames) on every timeline whose last + /// thing is a picture or a sound, which is every timeline that has no + /// caption hanging past the end of both. + pub fn media_frames(&self) -> u32 { + self.lanes + .iter() + .filter(|l| l.kind != LaneKind::Subtitle) + .filter_map(|l| l.clips.last().map(Clip::end)) + .max() + .unwrap_or(0) + } + /// `(timeline_start, len)` per `V1` clip, in order -- what a UI lane needs /// to lay clips out. Gaps show up as the holes between consecutive entries. pub fn clip_spans(&self) -> Vec<(u32, u32)> { diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs index 38269b0..d590bc5 100644 --- a/crates/engine/tests/export_subs.rs +++ b/crates/engine/tests/export_subs.rs @@ -19,7 +19,7 @@ use std::sync::Once; use std::time::{Duration, Instant}; use engine::export::{ExportSettings, Format}; -use engine::project::Lane; +use engine::project::{Lane, LaneKind, SubClip}; use engine::scratch::Scratch; use engine::subtitle::{self, Cue, SubtitleTrack}; use engine::{ExportHandle, Project}; @@ -130,6 +130,18 @@ fn both_tracks() -> Vec { /// and hands back what our own reader finds in the file -- one track per pick, /// in the order they were picked. fn exported(name: &str, project: Project, picks: &[usize]) -> (Scratch, Vec) { + exported_want(name, project, picks, picks.len()) +} + +/// The same, for a project whose tracks are its subtitle *lanes*: the picks say +/// nothing then ([`engine::export::planned_subtitles`] reads the lanes instead), +/// so how many tracks the file must carry is the caller's own statement. +fn exported_want( + name: &str, + project: Project, + picks: &[usize], + want: usize, +) -> (Scratch, Vec) { pin_software(); let out = out_path(name); let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); @@ -145,11 +157,7 @@ fn exported(name: &str, project: Project, picks: &[usize]) -> (Scratch, Vec, placed: &[(usize, u32, u32, i64, i64)]) -> Project { + let mut project = Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks); + for &(track, at, frames, in_us, out_us) in placed { + let lane = project.add_lane(LaneKind::Subtitle); + project + .place_sub( + lane, + at, + SubClip { + start: at, + frames, + track, + in_us, + out_us, + }, + ) + .expect("the lane is empty, so the placement lands"); + } + project +} + +/// The whole of a palette row, placed at frame 0: the window every "this lane +/// carries that track" test wants. +const WHOLE: (u32, u32, i64, i64) = (0, FRAMES, 0, 5_000_000); + +/// Two lanes are two tracks, **in lane order** -- not in the palette's. `S1` +/// carries the French row and `S2` the English one, and the file declares them +/// that way round, which is what a subtitle menu will list. +#[test] +fn a_lane_is_a_track_and_the_lanes_order_the_file() { + let project = on_lanes( + both_tracks(), + &[ + (1, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3), + (0, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3), + ], + ); + // The card says the same before the button is pressed, lane by lane. + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, [0, 1]), + "2 lanes → embedded (S1 fra — Signs, S2 eng)" + ); + + // ...and the picks are *not* what travels: this asks for the palette's order + // and gets the lanes' one. + let (out, tracks) = exported_want("lanes_two", project, &[0, 1], 2); + assert_eq!(tracks[0].label, "fra — Signs", "S1 is the first track"); + assert_eq!(tracks[1].label, "eng", "S2 is the second"); + for track in &tracks { + assert_eq!(track.cues.len(), 3, "the lane's whole window: {track:?}"); + near(track.cues[0].start_us, 500_000, "cue start"); + near(track.cues[2].end_us, 4_750_000, "cue end"); + } + if let Some(listing) = ffmpeg_streams(&out) { + assert!( + listing.contains("(fra): Subtitle") && listing.contains("(eng): Subtitle"), + "a second implementation reads both lanes: {listing}" + ); + } + std::fs::remove_file(&out).unwrap(); +} + +/// The same two lanes into an **mp4**, where a track is `tx3g` timed text: +/// ffmpeg reads two `mov_text` streams in the lanes' order. +#[test] +fn two_lanes_leave_an_mp4_as_two_timed_text_tracks() { + let project = on_lanes( + both_tracks(), + &[ + (1, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3), + (0, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3), + ], + ); + let out = exported_mp4("lanes_mp4", project, &[]); + let Some(listing) = ffmpeg_streams(&out) else { + println!("no ffmpeg on this box: an mp4's tx3g has no other reader here"); + std::fs::remove_file(&out).unwrap(); + return; + }; + assert_eq!( + listing.matches("Subtitle: mov_text").count(), + 2, + "one stream per lane, though nothing was picked: {listing}" + ); + assert!( + listing.contains("(fra): Subtitle") && listing.contains("(eng): Subtitle"), + "both lanes' languages: {listing}" + ); + let srt = ffmpeg_srt(&out, 0).expect("ffmpeg is here"); + println!("ffmpeg reads mp4 lane S1 back as:\n{srt}"); + assert!( + srt.contains("first line") && srt.contains("third line"), + "{srt}" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// A *trimmed* placement carries the cues its window keeps and no others, at the +/// times the placement puts them: 2.5s..5.0s of the track, dropped at timeline +/// frame 60, is the last two cues two and a half seconds earlier than the track +/// states them -- and the first one, outside the window, is not in the file. +#[test] +fn a_trimmed_placement_writes_the_cues_it_keeps_where_it_puts_them() { + let project = on_lanes(vec![track()], &[(0, 60, 75, 2_500_000, 5_000_000)]); + let (out, tracks) = exported_want("lanes_trim", project, &[], 1); + let cues = &tracks[0].cues; + assert_eq!(cues.len(), 2, "the first cue is outside the window: {cues:?}"); + // 2.0..3.25 of the track, of which 2.5s on is inside the window, landing at + // the placement's frame 60 (2.0s). + near( + cues[0].start_us, + 2_000_000, + "the straddling cue starts at the drop", + ); + near(cues[0].end_us, 2_750_000, "...and keeps the rest of its length"); + assert_eq!(cues[0].text, "second line\nwith a break"); + // 4.0..4.75, a second and a half into the window. + near( + cues[1].start_us, + 3_500_000, + "the last cue moves with the placement", + ); + near(cues[1].end_us, 4_250_000, "...end with it"); + assert_eq!(cues[1].text, "third line"); + if let Some(srt) = ffmpeg_srt(&out, 0) { + println!("ffmpeg reads the trimmed lane back as:\n{srt}"); + assert!(!srt.contains("first line"), "{srt}"); + assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}"); + assert!(srt.contains("00:00:03,500 --> 00:00:04,250"), "{srt}"); + } + std::fs::remove_file(&out).unwrap(); +} + +/// A lane nobody has placed anything on is not a project that uses lanes: the +/// picks still say what travels, byte for byte the file today's app exports. +#[test] +fn an_empty_lane_leaves_the_pick_list_in_charge() { + let mut project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()); + project.add_lane(LaneKind::Subtitle); + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, [0]), + "eng → embedded", + "the pick list's words, not a lane's" + ); + let (out, tracks) = exported("lanes_none", project, &[0]); + assert_eq!(tracks.len(), 1, "the pick, and only the pick"); + assert_eq!(tracks[0].label, "eng"); + assert_eq!(tracks[0].cues.len(), 3); + std::fs::remove_file(&out).unwrap(); +} + +/// A lane of **pictures** writes nothing at all, and says why before the button +/// is pressed: both muxers write words (`S_TEXT/UTF8`, `tx3g`) and neither has a +/// path that could write a bitmap -- the refusal is the capability's absence and +/// not a policy. +#[test] +fn a_lane_of_pictures_is_refused_in_words_and_written_nowhere() { + let mut pictures = track(); + pictures.bitmap = true; + pictures.label = "PGS".into(); + let project = on_lanes( + vec![track(), pictures], + &[ + (0, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3), + (1, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3), + ], + ); + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, []), + "S1 eng → embedded; S2 PGS — pictures; drawn, not written", + "the picture lane costs its own row and not the other's" + ); + // ...and the file has the one lane's track and nothing for the other: zero + // streams for a lane of pictures, not an empty one. + let (out, tracks) = exported_want("lanes_pgs", project, &[], 1); + assert_eq!( + tracks[0].label, "eng", + "the words travelled; the pictures did not" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// A caption hanging past the last picture: the timeline is held open under it +/// ([`Project::timeline_frames`]) but the export ends with the picture, so what +/// is out there is cut off -- a cue straddling the end keeps the half inside, a +/// lane wholly past it writes no track, and the card says so. +#[test] +fn a_caption_past_the_last_picture_is_cut_off_with_the_file() { + // S1 straddles the end: dropped at frame 120 (4.0s) with a 60-frame window + // of the track's first two seconds, so its one cue runs 4.5s..5.5s and the + // media stops at 5.0s. S2 sits entirely past the end. + let project = on_lanes( + vec![track(), track()], + &[(0, 120, 60, 0, 2_000_000), (1, FRAMES, 60, 0, 2_000_000)], + ); + assert_eq!(project.timeline_frames(), 210, "the captions hold it open"); + assert_eq!(project.media_frames(), FRAMES, "the pictures do not"); + assert_eq!( + engine::export::planned_subtitles(&project, Format::Hevc, []), + "S1 eng → embedded; S2 eng — past the last picture; cues past the last picture are cut \ + off there" + ); + + let (out, tracks) = exported_want("lanes_tail", project, &[], 1); + let cues = &tracks[0].cues; + assert_eq!(cues.len(), 1, "the one cue the window holds: {cues:?}"); + near(cues[0].start_us, 4_500_000, "where the placement puts it"); + near(cues[0].end_us, 5_000_000, "cut off with the last picture"); + std::fs::remove_file(&out).unwrap(); +} + +/// The Matroska ceiling counts lanes as it counts picks: past `MAX_SUB_TRACKS` a +/// block could not number the track, so the card says so and the export refuses +/// by name and leaves no file. +#[test] +fn more_lanes_than_a_block_can_number_are_refused_by_name() { + pin_software(); + let over = engine::mux::MAX_SUB_TRACKS + 1; + let project = on_lanes( + (0..over).map(|_| track()).collect(), + &(0..over) + .map(|i| (i, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3)) + .collect::>(), + ); + let said = engine::export::planned_subtitles(&project, Format::Hevc, []); + assert!( + said.contains(&format!("{over} subtitle lanes")) + && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)), + "the card says how many were placed and how many fit: {said}" + ); + + let out = out_path("lanes_ceiling"); + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); + let handle = engine::export::start( + project, + meta, + &out, + &ExportSettings { + format: Format::Hevc, + ..Default::default() + }, + ); + let said = wait(&handle, Duration::from_secs(300)) + .expect_err("a file that cannot be numbered is not written") + .to_string(); + assert!( + said.contains(&format!("{over} subtitle tracks")) + && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)), + "the muxer refuses it again, in its own words: {said}" + ); + assert!(!out.exists(), "and no half-written file is left: {said}"); +} diff --git a/crates/engine/tests/pgs_bitmaps.rs b/crates/engine/tests/pgs_bitmaps.rs index 5de2956..eedbf1d 100644 --- a/crates/engine/tests/pgs_bitmaps.rs +++ b/crates/engine/tests/pgs_bitmaps.rs @@ -81,6 +81,35 @@ fn the_session_maps_a_pgs_track_onto_the_timeline_and_draws_it() { "a subtitle that covers the whole frame is not a subtitle" ); + // ...and placed on a subtitle lane, that same real row is refused by name + // before any file exists: both muxers write *words* (`S_TEXT/UTF8`, `tx3g`) + // and neither has a path that could write a run-length picture, so the lane + // carries no track at all rather than the file coming out short + // (`export::planned_lanes`; `tests/export_subs.rs` pins the empty file it + // leaves). + let lane = session.add_lane(engine::project::LaneKind::Subtitle); + session + .place_sub( + lane, + 0, + engine::project::SubClip { + start: 0, + frames: 60, + track: pick, + in_us: cues[0].start_us, + out_us: cues[0].end_us, + }, + ) + .expect("the lane is empty, so the placement lands"); + assert_eq!( + session.planned_subtitles(engine::export::Format::Hevc, []), + format!( + "S1 {} — pictures; drawn, not written", + session.subtitles()[pick].label + ), + "a real PGS row on a lane says why it cannot travel" + ); + // A text row of the same film carries no picture, which is what keeps the // two kinds of row apart. let text = session