#!/usr/bin/env python3 """Convert a Bad Apple source video into firmware-ready assets. This tool requires ffmpeg in PATH. It produces: - video.baa : 1-bit packed frames with custom header. - audio.pdm : 1-bit sigma-delta encoded PCM data with custom header. """ import argparse import math import struct import subprocess import tempfile from pathlib import Path VIDEO_MAGIC = b"BAA\0" AUDIO_MAGIC = b"BAP\0" def run_ffmpeg(args): process = subprocess.run(args, check=False) if process.returncode != 0: raise RuntimeError(f"ffmpeg failed: {' '.join(args)}") def pcm_to_pdm(samples): # First-order sigma-delta modulation. acc = 0 threshold = 0 bitstream = bytearray((len(samples) + 7) // 8) for idx, sample in enumerate(samples): acc += sample - threshold if acc >= 0: threshold = 32767 bit = 1 else: threshold = -32768 bit = 0 if bit: bitstream[idx // 8] |= 1 << (idx % 8) return bitstream def encode_video(raw_path, width, height, frame_count, fps, threshold): stride_bits = width * height stride_bytes = (stride_bits + 7) // 8 output = bytearray() output += VIDEO_MAGIC output += struct.pack('= threshold: bits[i // 8] |= 1 << (i % 8) output.extend(bits) return output def encode_audio(raw_path, sample_rate, start_offset_samples=0): data = Path(raw_path).read_bytes() samples = struct.iter_unpack(' 0: pcm = pcm[start_offset_samples:] bitstream = pcm_to_pdm(pcm) header = bytearray() header += AUDIO_MAGIC header += struct.pack('