#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
#
# astra-ss-detect: does an audio file carry the astra-ss-v1 watermark (AI-generated by Astra)?
#
# Copyright (c) 2026 MINICE
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
# OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Detect the astra-ss-v1 audio watermark. Needs Python 3 and numpy; ffmpeg for formats other than WAV.

Usage:
    python3 astra-ss-detect.py greeting.mp3

Input: a WAV file (PCM, 8/16/24/32-bit, 8-384 kHz, any channel count) is read directly. Any other
format (MP3, OGG, M4A, ...) is decoded with ffmpeg when ffmpeg is on PATH; without it, install ffmpeg
or convert the file to WAV yourself. At most 30 minutes of audio are read.

Output: "marked" or "not marked", and the two scores. Exit status 0 = marked, 1 = not marked,
2 = the file could not be read or checked (any error at all).

The algorithm and its constants are published in Astra's specification of astra-ss-v1; this file
follows it line by line. The mark carries no data: it says only that the audio was generated by
Astra. It does not survive a change of speed or pitch.
"""
import shutil
import subprocess
import sys
import wave

try:
    import numpy as np
except ImportError:
    print("astra-ss-detect needs numpy: pip install numpy", file=sys.stderr)
    sys.exit(2)

SAMPLE_RATE = 24000
N = 16384                    # the pattern's period, in samples
BAND_HZ = (300, 4000)        # the band the mark lives in
SEED = 0x41535452412D5631    # "ASTRA-V1"
ENERGY_LAGS = 240            # the energy score's window (10 ms)
PEAK_THRESHOLD = 6.5
ENERGY_THRESHOLD = 14.0
MAGNITUDE_FLOOR_PER_PERIOD = 1e-3  # in 16-bit sample units, times (periods folded + 1)
MIN_RATE = 8000
MAX_RATE = 384000
MAX_SECONDS = 30 * 60
NUMPY_RESAMPLE_MAX = 600 * 48000  # input samples numpy may resample in one FFT (ffmpeg has no limit)
MASK = (1 << 64) - 1


class Unreadable(Exception):
    """The file cannot be checked; the message says why."""


def splitmix64(state):
    state = (state + 0x9E3779B97F4A7C15) & MASK
    z = state
    z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK
    return state, z ^ (z >> 31)


def band_phases():
    """The bins of the N-point DFT inside the band, and the pattern's phase at each."""
    hz_per_bin = SAMPLE_RATE / N
    lo = int(np.ceil(BAND_HZ[0] / hz_per_bin))
    hi = int(np.floor(BAND_HZ[1] / hz_per_bin))
    bins = np.arange(lo, hi + 1)
    state = SEED
    phases = np.empty(len(bins))
    for i in range(len(bins)):
        state, out = splitmix64(state)
        phases[i] = 2.0 * np.pi * ((out >> 11) / float(1 << 53))
    return bins, phases


def pcm_to_float(raw, width):
    """Little-endian PCM bytes to floats in 16-bit units (full scale +-32768)."""
    if width == 1:
        return (np.frombuffer(raw, dtype=np.uint8).astype(np.float64) - 128.0) * 256.0
    if width == 2:
        return np.frombuffer(raw, dtype="<i2").astype(np.float64)
    if width == 3:
        b = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3).astype(np.int32)
        v = b[:, 0] | (b[:, 1] << 8) | (b[:, 2] << 16)
        return np.where(v >= 1 << 23, v - (1 << 24), v).astype(np.float64) / 256.0
    if width == 4:
        return np.frombuffer(raw, dtype="<i4").astype(np.float64) / 65536.0
    raise Unreadable("unsupported sample width")


def read_wav(path):
    """Mono float samples in 16-bit units, and the rate; None when ffmpeg should resample instead.
    Raises wave.Error for a file that is not a PCM WAV. Read in blocks, so memory stays at the mono
    signal however many channels the file has."""
    with wave.open(path, "rb") as w:
        channels, width, rate, frames = w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()
        if not MIN_RATE <= rate <= MAX_RATE:
            raise Unreadable(f"sample rate {rate} Hz is outside {MIN_RATE}-{MAX_RATE} Hz")
        if frames > MAX_SECONDS * rate:
            raise Unreadable(f"longer than {MAX_SECONDS // 60} minutes")
        if width not in (1, 2, 3, 4) or channels < 1:
            raise Unreadable("unsupported sample width")
        if rate != SAMPLE_RATE:
            if shutil.which("ffmpeg") is not None:
                return None
            if frames > NUMPY_RESAMPLE_MAX:
                raise Unreadable(f"too long to resample from {rate} Hz without ffmpeg: install ffmpeg "
                                 "or pass a 24 kHz WAV")
        blocks = []
        while True:
            raw = w.readframes(1 << 20)
            if not raw:
                break
            raw = raw[: len(raw) - len(raw) % (width * channels)]
            blocks.append(pcm_to_float(raw, width).reshape(-1, channels).mean(axis=1))
    x = np.concatenate(blocks) if blocks else np.zeros(0)
    return x, rate


