timed_metadata/webvtt/cue.rs
1//! Extracted caption cue + the CEA-608/708 cue extractors.
2//!
3//! See `crate::webvtt` module docs for the diff-based boundary-detection
4//! design and the documented losses.
5use crate::event::MediaTime;
6use alloc::string::String;
7#[cfg(any(feature = "cc-data", feature = "teletext"))]
8use alloc::vec::Vec;
9
10/// A single extracted caption cue: display text plus its media-timeline span.
11///
12/// `start`/`end` are wrap-unrolled 90 kHz [`MediaTime`] instants (see
13/// [`crate::timeline`]). `text` may contain embedded `\n` for multi-line
14/// captions (e.g. a 2-row CEA-608 roll-up window); [`crate::webvtt::cue_block`]
15/// emits each line of `text` as its own WebVTT payload line.
16#[derive(Debug, Clone, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct Cue {
19 /// Cue start: the commit-event PTS (CEA-608 EOC / roll-up row reveal /
20 /// CEA-708 window-visible transition) — see `crate::webvtt` module docs.
21 pub start: MediaTime,
22 /// Cue end: the PTS of the next erase/replace event.
23 pub end: MediaTime,
24 /// Cue display text: plain, unescaped, unstyled (see `crate::webvtt`
25 /// module docs on documented losses).
26 pub text: String,
27}
28
29/// The cue currently on screen: its start and text, not yet closed by an
30/// erase or replace.
31#[cfg(feature = "teletext")]
32#[cfg_attr(docsrs, doc(cfg(feature = "teletext")))]
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct OpenCue {
36 /// Wrap-unrolled start in 90 kHz ticks, the same timeline as [`Cue::start`].
37 pub start_pts_90k: u64,
38 /// Display text, as [`Cue::text`].
39 pub text: String,
40}
41
42/// Shared diff-based boundary tracker used by the 608, 708, and Teletext
43/// extractors: unrolls the 33-bit PTS and turns "displayed text changed"
44/// transitions into completed [`Cue`]s.
45#[cfg(any(feature = "cc-data", feature = "teletext"))]
46struct DiffState {
47 unroller: crate::timeline::PtsUnroller,
48 open: Option<(u64, String)>,
49}
50
51#[cfg(any(feature = "cc-data", feature = "teletext"))]
52impl DiffState {
53 fn new() -> Self {
54 DiffState {
55 unroller: crate::timeline::PtsUnroller::default(),
56 open: None,
57 }
58 }
59
60 fn unroll(&mut self, pts33: u64) -> u64 {
61 self.unroller.unroll(pts33)
62 }
63
64 /// Observe the decoded text at `ticks`; push a completed cue into `cues`
65 /// when the text differs from the currently open cue (or, if none is
66 /// open, when the new text is non-empty).
67 fn observe(&mut self, ticks: u64, text: String, cues: &mut Vec<Cue>) {
68 let changed = match &self.open {
69 Some((_, cur)) => *cur != text,
70 None => !text.is_empty(),
71 };
72 if !changed {
73 return;
74 }
75 if let Some((start, prev)) = self.open.take() {
76 push_if_displayed(cues, start, ticks, prev);
77 }
78 if !text.is_empty() {
79 self.open = Some((ticks, text));
80 }
81 }
82
83 #[cfg(feature = "teletext")]
84 fn open_cue(&self) -> Option<OpenCue> {
85 self.open.as_ref().map(|(start, text)| OpenCue {
86 start_pts_90k: *start,
87 text: text.clone(),
88 })
89 }
90
91 /// Close any still-open cue at end of stream (or a channel/service reset).
92 fn finalize(&mut self, ticks: u64, cues: &mut Vec<Cue>) {
93 if let Some((start, prev)) = self.open.take() {
94 push_if_displayed(cues, start, ticks, prev);
95 }
96 }
97}
98
99/// Push `text` as a cue over `start..end` unless it was never on screen: empty
100/// text, or a zero-length interval. Real captures carry several caption
101/// updates under one access-unit PTS (the mux.js multi-channel capture has 21
102/// such cues on CC1), and a cue whose end equals its start is invisible
103/// (WebVTT requires the end time to be after the start time).
104#[cfg(any(feature = "cc-data", feature = "teletext"))]
105fn push_if_displayed(cues: &mut Vec<Cue>, start: u64, end: u64, text: String) {
106 if text.is_empty() || end <= start {
107 return;
108 }
109 cues.push(Cue {
110 start: MediaTime(start),
111 end: MediaTime(end),
112 text,
113 });
114}
115
116/// Extracts [`Cue`]s from a single CEA-608 data channel (CTA-608-E),
117/// wrapping a `cc-data` [`cc_data::decode::Cea608Decoder`].
118///
119/// Feed it one access unit's CEA-608 triplets at a time, tagged with that
120/// access unit's raw (non-unrolled) 33-bit PTS, via [`push_frame`]; call
121/// [`finalize`] at end of stream to close any still-open cue.
122///
123/// [`push_frame`]: Cea608CueExtractor::push_frame
124/// [`finalize`]: Cea608CueExtractor::finalize
125///
126/// ```
127/// use timed_metadata::webvtt::Cea608CueExtractor;
128/// use cc_data::{CcTriplet, CcType};
129/// use cc_data::decode::Cea608Channel;
130///
131/// fn pair(pts: u64, b1: u8, b2: u8) -> (u64, CcTriplet) {
132/// (
133/// pts,
134/// CcTriplet { cc_valid: true, cc_type: CcType::Ntsc608Field1, cc_data_1: b1, cc_data_2: b2 },
135/// )
136/// }
137///
138/// let mut ex = Cea608CueExtractor::new(Cea608Channel::Cc1);
139/// let frames = [
140/// pair(0, 0x14, 0x20), // RCL
141/// pair(1, 0x14, 0x70), // PAC row 15
142/// pair(2, b'H', b'I'), // "HI"
143/// pair(3, 0x14, 0x2F), // EOC -> commits "HI"
144/// pair(4, 0x14, 0x2C), // EDM -> erases
145/// ];
146/// for (pts, t) in frames {
147/// ex.push_frame(pts, core::slice::from_ref(&t));
148/// }
149/// let cues = ex.cues();
150/// assert_eq!(cues.len(), 1);
151/// assert_eq!(cues[0].text, "HI");
152/// ```
153#[cfg(feature = "cc-data")]
154#[cfg_attr(docsrs, doc(cfg(feature = "cc-data")))]
155pub struct Cea608CueExtractor {
156 decoder: cc_data::decode::Cea608Decoder,
157 channel: cc_data::decode::Cea608Channel,
158 state: DiffState,
159 cues: Vec<Cue>,
160}
161
162#[cfg(feature = "cc-data")]
163#[cfg_attr(docsrs, doc(cfg(feature = "cc-data")))]
164impl Cea608CueExtractor {
165 /// A new extractor tracking the given CEA-608 data channel (e.g. `Cc1`).
166 #[must_use]
167 pub fn new(channel: cc_data::decode::Cea608Channel) -> Self {
168 Cea608CueExtractor {
169 decoder: cc_data::decode::Cea608Decoder::new(),
170 channel,
171 state: DiffState::new(),
172 cues: Vec::new(),
173 }
174 }
175
176 /// Feed one access unit's CEA-608 triplets (already demuxed from its
177 /// `cc_data()`), tagged with that access unit's raw 33-bit PTS. Non-608
178 /// triplets in `triplets` are ignored.
179 pub fn push_frame(&mut self, pts33: u64, triplets: &[cc_data::CcTriplet]) {
180 let ticks = self.state.unroll(pts33);
181 self.decoder
182 .push_triplets(triplets.iter().filter(|t| t.cc_type.is_cea608()));
183 let text = self.decoder.channel_text(self.channel);
184 self.state.observe(ticks, text, &mut self.cues);
185 }
186
187 /// Close any still-open cue at end of stream, at `end_pts33`.
188 pub fn finalize(&mut self, end_pts33: u64) {
189 let ticks = self.state.unroll(end_pts33);
190 self.state.finalize(ticks, &mut self.cues);
191 }
192
193 /// The cues extracted so far, in order.
194 #[must_use]
195 pub fn cues(&self) -> &[Cue] {
196 &self.cues
197 }
198
199 /// Consume the extractor, returning the extracted cues.
200 #[must_use]
201 pub fn into_cues(self) -> Vec<Cue> {
202 self.cues
203 }
204}
205
206/// Extracts [`Cue`]s from a single CEA-708 (DTVCC) service (CTA-708-E),
207/// wrapping a `cc-data` [`cc_data::decode::Cea708Decoder`].
208///
209/// Reads [`cc_data::decode::Cea708Decoder::service_text`] for the configured
210/// service number (`1`-`6`; service 1 is the primary caption service) after
211/// each fed frame — see `crate::webvtt` module docs for the diff-based
212/// boundary design and its documented losses (styling, window geometry,
213/// cross-service merging).
214#[cfg(feature = "cc-data")]
215#[cfg_attr(docsrs, doc(cfg(feature = "cc-data")))]
216pub struct Cea708CueExtractor {
217 decoder: cc_data::decode::Cea708Decoder,
218 service_number: usize,
219 state: DiffState,
220 cues: Vec<Cue>,
221}
222
223#[cfg(feature = "cc-data")]
224#[cfg_attr(docsrs, doc(cfg(feature = "cc-data")))]
225impl Cea708CueExtractor {
226 /// A new extractor tracking the given CEA-708 service number (`1`-`6`).
227 #[must_use]
228 pub fn new(service_number: usize) -> Self {
229 Cea708CueExtractor {
230 decoder: cc_data::decode::Cea708Decoder::new(),
231 service_number,
232 state: DiffState::new(),
233 cues: Vec::new(),
234 }
235 }
236
237 /// Feed one access unit's CEA-708 triplets (already demuxed from its
238 /// `cc_data()`), tagged with that access unit's raw 33-bit PTS. Non-708
239 /// triplets in `triplets` are ignored.
240 pub fn push_frame(&mut self, pts33: u64, triplets: &[cc_data::CcTriplet]) {
241 let ticks = self.state.unroll(pts33);
242 self.decoder
243 .push_triplets(triplets.iter().filter(|t| t.cc_type.is_cea708()));
244 let text = self.decoder.service_text(self.service_number);
245 self.state.observe(ticks, text, &mut self.cues);
246 }
247
248 /// Close any still-open cue at end of stream, at `end_pts33`.
249 pub fn finalize(&mut self, end_pts33: u64) {
250 let ticks = self.state.unroll(end_pts33);
251 self.state.finalize(ticks, &mut self.cues);
252 }
253
254 /// The cues extracted so far, in order.
255 #[must_use]
256 pub fn cues(&self) -> &[Cue] {
257 &self.cues
258 }
259
260 /// Consume the extractor, returning the extracted cues.
261 #[must_use]
262 pub fn into_cues(self) -> Vec<Cue> {
263 self.cues
264 }
265}
266
267/// Extracts [`Cue`]s from an EBU Teletext (ETSI EN 300 706) subtitle page,
268/// feature `teletext`, layered on `dvb-vbi`'s carriage-only
269/// [`dvb_vbi::TeletextDataField`] (ETSI EN 301 775 §4.5).
270///
271/// `dvb-vbi` deliberately does not decode EN 300 706 (a large, separate spec
272/// covering FEC, character sets, and page composition — not carriage; see its
273/// own module docs). This crate owns that decode
274/// (`crate::webvtt::teletext`): Hamming-8/4 + odd-parity FEC, the Latin G0
275/// national option tables, and basic Level-1 page composition
276/// (header + rows 1-24), with every Table 36 national option selected by the
277/// page header's C12-C14 bits and, on C5/C6 pages, only the text inside a
278/// Start Box / End Box pair displayed. See `crate::webvtt::teletext` module
279/// docs for the full list of documented losses (no enhancement packets, no
280/// styling, no sub-code-based multi-page selection).
281///
282/// Tracks a single `(magazine, page)` — the caller supplies these (typically
283/// known from the carrying service's SI, e.g. a DVB VBI/teletext descriptor's
284/// page association). Feed every [`dvb_vbi::TeletextDataField`] carried by
285/// one access unit at a time via [`push_frame`], tagged with that access
286/// unit's raw (non-unrolled) 33-bit PTS; call [`finalize`] at end of stream.
287///
288/// Cue boundaries are derived the same way as the CEA extractors (see
289/// `crate::webvtt` module docs): a diff on the currently-displayed text
290/// (rows 1-24, non-empty, joined with `\n`) after each fed frame. A page's
291/// C4 (erase page) control bit clears the row buffer, which — combined with
292/// the diff — naturally produces a cue boundary when a subtitle disappears.
293///
294/// [`push_frame`]: TeletextCueExtractor::push_frame
295/// [`finalize`]: TeletextCueExtractor::finalize
296///
297/// ```
298/// use timed_metadata::webvtt::TeletextCueExtractor;
299/// use dvb_vbi::{TeletextDataField, LineHeader, FRAMING_CODE_EBU};
300///
301/// // Build one page-header packet (magazine 8, page 0x88, subtitle+erase
302/// // set) and one row-1 packet ("HI"), using the crate's own verified
303/// // Hamming-8/4 / odd-parity encoders (see `webvtt::teletext` tests).
304/// # fn hamming(n: u8) -> u8 {
305/// # let (d1,d2,d3,d4) = (n&1,(n>>1)&1,(n>>2)&1,(n>>3)&1);
306/// # let p1=1^d1^d3^d4; let p2=1^d1^d2^d4; let p3=1^d1^d2^d3;
307/// # let p4=1^p1^d1^p2^d2^p3^d3^d4;
308/// # p1|(d1<<1)|(p2<<2)|(d2<<3)|(p3<<4)|(d3<<5)|(p4<<6)|(d4<<7)
309/// # }
310/// # use broadcast_common::parity::set_odd_parity as parity;
311/// let mut header = [0u8; 42];
312/// header[0] = hamming(0); // magazine field 0 -> magazine 8, row 0
313/// header[1] = hamming(0);
314/// header[2] = hamming(8); // page units
315/// header[3] = hamming(8); // page tens -> page 0x88
316/// header[5] = hamming(0b1000); // C4 erase_page
317/// header[7] = hamming(0b1000); // C6 subtitle
318/// for b in header.iter_mut().skip(10) { *b = parity(0x20); }
319///
320/// let mut row1 = [0u8; 42];
321/// row1[0] = hamming(0 | (1 << 3)); // magazine 8, Y bit0 = 1 (row 1)
322/// row1[1] = hamming(0); // Y bits 1..4 = 0
323/// row1[2] = parity(0x0B); // Start Box, doubled
324/// row1[3] = parity(0x0B);
325/// row1[4] = parity(b'H');
326/// row1[5] = parity(b'I');
327/// row1[6] = parity(0x0A); // End Box
328/// for b in row1.iter_mut().skip(7) { *b = parity(0x20); }
329///
330/// // EN 300 706 transmits each byte LSB-first, so a real wire capture (what
331/// // `TeletextDataField` carries) is the bit-reversal of these
332/// // spec-canonical bytes -- reverse each one to build a realistic field.
333/// let field = |block: [u8; 42]| TeletextDataField {
334/// header: LineHeader::new(true, 0),
335/// framing_code: FRAMING_CODE_EBU,
336/// txt_data_block: block.map(u8::reverse_bits),
337/// };
338///
339/// let mut ex = TeletextCueExtractor::new(8, 0x88);
340/// ex.push_frame(0, &[field(header)]);
341/// ex.push_frame(1, &[field(row1)]);
342/// ex.finalize(2);
343/// assert_eq!(ex.cues().len(), 1);
344/// assert_eq!(ex.cues()[0].text, "HI");
345/// ```
346#[cfg(feature = "teletext")]
347#[cfg_attr(docsrs, doc(cfg(feature = "teletext")))]
348pub struct TeletextCueExtractor {
349 assembler: crate::webvtt::teletext::PageAssembler,
350 state: DiffState,
351 cues: Vec<Cue>,
352}
353
354#[cfg(feature = "teletext")]
355#[cfg_attr(docsrs, doc(cfg(feature = "teletext")))]
356impl TeletextCueExtractor {
357 /// A new extractor tracking the given `(magazine, page)` (magazine
358 /// `1..=8`; page `Pt << 4 | Pu`, e.g. `0x88` for the common "page 888"
359 /// subtitle convention).
360 #[must_use]
361 pub fn new(magazine: u8, page: u8) -> Self {
362 TeletextCueExtractor {
363 assembler: crate::webvtt::teletext::PageAssembler::new(magazine, page),
364 state: DiffState::new(),
365 cues: Vec::new(),
366 }
367 }
368
369 /// Feed every [`dvb_vbi::TeletextDataField`] carried by one access unit,
370 /// tagged with that access unit's raw 33-bit PTS. Fields for other
371 /// magazines/pages are ignored.
372 pub fn push_frame(&mut self, pts33: u64, fields: &[dvb_vbi::TeletextDataField]) {
373 let ticks = self.state.unroll(pts33);
374 for field in fields {
375 self.assembler.push(field);
376 }
377 let text = self.assembler.display_text();
378 self.state.observe(ticks, text, &mut self.cues);
379 }
380
381 /// Close any still-open cue at end of stream, at `end_pts33`.
382 pub fn finalize(&mut self, end_pts33: u64) {
383 let ticks = self.state.unroll(end_pts33);
384 self.state.finalize(ticks, &mut self.cues);
385 }
386
387 /// Remove and return every cue whose end is already known, in start-time
388 /// order. Each cue is returned exactly once; cues taken here no longer
389 /// appear in [`cues`](Self::cues) or [`into_cues`](Self::into_cues).
390 pub fn take_closed_cues(&mut self) -> Vec<Cue> {
391 core::mem::take(&mut self.cues)
392 }
393
394 /// The cue currently on screen, if any, without removing it.
395 #[must_use]
396 pub fn open_cue(&self) -> Option<OpenCue> {
397 self.state.open_cue()
398 }
399
400 /// The cues extracted so far, in order, excluding any already taken with
401 /// [`take_closed_cues`](Self::take_closed_cues).
402 #[must_use]
403 pub fn cues(&self) -> &[Cue] {
404 &self.cues
405 }
406
407 /// Consume the extractor, returning the extracted cues.
408 #[must_use]
409 pub fn into_cues(self) -> Vec<Cue> {
410 self.cues
411 }
412}
413
414#[cfg(all(test, feature = "cc-data"))]
415mod tests {
416 use super::*;
417 use cc_data::{CcTriplet, CcType};
418
419 fn t608(b1: u8, b2: u8) -> CcTriplet {
420 CcTriplet {
421 cc_valid: true,
422 cc_type: CcType::Ntsc608Field1,
423 cc_data_1: b1,
424 cc_data_2: b2,
425 }
426 }
427
428 /// Paint-on text that changes twice under one PTS: the intermediate text
429 /// was never on screen, so only the cue that actually has a duration is
430 /// emitted (no zero-length cue).
431 #[test]
432 fn same_pts_flicker_emits_no_zero_length_cue() {
433 let mut ex = Cea608CueExtractor::new(cc_data::decode::Cea608Channel::Cc1);
434 ex.push_frame(0, &[t608(0x14, 0x29)]); // RDC (paint-on)
435 ex.push_frame(0, &[t608(0x14, 0x70)]); // PAC row 15
436 ex.push_frame(10, &[t608(b'A', b'B')]); // "AB" shown at 10
437 ex.push_frame(10, &[t608(b'C', b'D')]); // "ABCD" at the SAME pts
438 ex.push_frame(20, &[t608(0x14, 0x2C)]); // EDM at 20
439 let cues = ex.cues();
440 assert_eq!(cues.len(), 1, "{cues:?}");
441 assert_eq!(cues[0].text, "ABCD");
442 assert!(cues[0].start.0 < cues[0].end.0);
443 }
444
445 /// Pop-on: RCL/PAC/chars produce no cue until EOC; EDM closes it.
446 #[test]
447 fn pop_on_boundary_is_eoc_and_edm() {
448 let mut ex = Cea608CueExtractor::new(cc_data::decode::Cea608Channel::Cc1);
449 ex.push_frame(0, &[t608(0x14, 0x20)]); // RCL
450 ex.push_frame(1, &[t608(0x14, 0x70)]); // PAC row 15
451 assert!(ex.cues().is_empty(), "composing must not yet emit a cue");
452 ex.push_frame(2, &[t608(b'H', b'I')]);
453 assert!(
454 ex.cues().is_empty(),
455 "non-displayed writes must not emit a cue"
456 );
457 ex.push_frame(3, &[t608(0x14, 0x2F)]); // EOC -> opens a cue (not yet closed)
458 assert!(
459 ex.cues().is_empty(),
460 "the cue is open, not yet closed by an erase/replace"
461 );
462 ex.push_frame(4, &[t608(0x14, 0x2C)]); // EDM -> closes it
463 assert_eq!(ex.cues().len(), 1);
464 assert_eq!(ex.cues()[0].start, MediaTime(3));
465 assert_eq!(ex.cues()[0].end, MediaTime(4));
466 assert_eq!(ex.cues()[0].text, "HI");
467 }
468
469 /// An unclosed cue is closed by `finalize` at end of stream.
470 #[test]
471 fn finalize_closes_open_cue() {
472 let mut ex = Cea608CueExtractor::new(cc_data::decode::Cea608Channel::Cc1);
473 ex.push_frame(0, &[t608(0x14, 0x20)]);
474 ex.push_frame(1, &[t608(0x14, 0x70)]);
475 ex.push_frame(2, &[t608(b'O', b'K')]);
476 ex.push_frame(3, &[t608(0x14, 0x2F)]); // EOC
477 assert!(ex.cues().is_empty());
478 ex.finalize(10);
479 assert_eq!(ex.cues().len(), 1);
480 assert_eq!(ex.cues()[0].start, MediaTime(3));
481 assert_eq!(ex.cues()[0].end, MediaTime(10));
482 assert_eq!(ex.cues()[0].text, "OK");
483 }
484
485 /// 708 extractor: DefineWindow + text + ToggleWindows(visible) commits a
486 /// cue; a subsequent hide closes it. Worked-example CCP bytes adapted
487 /// from `cc-data`'s own `Cea708Decoder` doctest.
488 #[test]
489 fn cea708_service1_basic_window() {
490 let mut ex = Cea708CueExtractor::new(1);
491 // DefineWindow window 0, then draw via a raw packet push through the
492 // extractor's triplet path (start + data triplets forming one CCP).
493 // header 0x05 (seq=0,size=5*2-1=9? use decoder's own doctest packet).
494 let packet: [u8; 9] = [0x05, 0x27, 0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11];
495 let t0 = CcTriplet {
496 cc_valid: true,
497 cc_type: CcType::Dtvcc708Start,
498 cc_data_1: packet[0],
499 cc_data_2: packet[1],
500 };
501 let rest: alloc::vec::Vec<CcTriplet> = packet[2..]
502 .chunks(2)
503 .map(|c| CcTriplet {
504 cc_valid: true,
505 cc_type: CcType::Dtvcc708Data,
506 cc_data_1: c[0],
507 cc_data_2: *c.get(1).unwrap_or(&0),
508 })
509 .collect();
510 let mut triplets = alloc::vec![t0];
511 triplets.extend(rest);
512 ex.push_frame(0, &triplets);
513 // This packet only defines window 2 on service 1 (from cc-data's own
514 // doctest) -- it does not make it visible or paint text, so no cue
515 // should be produced yet (documents that DefineWindow alone doesn't
516 // commit a cue).
517 assert!(ex.cues().is_empty());
518 }
519}