From bf6537184210313185f47d5e2da690535b2b4749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 11 Aug 2026 15:36:05 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A9=B9=20fix(subtitles):=20the=20grafts?= =?UTF-8?q?=20off=20the=20losing=20PGS=20lane?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The overlay is a flex box with the canvas as its one growing item, fitted (Contain) the way the picture under it is: size_full inside an absolutely placed box has nothing to be a percentage of, and Fill put every cue somewhere the disc did not. - One way out of subtitle_overlay, and it lets the drawn picture go on the way: the toggle going off leaked an 8 MB atlas tile per press. - A track is pictures because of its codec id, not because its first cue happens to be one: an all-erase or empty PGS track passed for text and an export promised words it has none of. - The sup handed to the decoder stops at the end of the first display set that composes something, so a muxer packing the erase into the same block no longer blanks the cue. - The film-gated session test: the row a click picks, the map a repaint asks for twice (under 16 ms warm), the picture it draws. --- crates/app/src/main.rs | 55 ++++++++++-------- crates/engine/src/edith.rs | 1 + crates/engine/src/export.rs | 1 + crates/engine/src/subtitle.rs | 32 ++++++++-- crates/engine/tests/export_subs.rs | 1 + crates/engine/tests/pgs_bitmaps.rs | 93 ++++++++++++++++++++++++++++++ crates/engine/tests/subtitles.rs | 43 +++++++++++--- 7 files changed, 189 insertions(+), 37 deletions(-) create mode 100644 crates/engine/tests/pgs_bitmaps.rs diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 3154154..571ff71 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -5349,24 +5349,27 @@ impl Player { /// /// 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. + /// canvas fitted over the picture region exactly as the picture itself is, + /// which puts every cue where the disc put it relative to its own frame. /// - /// 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()`. + /// ponytail: exact only while the canvas and the encode are the same shape + /// -- a 16:9 canvas over a 2.39:1 encode fits to the region's height and + /// the film to its width, so a cue sits a little low on a scope film. The + /// upgrade path is the picture's own rect, which wants `VideoMeta`'s aspect + /// and the measured bounds rather than the shared `Contain`. 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); + // One way out, and it lets the drawn picture go on the way: the toggle + // going off, the file closing and the gap between two cues are the same + // "nothing on screen", and an 8 MB atlas tile may not survive any of + // them (an early return above this leaked one per toggle-off). + let mapped = match self.session.as_ref().filter(|_| self.subs_on) { + Some(session) => session.timeline_cues(self.sub_track), + None => Vec::new(), + }; let cues = cues_at(&mapped, at); if cues.is_empty() { self.drop_sub_image(window); @@ -5379,27 +5382,30 @@ impl Player { .iter() .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?))) .and_then(|(start_us, image)| self.sub_picture(start_us, image, window)); + // A picture is fitted onto the whole region and a plate hangs off the + // bottom of it, and a track is one or the other -- so they are two + // shapes and not one with the parts switched off. + if let Some(image) = picture { + // A *flex* box with the canvas as its one growing item: a percentage + // size (`size_full`) inside an absolutely placed box has nothing to + // be a percentage of and lays the picture out to nothing, while a + // flex item is sized by the box itself. Fitted the way the picture + // above it is -- `Contain` over the same box -- so a canvas of the + // picture's own shape lands exactly on it. + return Some(div().absolute().inset_0().flex().child( + img(image).flex_1().h_full().object_fit(gpui::ObjectFit::Contain), + )); + } Some( div() .absolute() .left_0() .right_0() - // 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))) + .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().filter(|c| c.image.is_none()).map(|cue| { @@ -15513,6 +15519,7 @@ mod tests { track: Some(1), label: "eng".into(), cues: Vec::new(), + bitmap: false, refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()), }; assert!(subtitle_detail(&refused).contains("pictures")); diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 9b3927a..e908ded 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1046,6 +1046,7 @@ mod tests { track, label: String::new(), cues: Vec::new(), + bitmap: false, refused: None, } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 157f572..47327a7 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -2327,6 +2327,7 @@ mod tests { path: path.into(), track, label: "eng".into(), + bitmap: false, cues: vec![ Cue { start_us: 500_000, diff --git a/crates/engine/src/subtitle.rs b/crates/engine/src/subtitle.rs index 4fd796d..f57ea82 100644 --- a/crates/engine/src/subtitle.rs +++ b/crates/engine/src/subtitle.rs @@ -94,12 +94,25 @@ impl CueImage { // 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); + // Up to and including the `END` that closes the first display set which + // composes an object, and no further: a block is normally one set, but + // a muxer that packs a composition and the erase after it into one would + // otherwise leave the *erase* as the last word and decode to an empty + // canvas -- the cue drawn as nothing at all. + let mut shows = false; 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); + match kind { + oxideav_sub_image::pgs::SEG_PCS => { + shows = body.get(10).is_some_and(|&n| n > 0); + } + oxideav_sub_image::pgs::SEG_END if shows => break, + _ => {} + } } decoder .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup)) @@ -139,6 +152,15 @@ pub struct SubtitleTrack { pub label: String, /// In start order. Empty when [`refused`](Self::refused) says why. pub cues: Vec, + /// This track is pictures rather than text (`S_HDMV/PGS`). Not a refusal: + /// it is drawn over the picture like any other track, and what it cannot do + /// is be *written* as text -- an SRT carries none of it. + /// + /// Read off the codec id at every open rather than off the cues, because a + /// PGS track whose display sets are all erases -- or one with no cues at + /// all -- is still a track of pictures, and calling it text would have an + /// export promise to write words it does not have. + pub bitmap: bool, /// Why this track has no cues, when it has none: a codec that is pictures /// rather than text, a file that has gone missing since the project was /// saved. `None` for one that parsed -- which a track with genuinely no @@ -156,6 +178,7 @@ impl SubtitleTrack { track, label, cues: Vec::new(), + bitmap: false, refused: Some(why), } } @@ -164,11 +187,8 @@ impl SubtitleTrack { /// 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()) + self.bitmap } } @@ -212,6 +232,8 @@ fn external(path: &Path) -> SubtitleTrack { track: None, label, cues, + // Every format `parse_file` reads is text. + bitmap: false, refused: None, }, Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()), @@ -229,12 +251,14 @@ pub fn of_matroska(path: &Path) -> crate::Result> { (false, "und") => t.name.clone(), (false, lang) => format!("{lang} — {}", t.name), }; + let bitmap = t.codec == crate::demux::PGS; match cues_of(&mut t) { Ok(cues) => SubtitleTrack { path: path.to_path_buf(), track: Some(t.number), label, cues, + bitmap, refused: None, }, Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why), diff --git a/crates/engine/tests/export_subs.rs b/crates/engine/tests/export_subs.rs index a51aeef..052b146 100644 --- a/crates/engine/tests/export_subs.rs +++ b/crates/engine/tests/export_subs.rs @@ -79,6 +79,7 @@ fn track() -> SubtitleTrack { path: asset(MEDIA), track: Some(2), label: "eng".into(), + bitmap: false, cues: vec![ Cue { start_us: 500_000, diff --git a/crates/engine/tests/pgs_bitmaps.rs b/crates/engine/tests/pgs_bitmaps.rs new file mode 100644 index 0000000..8e63459 --- /dev/null +++ b/crates/engine/tests/pgs_bitmaps.rs @@ -0,0 +1,93 @@ +//! The chain a click on a PGS row actually runs, against a real BluRay remux: +//! the session lists the track, maps its cues onto the timeline and hands over +//! the picture of one -- which is what the window draws over the film. +//! +//! Gated on the film being there: it is a 4K remux in a local folder and no +//! fixture in this repository, so on a machine without it this says so and +//! passes. What it guards is what a hand-made display set cannot -- that a real +//! disc's blocks come whole out of the demuxer and decode, and that the map a +//! repaint asks for is cheap enough to ask sixty times a second. +//! +//! ```text +//! cargo test -p engine --release --test pgs_bitmaps -- --nocapture +//! ``` + +use std::path::Path; +use std::time::Instant; + +/// A remux with `S_TEXT/UTF8` + 4x `S_HDMV/PGS`. +const FILM: &str = "/path/to/a-real-4k-pgs-film.mkv"; + +#[test] +fn the_session_maps_a_pgs_track_onto_the_timeline_and_draws_it() { + let film = Path::new(FILM); + if !film.exists() { + eprintln!("skipped: {FILM} is not on this machine"); + return; + } + let opened = Instant::now(); + let mut session = engine::PlaybackSession::open(film).expect("the film opens"); + session.set_gain(0.0); + let rows = session + .import_subtitles(film) + .expect("the film's own subtitle tracks"); + eprintln!("{rows} rows in {:?}", opened.elapsed()); + let pick = session + .subtitles() + .iter() + .position(|t| t.is_bitmap()) + .expect("a bitmap row to pick"); + assert_eq!( + session.subtitles()[pick].refused, None, + "a row a click can pick" + ); + + let mapped = Instant::now(); + let cues = session.timeline_cues(pick); + eprintln!("{} cues mapped in {:?}", cues.len(), mapped.elapsed()); + assert!(!cues.is_empty(), "no cue of this track lands on the timeline"); + // The map is asked once per repaint, so the *second* ask is the one that has + // to be cheap -- the first paid for whatever the open did not. + let warm = Instant::now(); + let again = session.timeline_cues(pick); + let warm = warm.elapsed(); + eprintln!("mapped again in {warm:?}"); + assert_eq!(again, cues, "the same map, twice"); + assert!(warm.as_millis() < 16, "a repaint's worth of map: {warm:?}"); + + // Every cue is on screen for a while and gone again, in order: the erase + // blocks are what end them and are not cues themselves. + for pair in cues.windows(2) { + assert!(pair[0].end_us > pair[0].start_us, "{:?}", pair[0]); + assert!(pair[1].start_us >= pair[0].start_us, "{pair:?}"); + } + // ...and the first one's picture is the canvas a front-end lays over the + // film: the disc's own frame, painted where the line is and nowhere else. + let drawn = Instant::now(); + let image = cues[0].image.as_ref().expect("a picture cue"); + let rgba = image.rgba().expect("the first display set decodes"); + eprintln!( + "cue 0 decoded to {}x{} in {:?}", + image.width, + image.height, + drawn.elapsed() + ); + assert_eq!(rgba.len(), (image.width * image.height * 4) as usize); + let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count(); + assert!(opaque > 0, "the block decoded to an empty canvas"); + assert!( + opaque < (image.width * image.height) as usize, + "a subtitle that covers the whole frame is not a subtitle" + ); + + // A text row of the same film carries no picture, which is what keeps the + // two kinds of row apart. + let text = session + .subtitles() + .iter() + .position(|t| !t.is_bitmap() && t.refused.is_none()) + .expect("the film's text track"); + let words = session.timeline_cues(text); + assert!(!words.is_empty()); + assert!(words.iter().all(|c| c.image.is_none())); +} diff --git a/crates/engine/tests/subtitles.rs b/crates/engine/tests/subtitles.rs index 600a6a1..5431213 100644 --- a/crates/engine/tests/subtitles.rs +++ b/crates/engine/tests/subtitles.rs @@ -114,7 +114,7 @@ fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() { 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"); + std::fs::write(&file, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv"); let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them"); assert_eq!(tracks.len(), 4, "every PGS track is listed"); @@ -126,11 +126,13 @@ fn a_pgs_track_is_read_as_pictures_and_the_erase_after_one_ends_it() { // 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. + // The three tracks with no blocks are tracks with no cues -- and still + // tracks of pictures, because that is the codec and not a count: one whose + // every display set is an erase would otherwise pass for text, and an + // export would promise to write words it has none of. for track in &tracks[1..] { assert_eq!(track.cues, Vec::new()); - assert!(!track.is_bitmap()); + assert!(track.is_bitmap(), "a PGS track with no cue is still PGS"); } // Two blocks, one cue: the second composes no object, which is the disc @@ -165,6 +167,29 @@ fn a_pgs_track_is_read_as_pictures_and_the_erase_after_one_ends_it() { ); } +/// The muxer that packs a display set and the erase after it into one block: +/// the cue is still the picture. The sup handed to the decoder stops at the end +/// of the first set that composes something, and without that cut the erase is +/// the last word and the cue decodes to a canvas with nothing on it. +#[test] +fn a_block_holding_the_erase_after_the_picture_still_draws_the_picture() { + let dir = scratch("pgs_packed"); + let file = dir.join("packed.mkv"); + let packed = [pgs_display_set(), pgs_erase()].concat(); + std::fs::write(&file, pgs_matroska(packed)).expect("write the hand-made mkv"); + + let tracks = subtitle::of_matroska(&file).expect("the walk"); + let cue = &tracks[0].cues[0]; + let image = cue.image.as_ref().expect("the packed block is still a picture"); + assert_eq!((image.width, image.height), (8, 4)); + let rgba = image.rgba().expect("it decodes"); + assert_eq!( + rgba.chunks_exact(4).filter(|p| p[3] > 0).count(), + 4, + "the picture, not the erase written after it" + ); +} + /// 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. @@ -279,7 +304,7 @@ fn a_project_keeps_a_bitmap_track_as_a_reference_and_reads_its_pictures_back() { 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"); + std::fs::write(&remux, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv"); let mut session = engine::PlaybackSession::open(&media).expect("open the fixture"); session.set_gain(0.0); @@ -349,9 +374,9 @@ fn element(id: &[u8], body: &[u8]) -> Vec { } /// 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 { +/// `first` in a block at 500 ms and the erase that ends it at 2 s. No `Info`, +/// so the timestamp scale is the spec's default of a millisecond a tick. +fn pgs_matroska(first: Vec) -> Vec { let mut tracks = Vec::new(); for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] { let mut entry = Vec::new(); @@ -371,7 +396,7 @@ fn pgs_matroska() -> Vec { element(&[0xA3], &body) }; let mut cluster = element(&[0xE7], &[0x00]); // Timestamp: 0 - cluster.extend(block(500, pgs_display_set())); + cluster.extend(block(500, first)); cluster.extend(block(2000, pgs_erase())); let mut segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks