1use crate::cc_data::{CcTriplet, CcType};
13use crate::decode::screen::{
14 Color, EdgeType, FontStyle, Justify, Opacity, PenOffset, PenSize, PrintDirection,
15 ScrollDirection,
16};
17use alloc::string::String;
18use alloc::vec::Vec;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize))]
24#[non_exhaustive]
25pub enum AnchorPoint {
26 #[default]
28 TopLeft,
29 TopCenter,
31 TopRight,
33 MiddleLeft,
35 MiddleCenter,
37 MiddleRight,
39 BottomLeft,
41 BottomCenter,
43 BottomRight,
45}
46
47impl AnchorPoint {
48 #[must_use]
50 pub fn from_bits(v: u8) -> Self {
51 match v & 0x0F {
52 0 => Self::TopLeft,
53 1 => Self::TopCenter,
54 2 => Self::TopRight,
55 3 => Self::MiddleLeft,
56 4 => Self::MiddleCenter,
57 5 => Self::MiddleRight,
58 6 => Self::BottomLeft,
59 7 => Self::BottomCenter,
60 8 => Self::BottomRight,
61 _ => Self::TopLeft,
62 }
63 }
64 #[must_use]
66 pub fn name(&self) -> &'static str {
67 match self {
68 Self::TopLeft => "top_left",
69 Self::TopCenter => "top_center",
70 Self::TopRight => "top_right",
71 Self::MiddleLeft => "middle_left",
72 Self::MiddleCenter => "middle_center",
73 Self::MiddleRight => "middle_right",
74 Self::BottomLeft => "bottom_left",
75 Self::BottomCenter => "bottom_center",
76 Self::BottomRight => "bottom_right",
77 }
78 }
79}
80broadcast_common::impl_spec_display!(AnchorPoint);
81
82const NUM_SERVICES: usize = 6;
85const NUM_WINDOWS: usize = 8;
87const MAX_WINDOW_ROWS: usize = 12;
89const MAX_WINDOW_COLS: usize = 42;
91
92const PACKET_SIZE_ZERO_DATA: usize = 127;
95
96const EXTENDED_SERVICE_ESCAPE: u8 = 7;
99
100const C0_NUL: u8 = 0x00;
102const C0_ETX: u8 = 0x03;
103const C0_BS: u8 = 0x08;
104const C0_FF: u8 = 0x0C;
105const C0_CR: u8 = 0x0D;
106const C0_HCR: u8 = 0x0E;
107const C0_EXT1: u8 = 0x10;
108const C0_P16: u8 = 0x18;
109
110const C1_CW0: u8 = 0x80; const C1_CW7: u8 = 0x87;
113const C1_CLW: u8 = 0x88;
114const C1_DSW: u8 = 0x89;
115const C1_HDW: u8 = 0x8A;
116const C1_TGW: u8 = 0x8B;
117const C1_DLW: u8 = 0x8C;
118const C1_DLY: u8 = 0x8D;
119const C1_DLC: u8 = 0x8E;
120const C1_RST: u8 = 0x8F;
121const C1_SPA: u8 = 0x90;
122const C1_SPC: u8 = 0x91;
123const C1_SPL: u8 = 0x92;
124const C1_SWA: u8 = 0x97;
125const C1_DF0: u8 = 0x98; const C1_DF7: u8 = 0x9F;
127
128const C0_END: u8 = 0x1F;
130const G0_START: u8 = 0x20;
131const G0_END: u8 = 0x7F;
132const C1_START: u8 = 0x80;
133const C1_END: u8 = 0x9F;
134const G1_START: u8 = 0xA0;
135
136const G0_MUSIC_NOTE: u8 = 0x7F;
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
141#[cfg_attr(feature = "serde", derive(serde::Serialize))]
142#[non_exhaustive]
143pub enum WindowState {
144 #[default]
146 Hidden,
147 Visible,
149}
150
151impl WindowState {
152 #[must_use]
154 pub fn name(&self) -> &'static str {
155 match self {
156 Self::Hidden => "hidden",
157 Self::Visible => "visible",
158 }
159 }
160}
161broadcast_common::impl_spec_display!(WindowState);
162
163#[derive(Debug, Clone, PartialEq, Eq)]
169#[cfg_attr(feature = "serde", derive(serde::Serialize))]
170pub struct Window {
171 pub state: WindowState,
173 pub priority: u8,
175 pub anchor_point: AnchorPoint,
177 pub anchor_vertical: u8,
179 pub anchor_horizontal: u8,
181 pub relative_position: bool,
183 pub row_count: u8,
185 pub column_count: u8,
187 pub row_lock: bool,
189 pub column_lock: bool,
191 pub window_style: u8,
193 pub pen_style: u8,
195 pub justify: Justify,
197 pub print_direction: PrintDirection,
199 pub scroll_direction: ScrollDirection,
201 pub word_wrap: bool,
203 pub fill_color: Color,
205 pub fill_opacity: Opacity,
207 pub border_color: Color,
209 pub border_type: EdgeType,
211 pub pen_size: PenSize,
213 pub pen_offset: PenOffset,
215 pub font_style: FontStyle,
217 pub italics: bool,
219 pub underline: bool,
221 pub edge_type: EdgeType,
223 pub edge_color: Color,
227 pub fg_color: Color,
229 pub fg_opacity: Opacity,
231 pub bg_color: Color,
233 pub bg_opacity: Opacity,
235 rows: Vec<String>,
237 pen_row: usize,
239 pen_col: usize,
241}
242
243impl Window {
244 fn new() -> Self {
245 Window {
246 state: WindowState::Hidden,
247 priority: 0,
248 anchor_point: AnchorPoint::TopLeft,
249 anchor_vertical: 0,
250 anchor_horizontal: 0,
251 relative_position: false,
252 row_count: 1,
253 column_count: 1,
254 row_lock: false,
255 column_lock: false,
256 window_style: 0,
257 pen_style: 0,
258 justify: Justify::Left,
259 print_direction: PrintDirection::LeftToRight,
260 scroll_direction: ScrollDirection::BottomToTop,
261 word_wrap: false,
262 fill_color: Color::BLACK,
263 fill_opacity: Opacity::Solid,
264 border_color: Color::BLACK,
265 border_type: EdgeType::None,
266 pen_size: PenSize::Standard,
267 pen_offset: PenOffset::Normal,
268 font_style: FontStyle::Default,
269 italics: false,
270 underline: false,
271 edge_type: EdgeType::None,
272 edge_color: Color::BLACK,
273 fg_color: Color::WHITE,
274 fg_opacity: Opacity::Solid,
275 bg_color: Color::BLACK,
276 bg_opacity: Opacity::Solid,
277 rows: Vec::new(),
278 pen_row: 0,
279 pen_col: 0,
280 }
281 }
282
283 fn ensure_grid(&mut self) {
284 let rows = (self.row_count as usize).clamp(1, MAX_WINDOW_ROWS);
285 if self.rows.len() != rows {
286 self.rows = alloc::vec![String::new(); rows];
287 }
288 }
289
290 fn clear_text(&mut self) {
291 for r in &mut self.rows {
292 r.clear();
293 }
294 self.pen_row = 0;
295 self.pen_col = 0;
296 }
297
298 fn cols(&self) -> usize {
299 (self.column_count as usize).clamp(1, MAX_WINDOW_COLS)
300 }
301
302 fn put_char(&mut self, ch: char) {
304 self.ensure_grid();
305 let cols = self.cols();
306 if self.pen_row >= self.rows.len() {
307 return;
308 }
309 let row = &mut self.rows[self.pen_row];
311 while row.chars().count() < self.pen_col {
312 row.push(' ');
313 }
314 if self.pen_col < cols {
315 row.push(ch);
316 self.pen_col += 1;
317 }
318 }
319
320 fn back_space(&mut self) {
322 if self.pen_col > 0 {
323 self.pen_col -= 1;
324 if self.pen_row < self.rows.len() {
325 let row = &mut self.rows[self.pen_row];
326 let mut chars: Vec<char> = row.chars().collect();
327 if self.pen_col < chars.len() {
328 chars.truncate(self.pen_col);
329 *row = chars.into_iter().collect();
330 }
331 }
332 }
333 }
334
335 fn carriage_return(&mut self) {
337 self.ensure_grid();
338 self.pen_col = 0;
339 if self.pen_row + 1 < self.rows.len() {
340 self.pen_row += 1;
341 } else if !self.rows.is_empty() {
342 self.rows.remove(0);
344 self.rows.push(String::new());
345 self.pen_row = self.rows.len() - 1;
346 }
347 }
348
349 fn horizontal_cr(&mut self) {
351 self.ensure_grid();
352 if self.pen_row < self.rows.len() {
353 self.rows[self.pen_row].clear();
354 }
355 self.pen_col = 0;
356 }
357
358 fn set_pen_location(&mut self, row: usize, col: usize) {
359 self.ensure_grid();
360 self.pen_row = row.min(self.rows.len().saturating_sub(1));
361 self.pen_col = col.min(self.cols());
362 }
363
364 #[must_use]
370 pub fn text(&self) -> String {
371 let lines: Vec<&str> = self
372 .rows
373 .iter()
374 .map(|r| r.trim_end())
375 .filter(|l| !l.is_empty())
376 .collect();
377 lines.join("\n")
378 }
379}
380
381#[derive(Debug, Clone, PartialEq, Eq, Default)]
383#[cfg_attr(feature = "serde", derive(serde::Serialize))]
384struct Service {
385 windows: [Option<Window>; NUM_WINDOWS],
386 current_window: Option<usize>,
388}
389
390impl Service {
391 fn reset(&mut self) {
392 *self = Service::default();
393 }
394
395 fn current(&mut self) -> Option<&mut Window> {
396 let id = self.current_window?;
397 self.windows.get_mut(id)?.as_mut()
398 }
399}
400
401#[derive(Debug, Clone, PartialEq, Eq)]
417#[cfg_attr(feature = "serde", derive(serde::Serialize))]
418pub struct Cea708Decoder {
419 services: [Service; NUM_SERVICES],
420 packet: Vec<u8>,
422 last_seq: Option<u8>,
424}
425
426impl Default for Cea708Decoder {
427 fn default() -> Self {
428 Self::new()
429 }
430}
431
432impl Cea708Decoder {
433 #[must_use]
435 pub fn new() -> Self {
436 Cea708Decoder {
437 services: Default::default(),
438 packet: Vec::new(),
439 last_seq: None,
440 }
441 }
442
443 pub fn reset(&mut self) {
445 for s in &mut self.services {
446 s.reset();
447 }
448 self.packet.clear();
449 self.last_seq = None;
450 }
451
452 pub fn push_triplets<'a, I>(&mut self, triplets: I)
462 where
463 I: IntoIterator<Item = &'a CcTriplet>,
464 {
465 for t in triplets {
466 if !t.cc_valid {
467 continue;
468 }
469 match t.cc_type {
470 CcType::Dtvcc708Start => {
471 self.flush_packet();
475 self.packet.clear();
476 self.packet.push(t.cc_data_1);
477 self.packet.push(t.cc_data_2);
478 }
479 CcType::Dtvcc708Data => {
480 if self.packet.is_empty() {
481 continue;
487 }
488 self.packet.push(t.cc_data_1);
489 self.packet.push(t.cc_data_2);
490 }
491 _ => {}
492 }
493 }
494 if self.packet_is_complete() {
500 self.flush_packet();
501 }
502 }
503
504 pub fn push_packet(&mut self, ccp: &[u8]) {
507 self.decode_packet(ccp);
508 }
509
510 fn packet_is_complete(&self) -> bool {
514 let Some(&header) = self.packet.first() else {
515 return false;
516 };
517 let size_code = header & 0x3F;
518 let data_size = if size_code == 0 {
519 PACKET_SIZE_ZERO_DATA
520 } else {
521 (size_code as usize) * 2 - 1
522 };
523 self.packet.len() > data_size
524 }
525
526 fn flush_packet(&mut self) {
528 if self.packet.is_empty() {
529 return;
530 }
531 let packet = core::mem::take(&mut self.packet);
532 self.decode_packet(&packet);
533 }
534
535 fn decode_packet(&mut self, ccp: &[u8]) {
537 let Some((&header, rest)) = ccp.split_first() else {
538 return;
539 };
540 let seq = (header >> 6) & 0x03;
541 let size_code = header & 0x3F;
542 let data_size = if size_code == 0 {
543 PACKET_SIZE_ZERO_DATA
544 } else {
545 (size_code as usize) * 2 - 1
546 };
547 if let Some(prev) = self.last_seq
549 && seq != (prev + 1) & 0x03
550 {
551 for s in &mut self.services {
552 s.reset();
553 }
554 }
555 self.last_seq = Some(seq);
556 let end = data_size.min(rest.len());
557 self.decode_service_blocks(&rest[..end]);
558 }
559
560 fn decode_service_blocks(&mut self, mut data: &[u8]) {
562 loop {
563 let Some((&header, rest)) = data.split_first() else {
564 return;
565 };
566 if header == 0 {
568 return;
569 }
570 let mut service_number = u16::from((header >> 5) & 0x07);
571 let block_size = (header & 0x1F) as usize;
572 let mut body = rest;
573 if service_number == u16::from(EXTENDED_SERVICE_ESCAPE) && block_size != 0 {
574 let Some((&ext, after)) = rest.split_first() else {
576 return;
577 };
578 service_number = u16::from(ext & 0x3F);
579 body = after;
580 }
581 if block_size > body.len() {
582 self.dispatch_service(service_number, body);
584 return;
585 }
586 let (block, next) = body.split_at(block_size);
587 self.dispatch_service(service_number, block);
588 data = next;
589 }
590 }
591
592 fn dispatch_service(&mut self, service_number: u16, block: &[u8]) {
593 if service_number == 0 || service_number as usize > NUM_SERVICES {
595 return;
596 }
597 let idx = service_number as usize - 1;
598 Self::interpret(&mut self.services[idx], block);
599 }
600
601 fn interpret(service: &mut Service, block: &[u8]) {
603 let mut i = 0usize;
604 while i < block.len() {
605 let b = block[i];
606 let consumed = match b {
607 0x00..=C0_END => Self::handle_c0(service, &block[i..]),
608 G0_START..=G0_END => {
609 Self::put(service, Self::g0_char(b));
610 1
611 }
612 C1_START..=C1_END => Self::handle_c1(service, &block[i..]),
613 G1_START..=0xFF => {
614 Self::put(service, char::from(b));
616 1
617 }
618 };
619 i += consumed.max(1);
620 }
621 }
622
623 fn handle_c0(service: &mut Service, data: &[u8]) -> usize {
625 let b = data[0];
626 match b {
627 C0_NUL => 1,
628 C0_ETX => 1,
629 C0_BS if let Some(w) = service.current() => {
633 w.back_space();
634 1
635 }
636 C0_FF if let Some(w) = service.current() => {
637 w.clear_text();
638 1
639 }
640 C0_CR if let Some(w) = service.current() => {
641 w.carriage_return();
642 1
643 }
644 C0_HCR if let Some(w) = service.current() => {
645 w.horizontal_cr();
646 1
647 }
648 C0_EXT1 => Self::handle_ext1(service, data),
649 C0_P16 => 3, 0x11..=0x17 => 2,
653 0x19..=0x1F => 3,
654 _ => 1,
655 }
656 }
657
658 fn handle_ext1(service: &mut Service, data: &[u8]) -> usize {
661 let Some(&base) = data.get(1) else {
662 return 1;
663 };
664 match base {
665 0x00..=0x07 => 2,
667 0x08..=0x0F => 3,
668 0x10..=0x17 => 4,
669 0x18..=0x1F => 5,
670 0x20..=0x7F => {
672 Self::put(service, Self::g2_char(base));
673 2
674 }
675 0x80..=0x87 => 6,
677 0x88..=0x8F => 7,
678 0x90..=0x9F => {
679 let n = data.get(2).map_or(0, |d| (d & 0x3F) as usize + 1);
681 3 + n
682 }
683 _ => {
685 Self::put(service, Self::g3_char(base));
686 2
687 }
688 }
689 }
690
691 fn handle_c1(service: &mut Service, data: &[u8]) -> usize {
693 let op = data[0];
694 match op {
695 C1_CW0..=C1_CW7 => {
696 let id = (op - C1_CW0) as usize;
697 if service.windows.get(id).and_then(|w| w.as_ref()).is_some() {
698 service.current_window = Some(id);
699 }
700 1
701 }
702 C1_CLW => Self::window_map_cmd(service, data, WindowMapOp::Clear),
703 C1_DSW => Self::window_map_cmd(service, data, WindowMapOp::Display),
704 C1_HDW => Self::window_map_cmd(service, data, WindowMapOp::Hide),
705 C1_TGW => Self::window_map_cmd(service, data, WindowMapOp::Toggle),
706 C1_DLW => Self::window_map_cmd(service, data, WindowMapOp::Delete),
707 C1_DLY => 2, C1_DLC => 1, C1_RST => {
710 service.reset();
711 1
712 }
713 C1_SPA => Self::set_pen_attributes(service, data),
714 C1_SPC => Self::set_pen_color(service, data),
715 C1_SPL => Self::set_pen_location(service, data),
716 C1_SWA => Self::set_window_attributes(service, data),
717 C1_DF0..=C1_DF7 => Self::define_window(service, data),
718 _ => 1,
720 }
721 }
722
723 fn window_map_cmd(service: &mut Service, data: &[u8], op: WindowMapOp) -> usize {
724 let Some(&map) = data.get(1) else {
725 return 1;
726 };
727 for id in 0..NUM_WINDOWS {
728 if map & (1 << id) == 0 {
729 continue;
730 }
731 match op {
732 WindowMapOp::Clear if let Some(w) = service.windows[id].as_mut() => {
733 w.clear_text();
734 }
735 WindowMapOp::Clear => {}
736 WindowMapOp::Display if let Some(w) = service.windows[id].as_mut() => {
737 w.state = WindowState::Visible;
738 }
739 WindowMapOp::Display => {}
740 WindowMapOp::Hide if let Some(w) = service.windows[id].as_mut() => {
741 w.state = WindowState::Hidden;
742 }
743 WindowMapOp::Hide => {}
744 WindowMapOp::Toggle if let Some(w) = service.windows[id].as_mut() => {
745 w.state = match w.state {
746 WindowState::Visible => WindowState::Hidden,
747 WindowState::Hidden => WindowState::Visible,
748 };
749 }
750 WindowMapOp::Toggle => {}
751 WindowMapOp::Delete => {
752 service.windows[id] = None;
753 if service.current_window == Some(id) {
754 service.current_window = None;
755 }
756 }
757 }
758 }
759 2
760 }
761
762 fn define_window(service: &mut Service, data: &[u8]) -> usize {
764 const TOTAL: usize = 7;
765 if data.len() < TOTAL {
766 return data.len().max(1);
767 }
768 let id = (data[0] - C1_DF0) as usize;
769 let p1 = data[1];
770 let p2 = data[2];
771 let p3 = data[3];
772 let p4 = data[4];
773 let p5 = data[5];
774 let p6 = data[6];
775
776 let creating = service.windows[id].is_none();
777 let w = service.windows[id].get_or_insert_with(Window::new);
778
779 w.priority = p1 & 0x07;
780 w.column_lock = (p1 >> 3) & 0x01 != 0;
781 w.row_lock = (p1 >> 4) & 0x01 != 0;
782 w.state = if (p1 >> 5) & 0x01 != 0 {
783 WindowState::Visible
784 } else {
785 WindowState::Hidden
786 };
787 w.relative_position = (p2 >> 7) & 0x01 != 0;
788 w.anchor_vertical = p2 & 0x7F;
789 w.anchor_horizontal = p3;
790 w.anchor_point = AnchorPoint::from_bits((p4 >> 4) & 0x0F);
791 w.row_count = (p4 & 0x0F) + 1;
792 w.column_count = (p5 & 0x3F) + 1;
793 w.window_style = (p6 >> 3) & 0x07;
794 w.pen_style = p6 & 0x07;
795
796 if creating {
797 apply_window_style(
799 w,
800 if w.window_style == 0 {
801 1
802 } else {
803 w.window_style
804 },
805 );
806 apply_pen_style(w, if w.pen_style == 0 { 1 } else { w.pen_style });
807 w.ensure_grid();
808 w.clear_text();
809 } else {
810 if w.window_style != 0 {
812 apply_window_style(w, w.window_style);
813 }
814 if w.pen_style != 0 {
815 apply_pen_style(w, w.pen_style);
816 }
817 w.ensure_grid();
818 }
819 service.current_window = Some(id);
820 TOTAL
821 }
822
823 fn set_window_attributes(service: &mut Service, data: &[u8]) -> usize {
825 const TOTAL: usize = 5;
826 if data.len() < TOTAL {
827 return data.len().max(1);
828 }
829 let p1 = data[1];
830 let p2 = data[2];
831 let p3 = data[3];
832 let p4 = data[4];
833 if let Some(w) = service.current() {
834 w.fill_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
835 w.fill_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
836 let bt_lo = (p2 >> 6) & 0x03;
837 w.border_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
838 let bt_hi = (p3 >> 7) & 0x01;
839 w.border_type = EdgeType::from_bits((bt_hi << 2) | bt_lo);
840 w.word_wrap = (p3 >> 6) & 0x01 != 0;
841 w.print_direction = PrintDirection::from_bits((p3 >> 4) & 0x03);
842 w.scroll_direction = ScrollDirection::from_bits((p3 >> 2) & 0x03);
843 w.justify = Justify::from_bits(p3 & 0x03);
844 let _ = p4;
846 }
847 TOTAL
848 }
849
850 fn set_pen_attributes(service: &mut Service, data: &[u8]) -> usize {
852 const TOTAL: usize = 3;
853 if data.len() < TOTAL {
854 return data.len().max(1);
855 }
856 let p1 = data[1];
857 let p2 = data[2];
858 if let Some(w) = service.current() {
859 w.pen_offset = PenOffset::from_bits((p1 >> 2) & 0x03);
860 w.pen_size = PenSize::from_bits(p1 & 0x03);
861 w.italics = (p2 >> 7) & 0x01 != 0;
862 w.underline = (p2 >> 6) & 0x01 != 0;
863 w.edge_type = EdgeType::from_bits((p2 >> 3) & 0x07);
864 w.font_style = FontStyle::from_bits(p2 & 0x07);
865 }
866 TOTAL
867 }
868
869 fn set_pen_color(service: &mut Service, data: &[u8]) -> usize {
871 const TOTAL: usize = 4;
872 if data.len() < TOTAL {
873 return data.len().max(1);
874 }
875 let p1 = data[1];
876 let p2 = data[2];
877 let p3 = data[3];
878 if let Some(w) = service.current() {
879 w.fg_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
880 w.fg_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
881 w.bg_opacity = Opacity::from_bits((p2 >> 6) & 0x03);
882 w.bg_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
883 w.edge_color = Color::new((p3 >> 4) & 0x03, (p3 >> 2) & 0x03, p3 & 0x03);
885 }
886 TOTAL
887 }
888
889 fn set_pen_location(service: &mut Service, data: &[u8]) -> usize {
891 const TOTAL: usize = 3;
892 if data.len() < TOTAL {
893 return data.len().max(1);
894 }
895 let row = (data[1] & 0x0F) as usize;
896 let col = (data[2] & 0x3F) as usize;
897 if let Some(w) = service.current() {
898 w.set_pen_location(row, col);
899 }
900 TOTAL
901 }
902
903 fn put(service: &mut Service, ch: char) {
904 if let Some(w) = service.current() {
905 w.put_char(ch);
906 }
907 }
908
909 fn g0_char(b: u8) -> char {
911 if b == G0_MUSIC_NOTE {
912 '\u{266A}'
913 } else {
914 char::from(b)
915 }
916 }
917
918 fn g2_char(b: u8) -> char {
920 match b {
921 0x20 | 0x21 => ' ', 0x25 => '\u{2026}', 0x2A => '\u{0160}', 0x2C => '\u{0152}', 0x30 => '\u{25A0}', 0x31 => '\u{2018}', 0x32 => '\u{2019}', 0x33 => '\u{201C}', 0x34 => '\u{201D}', 0x35 => '\u{2022}', 0x39 => '\u{2122}', 0x3A => '\u{0161}', 0x3C => '\u{0153}', 0x3D => '\u{2120}', 0x3F => '\u{0178}', 0x76 => '\u{215B}', 0x77 => '\u{215C}', 0x78 => '\u{215D}', 0x79 => '\u{215E}', _ => '_', }
942 }
943
944 fn g3_char(b: u8) -> char {
946 if b == 0xA0 {
947 '\u{1F4FA}' } else {
949 '_'
950 }
951 }
952
953 #[must_use]
956 pub fn windows(&self, service_number: usize) -> &[Option<Window>; NUM_WINDOWS] {
957 const EMPTY: [Option<Window>; NUM_WINDOWS] =
958 [None, None, None, None, None, None, None, None];
959 if service_number == 0 || service_number > NUM_SERVICES {
960 return &EMPTY;
961 }
962 &self.services[service_number - 1].windows
963 }
964
965 #[must_use]
968 pub fn service_text(&self, service_number: usize) -> String {
969 if service_number == 0 || service_number > NUM_SERVICES {
970 return String::new();
971 }
972 let svc = &self.services[service_number - 1];
973 let mut idxs: Vec<usize> = (0..NUM_WINDOWS)
974 .filter(|&i| {
975 svc.windows[i]
976 .as_ref()
977 .is_some_and(|w| w.state == WindowState::Visible)
978 })
979 .collect();
980 idxs.sort_by_key(|&i| {
981 svc.windows[i]
982 .as_ref()
983 .map_or((u8::MAX, i), |w| (w.priority, i))
984 });
985 let mut out = String::new();
986 for i in idxs {
987 if let Some(w) = svc.windows[i].as_ref() {
988 let t = w.text();
989 if t.is_empty() {
990 continue;
991 }
992 if !out.is_empty() {
993 out.push('\n');
994 }
995 out.push_str(&t);
996 }
997 }
998 out
999 }
1000}
1001
1002#[derive(Clone, Copy)]
1004enum WindowMapOp {
1005 Clear,
1006 Display,
1007 Hide,
1008 Toggle,
1009 Delete,
1010}
1011
1012fn apply_window_style(w: &mut Window, id: u8) {
1014 w.border_type = EdgeType::None;
1017 match id {
1018 1 => style(w, Justify::Left, false, Some(Color::BLACK), Opacity::Solid),
1019 2 => style(w, Justify::Left, false, None, Opacity::Transparent),
1020 3 => style(
1021 w,
1022 Justify::Center,
1023 false,
1024 Some(Color::BLACK),
1025 Opacity::Solid,
1026 ),
1027 4 => style(w, Justify::Left, true, Some(Color::BLACK), Opacity::Solid),
1028 5 => style(w, Justify::Left, true, None, Opacity::Transparent),
1029 6 => style(w, Justify::Center, true, Some(Color::BLACK), Opacity::Solid),
1030 7 => {
1031 w.justify = Justify::Left;
1032 w.word_wrap = false;
1033 w.print_direction = PrintDirection::TopToBottom;
1034 w.scroll_direction = ScrollDirection::RightToLeft;
1035 w.fill_color = Color::BLACK;
1036 w.fill_opacity = Opacity::Solid;
1037 }
1038 _ => {}
1039 }
1040}
1041
1042fn style(w: &mut Window, j: Justify, ww: bool, fill: Option<Color>, op: Opacity) {
1043 w.justify = j;
1044 w.word_wrap = ww;
1045 w.print_direction = PrintDirection::LeftToRight;
1046 w.scroll_direction = ScrollDirection::BottomToTop;
1047 w.fill_opacity = op;
1048 if let Some(c) = fill {
1049 w.fill_color = c;
1050 }
1051}
1052
1053fn apply_pen_style(w: &mut Window, id: u8) {
1055 w.pen_size = PenSize::Standard;
1056 w.pen_offset = PenOffset::Normal;
1057 w.italics = false;
1058 w.underline = false;
1059 w.fg_color = Color::WHITE;
1060 w.fg_opacity = Opacity::Solid;
1061 match id {
1062 1 => pen(
1063 w,
1064 FontStyle::Default,
1065 EdgeType::None,
1066 Color::BLACK,
1067 Opacity::Solid,
1068 ),
1069 2 => pen(
1070 w,
1071 FontStyle::MonospacedSerif,
1072 EdgeType::None,
1073 Color::BLACK,
1074 Opacity::Solid,
1075 ),
1076 3 => pen(
1077 w,
1078 FontStyle::ProportionalSerif,
1079 EdgeType::None,
1080 Color::BLACK,
1081 Opacity::Solid,
1082 ),
1083 4 => pen(
1084 w,
1085 FontStyle::MonospacedSansSerif,
1086 EdgeType::None,
1087 Color::BLACK,
1088 Opacity::Solid,
1089 ),
1090 5 => pen(
1091 w,
1092 FontStyle::ProportionalSansSerif,
1093 EdgeType::None,
1094 Color::BLACK,
1095 Opacity::Solid,
1096 ),
1097 6 => pen(
1098 w,
1099 FontStyle::MonospacedSansSerif,
1100 EdgeType::Uniform,
1101 Color::BLACK,
1102 Opacity::Transparent,
1103 ),
1104 7 => pen(
1105 w,
1106 FontStyle::ProportionalSansSerif,
1107 EdgeType::Uniform,
1108 Color::BLACK,
1109 Opacity::Transparent,
1110 ),
1111 _ => {}
1112 }
1113}
1114
1115fn pen(w: &mut Window, font: FontStyle, edge: EdgeType, bg: Color, bg_op: Opacity) {
1116 w.font_style = font;
1117 w.edge_type = edge;
1118 w.bg_color = bg;
1119 w.bg_opacity = bg_op;
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124 use super::*;
1125
1126 fn ccp(svc: u8, cmds: &[u8]) -> Vec<u8> {
1128 let mut sb = alloc::vec![(svc << 5) | (cmds.len() as u8)];
1129 sb.extend_from_slice(cmds);
1130 let size_code = (sb.len().div_ceil(2) + 1) as u8 & 0x3F;
1132 let mut packet = alloc::vec![size_code];
1133 packet.extend_from_slice(&sb);
1134 packet
1135 }
1136
1137 #[test]
1142 fn define_window_worked_example() {
1143 let mut dec = Cea708Decoder::new();
1144 let packet = ccp(1, &[0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11]);
1145 dec.push_packet(&packet);
1146 let w = dec.windows(1)[2].as_ref().expect("window 2 defined");
1147 assert_eq!(w.state, WindowState::Visible);
1148 assert!(w.row_lock);
1149 assert!(w.column_lock);
1150 assert_eq!(w.priority, 0);
1151 assert!(!w.relative_position);
1152 assert_eq!(w.anchor_vertical, 74);
1153 assert_eq!(w.anchor_horizontal, 209);
1154 assert_eq!(w.anchor_point, AnchorPoint::BottomRight);
1155 assert_eq!(w.row_count, 12);
1156 assert_eq!(w.column_count, 16);
1157 assert_eq!(w.window_style, 2);
1158 assert_eq!(w.pen_style, 1);
1159 }
1160
1161 #[test]
1164 fn swa_border_type_split() {
1165 let mut dec = Cea708Decoder::new();
1166 let packet = ccp(
1168 1,
1169 &[
1170 0x98, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x64, 0x53, 0x88, 0x22, ],
1173 );
1174 dec.push_packet(&packet);
1175 let w = dec.windows(1)[0].as_ref().expect("window 0");
1176 assert_eq!(w.border_type, EdgeType::RightDropShadow);
1177 }
1178
1179 #[test]
1181 fn decode_text() {
1182 let mut dec = Cea708Decoder::new();
1183 let packet = ccp(
1184 1,
1185 &[
1186 0x98, 0x20, 0x00, 0x00, 0x02, 0x0F, 0x00, b'H', b'i',
1188 ],
1189 );
1190 dec.push_packet(&packet);
1191 assert_eq!(dec.service_text(1), "Hi");
1192 }
1193
1194 #[test]
1196 fn two_services_multi_window() {
1197 let mut dec = Cea708Decoder::new();
1198 let s1_block = [0x98, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'1'];
1200 let s2_block = [0x99, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'2'];
1202 let mut data = Vec::new();
1203 data.push((1 << 5) | (s1_block.len() as u8));
1204 data.extend_from_slice(&s1_block);
1205 data.push((2 << 5) | (s2_block.len() as u8));
1206 data.extend_from_slice(&s2_block);
1207 let size_code = (data.len().div_ceil(2) + 1) as u8 & 0x3F;
1208 let mut packet = alloc::vec![size_code];
1209 packet.extend_from_slice(&data);
1210 dec.push_packet(&packet);
1211 assert_eq!(dec.service_text(1), "S1");
1212 assert_eq!(dec.service_text(2), "S2");
1213 assert!(dec.windows(1)[0].is_some());
1214 assert!(dec.windows(2)[1].is_some());
1215 }
1216
1217 #[test]
1218 fn carriage_return_rolls_up() {
1219 let mut w = Window::new();
1220 w.row_count = 2;
1221 w.column_count = 10;
1222 w.ensure_grid();
1223 w.put_char('A');
1224 w.carriage_return();
1225 w.put_char('B');
1226 w.carriage_return(); w.put_char('C');
1228 assert_eq!(w.text(), "B\nC");
1229 }
1230
1231 #[test]
1232 fn g0_music_note() {
1233 assert_eq!(Cea708Decoder::g0_char(0x7F), '\u{266A}');
1234 assert_eq!(Cea708Decoder::g0_char(b'A'), 'A');
1235 }
1236
1237 #[test]
1238 fn no_panic_on_arbitrary_input() {
1239 let inputs: &[&[u8]] = &[
1241 &[],
1242 &[0x00],
1243 &[0xFF],
1244 &[0x01, 0x98], &[0x3F, 0x80, 0x90, 0x91, 0x92, 0x97, 0x98], &[0x20, 0xEE, (7 << 5) | 1], &[0x10, 0x9A], &[0x18, 0x00], ];
1250 for inp in inputs {
1251 let mut dec = Cea708Decoder::new();
1252 dec.push_packet(inp);
1253 }
1254 let mut dec = Cea708Decoder::new();
1256 let mut x: u32 = 0x1234_5678;
1257 let mut buf = Vec::new();
1258 for _ in 0..4096 {
1259 x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
1260 buf.push((x >> 16) as u8);
1261 }
1262 dec.push_packet(&buf);
1263 let mut dec2 = Cea708Decoder::new();
1265 let triplets: Vec<CcTriplet> = buf
1266 .chunks(2)
1267 .map(|c| CcTriplet {
1268 cc_valid: true,
1269 cc_type: CcType::Dtvcc708Data,
1270 cc_data_1: c[0],
1271 cc_data_2: *c.get(1).unwrap_or(&0),
1272 })
1273 .collect();
1274 dec2.push_triplets(&triplets);
1275 }
1276}