forge
Explore
Log in

Don't you dare go Hollow

The grafts off the losing PGS lane

Browse files at this commit

bf6537184210313185f47d5e2da690535b2b4749Ahmet Kaan GümüşParent: 1bee319
  • fix
    • the grafts off the losing PGS lane
Show full message
🩹 fix(subtitles): the grafts off the losing PGS lane

- 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.rsmodified+31 -24
@@ -5349,24 +5349,27 @@ impl Player {
5349 ///5349 ///
5350 /// A cue off a PGS track is a *picture* and not a line5350 /// A cue off a PGS track is a *picture* and not a line
5351 /// ([`engine::subtitle::CueImage`]), and is drawn as one: the disc's whole5351 /// ([`engine::subtitle::CueImage`]), and is drawn as one: the disc's whole
5352- /// canvas laid over the whole picture region, which puts every cue where5352+ /// canvas fitted over the picture region exactly as the picture itself is,
5353- /// the disc put it relative to its own frame, at the cost of the region and5353+ /// which puts every cue where the disc put it relative to its own frame.
5354- /// that frame not being the same shape.
5355 ///5354 ///
5356- /// ponytail: that cost is a stretch -- a 2.39:1 encode in a 16:9 region5355+ /// ponytail: exact only while the canvas and the encode are the same shape
5357- /// leaves the cue a little wide and a little low, because this maps the5356+ /// -- a 16:9 canvas over a 2.39:1 encode fits to the region's height and
5358- /// canvas onto the region and not onto the letterboxed picture inside it.5357+ /// the film to its width, so a cue sits a little low on a scope film. The
5359- /// The upgrade path is the picture's own rect, which wants `VideoMeta`'s5358+ /// upgrade path is the picture's own rect, which wants `VideoMeta`'s aspect
5360- /// aspect and the measured bounds rather than a `relative()`.5359+ /// and the measured bounds rather than the shared `Contain`.
5361 fn subtitle_overlay(5360 fn subtitle_overlay(
5362 &mut self,5361 &mut self,
5363 at: f64,5362 at: f64,
5364 window: &mut Window,5363 window: &mut Window,
5365 ) -> Option<impl IntoElement + use<>> {5364 ) -> Option<impl IntoElement + use<>> {
5366- if !self.subs_on {5365+ // One way out, and it lets the drawn picture go on the way: the toggle
5367- return None;5366+ // going off, the file closing and the gap between two cues are the same
5368- }5367+ // "nothing on screen", and an 8 MB atlas tile may not survive any of
5369- let mapped = self.session.as_ref()?.timeline_cues(self.sub_track);5368+ // them (an early return above this leaked one per toggle-off).
5369+ let mapped = match self.session.as_ref().filter(|_| self.subs_on) {
5370+ Some(session) => session.timeline_cues(self.sub_track),
5371+ None => Vec::new(),
5372+ };
5370 let cues = cues_at(&mapped, at);5373 let cues = cues_at(&mapped, at);
5371 if cues.is_empty() {5374 if cues.is_empty() {
5372 self.drop_sub_image(window);5375 self.drop_sub_image(window);
@@ -5379,27 +5382,30 @@ impl Player {
5379 .iter()5382 .iter()
5380 .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?)))5383 .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?)))
5381 .and_then(|(start_us, image)| self.sub_picture(start_us, image, window));5384 .and_then(|(start_us, image)| self.sub_picture(start_us, image, window));
5385+ // A picture is fitted onto the whole region and a plate hangs off the
5386+ // bottom of it, and a track is one or the other -- so they are two
5387+ // shapes and not one with the parts switched off.
5388+ if let Some(image) = picture {
5389+ // A *flex* box with the canvas as its one growing item: a percentage
5390+ // size (`size_full`) inside an absolutely placed box has nothing to
5391+ // be a percentage of and lays the picture out to nothing, while a
5392+ // flex item is sized by the box itself. Fitted the way the picture
5393+ // above it is -- `Contain` over the same box -- so a canvas of the
5394+ // picture's own shape lands exactly on it.
5395+ return Some(div().absolute().inset_0().flex().child(
5396+ img(image).flex_1().h_full().object_fit(gpui::ObjectFit::Contain),
5397+ ));
5398+ }
5382 Some(5399 Some(
5383 div()5400 div()
5384 .absolute()5401 .absolute()
5385 .left_0()5402 .left_0()
5386 .right_0()5403 .right_0()
5387- // A picture is placed on its own canvas and a plate is placed on5404+ .bottom(px(SUB_BOTTOM))
5388- // the region, so the picture takes the whole of it.
5389- .when(picture.is_some(), |d| d.top_0().bottom_0())
5390- .when(picture.is_none(), |d| d.bottom(px(SUB_BOTTOM)))
5391 .flex()5405 .flex()
5392 .flex_col()5406 .flex_col()
5393 .items_center()5407 .items_center()
5394 .gap(px(2.))5408 .gap(px(2.))
5395- .children(picture.map(|image| {
5396- img(image)
5397- .size_full()
5398- // Stretched, not fitted: the canvas *is* the frame the
5399- // disc composed against, so its corners are the frame's
5400- // corners and fitting it would move every cue.
5401- .object_fit(gpui::ObjectFit::Fill)
5402- }))
5403 // The plate takes no click: the picture behind it is still the5409 // The plate takes no click: the picture behind it is still the
5404 // drop target the whole window is.5410 // drop target the whole window is.
5405 .children(cues.into_iter().filter(|c| c.image.is_none()).map(|cue| {5411 .children(cues.into_iter().filter(|c| c.image.is_none()).map(|cue| {
@@ -15513,6 +15519,7 @@ mod tests {
15513 track: Some(1),15519 track: Some(1),
15514 label: "eng".into(),15520 label: "eng".into(),
15515 cues: Vec::new(),15521 cues: Vec::new(),
15522+ bitmap: false,
15516 refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()),15523 refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()),
15517 };15524 };
15518 assert!(subtitle_detail(&refused).contains("pictures"));15525 assert!(subtitle_detail(&refused).contains("pictures"));
crates/engine/src/edith.rsmodified+1 -0
@@ -1046,6 +1046,7 @@ mod tests {
1046 track,1046 track,
1047 label: String::new(),1047 label: String::new(),
1048 cues: Vec::new(),1048 cues: Vec::new(),
1049+ bitmap: false,
1049 refused: None,1050 refused: None,
1050 }1051 }
1051 }1052 }
crates/engine/src/export.rsmodified+1 -0
@@ -2327,6 +2327,7 @@ mod tests {
2327 path: path.into(),2327 path: path.into(),
2328 track,2328 track,
2329 label: "eng".into(),2329 label: "eng".into(),
2330+ bitmap: false,
2330 cues: vec![2331 cues: vec![
2331 Cue {2332 Cue {
2332 start_us: 500_000,2333 start_us: 500_000,
crates/engine/src/subtitle.rsmodified+28 -4
@@ -94,12 +94,25 @@ impl CueImage {
94 // back on. The times themselves are the block's and are already on the94 // back on. The times themselves are the block's and are already on the
95 // `Cue`, so they are written as nothing.95 // `Cue`, so they are written as nothing.
96 let mut sup = Vec::with_capacity(self.set.len() + 64);96 let mut sup = Vec::with_capacity(self.set.len() + 64);
97+ // Up to and including the `END` that closes the first display set which
98+ // composes an object, and no further: a block is normally one set, but
99+ // a muxer that packs a composition and the erase after it into one would
100+ // otherwise leave the *erase* as the last word and decode to an empty
101+ // canvas -- the cue drawn as nothing at all.
102+ let mut shows = false;
97 for (kind, body) in segments(&self.set)? {103 for (kind, body) in segments(&self.set)? {
98 sup.extend_from_slice(b"PG");104 sup.extend_from_slice(b"PG");
99 sup.extend_from_slice(&[0; 8]);105 sup.extend_from_slice(&[0; 8]);
100 sup.push(kind);106 sup.push(kind);
101 sup.extend_from_slice(&(body.len() as u16).to_be_bytes());107 sup.extend_from_slice(&(body.len() as u16).to_be_bytes());
102 sup.extend_from_slice(body);108 sup.extend_from_slice(body);
109+ match kind {
110+ oxideav_sub_image::pgs::SEG_PCS => {
111+ shows = body.get(10).is_some_and(|&n| n > 0);
112+ }
113+ oxideav_sub_image::pgs::SEG_END if shows => break,
114+ _ => {}
115+ }
103 }116 }
104 decoder117 decoder
105 .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup))118 .send_packet(&Packet::new(0, TimeBase::new(1, 90_000), sup))
@@ -139,6 +152,15 @@ pub struct SubtitleTrack {
139 pub label: String,152 pub label: String,
140 /// In start order. Empty when [`refused`](Self::refused) says why.153 /// In start order. Empty when [`refused`](Self::refused) says why.
141 pub cues: Vec<Cue>,154 pub cues: Vec<Cue>,
155+ /// This track is pictures rather than text (`S_HDMV/PGS`). Not a refusal:
156+ /// it is drawn over the picture like any other track, and what it cannot do
157+ /// is be *written* as text -- an SRT carries none of it.
158+ ///
159+ /// Read off the codec id at every open rather than off the cues, because a
160+ /// PGS track whose display sets are all erases -- or one with no cues at
161+ /// all -- is still a track of pictures, and calling it text would have an
162+ /// export promise to write words it does not have.
163+ pub bitmap: bool,
142 /// Why this track has no cues, when it has none: a codec that is pictures164 /// Why this track has no cues, when it has none: a codec that is pictures
143 /// rather than text, a file that has gone missing since the project was165 /// rather than text, a file that has gone missing since the project was
144 /// saved. `None` for one that parsed -- which a track with genuinely no166 /// saved. `None` for one that parsed -- which a track with genuinely no
@@ -156,6 +178,7 @@ impl SubtitleTrack {
156 track,178 track,
157 label,179 label,
158 cues: Vec::new(),180 cues: Vec::new(),
181+ bitmap: false,
159 refused: Some(why),182 refused: Some(why),
160 }183 }
161 }184 }
@@ -164,11 +187,8 @@ impl SubtitleTrack {
164 /// off a remux. What it decides is where words are the only answer: an187 /// off a remux. What it decides is where words are the only answer: an
165 /// export writes a *text* track and cannot carry these188 /// export writes a *text* track and cannot carry these
166 /// ([`crate::export::planned_subtitles`] says so out loud).189 /// ([`crate::export::planned_subtitles`] says so out loud).
167- ///
168- /// Read off the first cue rather than all of them, because a track is one
169- /// codec: PGS blocks are pictures to the last one.
170 pub fn is_bitmap(&self) -> bool {190 pub fn is_bitmap(&self) -> bool {
171- self.cues.first().is_some_and(|c| c.image.is_some())191+ self.bitmap
172 }192 }
173 }193 }
174 194
@@ -212,6 +232,8 @@ fn external(path: &Path) -> SubtitleTrack {
212 track: None,232 track: None,
213 label,233 label,
214 cues,234 cues,
235+ // Every format `parse_file` reads is text.
236+ bitmap: false,
215 refused: None,237 refused: None,
216 },238 },
217 Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()),239 Err(why) => SubtitleTrack::refused(path, None, label, why.to_string()),
@@ -229,12 +251,14 @@ pub fn of_matroska(path: &Path) -> crate::Result<Vec<SubtitleTrack>> {
229 (false, "und") => t.name.clone(),251 (false, "und") => t.name.clone(),
230 (false, lang) => format!("{lang} — {}", t.name),252 (false, lang) => format!("{lang} — {}", t.name),
231 };253 };
254+ let bitmap = t.codec == crate::demux::PGS;
232 match cues_of(&mut t) {255 match cues_of(&mut t) {
233 Ok(cues) => SubtitleTrack {256 Ok(cues) => SubtitleTrack {
234 path: path.to_path_buf(),257 path: path.to_path_buf(),
235 track: Some(t.number),258 track: Some(t.number),
236 label,259 label,
237 cues,260 cues,
261+ bitmap,
238 refused: None,262 refused: None,
239 },263 },
240 Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why),264 Err(why) => SubtitleTrack::refused(path, Some(t.number), label, why),
crates/engine/tests/export_subs.rsmodified+1 -0
@@ -79,6 +79,7 @@ fn track() -> SubtitleTrack {
79 path: asset(MEDIA),79 path: asset(MEDIA),
80 track: Some(2),80 track: Some(2),
81 label: "eng".into(),81 label: "eng".into(),
82+ bitmap: false,
82 cues: vec![83 cues: vec![
83 Cue {84 Cue {
84 start_us: 500_000,85 start_us: 500_000,
crates/engine/tests/pgs_bitmaps.rsadded+93 -0
@@ -0,0 +1,93 @@
1+//! The chain a click on a PGS row actually runs, against a real BluRay remux:
2+//! the session lists the track, maps its cues onto the timeline and hands over
3+//! the picture of one -- which is what the window draws over the film.
4+//!
5+//! Gated on the film being there: it is a 4K remux in a local folder and no
6+//! fixture in this repository, so on a machine without it this says so and
7+//! passes. What it guards is what a hand-made display set cannot -- that a real
8+//! disc's blocks come whole out of the demuxer and decode, and that the map a
9+//! repaint asks for is cheap enough to ask sixty times a second.
10+//!
11+//! ```text
12+//! cargo test -p engine --release --test pgs_bitmaps -- --nocapture
13+//! ```
14+
15+use std::path::Path;
16+use std::time::Instant;
17+
18+/// A remux with `S_TEXT/UTF8` + 4x `S_HDMV/PGS`.
19+const FILM: &str = "/path/to/a-real-4k-pgs-film.mkv";
20+
21+#[test]
22+fn the_session_maps_a_pgs_track_onto_the_timeline_and_draws_it() {
23+ let film = Path::new(FILM);
24+ if !film.exists() {
25+ eprintln!("skipped: {FILM} is not on this machine");
26+ return;
27+ }
28+ let opened = Instant::now();
29+ let mut session = engine::PlaybackSession::open(film).expect("the film opens");
30+ session.set_gain(0.0);
31+ let rows = session
32+ .import_subtitles(film)
33+ .expect("the film's own subtitle tracks");
34+ eprintln!("{rows} rows in {:?}", opened.elapsed());
35+ let pick = session
36+ .subtitles()
37+ .iter()
38+ .position(|t| t.is_bitmap())
39+ .expect("a bitmap row to pick");
40+ assert_eq!(
41+ session.subtitles()[pick].refused, None,
42+ "a row a click can pick"
43+ );
44+
45+ let mapped = Instant::now();
46+ let cues = session.timeline_cues(pick);
47+ eprintln!("{} cues mapped in {:?}", cues.len(), mapped.elapsed());
48+ assert!(!cues.is_empty(), "no cue of this track lands on the timeline");
49+ // The map is asked once per repaint, so the *second* ask is the one that has
50+ // to be cheap -- the first paid for whatever the open did not.
51+ let warm = Instant::now();
52+ let again = session.timeline_cues(pick);
53+ let warm = warm.elapsed();
54+ eprintln!("mapped again in {warm:?}");
55+ assert_eq!(again, cues, "the same map, twice");
56+ assert!(warm.as_millis() < 16, "a repaint's worth of map: {warm:?}");
57+
58+ // Every cue is on screen for a while and gone again, in order: the erase
59+ // blocks are what end them and are not cues themselves.
60+ for pair in cues.windows(2) {
61+ assert!(pair[0].end_us > pair[0].start_us, "{:?}", pair[0]);
62+ assert!(pair[1].start_us >= pair[0].start_us, "{pair:?}");
63+ }
64+ // ...and the first one's picture is the canvas a front-end lays over the
65+ // film: the disc's own frame, painted where the line is and nowhere else.
66+ let drawn = Instant::now();
67+ let image = cues[0].image.as_ref().expect("a picture cue");
68+ let rgba = image.rgba().expect("the first display set decodes");
69+ eprintln!(
70+ "cue 0 decoded to {}x{} in {:?}",
71+ image.width,
72+ image.height,
73+ drawn.elapsed()
74+ );
75+ assert_eq!(rgba.len(), (image.width * image.height * 4) as usize);
76+ let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count();
77+ assert!(opaque > 0, "the block decoded to an empty canvas");
78+ assert!(
79+ opaque < (image.width * image.height) as usize,
80+ "a subtitle that covers the whole frame is not a subtitle"
81+ );
82+
83+ // A text row of the same film carries no picture, which is what keeps the
84+ // two kinds of row apart.
85+ let text = session
86+ .subtitles()
87+ .iter()
88+ .position(|t| !t.is_bitmap() && t.refused.is_none())
89+ .expect("the film's text track");
90+ let words = session.timeline_cues(text);
91+ assert!(!words.is_empty());
92+ assert!(words.iter().all(|c| c.image.is_none()));
93+}
crates/engine/tests/subtitles.rsmodified+34 -9
@@ -114,7 +114,7 @@ fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() {
114 fn a_pgs_track_is_read_as_pictures_and_the_erase_after_one_ends_it() {114 fn a_pgs_track_is_read_as_pictures_and_the_erase_after_one_ends_it() {
115 let dir = scratch("pgs");115 let dir = scratch("pgs");
116 let file = dir.join("remux.mkv");116 let file = dir.join("remux.mkv");
117- std::fs::write(&file, pgs_matroska()).expect("write the hand-made mkv");117+ std::fs::write(&file, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv");
118 118
119 let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them");119 let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them");
120 assert_eq!(tracks.len(), 4, "every PGS track is listed");120 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() {
126 // track that names none is.126 // track that names none is.
127 assert_eq!(tracks[0].label, "eng");127 assert_eq!(tracks[0].label, "eng");
128 assert_eq!(tracks[3].label, "und");128 assert_eq!(tracks[3].label, "und");
129- // The three tracks with no blocks are tracks with no cues -- and a track129+ // The three tracks with no blocks are tracks with no cues -- and still
130- // with no cues is not a bitmap track as far as anything downstream knows.130+ // tracks of pictures, because that is the codec and not a count: one whose
131+ // every display set is an erase would otherwise pass for text, and an
132+ // export would promise to write words it has none of.
131 for track in &tracks[1..] {133 for track in &tracks[1..] {
132 assert_eq!(track.cues, Vec::new());134 assert_eq!(track.cues, Vec::new());
133- assert!(!track.is_bitmap());135+ assert!(track.is_bitmap(), "a PGS track with no cue is still PGS");
134 }136 }
135 137
136 // Two blocks, one cue: the second composes no object, which is the disc138 // 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() {
165 );167 );
166 }168 }
167 169
170+/// The muxer that packs a display set and the erase after it into one block:
171+/// the cue is still the picture. The sup handed to the decoder stops at the end
172+/// of the first set that composes something, and without that cut the erase is
173+/// the last word and the cue decodes to a canvas with nothing on it.
174+#[test]
175+fn a_block_holding_the_erase_after_the_picture_still_draws_the_picture() {
176+ let dir = scratch("pgs_packed");
177+ let file = dir.join("packed.mkv");
178+ let packed = [pgs_display_set(), pgs_erase()].concat();
179+ std::fs::write(&file, pgs_matroska(packed)).expect("write the hand-made mkv");
180+
181+ let tracks = subtitle::of_matroska(&file).expect("the walk");
182+ let cue = &tracks[0].cues[0];
183+ let image = cue.image.as_ref().expect("the packed block is still a picture");
184+ assert_eq!((image.width, image.height), (8, 4));
185+ let rgba = image.rgba().expect("it decodes");
186+ assert_eq!(
187+ rgba.chunks_exact(4).filter(|p| p[3] > 0).count(),
188+ 4,
189+ "the picture, not the erase written after it"
190+ );
191+}
192+
168 /// The film that reported the bug: four PGS tracks beside one `S_TEXT/UTF8`193 /// The film that reported the bug: four PGS tracks beside one `S_TEXT/UTF8`
169 /// one, none of them refused any more. Skipped where the file is not -- it is194 /// one, none of them refused any more. Skipped where the file is not -- it is
170 /// a 4K remux and lives in a local folder, not in this repository.195 /// 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() {
279 let media = dir.join("test_av.mp4");304 let media = dir.join("test_av.mp4");
280 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");305 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
281 let remux = dir.join("remux.mkv");306 let remux = dir.join("remux.mkv");
282- std::fs::write(&remux, pgs_matroska()).expect("write the hand-made mkv");307+ std::fs::write(&remux, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv");
283 308
284 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");309 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
285 session.set_gain(0.0);310 session.set_gain(0.0);
@@ -349,9 +374,9 @@ fn element(id: &[u8], body: &[u8]) -> Vec<u8> {
349 }374 }
350 375
351 /// A Matroska file carrying four PGS subtitle tracks, the first of them with376 /// A Matroska file carrying four PGS subtitle tracks, the first of them with
352-/// one display set and the erase that ends it. No `Info`, so the timestamp377+/// `first` in a block at 500 ms and the erase that ends it at 2 s. No `Info`,
353-/// scale is the spec's default of a millisecond a tick.378+/// so the timestamp scale is the spec's default of a millisecond a tick.
354-fn pgs_matroska() -> Vec<u8> {379+fn pgs_matroska(first: Vec<u8>) -> Vec<u8> {
355 let mut tracks = Vec::new();380 let mut tracks = Vec::new();
356 for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] {381 for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] {
357 let mut entry = Vec::new();382 let mut entry = Vec::new();
@@ -371,7 +396,7 @@ fn pgs_matroska() -> Vec<u8> {
371 element(&[0xA3], &body)396 element(&[0xA3], &body)
372 };397 };
373 let mut cluster = element(&[0xE7], &[0x00]); // Timestamp: 0398 let mut cluster = element(&[0xE7], &[0x00]); // Timestamp: 0
374- cluster.extend(block(500, pgs_display_set()));399+ cluster.extend(block(500, first));
375 cluster.extend(block(2000, pgs_erase()));400 cluster.extend(block(2000, pgs_erase()));
376 401
377 let mut segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks402 let mut segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks