Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Add disk-backed whole-recording intake with explicit clock provenance (#4)
Cinna Davis9538c466766a
diff --git a/docs/AUDIO_INTAKE.md b/docs/AUDIO_INTAKE.mdnew file mode 100644index 0000000..2d2146f--- /dev/null+++ b/docs/AUDIO_INTAKE.md@@ -0,0 +1,38 @@+# Whole-recording audio intake++`intake.intake_recording(source, output_dir, time_window=None, sample_rate_hz=4000)`+returns an `IntakeRecording` with `samples_path`, shared-contract `metadata`, and+intake-specific `diagnostics`. The output directory must not already contain+intake artifacts. It writes mono little-endian float32 `recording.f32`, validated+`recording.json`, and `intake.json` with probe time hints and the exact decode+command. Source files are read, never modified. The source SHA256 is calculated+in blocks and source stat identity is checked across decoding.++ffprobe selects the first actual audio stream regardless of extension. ffmpeg+averages all channels explicitly before resampling and applies its codec skip /+discard handling. Time zero is the first decoded sample, not a container PTS.+Decoded duration comes from sample count / sample rate. `iter_chunks(chunk_s,+overlap_s)` returns `(audio_relative_start_s, float32_samples)` from a disk-backed+cache, bounding working memory independently of recording length. Acoustic+analysis is available before the recording UTC clock is known.++The shared `time_window` bounds the UTC time of sample zero, including recording+clock uncertainty and any known trimming. Pass an explicit defensible user+window or externally verified recording metadata via that contract. Ordinary+MP3/WAV creation, edit, date, upload and filesystem times cannot establish the+recording clock. Embedded date/time tags are retained as **untrusted hints** in+`intake.json`; without an explicit window `recording.time_status == 'needs_input'`.+This implementation deliberately does not promote an unverified tag to a clock.++`AudioIntakeError.code` distinguishes unreadable_audio, invalid_media,+no_audio_stream, decoder_unavailable, decode_failed, invalid_samples, empty_audio+and source_changed. Existing output raises FileExistsError. Input parameter and+shared-contract validation raise ValueError. ffmpeg and ffprobe must be on PATH.++Verification: `PYTHONPATH=src .venv/bin/python -m pytest -q tests/test_intake.py`.+The tests encode a real MP3 with libmp3lame, compare WAV/MP3 burst timings at three+positions to <=1 ms and duration to one 4000 Hz sample, check 48 kHz stereo channel+averaging/resampling, overlapping chunk offsets, a 50 ms clip, missing/ambiguous+UTC, malformed/missing/empty media, hash identity and refusal to overwrite output.+These tolerances establish behavior for the exercised codec/container versions;+unknown encoders that omit gapless metadata can retain unknown leading padding.diff --git a/src/aircraft_geoloc/intake.py b/src/aircraft_geoloc/intake.pynew file mode 100644index 0000000..7efd50e--- /dev/null+++ b/src/aircraft_geoloc/intake.py@@ -0,0 +1,181 @@+"""Whole-recording, disk-backed decoding with explicit recording-clock provenance.++The first decoded sample is audio time zero. ffmpeg applies codec skip samples;+container PTS, file mtime, upload time and generic creation tags are not UTC clocks.+"""+from dataclasses import dataclass+import hashlib+import json+import os+from pathlib import Path+import subprocess+import tempfile++import numpy as np+++class AudioIntakeError(ValueError):+ """Predictable intake failure; ``code`` is suitable for a job reason_code."""++ def __init__(self, code, message):+ self.code = code+ super().__init__(message)+++def source_hash(path):+ digest = hashlib.sha256()+ with Path(path).open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def probe_media(source):+ """Probe the actual first audio stream, independent of filename extension."""+ path = Path(source)+ if not path.is_file():+ raise AudioIntakeError("unreadable_audio", "Audio source is not a readable file")+ try:+ result = subprocess.run(+ ["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(path)],+ capture_output=True, check=True, text=True)+ probe = json.loads(result.stdout)+ except FileNotFoundError as exc:+ raise AudioIntakeError("decoder_unavailable", "ffprobe is required for audio intake") from exc+ except (subprocess.CalledProcessError, json.JSONDecodeError) as exc:+ raise AudioIntakeError("invalid_media", "Media probe failed; file is unsupported or corrupt") from exc+ audio = [s for s in probe.get("streams", []) if s.get("codec_type") == "audio"]+ if not audio:+ raise AudioIntakeError("no_audio_stream", "Media contains no audio stream")+ if int(audio[0].get("sample_rate", 0)) <= 0 or int(audio[0].get("channels", 0)) <= 0:+ raise AudioIntakeError("invalid_media", "Audio stream has invalid sample rate or channels")+ return probe+++def _time_hints(probe):+ hints = []+ sources = [("format", probe.get("format", {}))]+ sources += [(f"stream:{i}", stream) for i, stream in enumerate(probe.get("streams", []))]+ for scope, info in sources:+ for key, value in info.get("tags", {}).items():+ if any(token in key.lower() for token in ("time", "date", "creation", "origination")):+ hints.append({"tag": key, "value": str(value), "scope": scope,+ "usable_as_recording_clock": False})+ return hints+++@dataclass+class IntakeRecording:+ """Decoded cache handle. Metadata is JSON; samples stay on disk."""++ samples_path: Path+ metadata: dict+ diagnostics: dict++ @property+ def time_status(self):+ return "ready" if self.metadata.get("time_window") is not None else "needs_input"++ def iter_chunks(self, chunk_s=120.0, overlap_s=60.0):+ sr = self.metadata["sample_rate_hz"]+ if not np.isfinite(chunk_s) or not np.isfinite(overlap_s) or not 0 <= overlap_s < chunk_s:+ raise ValueError("Require finite 0 <= overlap_s < chunk_s")+ size, overlap = int(round(chunk_s * sr)), int(round(overlap_s * sr))+ if size <= overlap:+ raise ValueError("Chunk step must be at least one sample")+ data = np.memmap(self.samples_path, dtype="<f4", mode="r")+ for first in range(0, len(data), size - overlap):+ yield first / sr, np.array(data[first:first + size])+ if first + size >= len(data):+ break+++def intake_recording(source, output_dir, *, time_window=None, sample_rate_hz=4000):+ """Decode mono f32 into a new cache without holding the whole input in RAM.++ ``time_window`` follows the shared RecordingTimeWindow contract and bounds+ the UTC time of sample zero. Metadata hints require human confirmation via+ that explicit window: tags alone do not provide clock error or edit history.+ A missing window permits acoustic analysis and yields ``needs_input`` for+ historical matching. Existing cache files are never overwritten.+ """+ from .contracts import validate_recording, validate_request++ if type(sample_rate_hz) is not int or not 1000 <= sample_rate_hz <= 192000:+ raise ValueError("sample_rate_hz must be an integer between 1000 and 192000")+ source = Path(source).resolve()+ request = validate_request({"schema_version": 1, "audio_path": str(source), "time_window": time_window})+ probe = probe_media(source)+ audio = next(s for s in probe["streams"] if s["codec_type"] == "audio")+ before = source.stat()+ digest = source_hash(source)+ output = Path(output_dir)+ output.mkdir(parents=True, exist_ok=True)+ samples_path, metadata_path = output / "recording.f32", output / "recording.json"+ if samples_path.exists() or metadata_path.exists():+ raise FileExistsError("Intake output already exists; use a new output directory")+ channels = int(audio["channels"])+ downmix = "pan=mono|c0=" + "+".join(f"{1 / channels:.17g}*c{i}" for i in range(channels))+ command = ["ffmpeg", "-nostdin", "-v", "error", "-xerror", "-i", str(source),+ "-map", "0:a:0", "-vn", "-sn", "-dn", "-af", downmix, "-ac", "1", "-ar", str(sample_rate_hz),+ "-acodec", "pcm_f32le", "-f", "f32le", "pipe:1"]+ temporary = None+ try:+ with tempfile.NamedTemporaryFile(dir=output, prefix=".decode-", delete=False) as cache, \+ tempfile.TemporaryFile() as errors:+ temporary = Path(cache.name)+ try:+ process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=errors)+ except FileNotFoundError as exc:+ raise AudioIntakeError("decoder_unavailable", "ffmpeg is required for audio intake") from exc+ count, peak, remainder = 0, 0.0, b""+ try:+ while block := process.stdout.read(256 * 1024):+ block = remainder + block+ usable = len(block) - len(block) % 4+ values = np.frombuffer(block[:usable], dtype="<f4")+ if not np.all(np.isfinite(values)):+ raise AudioIntakeError("invalid_samples", "Decoded audio contains nonfinite samples")+ if len(values):+ peak = max(peak, float(np.max(np.abs(values))))+ count += len(values)+ cache.write(block[:usable])+ remainder = block[usable:]+ code = process.wait()+ if code or remainder:+ raise AudioIntakeError("decode_failed", "Audio decode failed; media may be truncated or corrupt")+ finally:+ process.stdout.close()+ if process.poll() is None:+ process.kill()+ process.wait()+ if not count:+ raise AudioIntakeError("empty_audio", "Decoded audio contains no samples")+ after = source.stat()+ if (before.st_size, before.st_mtime_ns, before.st_ino) != (after.st_size, after.st_mtime_ns, after.st_ino):+ raise AudioIntakeError("source_changed", "Audio source changed during intake")+ metadata = validate_recording({+ "source_sha256": digest, "duration_s": count / sample_rate_hz,+ "sample_rate_hz": sample_rate_hz, "channels": 1,+ "source_format": probe["format"].get("format_name", audio.get("codec_name", "unknown")),+ "time_window": request.get("time_window"),+ })+ diagnostics = {+ "sample_count": count, "peak_amplitude": peak,+ "time_status": "ready" if time_window is not None else "needs_input",+ "time_hints": _time_hints(probe),+ "decode": {"decoder": "ffmpeg", "sample_format": "f32le", "channel_policy": "arithmetic channel mean",+ "source_sample_rate_hz": int(audio["sample_rate"]), "source_channels": int(audio["channels"]),+ "source_codec": audio.get("codec_name", "unknown"), "stream_index": int(audio["index"]),+ "audio_time_zero": "first decoded sample after codec skip/discard", "command": command},+ }+ # Exclusive creation also prevents accidental replacement on concurrent intake.+ os.link(temporary, samples_path)+ with metadata_path.open("x") as target:+ target.write(json.dumps(metadata, indent=2, allow_nan=False) + "\n")+ with (output / "intake.json").open("x") as target:+ target.write(json.dumps(diagnostics, indent=2, allow_nan=False) + "\n")+ return IntakeRecording(samples_path, metadata, diagnostics)+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)diff --git a/tests/test_intake.py b/tests/test_intake.pynew file mode 100644index 0000000..ba2fdd1--- /dev/null+++ b/tests/test_intake.py@@ -0,0 +1,90 @@+import json+import subprocess++import numpy as np+import pytest+import soundfile as sf++from aircraft_geoloc.contracts import validate_recording+from aircraft_geoloc.intake import AudioIntakeError, intake_recording, source_hash+++def test_stereo_resampling_chunk_times_and_missing_clock(tmp_path):+ sr = 48000+ t = np.arange(sr * 3) / sr+ # Distinct stereo channels verify downmix as well as resampling.+ stereo = np.column_stack((0.4 * np.sin(2 * np.pi * 120 * t), 0.2 * np.sin(2 * np.pi * 240 * t)))+ source = tmp_path / "stereo.wav"+ sf.write(source, stereo, sr, subtype="FLOAT")+ recording = intake_recording(source, tmp_path / "cache")+ assert validate_recording(recording.metadata) == recording.metadata+ assert recording.time_status == "needs_input"+ assert recording.metadata["time_window"] is None+ assert recording.metadata["duration_s"] == 3+ assert recording.metadata["source_sha256"] == source_hash(source)+ decoded = np.fromfile(recording.samples_path, dtype="<f4")+ expected_t = np.arange(12000) / 4000+ expected = 0.2 * np.sin(2 * np.pi * 120 * expected_t) + 0.1 * np.sin(2 * np.pi * 240 * expected_t)+ assert np.sqrt(np.mean((decoded[100:-100] - expected[100:-100]) ** 2)) < 0.001+ chunks = list(recording.iter_chunks(chunk_s=1, overlap_s=0.25))+ assert [start for start, _ in chunks] == [0, 0.75, 1.5, 2.25]+ for start, chunk in chunks:+ first = round(start * 4000)+ np.testing.assert_array_equal(chunk, decoded[first:first + len(chunk)])+ with pytest.raises(FileExistsError):+ intake_recording(source, tmp_path / "cache")+++def test_mp3_codec_skip_preserves_audio_zero(tmp_path):+ sr = 44100+ samples = np.zeros(sr * 4)+ for first in (sr // 2, sr * 2, sr * 3):+ samples[first:first + 1000] = np.hanning(1000) * np.sin(2 * np.pi * 600 * np.arange(1000) / sr)+ source = tmp_path / "bursts.wav"+ sf.write(source, samples, sr)+ mp3 = tmp_path / "actual.mp3"+ subprocess.run(["ffmpeg", "-v", "error", "-i", str(source), "-codec:a", "libmp3lame", "-q:a", "2", str(mp3)], check=True)+ window = {"start_utc": "2026-09-08T20:00:00Z", "end_utc": "2026-09-08T20:01:00Z", "source": "user"}+ wav = intake_recording(source, tmp_path / "wav", time_window=window)+ encoded = intake_recording(mp3, tmp_path / "mp3", time_window=window)+ assert encoded.time_status == "ready"+ assert abs(encoded.metadata["duration_s"] - wav.metadata["duration_s"]) <= 1 / 4000+ a = np.fromfile(wav.samples_path, dtype="<f4")+ b = np.fromfile(encoded.samples_path, dtype="<f4")+ for second in (0.5, 2, 3):+ first, last = int((second - 0.1) * 4000), int((second + 0.15) * 4000)+ lag = np.argmax(np.correlate(a[first:last], b[first:last], "full")) - (last - first - 1)+ assert abs(lag / 4000) <= 0.001+++def test_creation_tag_is_a_hint_and_short_clip_is_valid(tmp_path):+ source = tmp_path / "short.wav"+ sf.write(source, np.zeros(400), 8000)+ tagged = tmp_path / "tagged.wav"+ subprocess.run(["ffmpeg", "-v", "error", "-i", str(source), "-metadata", "date=2020-01-01T00:00:00Z", str(tagged)], check=True)+ recording = intake_recording(tagged, tmp_path / "cache")+ assert recording.metadata["duration_s"] == 0.05+ assert recording.time_status == "needs_input"+ hints = recording.diagnostics["time_hints"]+ assert any(hint["value"] == "2020-01-01T00:00:00Z" for hint in hints)+ assert all(not hint["usable_as_recording_clock"] for hint in hints)+ assert json.loads((tmp_path / "cache" / "recording.json").read_text()) == recording.metadata+++def test_malformed_missing_empty_and_invalid_clock(tmp_path):+ malformed = tmp_path / "pretend.mp3"+ malformed.write_bytes(b"not a media container")+ with pytest.raises(AudioIntakeError) as error:+ intake_recording(malformed, tmp_path / "bad")+ assert error.value.code == "invalid_media"+ with pytest.raises(AudioIntakeError) as error:+ intake_recording(tmp_path / "missing.wav", tmp_path / "missing")+ assert error.value.code == "unreadable_audio"+ source = tmp_path / "empty.wav"+ sf.write(source, np.empty(0), 4000)+ with pytest.raises(AudioIntakeError) as error:+ intake_recording(source, tmp_path / "empty")+ assert error.value.code in ("empty_audio", "invalid_media")+ with pytest.raises(ValueError, match="timezone"):+ intake_recording(malformed, tmp_path / "naive", time_window={+ "start_utc": "2026-01-01T00:00:00", "end_utc": "2026-01-01T00:01:00", "source": "user"})