forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

cea608.rs457 lines, 13.7 KiBHistoryRawDownload
1//! CEA-608 (line 21) caption decoder: CC1 and CC2 on field 1, CC3 and CC4 on field 2.
2//!
3//! Pop-on, roll-up (2 to 4 rows) and paint-on captioning, preamble address codes, mid-row codes,
4//! the special and extended character sets, tab offsets, backspace, erase displayed / non-displayed
5//! memory and end-of-caption swaps. Text mode (T1 to T4) is recognised and its data dropped.
6//!
7//! A cue is one *stable* picture of the display memory: a new cue starts whenever the displayed
8//! text is committed (EOC, EDM, CR in roll-up, a mode switch, end of stream). Colour, italic and
9//! underline become [`Segment`] wrappers; row and column ride in [`CaptionLine`] and in the cue's
10//! [`CuePosition`] (percent of a 32 column by 15 row grid).
11
12use ec_subs::{CuePosition, Segment, SubtitleCue, TextAlign};
13
14/// One text line of a caption with its screen position.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct CaptionLine {
17 /// Zero based row, 0..=14 for 608.
18 pub row: u8,
19 /// Zero based column of the first visible character, 0..=31 for 608.
20 pub col: u8,
21 /// The line's characters without trailing blanks.
22 pub text: String,
23}
24
25/// A decoded caption cue.
26#[derive(Clone, Debug, PartialEq)]
27pub struct CaptionCue {
28 /// 608: 1 to 4 for CC1 to CC4. 708: the service number (1).
29 pub channel: u8,
30 /// The cue in the shared subtitle IR (text plus italic / underline / colour).
31 pub cue: SubtitleCue,
32 /// Row and column of every line.
33 pub lines: Vec<CaptionLine>,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub(crate) struct Cell {
38 pub ch: char,
39 pub color: u8,
40 pub italic: bool,
41 pub underline: bool,
42}
43
44pub(crate) const EMPTY: Cell = Cell {
45 ch: '\0',
46 color: 0,
47 italic: false,
48 underline: false,
49};
50
51const COLORS: [(u8, u8, u8); 8] = [
52 (255, 255, 255),
53 (0, 255, 0),
54 (0, 0, 255),
55 (0, 255, 255),
56 (255, 0, 0),
57 (255, 255, 0),
58 (255, 0, 255),
59 (0, 0, 0),
60];
61
62pub(crate) fn rgb(i: u8) -> (u8, u8, u8) {
63 COLORS[(i as usize).min(7)]
64}
65
66pub(crate) fn visible(c: &Cell) -> bool {
67 c.ch != '\0' && c.ch != ' '
68}
69
70/// Build a cue from rows of cells. `rows` pairs a row number with its cells.
71pub(crate) fn rows_to_cue(
72 channel: u8,
73 rows: &[(u8, &[Cell])],
74 cols: f32,
75 row_count: f32,
76 start_us: i64,
77 end_us: i64,
78) -> Option<CaptionCue> {
79 let mut segments = Vec::new();
80 let mut lines = Vec::new();
81 for (row, cells) in rows {
82 let Some(first) = cells.iter().position(visible) else {
83 continue;
84 };
85 let last = cells.iter().rposition(visible)?;
86 if !lines.is_empty() {
87 segments.push(Segment::LineBreak);
88 }
89 let mut text = String::new();
90 let mut k = first;
91 while k <= last {
92 let key = (cells[k].color, cells[k].italic, cells[k].underline);
93 let mut run = String::new();
94 while k <= last && (cells[k].color, cells[k].italic, cells[k].underline) == key {
95 run.push(if cells[k].ch == '\0' {
96 ' '
97 } else {
98 cells[k].ch
99 });
100 k += 1;
101 }
102 text.push_str(&run);
103 let mut seg = vec![Segment::Text(run)];
104 if key.2 {
105 seg = vec![Segment::Underline(seg)];
106 }
107 if key.1 {
108 seg = vec![Segment::Italic(seg)];
109 }
110 if key.0 != 0 {
111 seg = vec![Segment::Color {
112 rgb: rgb(key.0),
113 children: seg,
114 }];
115 }
116 segments.extend(seg);
117 }
118 lines.push(CaptionLine {
119 row: *row,
120 col: first as u8,
121 text,
122 });
123 }
124 let top = lines.first()?;
125 let positioning = Some(CuePosition {
126 x: Some(top.col as f32 / cols * 100.0),
127 y: Some(top.row as f32 / row_count * 100.0),
128 align: TextAlign::Left,
129 size: None,
130 });
131 Some(CaptionCue {
132 channel,
133 cue: SubtitleCue {
134 start_us,
135 end_us,
136 style_ref: None,
137 positioning,
138 segments,
139 },
140 lines,
141 })
142}
143
144/// Push a cue, merging into the previous one when contiguous and identical.
145pub(crate) fn push_merged(out: &mut Vec<CaptionCue>, c: CaptionCue) {
146 if let Some(l) = out.last_mut()
147 && l.cue.end_us == c.cue.start_us
148 && l.lines == c.lines
149 && l.cue.segments == c.cue.segments
150 {
151 l.cue.end_us = c.cue.end_us;
152 return;
153 }
154 out.push(c);
155}
156
157type Grid = [[Cell; 32]; 15];
158
159#[derive(Clone, Copy, PartialEq, Eq, Debug)]
160enum Mode {
161 None,
162 PopOn,
163 RollUp,
164 PaintOn,
165}
166
167struct Chan {
168 mode: Mode,
169 text_mode: bool,
170 disp: Grid,
171 non: Grid,
172 row: usize,
173 col: usize,
174 color: u8,
175 italic: bool,
176 underline: bool,
177 roll_n: usize,
178 show_since: i64,
179 cues: Vec<CaptionCue>,
180}
181
182impl Chan {
183 fn new() -> Chan {
184 Chan {
185 mode: Mode::None,
186 text_mode: false,
187 disp: [[EMPTY; 32]; 15],
188 non: [[EMPTY; 32]; 15],
189 row: 14,
190 col: 0,
191 color: 0,
192 italic: false,
193 underline: false,
194 roll_n: 2,
195 show_since: 0,
196 cues: Vec::new(),
197 }
198 }
199
200 fn disp_visible(&self) -> bool {
201 self.disp.iter().any(|r| r.iter().any(visible))
202 }
203
204 fn commit(&mut self, ch: u8, t: i64) {
205 if self.disp_visible() && t > self.show_since {
206 let rows: Vec<(u8, &[Cell])> = self
207 .disp
208 .iter()
209 .enumerate()
210 .map(|(i, r)| (i as u8, &r[..]))
211 .collect();
212 if let Some(c) = rows_to_cue(ch, &rows, 32.0, 15.0, self.show_since, t) {
213 push_merged(&mut self.cues, c);
214 }
215 }
216 self.show_since = t;
217 }
218
219 fn put(&mut self, c: char, t: i64) {
220 let cell = Cell {
221 ch: c,
222 color: self.color,
223 italic: self.italic,
224 underline: self.underline,
225 };
226 let col = self.col.min(31);
227 match self.mode {
228 Mode::None => {}
229 Mode::PopOn => {
230 self.non[self.row][col] = cell;
231 self.col = (self.col + 1).min(32);
232 }
233 Mode::RollUp | Mode::PaintOn => {
234 if !self.disp_visible() {
235 self.show_since = t;
236 }
237 self.disp[self.row][col] = cell;
238 self.col = (self.col + 1).min(32);
239 }
240 }
241 }
242
243 fn target(&mut self) -> Option<&mut Grid> {
244 match self.mode {
245 Mode::None => None,
246 Mode::PopOn => Some(&mut self.non),
247 _ => Some(&mut self.disp),
248 }
249 }
250}
251
252fn basic(c: u8) -> char {
253 match c {
254 0x2A => 'á',
255 0x5C => 'é',
256 0x5E => 'í',
257 0x5F => 'ó',
258 0x60 => 'ú',
259 0x7B => 'ç',
260 0x7C => '÷',
261 0x7D => 'Ñ',
262 0x7E => 'ñ',
263 0x7F => '\u{25A0}',
264 c => c as char,
265 }
266}
267
268const SPECIAL: [char; 16] = [
269 '®', '°', '½', '¿', '™', '¢', '£', '♪', 'à', ' ', 'è', 'â', 'ê', 'î', 'ô', 'û',
270];
271const EXT_A: [char; 32] = [
272 'Á', 'É', 'Ó', 'Ú', 'Ü', 'ü', '\u{2018}', '¡', '*', '\u{2019}', '\u{2014}', '©', '\u{2120}',
273 '\u{2022}', '\u{201C}', '\u{201D}', 'À', 'Â', 'Ç', 'È', 'Ê', 'Ë', 'ë', 'Î', 'Ï', 'ï', 'Ô', 'Ù',
274 'ù', 'Û', '«', '»',
275];
276const EXT_B: [char; 32] = [
277 'Ã', 'ã', 'Í', 'Ì', 'ì', 'Ò', 'ò', 'Õ', 'õ', '{', '}', '\\', '^', '_', '|', '~', 'Ä', 'ä', 'Ö',
278 'ö', 'ß', '¥', '¤', '\u{2502}', 'Å', 'å', 'Ø', 'ø', '\u{250C}', '\u{2510}', '\u{2514}',
279 '\u{2518}',
280];
281const PAC_ROW: [usize; 8] = [11, 1, 3, 12, 14, 5, 7, 9];
282
283/// CEA-608 decoder over (time, field, byte pair) input.
284pub struct Cea608Decoder {
285 ch: [Chan; 4],
286 active: [usize; 2],
287 last_ctrl: [Option<(u8, u8)>; 2],
288}
289
290impl Default for Cea608Decoder {
291 fn default() -> Self {
292 Self::new()
293 }
294}
295
296impl Cea608Decoder {
297 /// A decoder in power-up state.
298 pub fn new() -> Cea608Decoder {
299 Cea608Decoder {
300 ch: [Chan::new(), Chan::new(), Chan::new(), Chan::new()],
301 active: [0, 0],
302 last_ctrl: [None, None],
303 }
304 }
305
306 /// Feed one byte pair (parity bits are masked, not checked). `field` 0 or 1.
307 pub fn push_pair(&mut self, time_us: i64, field: u8, b1: u8, b2: u8) {
308 let f = (field & 1) as usize;
309 let (b1, b2) = (b1 & 0x7F, b2 & 0x7F);
310 if b1 < 0x10 {
311 self.last_ctrl[f] = None;
312 return;
313 }
314 if b1 >= 0x20 {
315 self.last_ctrl[f] = None;
316 let c = f * 2 + self.active[f];
317 let chan = &mut self.ch[c];
318 if chan.text_mode {
319 return;
320 }
321 chan.put(basic(b1), time_us);
322 if b2 >= 0x20 {
323 chan.put(basic(b2), time_us);
324 }
325 return;
326 }
327 let low = b1 & 7;
328 let undoubled = (low == 1 && b2 >= 0x30) || ((low == 2 || low == 3) && b2 >= 0x20);
329 if !undoubled {
330 if self.last_ctrl[f] == Some((b1, b2)) {
331 self.last_ctrl[f] = None;
332 return;
333 }
334 self.last_ctrl[f] = Some((b1, b2));
335 } else {
336 self.last_ctrl[f] = None;
337 }
338 self.active[f] = ((b1 >> 3) & 1) as usize;
339 let ci = f * 2 + self.active[f];
340 let n = (ci + 1) as u8;
341 let t = time_us;
342 let c = &mut self.ch[ci];
343 if b2 >= 0x40 {
344 // Preamble address code.
345 if c.text_mode {
346 return;
347 }
348 let mut row = PAC_ROW[low as usize] + usize::from(b2 >= 0x60);
349 if low == 0 && b2 >= 0x60 {
350 return;
351 }
352 row -= 1;
353 c.underline = b2 & 1 != 0;
354 let v = (b2 >> 1) & 0xF;
355 c.italic = v == 7;
356 c.color = if v < 7 { v } else { 0 };
357 c.col = if v >= 8 { ((v - 8) * 4) as usize } else { 0 };
358 if c.mode == Mode::RollUp {
359 row = row.max(c.roll_n - 1);
360 }
361 c.row = row.min(14);
362 return;
363 }
364 match (low, b2) {
365 (1, 0x20..=0x2F) if !c.text_mode => {
366 let v = (b2 - 0x20) >> 1;
367 c.underline = b2 & 1 != 0;
368 c.italic = v == 7;
369 c.color = if v < 7 { v } else { 0 };
370 c.put(' ', t);
371 }
372 (1, 0x30..=0x3F) if !c.text_mode => c.put(SPECIAL[(b2 - 0x30) as usize], t),
373 (2 | 3, 0x20..=0x3F) if !c.text_mode => {
374 c.col = c.col.saturating_sub(1);
375 let table = if low == 2 { &EXT_A } else { &EXT_B };
376 c.put(table[(b2 - 0x20) as usize], t);
377 }
378 (7, 0x21..=0x23) if !c.text_mode => c.col = (c.col + (b2 - 0x20) as usize).min(31),
379 (4 | 5, 0x20..=0x2F) => match b2 {
380 0x20 => {
381 c.text_mode = false;
382 c.mode = Mode::PopOn;
383 }
384 0x21 if !c.text_mode => {
385 c.col = c.col.saturating_sub(1);
386 let col = c.col;
387 let row = c.row;
388 if let Some(g) = c.target() {
389 g[row][col] = EMPTY;
390 }
391 }
392 0x24 if !c.text_mode => {
393 let (row, col) = (c.row, c.col.min(31));
394 if let Some(g) = c.target() {
395 for x in &mut g[row][col..] {
396 *x = EMPTY;
397 }
398 }
399 }
400 0x25..=0x27 => {
401 c.text_mode = false;
402 c.roll_n = (b2 - 0x23) as usize;
403 if c.mode != Mode::RollUp {
404 c.commit(n, t);
405 c.disp = [[EMPTY; 32]; 15];
406 c.non = [[EMPTY; 32]; 15];
407 c.row = 14;
408 c.col = 0;
409 c.mode = Mode::RollUp;
410 } else {
411 c.row = c.row.max(c.roll_n - 1);
412 }
413 }
414 0x29 => {
415 c.text_mode = false;
416 c.mode = Mode::PaintOn;
417 }
418 0x2A | 0x2B => c.text_mode = true,
419 0x2C => {
420 c.commit(n, t);
421 c.disp = [[EMPTY; 32]; 15];
422 }
423 0x2D if c.mode == Mode::RollUp && !c.text_mode => {
424 c.commit(n, t);
425 let base = c.row;
426 let top = (base + 1).saturating_sub(c.roll_n);
427 for r in top..base {
428 c.disp[r] = c.disp[r + 1];
429 }
430 c.disp[base] = [EMPTY; 32];
431 c.col = 0;
432 }
433 0x2E => c.non = [[EMPTY; 32]; 15],
434 0x2F => {
435 c.text_mode = false;
436 c.commit(n, t);
437 std::mem::swap(&mut c.disp, &mut c.non);
438 c.mode = Mode::PopOn;
439 c.show_since = t;
440 }
441 _ => {}
442 },
443 _ => {}
444 }
445 }
446
447 /// Close the open display at `end_us` and return all cues of all channels by start time.
448 pub fn finish(&mut self, end_us: i64) -> Vec<CaptionCue> {
449 let mut out = Vec::new();
450 for (i, c) in self.ch.iter_mut().enumerate() {
451 c.commit((i + 1) as u8, end_us);
452 out.append(&mut c.cues);
453 }
454 out.sort_by_key(|c| (c.cue.start_us, c.channel));
455 out
456 }
457}