Metadata-Version: 2.4
Name: nsstv
Version: 1.1.0
Summary: High-performance nSSTV (Slow-Scan Television) audio/image encoder-decoder library for WAV, MP3, VIS, custom modes, and SSTV image styling.
Author: Nana Kwadjo Agyare
License-Expression: MIT
Project-URL: Homepage, https://github.com/wambo3/nSSTV
Project-URL: Repository, https://github.com/wambo3/nSSTV
Project-URL: Issues, https://github.com/wambo3/nSSTV/issues
Keywords: sstv,slow scan television,ham radio,amateur radio,radio,audio,image processing,signal processing,spectrogram,vis
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Multimedia :: Sound/Audio
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Communications :: Ham Radio
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20.0
Requires-Dist: scipy>=1.7.0
Requires-Dist: Pillow>=8.0.0
Provides-Extra: mp3
Requires-Dist: pydub>=0.25.1; extra == "mp3"
Provides-Extra: audio
Requires-Dist: sounddevice>=0.4.0; extra == "audio"
Provides-Extra: serial
Requires-Dist: pyserial>=3.5; extra == "serial"
Provides-Extra: sdr
Requires-Dist: pyrtlsdr>=0.2.9; extra == "sdr"
Provides-Extra: all
Requires-Dist: pydub>=0.25.1; extra == "all"
Requires-Dist: sounddevice>=0.4.0; extra == "all"
Requires-Dist: pyserial>=3.5; extra == "all"
Requires-Dist: pyrtlsdr>=0.2.9; extra == "all"
Dynamic: license-file

<p align="center">
  <img src="https://github.com/user-attachments/assets/8eed1fbe-a135-4d00-b7f0-d51395689181" alt="nSSTV Logo" width="650" />
</p>

<h1 align="center">nSSTV v1.1</h1>

<p align="center">
  <strong>Complete SSTV (Slow-Scan Television) Encoder, Decoder, Live Radio Receiver & Transceiver Rig Controller for Python</strong>
</p>

<p align="center">
  <a href="#general-features">General Features</a> •
  <a href="#advanced--hidden-features">Advanced Capabilities</a> •
  <a href="#output-image-styles">Output Styles</a> •
  <a href="#installation">Installation</a> •
  <a href="#python-api-handbook">Python API Handbook</a> •
  <a href="#command-line-interface">CLI Reference</a> •
  <a href="#callsign-demo-code">Callsign Demo</a> •
  <a href="#supported-modes">Supported Modes</a> •
  <a href="#notes--operating-tips">Notes & Tips</a>
</p>

---

## What is SSTV?

**Slow-Scan Television** is a mode used by amateur radio operators to transmit still images over HF, VHF, and UHF radio bands or satellite links (such as the International Space Station). Each pixel row is painted sample-by-sample by modulating audio frequencies (1500 Hz = black, 2300 Hz = white, 1200 Hz = sync).

---

## General Features