def read_ffmpeg(path):
    """Any format ffmpeg reads, decoded to mono 16-bit at 24 kHz."""
    ffmpeg = shutil.which("ffmpeg")
    if ffmpeg is None:
        raise Unreadable("not a PCM WAV file, and ffmpeg is not installed: install ffmpeg "
                         "(https://ffmpeg.org) or convert the file to WAV first")
    limit = MAX_SECONDS * SAMPLE_RATE * 2
    # Local files only: a crafted playlist or concat file must not make ffmpeg open a URL.
    cmd = [ffmpeg, "-nostdin", "-v", "error", "-protocol_whitelist", "file,pipe", "-i", path, "-t", str(MAX_SECONDS + 1),
           "-ac", "1", "-ar", str(SAMPLE_RATE), "-f", "s16le", "-"]
    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600)
    if proc.returncode != 0:
        detail = proc.stderr.decode("utf-8", "replace").strip().splitlines()
        raise Unreadable("ffmpeg could not decode it" + (f": {detail[-1]}" if detail else ""))
    if len(proc.stdout) > limit:
        raise Unreadable(f"longer than {MAX_SECONDS // 60} minutes")
    raw = proc.stdout[: len(proc.stdout) - len(proc.stdout) % 2]
    return np.frombuffer(raw, dtype="<i2").astype(np.float64), SAMPLE_RATE


def read_audio(path):
    try:
        got = read_wav(path)
    except (wave.Error, EOFError):
        got = None
    return got if got is not None else read_ffmpeg(path)


def resample(x, rate):
    """To 24 kHz, by zero-padding or truncating the spectrum (numpy only)."""
    if rate == SAMPLE_RATE or len(x) == 0:
        return x
    n_out = int(round(len(x) * SAMPLE_RATE / rate))
    spectrum = np.fft.rfft(x)
    out = np.zeros(n_out // 2 + 1, dtype=complex)
    keep = min(len(spectrum), len(out))
    out[:keep] = spectrum[:keep]
    return np.fft.irfft(out, n_out) * (n_out / len(x))


def detect(x):
    """(peak, energy, marked) for mono float samples at 24 kHz, in 16-bit units."""
    if len(x) == 0:
        return 0.0, 0.0, False
    folded = np.concatenate([x, np.zeros((-len(x)) % N)]).reshape(-1, N).sum(axis=0)
    y = np.fft.fft(folded)
    bins, phases = band_phases()
    c_spec = np.zeros(N, dtype=complex)
    mag = np.abs(y[bins])
    used = mag > MAGNITUDE_FLOOR_PER_PERIOD * (len(x) // N + 1)
    v = np.zeros(len(bins), dtype=complex)
    v[used] = y[bins][used] / mag[used] * np.exp(-1j * phases[used])
    c_spec[bins] = v
    c_spec[N - bins] = np.conj(v)
    c = np.real(np.fft.ifft(c_spec))
    sigma = np.sqrt(np.mean(c ** 2))
    if not np.isfinite(sigma) or sigma == 0.0:
        return 0.0, 0.0, False
    peak = float(np.max(np.abs(c)) / sigma)
    e = (c / sigma) ** 2
    window = np.concatenate([e, e[:ENERGY_LAGS - 1]])
    sums = np.convolve(window, np.ones(ENERGY_LAGS), mode="valid")[:N]
    energy = float((np.max(sums) - ENERGY_LAGS) / np.sqrt(2 * ENERGY_LAGS))
    return peak, energy, peak >= PEAK_THRESHOLD or energy >= ENERGY_THRESHOLD


def main(argv):
    if len(argv) != 2:
        print("usage: python3 astra-ss-detect.py <audio file>", file=sys.stderr)
        return 2
    try:
        x, rate = read_audio(argv[1])
        peak, energy, marked = detect(resample(x, rate))
    except Unreadable as e:
        print(f"cannot check {argv[1]}: {e}", file=sys.stderr)
        return 2
    except BaseException as e:  # any failure is "could not check" (2), never "not marked" (1)
        print(f"cannot check {argv[1]}: {type(e).__name__}: {e}", file=sys.stderr)
        return 2
    print(f"{'marked' if marked else 'not marked'} (astra-ss-v1)  peak {peak:.2f}  energy {energy:.2f}")
    return 0 if marked else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
