#!/usr/bin/env python3
"""Print the time of the loudest sound (the clap) in the first N seconds of an audio or video file.
Usage: python3 find-clap.py <file> [seconds=30]
Needs ffmpeg on the PATH. Prints: <seconds with 3 decimals> and a confidence ratio."""
import os, struct, subprocess, sys

RATE = 8000  # decode to 8 kHz mono: 0.125 ms per sample, enough for a clap

def main():
    if len(sys.argv) < 2:
        sys.exit("usage: python3 find-clap.py <file> [seconds]")
    path = sys.argv[1]
    limit = float(sys.argv[2]) if len(sys.argv) > 2 else 30.0
    if not os.path.isfile(path):
        sys.exit("find-clap: file not found: " + path)
    if os.path.getsize(path) == 0:
        sys.exit("find-clap: file is empty: " + path)
    cmd = ["ffmpeg", "-v", "error", "-i", path, "-t", str(limit), "-vn", "-ac", "1", "-ar", str(RATE), "-f", "s16le", "-"]
    res = subprocess.run(cmd, capture_output=True)
    if res.returncode != 0 or len(res.stdout) < 2:
        sys.exit("find-clap: ffmpeg could not read audio from " + path + ": " + res.stderr.decode("utf-8", "replace").strip()[:200])
    n = len(res.stdout) // 2
    samples = struct.unpack("<%dh" % n, res.stdout[: n * 2])
    peak = max(range(n), key=lambda i: abs(samples[i]))
    peak_v = abs(samples[peak])
    if peak_v == 0:
        sys.exit("find-clap: the file is silent in the first %.0f seconds" % limit)
    # loudest sample at least 0.5 s away from the peak, to say how clear the clap is
    guard = RATE // 2
    other = max((abs(samples[i]) for i in range(n) if abs(i - peak) > guard), default=1) or 1
    print("%.3f s  (peak %.1f times the loudest sound elsewhere)" % (peak / RATE, peak_v / other))
    if peak_v / other < 1.5:
        print("warning: the peak is not clearly louder than the rest; check by ear or on a waveform", file=sys.stderr)

main()
