Fix: Improve file integrity on save by preserving original packet headers

This commit is contained in:
2025-12-30 20:41:47 +01:00
parent fc55927b78
commit e223917b94

View File

@@ -100,36 +100,63 @@ def encode_hamming_8_4(value):
return res return res
def decode_packet_header(b1, b2):
"""
Decodes the Magazine and Row from the first 2 bytes of a T42 packet.
"""
d1 = decode_hamming_8_4(b1)
d2 = decode_hamming_8_4(b2)
mag = (d1 & 0b0111)
if mag == 0: mag = 8
row = (d2 << 1) | ((d1 >> 3) & 1)
return mag, row
def save_t42(file_path: str, service: TeletextService): def save_t42(file_path: str, service: TeletextService):
with open(file_path, 'wb') as f: with open(file_path, 'wb') as f:
for packet in service.all_packets: for packet in service.all_packets:
# Reconstruct header bytes from packet.magazine and packet.row # Check if we can reuse the original header (preserving parity/integrity)
# Byte 1: M1 M2 M3 R1 use_original_header = False
# Byte 2: R2 R3 R4 R5
mag = packet.magazine if hasattr(packet, 'original_data') and len(packet.original_data) >= 2:
if mag == 8: mag = 0 # 0 encoded as 8 # Try to decode the original header
try:
orig_mag, orig_row = decode_packet_header(packet.original_data[0], packet.original_data[1])
if orig_mag == packet.magazine and orig_row == packet.row:
use_original_header = True
except:
pass
# Bits: if use_original_header:
# B1 data: M1(0) M2(1) M3(2) R1(3) header = packet.original_data[:2]
m1 = (mag >> 0) & 1 else:
m2 = (mag >> 1) & 1 # Reconstruct header bytes
m3 = (mag >> 2) & 1 mag = packet.magazine
r1 = (packet.row >> 0) & 1 if mag == 8: mag = 0 # 0 encoded as 8
b1_val = m1 | (m2 << 1) | (m3 << 2) | (r1 << 3) # Bits:
b1_enc = encode_hamming_8_4(b1_val) # B1 data: M1(0) M2(1) M3(2) R1(3)
m1 = (mag >> 0) & 1
m2 = (mag >> 1) & 1
m3 = (mag >> 2) & 1
r1 = (packet.row >> 0) & 1
# B2 data: R2(0) R3(1) R4(2) R5(3) b1_val = m1 | (m2 << 1) | (m3 << 2) | (r1 << 3)
r2 = (packet.row >> 1) & 1 b1_enc = encode_hamming_8_4(b1_val)
r3 = (packet.row >> 2) & 1
r4 = (packet.row >> 3) & 1
r5 = (packet.row >> 4) & 1
b2_val = r2 | (r3 << 1) | (r4 << 2) | (r5 << 3) # B2 data: R2(0) R3(1) R4(2) R5(3)
b2_enc = encode_hamming_8_4(b2_val) r2 = (packet.row >> 1) & 1
r3 = (packet.row >> 2) & 1
r4 = (packet.row >> 3) & 1
r5 = (packet.row >> 4) & 1
b2_val = r2 | (r3 << 1) | (r4 << 2) | (r5 << 3)
b2_enc = encode_hamming_8_4(b2_val)
header = bytes([b1_enc, b2_enc])
header = bytes([b1_enc, b2_enc])
f.write(header + packet.data) f.write(header + packet.data)
def decode_hamming_8_4(byte_val): def decode_hamming_8_4(byte_val):