Skip to content

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

Capture public-camera audio while preserving source timing (#3)

Cinna Davisd7741a692488
diff --git a/docs/verification/PUBLIC_CAMERA_BENCHMARK.md b/docs/verification/PUBLIC_CAMERA_BENCHMARK.md
new file mode 100644
index 0000000..d8af440
--- /dev/null
+++ b/docs/verification/PUBLIC_CAMERA_BENCHMARK.md
@@ -0,0 +1,62 @@
+# Public-camera audio benchmarks
+
+The user requested real-audio benchmarks from public webcams, beginning with
+[EarthCam Times Square Street Cam](https://www.earthcam.com/usa/newyork/timessquare/?cam=tsstreet).
+Capture audio with a new output directory:
+
+```bash
+python scripts/capture_camera_audio.py \
+ --page 'https://www.earthcam.com/usa/newyork/timessquare/?cam=tsstreet' \
+ --camera tsstreet --duration-s 300 \
+ --output results/public-camera-timesquare-new
+```
+
+The tool uses the page's normal public HLS stream and saves MP3 audio plus a
+capture receipt. It records source/playlist hashes, source segment timing if
+provided, fetch and capture UTC, decoded duration, media hashes, implementation
+hash and the provider's map marker. Transient stream query parameters are omitted
+from the receipt. The local decoder log can contain expiring URLs and stays out
+of Git.
+
+The provider's map marker is an evaluation reference, with unquantified physical
+uncertainty. It must not enter detection or search inputs. Capture UTC and HTTP
+Date are receipt times. The tool leaves recording-start UTC unestablished, even
+when a broadcaster supplies segment dates, until the first captured audio sample
+is bound to that source clock with a defensible uncertainty.
+
+## Preserve the source timeline
+
+An audio-only FFmpeg transcode can discard a delay between the source video and
+audio streams. A controlled eight-second MPEG-TS fixture with a tone starting at
+two seconds becomes approximately six seconds long, with the tone near zero.
+Adding a resampler alone does not restore that offset on the tested FFmpeg 6.1.1.
+
+The capture command keeps source timestamps, rebases the mapped audio/video clock
+together, pads timestamp gaps in audio, and copies video packets to a null output.
+No video file is saved. Its regression preserves eight seconds and a tone onset
+within 5 ms of two seconds. The tool measures decoded MP3 duration rather than
+counting codec padding as sound; a duration discrepancy above 50 ms produces
+`partial_capture`, preserving the clip and receipt.
+
+## Verification scope
+
+The Times Square metadata advertises audio and supplies a map marker at
+40.75941552728725, -73.98521661758423. The inspected live HLS playlist contains no
+`EXT-X-PROGRAM-DATE-TIME`, and the sampled video frame contains no visible clock
+overlay. Neither a microphone-coordinate error bound nor source-to-receiver
+latency was established.
+
+The initial preserved audio-only prototype requested 300 s and produced
+295.296 s of decoded audio, SHA256
+`fb8be2a1ef326392734eb1a94cd3ab44acd4b9540266f377a5946c8c15b21789`.
+Automatic analysis at product source `53fefe67425bb9e83ce1fa4c743500e9843c01d1`
+used the complete opaque-named MP3, with no event windows, bands, aircraft IDs,
+camera coordinate or recording-clock guess. It found zero supported proposals
+and returned `needs_input / recording_time_required`. This is an observed
+discovery/abstention outcome, not a labelled aircraft-negative or location test.
+
+A corrected live 12-second capture decoded to exactly 12.0 s. The corrected
+five-minute capture and its complete automatic outcome will be added after the
+run finishes. Preserve every capture, processing failure and inconclusive result;
+do not select only clips that return a coordinate. Current-day historical flight
+archives may not yet exist, which is a separate data-availability limitation.
diff --git a/scripts/capture_camera_audio.py b/scripts/capture_camera_audio.py
new file mode 100644
index 0000000..8c9c6b9
--- /dev/null
+++ b/scripts/capture_camera_audio.py
@@ -0,0 +1,223 @@
+"""Capture public webcam audio with explicit clock and map-reference provenance.
+
+EarthCam pages expose their normal public HLS URL in json_base. This tool uses
+that URL without credentials. Captured bytes, HTTP/capture times and broadcaster
+segment timestamps are distinct; absent segment timestamps never become UTC.
+"""
+import argparse
+from datetime import datetime, timedelta, timezone
+import hashlib
+import json
+import math
+import os
+from pathlib import Path
+import re
+import signal
+import subprocess
+import time
+from urllib.parse import urljoin, urlsplit, urlunsplit
+from urllib.error import HTTPError
+from urllib.request import Request, urlopen
+
+
+def utc_now():
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def sha256(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def public_stream_url(url):
+ """Exclude transient stream authorization queries from published receipts."""
+ parts = urlsplit(url)
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
+
+
+def fetch(url, referer):
+ started = utc_now()
+ request = Request(url, headers={"User-Agent": "Mozilla/5.0", "Referer": referer})
+ with urlopen(request, timeout=30) as response:
+ data = response.read(8 * 1024 * 1024 + 1)
+ if len(data) > 8 * 1024 * 1024:
+ raise ValueError("Metadata response exceeds 8 MiB")
+ return data, {"started_utc": started, "finished_utc": utc_now(),
+ "http_status": response.status, "http_date": response.headers.get("Date"),
+ "sha256": sha256(data), "bytes": len(data)}
+
+
+def earthcam_metadata(html, camera):
+ match = re.search(r"\bvar\s+json_base\s*=\s*", html)
+ if not match:
+ raise ValueError("Page does not expose EarthCam json_base metadata")
+ value, _ = json.JSONDecoder().raw_decode(html[match.end():])
+ selected = value["cam"][camera]
+ if str(selected.get("hasaudio", "")).lower() != "true":
+ raise ValueError("Selected camera does not advertise audio")
+ stream = selected.get("stream")
+ if not stream or urlsplit(stream).scheme not in {"http", "https"}:
+ raise ValueError("Selected camera has no public HTTP stream")
+ return selected
+
+
+def media_segments(text, base_url):
+ """Keep broadcaster PDT only across contiguous, timed HLS segments."""
+ timestamp = None
+ duration = None
+ sequence = 0
+ segments = []
+ for line in text.splitlines():
+ line = line.strip()
+ if line.startswith("#EXT-X-MEDIA-SEQUENCE:"):
+ sequence = int(line.partition(":")[2])
+ elif line.startswith("#EXT-X-DISCONTINUITY"):
+ # DISCONTINUITY-SEQUENCE is a counter, not a new boundary.
+ if line == "#EXT-X-DISCONTINUITY":
+ timestamp = None
+ elif line.startswith("#EXT-X-PROGRAM-DATE-TIME:"):
+ raw = line.partition(":")[2]
+ timestamp = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ if timestamp.tzinfo is None:
+ raise ValueError("HLS program timestamp has no timezone")
+ timestamp = timestamp.astimezone(timezone.utc)
+ elif line.startswith("#EXTINF:"):
+ duration = float(line.partition(":")[2].split(",")[0])
+ if not math.isfinite(duration) or duration <= 0:
+ raise ValueError("Invalid HLS segment duration")
+ elif line and not line.startswith("#"):
+ if duration is None:
+ raise ValueError("Media URI lacks EXTINF duration")
+ segments.append({"sequence": sequence, "url": public_stream_url(urljoin(base_url, line)),
+ "duration_s": duration,
+ "broadcaster_start_utc": timestamp.isoformat().replace("+00:00", "Z") if timestamp else None})
+ sequence += 1
+ if timestamp is not None:
+ timestamp += timedelta(seconds=duration)
+ duration = None
+ return segments
+
+
+def decoder_command(stream, page_url, audio_path, duration_s):
+ command = ["ffmpeg", "-hide_banner", "-loglevel", "warning", "-copyts", "-start_at_zero"]
+ if urlsplit(stream).scheme in {"http", "https"}:
+ command += ["-rw_timeout", "15000000", "-user_agent", "Mozilla/5.0",
+ "-headers", f"Referer: {page_url}\r\n"]
+ return command + ["-i", str(stream), "-t", str(duration_s), "-map", "0:a:0", "-vn",
+ "-ac", "1", "-ar", "16000", "-af", "aresample=async=1:first_pts=0",
+ "-c:a", "libmp3lame", "-b:a", "64k", str(audio_path),
+ # Keeping video mapped prevents ffmpeg from rebasing input
+ # time to the first audio packet and discarding an A/V delay.
+ # Copying to null retains its clock without saving video.
+ "-t", str(duration_s), "-map", "0:v:0", "-c:v", "copy", "-an", "-f", "null", os.devnull]
+
+
+def decoded_duration(path):
+ command = ["ffmpeg", "-v", "error", "-i", str(path), "-map", "0:a:0", "-ac", "1",
+ "-ar", "16000", "-f", "f32le", "pipe:1"]
+ with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as process:
+ count = 0
+ while block := process.stdout.read(1024 * 1024):
+ count += len(block)
+ if process.wait() != 0 or count % 4:
+ raise ValueError("Captured MP3 cannot be decoded to complete float32 samples")
+ return count / (4 * 16000)
+
+
+def capture(page_url, camera, output, duration_s):
+ output = Path(output).resolve()
+ output.mkdir(parents=True, exist_ok=False)
+ receipt = {"schema_version": 1, "source_page": page_url, "camera": camera,
+ "requested_duration_s": duration_s, "status": "failed",
+ "recording_start_utc": None, "recording_clock_established": False,
+ "truth_used_for_event_detection": False, "location_validation_eligible": False,
+ "implementation_sha256": sha256(Path(__file__).read_bytes())}
+ try:
+ page, receipt["page_fetch"] = fetch(page_url, page_url)
+ metadata = earthcam_metadata(page.decode(), camera)
+ stream = metadata["stream"]
+ receipt["camera_name"] = metadata.get("name")
+ receipt["stream_url"] = public_stream_url(stream)
+ receipt["stream_url_sha256"] = sha256(stream.encode())
+ receipt["provider_map_reference"] = {
+ "lat": float(metadata["map_lat"]), "lon": float(metadata["map_long"]),
+ "kind": "provider_map_marker", "uncertainty_m": None,
+ "source": page_url, "timezone": metadata.get("timezone")}
+ master, receipt["playlist_fetch"] = fetch(stream, page_url)
+ playlist_url = stream
+ playlist = master.decode()
+ if "#EXT-X-STREAM-INF:" in playlist:
+ variant = next(line.strip() for line in playlist.splitlines()
+ if line.strip() and not line.startswith("#"))
+ playlist_url = urljoin(stream, variant)
+ body, receipt["media_playlist_fetch"] = fetch(playlist_url, page_url)
+ playlist = body.decode()
+ receipt["initial_media_segments"] = media_segments(playlist, playlist_url)
+ receipt["broadcaster_segment_clock_present"] = any(
+ segment["broadcaster_start_utc"] for segment in receipt["initial_media_segments"])
+ receipt["clock_limitations"] = [
+ "Capture/HTTP times are receipt times, not microphone sample-zero UTC.",
+ "A map marker does not establish a surveyed microphone coordinate or uncertainty.",
+ "Broadcaster segment timestamps, if present, still require binding to the first captured audio sample."]
+ command = decoder_command(stream, page_url, output / "audio.mp3", duration_s)
+ receipt["audio_timeline"] = "source A/V timestamps, rebased together; audio gaps may be padded by aresample"
+ receipt["decoder_command_redacted"] = [
+ public_stream_url(value) + "?[query omitted]" if value == stream else value for value in command]
+ receipt["ffmpeg_version"] = subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0]
+ # The complete URL stays in memory and the local ignored decoder log;
+ # published metadata retains its hash and a URL without transient query.
+ receipt["capture_started_utc"] = utc_now()
+ began = time.monotonic()
+ with (output / "decoder.log").open("wb") as log:
+ process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ try:
+ receipt["decoder_exit_code"] = process.wait(timeout=duration_s + 90)
+ except subprocess.TimeoutExpired:
+ receipt["timed_out"] = True
+ os.killpg(process.pid, signal.SIGTERM)
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait()
+ receipt["decoder_exit_code"] = process.returncode
+ receipt["capture_finished_utc"] = utc_now()
+ receipt["capture_elapsed_s"] = time.monotonic() - began
+ audio = output / "audio.mp3"
+ if audio.is_file():
+ receipt["audio"] = {"path": "audio.mp3", "bytes": audio.stat().st_size,
+ "sha256": sha256(audio.read_bytes())}
+ if receipt["decoder_exit_code"] == 0 and receipt.get("audio", {}).get("bytes", 0) > 0:
+ receipt["audio_probe"] = json.loads(subprocess.check_output([
+ "ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_name,sample_rate,channels",
+ "-of", "json", str(audio)], text=True, timeout=20))
+ actual_duration = decoded_duration(audio)
+ receipt["decoded_duration_s"] = actual_duration
+ receipt["status"] = "captured" if abs(actual_duration - duration_s) <= 0.05 else "partial_capture"
+ except Exception as exc:
+ # URLs in provider exceptions can contain expiring access queries.
+ receipt["error_type"] = type(exc).__name__
+ if isinstance(exc, HTTPError):
+ receipt["http_error_status"] = exc.code
+ receipt["error"] = "Capture failed; inspect local source/decoder evidence."
+ (output / "capture.json").write_text(json.dumps(receipt, indent=2, allow_nan=False) + "\n")
+ return receipt
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--page", required=True)
+ parser.add_argument("--camera", required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--duration-s", type=float, default=300)
+ args = parser.parse_args(argv)
+ if not math.isfinite(args.duration_s) or not 0 < args.duration_s <= 3600:
+ parser.error("--duration-s must be finite and between 0 and 3600")
+ if urlsplit(args.page).scheme not in {"http", "https"} or "\n" in args.page or "\r" in args.page:
+ parser.error("--page must be an HTTP URL without header control characters")
+ receipt = capture(args.page, args.camera, args.output, args.duration_s)
+ print(json.dumps(receipt, indent=2, allow_nan=False))
+ return 0 if receipt["status"] == "captured" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_camera_capture.py b/tests/test_camera_capture.py
new file mode 100644
index 0000000..9901829
--- /dev/null
+++ b/tests/test_camera_capture.py
@@ -0,0 +1,100 @@
+"""Live capture metadata must not invent recording clocks or retain URL tokens."""
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+
+spec = importlib.util.spec_from_file_location(
+ "capture_camera_audio", Path(__file__).resolve().parents[1] / "scripts/capture_camera_audio.py")
+capture = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(capture)
+
+
+def test_untimed_live_segments_stay_without_a_recording_clock():
+ playlist = "#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:42\n#EXTINF:6.1,\na.ts?t=secret\n#EXTINF:6,\nb.ts\n"
+ segments = capture.media_segments(playlist, "https://example.org/live/playlist.m3u8?token=secret")
+ assert [row["sequence"] for row in segments] == [42, 43]
+ assert all(row["broadcaster_start_utc"] is None for row in segments)
+ assert segments[0]["url"] == "https://example.org/live/a.ts"
+
+
+def test_broadcaster_clock_propagates_by_segment_duration_and_resets_at_a_gap():
+ playlist = """#EXTM3U
+#EXT-X-DISCONTINUITY-SEQUENCE:8
+#EXT-X-PROGRAM-DATE-TIME:2026-11-02T19:49:23-05:00
+#EXTINF:6.1,
+a.ts
+#EXTINF:6,
+b.ts
+#EXT-X-DISCONTINUITY
+#EXTINF:6,
+c.ts
+#EXT-X-PROGRAM-DATE-TIME:2026-11-03T00:50:00Z
+#EXTINF:6,
+d.ts
+"""
+ segments = capture.media_segments(playlist, "https://example.org/live/")
+ assert [row["broadcaster_start_utc"] for row in segments] == [
+ "2026-11-03T00:49:23Z", "2026-11-03T00:49:29.100000Z", None, "2026-11-03T00:50:00Z"]
+
+
[email protected]("line", ["#EXTINF:nan,", "#EXTINF:-1,", "#EXTINF:inf,"])
+def test_invalid_media_duration_is_rejected(line):
+ with pytest.raises(ValueError, match="duration"):
+ capture.media_segments(f"#EXTM3U\n{line}\na.ts\n", "https://example.org/")
+
+
+def test_naive_program_timestamp_is_rejected():
+ with pytest.raises(ValueError, match="timezone"):
+ capture.media_segments("#EXT-X-PROGRAM-DATE-TIME:2026-11-03T00:50:00\n", "https://example.org/")
+
+
+def test_public_page_metadata_is_json_not_executed_javascript():
+ camera = {"hasaudio": "true", "stream": "https://example.org/p.m3u8?t=secret"}
+ page = '<script>var json_base = ' + json.dumps({"cam": {"test": camera}}) + '; throw Error("do not run");</script>'
+ assert capture.earthcam_metadata(page, "test") == camera
+ assert capture.public_stream_url(camera["stream"]) == "https://example.org/p.m3u8"
+ camera["hasaudio"] = "false"
+ with pytest.raises(ValueError, match="audio"):
+ capture.earthcam_metadata('var json_base=' + json.dumps({"cam": {"test": camera}}), "test")
+
+
+def test_failed_http_capture_retains_status_and_no_false_clock(tmp_path, monkeypatch):
+ from urllib.error import HTTPError
+
+ def unavailable(*args):
+ raise HTTPError("https://example.org/?token=secret", 503, "unavailable", {}, None)
+
+ monkeypatch.setattr(capture, "fetch", unavailable)
+ output = tmp_path / "receipt"
+ receipt = capture.capture("https://example.org/", "test", output, 1)
+ assert receipt["status"] == "failed"
+ assert receipt["http_error_status"] == 503
+ assert receipt["recording_start_utc"] is None
+ assert receipt["recording_clock_established"] is False
+ assert "secret" not in (output / "capture.json").read_text()
+
+
+def test_real_transcode_keeps_audio_delay_relative_to_source_video(tmp_path):
+ import subprocess
+ import numpy as np
+
+ source = tmp_path / "delayed-audio.ts"
+ subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i",
+ "color=c=black:s=160x90:r=10:d=8", "-itsoffset", "2", "-f", "lavfi", "-i",
+ "sine=frequency=440:sample_rate=16000:duration=6", "-map", "0:v", "-map", "1:a",
+ "-c:v", "mpeg2video", "-c:a", "aac", "-f", "mpegts", str(source)], check=True)
+ output = tmp_path / "preserved.mp3"
+ subprocess.run(capture.decoder_command(str(source), "", output, 8), check=True,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ raw = subprocess.check_output(["ffmpeg", "-v", "error", "-i", str(output), "-f", "f32le",
+ "-ac", "1", "-ar", "16000", "pipe:1"])
+ samples = np.frombuffer(raw, dtype="<f4")
+ assert capture.decoded_duration(output) == 8
+ # Ordinary audio-only extraction rebases this tone to ~0 s and shortens the
+ # result to ~6 s. Preserve its independent two-second source-timeline offset.
+ assert np.max(np.abs(samples[:int(1.8 * 16000)])) < 0.001
+ onset = np.flatnonzero(np.abs(samples) > 0.03)[0] / 16000
+ assert onset == pytest.approx(2, abs=0.005)