- **Full-Spectrum SSTV Encoding**: Converts any image format (JPEG, PNG, BMP, WEBP) into high-fidelity FM radio audio streams (WAV or MP3) with custom sample rates, pre/post-silence padding, and aspect ratio handling.
- **Universal SSTV Demodulation**: Decodes weak, noisy, or off-frequency SSTV audio broadcasts back into clear images with automatic mode detection and VIS header verification.
- **Decode-All Transmissions**: Automatically scans long audio recordings and extracts every SSTV transmission contained within the file into separate decoded images.
- **Batch Processing**: Recursively processes entire directories of WAV or MP3 audio files in one command.
- **Managed Radio Transmission (`transmit`)**: Managed audio playback engine with automated PTT keying before transmission and guaranteed PTT release in a `finally` block to prevent stuck radio transmitters.
- **Comprehensive Hardware & Rig Control**: Built-in CAT control for Hamlib `rigctl`/`rigctld`, Raspberry Pi 5 (`/dev/gpiochip4`) and Pi 4/3 (`/dev/gpiochip0`) GPIO pins, and serial RTS/DTR interface lines.
- **Direct RTL-SDR USB Dongle Receiver**: Captures and decodes SSTV broadcasts directly from RTL-SDR USB dongles (e.g. 145.800 MHz FM for ISS passes or 14.230 MHz HF) with zero external radio hardware required.
- **Automated Background Station Daemons**: Systemd unit file generator (`nsstv-rx.service`) for running 24/7 background radio monitoring and continuous decoding on Raspberry Pi OS.
- **Multiple Output Image Styles**: Generates raw decoded images, Polaroid-framed output, annotated spectrograms, stacked composite comparisons, or all styles simultaneously.
- **Smart Image Fit**: Supports `contain` (pad background), `cover` (crop overflow), and `stretch` scaling modes.
- **Dynamic Overlay & Station Watermarking**: Templating engine for callsign, grid square, timestamp, frequency, and mode text overlays with customizable fonts, opacity, rotation, and positioning.
- **Complete Mode Compatibility**: Comprehensive support for Martin, Scottie, Robot, PD, Pasocon, MMSSTV (including 16-bit extended VIS and N-VIS), and Wraase mode families.
- **Automated Quality Metrics**: Calculates MAE, PSNR (dB), and structural correlation on roundtrip tests and ranks modes automatically.

---

## Advanced & Hidden Features (Full Breadth of Capability)

`nSSTV` includes powerful DSP, image processing, and analytical capabilities that give you full control over signal generation and image enhancement:

- **Anti-Aliased Font Curves & Sub-Pixel Rasterization**: Sub-pixel anti-aliasing renders smooth text glyph curves, custom font outlines, and alpha-blended background bars directly into the frequency stream without blocky staircase artifacts.
- **Custom Font Family & Style Loading**: Supports custom TTF/OTF font loading (`font_family`, `font_style="bold/italic"`) for personalized callsign badges and station branding.
- **Arbitrary Text Overlay Rotation**: Overlays can be rotated by arbitrary angles (e.g., `rotation=15.0` degrees) with automatic bounding-box expansion to prevent text clipping.
- **Diagnostic Spectrogram Generation**: `diagnostics=True` generates annotated spectrogram analysis images revealing leader tones, VIS header bit breakdowns, sync pulse alignment, and signal-to-noise metrics.
- **Automatic Dynamic Range Contrast (`auto_levels=True`)**: Contrast auto-leveling automatically stretches dynamic color range to restore dark or faded SSTV images.
- **Adaptive Heterodyne Whistle Notch Filters**: Spectral pre-filtering automatically detects interfering carrier or CW whistle tones and notches them out prior to FM demodulation.
- **Sub-Audible Bandpass Pre-Filtering**: 1100-2300 Hz Butterworth bandpass filtering isolates the core SSTV audio spectrum from sub-audible hums (<1000 Hz) and high-frequency noise (>2500 Hz).
- **Auto-Slant Clock Drift Calibration**: `slant_search=0.03` automatically calculates and corrects clock drift between transmitting and receiving soundcards to eliminate image tilt.
- **Mode Benchmarking & Quality Ranking (`nsstv.bench`)**: Encodes and decodes your image across every supported mode, calculates MAE, PSNR (dB), and structural correlation, and ranks the best mode for your picture.
- **Custom SSTV Mode Architecture**: Extend `SSTVMode` and `ModeRegistry` to design custom SSTV modes with arbitrary resolutions, frame rates, line timing, and RGB/YUV scan patterns via Python or custom JSON files.
- **In-Place 32-Bit RIFF WAV Auto-Rollover**: Streaming buffer scanner automatically rolls over long-running background sessions into `_part2.wav` files when 32-bit RIFF size thresholds are reached under heavy CPU load.

---

## Output Image Styles & Fit Modes

`nSSTV` supports multiple output styling options for decoded and roundtrip images:

### Output Styles (`output_mode`)

- **`raw`** (default): Pure decoded image without borders or overlays.
- **`polaroid`**: Classic vintage Polaroid photo frame with metadata.
- **`polaroid_text`**: Polaroid frame with mode, timestamp, and quality metadata.
- **`polaroid_notext`**: Polaroid frame without text annotations.
- **`spectrogram`**: Annotated audio spectrogram showing leader, VIS, and sync locks.
- **`spectrogram_text`**: Spectrogram with detailed signal timing annotations.
- **`spectrogram_notext`**: Clean audio spectrogram.
- **`stack`**: Vertical stack combining the raw image and annotated spectrogram.
- **`all`**: Generates all of the above output styles in one pass.

### Image Fit Modes (`fit` / `image_fit`)

- **`contain`** (default): Preserves original aspect ratio and pads borders with background color.
- **`cover`**: Preserves aspect ratio by cropping image overflow to fill the mode frame.
- **`stretch`**: Distorts image to fill exact frame dimensions.

<p align="center">
  <img width="1226" height="636" alt="nSSTV Image Output Comparison Showcase" src="https://github.com/user-attachments/assets/4273c915-325b-4b72-ae69-8ebeb3df75ac" />
</p>

---

## Installation

```bash
pip install nsstv            # Core encoder/decoder
pip install "nSSTV[audio]"   # + Live soundcard playback & mic recording (sounddevice)
pip install "nSSTV[serial]"  # + Serial port DTR/RTS PTT keying (pyserial)
pip install "nSSTV[sdr]"     # + Direct RTL-SDR USB dongle receiver (pyrtlsdr)
pip install "nSSTV[all]"     # Install all optional dependencies
```

If you process MP3 audio files, install `ffmpeg`:

```bash
# macOS (Homebrew)
brew install ffmpeg

# Linux (Debian / Ubuntu / Raspberry Pi OS)
sudo apt update && sudo apt install -y ffmpeg libportaudio2
```

---

## Python API Handbook

All Python functions in `nSSTV` work out of the box with sensible defaults. Only input file paths are required; all tuning parameters are optional.

### 1. Encoding Images (`nsstv.encode`)

```python
import nsstv

# REQUIRED parameter: image_path
# OPTIONAL parameters shown below with their defaults:
info = nsstv.encode(
    image_path="photo.jpg",         # REQUIRED
    wav_out=None,                   # Optional: default creates "photo_sstv.wav"
    mode="Martin M1",               # Optional: SSTV mode name (default "PD-180")
    sample_rate=48000,              # Optional: audio sample rate in Hz (default 48000)
    amplitude=0.80,                 # Optional: audio volume amplitude 0.0..1.0 (default 0.80)
    callsign=None,                  # Optional: station callsign string (e.g. "W1AW")
    callsign_position="watermark",  # Optional: "watermark", "stamp", "header", "footer", "ur", "ll"
    callsign_opacity=1.0,           # Optional: callsign overlay transparency 0.0..1.0
    image_fit="contain",            # Optional: "contain" (pad), "cover" (crop), "stretch"
    oversample=4,                   # Optional: sub-pixel oversampling factor (default 4)
)

print("Generated WAV audio duration:", info["duration_seconds"], "seconds")
```

### 2. Managed Radio Transmission with PTT (`nsstv.transmit`)

`nsstv.transmit()` keys your radio transceiver before audio playback begins and guarantees PTT release in a `finally` block:

```python
import nsstv

# REQUIRED parameter: audio (WAV file path or audio array)
# OPTIONAL parameters: sample_rate, device, rig_hooks, mode_name

# Option A: Hamlib CAT Rig Control (rigctl / rigctld)
rig_hooks = nsstv.make_rigctl_hooks(
    rig_model=2024,            # Hamlib rig model ID
    rig_file="/dev/ttyUSB0",    # Serial port path
    baud=9600,                 # Baud rate
    freq_hz=14230000,          # Set frequency to 14.230 MHz USB
    mode="USB",
)
nsstv.transmit("photo_sstv.wav", rig_hooks=rig_hooks)

# Option B: Raspberry Pi 5 & 4 GPIO Control
gpio_hooks = nsstv.make_rpi_gpio_hooks(ptt_pin=17, active_high=True, ptt_delay=0.2)
nsstv.transmit("photo_sstv.wav", rig_hooks=gpio_hooks)

# Option C: Serial RTS/DTR Line Control (SignaLink / USB Interfaces)
serial_hooks = nsstv.make_serial_dtr_rts_hooks(port="/dev/ttyUSB0", line="dtr")
nsstv.transmit("photo_sstv.wav", rig_hooks=serial_hooks)
```

### 3. Decoding Single, Multi-Transmission & Batch Audio (`nsstv.decode`, `nsstv.decode_all`, `nsstv.batch_decode`)

```python
import nsstv

# 1. Decode single transmission from WAV file
single_res = nsstv.decode(
    audio_path="received_recording.wav",  # REQUIRED
    out="decoded_images/photo_1",         # Optional: output base path
    output_mode="raw",                    # Optional: "raw", "polaroid", "spectrogram", "stack", "all"
    auto_levels=True,                      # Optional: auto-stretch contrast (default False)
    denoise="light",                       # Optional: "off", "light", "medium", "strong"
    diagnostics=True,                      # Optional: save annotated spectrogram (default False)
)

# 2. Decode-All: extract every transmission embedded in a long recording
multi_res = nsstv.decode_all(
    audio_path="long_field_day_recording.wav",  # REQUIRED
    out_dir="field_day_decoded",               # Optional: output folder
    slant_search=0.03,                         # Optional: auto-slant search range
    output_mode="all",                         # Optional: generate raw + polaroid + spectrogram
)
print("Decoded transmissions count:", multi_res["decoded_count"])

# 3. Batch Decode: process an entire directory of audio files recursively
batch_res = nsstv.batch_decode(
    input_dir="./field_recordings",            # REQUIRED
    out_dir="./batch_decoded",                 # Optional: output directory
    recursive=True,                            # Optional: search subdirectories
    output_mode="raw",
)
print("Batch decoded files:", batch_res["processed_count"])
```

### 4. Continuous Soundcard Receiver (`nsstv.live_listen_and_decode`)

```python
import nsstv

# Listens continuously on soundcard input and saves decoded images automatically
nsstv.live_listen_and_decode(
    out_dir="live_rx_images",  # Optional: output directory (default "live_decoded")
    sample_rate=48000,         # Optional: audio sample rate
    device=None,               # Optional: soundcard device index or name
    keep_wav=True,             # Optional: save session WAV recording
)
```

### 5. Direct RTL-SDR Receiver (`nsstv.sdr_listen_and_decode`)

```python
import nsstv

# Tune to 145.800 MHz FM for International Space Station (ISS) passes
nsstv.sdr_listen_and_decode(
    frequency_hz=145800000,   # Optional: 145.800 MHz (default 145800000)
    sample_rate=2000000,      # Optional: SDR IQ sample rate
    out_dir="iss_images",     # Optional: output folder
)
```

### 6. Roundtrip Testing & Mode Benchmarking (`nsstv.rt` & `nsstv.bench`)

```python
import nsstv

# Roundtrip: encode -> decode -> score quality metrics (MAE, PSNR dB, correlation)
rt_res = nsstv.rt(
    image_path="photo.jpg",     # REQUIRED
    mode="PD-180",              # Optional: mode name
    fit="cover",                # Optional: "contain", "cover", "stretch"
    denoise="light",            # Optional: denoise level
)
print("Roundtrip PSNR Score:", rt_res["metrics"]["psnr"], "dB")

# Benchmark: test your image across all modes and rank them by quality
bench_summary = nsstv.bench("photo.jpg")
print("Top ranked mode:", bench_summary["best_mode"])
```

### 7. Image Comparison & Side-by-Side (`nsstv.compare` & `nsstv.side`)

```python
import nsstv

# Score difference between original and decoded image
metrics = nsstv.compare("original.png", "decoded.png")
print("MAE:", metrics["mae"], "PSNR:", metrics["psnr"], "dB")

# Generate side-by-side comparison image
side_path = nsstv.side("original.png", "decoded.png", out="side_by_side.png")
```

### 8. Raspberry Pi Background Service Generator (`nsstv.make_rpi_systemd_service`)

```python
import nsstv

service_unit = nsstv.make_rpi_systemd_service(
    service_name="nsstv-rx",
    out_dir="/home/pi/sstv_images",
    sample_rate=48000,
    keep_wav=True,
)

print(service_unit)
```

Generated unit template:

```ini
[Unit]
Description=nSSTV Radio encoding and decoding
After=network.target sound.target

[Service]
Type=simple
User=pi
ExecStart=/usr/bin/python3 -m nsstv listen --out-dir /home/pi/sstv_images --sample-rate 48000 --keep-wav
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
```

---

## Callsign Demo Code

The code below demonstrates how to format and stamp multiple station text overlays onto an SSTV image prior to transmission:

```python
import nsstv

# Define overlay elements with custom formatting, font styles, colors, and opacity
overlays = [
    nsstv.TextOverlay(
        text="DE {callsign} GRID {grid}",
        position="bottom-right",      # Aliases: watermark, stamp, callsign, header, footer, ur, ll
        font_style="bold",
        text_color=(255, 255, 255),
        bg_color=(20, 20, 20),
        outline_color=(0, 0, 0),
        outline_width=3,
        opacity=0.90,
    ),
    nsstv.TextOverlay(
        text="2024-01-15 14:32 UTC | Scottie S1",
        position="top-left",
        font_size=16,
        font_style="italic",
        bg_color=(0, 0, 0),
        opacity=0.75,
    ),
]

# Format template tags and composite overlays onto the source image
ctx = {"callsign": "N0CALL", "grid": "FN31"}
nsstv.add_texts_to_image(
    image_path="ufo_decoded.png",
    out_path="ufo_stamped.png",
    overlays=overlays,
)
```

<p align="center">
  <img width="320" height="256" alt="nSSTV Callsign Demo Image" src="https://github.com/user-attachments/assets/8eccb4e1-e659-44e0-8a27-7c054d160d90" />
</p>

---

## Command Line Interface

`nSSTV` can be executed from the terminal as `nSSTV` or `python3 -m nsstv`:

```bash
# Decode an audio recording
python3 -m nsstv decode input.wav --out-base decoded_img --output-mode polaroid --image-format png

# Decode-All: extract every transmission embedded in a long recording
python3 -m nsstv decode-all recording.wav --out-dir decoded_all --output-mode all

# Batch decode a folder of recordings at once
python3 -m nsstv batch ./recordings --out-dir ./decoded_batch

# Encode an image to SSTV audio WAV file with callsign
python3 -m nsstv encode photo.jpg --mode "Martin M1" --wav-out tx.wav --callsign W1AW

# Transmit an image over radio with Raspberry Pi GPIO PTT
python3 -m nsstv transmit photo.jpg --mode "Martin M1" --gpio-pin 17

# Transmit an image over radio with Hamlib CAT control
python3 -m nsstv transmit photo.jpg --mode "PD-180" --rig-model 2024 --rig-file /dev/ttyUSB0

# Live record from mic/virtual audio for fixed duration, then decode
python3 -m nsstv live --seconds 240 --out-base live_record.jpg

# Continuous soundcard radio listening
python3 -m nsstv listen --out-dir live_rx --sample-rate 48000

# Continuous live listening alias
python3 -m nsstv live-listen --out-dir live_rx --sample-rate 48000

# Full roundtrip test (encode -> decode -> score)
python3 -m nsstv rt photo.jpg --mode PD-180 --fit cover --output-mode stack

# Score difference between two images
python3 -m nsstv compare original.png decoded.png

# Generate side-by-side comparison image
python3 -m nsstv side original.png decoded.png --out side.png

# Preview how an image fits a mode frame
python3 -m nsstv fit photo.jpg --mode PD-180 --how cover

# Benchmark every mode on an image and rank by quality
python3 -m nsstv bench photo.jpg

# Generate a calibrated mode test card image
python3 -m nsstv testcard --mode "Scottie S1" --out testcard.png

# List all supported modes and VIS header codes
python3 -m nsstv modes
```

