Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

Add independent MP3 timing acceptance measurements for DG-12

Cinna Davis9a1f74ba2472
diff --git a/docs/E2E_VERIFICATION.md b/docs/E2E_VERIFICATION.md
new file mode 100644
index 0000000..f4aff38
--- /dev/null
+++ b/docs/E2E_VERIFICATION.md
@@ -0,0 +1,60 @@
+# Independent MP3 and product verification
+
+This lane supports DG-12 / issue #13. It complements the independent regional
+replay lane and does not replace held-out real national localization evidence.
+
+Run the codec measurement from an installed checkout with ffmpeg/libmp3lame:
+
+```bash
+.venv/bin/python -m pytest -q tests/test_methodology_verifier.py
+.venv/bin/python scripts/verify_methodology.py codec --output results/mp3-timing-new
+```
+
+The output directory must be new. The runner generates a deterministic stereo
+signal with three nonperiodic timing pilots, encodes five MP3 variants, and decodes
+the WAV and MP3s independently to mono 4 kHz. It measures each pilot by normalized
+cross-correlation. Silence, unrelated signals, truncated input and offsets beyond
+the measurement range cannot pass. Original/MP3/code hashes, versions, exact
+commands, stderr and decoded arrays remain in that directory. `report.json`
+records all cases; the command fails if a required encoding fails.
+
+The four gapless encodings must retain pilot timing and decoded duration within
+2 ms. The fifth deliberately omits the Xing header and is a diagnostic: an MP3
+without gapless metadata need not identify the original recorder's sample zero.
+A failed diagnostic measurement still fails the command. A measured delay on this
+test signal is not a universal correction that can be applied to other files.
+
+## Local codec measurement, 2026-11-02
+
+Platform: Linux x86-64, CPython 3.12.3, ffmpeg 6.1.1 with libmp3lame. The environment
+was created with `uv venv --python 3.12 .venv` and installed with
+`uv pip install --python .venv/bin/python -e . pytest`.
+
+| Encoding | Maximum pilot offset | Duration difference | Outcome |
+| --- | ---: | ---: | --- |
+| Mono 8 kHz / CBR 16 kbps | 0.000966 ms | 0 ms | Pass |
+| Mono 16 kHz / CBR 32 kbps | 0.000234 ms | 0 ms | Pass |
+| Stereo 44.1 kHz / CBR 96 kbps | 0.000055 ms | 0.75 ms | Pass |
+| Stereo 48 kHz / VBR q4 | 0.000014 ms | 0 ms | Pass |
+| Mono 16 kHz / CBR 32 kbps, no Xing header | 69.051 ms | 93 ms | Diagnostic |
+
+Subsample offsets are interpolation estimates, not claims of clock precision
+beyond the 0.25 ms decoded sample period. Five verifier tests cover planted delays
+and rejection controls. The original 11 baseline tests passed in this clean
+environment. The checked-in codec receipt is
+`evidence/verification/mp3-timing-20261102.json`; full local output is
+`results/mp3-timing-20261102/`.
+
+## Automatic workflow acceptance
+
+The actual CLI/API/upload acceptance depends on the producer implementations in
+issues #4–#11. It must invoke real intake, discovery, acquisition, association,
+search and decision code; inspectable output alone does not establish a successful
+location. An undated file must retain `needs_input`; unsupported audio/coverage
+must retain failed/inconclusive distinctions. Manual event windows/bands, true
+flight IDs and truth-derived bounds are not normal automatic inputs.
+
+No automatic location or national validation is established by the codec results
+above. Final acceptance remains open until the integrated upload path is executed
+and the real benchmark outcomes, time/location uncertainty and searched coverage
+are reported.
diff --git a/evidence/verification/mp3-timing-20261102.json b/evidence/verification/mp3-timing-20261102.json
new file mode 100644
index 0000000..b79d475
--- /dev/null
+++ b/evidence/verification/mp3-timing-20261102.json
@@ -0,0 +1,185 @@
+{
+ "schema_version": 1,
+ "scope": "codec_timing_only",
+ "location_validation": false,
+ "provenance": {
+ "git_commit": "c7d88f6016812eac37d3eb1f6e6cfa848a562735",
+ "working_tree": [
+ "?? scripts/verify_methodology.py",
+ "?? tests/test_methodology_verifier.py"
+ ],
+ "source_sha256": {
+ "scripts/verify_methodology.py": "d8ea2edd66b7761843174f17ab18c4ac76dd51e135c50315568be5296ebec9db",
+ "src/aircraft_geoloc/__init__.py": "01428b7938817c1cfe7eb3cf7e186f35b3fa7bc2d85f14204d07e0aa251d2c88",
+ "src/aircraft_geoloc/audio.py": "f9248876059f7f05f3f3db8575e43b9c12f96c536c70b8afc298cfdebcb977a0",
+ "src/aircraft_geoloc/cli.py": "591b4f6b6f08fb649acd0003f432bbd4f01ab3f9f8858b094245c54b9260ac00",
+ "src/aircraft_geoloc/contracts.py": "66e311197e69fc6636dea33e25ae2acccfeba2845b0561963f33112c932a969f",
+ "src/aircraft_geoloc/geometry.py": "f892fac88864d8095ce47a1e3e6139235b86061fb0814944867436cb5a92bb94",
+ "src/aircraft_geoloc/pipeline.py": "d2361725283053a0911a803717f8dab6e59ed8e1c20e305f191aeea693156adb",
+ "src/aircraft_geoloc/search.py": "79c84c0792184d6cd394f7ba3f5d73229b4ec338304284a87477206178143d40",
+ "src/aircraft_geoloc/terrain.py": "b8258fa2d950c2348c78e019f9e97ce9fe6c760cf7fd47a81d1a21d23362948a",
+ "src/aircraft_geoloc/tracks.py": "9af648eaa1f7880ba00bead2a66cd7b05fb98f6a5d6045d506cf3276604ae6e3"
+ },
+ "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]",
+ "platform": "Linux-6.8.0-142-generic-x86_64-with-glibc2.39",
+ "dependencies": {
+ "numpy": "2.5.4",
+ "scipy": "1.18.1",
+ "soundfile": "0.14.0"
+ },
+ "ffmpeg": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers"
+ },
+ "source_sha256": "071aa02f069b64d9ff0458971c67ea72e4a07af8465b9efc116c785e03582e99",
+ "reference_sample_rate_hz": 4000,
+ "reference_samples": 181500,
+ "cases": [
+ {
+ "name": "mono-8k-cbr16",
+ "gapless_expected": true,
+ "encoded_sample_rate_hz": 8000,
+ "encoded_channels": 1,
+ "mp3_sha256": "faf739c594a5b6cd47c6b3d4159844ae3f4e6de31a7f6dd136b784b1470b53f4",
+ "decoded_samples": 181500,
+ "duration_difference_s": 0.0,
+ "pilots": [
+ {
+ "center_s": 2.3,
+ "offset_s": 4.43555963566606e-08,
+ "correlation": 0.9784921112512649
+ },
+ {
+ "center_s": 18.7,
+ "offset_s": 9.659541944089177e-07,
+ "correlation": 0.9798177367308618
+ },
+ {
+ "center_s": 39.2,
+ "offset_s": -4.4992836008716566e-07,
+ "correlation": 0.9812575355739114
+ }
+ ],
+ "max_absolute_offset_s": 9.659541944089177e-07,
+ "end_to_start_drift_s": -4.942839564438262e-07,
+ "status": "passed"
+ },
+ {
+ "name": "mono-16k-cbr32",
+ "gapless_expected": true,
+ "encoded_sample_rate_hz": 16000,
+ "encoded_channels": 1,
+ "mp3_sha256": "f99f3c0627b6155beceac4893fb3fee623738a10137750d734e98dcabc6989c7",
+ "decoded_samples": 181500,
+ "duration_difference_s": 0.0,
+ "pilots": [
+ {
+ "center_s": 2.3,
+ "offset_s": 8.80992566250759e-08,
+ "correlation": 0.9987160918832674
+ },
+ {
+ "center_s": 18.7,
+ "offset_s": 1.4291671502028586e-07,
+ "correlation": 0.9986624995894987
+ },
+ {
+ "center_s": 39.2,
+ "offset_s": 2.3380275343239073e-07,
+ "correlation": 0.9987963753696862
+ }
+ ],
+ "max_absolute_offset_s": 2.3380275343239073e-07,
+ "end_to_start_drift_s": 1.4570349680731485e-07,
+ "status": "passed"
+ },
+ {
+ "name": "stereo-44k-cbr96",
+ "gapless_expected": true,
+ "encoded_sample_rate_hz": 44100,
+ "encoded_channels": 2,
+ "mp3_sha256": "feda1ea0b884ac4cecccb44830c9790e338a044bb93eb34f30ac76c74638f4b0",
+ "decoded_samples": 181503,
+ "duration_difference_s": 0.00075,
+ "pilots": [
+ {
+ "center_s": 2.3,
+ "offset_s": 2.6380644078913976e-08,
+ "correlation": 0.999939442358988
+ },
+ {
+ "center_s": 18.7,
+ "offset_s": -5.494363603993495e-08,
+ "correlation": 0.9999580079778554
+ },
+ {
+ "center_s": 39.2,
+ "offset_s": -1.2435207563900224e-08,
+ "correlation": 0.9999401478513301
+ }
+ ],
+ "max_absolute_offset_s": 5.494363603993495e-08,
+ "end_to_start_drift_s": -3.88158516428142e-08,
+ "status": "passed"
+ },
+ {
+ "name": "stereo-48k-vbr",
+ "gapless_expected": true,
+ "encoded_sample_rate_hz": 48000,
+ "encoded_channels": 2,
+ "mp3_sha256": "3a212ad5973a6c08d7006fff7db3b0bc52a0b8457c39b882b5be3245353e9db2",
+ "decoded_samples": 181500,
+ "duration_difference_s": 0.0,
+ "pilots": [
+ {
+ "center_s": 2.3,
+ "offset_s": 1.1906356061568398e-08,
+ "correlation": 0.9999946729800973
+ },
+ {
+ "center_s": 18.7,
+ "offset_s": -7.504538506845514e-09,
+ "correlation": 0.999994408193669
+ },
+ {
+ "center_s": 39.2,
+ "offset_s": 1.3622036025890208e-08,
+ "correlation": 0.9999953504447623
+ }
+ ],
+ "max_absolute_offset_s": 1.3622036025890208e-08,
+ "end_to_start_drift_s": 1.71567996432181e-09,
+ "status": "passed"
+ },
+ {
+ "name": "mono-16k-no-xing",
+ "gapless_expected": false,
+ "encoded_sample_rate_hz": 16000,
+ "encoded_channels": 1,
+ "mp3_sha256": "5dedd3ae204dc6213d72fc84f3dd93ea1b7151f05b46297ea5240df0a2d39d14",
+ "decoded_samples": 181872,
+ "duration_difference_s": 0.093,
+ "pilots": [
+ {
+ "center_s": 2.3,
+ "offset_s": 0.06905087844050355,
+ "correlation": 0.9513595173048914
+ },
+ {
+ "center_s": 18.7,
+ "offset_s": 0.06905065503635927,
+ "correlation": 0.9488484497938505
+ },
+ {
+ "center_s": 39.2,
+ "offset_s": 0.06905116401412273,
+ "correlation": 0.9502509369412082
+ }
+ ],
+ "max_absolute_offset_s": 0.06905116401412273,
+ "end_to_start_drift_s": 2.855736191825775e-07,
+ "status": "diagnostic",
+ "limitation": "No gapless header: source sample zero is not recoverable from this MP3 alone."
+ }
+ ],
+ "elapsed_s": 2.1917175468988717,
+ "passed": true
+}
diff --git a/scripts/verify_methodology.py b/scripts/verify_methodology.py
new file mode 100644
index 0000000..2aabb89
--- /dev/null
+++ b/scripts/verify_methodology.py
@@ -0,0 +1,196 @@
+#!/usr/bin/env python3
+"""Measured codec and automatic-product acceptance checks; never fabricate a fix.
+
+Each invocation creates a new output directory. Codec checks establish only
+sample timing through the installed encoder/decoder, not location accuracy.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.metadata
+import json
+from pathlib import Path
+import platform
+import subprocess
+import sys
+import time
+
+import numpy as np
+from scipy import signal
+import soundfile as sf
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def sha256(path):
+ with Path(path).open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def write_json(path, value):
+ Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
+
+
+def provenance():
+ sources = list((ROOT / "src").rglob("*.py")) + [Path(__file__)]
+ return {
+ "git_commit": subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
+ ).strip(),
+ "working_tree": subprocess.check_output(
+ ["git", "status", "--porcelain"], cwd=ROOT, text=True
+ ).splitlines(),
+ "source_sha256": {str(p.relative_to(ROOT)): sha256(p) for p in sorted(sources)},
+ "python": sys.version,
+ "platform": platform.platform(),
+ "dependencies": {
+ name: importlib.metadata.version(name)
+ for name in ("numpy", "scipy", "soundfile")
+ },
+ "ffmpeg": subprocess.check_output(
+ ["ffmpeg", "-version"], text=True
+ ).splitlines()[0],
+ }
+
+
+def run_command(command, directory, name):
+ started = time.monotonic()
+ with (directory / f"{name}.stdout").open("wb") as stdout, (
+ directory / f"{name}.stderr"
+ ).open("wb") as stderr:
+ result = subprocess.run(command, stdout=stdout, stderr=stderr, check=False)
+ record = {
+ "command": list(map(str, command)),
+ "returncode": result.returncode,
+ "elapsed_s": time.monotonic() - started,
+ }
+ write_json(directory / f"{name}.command.json", record)
+ if result.returncode:
+ raise RuntimeError(f"{name} failed ({result.returncode}); see {name}.stderr")
+ return record
+
+
+def timing_offsets(reference, decoded, sample_rate_hz, centers_s, radius_s=0.25):
+ """Find independent pilot offsets; positive means decoded content is later.
+
+ A correlation floor prevents silence or unrelated decoded content from
+ being reported as a valid clock measurement.
+ """
+ radius = round(radius_s * sample_rate_hz)
+ offsets = []
+ for center in centers_s:
+ start = round((center - 0.75) * sample_rate_hz)
+ stop = round((center + 0.75) * sample_rate_hz)
+ if start < radius or stop + radius > len(decoded) or stop > len(reference):
+ raise ValueError("Decoded audio does not contain every complete timing pilot")
+ pilot = np.asarray(reference[start:stop], dtype=float)
+ observed = np.asarray(decoded[start - radius:stop + radius], dtype=float)
+ pilot -= pilot.mean()
+ observed -= observed.mean()
+ energy = np.dot(pilot, pilot)
+ if energy < 1e-12:
+ raise ValueError("Timing pilot has no usable signal")
+ correlation = signal.correlate(observed, pilot, mode="valid", method="fft")
+ energies = np.convolve(observed**2, np.ones(len(pilot)), mode="valid")
+ normalized = correlation / np.sqrt(np.maximum(energies * energy, 1e-30))
+ peak = int(np.argmax(normalized))
+ coefficient = float(normalized[peak])
+ if coefficient < 0.8 or peak in (0, 2 * radius):
+ raise ValueError("Timing pilot is absent, distorted, or outside the measured range")
+ offset = float(peak - radius)
+ a, b, c = correlation[peak - 1:peak + 2]
+ denominator = a - 2 * b + c
+ if denominator:
+ offset += float(0.5 * (a - c) / denominator)
+ offsets.append({"center_s": center, "offset_s": offset / sample_rate_hz,
+ "correlation": coefficient})
+ return offsets
+
+
+def decode(source, target, directory, name, sample_rate_hz=4000):
+ run_command(
+ ["ffmpeg", "-v", "error", "-nostdin", "-i", str(source),
+ "-ac", "1", "-ar", str(sample_rate_hz), "-f", "f32le", str(target)],
+ directory, name,
+ )
+ return np.fromfile(target, dtype="<f4")
+
+
+def codec_audit(output):
+ output.mkdir(parents=True, exist_ok=False)
+ began = time.monotonic()
+ rate = 24000
+ duration_s = 45.375
+ centers = [2.3, 18.7, 39.2]
+ t = np.arange(round(rate * duration_s)) / rate
+ rng = np.random.default_rng(902613)
+ # The nonperiodic pilots make a half-cycle or MP3-frame shift observable.
+ noise = signal.sosfilt(signal.butter(6, [150, 1300], fs=rate,
+ btype="bandpass", output="sos"),
+ rng.normal(size=len(t)))
+ envelope = sum(np.exp(-((t - center) / 0.45)**8) for center in centers)
+ channel = 0.08 * np.sin(2 * np.pi * (170 * t - 0.5 * t**2)) + noise * envelope
+ channel /= max(1.0, float(np.max(np.abs(channel))))
+ source = output / "timing-source.wav"
+ sf.write(source, np.column_stack((channel, 0.7 * channel)), rate, subtype="FLOAT")
+ reference = decode(source, output / "reference.f32", output, "reference-decode")
+ report = {
+ "schema_version": 1, "scope": "codec_timing_only",
+ "location_validation": False, "provenance": provenance(),
+ "source_sha256": sha256(source), "reference_sample_rate_hz": 4000,
+ "reference_samples": len(reference), "cases": [],
+ }
+ variants = [
+ ("mono-8k-cbr16", 8000, 1, ["-b:a", "16k"], True),
+ ("mono-16k-cbr32", 16000, 1, ["-b:a", "32k"], True),
+ ("stereo-44k-cbr96", 44100, 2, ["-b:a", "96k"], True),
+ ("stereo-48k-vbr", 48000, 2, ["-q:a", "4"], True),
+ ("mono-16k-no-xing", 16000, 1, ["-b:a", "32k", "-write_xing", "0"], False),
+ ]
+ for name, encoded_rate, channels, options, gapless_expected in variants:
+ row = {"name": name, "gapless_expected": gapless_expected,
+ "encoded_sample_rate_hz": encoded_rate, "encoded_channels": channels}
+ report["cases"].append(row)
+ try:
+ mp3 = output / f"{name}.mp3"
+ run_command(["ffmpeg", "-v", "error", "-nostdin", "-i", str(source),
+ "-ar", str(encoded_rate), "-ac", str(channels),
+ "-c:a", "libmp3lame", *options, str(mp3)], output, name + "-encode")
+ decoded = decode(mp3, output / f"{name}.f32", output, name + "-decode")
+ offsets = timing_offsets(reference, decoded, 4000, centers)
+ row.update({"mp3_sha256": sha256(mp3), "decoded_samples": len(decoded),
+ "duration_difference_s": (len(decoded) - len(reference)) / 4000,
+ "pilots": offsets,
+ "max_absolute_offset_s": max(abs(p["offset_s"]) for p in offsets),
+ "end_to_start_drift_s": offsets[-1]["offset_s"] - offsets[0]["offset_s"]})
+ if gapless_expected:
+ row["status"] = ("passed" if row["max_absolute_offset_s"] <= 0.002
+ and abs(row["duration_difference_s"]) <= 0.002 else "failed")
+ else:
+ row["status"] = "diagnostic"
+ row["limitation"] = "No gapless header: source sample zero is not recoverable from this MP3 alone."
+ except (RuntimeError, ValueError) as exc:
+ row.update(status="failed", error=str(exc))
+ write_json(output / "report.json", report)
+ report["elapsed_s"] = time.monotonic() - began
+ report["passed"] = all(row["status"] != "failed" for row in report["cases"])
+ write_json(output / "report.json", report)
+ print(json.dumps({"report": str(output / "report.json"), "passed": report["passed"],
+ "cases": [{k: r[k] for k in ("name", "status")} for r in report["cases"]]}))
+ return 0 if report["passed"] else 1
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+ codec = subparsers.add_parser("codec", help="Measure independent MP3 sample timing pilots")
+ codec.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ if args.command == "codec":
+ return codec_audit(args.output.resolve())
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_methodology_verifier.py b/tests/test_methodology_verifier.py
new file mode 100644
index 0000000..528982b
--- /dev/null
+++ b/tests/test_methodology_verifier.py
@@ -0,0 +1,37 @@
+"""Negative controls for the external timing acceptance measurement."""
+import importlib.util
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+
+spec = importlib.util.spec_from_file_location(
+ "methodology_verifier", Path(__file__).parents[1] / "scripts/verify_methodology.py"
+)
+verifier = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(verifier)
+
+
[email protected]("shift", [-70, 0, 83])
+def test_timing_pilots_recover_inserted_delay(shift):
+ rate = 4000
+ reference = np.random.default_rng(441).normal(0, 0.1, rate * 10)
+ decoded = np.roll(reference, shift)
+ measured = verifier.timing_offsets(reference, decoded, rate, [2, 5, 8])
+ assert all(abs(row["offset_s"] - shift / rate) < 1 / rate for row in measured)
+
+
+def test_unrelated_or_silent_audio_cannot_pass_timing():
+ reference = np.random.default_rng(441).normal(0, 0.1, 40000)
+ unrelated = np.random.default_rng(442).normal(0, 0.1, 40000)
+ with pytest.raises(ValueError, match="absent, distorted"):
+ verifier.timing_offsets(reference, unrelated, 4000, [2, 5, 8])
+ with pytest.raises(ValueError, match="no usable signal"):
+ verifier.timing_offsets(np.zeros(40000), unrelated, 4000, [2, 5, 8])
+
+
+def test_truncated_decode_cannot_pass_timing():
+ reference = np.random.default_rng(441).normal(0, 0.1, 40000)
+ with pytest.raises(ValueError, match="every complete timing pilot"):
+ verifier.timing_offsets(reference, reference[:20000], 4000, [2, 5, 8])