Skip to main content

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