### Script Mode (Environment Variables)

Running `nSSTV` with no arguments triggers Script Mode, configured via environment variables:

```bash
NSSTV_ACTION=decode NSSTV_AUDIO_INPUT=input.wav nSSTV
NSSTV_ACTION=batch NSSTV_WORKDIR=./recordings nSSTV
NSSTV_ACTION=encode NSSTV_IMAGE_INPUT=image.jpg nSSTV
```

---

## Supported Modes

| Family | Mode Name | Resolution | Line Time (s) | VIS Code | Notes |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **Martin** | Martin M1 | 320x256 | 448.0 ms | 0x2B | Standard European HF mode |
| **Martin** | Martin M2 | 320x256 | 224.2 ms | 0x28 | High-speed Martin mode |
| **Scottie** | Scottie S1 | 320x256 | 428.8 ms | 0x3C | Standard US HF mode |
| **Scottie** | Scottie S2 | 320x256 | 269.8 ms | 0x38 | High-speed Scottie mode |
| **Scottie** | Scottie DX | 320x256 | 1045.6 ms | 0x4C | Long-distance weak signal mode |
| **Robot** | Robot 36 | 320x240 | 150.0 ms | 0x08 | Y/C YUV mode (ISS pass default) |
| **Robot** | Robot 72 | 320x240 | 300.0 ms | 0x0C | High-resolution Y/C mode |
| **PD** | PD-50 | 512x400 | 252.8 ms | 0x5D | High resolution |
| **PD** | PD-90 | 512x400 | 452.8 ms | 0x63 | High resolution |
| **PD** | PD-120 | 640x496 | 379.2 ms | 0x5F | Standard high-resolution mode |
| **PD** | PD-160 | 512x400 | 800.0 ms | 0x62 | High resolution |
| **PD** | PD-180 | 640x496 | 569.6 ms | 0x60 | Popular high-resolution mode |
| **PD** | PD-240 | 640x496 | 758.4 ms | 0x58 | Ultra high-resolution mode |
| **PD** | PD-290 | 800x616 | 940.8 ms | 0x5E | Maximum resolution PD mode |
| **MMSSTV** | MMSSTV MP73..MR320 | 320x256 / 640x496 | Variable | 0x23 | 16-bit extended VIS & N-VIS modes |
| **Pasokon** | Pasokon P3..P7 | 640x496 | Variable | 0x71..0x73 | High-resolution Pasokon modes |
| **Wraase** | SC-180 | 320x256 | 705.0 ms | 0x37 | Classic 180s RGB mode |

---

## Notes & Operating Tips

> [!NOTE]
> **Clock Drift & Slanted Images**
> Slanted images occur when slight clock speed differences exist between the transmitting radio's soundcard and the receiving soundcard. If received pictures tilt, enable auto-slant correction with `--slant-search 0.03` or `slant_search=0.03` in Python.

> [!NOTE]
> **Audio Level Adjustment**
> Ensure your radio interface output volume is set so the transmitter operates in linear SSB mode without clipping or over-modulating ALC levels. For receiving, adjust soundcard input levels so signals fill 50% to 80% of dynamic range.

> [!NOTE]
> **MP3 Compression Caution**
> MP3 is a lossy compression format that alters sub-audible FM SSTV frequencies. While `nSSTV` supports encoding and decoding MP3 files, WAV format is strongly recommended for highest picture clarity.

> [!NOTE]
> **Raspberry Pi Hardware Permissions**
> When using GPIO PTT control on Raspberry Pi systems, ensure your user account belongs to the `gpio` and `dialout` system groups:
> ```bash
> sudo usermod -aG gpio,dialout pi
> ```

---

## License

`nSSTV` is licensed under the MIT License. Free for amateur radio operators, open source projects, educational research, and commercial applications.
