Files
Teletext-Editor/src/teletext/models.py
T

170 lines
5.4 KiB
Python
Raw Normal View History

from dataclasses import dataclass, field
from typing import List, Optional
def decode_hamming_8_4(byte_val):
# Extract data bits: bits 1, 3, 5, 7
return ((byte_val >> 1) & 1) | \
(((byte_val >> 3) & 1) << 1) | \
(((byte_val >> 5) & 1) << 2) | \
(((byte_val >> 7) & 1) << 3)
@dataclass
class Packet:
"""
Represents a single Teletext packet (Row).
In T42, we have 42 bytes:
Byte 0-1: Magazine and Row Address (Hamming 8/4 encoding)
Byte 2-41: Data bytes (40 bytes)
"""
original_data: bytes
magazine: int = field(init=False)
row: int = field(init=False)
data: bytearray = field(init=False)
def __post_init__(self):
if len(self.original_data) != 42:
raise ValueError(f"Packet must be 42 bytes, got {len(self.original_data)}")
# Parse Magazine and Row from the first 2 bytes (Hamming 8/4)
# MRAG (Magazine + Row Address Group)
# Byte 0: P1 D1 P2 D2 P3 D3 P4 D4
# Byte 1: P1 D1 P2 D2 P3 D3 P4 D4
b1 = self.original_data[0]
b2 = self.original_data[1]
# De-interleave Hamming bits to get M (3 bits) and R (5 bits)
d1 = decode_hamming_8_4(b1)
d2 = decode_hamming_8_4(b2)
# Magazine is 3 bits (Logic is specific: Mag 8 is encoded as 0)
# Row is 5 bits.
# According to Spec (ETSI EN 300 706):
# b1 encoded: M1 M2 M3 R1
# b2 encoded: R2 R3 R4 R5
self.magazine = (d1 & 0b0111)
if self.magazine == 0:
self.magazine = 8
row_low_bit = (d1 >> 3) & 1
row_high_bits = d2
self.row = (row_high_bits << 1) | row_low_bit
self.data = bytearray(self.original_data[2:])
@property
def is_header(self):
return self.row == 0
@dataclass
class Page:
"""
Represents a Teletext Page (e.g., 100).
Can have multiple subpages.
"""
magazine: int
page_number: int # 00-99
sub_code: int = 0 # Subpage code (0000 to 3F7F hex usually, simplest is 0-99 equivalent)
language: int = 0 # National Option (0-7)
packets: List[Packet] = field(default_factory=list)
@property
def full_page_number(self):
# Format as Hex to support A-F pages
return f"{self.magazine}{self.page_number:02X}"
def calculate_crc(self) -> int:
"""
Calculates the CRC-16 (CCITT) checksum for the page.
According to ETSI EN 300 706 (Section 9.4.1.2 & Figure 13):
- Covers Row 0 columns 8-31 (Bytes 14-37 in packet, excluding header and clock).
- Covers Rows 1-25 columns 0-39 (Bytes 6-45 in packet).
- Total 1024 bytes (8192 bits).
- Data is 7-bit (stripped parity).
- Initial value: 0.
"""
crc = 0
poly = 0x1021
# Helper to update CRC with a byte
def update_crc(c, val):
v = (val << 8) & 0xFFFF
for _ in range(8):
if (c ^ v) & 0x8000:
c = (c << 1) ^ poly
else:
c = c << 1
v <<= 1
c &= 0xFFFF
return c
# Organize packets by row
rows = {}
for p in self.packets:
rows[p.row] = p
for r in range(26): # 0 to 25
# Determine column range
if r == 0:
start_col, end_col = 8, 32 # Cols 8-31 (24 bytes)
else:
start_col, end_col = 0, 40 # Cols 0-39 (40 bytes)
if r in rows:
data = rows[r].data
# Ensure data is long enough (should be 40)
d_len = len(data)
for i in range(start_col, end_col):
if i < d_len:
byte_val = data[i] & 0x7F # Strip parity
else:
byte_val = 0x20 # Pad with space if short
crc = update_crc(crc, byte_val)
else:
# Missing row treated as spaces
for i in range(start_col, end_col):
crc = update_crc(crc, 0x20)
return crc
def get_stored_crc(self) -> Optional[int]:
"""
Attempts to retrieve the stored CRC from Packet 27/0 if present.
Returns None if not found.
"""
# Look for Packet 27
for p in self.packets:
if p.row == 27:
# Check Designation Code (Byte 0)
try:
b0 = p.data[0]
# Decode Hamming 8/4
designation = decode_hamming_8_4(b0)
if designation == 0:
# Packet 27/0
# Checksum is in bytes 38 and 39.
# ETSI EN 300 706: 8 bits of each byte are used.
if len(p.data) >= 40:
hi = p.data[38]
lo = p.data[39]
crc = (hi << 8) | lo
return crc
except:
pass
return None
@dataclass
class TeletextService:
"""
Container for all pages.
"""
pages: List[Page] = field(default_factory=list)
# We also keep a flat list of all packets to preserve order on save
all_packets: List[Packet] = field(default_factory=list)