diff --git a/Cargo.lock b/Cargo.lock index c9e1f02..66a74ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1647,6 +1647,7 @@ dependencies = [ "oxideav-core", "oxideav-h265", "oxideav-ogg", + "oxideav-sub-image", "oxideav-subtitle", "rav1e", "rusty_aac", @@ -4038,6 +4039,15 @@ dependencies = [ "oxideav-ttf", ] +[[package]] +name = "oxideav-sub-image" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5030e2dce8efa58c20f3e9ce4e53064b7697dc2dcc2585a678d313718582d6" +dependencies = [ + "oxideav-core", +] + [[package]] name = "oxideav-subtitle" version = "0.1.2" diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index be2e8e2..3154154 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -938,6 +938,17 @@ struct Player { fps: f64, name: SharedString, image: Option>, + /// The picture of the bitmap cue on screen, and which cue that is: the + /// track it is a row of and where it starts on the timeline. A PGS display + /// set is run-length and has to be walked into a canvas-sized buffer to be + /// drawn ([`engine::subtitle::CueImage::rgba`]), which is a thing to do + /// when the cue changes -- every few seconds -- and not at every repaint. + /// + /// The *track* is half the key because the four PGS tracks of a remux are + /// one film's subtitles in four languages: they start at the same + /// microsecond, and a picked row that only changed the language would go on + /// showing the one before it. + sub_image: Option<((usize, i64), Arc)>, /// A frame that arrived before its time; shown on the tick it comes due. /// The pump's buffer, not transport state -- but a frame waiting here is /// what keeps a finished decoder from reading as [`Transport::Ended`] one @@ -3514,6 +3525,8 @@ impl Player { // emptied library, against one per displayed frame in `pump`; the // upgrade path is threading the window through `act_on_row`. self.image = None; + // The drawn cue with it, and its tile for the same reason as above. + self.sub_image = None; self.clipboard = None; self.selected = None; self.selected_asset = None; @@ -4912,7 +4925,7 @@ impl Render for Player { ) // After the picture, so the plate is drawn over it // rather than under: siblings paint in order. - .children(self.subtitle_overlay(position)), + .children(self.subtitle_overlay(position, window)), ), ) // Above the panel and only when there is one to show, so it costs @@ -5333,28 +5346,63 @@ impl Player { /// not the track's own: on a cut timeline an embedded track's cues ride the /// pictures they belong to, and this is the same map the export writes the /// file with -- so what is read here is what the file says. - fn subtitle_overlay(&self, at: f64) -> Option> { + /// + /// A cue off a PGS track is a *picture* and not a line + /// ([`engine::subtitle::CueImage`]), and is drawn as one: the disc's whole + /// canvas laid over the whole picture region, which puts every cue where + /// the disc put it relative to its own frame, at the cost of the region and + /// that frame not being the same shape. + /// + /// ponytail: that cost is a stretch -- a 2.39:1 encode in a 16:9 region + /// leaves the cue a little wide and a little low, because this maps the + /// canvas onto the region and not onto the letterboxed picture inside it. + /// The upgrade path is the picture's own rect, which wants `VideoMeta`'s + /// aspect and the measured bounds rather than a `relative()`. + fn subtitle_overlay( + &mut self, + at: f64, + window: &mut Window, + ) -> Option> { if !self.subs_on { return None; } let mapped = self.session.as_ref()?.timeline_cues(self.sub_track); let cues = cues_at(&mapped, at); if cues.is_empty() { + self.drop_sub_image(window); return None; } + // The first picture cue up, decoded once and kept: two bitmap cues at + // one moment is a thing PGS composes into one display set, so there is + // never a second picture to stack under the first. + let picture = cues + .iter() + .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?))) + .and_then(|(start_us, image)| self.sub_picture(start_us, image, window)); Some( div() .absolute() .left_0() .right_0() - .bottom(px(SUB_BOTTOM)) + // A picture is placed on its own canvas and a plate is placed on + // the region, so the picture takes the whole of it. + .when(picture.is_some(), |d| d.top_0().bottom_0()) + .when(picture.is_none(), |d| d.bottom(px(SUB_BOTTOM))) .flex() .flex_col() .items_center() .gap(px(2.)) + .children(picture.map(|image| { + img(image) + .size_full() + // Stretched, not fitted: the canvas *is* the frame the + // disc composed against, so its corners are the frame's + // corners and fitting it would move every cue. + .object_fit(gpui::ObjectFit::Fill) + })) // The plate takes no click: the picture behind it is still the // drop target the whole window is. - .children(cues.into_iter().map(|cue| { + .children(cues.into_iter().filter(|c| c.image.is_none()).map(|cue| { div() .max_w(relative(0.9)) .px(px(6.)) @@ -5376,6 +5424,48 @@ impl Player { ) } + /// The cue starting at `start_us` as a drawable picture, decoded on the + /// first repaint it is up for and kept until another cue takes its place + /// ([`Player::sub_image`]). `None` for a display set the decoder refuses, + /// which draws nothing rather than failing the frame. + /// + /// Its atlas tile is released as the video's is: every [`RenderImage`] gets + /// a fresh id and its own tile, so a film's worth of cues would grow the + /// sprite atlas by the whole film. + fn sub_picture( + &mut self, + start_us: i64, + image: &engine::subtitle::CueImage, + window: &mut Window, + ) -> Option> { + let key = (self.sub_track, start_us); + if let Some((up, ready)) = &self.sub_image + && *up == key + { + return Some(ready.clone()); + } + let mut rgba = image.rgba()?; + // gpui's atlas is BGRA with straight alpha; PGS decodes to RGBA with + // straight alpha. The same swap the video frames get. + for pixel in rgba.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + let buf = image::RgbaImage::from_raw(image.width, image.height, rgba)?; + let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); + self.drop_sub_image(window); + self.sub_image = Some((key, next.clone())); + Some(next) + } + + /// Lets go of the drawn cue and its atlas tile. Called where the cue stops + /// being on screen, which is every gap between two of them: an 8 MB tile + /// per cue is not a thing to leave behind a film. + fn drop_sub_image(&mut self, window: &mut Window) { + if let Some((_, old)) = self.sub_image.take() { + let _ = window.drop_image(old); + } + } + /// What is decoding the picture right now, for the transport line: the /// backend is the running worker's own (it is written where a hardware /// session falls back to software, so this follows reality), and the codec @@ -9237,14 +9327,17 @@ fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Opt } } -/// What a subtitle row says under its name: how many cues it holds, or -- for a -/// track that could not be read -- the engine's own reason, verbatim. A refusal -/// is what the row is *for*: a PGS track off a BluRay remux is pictures, and a -/// list that dropped it would say the film has no subtitles at all. +/// What a subtitle row says under its name: how many cues it holds and whether +/// they are pictures ([`engine::subtitle::SubtitleTrack::is_bitmap`]) -- which +/// is the difference between a track an export writes into the file and one it +/// can only draw -- or, for a track that could not be read, the engine's own +/// reason verbatim. A refusal is still what a row can be *for*: a VobSub track +/// dropped from the list would say the film has no subtitles at all. fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String { - match &track.refused { - Some(why) => why.clone(), - None => format!("{} cues", track.cues.len()), + match (&track.refused, track.is_bitmap()) { + (Some(why), _) => why.clone(), + (None, true) => format!("{} cues — pictures", track.cues.len()), + (None, false) => format!("{} cues", track.cues.len()), } } @@ -15274,6 +15367,7 @@ mod tests { start_us, end_us, text: text.to_string(), + image: None, }; // Two cues that hand over exactly, and one that overlaps the second -- // a sign over a line of dialogue, which is two plates at one moment. @@ -16077,6 +16171,7 @@ fn main() { fps: meta.map_or(30., |meta| meta.frame_rate), name: name.clone(), image: None, + sub_image: None, held: None, ruler: Rc::default(), // A second is [`PPS_DEFAULT`] pixels wide until someone diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 529acd2..038873a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -115,6 +115,7 @@ rav1e = { version = "0.8.1", default-features = false, features = ["threading"] # project offers -- an intraframe master, ProRes-shaped, large files and all. # Built from `vendor/oxideav-h265`; see the note in the workspace manifest. oxideav-h265 = { path = "../../vendor/oxideav-h265" } +oxideav-sub-image = "0.0.7" [dev-dependencies] # The still-image suite compares what the timeline shows against the file's own diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 6b50bc2..f215c56 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -1580,9 +1580,10 @@ pub struct MkvSubtitle { /// `CodecPrivate`: the ASS script header (`[Script Info]` through the /// `[Events]` `Format:` line) for `S_TEXT/ASS`, empty for `S_TEXT/UTF8`. pub private: Vec, - /// Every cue block, in storage order -- but only for the `S_TEXT/*` codecs. - /// A bitmap track (PGS, VobSub) comes back declared and empty: its blocks - /// are megabytes of pictures, and nothing here can draw one. + /// Every cue block, in storage order, for the codecs [`crate::subtitle`] + /// reads: the `S_TEXT/*` ones and `S_HDMV/PGS`, whose blocks are display + /// sets of run-length pictures rather than lines. A codec neither of those + /// -- VobSub off a DVD -- comes back declared and empty. pub cues: Vec, /// Why this track's blocks were not read at all: a `ContentEncodings` this /// cannot undo. Listed like a bitmap track rather than raised, so a film @@ -1607,6 +1608,10 @@ pub struct MkvCue { pub payload: Vec, } +/// The Matroska codec id of Blu-ray bitmap subtitles: run-length pictures in +/// display sets, read by [`crate::subtitle`] as [`MkvCue`]s like any other. +pub const PGS: &str = "S_HDMV/PGS"; + /// The subtitle tracks of a Matroska file, in file order. An mp4's are not read /// (its `tx3g` is a different beast, and no file this project opens carries /// one); anything that is not a Matroska file at all is an error, as it is for @@ -1646,10 +1651,12 @@ pub fn matroska_subtitles(path: &Path) -> crate::Result> { } at = stop; } - // The text tracks only: see `MkvSubtitle::cues`. + // The tracks something reads: see `MkvSubtitle::cues`. let wanted: Vec = tracks .iter() - .filter(|t| t.codec.starts_with("S_TEXT") && t.unsupported.is_none()) + .filter(|t| { + (t.codec.starts_with("S_TEXT") || t.codec == PGS) && t.unsupported.is_none() + }) .map(|t| t.number) .collect(); if !wanted.is_empty() { @@ -1764,9 +1771,10 @@ fn mkv_subtitle_blocks( _ => mkv_lace(file, &block)?, }; for (at, len) in frames { - // A megabyte of *text* in one cue is a corrupt file, not a - // subtitle, and a crafted length may not reach an allocation - // through here. + // A megabyte in one cue is a corrupt file, not a subtitle -- a + // line of dialogue is bytes and a PGS display set of run-length + // pictures is tens of kilobytes -- and a crafted length may not + // reach an allocation through here. if len > 1 << 20 { return Err("a Matroska subtitle block larger than a megabyte".into()); } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 94aac2a..157f572 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -570,7 +570,10 @@ fn export_subtitles( return None; } let track = project.subtitles().get(settings.subtitles?)?; - if track.refused.is_some() { + // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a + // PGS cue has no words to put in one. `planned_subtitles` says so before + // the button is pressed rather than the file coming out short. + if track.refused.is_some() || track.is_bitmap() { return None; } let cues = timeline_cues(project, track, meta.frame_rate); @@ -633,6 +636,7 @@ pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec< start_us, end_us, text: cue.text.clone(), + image: cue.image.clone(), }) }) .collect(); @@ -660,6 +664,7 @@ pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec< start_us: onto(a), end_us: onto(b).min(end), text: cue.text.clone(), + image: cue.image.clone(), }); } } @@ -679,6 +684,12 @@ pub fn planned_subtitles(project: &Project, format: Format, pick: Option) if let Some(why) = &track.refused { return format!("{} — {why}", track.label); } + // Drawn over the picture, written into no file: the exported track is text + // and these cues are bitmaps. Said whatever the format, because it is the + // track and not the container that cannot be carried. + if track.is_bitmap() { + return format!("{} — pictures; drawn, not written", track.label); + } match format { _ if track.cues.is_empty() => "none".into(), Format::Av1 | Format::Hevc => format!("{} → embedded", track.label), @@ -2321,16 +2332,19 @@ mod tests { start_us: 500_000, end_us: 1_500_000, text: "first".into(), + image: None, }, Cue { start_us: 2_000_000, end_us: 3_250_000, text: "second".into(), + image: None, }, Cue { start_us: 4_000_000, end_us: 4_750_000, text: "third".into(), + image: None, }, ], refused: None, @@ -2359,13 +2373,15 @@ mod tests { Cue { start_us: 500_000, end_us: 1_500_000, - text: "first".into() + text: "first".into(), + image: None, }, // Clipped to the three seconds the export writes... Cue { start_us: 2_000_000, end_us: 3_000_000, - text: "second".into() + text: "second".into(), + image: None, }, // ...and the one wholly past the end is not written at all. ] @@ -2393,13 +2409,15 @@ mod tests { Cue { start_us: 500_000, end_us: 1_250_000, - text: "second".into() + text: "second".into(), + image: None, }, // ...and the third simply moves back the two seconds that went. Cue { start_us: 2_000_000, end_us: 2_750_000, - text: "third".into() + text: "third".into(), + image: None, }, ] ); diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs index 9cc49eb..4fd796d 100644 --- a/crates/engine/src/subtitle.rs +++ b/crates/engine/src/subtitle.rs @@ -14,12 +14,20 @@ //! renderer is a later thing, and a cue nobody can draw yet is still a cue that //! has to be listed, timed and saved. //! -//! What is *refused* is refused by name rather than by omission -//! ([`SubtitleTrack::refused`]): the bitmap subtitle formats -- PGS off a -//! BluRay remux, VobSub off a DVD -- are pictures, and a film carrying four of -//! them opens with four rows that say so instead of opening with an empty list. +//! A cue is not always words. `S_HDMV/PGS` off a BluRay remux is *pictures* -- +//! run-length bitmaps the disc composed against its own frame -- and one of +//! those is a [`Cue`] with a [`CueImage`] on it and no text. The decoding is +//! `oxideav-sub-image`, for the reason above. Everything downstream carries the +//! picture the way it carries the string: [`crate::export::timeline_cues`] maps +//! it onto the timeline, a front-end draws it over the film. +//! +//! What is still *refused* is refused by name rather than by omission +//! ([`SubtitleTrack::refused`]): VobSub off a DVD is a picture format nothing +//! here reads, and a file carrying one opens with a row that says so instead of +//! opening with an empty list. use std::path::{Path, PathBuf}; +use std::sync::Arc; use oxideav_subtitle::ir::plain_text; @@ -37,6 +45,84 @@ pub struct Cue { /// is to keep `oxideav_core::Segment` beside this string -- the parsers /// already hand it over -- and it belongs to whoever writes the renderer. pub text: String, + /// The picture this cue *is*, for a track that is pictures rather than + /// lines. `None` for every text cue -- an `.srt`, a `.vtt`, an `.ass`, an + /// `S_TEXT/*` track -- and `Some` for every cue of a PGS one, which then + /// has no [`text`](Self::text) at all. + /// + /// Shared rather than owned: [`crate::export::timeline_cues`] copies a whole + /// track's cues, per repaint, and a display set is tens of kilobytes. + pub image: Option>, +} + +/// A cue that is a picture: one PGS display set, kept the way the Matroska +/// block held it -- run-length and palettised, tens of kilobytes -- and turned +/// into pixels only when something is about to draw it ([`Self::rgba`]). +/// +/// Kept encoded because decoded is enormous: this film's canvas is 8 MB of +/// RGBA and its four PGS tracks carry about eleven thousand display sets +/// between them, so a track that decoded itself at import would cost gigabytes +/// where it now costs the thirty megabytes the file already spends on it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CueImage { + /// The canvas the disc composed against: 1920x1080 for a BluRay, whatever + /// the film's own frame was cropped to. The whole canvas is the picture -- + /// transparent everywhere the cue does not paint -- so a caller lays it + /// over the film rather than placing it. + pub width: u32, + pub height: u32, + /// The display set: `type`, big-endian size, body, segment after segment, + /// which is the shape a Matroska block holds PGS in. + set: Vec, +} + +impl CueImage { + /// The picture: straight (not premultiplied) RGBA, `width * height * 4` + /// bytes, transparent wherever the cue paints nothing. `None` for a display + /// set the decoder will not have, which is a corrupt block. + /// + /// Decoded on the spot: the run-length walk and one canvas-sized buffer, + /// which is a thing to do when the cue on screen changes and not sixty + /// times a second. A caller that draws these keeps the answer for as long + /// as the cue is up. + pub fn rgba(&self) -> Option> { + use oxideav_core::{CodecId, CodecParameters, Frame, Packet, TimeBase}; + let params = CodecParameters::subtitle(CodecId::new(oxideav_sub_image::PGS_CODEC_ID)); + let mut decoder = oxideav_sub_image::pgs::make_decoder(¶ms).ok()?; + // The decoder reads a `.sup`'s framing and a Matroska block is the same + // segments with the `PG` magic and the timestamps taken off, so they go + // back on. The times themselves are the block's and are already on the + // `Cue`, so they are written as nothing. + let mut sup = Vec::with_capacity(self.set.len() + 64); + for (kind, body) in segments(&self.set)? { + sup.extend_from_slice(b"PG"); + sup.extend_from_slice(&[0; 8]); + sup.push(kind); + sup.extend_from_slice(&(body.len() as u16).to_be_bytes()); + sup.extend_from_slice(body); + } + decoder + .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) + .ok()?; + match decoder.receive_frame().ok()? { + Frame::Video(frame) => Some(frame.planes.into_iter().next()?.data), + _ => None, + } + } +} + +/// The segments of a display set as a Matroska block holds them: a type byte, a +/// big-endian size, that many bytes of body, and again until the block is out. +/// `None` for bytes that do not walk -- a truncated or mislabelled block. +fn segments(set: &[u8]) -> Option> { + let mut out = Vec::new(); + let mut at = 0; + while at < set.len() { + let size = u16::from_be_bytes([*set.get(at + 1)?, *set.get(at + 2)?]) as usize; + out.push((set[at], set.get(at + 3..at + 3 + size)?)); + at += 3 + size; + } + Some(out) } /// A subtitle track: where it came from and what it says. @@ -73,6 +159,17 @@ impl SubtitleTrack { refused: Some(why), } } + + /// Whether this track's cues are pictures rather than lines -- a PGS track + /// off a remux. What it decides is where words are the only answer: an + /// export writes a *text* track and cannot carry these + /// ([`crate::export::planned_subtitles`] says so out loud). + /// + /// Read off the first cue rather than all of them, because a track is one + /// codec: PGS blocks are pictures to the last one. + pub fn is_bitmap(&self) -> bool { + self.cues.first().is_some_and(|c| c.image.is_some()) + } } /// The one door a saved subtitle line comes back in through: a standalone file @@ -126,13 +223,13 @@ fn external(path: &Path) -> SubtitleTrack { pub fn of_matroska(path: &Path) -> crate::Result> { Ok(crate::demux::matroska_subtitles(path)? .into_iter() - .map(|t| { + .map(|mut t| { let label = match (t.name.is_empty(), t.language.as_str()) { (true, lang) => lang.to_owned(), (false, "und") => t.name.clone(), (false, lang) => format!("{lang} — {}", t.name), }; - match cues_of(&t) { + match cues_of(&mut t) { Ok(cues) => SubtitleTrack { path: path.to_path_buf(), track: Some(t.number), @@ -156,9 +253,13 @@ pub fn of_matroska(path: &Path) -> crate::Result> { /// reads -- rather than the markup being re-derived here -- which is also what /// makes an embedded track and the standalone file it was muxed from come back /// as the same cues. -fn cues_of(track: &crate::demux::MkvSubtitle) -> Result, String> { +/// +/// A PGS track is neither: its blocks are pictures, and they are moved out of +/// `track` rather than copied ([`pgs_cues`]) -- thirty megabytes a track is not +/// a thing to hold twice. +fn cues_of(track: &mut crate::demux::MkvSubtitle) -> Result, String> { // A track compressed or encrypted with something the demuxer cannot undo is - // refused in those words, like a bitmap one: the row stays, and it says why. + // refused in those words: the row stays, and it says why. if let Some(why) = &track.unsupported { return Err(why.clone()); } @@ -170,9 +271,11 @@ fn cues_of(track: &crate::demux::MkvSubtitle) -> Result, String> { start_us: c.start_us, end_us: end_of(track, c), text: srt_body(&String::from_utf8_lossy(&c.payload)), + image: None, }) .collect(), "S_TEXT/ASS" | "S_TEXT/SSA" => ass_cues(track)?, + crate::demux::PGS => pgs_cues(track), codec => { return Err(format!( "{codec} subtitles are pictures, not text — this track is listed, not read" @@ -182,13 +285,62 @@ fn cues_of(track: &crate::demux::MkvSubtitle) -> Result, String> { Ok(cues) } +/// The cues of an `S_HDMV/PGS` track: one display set per block, and a display +/// set is a picture the disc composes onto its own canvas. +/// +/// Only the blocks that compose *something* are cues. The other half of them +/// are the disc's "take it off again" -- a composition with no object on it -- +/// and they are what says when the picture before them goes away, which is why +/// they are walked and not skipped. A muxer writes `BlockDuration` zero for all +/// of them, so [`end_of`] is what pairs the two. +fn pgs_cues(track: &mut crate::demux::MkvSubtitle) -> Vec { + // Before the blocks are emptied: `end_of` reads the ones after this one. + let ends: Vec = track.cues.iter().map(|c| end_of(track, c)).collect(); + track + .cues + .iter_mut() + .zip(ends) + .filter_map(|(block, end_us)| { + let (width, height) = pgs_canvas(&block.payload)?; + Some(Cue { + start_us: block.start_us, + end_us, + text: String::new(), + image: Some(Arc::new(CueImage { + width, + height, + set: std::mem::take(&mut block.payload), + })), + }) + }) + .collect() +} + +/// The canvas of a display set that paints something -- its `PCS` says how big +/// the disc's picture is, and how many objects are composed onto it. +/// +/// `None` when nothing is composed, which is the disc clearing the screen, and +/// `None` for bytes that are not a display set at all. +fn pgs_canvas(set: &[u8]) -> Option<(u32, u32)> { + /// `PresentationCompositionSegment`, which every display set opens with. + const PCS: u8 = 0x16; + let (_, pcs) = segments(set)?.into_iter().find(|&(kind, _)| kind == PCS)?; + // Width and height, then the frame rate, the composition number and state, + // the palette-update flag and the palette id -- and then how many objects + // this composition puts on the canvas. + let width = u16::from_be_bytes([*pcs.first()?, *pcs.get(1)?]); + let height = u16::from_be_bytes([*pcs.get(2)?, *pcs.get(3)?]); + (*pcs.get(10)? > 0).then_some((u32::from(width), u32::from(height))) +} + /// When a cue goes away: its `BlockDuration`, or -- for the muxer that writes -/// none -- when the next one arrives, and [`NO_DURATION_US`] for the last. +/// none, and for the PGS block that writes a zero, which says the same thing -- +/// when the next one arrives, and [`NO_DURATION_US`] for the last. fn end_of(track: &crate::demux::MkvSubtitle, cue: &crate::demux::MkvCue) -> i64 { /// How long a cue with nothing to say about it stays up: two seconds, a /// read of one line. const NO_DURATION_US: i64 = 2_000_000; - match cue.duration_us { + match cue.duration_us.filter(|&d| d > 0) { Some(d) => cue.start_us + d, None => track .cues @@ -264,6 +416,7 @@ fn ass_cues(track: &crate::demux::MkvSubtitle) -> Result, String> { c.end_us }, text: plain_text(&c.segments), + image: None, }) .collect()) } @@ -310,6 +463,7 @@ fn parse_file(path: &Path) -> crate::Result> { start_us: c.start_us, end_us: c.end_us, text: plain_text(&c.segments), + image: None, }) .collect()) } diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs index 7c977b7..a51aeef 100644 --- a/crates/engine/tests/export_subs.rs +++ b/crates/engine/tests/export_subs.rs @@ -84,16 +84,19 @@ fn track() -> SubtitleTrack { start_us: 500_000, end_us: 1_500_000, text: "first line".into(), + image: None, }, Cue { start_us: 2_000_000, end_us: 3_250_000, text: "second line\nwith a break".into(), + image: None, }, Cue { start_us: 4_000_000, end_us: 4_750_000, text: "third line".into(), + image: None, }, ], refused: None, diff --git a/crates/engine/tests/subtitles.rs b/crates/engine/tests/subtitles.rs index e10bea5..600a6a1 100644 --- a/crates/engine/tests/subtitles.rs +++ b/crates/engine/tests/subtitles.rs @@ -1,7 +1,7 @@ //! Subtitles: the cues of a file beside the media and of a track inside it are -//! the same cues, a project keeps them across a save, and the formats that are -//! pictures rather than text are listed and skipped by name rather than -//! silently dropped. +//! the same cues, a project keeps them across a save, and a track that is +//! pictures rather than text is read as pictures rather than listed and +//! skipped. //! //! ```text //! cargo test -p engine --release --test subtitles -- --nocapture @@ -39,16 +39,19 @@ fn expected() -> Vec { start_us: 500_000, end_us: 1_500_000, text: "first line".into(), + image: None, }, Cue { start_us: 2_000_000, end_us: 3_250_000, text: "second line\nwith a break".into(), + image: None, }, Cue { start_us: 4_000_000, end_us: 4_750_000, text: "third line".into(), + image: None, }, ] } @@ -100,16 +103,15 @@ fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() { ); } -/// A subtitle track this cannot read is a row that says why -- never an error -/// that takes the whole file down with it. The repro is a BluRay remux -/// carrying four PGS tracks: opening it lists four subtitles it cannot draw, -/// and the picture and the sound come up regardless. +/// The whole of the bitmap half on a file small enough to read in one screen: +/// four PGS tracks, the first of them carrying one picture and the disc's own +/// "take it off again" after it. A row per track, cues on the one with blocks, +/// and the picture decodes to the pixels the display set describes. /// /// Written here rather than muxed by the fixture script because ffmpeg cannot -/// encode text subtitles into pictures; the bytes below are the `Tracks` -/// element of such a file and nothing else. +/// encode text subtitles into pictures; the bytes below are that Matroska file. #[test] -fn bitmap_subtitles_are_listed_and_skipped_by_name() { +fn a_pgs_track_is_read_as_pictures_and_the_erase_after_one_ends_it() { let dir = scratch("pgs"); let file = dir.join("remux.mkv"); std::fs::write(&file, pgs_matroska()).expect("write the hand-made mkv"); @@ -118,17 +120,96 @@ fn bitmap_subtitles_are_listed_and_skipped_by_name() { assert_eq!(tracks.len(), 4, "every PGS track is listed"); for (i, track) in tracks.iter().enumerate() { assert_eq!(track.track, Some(i as u64 + 1)); - assert_eq!(track.cues, Vec::new(), "no cues to have"); - let why = track.refused.clone().unwrap_or_default(); - assert!( - why.contains("S_HDMV/PGS") && why.contains("pictures"), - "the refusal names the codec: {why:?}" - ); + assert_eq!(track.refused, None, "a PGS track is read, not refused"); } // The language is what a list shows, and `und` is what the spec says a // track that names none is. assert_eq!(tracks[0].label, "eng"); assert_eq!(tracks[3].label, "und"); + // The three tracks with no blocks are tracks with no cues -- and a track + // with no cues is not a bitmap track as far as anything downstream knows. + for track in &tracks[1..] { + assert_eq!(track.cues, Vec::new()); + assert!(!track.is_bitmap()); + } + + // Two blocks, one cue: the second composes no object, which is the disc + // clearing the screen, and that is where the first one ends. `BlockDuration` + // says nothing here, exactly as it says zero on a real remux. + let track = &tracks[0]; + assert!(track.is_bitmap(), "its cues are pictures"); + assert_eq!(track.cues.len(), 1, "the erase is not a cue of its own"); + let cue = &track.cues[0]; + assert_eq!((cue.start_us, cue.end_us), (500_000, 2_000_000)); + assert_eq!(cue.text, "", "a picture has no words"); + + let image = cue.image.as_ref().expect("the cue is a picture"); + assert_eq!( + (image.width, image.height), + (8, 4), + "the canvas is the disc's frame, not the object's box" + ); + let rgba = image.rgba().expect("the display set decodes"); + assert_eq!(rgba.len(), 8 * 4 * 4); + // A 2x2 white square at (1, 1) on an otherwise transparent canvas: opaque + // where the object is, and nothing anywhere else. + let at = |x: usize, y: usize| rgba[(y * 8 + x) * 4..(y * 8 + x) * 4 + 4].to_vec(); + assert_eq!(at(1, 1), vec![235, 235, 235, 255]); + assert_eq!(at(2, 2), vec![235, 235, 235, 255]); + assert_eq!(at(0, 0), vec![0, 0, 0, 0]); + assert_eq!(at(3, 1), vec![0, 0, 0, 0], "and no wider than it is"); + assert_eq!( + rgba.chunks_exact(4).filter(|p| p[3] > 0).count(), + 4, + "four painted pixels and no more" + ); +} + +/// The film that reported the bug: four PGS tracks beside one `S_TEXT/UTF8` +/// one, none of them refused any more. Skipped where the file is not -- it is +/// a 4K remux and lives in a local folder, not in this repository. +#[test] +fn the_remux_that_reported_the_bug_reads_all_five_of_its_tracks() { + let film = std::path::Path::new( + "/path/to/a-real-4k-pgs-film.mkv", + ); + if !film.exists() { + eprintln!("skipped: {} is not here", film.display()); + return; + } + let tracks = subtitle::of_matroska(film).expect("the walk"); + assert_eq!(tracks.len(), 5); + assert!( + tracks.iter().all(|t| t.refused.is_none()), + "every row is one a click can pick: {:?}", + tracks.iter().map(|t| &t.refused).collect::>() + ); + // One text track and four of pictures, which is what the remux carries. + let bitmap: Vec<_> = tracks.iter().filter(|t| t.is_bitmap()).collect(); + assert_eq!(bitmap.len(), 4); + for track in &bitmap { + assert!( + track.cues.len() > 100, + "{} — {} cues", + track.label, + track.cues.len() + ); + let cue = &track.cues[0]; + let image = cue.image.as_ref().expect("a picture cue"); + assert_eq!( + (image.width, image.height), + (1920, 1080), + "the BluRay canvas" + ); + assert!(cue.end_us > cue.start_us, "a cue that is up for a while"); + let rgba = image.rgba().expect("the first display set decodes"); + assert_eq!(rgba.len(), 1920 * 1080 * 4); + assert!( + rgba.chunks_exact(4).any(|p| p[3] > 0), + "{} — the first cue paints something", + track.label + ); + } } /// A saved project comes back with its subtitles: the `.edith` names the file @@ -187,6 +268,55 @@ fn a_project_keeps_its_subtitles_across_a_save() { ); } +/// A bitmap track survives a save the same way a text one does, and for the +/// same reason: a `.edith` holds the file and the track number, never a cue, so +/// what comes back is what the file still says. The pictures are read out of +/// the remux again on the way in -- thirty megabytes a track is exactly what a +/// project file is not for. +#[test] +fn a_project_keeps_a_bitmap_track_as_a_reference_and_reads_its_pictures_back() { + let dir = scratch("save_pgs"); + let media = dir.join("test_av.mp4"); + std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture"); + let remux = dir.join("remux.mkv"); + std::fs::write(&remux, pgs_matroska()).expect("write the hand-made mkv"); + + let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + assert_eq!( + session.import_subtitles(&remux).expect("the remux imports"), + 4, + "one row per PGS track" + ); + assert!(session.subtitles()[0].is_bitmap()); + // An mkv export writes a *text* track and these cues are pictures, so the + // card says so before the button rather than the file coming out short. + // The same `is_bitmap` is what makes `export_subtitles` write none. + let planned = session.planned_subtitles(engine::export::Format::Hevc, Some(0)); + assert!( + planned.contains("pictures") && planned.contains("not written"), + "{planned}" + ); + + let project = dir.join("cut.edith"); + session.save_project(&project).expect("save"); + let text = std::fs::read_to_string(&project).expect("read the project back"); + assert!( + text.contains("\nsubtitle 1 remux.mkv\n"), + "the track is a reference and no picture is written: {text}" + ); + + let back = engine::PlaybackSession::open_project(&project).expect("open the project"); + assert_eq!(back.subtitles().len(), 4); + let track = &back.subtitles()[0]; + assert_eq!(track.refused, None); + assert!(track.is_bitmap(), "and it comes back as pictures"); + assert_eq!(track.cues.len(), 1); + let image = track.cues[0].image.as_ref().expect("the picture is back"); + assert_eq!((image.width, image.height), (8, 4)); + assert_eq!(image.rgba().expect("it decodes").len(), 8 * 4 * 4); +} + /// A refusal a front-end shows at the moment of the import, rather than a row /// nobody asked for: a file that is not a subtitle format at all. #[test] @@ -207,20 +337,21 @@ fn importing_something_that_is_not_a_subtitle_says_so() { assert_eq!(session.subtitles().len(), 0, "and nothing was added"); } -/// The `Tracks` element of a Matroska file carrying four PGS subtitle tracks -/// and nothing else -- enough for the walk, which stops at the first `Cluster` -/// and there is none. +/// An EBML element: its id as it is written in the file, then an 8-byte +/// length, which is always a legal encoding of one. +fn element(id: &[u8], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + let mut len = (body.len() as u64).to_be_bytes(); + len[0] |= 0x01; // the 8-byte length marker + out.extend_from_slice(&len); + out.extend_from_slice(body); + out +} + +/// A Matroska file carrying four PGS subtitle tracks, the first of them with +/// one display set and the erase that ends it. No `Info`, so the timestamp +/// scale is the spec's default of a millisecond a tick. fn pgs_matroska() -> Vec { - /// An EBML element: its id as it is written in the file, then an 8-byte - /// length, which is always a legal encoding of one. - fn element(id: &[u8], body: &[u8]) -> Vec { - let mut out = id.to_vec(); - let mut len = (body.len() as u64).to_be_bytes(); - len[0] |= 0x01; // the 8-byte length marker - out.extend_from_slice(&len); - out.extend_from_slice(body); - out - } let mut tracks = Vec::new(); for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] { let mut entry = Vec::new(); @@ -232,6 +363,67 @@ fn pgs_matroska() -> Vec { } tracks.extend(element(&[0xAE], &entry)); // TrackEntry } - let segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks + // A `SimpleBlock` on track 1: the track number as a one-byte vint, the + // timestamp relative to the cluster's, and no flags. + let block = |at: i16, data: Vec| { + let mut body = vec![0x81, (at >> 8) as u8, at as u8, 0x00]; + body.extend(data); + element(&[0xA3], &body) + }; + let mut cluster = element(&[0xE7], &[0x00]); // Timestamp: 0 + cluster.extend(block(500, pgs_display_set())); + cluster.extend(block(2000, pgs_erase())); + + let mut segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks + segment.extend(element(&[0x1F, 0x43, 0xB6, 0x75], &cluster)); // Cluster element(&[0x18, 0x53, 0x80, 0x67], &segment) // Segment } + +/// One PGS segment as a Matroska block holds it: the type, a big-endian size, +/// the body -- and none of the `PG` magic or timestamps a `.sup` file writes, +/// which the muxer takes off. +fn pgs_segment(kind: u8, body: &[u8]) -> Vec { + let mut out = vec![kind]; + out.extend_from_slice(&(body.len() as u16).to_be_bytes()); + out.extend_from_slice(body); + out +} + +/// A display set that paints a 2x2 white square at (1, 1) of an 8x4 canvas: +/// the composition, the palette it colours by, the run-length object itself, +/// and the end of the set. +fn pgs_display_set() -> Vec { + // Canvas 8x4, a frame-rate byte, composition 0, epoch start, no palette + // update, palette 0 -- and one object, id 0, at (1, 1) with no flags. + #[rustfmt::skip] + let pcs = [ + 0, 8, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1, + 0, 0, 0, 0, 0, 1, 0, 1, + ]; + // Palette 0, version 0, then colour 1: white at full opacity, in the + // limited-range YCbCr a disc writes (index, Y, Cr, Cb, A). Colour 0 is the + // transparent one every palette starts with. + let pds = [0, 0, 1, 235, 128, 128, 255]; + // Two rows of "two pixels of colour 1, end of line", which is the shortest + // run PGS can write and still be a picture. + let rle = [0x00, 0x82, 0x01, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00]; + // Object 0, version 0, first *and* last fragment of the sequence; then the + // length of what follows, and the object's own 2x2 box. + let mut ods = vec![0, 0, 0, 0xC0]; + ods.extend_from_slice(&[0, 0, (4 + rle.len()) as u8, 0, 2, 0, 2]); + ods.extend_from_slice(&rle); + + let mut set = pgs_segment(0x16, &pcs); + set.extend(pgs_segment(0x14, &pds)); + set.extend(pgs_segment(0x15, &ods)); + set.extend(pgs_segment(0x80, &[])); + set +} + +/// The display set that composes nothing: the same canvas with no object on +/// it, which is how a disc says the picture before it is over. +fn pgs_erase() -> Vec { + let mut set = pgs_segment(0x16, &[0, 8, 0, 4, 0x10, 0, 1, 0, 0, 0, 0]); + set.extend(pgs_segment(0x80, &[])); + set +}