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 MIN_SERVICE_NUMBER: u8 = 1;
86const MAX_SERVICE_NUMBER: u8 = 63;
87const NUM_WINDOWS: usize = 8;
89const MAX_WINDOW_ROWS: usize = 12;
91const MAX_WINDOW_COLS: usize = 42;
93
94const PACKET_SIZE_ZERO_DATA: usize = 127;
97
98const EXTENDED_SERVICE_ESCAPE: u8 = 7;
101
102const C0_NUL: u8 = 0x00;
104const C0_ETX: u8 = 0x03;
105const C0_BS: u8 = 0x08;
106const C0_FF: u8 = 0x0C;
107const C0_CR: u8 = 0x0D;
108const C0_HCR: u8 = 0x0E;
109const C0_EXT1: u8 = 0x10;
110const C0_P16: u8 = 0x18;
111
112const C1_CW0: u8 = 0x80; const C1_CW7: u8 = 0x87;
115const C1_CLW: u8 = 0x88;
116const C1_DSW: u8 = 0x89;
117const C1_HDW: u8 = 0x8A;
118const C1_TGW: u8 = 0x8B;
119const C1_DLW: u8 = 0x8C;
120const C1_DLY: u8 = 0x8D;
121const C1_DLC: u8 = 0x8E;
122const C1_RST: u8 = 0x8F;
123const C1_SPA: u8 = 0x90;
124const C1_SPC: u8 = 0x91;
125const C1_SPL: u8 = 0x92;
126const C1_SWA: u8 = 0x97;
127const C1_DF0: u8 = 0x98; const C1_DF7: u8 = 0x9F;
129
130const C0_END: u8 = 0x1F;
132const G0_START: u8 = 0x20;
133const G0_END: u8 = 0x7F;
134const C1_START: u8 = 0x80;
135const C1_END: u8 = 0x9F;
136const G1_START: u8 = 0xA0;
137
138const G0_MUSIC_NOTE: u8 = 0x7F;
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143#[cfg_attr(feature = "serde", derive(serde::Serialize))]
144#[non_exhaustive]
145pub enum WindowState {
146 #[default]
148 Hidden,
149 Visible,
151}
152
153impl WindowState {
154 #[must_use]
156 pub fn name(&self) -> &'static str {
157 match self {
158 Self::Hidden => "hidden",
159 Self::Visible => "visible",
160 }
161 }
162}
163broadcast_common::impl_spec_display!(WindowState);
164
165#[derive(Debug, Clone, PartialEq, Eq)]
171#[cfg_attr(feature = "serde", derive(serde::Serialize))]
172pub struct Window {
173 pub state: WindowState,
175 pub priority: u8,
177 pub anchor_point: AnchorPoint,
179 pub anchor_vertical: u8,
181 pub anchor_horizontal: u8,
183 pub relative_position: bool,
185 pub row_count: u8,
187 pub column_count: u8,
189 pub row_lock: bool,
191 pub column_lock: bool,
193 pub window_style: u8,
195 pub pen_style: u8,
197 pub justify: Justify,
199 pub print_direction: PrintDirection,
201 pub scroll_direction: ScrollDirection,
203 pub word_wrap: bool,
205 pub fill_color: Color,
207 pub fill_opacity: Opacity,
209 pub border_color: Color,
211 pub border_type: EdgeType,
213 pub pen_size: PenSize,
215 pub pen_offset: PenOffset,
217 pub font_style: FontStyle,
219 pub italics: bool,
221 pub underline: bool,
223 pub edge_type: EdgeType,
225 pub edge_color: Color,
229 pub fg_color: Color,
231 pub fg_opacity: Opacity,
233 pub bg_color: Color,
235 pub bg_opacity: Opacity,
237 rows: Vec<String>,
239 pen_row: usize,
241 pen_col: usize,
243}
244
245impl Window {
246 fn new() -> Self {
247 Window {
248 state: WindowState::Hidden,
249 priority: 0,
250 anchor_point: AnchorPoint::TopLeft,
251 anchor_vertical: 0,
252 anchor_horizontal: 0,
253 relative_position: false,
254 row_count: 1,
255 column_count: 1,
256 row_lock: false,
257 column_lock: false,
258 window_style: 0,
259 pen_style: 0,
260 justify: Justify::Left,
261 print_direction: PrintDirection::LeftToRight,
262 scroll_direction: ScrollDirection::BottomToTop,
263 word_wrap: false,
264 fill_color: Color::BLACK,
265 fill_opacity: Opacity::Solid,
266 border_color: Color::BLACK,
267 border_type: EdgeType::None,
268 pen_size: PenSize::Standard,
269 pen_offset: PenOffset::Normal,
270 font_style: FontStyle::Default,
271 italics: false,
272 underline: false,
273 edge_type: EdgeType::None,
274 edge_color: Color::BLACK,
275 fg_color: Color::WHITE,
276 fg_opacity: Opacity::Solid,
277 bg_color: Color::BLACK,
278 bg_opacity: Opacity::Solid,
279 rows: Vec::new(),
280 pen_row: 0,
281 pen_col: 0,
282 }
283 }
284
285 fn ensure_grid(&mut self) {
286 let rows = (self.row_count as usize).clamp(1, MAX_WINDOW_ROWS);
287 if self.rows.len() != rows {
288 self.rows = alloc::vec![String::new(); rows];
289 }
290 }
291
292 fn clear_text(&mut self) {
293 for r in &mut self.rows {
294 r.clear();
295 }
296 self.pen_row = 0;
297 self.pen_col = 0;
298 }
299
300 fn cols(&self) -> usize {
301 (self.column_count as usize).clamp(1, MAX_WINDOW_COLS)
302 }
303
304 fn put_char(&mut self, ch: char) {
306 self.ensure_grid();
307 let cols = self.cols();
308 if self.pen_row >= self.rows.len() {
309 return;
310 }
311 let row = &mut self.rows[self.pen_row];
313 while row.chars().count() < self.pen_col {
314 row.push(' ');
315 }
316 if self.pen_col < cols {
317 match row.char_indices().nth(self.pen_col) {
318 Some((at, old)) => {
319 row.replace_range(at..at + old.len_utf8(), ch.encode_utf8(&mut [0; 4]))
320 }
321 None => row.push(ch),
322 }
323 self.pen_col += 1;
324 }
325 }
326
327 fn back_space(&mut self) {
329 if self.pen_col > 0 {
330 self.pen_col -= 1;
331 if self.pen_row < self.rows.len() {
332 let row = &mut self.rows[self.pen_row];
333 let mut chars: Vec<char> = row.chars().collect();
334 if self.pen_col < chars.len() {
335 chars.truncate(self.pen_col);
336 *row = chars.into_iter().collect();
337 }
338 }
339 }
340 }
341
342 fn carriage_return(&mut self) {
344 self.ensure_grid();
345 self.pen_col = 0;
346 if self.pen_row + 1 < self.rows.len() {
347 self.pen_row += 1;
348 } else if !self.rows.is_empty() {
349 self.rows.remove(0);
351 self.rows.push(String::new());
352 self.pen_row = self.rows.len() - 1;
353 }
354 }
355
356 fn horizontal_cr(&mut self) {
358 self.ensure_grid();
359 if self.pen_row < self.rows.len() {
360 self.rows[self.pen_row].clear();
361 }
362 self.pen_col = 0;
363 }
364
365 fn set_pen_location(&mut self, row: usize, col: usize) {
366 self.ensure_grid();
367 self.pen_row = row.min(self.rows.len().saturating_sub(1));
368 self.pen_col = col.min(self.cols());
369 }
370
371 #[must_use]
377 pub fn text(&self) -> String {
378 let lines: Vec<&str> = self
379 .rows
380 .iter()
381 .map(|r| r.trim_end())
382 .filter(|l| !l.is_empty())
383 .collect();
384 lines.join("\n")
385 }
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Default)]
390#[cfg_attr(feature = "serde", derive(serde::Serialize))]
391struct Service {
392 windows: [Option<Window>; NUM_WINDOWS],
393 current_window: Option<usize>,
395}
396
397impl Service {
398 fn reset(&mut self) {
399 *self = Service::default();
400 }
401
402 fn current(&mut self) -> Option<&mut Window> {
403 let id = self.current_window?;
404 self.windows.get_mut(id)?.as_mut()
405 }
406}
407
408#[derive(Debug, Clone, PartialEq, Eq)]
424#[cfg_attr(feature = "serde", derive(serde::Serialize))]
425pub struct Cea708Decoder {
426 services: [Service; NUM_SERVICES],
427 packet: Vec<u8>,
429 last_seq: Option<u8>,
431 services_seen: u64,
434}
435
436impl Default for Cea708Decoder {
437 fn default() -> Self {
438 Self::new()
439 }
440}
441
442impl Cea708Decoder {
443 #[must_use]
445 pub fn new() -> Self {
446 Cea708Decoder {
447 services: Default::default(),
448 packet: Vec::new(),
449 last_seq: None,
450 services_seen: 0,
451 }
452 }
453
454 #[must_use]
459 pub fn services_seen(&self) -> Vec<u8> {
460 (MIN_SERVICE_NUMBER..=MAX_SERVICE_NUMBER)
461 .filter(|n| self.services_seen & (1u64 << n) != 0)
462 .collect()
463 }
464
465 pub fn reset(&mut self) {
467 for s in &mut self.services {
468 s.reset();
469 }
470 self.packet.clear();
471 self.last_seq = None;
472 }
473
474 pub fn push_triplets<'a, I>(&mut self, triplets: I)
484 where
485 I: IntoIterator<Item = &'a CcTriplet>,
486 {
487 for t in triplets {
488 if !t.cc_valid {
489 continue;
490 }
491 match t.cc_type {
492 CcType::Dtvcc708Start => {
493 self.flush_packet();
497 self.packet.clear();
498 self.packet.push(t.cc_data_1);
499 self.packet.push(t.cc_data_2);
500 }
501 CcType::Dtvcc708Data => {
502 if self.packet.is_empty() {
503 continue;
509 }
510 self.packet.push(t.cc_data_1);
511 self.packet.push(t.cc_data_2);
512 }
513 _ => {}
514 }
515 }
516 if self.packet_is_complete() {
522 self.flush_packet();
523 }
524 }
525
526 pub fn push_packet(&mut self, ccp: &[u8]) {
529 self.decode_packet(ccp);
530 }
531
532 fn packet_is_complete(&self) -> bool {
536 let Some(&header) = self.packet.first() else {
537 return false;
538 };
539 let size_code = header & 0x3F;
540 let data_size = if size_code == 0 {
541 PACKET_SIZE_ZERO_DATA
542 } else {
543 (size_code as usize) * 2 - 1
544 };
545 self.packet.len() > data_size
546 }
547
548 fn flush_packet(&mut self) {
550 if self.packet.is_empty() {
551 return;
552 }
553 let packet = core::mem::take(&mut self.packet);
554 self.decode_packet(&packet);
555 }
556
557 fn decode_packet(&mut self, ccp: &[u8]) {
559 let Some((&header, rest)) = ccp.split_first() else {
560 return;
561 };
562 let seq = (header >> 6) & 0x03;
563 let size_code = header & 0x3F;
564 let data_size = if size_code == 0 {
565 PACKET_SIZE_ZERO_DATA
566 } else {
567 (size_code as usize) * 2 - 1
568 };
569 if let Some(prev) = self.last_seq
571 && seq != (prev + 1) & 0x03
572 {
573 for s in &mut self.services {
574 s.reset();
575 }
576 }
577 self.last_seq = Some(seq);
578 let end = data_size.min(rest.len());
579 self.decode_service_blocks(&rest[..end]);
580 }
581
582 fn decode_service_blocks(&mut self, mut data: &[u8]) {
584 loop {
585 let Some((&header, rest)) = data.split_first() else {
586 return;
587 };
588 if header == 0 {
590 return;
591 }
592 let mut service_number = u16::from((header >> 5) & 0x07);
593 let block_size = (header & 0x1F) as usize;
594 let mut body = rest;
595 if service_number == u16::from(EXTENDED_SERVICE_ESCAPE) && block_size != 0 {
596 let Some((&ext, after)) = rest.split_first() else {
598 return;
599 };
600 service_number = u16::from(ext & 0x3F);
601 body = after;
602 }
603 if block_size > body.len() {
604 self.dispatch_service(service_number, body);
606 return;
607 }
608 let (block, next) = body.split_at(block_size);
609 self.dispatch_service(service_number, block);
610 data = next;
611 }
612 }
613
614 fn dispatch_service(&mut self, service_number: u16, block: &[u8]) {
615 if (u16::from(MIN_SERVICE_NUMBER)..=u16::from(MAX_SERVICE_NUMBER)).contains(&service_number)
616 && block.iter().any(|&b| b != 0)
617 {
618 self.services_seen |= 1u64 << service_number;
619 }
620 if service_number == 0 || service_number as usize > NUM_SERVICES {
622 return;
623 }
624 let idx = service_number as usize - 1;
625 Self::interpret(&mut self.services[idx], block);
626 }
627
628 fn interpret(service: &mut Service, block: &[u8]) {
630 let mut i = 0usize;
631 while i < block.len() {
632 let b = block[i];
633 let consumed = match b {
634 0x00..=C0_END => Self::handle_c0(service, &block[i..]),
635 G0_START..=G0_END => {
636 Self::put(service, Self::g0_char(b));
637 1
638 }
639 C1_START..=C1_END => Self::handle_c1(service, &block[i..]),
640 G1_START..=0xFF => {
641 Self::put(service, char::from(b));
643 1
644 }
645 };
646 i += consumed.max(1);
647 }
648 }
649
650 fn handle_c0(service: &mut Service, data: &[u8]) -> usize {
652 let b = data[0];
653 match b {
654 C0_NUL => 1,
655 C0_ETX => 1,
656 C0_BS if let Some(w) = service.current() => {
660 w.back_space();
661 1
662 }
663 C0_FF if let Some(w) = service.current() => {
664 w.clear_text();
665 1
666 }
667 C0_CR if let Some(w) = service.current() => {
668 w.carriage_return();
669 1
670 }
671 C0_HCR if let Some(w) = service.current() => {
672 w.horizontal_cr();
673 1
674 }
675 C0_EXT1 => Self::handle_ext1(service, data),
676 C0_P16 => 3, 0x11..=0x17 => 2,
680 0x19..=0x1F => 3,
681 _ => 1,
682 }
683 }
684
685 fn handle_ext1(service: &mut Service, data: &[u8]) -> usize {
688 let Some(&base) = data.get(1) else {
689 return 1;
690 };
691 match base {
692 0x00..=0x07 => 2,
694 0x08..=0x0F => 3,
695 0x10..=0x17 => 4,
696 0x18..=0x1F => 5,
697 0x20..=0x7F => {
699 Self::put(service, Self::g2_char(base));
700 2
701 }
702 0x80..=0x87 => 6,
704 0x88..=0x8F => 7,
705 0x90..=0x9F => {
706 let n = data.get(2).map_or(0, |d| (d & 0x3F) as usize + 1);
708 3 + n
709 }
710 _ => {
712 Self::put(service, Self::g3_char(base));
713 2
714 }
715 }
716 }
717
718 fn handle_c1(service: &mut Service, data: &[u8]) -> usize {
720 let op = data[0];
721 match op {
722 C1_CW0..=C1_CW7 => {
723 let id = (op - C1_CW0) as usize;
724 if service.windows.get(id).and_then(|w| w.as_ref()).is_some() {
725 service.current_window = Some(id);
726 }
727 1
728 }
729 C1_CLW => Self::window_map_cmd(service, data, WindowMapOp::Clear),
730 C1_DSW => Self::window_map_cmd(service, data, WindowMapOp::Display),
731 C1_HDW => Self::window_map_cmd(service, data, WindowMapOp::Hide),
732 C1_TGW => Self::window_map_cmd(service, data, WindowMapOp::Toggle),
733 C1_DLW => Self::window_map_cmd(service, data, WindowMapOp::Delete),
734 C1_DLY => 2, C1_DLC => 1, C1_RST => {
737 service.reset();
738 1
739 }
740 C1_SPA => Self::set_pen_attributes(service, data),
741 C1_SPC => Self::set_pen_color(service, data),
742 C1_SPL => Self::set_pen_location(service, data),
743 C1_SWA => Self::set_window_attributes(service, data),
744 C1_DF0..=C1_DF7 => Self::define_window(service, data),
745 _ => 1,
747 }
748 }
749
750 fn window_map_cmd(service: &mut Service, data: &[u8], op: WindowMapOp) -> usize {
751 let Some(&map) = data.get(1) else {
752 return 1;
753 };
754 for id in 0..NUM_WINDOWS {
755 if map & (1 << id) == 0 {
756 continue;
757 }
758 match op {
759 WindowMapOp::Clear if let Some(w) = service.windows[id].as_mut() => {
760 w.clear_text();
761 }
762 WindowMapOp::Clear => {}
763 WindowMapOp::Display if let Some(w) = service.windows[id].as_mut() => {
764 w.state = WindowState::Visible;
765 }
766 WindowMapOp::Display => {}
767 WindowMapOp::Hide if let Some(w) = service.windows[id].as_mut() => {
768 w.state = WindowState::Hidden;
769 }
770 WindowMapOp::Hide => {}
771 WindowMapOp::Toggle if let Some(w) = service.windows[id].as_mut() => {
772 w.state = match w.state {
773 WindowState::Visible => WindowState::Hidden,
774 WindowState::Hidden => WindowState::Visible,
775 };
776 }
777 WindowMapOp::Toggle => {}
778 WindowMapOp::Delete => {
779 service.windows[id] = None;
780 if service.current_window == Some(id) {
781 service.current_window = None;
782 }
783 }
784 }
785 }
786 2
787 }
788
789 fn define_window(service: &mut Service, data: &[u8]) -> usize {
791 const TOTAL: usize = 7;
792 if data.len() < TOTAL {
793 return data.len().max(1);
794 }
795 let id = (data[0] - C1_DF0) as usize;
796 let p1 = data[1];
797 let p2 = data[2];
798 let p3 = data[3];
799 let p4 = data[4];
800 let p5 = data[5];
801 let p6 = data[6];
802
803 let creating = service.windows[id].is_none();
804 let w = service.windows[id].get_or_insert_with(Window::new);
805
806 w.priority = p1 & 0x07;
807 w.column_lock = (p1 >> 3) & 0x01 != 0;
808 w.row_lock = (p1 >> 4) & 0x01 != 0;
809 w.state = if (p1 >> 5) & 0x01 != 0 {
810 WindowState::Visible
811 } else {
812 WindowState::Hidden
813 };
814 w.relative_position = (p2 >> 7) & 0x01 != 0;
815 w.anchor_vertical = p2 & 0x7F;
816 w.anchor_horizontal = p3;
817 w.anchor_point = AnchorPoint::from_bits((p4 >> 4) & 0x0F);
818 w.row_count = (p4 & 0x0F) + 1;
819 w.column_count = (p5 & 0x3F) + 1;
820 w.window_style = (p6 >> 3) & 0x07;
821 w.pen_style = p6 & 0x07;
822
823 if creating {
824 apply_window_style(
826 w,
827 if w.window_style == 0 {
828 1
829 } else {
830 w.window_style
831 },
832 );
833 apply_pen_style(w, if w.pen_style == 0 { 1 } else { w.pen_style });
834 w.ensure_grid();
835 w.clear_text();
836 } else {
837 if w.window_style != 0 {
839 apply_window_style(w, w.window_style);
840 }
841 if w.pen_style != 0 {
842 apply_pen_style(w, w.pen_style);
843 }
844 w.ensure_grid();
845 }
846 service.current_window = Some(id);
847 TOTAL
848 }
849
850 fn set_window_attributes(service: &mut Service, data: &[u8]) -> usize {
852 const TOTAL: usize = 5;
853 if data.len() < TOTAL {
854 return data.len().max(1);
855 }
856 let p1 = data[1];
857 let p2 = data[2];
858 let p3 = data[3];
859 let p4 = data[4];
860 if let Some(w) = service.current() {
861 w.fill_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
862 w.fill_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
863 let bt_lo = (p2 >> 6) & 0x03;
864 w.border_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
865 let bt_hi = (p3 >> 7) & 0x01;
866 w.border_type = EdgeType::from_bits((bt_hi << 2) | bt_lo);
867 w.word_wrap = (p3 >> 6) & 0x01 != 0;
868 w.print_direction = PrintDirection::from_bits((p3 >> 4) & 0x03);
869 w.scroll_direction = ScrollDirection::from_bits((p3 >> 2) & 0x03);
870 w.justify = Justify::from_bits(p3 & 0x03);
871 let _ = p4;
873 }
874 TOTAL
875 }
876
877 fn set_pen_attributes(service: &mut Service, data: &[u8]) -> usize {
879 const TOTAL: usize = 3;
880 if data.len() < TOTAL {
881 return data.len().max(1);
882 }
883 let p1 = data[1];
884 let p2 = data[2];
885 if let Some(w) = service.current() {
886 w.pen_offset = PenOffset::from_bits((p1 >> 2) & 0x03);
887 w.pen_size = PenSize::from_bits(p1 & 0x03);
888 w.italics = (p2 >> 7) & 0x01 != 0;
889 w.underline = (p2 >> 6) & 0x01 != 0;
890 w.edge_type = EdgeType::from_bits((p2 >> 3) & 0x07);
891 w.font_style = FontStyle::from_bits(p2 & 0x07);
892 }
893 TOTAL
894 }
895
896 fn set_pen_color(service: &mut Service, data: &[u8]) -> usize {
898 const TOTAL: usize = 4;
899 if data.len() < TOTAL {
900 return data.len().max(1);
901 }
902 let p1 = data[1];
903 let p2 = data[2];
904 let p3 = data[3];
905 if let Some(w) = service.current() {
906 w.fg_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
907 w.fg_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
908 w.bg_opacity = Opacity::from_bits((p2 >> 6) & 0x03);
909 w.bg_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
910 w.edge_color = Color::new((p3 >> 4) & 0x03, (p3 >> 2) & 0x03, p3 & 0x03);
912 }
913 TOTAL
914 }
915
916 fn set_pen_location(service: &mut Service, data: &[u8]) -> usize {
918 const TOTAL: usize = 3;
919 if data.len() < TOTAL {
920 return data.len().max(1);
921 }
922 let row = (data[1] & 0x0F) as usize;
923 let col = (data[2] & 0x3F) as usize;
924 if let Some(w) = service.current() {
925 w.set_pen_location(row, col);
926 }
927 TOTAL
928 }
929
930 fn put(service: &mut Service, ch: char) {
931 if let Some(w) = service.current() {
932 w.put_char(ch);
933 }
934 }
935
936 fn g0_char(b: u8) -> char {
938 if b == G0_MUSIC_NOTE {
939 '\u{266A}'
940 } else {
941 char::from(b)
942 }
943 }
944
945 fn g2_char(b: u8) -> char {
947 match b {
948 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}', _ => '_', }
969 }
970
971 fn g3_char(b: u8) -> char {
973 if b == 0xA0 {
974 '\u{1F4FA}' } else {
976 '_'
977 }
978 }
979
980 #[must_use]
983 pub fn windows(&self, service_number: usize) -> &[Option<Window>; NUM_WINDOWS] {
984 const EMPTY: [Option<Window>; NUM_WINDOWS] =
985 [None, None, None, None, None, None, None, None];
986 if service_number == 0 || service_number > NUM_SERVICES {
987 return &EMPTY;
988 }
989 &self.services[service_number - 1].windows
990 }
991
992 #[must_use]
995 pub fn service_text(&self, service_number: usize) -> String {
996 if service_number == 0 || service_number > NUM_SERVICES {
997 return String::new();
998 }
999 let svc = &self.services[service_number - 1];
1000 let mut idxs: Vec<usize> = (0..NUM_WINDOWS)
1001 .filter(|&i| {
1002 svc.windows[i]
1003 .as_ref()
1004 .is_some_and(|w| w.state == WindowState::Visible)
1005 })
1006 .collect();
1007 idxs.sort_by_key(|&i| {
1008 svc.windows[i]
1009 .as_ref()
1010 .map_or((u8::MAX, i), |w| (w.priority, i))
1011 });
1012 let mut out = String::new();
1013 for i in idxs {
1014 if let Some(w) = svc.windows[i].as_ref() {
1015 let t = w.text();
1016 if t.is_empty() {
1017 continue;
1018 }
1019 if !out.is_empty() {
1020 out.push('\n');
1021 }
1022 out.push_str(&t);
1023 }
1024 }
1025 out
1026 }
1027}
1028
1029#[derive(Clone, Copy)]
1031enum WindowMapOp {
1032 Clear,
1033 Display,
1034 Hide,
1035 Toggle,
1036 Delete,
1037}
1038
1039fn apply_window_style(w: &mut Window, id: u8) {
1041 w.border_type = EdgeType::None;
1044 match id {
1045 1 => style(w, Justify::Left, false, Some(Color::BLACK), Opacity::Solid),
1046 2 => style(w, Justify::Left, false, None, Opacity::Transparent),
1047 3 => style(
1048 w,
1049 Justify::Center,
1050 false,
1051 Some(Color::BLACK),
1052 Opacity::Solid,
1053 ),
1054 4 => style(w, Justify::Left, true, Some(Color::BLACK), Opacity::Solid),
1055 5 => style(w, Justify::Left, true, None, Opacity::Transparent),
1056 6 => style(w, Justify::Center, true, Some(Color::BLACK), Opacity::Solid),
1057 7 => {
1058 w.justify = Justify::Left;
1059 w.word_wrap = false;
1060 w.print_direction = PrintDirection::TopToBottom;
1061 w.scroll_direction = ScrollDirection::RightToLeft;
1062 w.fill_color = Color::BLACK;
1063 w.fill_opacity = Opacity::Solid;
1064 }
1065 _ => {}
1066 }
1067}
1068
1069fn style(w: &mut Window, j: Justify, ww: bool, fill: Option<Color>, op: Opacity) {
1070 w.justify = j;
1071 w.word_wrap = ww;
1072 w.print_direction = PrintDirection::LeftToRight;
1073 w.scroll_direction = ScrollDirection::BottomToTop;
1074 w.fill_opacity = op;
1075 if let Some(c) = fill {
1076 w.fill_color = c;
1077 }
1078}
1079
1080fn apply_pen_style(w: &mut Window, id: u8) {
1082 w.pen_size = PenSize::Standard;
1083 w.pen_offset = PenOffset::Normal;
1084 w.italics = false;
1085 w.underline = false;
1086 w.fg_color = Color::WHITE;
1087 w.fg_opacity = Opacity::Solid;
1088 match id {
1089 1 => pen(
1090 w,
1091 FontStyle::Default,
1092 EdgeType::None,
1093 Color::BLACK,
1094 Opacity::Solid,
1095 ),
1096 2 => pen(
1097 w,
1098 FontStyle::MonospacedSerif,
1099 EdgeType::None,
1100 Color::BLACK,
1101 Opacity::Solid,
1102 ),
1103 3 => pen(
1104 w,
1105 FontStyle::ProportionalSerif,
1106 EdgeType::None,
1107 Color::BLACK,
1108 Opacity::Solid,
1109 ),
1110 4 => pen(
1111 w,
1112 FontStyle::MonospacedSansSerif,
1113 EdgeType::None,
1114 Color::BLACK,
1115 Opacity::Solid,
1116 ),
1117 5 => pen(
1118 w,
1119 FontStyle::ProportionalSansSerif,
1120 EdgeType::None,
1121 Color::BLACK,
1122 Opacity::Solid,
1123 ),
1124 6 => pen(
1125 w,
1126 FontStyle::MonospacedSansSerif,
1127 EdgeType::Uniform,
1128 Color::BLACK,
1129 Opacity::Transparent,
1130 ),
1131 7 => pen(
1132 w,
1133 FontStyle::ProportionalSansSerif,
1134 EdgeType::Uniform,
1135 Color::BLACK,
1136 Opacity::Transparent,
1137 ),
1138 _ => {}
1139 }
1140}
1141
1142fn pen(w: &mut Window, font: FontStyle, edge: EdgeType, bg: Color, bg_op: Opacity) {
1143 w.font_style = font;
1144 w.edge_type = edge;
1145 w.bg_color = bg;
1146 w.bg_opacity = bg_op;
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151 use super::*;
1152
1153 fn ccp(svc: u8, cmds: &[u8]) -> Vec<u8> {
1155 let mut sb = alloc::vec![(svc << 5) | (cmds.len() as u8)];
1156 sb.extend_from_slice(cmds);
1157 let size_code = (sb.len().div_ceil(2) + 1) as u8 & 0x3F;
1159 let mut packet = alloc::vec![size_code];
1160 packet.extend_from_slice(&sb);
1161 packet
1162 }
1163
1164 #[test]
1169 fn define_window_worked_example() {
1170 let mut dec = Cea708Decoder::new();
1171 let packet = ccp(1, &[0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11]);
1172 dec.push_packet(&packet);
1173 let w = dec.windows(1)[2].as_ref().expect("window 2 defined");
1174 assert_eq!(w.state, WindowState::Visible);
1175 assert!(w.row_lock);
1176 assert!(w.column_lock);
1177 assert_eq!(w.priority, 0);
1178 assert!(!w.relative_position);
1179 assert_eq!(w.anchor_vertical, 74);
1180 assert_eq!(w.anchor_horizontal, 209);
1181 assert_eq!(w.anchor_point, AnchorPoint::BottomRight);
1182 assert_eq!(w.row_count, 12);
1183 assert_eq!(w.column_count, 16);
1184 assert_eq!(w.window_style, 2);
1185 assert_eq!(w.pen_style, 1);
1186 }
1187
1188 #[test]
1191 fn swa_border_type_split() {
1192 let mut dec = Cea708Decoder::new();
1193 let packet = ccp(
1195 1,
1196 &[
1197 0x98, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x64, 0x53, 0x88, 0x22, ],
1200 );
1201 dec.push_packet(&packet);
1202 let w = dec.windows(1)[0].as_ref().expect("window 0");
1203 assert_eq!(w.border_type, EdgeType::RightDropShadow);
1204 }
1205
1206 #[test]
1208 fn decode_text() {
1209 let mut dec = Cea708Decoder::new();
1210 let packet = ccp(
1211 1,
1212 &[
1213 0x98, 0x20, 0x00, 0x00, 0x02, 0x0F, 0x00, b'H', b'i',
1215 ],
1216 );
1217 dec.push_packet(&packet);
1218 assert_eq!(dec.service_text(1), "Hi");
1219 }
1220
1221 #[test]
1223 fn two_services_multi_window() {
1224 let mut dec = Cea708Decoder::new();
1225 let s1_block = [0x98, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'1'];
1227 let s2_block = [0x99, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'2'];
1229 let mut data = Vec::new();
1230 data.push((1 << 5) | (s1_block.len() as u8));
1231 data.extend_from_slice(&s1_block);
1232 data.push((2 << 5) | (s2_block.len() as u8));
1233 data.extend_from_slice(&s2_block);
1234 let size_code = (data.len().div_ceil(2) + 1) as u8 & 0x3F;
1235 let mut packet = alloc::vec![size_code];
1236 packet.extend_from_slice(&data);
1237 dec.push_packet(&packet);
1238 assert_eq!(dec.service_text(1), "S1");
1239 assert_eq!(dec.service_text(2), "S2");
1240 assert!(dec.windows(1)[0].is_some());
1241 assert!(dec.windows(2)[1].is_some());
1242 }
1243
1244 #[test]
1245 fn services_seen_covers_unmodelled_and_extended_services() {
1246 let mut dec = Cea708Decoder::new();
1247 dec.push_packet(&ccp(1, b"A"));
1248 dec.push_packet(&ccp(2, &[0x00, 0x00]));
1249 let extended = [(7 << 5) | 1, 63, b'Z'];
1250 let size_code = (extended.len().div_ceil(2) + 1) as u8 & 0x3F;
1251 let mut packet = alloc::vec![size_code];
1252 packet.extend_from_slice(&extended);
1253 dec.push_packet(&packet);
1254 assert_eq!(dec.services_seen(), alloc::vec![1, 63]);
1255 }
1256
1257 #[test]
1258 fn carriage_return_rolls_up() {
1259 let mut w = Window::new();
1260 w.row_count = 2;
1261 w.column_count = 10;
1262 w.ensure_grid();
1263 w.put_char('A');
1264 w.carriage_return();
1265 w.put_char('B');
1266 w.carriage_return(); w.put_char('C');
1268 assert_eq!(w.text(), "B\nC");
1269 }
1270
1271 #[test]
1272 fn g0_music_note() {
1273 assert_eq!(Cea708Decoder::g0_char(0x7F), '\u{266A}');
1274 assert_eq!(Cea708Decoder::g0_char(b'A'), 'A');
1275 }
1276
1277 #[test]
1278 fn no_panic_on_arbitrary_input() {
1279 let inputs: &[&[u8]] = &[
1281 &[],
1282 &[0x00],
1283 &[0xFF],
1284 &[0x01, 0x98], &[0x3F, 0x80, 0x90, 0x91, 0x92, 0x97, 0x98], &[0x20, 0xEE, (7 << 5) | 1], &[0x10, 0x9A], &[0x18, 0x00], ];
1290 for inp in inputs {
1291 let mut dec = Cea708Decoder::new();
1292 dec.push_packet(inp);
1293 }
1294 let mut dec = Cea708Decoder::new();
1296 let mut x: u32 = 0x1234_5678;
1297 let mut buf = Vec::new();
1298 for _ in 0..4096 {
1299 x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
1300 buf.push((x >> 16) as u8);
1301 }
1302 dec.push_packet(&buf);
1303 let mut dec2 = Cea708Decoder::new();
1305 let triplets: Vec<CcTriplet> = buf
1306 .chunks(2)
1307 .map(|c| CcTriplet {
1308 cc_valid: true,
1309 cc_type: CcType::Dtvcc708Data,
1310 cc_data_1: c[0],
1311 cc_data_2: *c.get(1).unwrap_or(&0),
1312 })
1313 .collect();
1314 dec2.push_triplets(&triplets);
1315 }
1316
1317 #[test]
1318 fn set_pen_location_back_over_existing_text_overwrites() {
1319 let mut d = Cea708Decoder::new();
1320 d.push_packet(&[0x05, 0x27, 0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11, 0x00]);
1321 d.push_packet(&[0x45, 0x26, b'A', b'B', b'C', 0x92, 0x00, 0x00, 0x00, 0x00]);
1322 d.push_packet(&[0x82, 0x22, b'X', 0x00]);
1323 let w = d.windows(1)[2].as_ref().unwrap();
1324 assert_eq!(w.text(), "XBC");
1325 }
1326}