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 row.push(ch);
318 self.pen_col += 1;
319 }
320 }
321
322 fn back_space(&mut self) {
324 if self.pen_col > 0 {
325 self.pen_col -= 1;
326 if self.pen_row < self.rows.len() {
327 let row = &mut self.rows[self.pen_row];
328 let mut chars: Vec<char> = row.chars().collect();
329 if self.pen_col < chars.len() {
330 chars.truncate(self.pen_col);
331 *row = chars.into_iter().collect();
332 }
333 }
334 }
335 }
336
337 fn carriage_return(&mut self) {
339 self.ensure_grid();
340 self.pen_col = 0;
341 if self.pen_row + 1 < self.rows.len() {
342 self.pen_row += 1;
343 } else if !self.rows.is_empty() {
344 self.rows.remove(0);
346 self.rows.push(String::new());
347 self.pen_row = self.rows.len() - 1;
348 }
349 }
350
351 fn horizontal_cr(&mut self) {
353 self.ensure_grid();
354 if self.pen_row < self.rows.len() {
355 self.rows[self.pen_row].clear();
356 }
357 self.pen_col = 0;
358 }
359
360 fn set_pen_location(&mut self, row: usize, col: usize) {
361 self.ensure_grid();
362 self.pen_row = row.min(self.rows.len().saturating_sub(1));
363 self.pen_col = col.min(self.cols());
364 }
365
366 #[must_use]
372 pub fn text(&self) -> String {
373 let lines: Vec<&str> = self
374 .rows
375 .iter()
376 .map(|r| r.trim_end())
377 .filter(|l| !l.is_empty())
378 .collect();
379 lines.join("\n")
380 }
381}
382
383#[derive(Debug, Clone, PartialEq, Eq, Default)]
385#[cfg_attr(feature = "serde", derive(serde::Serialize))]
386struct Service {
387 windows: [Option<Window>; NUM_WINDOWS],
388 current_window: Option<usize>,
390}
391
392impl Service {
393 fn reset(&mut self) {
394 *self = Service::default();
395 }
396
397 fn current(&mut self) -> Option<&mut Window> {
398 let id = self.current_window?;
399 self.windows.get_mut(id)?.as_mut()
400 }
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
419#[cfg_attr(feature = "serde", derive(serde::Serialize))]
420pub struct Cea708Decoder {
421 services: [Service; NUM_SERVICES],
422 packet: Vec<u8>,
424 last_seq: Option<u8>,
426 services_seen: u64,
429}
430
431impl Default for Cea708Decoder {
432 fn default() -> Self {
433 Self::new()
434 }
435}
436
437impl Cea708Decoder {
438 #[must_use]
440 pub fn new() -> Self {
441 Cea708Decoder {
442 services: Default::default(),
443 packet: Vec::new(),
444 last_seq: None,
445 services_seen: 0,
446 }
447 }
448
449 #[must_use]
454 pub fn services_seen(&self) -> Vec<u8> {
455 (MIN_SERVICE_NUMBER..=MAX_SERVICE_NUMBER)
456 .filter(|n| self.services_seen & (1u64 << n) != 0)
457 .collect()
458 }
459
460 pub fn reset(&mut self) {
462 for s in &mut self.services {
463 s.reset();
464 }
465 self.packet.clear();
466 self.last_seq = None;
467 }
468
469 pub fn push_triplets<'a, I>(&mut self, triplets: I)
479 where
480 I: IntoIterator<Item = &'a CcTriplet>,
481 {
482 for t in triplets {
483 if !t.cc_valid {
484 continue;
485 }
486 match t.cc_type {
487 CcType::Dtvcc708Start => {
488 self.flush_packet();
492 self.packet.clear();
493 self.packet.push(t.cc_data_1);
494 self.packet.push(t.cc_data_2);
495 }
496 CcType::Dtvcc708Data => {
497 if self.packet.is_empty() {
498 continue;
504 }
505 self.packet.push(t.cc_data_1);
506 self.packet.push(t.cc_data_2);
507 }
508 _ => {}
509 }
510 }
511 if self.packet_is_complete() {
517 self.flush_packet();
518 }
519 }
520
521 pub fn push_packet(&mut self, ccp: &[u8]) {
524 self.decode_packet(ccp);
525 }
526
527 fn packet_is_complete(&self) -> bool {
531 let Some(&header) = self.packet.first() else {
532 return false;
533 };
534 let size_code = header & 0x3F;
535 let data_size = if size_code == 0 {
536 PACKET_SIZE_ZERO_DATA
537 } else {
538 (size_code as usize) * 2 - 1
539 };
540 self.packet.len() > data_size
541 }
542
543 fn flush_packet(&mut self) {
545 if self.packet.is_empty() {
546 return;
547 }
548 let packet = core::mem::take(&mut self.packet);
549 self.decode_packet(&packet);
550 }
551
552 fn decode_packet(&mut self, ccp: &[u8]) {
554 let Some((&header, rest)) = ccp.split_first() else {
555 return;
556 };
557 let seq = (header >> 6) & 0x03;
558 let size_code = header & 0x3F;
559 let data_size = if size_code == 0 {
560 PACKET_SIZE_ZERO_DATA
561 } else {
562 (size_code as usize) * 2 - 1
563 };
564 if let Some(prev) = self.last_seq
566 && seq != (prev + 1) & 0x03
567 {
568 for s in &mut self.services {
569 s.reset();
570 }
571 }
572 self.last_seq = Some(seq);
573 let end = data_size.min(rest.len());
574 self.decode_service_blocks(&rest[..end]);
575 }
576
577 fn decode_service_blocks(&mut self, mut data: &[u8]) {
579 loop {
580 let Some((&header, rest)) = data.split_first() else {
581 return;
582 };
583 if header == 0 {
585 return;
586 }
587 let mut service_number = u16::from((header >> 5) & 0x07);
588 let block_size = (header & 0x1F) as usize;
589 let mut body = rest;
590 if service_number == u16::from(EXTENDED_SERVICE_ESCAPE) && block_size != 0 {
591 let Some((&ext, after)) = rest.split_first() else {
593 return;
594 };
595 service_number = u16::from(ext & 0x3F);
596 body = after;
597 }
598 if block_size > body.len() {
599 self.dispatch_service(service_number, body);
601 return;
602 }
603 let (block, next) = body.split_at(block_size);
604 self.dispatch_service(service_number, block);
605 data = next;
606 }
607 }
608
609 fn dispatch_service(&mut self, service_number: u16, block: &[u8]) {
610 if (u16::from(MIN_SERVICE_NUMBER)..=u16::from(MAX_SERVICE_NUMBER)).contains(&service_number)
611 && block.iter().any(|&b| b != 0)
612 {
613 self.services_seen |= 1u64 << service_number;
614 }
615 if service_number == 0 || service_number as usize > NUM_SERVICES {
617 return;
618 }
619 let idx = service_number as usize - 1;
620 Self::interpret(&mut self.services[idx], block);
621 }
622
623 fn interpret(service: &mut Service, block: &[u8]) {
625 let mut i = 0usize;
626 while i < block.len() {
627 let b = block[i];
628 let consumed = match b {
629 0x00..=C0_END => Self::handle_c0(service, &block[i..]),
630 G0_START..=G0_END => {
631 Self::put(service, Self::g0_char(b));
632 1
633 }
634 C1_START..=C1_END => Self::handle_c1(service, &block[i..]),
635 G1_START..=0xFF => {
636 Self::put(service, char::from(b));
638 1
639 }
640 };
641 i += consumed.max(1);
642 }
643 }
644
645 fn handle_c0(service: &mut Service, data: &[u8]) -> usize {
647 let b = data[0];
648 match b {
649 C0_NUL => 1,
650 C0_ETX => 1,
651 C0_BS if let Some(w) = service.current() => {
655 w.back_space();
656 1
657 }
658 C0_FF if let Some(w) = service.current() => {
659 w.clear_text();
660 1
661 }
662 C0_CR if let Some(w) = service.current() => {
663 w.carriage_return();
664 1
665 }
666 C0_HCR if let Some(w) = service.current() => {
667 w.horizontal_cr();
668 1
669 }
670 C0_EXT1 => Self::handle_ext1(service, data),
671 C0_P16 => 3, 0x11..=0x17 => 2,
675 0x19..=0x1F => 3,
676 _ => 1,
677 }
678 }
679
680 fn handle_ext1(service: &mut Service, data: &[u8]) -> usize {
683 let Some(&base) = data.get(1) else {
684 return 1;
685 };
686 match base {
687 0x00..=0x07 => 2,
689 0x08..=0x0F => 3,
690 0x10..=0x17 => 4,
691 0x18..=0x1F => 5,
692 0x20..=0x7F => {
694 Self::put(service, Self::g2_char(base));
695 2
696 }
697 0x80..=0x87 => 6,
699 0x88..=0x8F => 7,
700 0x90..=0x9F => {
701 let n = data.get(2).map_or(0, |d| (d & 0x3F) as usize + 1);
703 3 + n
704 }
705 _ => {
707 Self::put(service, Self::g3_char(base));
708 2
709 }
710 }
711 }
712
713 fn handle_c1(service: &mut Service, data: &[u8]) -> usize {
715 let op = data[0];
716 match op {
717 C1_CW0..=C1_CW7 => {
718 let id = (op - C1_CW0) as usize;
719 if service.windows.get(id).and_then(|w| w.as_ref()).is_some() {
720 service.current_window = Some(id);
721 }
722 1
723 }
724 C1_CLW => Self::window_map_cmd(service, data, WindowMapOp::Clear),
725 C1_DSW => Self::window_map_cmd(service, data, WindowMapOp::Display),
726 C1_HDW => Self::window_map_cmd(service, data, WindowMapOp::Hide),
727 C1_TGW => Self::window_map_cmd(service, data, WindowMapOp::Toggle),
728 C1_DLW => Self::window_map_cmd(service, data, WindowMapOp::Delete),
729 C1_DLY => 2, C1_DLC => 1, C1_RST => {
732 service.reset();
733 1
734 }
735 C1_SPA => Self::set_pen_attributes(service, data),
736 C1_SPC => Self::set_pen_color(service, data),
737 C1_SPL => Self::set_pen_location(service, data),
738 C1_SWA => Self::set_window_attributes(service, data),
739 C1_DF0..=C1_DF7 => Self::define_window(service, data),
740 _ => 1,
742 }
743 }
744
745 fn window_map_cmd(service: &mut Service, data: &[u8], op: WindowMapOp) -> usize {
746 let Some(&map) = data.get(1) else {
747 return 1;
748 };
749 for id in 0..NUM_WINDOWS {
750 if map & (1 << id) == 0 {
751 continue;
752 }
753 match op {
754 WindowMapOp::Clear if let Some(w) = service.windows[id].as_mut() => {
755 w.clear_text();
756 }
757 WindowMapOp::Clear => {}
758 WindowMapOp::Display if let Some(w) = service.windows[id].as_mut() => {
759 w.state = WindowState::Visible;
760 }
761 WindowMapOp::Display => {}
762 WindowMapOp::Hide if let Some(w) = service.windows[id].as_mut() => {
763 w.state = WindowState::Hidden;
764 }
765 WindowMapOp::Hide => {}
766 WindowMapOp::Toggle if let Some(w) = service.windows[id].as_mut() => {
767 w.state = match w.state {
768 WindowState::Visible => WindowState::Hidden,
769 WindowState::Hidden => WindowState::Visible,
770 };
771 }
772 WindowMapOp::Toggle => {}
773 WindowMapOp::Delete => {
774 service.windows[id] = None;
775 if service.current_window == Some(id) {
776 service.current_window = None;
777 }
778 }
779 }
780 }
781 2
782 }
783
784 fn define_window(service: &mut Service, data: &[u8]) -> usize {
786 const TOTAL: usize = 7;
787 if data.len() < TOTAL {
788 return data.len().max(1);
789 }
790 let id = (data[0] - C1_DF0) as usize;
791 let p1 = data[1];
792 let p2 = data[2];
793 let p3 = data[3];
794 let p4 = data[4];
795 let p5 = data[5];
796 let p6 = data[6];
797
798 let creating = service.windows[id].is_none();
799 let w = service.windows[id].get_or_insert_with(Window::new);
800
801 w.priority = p1 & 0x07;
802 w.column_lock = (p1 >> 3) & 0x01 != 0;
803 w.row_lock = (p1 >> 4) & 0x01 != 0;
804 w.state = if (p1 >> 5) & 0x01 != 0 {
805 WindowState::Visible
806 } else {
807 WindowState::Hidden
808 };
809 w.relative_position = (p2 >> 7) & 0x01 != 0;
810 w.anchor_vertical = p2 & 0x7F;
811 w.anchor_horizontal = p3;
812 w.anchor_point = AnchorPoint::from_bits((p4 >> 4) & 0x0F);
813 w.row_count = (p4 & 0x0F) + 1;
814 w.column_count = (p5 & 0x3F) + 1;
815 w.window_style = (p6 >> 3) & 0x07;
816 w.pen_style = p6 & 0x07;
817
818 if creating {
819 apply_window_style(
821 w,
822 if w.window_style == 0 {
823 1
824 } else {
825 w.window_style
826 },
827 );
828 apply_pen_style(w, if w.pen_style == 0 { 1 } else { w.pen_style });
829 w.ensure_grid();
830 w.clear_text();
831 } else {
832 if w.window_style != 0 {
834 apply_window_style(w, w.window_style);
835 }
836 if w.pen_style != 0 {
837 apply_pen_style(w, w.pen_style);
838 }
839 w.ensure_grid();
840 }
841 service.current_window = Some(id);
842 TOTAL
843 }
844
845 fn set_window_attributes(service: &mut Service, data: &[u8]) -> usize {
847 const TOTAL: usize = 5;
848 if data.len() < TOTAL {
849 return data.len().max(1);
850 }
851 let p1 = data[1];
852 let p2 = data[2];
853 let p3 = data[3];
854 let p4 = data[4];
855 if let Some(w) = service.current() {
856 w.fill_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
857 w.fill_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
858 let bt_lo = (p2 >> 6) & 0x03;
859 w.border_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
860 let bt_hi = (p3 >> 7) & 0x01;
861 w.border_type = EdgeType::from_bits((bt_hi << 2) | bt_lo);
862 w.word_wrap = (p3 >> 6) & 0x01 != 0;
863 w.print_direction = PrintDirection::from_bits((p3 >> 4) & 0x03);
864 w.scroll_direction = ScrollDirection::from_bits((p3 >> 2) & 0x03);
865 w.justify = Justify::from_bits(p3 & 0x03);
866 let _ = p4;
868 }
869 TOTAL
870 }
871
872 fn set_pen_attributes(service: &mut Service, data: &[u8]) -> usize {
874 const TOTAL: usize = 3;
875 if data.len() < TOTAL {
876 return data.len().max(1);
877 }
878 let p1 = data[1];
879 let p2 = data[2];
880 if let Some(w) = service.current() {
881 w.pen_offset = PenOffset::from_bits((p1 >> 2) & 0x03);
882 w.pen_size = PenSize::from_bits(p1 & 0x03);
883 w.italics = (p2 >> 7) & 0x01 != 0;
884 w.underline = (p2 >> 6) & 0x01 != 0;
885 w.edge_type = EdgeType::from_bits((p2 >> 3) & 0x07);
886 w.font_style = FontStyle::from_bits(p2 & 0x07);
887 }
888 TOTAL
889 }
890
891 fn set_pen_color(service: &mut Service, data: &[u8]) -> usize {
893 const TOTAL: usize = 4;
894 if data.len() < TOTAL {
895 return data.len().max(1);
896 }
897 let p1 = data[1];
898 let p2 = data[2];
899 let p3 = data[3];
900 if let Some(w) = service.current() {
901 w.fg_opacity = Opacity::from_bits((p1 >> 6) & 0x03);
902 w.fg_color = Color::new((p1 >> 4) & 0x03, (p1 >> 2) & 0x03, p1 & 0x03);
903 w.bg_opacity = Opacity::from_bits((p2 >> 6) & 0x03);
904 w.bg_color = Color::new((p2 >> 4) & 0x03, (p2 >> 2) & 0x03, p2 & 0x03);
905 w.edge_color = Color::new((p3 >> 4) & 0x03, (p3 >> 2) & 0x03, p3 & 0x03);
907 }
908 TOTAL
909 }
910
911 fn set_pen_location(service: &mut Service, data: &[u8]) -> usize {
913 const TOTAL: usize = 3;
914 if data.len() < TOTAL {
915 return data.len().max(1);
916 }
917 let row = (data[1] & 0x0F) as usize;
918 let col = (data[2] & 0x3F) as usize;
919 if let Some(w) = service.current() {
920 w.set_pen_location(row, col);
921 }
922 TOTAL
923 }
924
925 fn put(service: &mut Service, ch: char) {
926 if let Some(w) = service.current() {
927 w.put_char(ch);
928 }
929 }
930
931 fn g0_char(b: u8) -> char {
933 if b == G0_MUSIC_NOTE {
934 '\u{266A}'
935 } else {
936 char::from(b)
937 }
938 }
939
940 fn g2_char(b: u8) -> char {
942 match b {
943 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}', _ => '_', }
964 }
965
966 fn g3_char(b: u8) -> char {
968 if b == 0xA0 {
969 '\u{1F4FA}' } else {
971 '_'
972 }
973 }
974
975 #[must_use]
978 pub fn windows(&self, service_number: usize) -> &[Option<Window>; NUM_WINDOWS] {
979 const EMPTY: [Option<Window>; NUM_WINDOWS] =
980 [None, None, None, None, None, None, None, None];
981 if service_number == 0 || service_number > NUM_SERVICES {
982 return &EMPTY;
983 }
984 &self.services[service_number - 1].windows
985 }
986
987 #[must_use]
990 pub fn service_text(&self, service_number: usize) -> String {
991 if service_number == 0 || service_number > NUM_SERVICES {
992 return String::new();
993 }
994 let svc = &self.services[service_number - 1];
995 let mut idxs: Vec<usize> = (0..NUM_WINDOWS)
996 .filter(|&i| {
997 svc.windows[i]
998 .as_ref()
999 .is_some_and(|w| w.state == WindowState::Visible)
1000 })
1001 .collect();
1002 idxs.sort_by_key(|&i| {
1003 svc.windows[i]
1004 .as_ref()
1005 .map_or((u8::MAX, i), |w| (w.priority, i))
1006 });
1007 let mut out = String::new();
1008 for i in idxs {
1009 if let Some(w) = svc.windows[i].as_ref() {
1010 let t = w.text();
1011 if t.is_empty() {
1012 continue;
1013 }
1014 if !out.is_empty() {
1015 out.push('\n');
1016 }
1017 out.push_str(&t);
1018 }
1019 }
1020 out
1021 }
1022}
1023
1024#[derive(Clone, Copy)]
1026enum WindowMapOp {
1027 Clear,
1028 Display,
1029 Hide,
1030 Toggle,
1031 Delete,
1032}
1033
1034fn apply_window_style(w: &mut Window, id: u8) {
1036 w.border_type = EdgeType::None;
1039 match id {
1040 1 => style(w, Justify::Left, false, Some(Color::BLACK), Opacity::Solid),
1041 2 => style(w, Justify::Left, false, None, Opacity::Transparent),
1042 3 => style(
1043 w,
1044 Justify::Center,
1045 false,
1046 Some(Color::BLACK),
1047 Opacity::Solid,
1048 ),
1049 4 => style(w, Justify::Left, true, Some(Color::BLACK), Opacity::Solid),
1050 5 => style(w, Justify::Left, true, None, Opacity::Transparent),
1051 6 => style(w, Justify::Center, true, Some(Color::BLACK), Opacity::Solid),
1052 7 => {
1053 w.justify = Justify::Left;
1054 w.word_wrap = false;
1055 w.print_direction = PrintDirection::TopToBottom;
1056 w.scroll_direction = ScrollDirection::RightToLeft;
1057 w.fill_color = Color::BLACK;
1058 w.fill_opacity = Opacity::Solid;
1059 }
1060 _ => {}
1061 }
1062}
1063
1064fn style(w: &mut Window, j: Justify, ww: bool, fill: Option<Color>, op: Opacity) {
1065 w.justify = j;
1066 w.word_wrap = ww;
1067 w.print_direction = PrintDirection::LeftToRight;
1068 w.scroll_direction = ScrollDirection::BottomToTop;
1069 w.fill_opacity = op;
1070 if let Some(c) = fill {
1071 w.fill_color = c;
1072 }
1073}
1074
1075fn apply_pen_style(w: &mut Window, id: u8) {
1077 w.pen_size = PenSize::Standard;
1078 w.pen_offset = PenOffset::Normal;
1079 w.italics = false;
1080 w.underline = false;
1081 w.fg_color = Color::WHITE;
1082 w.fg_opacity = Opacity::Solid;
1083 match id {
1084 1 => pen(
1085 w,
1086 FontStyle::Default,
1087 EdgeType::None,
1088 Color::BLACK,
1089 Opacity::Solid,
1090 ),
1091 2 => pen(
1092 w,
1093 FontStyle::MonospacedSerif,
1094 EdgeType::None,
1095 Color::BLACK,
1096 Opacity::Solid,
1097 ),
1098 3 => pen(
1099 w,
1100 FontStyle::ProportionalSerif,
1101 EdgeType::None,
1102 Color::BLACK,
1103 Opacity::Solid,
1104 ),
1105 4 => pen(
1106 w,
1107 FontStyle::MonospacedSansSerif,
1108 EdgeType::None,
1109 Color::BLACK,
1110 Opacity::Solid,
1111 ),
1112 5 => pen(
1113 w,
1114 FontStyle::ProportionalSansSerif,
1115 EdgeType::None,
1116 Color::BLACK,
1117 Opacity::Solid,
1118 ),
1119 6 => pen(
1120 w,
1121 FontStyle::MonospacedSansSerif,
1122 EdgeType::Uniform,
1123 Color::BLACK,
1124 Opacity::Transparent,
1125 ),
1126 7 => pen(
1127 w,
1128 FontStyle::ProportionalSansSerif,
1129 EdgeType::Uniform,
1130 Color::BLACK,
1131 Opacity::Transparent,
1132 ),
1133 _ => {}
1134 }
1135}
1136
1137fn pen(w: &mut Window, font: FontStyle, edge: EdgeType, bg: Color, bg_op: Opacity) {
1138 w.font_style = font;
1139 w.edge_type = edge;
1140 w.bg_color = bg;
1141 w.bg_opacity = bg_op;
1142}
1143
1144#[cfg(test)]
1145mod tests {
1146 use super::*;
1147
1148 fn ccp(svc: u8, cmds: &[u8]) -> Vec<u8> {
1150 let mut sb = alloc::vec![(svc << 5) | (cmds.len() as u8)];
1151 sb.extend_from_slice(cmds);
1152 let size_code = (sb.len().div_ceil(2) + 1) as u8 & 0x3F;
1154 let mut packet = alloc::vec![size_code];
1155 packet.extend_from_slice(&sb);
1156 packet
1157 }
1158
1159 #[test]
1164 fn define_window_worked_example() {
1165 let mut dec = Cea708Decoder::new();
1166 let packet = ccp(1, &[0x9A, 0x38, 0x4A, 0xD1, 0x8B, 0x0F, 0x11]);
1167 dec.push_packet(&packet);
1168 let w = dec.windows(1)[2].as_ref().expect("window 2 defined");
1169 assert_eq!(w.state, WindowState::Visible);
1170 assert!(w.row_lock);
1171 assert!(w.column_lock);
1172 assert_eq!(w.priority, 0);
1173 assert!(!w.relative_position);
1174 assert_eq!(w.anchor_vertical, 74);
1175 assert_eq!(w.anchor_horizontal, 209);
1176 assert_eq!(w.anchor_point, AnchorPoint::BottomRight);
1177 assert_eq!(w.row_count, 12);
1178 assert_eq!(w.column_count, 16);
1179 assert_eq!(w.window_style, 2);
1180 assert_eq!(w.pen_style, 1);
1181 }
1182
1183 #[test]
1186 fn swa_border_type_split() {
1187 let mut dec = Cea708Decoder::new();
1188 let packet = ccp(
1190 1,
1191 &[
1192 0x98, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x64, 0x53, 0x88, 0x22, ],
1195 );
1196 dec.push_packet(&packet);
1197 let w = dec.windows(1)[0].as_ref().expect("window 0");
1198 assert_eq!(w.border_type, EdgeType::RightDropShadow);
1199 }
1200
1201 #[test]
1203 fn decode_text() {
1204 let mut dec = Cea708Decoder::new();
1205 let packet = ccp(
1206 1,
1207 &[
1208 0x98, 0x20, 0x00, 0x00, 0x02, 0x0F, 0x00, b'H', b'i',
1210 ],
1211 );
1212 dec.push_packet(&packet);
1213 assert_eq!(dec.service_text(1), "Hi");
1214 }
1215
1216 #[test]
1218 fn two_services_multi_window() {
1219 let mut dec = Cea708Decoder::new();
1220 let s1_block = [0x98, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'1'];
1222 let s2_block = [0x99, 0x20, 0x00, 0x00, 0x00, 0x0F, 0x00, b'S', b'2'];
1224 let mut data = Vec::new();
1225 data.push((1 << 5) | (s1_block.len() as u8));
1226 data.extend_from_slice(&s1_block);
1227 data.push((2 << 5) | (s2_block.len() as u8));
1228 data.extend_from_slice(&s2_block);
1229 let size_code = (data.len().div_ceil(2) + 1) as u8 & 0x3F;
1230 let mut packet = alloc::vec![size_code];
1231 packet.extend_from_slice(&data);
1232 dec.push_packet(&packet);
1233 assert_eq!(dec.service_text(1), "S1");
1234 assert_eq!(dec.service_text(2), "S2");
1235 assert!(dec.windows(1)[0].is_some());
1236 assert!(dec.windows(2)[1].is_some());
1237 }
1238
1239 #[test]
1240 fn services_seen_covers_unmodelled_and_extended_services() {
1241 let mut dec = Cea708Decoder::new();
1242 dec.push_packet(&ccp(1, b"A"));
1243 dec.push_packet(&ccp(2, &[0x00, 0x00]));
1244 let extended = [(7 << 5) | 1, 63, b'Z'];
1245 let size_code = (extended.len().div_ceil(2) + 1) as u8 & 0x3F;
1246 let mut packet = alloc::vec![size_code];
1247 packet.extend_from_slice(&extended);
1248 dec.push_packet(&packet);
1249 assert_eq!(dec.services_seen(), alloc::vec![1, 63]);
1250 }
1251
1252 #[test]
1253 fn carriage_return_rolls_up() {
1254 let mut w = Window::new();
1255 w.row_count = 2;
1256 w.column_count = 10;
1257 w.ensure_grid();
1258 w.put_char('A');
1259 w.carriage_return();
1260 w.put_char('B');
1261 w.carriage_return(); w.put_char('C');
1263 assert_eq!(w.text(), "B\nC");
1264 }
1265
1266 #[test]
1267 fn g0_music_note() {
1268 assert_eq!(Cea708Decoder::g0_char(0x7F), '\u{266A}');
1269 assert_eq!(Cea708Decoder::g0_char(b'A'), 'A');
1270 }
1271
1272 #[test]
1273 fn no_panic_on_arbitrary_input() {
1274 let inputs: &[&[u8]] = &[
1276 &[],
1277 &[0x00],
1278 &[0xFF],
1279 &[0x01, 0x98], &[0x3F, 0x80, 0x90, 0x91, 0x92, 0x97, 0x98], &[0x20, 0xEE, (7 << 5) | 1], &[0x10, 0x9A], &[0x18, 0x00], ];
1285 for inp in inputs {
1286 let mut dec = Cea708Decoder::new();
1287 dec.push_packet(inp);
1288 }
1289 let mut dec = Cea708Decoder::new();
1291 let mut x: u32 = 0x1234_5678;
1292 let mut buf = Vec::new();
1293 for _ in 0..4096 {
1294 x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
1295 buf.push((x >> 16) as u8);
1296 }
1297 dec.push_packet(&buf);
1298 let mut dec2 = Cea708Decoder::new();
1300 let triplets: Vec<CcTriplet> = buf
1301 .chunks(2)
1302 .map(|c| CcTriplet {
1303 cc_valid: true,
1304 cc_type: CcType::Dtvcc708Data,
1305 cc_data_1: c[0],
1306 cc_data_2: *c.get(1).unwrap_or(&0),
1307 })
1308 .collect();
1309 dec2.push_triplets(&triplets);
1310 }
1311}