Compare commits

...

54 Commits

Author SHA1 Message Date
bsncubed 02c02a821d Added factory reset todo item
Added factory reset todo item
2026-09-27 22:19:42 +10:00
bsncubed 41103e3b5e Licences: MIT for the AES67 core and web page, GPL-3.0 for the rest
- LICENSE (GPL-3.0) at the root; an MIT LICENSE in each components/aes67_*
  and in web/, so they travel with the code when reused.
- THIRD_PARTY.md: third-party code and licences, and the known conflict of
  the Espressif binary audio libraries with GPL-3.0 (firmware contains cspot).
- CLAUDE.md: rule to keep GPL code out of the core; phase 2 item to replace
  the Espressif binaries (opencore-aacdec, Speex resampler).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 08:37:38 +10:00
bsncubed c641671d24 CLAUDE.md: AirPlay 1 source check (licences, what to take, caveats)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 08:34:19 +10:00
bsncubed 4c16686c6b CLAUDE.md: phase 2 gets clock-drift correction and AirPlay 1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 08:27:04 +10:00
bsncubed fd30ac3eb1 CLAUDE.md: autoplay off the to-do list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 08:51:33 +10:00
bsncubed e2721d6bd1 CLAUDE.md: step 8 status (mono sum, gain, polish done so far), step 6 roles
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 08:48:46 +10:00
bsncubed d4aa9c7be1 PTP status: 2-min average offset, details split; uptime as d/h/m/s
- Firmware: status.ptp.offset_avg_ns = mean |offset| over the last 2 min
  (one bucket per second, cleared on a clock step).
- Main panel: Time Offset (2 min avg) shows only the Bolero bracket of the
  average. Details: the current offset (coloured by the same brackets),
  hops, time/frequency traceable, version and own clock class.
- Uptime shown as "1d 2h 3m 4s".
- Preset buttons renamed: "Riedel PTP defaults", "AES67 Media PTP defaults".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 08:32:15 +10:00
bsncubed 5f27262b27 PTP: drop the "Preferred TimeTransmitter" role
It behaved exactly like auto (clock class 248); the only difference was a
priority1 suggestion in the page. Roles are now slave|auto; to prefer this
device, use auto with a low priority1. A stored "master" is converted to
auto at boot (new cfg_set_string, like cfg_set_number).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:58:26 +10:00
bsncubed ee03d9f9f1 PTP: hardware timestamping is not a setting any more
The hw_ts config key was never read (hardware timestamps are always used);
the checkbox suggested it could be turned off. Removed from the config,
the page and the docs; status.ptp.hw_ts still reports it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:55:54 +10:00
bsncubed ec65374e8d Web UI: firmware table without build date, project and ESP-IDF
Only version, slots and state are shown; GET /api/ota still reports them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:54:28 +10:00
bsncubed 214d6b2c29 Firmware version: <version.txt>-<git short hash>, starting at 0.0.1
e.g. 0.0.1-1d613b1: the first part is set by hand, the hash says which
commit was built. No dirty flag (the build always patches cspot).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:52:23 +10:00
bsncubed 1d613b16c1 Firmware version from version.txt (0.9.0) instead of git describe
The version is now set by hand in version.txt, so it's readable and only
changes on purpose. git describe gave commit hashes, and always "-dirty"
because the build applies patches to the cspot submodule. Editing the file
is enough; the next build picks it up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:41:53 +10:00
bsncubed 05f4ce45c3 48 kHz only: drop 96 kHz from the AES67 output
All sources (player, test signals) are 48 kHz; at 96 kHz Spotify and HLS
played at the wrong speed. Validation, the page and the docs allow 48000
only, and a 96000 stored before is reset to 48000 at boot (stored values
aren't re-validated, and the SDP would still have said 96 kHz).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:30:39 +10:00
bsncubed 62b32c31ff Docs: end-user guide; README brought up to date
docs/user-guide.md covers setup, the web page, sources and failover, the
Spotify developer app, AES67 output and SDP/SAP, PTP presets, network and
static IP, logging, firmware updates (OTA and USB), the player API,
troubleshooting and known limitations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:26:52 +10:00
bsncubed 5d1627f8d0 tools/flash_board.py: flash another board over USB and give it its own identity
Picks the port, checks ESP32-P4 / chip revision against the image header /
32 MB flash, optionally erases, writes the images from build/flash_args,
reads the boot log for the IP and sets hostname, stream/Spotify name and
multicast address over the API. All questions also work as options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:19:01 +10:00
bsncubed d744a36275 Web UI: dark by default with a light/dark toggle; fix hidden labels
The page starts dark regardless of the system setting; the toggle at the top
right switches to light and is remembered in the browser. [hidden] now
always wins: label{display:block} had overridden it, so the hidden VLAN
split checkbox still showed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 07:16:04 +10:00
bsncubed b2c5496057 Web UI: hide the VLAN split option until it is implemented
The firmware doesn't apply the VLAN split yet (phase 2). The checkbox is
hidden, which also keeps the internet-interface fields and "Web UI / API on"
hidden; the markup stays for phase 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 00:04:46 +10:00
bsncubed b36419477c Network: static IP addressing
net.dhcp = false applies ip/mask/gw/dns on link up (DHCP client stopped).
PTP/TX/SAP sockets are bound to the address, so a changed IP setup reboots
the device; with DHCP on, the static fields (UI fills them with the lease)
don't count as a change. Validation: contiguous netmask, not the network or
broadcast address, gateway in the subnet. The page follows the device to the
new address after saving. Checked: DHCP -> static .245 (PTP, TX, SAP, SDP
origin, mDNS on the new address) -> DHCP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 00:01:34 +10:00
bsncubed c4468c4af0 Network: status reports mask/gw/dns; UI shows the DHCP lease in the static fields
With DHCP on, the greyed-out IP/netmask/gateway/DNS fields show the
addresses in use. Unticking DHCP keeps them as the starting point for a
static setup. (Static addressing itself is not applied yet.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:42:35 +10:00
bsncubed 122e46e862 Pink noise as a source (mode "pink")
Core: aes67_tx_pink_noise(), a ready-made TX source: xorshift32 white noise
through Paul Kellet's pink filter, -18 dBFS RMS (peaks about -6 dBFS), same
on L and R. The player uses it like the tone (straight to TX, no volume or
gain). Checked on the board: -18 dBFS RMS, octave bands 63 Hz-4 kHz flat
within +-0.4 dB, L = R.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:37:05 +10:00
bsncubed bbeb7d3fd2 Player: apply source.gain_db as a fixed trim on top of the volume
It was in the config and UI but never applied. The gain now saturates at
full scale (the trim boosts up to +12 dB). Checked on HLS: -12 dB lowers
the peak by exactly 12 dB, +12 dB clips cleanly at 0 dBFS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:29:40 +10:00
bsncubed c9e06da47c aes67_tx: mono sum; the source always delivers stereo
The pull callback's contract said "stream channels", but the player always
delivers stereo, so a 1-channel stream went out as L,R,L,R at half speed.
Sources now always deliver AES67_TX_SRC_CHANNELS (2); TX maps to the stream:
2 ch as is, 1 ch = (L+R)/2 in 64 bit with mono_sum (can't clip), else L.
Checked: mono packets 156 B, 1000/s, 48 samples each, SDP L24/48000/1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:26:48 +10:00
bsncubed faf427c897 Web UI: sticky save bar; drop the Force source dropdown
Save/Revert/Reboot and the status message stay at the bottom of the window
while the settings form is in view. The runtime source override stays in
the API (listed in the page's API box) but is no longer on the page, where
it duplicated the saved source mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:20:41 +10:00
bsncubed e5c3c0ad8a Player: runtime source override and play-a-URL on /api/player
The player now owns the effective mode (config or override) and passes it
down: spotify_apply(enable) and hls_set_url(url) instead of both reading
source.mode from the config. /api/player/source forces spotify|hls|off
(config returns to the saved mode), /api/player/url plays an m3u8 now;
neither is saved. GET reports it in `forced`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:15:38 +10:00
bsncubed fd88e02e96 Web UI: player progress bar with seek
Follows /api/player's position, moves on locally between polls while
playing, seeks on release; disabled when the source can't seek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:07:39 +10:00
bsncubed a55a3ce14a Player: seek and volume on /api/player
seek {ms} runs on the Spotify session task like a seek from the app (buffer
flushed, app notified). volume {value}|{delta} sets the player volume and
pushes it to the session, so the app's slider follows; setRemoteVolume now
also runs on the session task.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 23:04:11 +10:00
bsncubed 8485ecb5b7 Player: transport commands on /api/player
play/pause/toggle/stop/next/prev. Spotify commands run on the session task
(same thread as cspot's frame handling) and the POST waits until they ran,
so it answers the new state. HLS pause stops fetching and resume rejoins at
the live edge; next/prev on HLS and anything on tone/off return 409.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 22:59:14 +10:00
bsncubed 9e1ca98a5d Player: GET /api/player with Spotify now-playing info
Source, state, artist/title/album, position and duration (from cspot's
playback state, so it matches the app), volume and `can`. cspot patch 0004
adds read getters for the playback state and context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 22:48:00 +10:00
bsncubed c6ecbbeb25 Player: auto mode fails over between Spotify and HLS
No Spotify session (or paused, with failover_on_pause) for failover_delay_s
switches to HLS; Spotify playing switches back within ~1 s. Switches fade
out/in over 30 ms and flush the ring. HLS is suspended while Spotify plays.
cspot is held back instead of drained while it isn't Spotify's turn: it keeps
decoding on pause, so dropping its frames let it race through the queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 22:36:11 +10:00
bsncubed 78c480a7c2 CLAUDE.md: Spotify status after the connection fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 20:47:39 +10:00
bsncubed b8702e6faa Spotify: tell cspot when a new track becomes audible
The Mac dropped the device soon after the first track change: we never
called SpircHandler::notifyAudioReachedPlayback(), so cspot's queue did
not advance and the state sent to Spotify stalled.
- The data callback records a boundary (output write position, track
  id) when the track id changes; the session loop (<= 200 ms) calls
  notifyAudioReachedPlayback(id) once playback (ring read position)
  passes it, and notifyAudioEnded() after DEPLETED once the buffer is
  empty. PLAYBACK_START clears boundaries (next data is a new one),
  seek/flush drop pending ones.
- audio_ring exposes its write/read frame counters (wrap-safe compare).
- Verified: 10 min on the Mac without a disconnect, every track change
  notified ("track audible, Spotify notified"), app shows the playing
  track (switches up to ~3-5 s early), 0 underruns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 20:47:28 +10:00
bsncubed 5ce4588c80 cspot: delayed Pong (like librespot) stops the 6-minute connection resets
The Spotify AP reset the connection (recv -1, errno 104 ECONNRESET) on
the third Ping, every 6 minutes, like clockwork. cspot answered each
Ping at once; librespot (core/src/session.rs) waits 60 s:
Ping -> 60 s -> Pong -> PongAck -> 60 s -> Ping.
- 0003-delayed-pong: record the Ping, send the Pong 60 s later from
  triggerTimeout() (called on every 3 s receive timeout), through the
  PR #3 connection snapshot; dropped on reconnect.
- 0002-diag-log-recv-errors: log recv's return value/errno before
  "Error in read" (error path only); this is what showed the RST.
Verified: over 8+ minutes Ping/delayed Pong/PongAck every 2 min, no
reset at the 6-minute mark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 20:47:27 +10:00
bsncubed 8008aa175f cspot: patch in philippe44/cspot PR #3 (crash when a request races a reconnect)
MercurySession::reconnect() nulls conn/shanConn (for 5 s per failed
retry) while other tasks keep sending through them: a NULL dereference,
not a catchable exception. Our Spotify sessions are dropped by the
server and reconnect every ~6 minutes, so this race is hit regularly;
likely behind the sporadic resets during long sessions/OTA.
Patch applies cleanly to the pinned 3010349; builds, boots, confirmed.
Drop it once the fix is in the pinned cspot commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 20:17:01 +10:00
bsncubed f0fe53d5d1 Spotify: end the session for OTA; app volume starts at the player's
- OTA: the player now ends the Spotify session (spotify_suspend: stop
  flag, waits until the session's tasks are gone, refuses new ones)
  instead of pausing it, and suspends HLS. Pausing was not enough (an
  upload still failed once with a paused session). Verified twice with a
  session running for minutes: "Disconnecting mercury session / session
  ended / suspended", installed in ~26 s, clean reboot.
- Volume: createFromBlob() starts cspot at volume 0, which the app
  showed while we played at 100 %. The session now starts with the
  player's volume (spotify_set_volume); volumes coming from the app are
  stored exactly, without echo. Verified: slider starts at 100 %.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 20:15:29 +10:00
bsncubed 0aac7bc339 Spotify follows source mode, name and credentials live
- spotify_init() sets up the logger, zeroconf routes and session task
  once; spotify_apply() (at boot and on every source save) enables or
  disables: enabled = mode spotify/auto + credentials. Disable removes
  the mDNS entry, zeroconf answers 404 and a running session ends
  (loop exits within 200 ms, SpircHandler::disconnect stops the queue
  and player tasks). A new device name ends the session and
  re-advertises. The login blob is swapped under a mutex.
- Verified: hls/spotify/rename switch the mDNS entry and /spotify_info
  (404/200) live; switching to hls during Spotify playback ended the
  session in < 2 s, HLS played after ~5 s, internal heap 221 -> 365 KB
  (cspot frees everything).
- CLAUDE.md: OTA-with-session findings (intermittent, flash-write stalls
  seen as TX resyncs during uploads), serial-port reset caveat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 19:43:16 +10:00
bsncubed 8ba4de5eda OTA: quiet the audio sources during a firmware upload
An upload during an active Spotify session crawled (~10 kB/s, 197 s)
and ended in a reset (seen twice). Workaround:
- aes67_ota_on_update(cb): cb(true) right before an accepted upload
  writes flash, cb(false) if it then fails.
- The player pauses Spotify (spotify_pause -> SpircHandler::setPause, the
  app follows) and suspends HLS fetching (hls_suspend); resumed if the
  upload fails. AES67 TX keeps running (silence).
- Verified: upload during Spotify playback paused the session and
  installed in 25.8 s (normal for 2 MB), clean reboot and self-test.
  Root cause still open (noted in CLAUDE.md with the other cspot items).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 19:02:03 +10:00
bsncubed cd747aec40 Step 7.5b4a: player volume (Spotify app slider), applied after the ring
- player: volume 0..100 %, amplitude = (v/100)^3 (about -18 dB at 50 %,
  0 = mute), applied in the TX pull callback after the ring so a change
  is heard at once (the ring holds 4 s); ramped over one packet to avoid
  zipper noise. Spotify VOLUME events (0..65535) set it.
- Docs: pipeline order ring -> volume/gain, curve described.
- Verified from a Mac: RMS followed the slider immediately (100 % about
  -10 dBFS; steps to about -24.5 and -28 dBFS match the cubic curve for
  ~57 % / ~50 %); user: "sounds about right". Mute at 0 % not yet
  confirmed (check via /api/player/volume later).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:52:57 +10:00
bsncubed 4a38254660 Step 7.5b3b: Spotify audio on AES67
- spotify_init(pcm_cb, event_cb): cspot's data callback hands 44.1 kHz
  stereo s16 PCM to the player and returns what was taken; the player's
  blocking ring write paces decoding to playback speed.
- Events: FLUSH/SEEK/PLAYBACK_START empty the ring (skip/seek sound at
  once); PLAY_PAUSE pauses output (silence, buffer kept, no underrun);
  VOLUME logged (applied in b4).
- player: Spotify via its own audio_out converter (44.1 -> 48 kHz);
  source_state playing / paused / buffering.
- Verified from a Mac: music on the AES67 stream (10 s: 0 gaps, no
  silent packets, RMS -9.6 dBFS, peak 0.0 dBFS), buffer 4.0 s full,
  0 underruns, pause/play/skip/seek events.
  Seen: first 3 connects "Can't connect to spotify servers", 4th worked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:41:49 +10:00
bsncubed 5b0d7c9ba4 Step 7.5b3a: per-source PCM converter (audio_out), shared by HLS and Spotify
- main/audio_out: one converter instance per source (own rate converter
  state): s16 any rate/channels -> 48 kHz stereo int32 -> ring.
- player_write(src, ...) only writes for the active source, drops the
  rest; player_src_t is public in player.h.
- HLS decoder uses audio_out (no behaviour change).
- Verified: HLS still sample exact (441344 -> 480375 frames per
  10.008 s segment), buffer ~4 s, 0 underruns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:34:15 +10:00
bsncubed c240ac9a3c Step 7.5b2: Spotify Connect zeroconf and login work (PCM counted only)
- Zeroconf on our httpd (GET/POST /spotify_info, form body URL-decoded)
  and _spotify-connect._tcp via our mDNS (VERSION, CPath, Stack TXT).
- Session task: waits for the app's login blob, connects with the
  user's client ID/secret and the configured bitrate (96/160/320 ->
  OGG_VORBIS_*), SpircHandler, events logged; cspot exceptions caught.
  Starts when source.mode is spotify/auto and credentials are set.
- bell::bellGlobalLogger was NULL: every CSPOT_LOG crashed the board
  right after addUser (Load access fault in Session.cpp:67 /
  LoginBlob.cpp:58). cspot/bell logs now go to esp_log (UART + syslog);
  signed CDN URL tokens are cut from the log.
- esp_audio_codec's own Vorbis decoder clashed with bell's Tremor
  symbols: CONFIG_AUDIO_DECODER_VORBIS_SUPPORT / SIMPLE_DEC_OGG off.
- status.spotify_state from the session (waiting / connecting /
  connected / login failed / error / disabled / no client credentials).
- Verified from a Mac: device appears, "connected as <user>", access
  token fetched with the user's client credentials, track info, audio
  key, CDN URL (the step broken upstream), PCM decoded. Without
  backpressure a track decodes in ~26 s (b3 feeds the ring).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 18:26:36 +10:00
bsncubed 039ec75473 Step 7.5b1: cspot (philippe44 fork) builds and links on the P4
- external/cspot: git submodule, pinned to philippe44/cspot 3010349
  (bell ed2d6e9); GPL-3.0.
- components/spotify: project component wrapping cspot. bell trimmed to
  what cspot needs (Tremor Vorbis; no codec wrapper, sinks, MQTT, web
  server, fmt, regex; cJSON from IDF). Xtensa biquad assembly filtered
  out (P4 is RISC-V). CMAKE_POLICY_VERSION_MINIMUM 3.5 for CMake 4.
- Patches in components/spotify/patches, applied at configure time:
  nanopb generator works with protobuf >= 5 (MakeClass removed);
  URLParser.cpp missing <cstdio>/<cstring> for GCC 14.
- CONFIG_COMPILER_CXX_EXCEPTIONS=y (cspot needs exceptions).
- spotify_init() only builds a LoginBlob (link check).
- CLAUDE.md: submodule init and IDF-venv Python packages for nanopb.
- Verified on board: "cspot linked: device "P4 AES67", zeroconf info 588
  bytes"; HLS still playing, PTP locked; image 1.83 MB (70% free).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:25:10 +10:00
bsncubed 7bbda0a1e8 Step 7.5a: Spotify client credentials in config/UI, write-only secrets
- Core config: cfg_mark_secret(group, key). GET /api/config returns ""
  for secret keys; a POST with "" keeps the stored value, null clears it;
  cfg_get() returns the real value. Documented in aes67-core-base.md.
- source.spotify_client_id / spotify_client_secret (secret write-only):
  each user's own Spotify developer app, needed by the maintained cspot
  fork (philippe44/cspot) since Spotify's 2025 API restrictions.
- UI: client ID field, password field for the secret ("leave empty to
  keep"), link to developer.spotify.com; enabled for spotify/auto modes.
- status.spotify_state: "no client credentials" while either is missing.
- Verified: secret never appears in GET; UI-style re-save keeps it;
  survives reboot; null clears it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:16:42 +10:00
bsncubed c0e0388ff0 CLAUDE.md: step 7 progress and open HLS items
HLS plays on AES67; list what to come back to (clock drift vs PTP,
download speed, untested cases) before moving on to cspot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:00:09 +10:00
bsncubed 3ebb27e4bb Step 7.4: HLS audio on AES67 (44.1 -> 48 kHz into the ring)
- decoder: s16 PCM -> stereo int32 -> esp_ae_rate_cvt 44.1 -> 48 kHz
  (32-bit, complexity 3; bypassed at 48 kHz; mono duplicated) -> ring.
  esp_audio_effects pinned to ~1.3.0 (1.4+ needs P4 rev >= 3).
- hls: each segment is downloaded completely into PSRAM (max 4 MB), then
  decoded; the connection is not held open while the decoder waits for
  ring space at playback speed.
- player: player_write() blocks while the ring is full and gives up when
  the source changes; the temporary 440 Hz producer is removed.
- Verified with Triple J Hottest: 441344 -> 480375 frames (10.008 s) and
  440320 -> 479260 (9.985 s) per segment; RTP 15000 packets, 0 gaps,
  peak -10 dBFS / RMS -22 dBFS; ring ~4.0 s, 0 underruns over ~50 s;
  heap 422 KB, PSRAM 27.5 MB free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:52:19 +10:00
bsncubed 8a6cb53e3b Step 7.3: decode HLS TS segments to PCM (own TS demux + AAC decoder)
- main/decoder: MPEG-TS demux (packets reassembled across HTTP chunks,
  PAT -> PMT -> first ADTS-AAC PID, PES headers stripped) feeding the
  esp_audio_codec simple AAC decoder (ADTS, AAC-Plus enabled for HE-AAC
  v1/v2 variants). 7.3 only counts and logs PCM per segment.
- esp_audio_codec pinned to ~2.5.0: 2.6+ needs P4 rev >= 3 (this board
  is rev 1.3). Noted in CLAUDE.md, also for esp_audio_effects < 1.4.
- The library's combined TS decoder lost ~8% of the frames (segments
  decoded to 7.9-9.6 s, "decode error -1"); with the own demux every
  segment is sample exact: 441344 / 440320 frames = 10.008 / 9.985 s,
  matching EXTINF 10.0078 / 9.9846 (431 / 430 AAC frames), no errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:48:12 +10:00
bsncubed 852c0ffa0f Step 7.2: HLS client fetches live segments (log only)
- main/hls: task active while source.mode is hls/auto and hls_url is
  set. esp_http_client over HTTPS (IDF certificate bundle), redirects
  followed (max 5), streamed reads in 4 KB chunks to a sink callback.
- Master playlist: highest BANDWIDTH variant; URL resolution for
  absolute, host-relative and path-relative references; CRLF tolerant.
- Media playlist: TARGETDURATION, MEDIA-SEQUENCE, segments; start 3
  segments behind the live edge, fetch each new one in order, skip ahead
  if the window moved past us, reload after target/2 when nothing is new.
- Verified with Triple J Hottest (ABC, Akamai): 252 kbit/s AAC-LC
  variant chosen, 3 back-fill segments then one new ~10 s segment at a
  time, ~303 KB in ~1.25 s each; heap 439 KB, PSRAM 31.9 MB free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:40:18 +10:00
bsncubed d3897f3179 Step 7.1: player plumbing (PSRAM ring -> AES67 TX), test tone mode
- main/audio_ring: SPSC ring of interleaved int32 frames in PSRAM
  (4 s at 48 kHz stereo), lock-free with acquire/release counters; the
  TX pull callback never blocks.
- main/player: source selection from source.mode and the pull callback
  for aes67_tx. tone -> the core's PTP-phased 1 kHz tone; off -> silence;
  hls/spotify -> ring with 1 s prefill (silence while buffering is not an
  underrun; running dry is, and prefills again). Status fields
  active_source, source_state, spotify_state, buffer_ms. source config
  applies live.
- New source.mode "tone" (validation, UI dropdown, doc) for commissioning.
- Temporary 440 Hz producer in hls mode (until the HLS player exists).
- Verified: tone 999.7 Hz -18 dBFS; off silent; hls 440.0 Hz with max
  sample step 60816 (ideal sine 60825, i.e. no discontinuities), buffer
  3983 ms, 0 underruns; spotify silent/not implemented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:36:15 +10:00
bsncubed 2a7ab7922d Step 7 prep: enable the 32 MB PSRAM
CONFIG_SPIRAM=y (hex mode, 200 MHz; 250 MHz needs chip rev >= 3).
malloc() places blocks above 16 KB in PSRAM, 32 KB internal RAM stays
reserved, DMA buffers remain internal. Needed for HLS segment buffers,
cspot and decoders.
Verified on board: psram_free 33,551,300 bytes, internal heap 463 KB,
PTP locked, AES67 stream unchanged (1000/s, no gaps, tone within 1 LSB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:27:04 +10:00
bsncubed 1961c7fe13 Phase 3: remote access via VPN / Tailscale
No official Tailscale client exists for ESP32: evaluate a Tailscale
subnet router on the LAN (no firmware change) or WireGuard on the device.
API authentication is a prerequisite before remote exposure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:26:38 +10:00
bsncubed e763dc81bd Phase 2: NTP with hostnames (pool.ntp.org) or IPs
Planned SNTP client: servers as names or IPs, several allowed, resolved
via DNS. Seeds the PTP clock with real time before becoming GM (today it
starts at 1970) and gives syslog timestamps. Added to the phase 2 list
in CLAUDE.md and as a section in aes67-core-base.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:22:58 +10:00
bsncubed 5bd1a20e43 Step 6.3: PTP hybrid mode (unicast Delay_Req/Resp), step 6 done
- As TimeReceiver in ptp.mode hybrid: Delay_Req unicast to the GM (IP
  from its Announce, MAC recorded by the RX hook from its Sync frames),
  unicastFlag set.
- As TimeTransmitter: a Delay_Req with the unicastFlag gets a unicast
  Delay_Resp; multicast requests get multicast replies.
- EMAC timestamps every received frame (en_ts4all): its PTP filter left
  unicast Delay_Req unstamped ("no HW RX timestamp").
- A unicast Delay_Resp's logMessageInterval 0x7F is ignored (use
  ptp.log_delay_req); log_us() clamps to -7..6 (the shift was undefined).
- Verified vs ptp4l --hybrid_e2e 1: board hybrid TimeReceiver 18
  Delay_Req in 20 s, all answered, locked; board TimeTransmitter
  (p1 100): tcpdump shows Sync/Follow_Up/Announce to 224.0.1.129,
  Delay_Req 192.168.192.233 -> .244 [unicast] and Delay_Resp .244 ->
  .233 [unicast] within 0.4 ms; ptp4l s2.
- Docs: TimeTransmitter/hybrid notes; step 6 ticked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:21:09 +10:00
bsncubed dcea39b216 Step 6.2: role hand-over, session_ver bump on GM change
- aes67_cfg: cfg_set_number(group, key, value, apply) for firmware-side
  changes, stored in NVS like a POST; apply can be skipped.
- aes67_sdp_sap: once a second, a change of the PTP GM (ts-refclk) bumps
  aes67.session_ver without re-applying the aes67 group (no stream
  restart); SAP then re-announces. Runs whether or not SAP is on.
- Verified with ptp4l as a normal clock (p1 128): board auto (p1 250)
  steps down to SLAVE (session_ver 1->2); role master p1 100 via API ->
  board MASTER at once (->3); back to auto p1 250 -> ptp4l takes over
  within ~1 s, board SLAVE again (->4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 08:08:00 +10:00
bsncubed 08b83a069c Step 6.1: PTP TimeTransmitter with BMCA (multicast)
- Own dataset from config: slave -> class 255, never TimeTransmitter;
  auto/master -> class 248 with ptp.priority1/2; accuracy 0xFE, variance
  0xFFFF, timeSource 0xA0, clockIdentity EUI-64 from MAC.
- BMCA: a foreign TimeTransmitter is followed only if its Announce beats
  our dataset (always for slave-only); if the followed one turns worse we
  take over; a better one makes us step down. LISTENING -> MASTER after
  announceReceiptTimeout x our announce interval.
- MASTER: Announce (PTP timescale flag) every 2^log_announce, two-step
  Sync every 2^log_sync (raw frame, HW TX time in Follow_Up), Delay_Resp
  for each Delay_Req with its HW RX time and logMessageInterval =
  log_delay_req. Frequency correction kept (holdover).
- ptp config applies live (role, priorities, intervals, domain, DSCP).
- status.ptp: state MASTER, gm_id = own, TX Sync/Announce intervals,
  Delay_Req/Resp counters; locked is true as master so AES67 TX keeps
  running; SDP ts-refclk and SAP follow.
- Verified: with ptp4l GM p1 128 the board (auto, p1 250) stays SLAVE;
  ptp4l stopped -> board MASTER; ptp4l -s --priority1 255 locks to it
  (s2) in ~4 s, offset within +-320 ns, path delay 10.3 us.
  Known: Sync send times jitter ~10 ms (FreeRTOS tick); accuracy is not
  affected (two-step Follow_Up carries the exact HW time).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 07:42:43 +10:00
bsncubed 6d85eb49f8 lwIP: 16 sockets so web clients are not starved
With the default 10, PTP (2), AES67 TX, SAP, syslog and httpd's
listen/control sockets left ~3 for web clients although httpd allows 7.
A browser's keep-alive connections then made new requests fail with a
reset for seconds at a time (the intermittent 'outages').
Reproduced: with 1 idle connection held, new requests were reset.
After: 6 idle connections held, new requests answered in 6-7 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 07:35:02 +10:00
62 changed files with 4789 additions and 111 deletions
+1
View File
@@ -3,3 +3,4 @@ sdkconfig
sdkconfig.old
managed_components/
build-*/
tools/__pycache__/
+3
View File
@@ -0,0 +1,3 @@
[submodule "external/cspot"]
path = external/cspot
url = https://github.com/philippe44/cspot.git
+49 -3
View File
@@ -15,6 +15,7 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
- After every change: `idf.py build`, flash, and check the serial monitor output. Show the relevant log lines.
- Don't mark a step done until it has been verified on the board.
- Keep core and project separate: `components/aes67_*` must not depend on `main/` (sources/player). Project code plugs in through the config, status and route registries.
- Licences: core (`components/aes67_*`) and `web/` are MIT, the rest GPL-3.0-or-later (see THIRD_PARTY.md). Never pull GPL code (cspot, bell, squeezelite) into the core. New third-party code: check its licence first and add it to THIRD_PARTY.md.
- `web/index.html`: keep the CORE / PROJECT markers. If the firmware needs an API change, change the doc and the page together.
- Small, focused commits per step.
@@ -25,10 +26,14 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
- Chip revision < v3.0 (engineering silicon, seen on some of these boards) needs `CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y`.
Our board: **v1.3** (set in sdkconfig.defaults, min rev v1.0).
- Our board: **32 MB** flash (GigaDevice c8/4019). App slots must stay below 16 MB (cache mapping above 16 MB is experimental in IDF).
- Rev < 3 also limits Espressif's prebuilt audio libraries: `esp_audio_codec` must stay < 2.6 and `esp_audio_effects` < 1.4 (newer versions use P4 assembly that needs rev >= 3; the build fails with a message saying so). Check this for any new Espressif binary component.
- Embed `web/index.html` via `EMBED_TXTFILES` in `aes67_web`.
- cspot (Spotify, `external/cspot` git submodule, philippe44 fork, pinned): after cloning run `git submodule update --init external/cspot && git -C external/cspot submodule update --init cspot/bell`. Its nanopb code generator needs, in the IDF Python env: `python -m pip install protobuf grpcio-tools 'setuptools<81'` (after `. export.sh`). Our fixes to cspot/bell live in `components/spotify/patches/{cspot,bell}/*.patch` and are applied automatically at configure time; don't edit the submodule directly, add a patch.
- Firmware version: `<version.txt>-<git short hash>`, e.g. `0.0.1-1d613b1`. Bump `version.txt` for a release; the hash is the commit that was built (commit first, then build, so it matches). No dirty flag.
- Flash over the network (normal way since step 2b; keep USB for recovery):
`curl -f --data-binary @build/aes67_p4.bin -H 'Content-Type: application/octet-stream' http://p4-aes67/api/ota`
The board reboots into the new image on trial; check `GET /api/ota` shows the new version with `pending_verify: false`.
- Another board, over USB: `tools/flash_board.py` (checks chip revision and flash size, optional erase, flashes, finds the IP in the boot log, sets hostname / stream name / multicast so boards don't clash). Needs a build and esptool (IDF env or `pip install esptool`).
- Serial: opening /dev/ttyACM0 can reset the board. Don't open it while an OTA image is on trial (a reset then counts as a failed boot and rolls back).
- Rollback test build (self-test always fails), in its own build dir:
`idf.py -B build-selftest-fail -DSDKCONFIG=build-selftest-fail/sdkconfig -DSDKCONFIG_DEFAULTS="sdkconfig.defaults;sdkconfig.selftest_fail" build`
@@ -40,7 +45,7 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
- On-die temperature sensor only (driver/temperature_sensor.h).
## Build order / status
- [x] 0. Check chip revision and flash size; create IDF project and empty component stubs (layout in aes67-core-base.md). Set up the OTA partition table (two app slots, no factory) and PROJECT_VER from git now, so the layout never changes later.
- [x] 0. Check chip revision and flash size; create IDF project and empty component stubs (layout in aes67-core-base.md). Set up the OTA partition table (two app slots, no factory) and PROJECT_VER now, so the layout never changes later. (PROJECT_VER = `version.txt` + git short hash.)
- [x] 1. Ethernet: IP101 up, DHCP, IP logged. Ping works.
- [x] 2. Web server + config store (cJSON in NVS) + embedded index.html; /api/config, /api/status (stub values), /api/reboot.
- [x] 2a. Finding the device: mDNS (hostname.local + _http._tcp), then LLDP (switch shows name + IP).
@@ -49,9 +54,50 @@ Repo: https://gitea.apointless.space/bsncubed/aes67-ESP32-P4
- [ ] 4. AES67 TX with a 1 kHz test tone, PTP-paced; /stream.sdp. Verify: import SDP on a Riedel Artist 4-wire AES67 port, and check packets/timestamps in Wireshark.
Done and checked with a receiver script (all ptimes, L16/L24, tone phase-locked to PTP); still open: the Riedel import and a Wireshark capture.
- [x] 5. SAP discovery, then syslog, then health/temperatures (one at a time). VLAN split moved to phase 2.
- [ ] 6. PTP TimeTransmitter: BMCA roles (auto/master), hybrid mode.
- [x] 6. PTP TimeTransmitter: BMCA roles (slave/auto; the separate "master" role was dropped later, auto with a low priority1 does the same), hybrid mode.
- [ ] 7. Sources: HLS player, then cspot (Spotify Connect), then failover + /api/player.
- [x] 7.1-7.4 HLS plays on AES67 (PSRAM ring, TS demux + AAC, 44.1 -> 48 kHz). Tested with Triple J Hottest (TS, AAC-LC 44.1k).
- [ ] Come back to HLS (open items):
- Clock drift: the station's encoder clock vs our PTP clock is not corrected. Starts 3 segments (~30 s) behind live, so it shows after hours/days (skip when falling out of the live window, or buffering). Fix: steer the 44.1 -> 48 kHz ratio by a few ppm from the distance to the live edge / ring level.
- Download speed ~1.4 Mbit/s over TLS (fine for ~250 kbit/s; tune buffer sizes / per-chunk overhead).
- Not yet tested: HE-AAC variant (140k), other stations, fMP4/ADTS-only playlists, discontinuities (#EXT-X-DISCONTINUITY), network loss and recovery, long runs.
- Audio starts only after PTP lock (~20 s after boot): intended, TX needs PTP.
- [ ] cspot (Spotify Connect): login, audio, pause/skip/seek, app volume, live mode switching work; stays connected across track changes and past 6 min (7.5b). Fixed so far: logger NULL crash, Vorbis symbol clash, volume starting at 0, reconnect race (PR #3 patch), 6-minute AP resets (delayed Pong patch), app dropping the device (notifyAudioReachedPlayback). Open:
- OTA with a session: now ends the session first; 2 of 2 uploads with a running session were clean since. Flash writes still stall TX > 20 ms during uploads (stream stutters while updating).
- First connects sometimes fail ("Can't connect to spotify servers"), a retry works.
- Internal heap drops from ~365 KB to ~231 KB with a session; check what can move to PSRAM.
- Track display in the app can switch ~3-5 s early.
- Mute at 0 % volume not yet confirmed.
- Consider offering the delayed-Pong fix upstream (philippe44/cspot).
- An old, long-idle session can get out of sync with the app: it sends empty Load frames ("No tracks in frame") instead of Pause/Play, so controls do nothing. Quitting and reopening Spotify on the Mac fixes it.
- [x] failover (auto mode): no session or (with `failover_on_pause`) paused for `failover_delay_s` -> HLS; Spotify playing -> Spotify within ~1 s; 30 ms fades; HLS suspended while Spotify plays; cspot is held back (not drained) while it isn't Spotify's turn, so it resumes where it paused. Verified: no session -> HLS, play -> Spotify, pause stays (on_pause off), pause -> HLS after 5 s (on_pause on), play -> Spotify at the paused position.
- Open: `aes67_tx resync` (TX 20-27 ms late) ~11 s after each switch to Spotify (seen 3 times); clicks at switches not yet checked in a recording; HLS start sometimes hits CDN read timeouts.
- [x] /api/player: GET, transport, seek, volume (the app follows), source override and url (runtime, not saved); web UI progress bar.
- [ ] 8. Mono sum, gain, polish.
- [x] Mono sum: stereo source mapped to a 1-channel stream in the core ((L+R)/2, 64 bit). Checked: 156 B packets, SDP L24/48000/1.
- [x] Gain: source.gain_db as a trim on top of the volume, saturating. Checked: -12 dB = -12 dB peak, +12 dB clips at 0 dBFS.
- [x] Pink noise source (-18 dBFS RMS, octaves flat within 0.4 dB 63 Hz-4 kHz).
- [x] 48 kHz only (96 kHz dropped: all sources are 48 kHz).
- [x] Network: status mask/gw/dns, UI shows the lease; static IP (reboot on change, validation).
- [x] Web UI: sticky save bar, dark default + light toggle, progress bar, PTP panel (2 min average offset, details), uptime d/h/m/s, VLAN option hidden, no hw_ts / preferred-TimeTransmitter options.
- [x] Versioning `<version.txt>-<git hash>`; tools/flash_board.py (tested on this board); docs/user-guide.md.
- [ ] Mute at 0 % volume: confirm on the board.
## Phase 2 (parked)
- [ ] VLAN split: AES67 untagged + internet tagged (inet.vlan_id/pcp), per aes67-core-base.md "Network". Needs a tagged VLAN with DHCP on the switch port. Config group `inet` and the UI fields exist already; nothing is applied yet.
- [ ] Replace the Espressif binary audio libraries (GPL-3 conflict, see THIRD_PARTY.md): AAC via opencore-aacdec (Apache-2.0, in bell/external), 44.1 -> 48 kHz via the Speex resampler (BSD). Do together with / right before the clock-drift correction (Speex can steer the ratio).
- [ ] Clock-drift correction (do before AirPlay): steer the 44.1 -> 48 kHz converter by a few ppm from the ring level / distance to the live edge, so push sources that run on the sender's clock don't slowly over- or underrun. Closes the HLS clock-drift item in step 7; AirPlay needs the same.
- [ ] AirPlay 1 (RAOP) as a source: `_raop._tcp` via our mDNS, RTSP control, AES (mbedTLS), ALAC decode, RTP audio + timing, 44.1 kHz into the existing converter, uses the clock-drift correction. Start from philippe44's RAOP code in squeezelite-esp32 (`components/raop`, checked 2026-09-27 at commit 1d542bd):
- Take `raop.c`, `util.c` (MIT, philippe44) and `rtp.c` (MIT, James Laird/shairport); keep their headers. Write our own glue to the player (their `raop_sink.c` has no licence header and the repo has no LICENSE file; it's specific to squeezelite anyway).
- ALAC: they link a prebuilt `libalac.a`; build Apple's ALAC from source instead (Apache-2.0, already in `external/cspot/cspot/bell/external/alac`).
- `dmap_parser.c` (track metadata) has no header: confirm its origin (likely the MIT dmap-parser project) or leave it out.
- `raop.c` contains the AirPort Express RSA private key (reverse-engineered in 2011, in every AirPlay 1 receiver): known grey area.
- Code is written for squeezelite-esp32's platform (pthreads, their logging, OpenSSL/mbedTLS switches, NVS): needs porting like cspot. `rtp.c` hands each frame to the sink with its play time (NTP-synced to the sender); following the sender's clock is the sink's job, i.e. our clock-drift correction. Covers iPhone/iPad/Mac (incl. Tidal and Apple Music apps) and Windows via AirPlay senders (TuneBlade, Airfoil). Not AirPlay 2 (HomeKit pairing, its own PTP on ports 319/320 clashes with ours). Then: auto mode as a priority list (whichever source plays wins, HLS as fallback). Check internal heap with Spotify + AirPlay sessions (buffers to PSRAM).
- [ ] VLAN split: AES67 untagged + internet tagged (inet.vlan_id/pcp), per aes67-core-base.md "Network". Needs a tagged VLAN with DHCP on the switch port. Config group `inet` and the UI fields exist already; nothing is applied yet. The "VLAN split" checkbox is hidden in web/index.html (`<label hidden>`); unhide it when this is done.
- [ ] NTP (SNTP): servers as hostnames or IPs (e.g. `pool.ntp.org`, several allowed; names resolved via DNS, re-resolved on failure). Uses: seed the PTP clock with real time before becoming GM (today it starts at 1970), syslog timestamps. Needs a `time` config group + UI fields (change doc and page together).
- [ ] Factory reset buton in the webgui with a confromation popup.
## Phase 3 (parked)
- [ ] Remote access via VPN / Tailscale. There is no official Tailscale client for ESP32; options to evaluate first:
(a) no firmware change: a Tailscale subnet router on the LAN (e.g. the dev PC or a Pi) advertising the device's subnet;
(b) WireGuard on the device (e.g. the `esp_wireguard` component) to a WireGuard server or a Tailscale/Headscale-compatible peer.
Before exposing the web/API remotely: add authentication (bearer token) as noted in the OTA/security section of aes67-core-base.md. Keep AES67/PTP traffic off the tunnel.
+11 -9
View File
@@ -1,19 +1,21 @@
cmake_minimum_required(VERSION 3.16)
# Firmware version = git describe (tags, dirty flag). Reported by esp_app_get_description()
# and in status.fw / GET /api/ota. CMake re-runs when git's HEAD log or index changes (commit,
# checkout, add), so the version follows. A new tag or unstaged edits need `idf.py reconfigure`.
# Firmware version = "<version.txt>-<git short hash>", e.g. 0.0.1-1d613b1. The first part is set by
# hand in version.txt; the hash says which commit was built (no dirty flag: the build always patches
# the cspot submodule). Reported by esp_app_get_description(), status.fw and GET /api/ota.
# CMake re-runs when version.txt or the checked-out commit changes.
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
${CMAKE_CURRENT_LIST_DIR}/.git/logs/HEAD
${CMAKE_CURRENT_LIST_DIR}/.git/index)
${CMAKE_CURRENT_LIST_DIR}/version.txt
${CMAKE_CURRENT_LIST_DIR}/.git/logs/HEAD)
file(STRINGS ${CMAKE_CURRENT_LIST_DIR}/version.txt PROJECT_VER LIMIT_COUNT 1)
execute_process(
COMMAND git describe --tags --always --dirty
COMMAND git rev-parse --short HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE PROJECT_VER
OUTPUT_VARIABLE GIT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET)
if(NOT PROJECT_VER)
set(PROJECT_VER "0.0.0-nogit")
if(GIT_HASH)
set(PROJECT_VER "${PROJECT_VER}-${GIT_HASH}")
endif()
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+24 -6
View File
@@ -1,10 +1,28 @@
# aes67-ESP32-P4
AES67 sender for the Waveshare ESP32-P4-ETH (PoE): Spotify Connect and HLS/m3u8 streams out as an AES67 multicast stream, PTP-locked, with a simple web UI for settings and SDP export.
AES67 sender for the Waveshare ESP32-P4-ETH (PoE): Spotify Connect and HLS/m3u8 internet radio (with failover between them) go out as an AES67 multicast stream, locked to PTP. Everything is set up from a built-in web page, with SAP announcements and SDP export for receivers (tested with Riedel PTP).
- `docs/aes67-core-base.md` — reusable AES67 core design (PTP, RTP, SDP/SAP, VLAN, syslog, web UI contract)
- `docs/hardware-and-design-notes.md` — board details and project-specific design
- `web/index.html` — web UI (served by the device)
- `CLAUDE.md` — working rules and build order
**Using it:** see the [user guide](docs/user-guide.md).
Status: design complete, firmware not started. See the build order in CLAUDE.md.
**Quick start:** power the board over PoE and open http://p4-aes67.local/. Pick a source and save. Then find "P4 AES67" via SAP on the receiver, or import the SDP from the page.
## Building and flashing
- ESP-IDF 5.5 or later, target `esp32p4`: `idf.py set-target esp32p4 && idf.py build`
- cspot submodule: `git submodule update --init external/cspot && git -C external/cspot submodule update --init cspot/bell`
- New board over USB: `tools/flash_board.py`
- Update over the network: web page → Firmware, or `curl -f --data-binary @build/aes67_p4.bin -H 'Content-Type: application/octet-stream' http://p4-aes67.local/api/ota`
Toolchain details and caveats (chip revision, Python packages for cspot) are in `CLAUDE.md`.
## Documentation
- `docs/user-guide.md`: setup, web page, sources, Spotify, AES67, PTP, network, updates, player API, troubleshooting
- `docs/aes67-core-base.md`: reusable AES67 core design (PTP, RTP, SDP/SAP, syslog, web UI and API contract)
- `docs/hardware-and-design-notes.md`: board details and project-specific design
- `web/index.html`: the web page (served by the device)
- `CLAUDE.md`: working rules, build order and status
## Licence
The AES67 core (`components/aes67_*`) and the web page (`web/`) are MIT. Everything else is GPL-3.0-or-later (`LICENSE`). The firmware image contains cspot (GPL-3.0), so distributing it falls under GPL-3.0. Third-party code, its licences and a known conflict with two Espressif binary libraries: [THIRD_PARTY.md](THIRD_PARTY.md).
+37
View File
@@ -0,0 +1,37 @@
# Licences
## This project
| Part | Licence |
|---|---|
| AES67 core: `components/aes67_*` (each has its own `LICENSE`) | MIT |
| Web page: `web/index.html` (`web/LICENSE`) | MIT |
| Everything else: `main/`, `components/spotify/` (incl. our cspot/bell patches), `tools/`, docs, build files | GPL-3.0-or-later (`LICENSE`) |
The core is MIT so it can be reused in other AES67 projects, including closed ones. It must not depend on GPL code: nothing in `components/aes67_*` may include or link cspot or `main/`.
The firmware image as a whole contains cspot (GPL-3.0), so anyone who distributes the firmware (a `.bin` or a flashed board) must do so under GPL-3.0, with the complete corresponding source.
## Third-party code in the firmware
| Code | Used for | Licence | Notes |
|---|---|---|---|
| [cspot](https://github.com/philippe44/cspot) (philippe44 fork, `external/cspot`) | Spotify Connect | GPL-3.0-or-later | Our patches: `components/spotify/patches/cspot` |
| [bell](https://github.com/philippe44/bell) (cspot submodule) | cspot's I/O and utilities | no licence file | Part of the cspot project; licence to be confirmed with the author |
| tremor (via bell) | Vorbis decoding (Spotify) | BSD-3-Clause (Xiph.Org) | |
| nanopb (via bell) | Protobuf (Spotify protocol) | zlib | |
| ESP-IDF, incl. mbedTLS, esp_http_server, esp_eth | Platform, TLS, web server, Ethernet | Apache-2.0 | mbedTLS is dual Apache-2.0 / GPL-2.0-or-later |
| lwIP | TCP/IP | BSD-3-Clause | |
| FreeRTOS | RTOS | MIT | |
| cJSON | JSON | MIT | |
| espressif/mdns | mDNS | Apache-2.0 | |
| **espressif/esp_audio_codec** | AAC decoding (HLS) | **Espressif Modified MIT, prebuilt binary** | Only allowed with Espressif chips; no source |
| **espressif/esp_audio_effects**, gmf_fft | 44.1 → 48 kHz conversion | **Espressif Modified MIT**; esp_audio_effects is a prebuilt binary | as above |
Algorithms: pink noise uses Paul Kellet's filter and a xorshift32 generator (both public domain).
## Known conflict
The two Espressif binary libraries can't be distributed under GPL-3.0: there is no source, and "Espressif chips only" is an additional restriction that GPL-3.0 forbids. A firmware image containing both them and cspot therefore can't be distributed in line with GPL-3.0. Private use is not affected.
Planned fix (phase 2 in `CLAUDE.md`): replace them with open code, e.g. opencore-aacdec (Apache-2.0, already in `bell/external`) for AAC and the Speex resampler (BSD) for the sample-rate conversion. The Speex resampler can also do the fine rate steering the clock-drift correction needs.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+95 -6
View File
@@ -11,10 +11,13 @@
#include "esp_log.h"
#include "esp_netif.h"
#include "lldp.h"
#include "lwip/inet.h"
#include "mdns.h"
static const char *TAG = "net";
static const char *const ADDR_KEYS[] = { "dhcp", "ip", "mask", "gw", "dns" };
// AES67 / untagged interface.
static const char NET_DEFAULTS[] =
"{\"hostname\":\"aes67\",\"vlan\":false,\"web_on\":\"both\",\"dhcp\":true,"
@@ -25,6 +28,48 @@ static const char INET_DEFAULTS[] =
static esp_netif_t *s_netif;
static char s_link[24] = "down";
static cJSON *s_addr; // addressing in use since boot (ADDR_KEYS of "net")
// The keys that define the IP setup. With DHCP the static fields don't matter (the UI fills them
// with the lease), so they don't count as a change.
static cJSON *addressing(const cJSON *g)
{
cJSON *a = cJSON_CreateObject();
int n = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(g, "dhcp")) ? 1 : sizeof(ADDR_KEYS) / sizeof(ADDR_KEYS[0]);
for (int i = 0; i < n; i++) {
cJSON_AddItemToObject(a, ADDR_KEYS[i], cJSON_Duplicate(cJSON_GetObjectItemCaseSensitive(g, ADDR_KEYS[i]), true));
}
return a;
}
static uint32_t addr_of(const cJSON *g, const char *key)
{
const cJSON *v = cJSON_GetObjectItemCaseSensitive(g, key);
return cJSON_IsString(v) && v->valuestring[0] ? inet_addr(v->valuestring) : 0;
}
// Static addressing: stop the DHCP client and set ours. On link up, like IDF's static IP example.
static void set_static(void)
{
if (cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(s_addr, "dhcp"))) {
return;
}
esp_err_t err = esp_netif_dhcpc_stop(s_netif);
if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
ESP_LOGE(TAG, "DHCP client stop: %s", esp_err_to_name(err));
}
esp_netif_ip_info_t ip = {
.ip.addr = addr_of(s_addr, "ip"), .netmask.addr = addr_of(s_addr, "mask"), .gw.addr = addr_of(s_addr, "gw"),
};
err = esp_netif_set_ip_info(s_netif, &ip);
if (err != ESP_OK) {
ESP_LOGE(TAG, "static IP: %s", esp_err_to_name(err));
}
esp_netif_dns_info_t dns = { .ip.type = ESP_IPADDR_TYPE_V4, .ip.u_addr.ip4.addr = addr_of(s_addr, "dns") };
if (dns.ip.u_addr.ip4.addr) {
esp_netif_set_dns_info(s_netif, ESP_NETIF_DNS_MAIN, &dns);
}
}
static void eth_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
@@ -43,6 +88,7 @@ static void eth_event(void *arg, esp_event_base_t base, int32_t id, void *data)
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
snprintf(s_link, sizeof(s_link), "up, %s Mbps %s", speed == ETH_SPEED_100M ? "100" : "10",
duplex == ETH_DUPLEX_FULL ? "full" : "half");
set_static();
break;
}
case ETHERNET_EVENT_DISCONNECTED:
@@ -66,10 +112,27 @@ static void ip_event(void *arg, esp_event_base_t base, int32_t id, void *data)
static bool check_addr(const cJSON *g, char *err, size_t n)
{
bool dhcp = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(g, "dhcp"));
return cfg_check_ipv4(g, "ip", dhcp, err, n) &&
cfg_check_ipv4(g, "mask", dhcp, err, n) &&
cfg_check_ipv4(g, "gw", true, err, n) &&
cfg_check_ipv4(g, "dns", true, err, n);
if (!cfg_check_ipv4(g, "ip", dhcp, err, n) || !cfg_check_ipv4(g, "mask", dhcp, err, n) ||
!cfg_check_ipv4(g, "gw", true, err, n) || !cfg_check_ipv4(g, "dns", true, err, n)) {
return false;
}
if (dhcp) {
return true;
}
uint32_t ip = ntohl(addr_of(g, "ip")), mask = ntohl(addr_of(g, "mask")), gw = ntohl(addr_of(g, "gw"));
if (mask == 0 || (~mask & (~mask + 1)) != 0 || mask == 0xffffffff) {
snprintf(err, n, "mask: not a valid netmask");
return false;
}
if ((ip & ~mask) == 0 || (ip & ~mask) == ~mask) {
snprintf(err, n, "ip: network or broadcast address of the subnet");
return false;
}
if (gw && ((gw & mask) != (ip & mask) || gw == ip)) {
snprintf(err, n, "gw: must be another address in the IP's subnet");
return false;
}
return true;
}
// RFC 1123 label: letters, digits, hyphen; not starting or ending with a hyphen.
@@ -134,14 +197,30 @@ static void net_apply(const cJSON *g)
ESP_LOGI(TAG, "mDNS: now %s.local", host);
}
lldp_changed();
// New addressing: PTP/TX/SAP sockets are bound to the address, so it takes a reboot.
cJSON *a = addressing(g);
if (!cJSON_Compare(a, s_addr, true)) {
ESP_LOGW(TAG, "IP setup changed: rebooting to apply it");
web_reboot_later(1500);
}
cJSON_Delete(a);
}
static void net_status(cJSON *st)
{
char ip[16] = "", mac_s[18] = "";
char ip[16] = "", mask[16] = "", gw[16] = "", dns[16] = "", mac_s[18] = "";
esp_netif_ip_info_t info;
if (esp_netif_get_ip_info(s_netif, &info) == ESP_OK && info.ip.addr) {
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&info.ip));
snprintf(mask, sizeof(mask), IPSTR, IP2STR(&info.netmask));
if (info.gw.addr) {
snprintf(gw, sizeof(gw), IPSTR, IP2STR(&info.gw));
}
}
esp_netif_dns_info_t d;
if (esp_netif_get_dns_info(s_netif, ESP_NETIF_DNS_MAIN, &d) == ESP_OK && d.ip.type == ESP_IPADDR_TYPE_V4 &&
d.ip.u_addr.ip4.addr) {
snprintf(dns, sizeof(dns), IPSTR, IP2STR(&d.ip.u_addr.ip4));
}
uint8_t mac[6];
if (esp_netif_get_mac(s_netif, mac) == ESP_OK) {
@@ -151,13 +230,16 @@ static void net_status(cJSON *st)
// Single untagged interface until the VLAN split: AES67 and web share it.
cJSON_AddStringToObject(st, "ip", ip);
cJSON_AddStringToObject(st, "aes67_ip", ip);
cJSON_AddStringToObject(st, "mask", mask); // in use (from DHCP or static)
cJSON_AddStringToObject(st, "gw", gw);
cJSON_AddStringToObject(st, "dns", dns);
cJSON_AddStringToObject(st, "mac", mac_s);
cJSON_AddStringToObject(st, "link", s_link);
}
esp_err_t aes67_net_init(esp_eth_handle_t eth)
{
// Applied so far: hostname (DHCP, mDNS, LLDP). Static IP and VLAN come later.
// Applied: hostname (DHCP, mDNS, LLDP) live; DHCP/static addressing at boot. VLAN comes later.
ESP_ERROR_CHECK(cfg_register("net", NET_DEFAULTS, net_validate, net_apply));
ESP_ERROR_CHECK(cfg_register("inet", INET_DEFAULTS, inet_validate, NULL));
@@ -177,6 +259,13 @@ esp_err_t aes67_net_init(esp_eth_handle_t eth)
// Hostname in DHCP requests (option 12), so the router's lease list shows it.
cJSON *net = cfg_get("net");
ESP_ERROR_CHECK(esp_netif_set_hostname(s_netif, cJSON_GetObjectItemCaseSensitive(net, "hostname")->valuestring));
s_addr = addressing(net);
if (!cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(net, "dhcp"))) {
ESP_LOGI(TAG, "static IP %s/%s gw %s dns %s", cJSON_GetObjectItemCaseSensitive(net, "ip")->valuestring,
cJSON_GetObjectItemCaseSensitive(net, "mask")->valuestring,
cJSON_GetObjectItemCaseSensitive(net, "gw")->valuestring,
cJSON_GetObjectItemCaseSensitive(net, "dns")->valuestring);
}
cJSON_Delete(net);
mdns_setup();
ESP_ERROR_CHECK(lldp_start(eth, s_netif));
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+28
View File
@@ -23,6 +23,26 @@
static const char *TAG = "ota";
#define MAX_UPDATE_CBS 4
static aes67_ota_update_cb_t s_update_cbs[MAX_UPDATE_CBS];
static int s_update_n;
esp_err_t aes67_ota_on_update(aes67_ota_update_cb_t cb)
{
if (s_update_n >= MAX_UPDATE_CBS) {
return ESP_ERR_NO_MEM;
}
s_update_cbs[s_update_n++] = cb;
return ESP_OK;
}
static void notify_update(bool starting)
{
for (int i = 0; i < s_update_n; i++) {
s_update_cbs[i](starting);
}
}
static bool is_pending(void)
{
esp_ota_img_states_t st;
@@ -114,6 +134,7 @@ static esp_err_t ota_post(httpd_req_t *req)
esp_ota_handle_t ota = 0;
size_t total = 0, fill = 0;
const char *err_msg = NULL;
bool notified = false;
int64_t t0 = esp_timer_get_time();
while (total < req->content_len) {
@@ -137,6 +158,8 @@ static esp_err_t ota_post(httpd_req_t *req)
}
const esp_app_desc_t *d = (const esp_app_desc_t *)(buf + DESC_OFFSET);
ESP_LOGI(TAG, "image %.32s %.32s", d->project_name, d->version);
notify_update(true); // project quiets streaming/decoding before the flash writes
notified = true;
if (esp_ota_begin(dst, OTA_WITH_SEQUENTIAL_WRITES, &ota) != ESP_OK) {
err_msg = "ota begin failed";
break;
@@ -154,15 +177,20 @@ static esp_err_t ota_post(httpd_req_t *req)
if (ota) {
esp_ota_abort(ota);
}
if (notified) {
notify_update(false);
}
// Rejected before the whole body was read: close instead of draining it.
httpd_resp_set_hdr(req, "Connection", "close");
return reject(req, err_msg);
}
esp_err_t err = esp_ota_end(ota); // verifies the image (checksum/hash, chip)
if (err != ESP_OK) {
notify_update(false);
return reject(req, err == ESP_ERR_OTA_VALIDATE_FAILED ? "image verification failed" : "ota end failed");
}
if (esp_ota_set_boot_partition(dst) != ESP_OK) {
notify_update(false);
return httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "could not set boot partition");
}
ESP_LOGW(TAG, "installed to %s in %.1f s, rebooting", dst->label,
+8
View File
@@ -2,8 +2,16 @@
// Core component: must not depend on main/ (project code).
#pragma once
#include <stdbool.h>
#include "esp_err.h"
// Registers /api/ota routes. If the running image is pending verification, starts the
// self-test: IP address + own web server answering within 60 s, else roll back.
esp_err_t aes67_ota_init(void);
// Called with true right before an accepted upload starts writing flash, and with false if that
// upload then fails (on success the device reboots). Lets the project quiet heavy work (streaming,
// decoding) during the flash writes. Up to 4 callbacks.
typedef void (*aes67_ota_update_cb_t)(bool starting);
esp_err_t aes67_ota_on_update(aes67_ota_update_cb_t cb);
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+24 -3
View File
@@ -1,7 +1,10 @@
#include "aes67_ptp.h"
#include <string.h>
#include "aes67_cfg.h"
#include "aes67_web.h"
#include "esp_log.h"
#include "ptp_clock.h"
#include "ptp_hw.h"
@@ -9,12 +12,12 @@
static const char PTP_DEFAULTS[] =
"{\"mode\":\"multicast\",\"role\":\"auto\",\"domain\":0,\"priority1\":250,\"priority2\":250,"
"\"log_sync\":0,\"log_announce\":1,\"announce_timeout\":3,\"log_delay_req\":0,"
"\"dscp\":46,\"hw_ts\":true}";
"\"dscp\":46}"; // hardware timestamps always (status.ptp.hw_ts)
static bool ptp_validate(const cJSON *g, char *err, size_t n)
{
static const char *const modes[] = { "multicast", "hybrid", NULL };
static const char *const roles[] = { "slave", "auto", "master", NULL };
static const char *const roles[] = { "slave", "auto", NULL };
return cfg_check_enum(g, "mode", modes, err, n) &&
cfg_check_enum(g, "role", roles, err, n) &&
cfg_check_int(g, "domain", 0, 127, err, n) &&
@@ -27,9 +30,27 @@ static bool ptp_validate(const cJSON *g, char *err, size_t n)
cfg_check_int(g, "dscp", 0, 63, err, n);
}
static void ptp_apply(const cJSON *g)
{
ptp_clock_reconfig();
}
esp_err_t aes67_ptp_init(void)
{
return cfg_register("ptp", PTP_DEFAULTS, ptp_validate, NULL);
esp_err_t err = cfg_register("ptp", PTP_DEFAULTS, ptp_validate, ptp_apply);
if (err != ESP_OK) {
return err;
}
// Role "master" was dropped (it behaved like auto; a low priority1 does the same). Stored values
// aren't re-validated, so convert it here.
cJSON *c = cfg_get("ptp");
bool master = !strcmp(cJSON_GetObjectItemCaseSensitive(c, "role")->valuestring, "master");
cJSON_Delete(c);
if (master) {
ESP_LOGW("ptp", "stored role \"master\" is no longer offered: now \"auto\" (same behaviour)");
cfg_set_string("ptp", "role", "auto", false);
}
return ESP_OK;
}
esp_err_t aes67_ptp_start(esp_eth_handle_t eth)
+368 -20
View File
@@ -26,6 +26,11 @@
#define MAX_DRIFT_PPB 500000.0
#define WINDOW 64 // samples for interval/delay statistics
#define SUMMARY_US (60 * 1000000LL)
#define AVG_S 120 // status.ptp.offset_avg_ns: mean |offset| over 2 min
#define FLAG_PTP_TIMESCALE 0x0008 // flagField octet 1 bit 3
#define FLAG_UNICAST 0x0400 // flagField octet 0 bit 2
#define UTC_OFFSET 37 // TAI - UTC (s), announced as information only
#define TIME_SOURCE_OSC 0xA0 // internal oscillator
static const char *TAG = "ptp";
static const uint8_t PTP_MCAST_MAC[6] = { 0x01, 0x00, 0x5e, 0x00, 0x01, 0x81 };
@@ -54,7 +59,20 @@ static struct {
int ev, gen;
uint8_t domain, dscp, timeout;
uint8_t port_id[10]; // our clockId (EUI-64 from MAC) + port 1
master_t gm;
master_t gm; // foreign TimeTransmitter we follow (valid = TimeReceiver)
master_t own; // our own dataset for BMCA
bool slave_only; // role "slave": never TimeTransmitter
bool hybrid; // mode "hybrid": Delay_Req/Resp unicast as TimeReceiver
uint8_t gm_mac[6]; // Ethernet source of the GM's Sync (for unicast Delay_Req)
bool have_gm_mac;
uint32_t dreq_logged_ip; // last Delay_Req destination logged
bool master; // we are the TimeTransmitter
int64_t listen_since_us; // start of LISTENING (for the announce receipt timeout)
volatile bool reconfig;
int8_t cfg_log_sync, cfg_log_announce, cfg_log_dreq;
// TimeTransmitter
uint16_t tx_sync_seq, tx_announce_seq;
int64_t next_sync_us, next_announce_us, prev_t1_tx;
// Sync / Follow_Up
uint16_t sync_seq;
bool sync_pending;
@@ -80,13 +98,53 @@ static struct {
bool locked;
// Statistics for status.ptp (guarded by lock)
SemaphoreHandle_t lock;
window_t sync_iv, announce_iv, delays;
window_t sync_iv, announce_iv, delays; // RX intervals as receiver, TX intervals as transmitter
int64_t last_announce_us;
uint32_t delay_req, delay_resp;
uint8_t own_class;
int64_t sum_max_ns, sum_start_us;
// Mean |offset| over the last AVG_S seconds (status.ptp.offset_avg_ns): one bucket per second.
struct {
int64_t sec, sum;
uint32_t n;
} avg[AVG_S];
} s;
static void avg_add(int64_t offset)
{
int64_t sec = esp_timer_get_time() / 1000000;
typeof(s.avg[0]) *b = &s.avg[sec % AVG_S];
if (b->sec != sec) {
b->sec = sec;
b->sum = 0;
b->n = 0;
}
b->sum += llabs(offset);
b->n++;
}
static void avg_clear(void)
{
memset(s.avg, 0, sizeof(s.avg));
}
// False while no offset was measured in the window.
static bool avg_get(double *mean)
{
int64_t now = esp_timer_get_time() / 1000000, sum = 0;
uint32_t n = 0;
for (int i = 0; i < AVG_S; i++) {
if (s.avg[i].n && now - s.avg[i].sec < AVG_S) {
sum += s.avg[i].sum;
n += s.avg[i].n;
}
}
if (n) {
*mean = (double)sum / n;
}
return n > 0;
}
static void win_add(window_t *w, int64_t v)
{
w->v[w->next] = v;
@@ -122,9 +180,17 @@ static void win_stats(const window_t *w, double *mean, double *min, double *max,
#define LOCKED(stmt) do { xSemaphoreTake(s.lock, portMAX_DELAY); stmt; xSemaphoreGive(s.lock); } while (0)
static void set_locked(bool locked);
static void become_master(void);
/* ----- helpers ----- */
// 2^log seconds in us; log clamped to the sane PTP range (-7..6).
static int64_t log_us(int8_t log)
{
log = log < -7 ? -7 : log > 6 ? 6 : log;
return log >= 0 ? 1000000LL << log : 1000000LL >> -log;
}
static uint16_t rd16(const uint8_t *p) { return (p[0] << 8) | p[1]; }
static int64_t rd_ts(const uint8_t *p) // 48-bit seconds + 32-bit ns
@@ -205,6 +271,19 @@ static void on_announce(const uint8_t *b, int len, uint32_t src_ip)
if (memcmp(m.port_id, s.port_id, 10) == 0) {
return; // our own
}
// BMCA: follow a foreign TimeTransmitter only if it beats our own dataset (always when slave-only).
bool better = s.slave_only || compare(&m, &s.own) < 0;
if (!better) {
if (from_gm(b)) {
ESP_LOGI(TAG, "TimeTransmitter's dataset is now worse than ours");
become_master();
}
return; // as TimeTransmitter a worse one should yield; nothing to do
}
if (s.master) {
s.master = false;
ESP_LOGI(TAG, "better TimeTransmitter seen: leaving TimeTransmitter state");
}
if (from_gm(b)) {
LOCKED({
if (s.last_announce_us) {
@@ -226,6 +305,7 @@ static void on_announce(const uint8_t *b, int len, uint32_t src_ip)
win_clear(&s.delays);
});
s.sync_pending = s.dreq_pending = false;
s.have_gm_mac = false;
LOCKED({
s.delay_ns = s.prev_t2 = 0;
s.stepped = false;
@@ -270,6 +350,7 @@ static void servo(int64_t offset)
s.stepped = true;
s.offset_ns = 0; // the pre-step offset is history: not for status or the summary
s.sum_max_ns = 0;
avg_clear();
s.sum_start_us = 0;
s.prev_t2 = 0; // rate across the step is meaningless
s.bad = 0;
@@ -284,6 +365,7 @@ static void servo(int64_t offset)
s.drift_ppb = fmax(-MAX_DRIFT_PPB, fmin(MAX_DRIFT_PPB, s.drift_ppb + ki * offset));
s.freq_ppb = -ppb;
ptp_hw_adj_freq(s.freq_ppb);
avg_add(offset);
if (llabs(offset) < LOCK_NS) {
s.bad = 0;
@@ -335,10 +417,11 @@ static void on_sync(const uint8_t *b, int len)
}
eth_mac_time_t t2;
uint16_t seq = rd16(b + 30);
if (!ptp_hw_rx_ts(PTP_MSG_SYNC, seq, b + 20, &t2)) {
if (!ptp_hw_rx_ts_mac(PTP_MSG_SYNC, seq, b + 20, &t2, s.gm_mac)) {
ESP_LOGW(TAG, "Sync %u: no HW RX timestamp", seq);
return;
}
s.have_gm_mac = true;
s.sync_seq = seq;
s.log_sync = (int8_t)b[33];
s.t2 = mac_ns(&t2);
@@ -375,9 +458,22 @@ static void send_delay_req(void)
m[32] = 1; // controlField: Delay_Req
m[33] = 0x7f;
uint32_t dst;
const uint8_t *dst_mac = PTP_MCAST_MAC;
inet_aton(PTP_MCAST, (struct in_addr *)&dst);
if (s.hybrid && s.gm.ip && s.have_gm_mac) {
// Hybrid: unicast to the GM (address from its Announce, MAC from its Sync frames).
dst = s.gm.ip;
dst_mac = s.gm_mac;
m[6] |= FLAG_UNICAST >> 8;
}
if (dst != s.dreq_logged_ip) {
s.dreq_logged_ip = dst;
ESP_LOGI(TAG, "Delay_Req %s to " IPSTR " (%02x:%02x:%02x:%02x:%02x:%02x)",
dst_mac == PTP_MCAST_MAC ? "multicast" : "unicast", IP2STR((esp_ip4_addr_t *)&dst),
dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5]);
}
eth_mac_time_t t3;
esp_err_t err = ptp_hw_send_event(PTP_MCAST_MAC, dst, s.dscp, m, sizeof(m), &t3);
esp_err_t err = ptp_hw_send_event(dst_mac, dst, s.dscp, m, sizeof(m), &t3);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Delay_Req %u: %s", s.dreq_seq, esp_err_to_name(err));
s.dreq_pending = false;
@@ -397,7 +493,10 @@ static void on_delay_resp(const uint8_t *b, int len)
s.dreq_pending = false;
LOCKED(s.delay_resp++);
int64_t t4 = rd_ts(b + 34) - rd_corr_ns(b + 8);
s.log_dreq = (int8_t)b[33];
// Delay_Req interval from the GM; a unicast Delay_Resp carries 0x7F ("not specified"):
// then use our configured interval.
int8_t l = (int8_t)b[33];
s.log_dreq = l >= -7 && l <= 6 ? l : s.cfg_log_dreq;
if (!s.prev_t2) {
return;
}
@@ -409,6 +508,152 @@ static void on_delay_resp(const uint8_t *b, int len)
});
}
/* ----- TimeTransmitter ----- */
static void wr_ts(uint8_t *p, int64_t ns)
{
uint64_t sec = ns / 1000000000LL;
uint32_t n = ns % 1000000000LL;
p[0] = sec >> 40; p[1] = sec >> 32; p[2] = sec >> 24; p[3] = sec >> 16; p[4] = sec >> 8; p[5] = sec;
p[6] = n >> 24; p[7] = n >> 16; p[8] = n >> 8; p[9] = n;
}
static void hdr(uint8_t *m, uint8_t type, uint16_t len, uint16_t flags, uint16_t seq, uint8_t control, int8_t log)
{
memset(m, 0, len);
m[0] = type;
m[1] = 2;
m[2] = len >> 8;
m[3] = len & 0xff;
m[4] = s.domain;
m[6] = flags >> 8;
m[7] = flags & 0xff;
memcpy(m + 20, s.port_id, 10);
m[30] = seq >> 8;
m[31] = seq & 0xff;
m[32] = control;
m[33] = (uint8_t)log;
}
// General messages (Announce, Follow_Up, Delay_Resp) go through the lwIP socket on port 320.
static void send_general(const uint8_t *m, size_t len, uint32_t dst_ip)
{
struct sockaddr_in dst = { .sin_family = AF_INET, .sin_port = htons(PTP_GENERAL_PORT), .sin_addr.s_addr = dst_ip };
if (sendto(s.gen, m, len, 0, (struct sockaddr *)&dst, sizeof(dst)) < 0) {
ESP_LOGW(TAG, "send type %u failed (errno %d)", m[0] & 0x0f, errno);
}
}
static uint32_t mcast_ip(void)
{
struct in_addr a;
inet_aton(PTP_MCAST, &a);
return a.s_addr;
}
static void send_announce(void)
{
uint8_t m[64];
hdr(m, PTP_MSG_ANNOUNCE, sizeof(m), FLAG_PTP_TIMESCALE, s.tx_announce_seq++, 5, s.cfg_log_announce);
m[44] = UTC_OFFSET >> 8;
m[45] = UTC_OFFSET & 0xff;
m[47] = s.own.p1;
m[48] = s.own.cls;
m[49] = s.own.acc;
m[50] = s.own.var >> 8;
m[51] = s.own.var & 0xff;
m[52] = s.own.p2;
memcpy(m + 53, s.own.gm_id, 8);
m[63] = TIME_SOURCE_OSC;
send_general(m, sizeof(m), mcast_ip());
int64_t now = esp_timer_get_time();
LOCKED({
if (s.last_announce_us) {
win_add(&s.announce_iv, now - s.last_announce_us);
}
s.last_announce_us = now;
});
}
// Two-step: Sync as a raw frame for its hardware TX timestamp, then Follow_Up with that time.
static void send_sync(void)
{
uint8_t m[44];
uint16_t seq = s.tx_sync_seq++;
hdr(m, PTP_MSG_SYNC, sizeof(m), FLAG_TWO_STEP, seq, 0, s.cfg_log_sync);
eth_mac_time_t t1;
esp_err_t err = ptp_hw_send_event(PTP_MCAST_MAC, mcast_ip(), s.dscp, m, sizeof(m), &t1);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Sync %u: %s", seq, esp_err_to_name(err));
return;
}
hdr(m, PTP_MSG_FOLLOW_UP, sizeof(m), 0, seq, 2, s.cfg_log_sync);
int64_t t1n = mac_ns(&t1);
wr_ts(m + 34, t1n);
send_general(m, sizeof(m), mcast_ip());
LOCKED({
if (s.prev_t1_tx) {
win_add(&s.sync_iv, t1n - s.prev_t1_tx);
}
s.prev_t1_tx = t1n;
});
}
static void on_delay_req(const uint8_t *b, int len, uint32_t src_ip)
{
if (!s.master || len < 44) {
return;
}
eth_mac_time_t t4;
uint16_t seq = rd16(b + 30);
if (!ptp_hw_rx_ts(PTP_MSG_DELAY_REQ, seq, b + 20, &t4)) {
ESP_LOGW(TAG, "Delay_Req %u: no HW RX timestamp", seq);
return;
}
uint8_t m[54];
hdr(m, PTP_MSG_DELAY_RESP, sizeof(m), 0, seq, 3, s.cfg_log_dreq);
memcpy(m + 8, b + 8, 8); // correctionField of the Delay_Req
wr_ts(m + 34, mac_ns(&t4));
memcpy(m + 44, b + 20, 10); // requestingPortIdentity
// Unicast Delay_Req (hybrid TimeReceiver) -> unicast Delay_Resp; multicast -> multicast.
bool unicast = rd16(b + 6) & FLAG_UNICAST;
if (unicast) {
m[6] |= FLAG_UNICAST >> 8;
}
send_general(m, sizeof(m), unicast ? src_ip : mcast_ip());
LOCKED({
s.delay_req++;
s.delay_resp++;
});
}
static void become_master(void)
{
char id[24];
fmt_id(id, s.own.gm_id);
ESP_LOGI(TAG, "no better TimeTransmitter: this device is TimeTransmitter %s (p1 %u class %u p2 %u)",
id, s.own.p1, s.own.cls, s.own.p2);
LOCKED({
memset(&s.gm, 0, sizeof(s.gm));
s.master = true;
s.delay_ns = s.prev_t2 = 0;
s.stepped = false;
set_locked(false); // servo state; the frequency correction stays (holdover)
s.last_announce_us = s.prev_t1_tx = 0;
win_clear(&s.announce_iv);
win_clear(&s.sync_iv);
win_clear(&s.delays);
});
s.sync_pending = s.dreq_pending = false;
s.next_sync_us = s.next_announce_us = esp_timer_get_time();
}
static void enter_listening(void)
{
s.listen_since_us = esp_timer_get_time();
}
/* ----- task ----- */
static void load_config(void)
@@ -417,11 +662,29 @@ static void load_config(void)
s.domain = cJSON_GetObjectItem(c, "domain")->valueint;
s.dscp = cJSON_GetObjectItem(c, "dscp")->valueint;
s.timeout = cJSON_GetObjectItem(c, "announce_timeout")->valueint;
// clockClass per role: slave-only 255, auto/master 248 (TimeTransmitter itself: step 6)
s.own_class = strcmp(cJSON_GetObjectItem(c, "role")->valuestring, "slave") == 0 ? 255 : 248;
s.cfg_log_sync = cJSON_GetObjectItem(c, "log_sync")->valueint;
s.cfg_log_announce = cJSON_GetObjectItem(c, "log_announce")->valueint;
s.cfg_log_dreq = cJSON_GetObjectItem(c, "log_delay_req")->valueint;
// Roles (docs): slave = clockClass 255, never transmits; auto = 248 with the configured priorities
// (250/250 by default: loses to any real GM; a lower priority1 prefers this device).
s.slave_only = strcmp(cJSON_GetObjectItem(c, "role")->valuestring, "slave") == 0;
s.hybrid = strcmp(cJSON_GetObjectItem(c, "mode")->valuestring, "hybrid") == 0;
s.own_class = s.slave_only ? 255 : 248;
s.own = (master_t){
.valid = true, .p1 = cJSON_GetObjectItem(c, "priority1")->valueint, .cls = s.own_class,
.acc = 0xFE, .var = 0xFFFF, .p2 = cJSON_GetObjectItem(c, "priority2")->valueint, .steps = 0,
.log_announce = s.cfg_log_announce,
};
memcpy(s.own.gm_id, s.port_id, 8);
memcpy(s.own.port_id, s.port_id, 10);
cJSON_Delete(c);
}
void ptp_clock_reconfig(void)
{
s.reconfig = true;
}
static void ptp_task(void *arg)
{
esp_netif_ip_info_t ip = { 0 };
@@ -434,9 +697,18 @@ static void ptp_task(void *arg)
if (s.ev < 0 || s.gen < 0) {
vTaskDelete(NULL);
}
// General messages we send as TimeTransmitter: subnet only, PTP DSCP, no loopback.
uint8_t ttl = 1, loop = 0;
int tos = s.dscp << 2;
setsockopt(s.gen, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
setsockopt(s.gen, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
setsockopt(s.gen, IPPROTO_IP, IP_MULTICAST_IF, &ifaddr, sizeof(ifaddr));
setsockopt(s.gen, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
enter_listening();
char id[24];
fmt_id(id, s.port_id);
ESP_LOGI(TAG, "TimeReceiver on " IPSTR ", domain %u, clock %s, listening", IP2STR(&ip.ip), s.domain, id);
ESP_LOGI(TAG, "PTP on " IPSTR ", domain %u, clock %s, role %s, listening", IP2STR(&ip.ip), s.domain, id,
s.slave_only ? "TimeReceiver only" : "auto/TimeTransmitter capable");
uint8_t b[128];
while (1) {
@@ -444,7 +716,14 @@ static void ptp_task(void *arg)
FD_ZERO(&fds);
FD_SET(s.ev, &fds);
FD_SET(s.gen, &fds);
struct timeval tv = { .tv_sec = 0, .tv_usec = 100000 };
// Sleep until the next message is due as TimeTransmitter, at most 100 ms.
int64_t wait = 100000;
if (s.master) {
int64_t now = esp_timer_get_time();
int64_t due = s.next_sync_us < s.next_announce_us ? s.next_sync_us : s.next_announce_us;
wait = due - now < 0 ? 0 : due - now < wait ? due - now : wait;
}
struct timeval tv = { .tv_sec = 0, .tv_usec = wait };
if (select((s.ev > s.gen ? s.ev : s.gen) + 1, &fds, NULL, NULL, &tv) > 0) {
for (int k = 0; k < 2; k++) {
int fd = k ? s.gen : s.ev;
@@ -462,16 +741,58 @@ static void ptp_task(void *arg)
case PTP_MSG_SYNC: on_sync(b, len); break;
case PTP_MSG_FOLLOW_UP: on_follow_up(b, len); break;
case PTP_MSG_DELAY_RESP: on_delay_resp(b, len); break;
case PTP_MSG_DELAY_REQ: on_delay_req(b, len, src.sin_addr.s_addr); break;
default: break;
}
}
}
if (s.reconfig) {
s.reconfig = false;
bool was_slave_only = s.slave_only;
load_config();
int tos2 = s.dscp << 2;
setsockopt(s.gen, IPPROTO_IP, IP_TOS, &tos2, sizeof(tos2));
ESP_LOGI(TAG, "config applied: role %s, mode %s, p1 %u p2 %u, domain %u",
s.slave_only ? "slave" : "auto", s.hybrid ? "hybrid" : "multicast",
s.own.p1, s.own.p2, s.domain);
// Re-run the decision: a foreign GM worse than our new dataset is dropped; as
// TimeTransmitter with role slave we stop.
if (s.master && s.slave_only) {
s.master = false;
ESP_LOGI(TAG, "role slave: leaving TimeTransmitter state");
enter_listening();
} else if (s.gm.valid && !s.slave_only && compare(&s.gm, &s.own) > 0) {
become_master();
} else if (!s.gm.valid && was_slave_only != s.slave_only) {
enter_listening();
}
}
int64_t now = esp_timer_get_time();
if (s.gm.valid) {
if (s.master) {
if (now >= s.next_announce_us) {
send_announce();
s.next_announce_us += log_us(s.cfg_log_announce);
if (s.next_announce_us < now) {
s.next_announce_us = now + log_us(s.cfg_log_announce);
}
}
if (now >= s.next_sync_us) {
send_sync();
s.next_sync_us += log_us(s.cfg_log_sync);
if (s.next_sync_us < now) {
s.next_sync_us = now + log_us(s.cfg_log_sync);
}
}
} else if (!s.gm.valid) {
// LISTENING: no better TimeTransmitter within announceReceiptTimeout -> become one
if (!s.slave_only && now - s.listen_since_us > (int64_t)s.timeout * log_us(s.cfg_log_announce)) {
become_master();
}
} else if (s.gm.valid) {
// announceReceiptTimeout x the GM's announce interval
int64_t window = (int64_t)s.timeout * (s.gm.log_announce >= 0 ? 1000000LL << s.gm.log_announce
: 1000000LL >> -s.gm.log_announce);
int64_t window = (int64_t)s.timeout * log_us(s.gm.log_announce);
if (now - s.gm.last_us > window) {
ESP_LOGW(TAG, "TimeTransmitter lost (no Announce for %lld ms), listening", window / 1000);
LOCKED({
@@ -480,10 +801,11 @@ static void ptp_task(void *arg)
s.stepped = false;
set_locked(false); // frequency correction stays (holdover)
});
enter_listening();
} else if (now >= s.next_dreq_us && s.prev_t2) {
send_delay_req();
// Delay_Req interval from the GM's Delay_Resp; randomised 0.5..1.5x
int64_t iv = s.log_dreq >= 0 ? 1000000LL << s.log_dreq : 1000000LL >> -s.log_dreq;
int64_t iv = log_us(s.log_dreq);
s.next_dreq_us = now + iv / 2 + (esp_random() % (uint32_t)iv);
}
}
@@ -493,17 +815,18 @@ static void ptp_task(void *arg)
bool ptp_clock_gm_id(char out[24])
{
xSemaphoreTake(s.lock, portMAX_DELAY);
bool valid = s.gm.valid;
bool valid = s.gm.valid || s.master;
if (valid) {
fmt_id(out, s.gm.gm_id);
fmt_id(out, s.master ? s.own.gm_id : s.gm.gm_id);
}
xSemaphoreGive(s.lock);
return valid;
}
// Media may be timed from our clock: locked to a GM, or we are the GM.
bool ptp_clock_locked(void)
{
return s.locked;
return s.locked || s.master;
}
void ptp_clock_status(cJSON *st)
@@ -513,9 +836,9 @@ void ptp_clock_status(cJSON *st)
double mean, min, max, sd;
xSemaphoreTake(s.lock, portMAX_DELAY);
const char *state = !s.gm.valid ? "LISTENING" : s.locked ? "SLAVE" : "UNCALIBRATED";
const char *state = s.master ? "MASTER" : !s.gm.valid ? "LISTENING" : s.locked ? "SLAVE" : "UNCALIBRATED";
cJSON_AddStringToObject(p, "state", state);
cJSON_AddBoolToObject(p, "locked", s.locked);
cJSON_AddBoolToObject(p, "locked", s.locked || s.master);
cJSON_AddNumberToObject(p, "version", 2);
cJSON_AddNumberToObject(p, "own_class", s.own_class);
fmt_id(id, s.port_id);
@@ -524,7 +847,29 @@ void ptp_clock_status(cJSON *st)
cJSON_AddNumberToObject(p, "window", WINDOW);
cJSON_AddNumberToObject(p, "delay_req", s.delay_req);
cJSON_AddNumberToObject(p, "delay_resp", s.delay_resp);
if (s.gm.valid) {
if (s.master) {
// We are the GM: the UI shows "(this device)" and "-" for offset/frequency/delay.
fmt_id(id, s.own.gm_id);
cJSON_AddStringToObject(p, "gm_id", id);
cJSON_AddNumberToObject(p, "gm_class", s.own.cls);
cJSON_AddNumberToObject(p, "gm_accuracy", s.own.acc);
cJSON_AddNumberToObject(p, "gm_p1", s.own.p1);
cJSON_AddNumberToObject(p, "gm_p2", s.own.p2);
cJSON_AddNumberToObject(p, "steps_removed", 0);
cJSON_AddBoolToObject(p, "gm_time_traceable", false);
cJSON_AddBoolToObject(p, "gm_freq_traceable", false);
if (s.sync_iv.n) {
win_stats(&s.sync_iv, &mean, &min, &max, &sd);
cJSON_AddNumberToObject(p, "sync_avg_ms", mean / 1e6);
cJSON_AddNumberToObject(p, "sync_min_ms", min / 1e6);
cJSON_AddNumberToObject(p, "sync_max_ms", max / 1e6);
cJSON_AddNumberToObject(p, "sync_jitter_us", sd / 1e3);
}
if (s.announce_iv.n) {
win_stats(&s.announce_iv, &mean, NULL, NULL, NULL);
cJSON_AddNumberToObject(p, "announce_avg_ms", mean / 1e3);
}
} else if (s.gm.valid) {
fmt_id(id, s.gm.gm_id);
cJSON_AddStringToObject(p, "gm_id", id);
cJSON_AddNumberToObject(p, "gm_class", s.gm.cls);
@@ -536,6 +881,9 @@ void ptp_clock_status(cJSON *st)
cJSON_AddBoolToObject(p, "gm_freq_traceable", s.gm.flags & 0x20);
if (s.stepped) {
cJSON_AddNumberToObject(p, "offset_ns", s.offset_ns);
if (avg_get(&mean)) {
cJSON_AddNumberToObject(p, "offset_avg_ns", round(mean));
}
cJSON_AddNumberToObject(p, "freq_ppb", round(s.freq_ppb));
}
if (s.delays.n) {
@@ -562,10 +910,10 @@ esp_err_t ptp_clock_start(esp_netif_t *netif)
{
s.netif = netif;
s.lock = xSemaphoreCreateMutex();
load_config();
uint8_t mac[6];
esp_netif_get_mac(netif, mac);
const uint8_t pid[10] = { mac[0], mac[1], mac[2], 0xff, 0xfe, mac[3], mac[4], mac[5], 0, 1 };
memcpy(s.port_id, pid, sizeof(pid));
load_config(); // after port_id: the own dataset uses it
return xTaskCreate(ptp_task, "ptp", 4096, NULL, 10, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
+3 -1
View File
@@ -1,4 +1,4 @@
// PTPv2 ordinary clock over UDP/IPv4 (E2E). TimeReceiver (TimeTransmitter: step 6).
// PTPv2 ordinary clock over UDP/IPv4 (E2E). TimeReceiver and TimeTransmitter (BMCA).
#pragma once
#include "cJSON.h"
@@ -6,6 +6,8 @@
#include "esp_netif.h"
esp_err_t ptp_clock_start(esp_netif_t *netif);
// Re-read the "ptp" config group (role, priorities, intervals, domain, DSCP) in the PTP task.
void ptp_clock_reconfig(void);
bool ptp_clock_gm_id(char out[24]);
bool ptp_clock_locked(void);
// Adds the "ptp" object to /api/status.
+14
View File
@@ -18,6 +18,7 @@ typedef struct {
uint8_t type;
uint16_t seq;
uint8_t port_id[10];
uint8_t mac[6]; // Ethernet source
eth_mac_time_t ts;
} rx_rec_t;
@@ -48,6 +49,7 @@ static esp_err_t rx_hook(esp_eth_handle_t eth, uint8_t *buf, uint32_t len, void
r->type = ptp[0] & 0x0f;
r->seq = (ptp[30] << 8) | ptp[31];
memcpy(r->port_id, ptp + 20, 10);
memcpy(r->mac, buf + 6, 6);
r->ts = *ts;
portEXIT_CRITICAL(&s_lock);
}
@@ -56,6 +58,12 @@ static esp_err_t rx_hook(esp_eth_handle_t eth, uint8_t *buf, uint32_t len, void
}
bool ptp_hw_rx_ts(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts)
{
return ptp_hw_rx_ts_mac(msg_type, seq, src_port_id, ts, NULL);
}
bool ptp_hw_rx_ts_mac(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts,
uint8_t src_mac[6])
{
bool found = false;
portENTER_CRITICAL(&s_lock);
@@ -63,6 +71,9 @@ bool ptp_hw_rx_ts(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, et
rx_rec_t *r = &s_rx[i];
if (r->used && r->type == msg_type && r->seq == seq && memcmp(r->port_id, src_port_id, 10) == 0) {
*ts = r->ts;
if (src_mac) {
memcpy(src_mac, r->mac, 6);
}
r->used = false;
found = true;
break;
@@ -181,6 +192,9 @@ esp_err_t ptp_hw_init(esp_eth_handle_t eth, esp_netif_t *netif)
}
// IDF enables timestamping for PTP over Ethernet (L2) only; AES67 uses UDP/IPv4.
emac_ll_ts_ptp_ip4_enable(&EMAC_PTP, true);
// The PTP packet filter only stamps multicast PTP; unicast Delay_Req (hybrid mode) would get
// no timestamp. Stamp every frame instead; rx_hook picks the PTP event messages.
emac_ll_ts_all_enable(&EMAC_PTP, true);
// The netif glue registered its own input path; take it over and forward to the netif.
err = esp_eth_update_input_path_info(eth, rx_hook, netif);
+3
View File
@@ -19,6 +19,9 @@ esp_err_t ptp_hw_init(esp_eth_handle_t eth, esp_netif_t *netif);
// Hardware RX timestamp of an event message (UDP port 319), looked up by type,
// sequence ID and sourcePortIdentity (10 bytes). Each record is returned once.
bool ptp_hw_rx_ts(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts);
// Same, also returning the sender's Ethernet MAC (for unicast replies as raw frames). src_mac may be NULL.
bool ptp_hw_rx_ts_mac(uint8_t msg_type, uint16_t seq, const uint8_t *src_port_id, eth_mac_time_t *ts,
uint8_t src_mac[6]);
esp_err_t ptp_hw_get_time(eth_mac_time_t *t);
// Frequency correction relative to the nominal rate, in ppb (positive = faster).
esp_err_t ptp_hw_adj_freq(double ppb);
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+21
View File
@@ -164,6 +164,26 @@ static bool sap_wanted(uint8_t *ttl)
return on;
}
// When the PTP GM changes, the SDP's ts-refclk changes: bump the session version (RFC 4566 o=)
// so receivers see a new description. Runs whether or not SAP is on (manual SDP users too).
static void check_gm_change(void)
{
static char last[24];
char gm[24];
if (!aes67_ptp_gm_id(gm) || strcmp(gm, last) == 0) {
return;
}
if (last[0]) {
cJSON *a = cfg_get("aes67");
double ver = cJSON_GetObjectItemCaseSensitive(a, "session_ver")->valuedouble + 1;
cJSON_Delete(a);
// Not applied: re-applying the aes67 group would restart the stream.
esp_err_t err = cfg_set_number("aes67", "session_ver", ver, false);
ESP_LOGI(TAG, "PTP TimeTransmitter %s -> %s: session_ver %.0f (%s)", last, gm, ver, esp_err_to_name(err));
}
strcpy(last, gm);
}
static void sap_task(void *arg)
{
static char sdp[SDP_MAX];
@@ -172,6 +192,7 @@ static void sap_task(void *arg)
while (1) {
vTaskDelay(pdMS_TO_TICKS(1000));
check_gm_change();
esp_netif_ip_info_t ip;
esp_netif_t *netif = aes67_net_netif();
bool have_ip = netif && esp_netif_get_ip_info(netif, &ip) == ESP_OK && ip.ip.addr;
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+60 -6
View File
@@ -16,6 +16,7 @@
#include "lwip/inet.h"
#include "lwip/sockets.h"
#define AES67_RATE 48000 // the only sample rate (all sources are 48 kHz)
#define MAX_FRAMES 192 // 4 ms at 48 kHz
#define MAX_CH 2
#define RTP_HDR 12
@@ -56,7 +57,7 @@ static bool aes67_validate(const cJSON *g, char *err, size_t n)
{
static const char *const discovery[] = { "manual", "sap", NULL };
static const char *const encodings[] = { "L16", "L24", NULL };
static const double rates[] = { 48000, 96000 };
static const double rates[] = { AES67_RATE }; // the sources (player, test signals) are 48 kHz
static const double ptimes[] = { 0.125, 0.25, 0.333, 1, 4 };
bool ok = cfg_check_str(g, "name", 1, 63, err, n) &&
@@ -67,7 +68,7 @@ static bool aes67_validate(const cJSON *g, char *err, size_t n)
cfg_check_int(g, "dscp", 0, 63, err, n) &&
cfg_check_int(g, "channels", 1, 2, err, n) &&
cfg_check_enum(g, "encoding", encodings, err, n) &&
cfg_check_num_in(g, "rate", rates, 2, err, n) &&
cfg_check_num_in(g, "rate", rates, 1, err, n) &&
cfg_check_num_in(g, "ptime", ptimes, 5, err, n) &&
cfg_check_int(g, "pt", 96, 127, err, n) &&
cfg_check_int(g, "ssrc", 0, 4294967295.0, err, n) &&
@@ -106,6 +107,7 @@ typedef struct {
uint8_t ttl, dscp, pt;
uint32_t ssrc, clk_offset;
int channels, rate, bytes; // bytes per sample: 3 (L24) or 2 (L16)
bool mono_sum; // 1-channel stream carries (L + R) / 2, else L
int frames; // samples per channel per packet
} tx_cfg_t;
@@ -127,6 +129,7 @@ static bool load(tx_cfg_t *c)
c->ssrc = (uint32_t)NUM("ssrc");
c->clk_offset = (uint32_t)NUM("clk_offset");
c->channels = (int)NUM("channels");
c->mono_sum = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(a, "mono_sum"));
c->rate = (int)NUM("rate");
c->bytes = strcmp(cJSON_GetObjectItemCaseSensitive(a, "encoding")->valuestring, "L16") == 0 ? 2 : 3;
c->frames = (int)lround(NUM("ptime") * c->rate / 1000.0); // 0.333 ms -> 16 at 48 kHz
@@ -166,11 +169,50 @@ static int64_t samples_to_ns(int64_t s, int rate)
return (s / rate) * 1000000000LL + ((s % rate) * 1000000000LL + rate - 1) / rate;
}
// Pink noise: xorshift32 white noise through Paul Kellet's refined pink filter (within 0.05 dB
// above 9 Hz). The scale gives -18 dBFS RMS (measured over 10 s; peaks about -6 dBFS).
#define PINK_SCALE 0.0714f
size_t aes67_tx_pink_noise(int32_t *buf, size_t frames)
{
static uint32_t rnd = 0x12345678;
static float b0, b1, b2, b3, b4, b5, b6;
for (size_t i = 0; i < frames; i++) {
rnd ^= rnd << 13;
rnd ^= rnd >> 17;
rnd ^= rnd << 5;
float w = (int32_t)rnd * (1.0f / 2147483648.0f); // -1..1
b0 = 0.99886f * b0 + w * 0.0555179f;
b1 = 0.99332f * b1 + w * 0.0750759f;
b2 = 0.96900f * b2 + w * 0.1538520f;
b3 = 0.86650f * b3 + w * 0.3104856f;
b4 = 0.55000f * b4 + w * 0.5329522f;
b5 = -0.7616f * b5 - w * 0.0168980f;
float pink = b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362f;
b6 = w * 0.115926f;
float x = pink * PINK_SCALE;
x = x > 0.999f ? 0.999f : x < -0.999f ? -0.999f : x; // never reached in practice
int32_t v = (int32_t)(x * 2147483647.0f);
buf[i * AES67_TX_SRC_CHANNELS] = v;
buf[i * AES67_TX_SRC_CHANNELS + 1] = v;
}
return frames;
}
// Stereo source -> 1-channel stream, in place. The sum is in 64 bit, so it can't clip; identical
// L/R comes out at the same level.
static void to_mono(int32_t *buf, int frames, bool sum)
{
for (int i = 0; i < frames; i++) {
buf[i] = sum ? (int32_t)(((int64_t)buf[2 * i] + buf[2 * i + 1]) / 2) : buf[2 * i];
}
}
// 1 kHz tone, phase from the PTP sample index, so every sender's tone lines up.
// One period is rate / 1000 samples (48 at 48 kHz, 96 at 96 kHz): precomputed table.
// One period is rate / 1000 samples (48 at 48 kHz): precomputed table.
static void tone(int32_t *buf, int frames, int channels, int rate, int64_t s0)
{
static int32_t table[96000 / TONE_HZ];
static int32_t table[AES67_RATE / TONE_HZ];
static int table_rate;
int period = rate / TONE_HZ;
if (table_rate != rate) {
@@ -202,7 +244,7 @@ static void tx_task(void *arg)
esp_timer_handle_t timer = NULL;
const esp_timer_create_args_t targs = { .callback = timer_cb, .name = "aes67_tx" };
esp_timer_create(&targs, &timer);
static int32_t pcm[MAX_FRAMES * MAX_CH];
static int32_t pcm[MAX_FRAMES * (MAX_CH > AES67_TX_SRC_CHANNELS ? MAX_CH : AES67_TX_SRC_CHANNELS)];
static uint8_t pkt[RTP_HDR + MAX_FRAMES * MAX_CH * 3];
uint16_t seq = (uint16_t)esp_random();
int64_t next = 0; // sample index of the next packet; 0 = resync needed
@@ -250,9 +292,13 @@ static void tx_task(void *arg)
if (read) {
size_t got = read(pcm, c.frames);
if (got < (size_t)c.frames) {
memset(pcm + got * c.channels, 0, (c.frames - got) * c.channels * sizeof(int32_t));
memset(pcm + got * AES67_TX_SRC_CHANNELS, 0,
(c.frames - got) * AES67_TX_SRC_CHANNELS * sizeof(int32_t));
s_underruns++;
}
if (c.channels == 1) {
to_mono(pcm, c.frames, c.mono_sum);
}
} else {
tone(pcm, c.frames, c.channels, c.rate, next);
}
@@ -316,5 +362,13 @@ esp_err_t aes67_tx_init(void)
if (err != ESP_OK) {
return err;
}
// Stored before 96 kHz was dropped: stored values aren't re-validated, so fix it here (SDP too).
cJSON *a = cfg_get("aes67");
double rate = cJSON_GetObjectItemCaseSensitive(a, "rate")->valuedouble;
cJSON_Delete(a);
if (rate != AES67_RATE) {
ESP_LOGW(TAG, "stored sample rate %.0f not supported: using %d", rate, AES67_RATE);
cfg_set_number("aes67", "rate", AES67_RATE, false);
}
return status_register(tx_status);
}
+6 -1
View File
@@ -7,8 +7,10 @@
#include "esp_err.h"
// Audio source: fill buf with frames x channels interleaved samples (full scale = INT32_MAX).
// Audio source: fill buf with frames x AES67_TX_SRC_CHANNELS interleaved samples (stereo, full scale =
// INT32_MAX), whatever the stream's channel count: TX maps it (mono stream: L, or (L+R)/2 with mono_sum).
// Return the number of frames delivered; fewer than asked counts as an underrun (padded with silence).
#define AES67_TX_SRC_CHANNELS 2
typedef size_t (*aes67_tx_read_cb_t)(int32_t *buf, size_t frames);
// Registers the "aes67" config group and the TX status fields.
@@ -17,3 +19,6 @@ esp_err_t aes67_tx_init(void);
esp_err_t aes67_tx_start(void);
// Set the audio source. NULL = built-in 1 kHz test tone at -18 dBFS, phase-locked to PTP time.
void aes67_tx_set_source(aes67_tx_read_cb_t read);
// Ready-made source: pink noise at -18 dBFS RMS (peaks about -6 dBFS), same on L and R.
// Pass it to aes67_tx_set_source(). Keeps state: use for one stream only.
size_t aes67_tx_pink_noise(int32_t *buf, size_t frames);
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+107 -2
View File
@@ -13,6 +13,7 @@
#include "nvs_flash.h"
#define MAX_GROUPS 12
#define MAX_SECRETS 4
#define MAX_BODY 8192
#define NVS_NAMESPACE "cfg"
@@ -24,6 +25,8 @@ typedef struct {
cJSON *values;
cfg_validate_cb_t validate;
cfg_apply_cb_t apply;
char secrets[MAX_SECRETS][24]; // write-only keys
int n_secrets;
} cfg_group_t;
static cfg_group_t s_groups[MAX_GROUPS];
@@ -220,6 +223,35 @@ esp_err_t cfg_register(const char *group, const char *defaults_json,
return ESP_OK;
}
esp_err_t cfg_mark_secret(const char *group, const char *key)
{
if (!s_lock) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
cfg_group_t *g = find(group);
esp_err_t err = ESP_OK;
if (!g || !cJSON_IsString(cJSON_GetObjectItemCaseSensitive(g->defaults, key))) {
err = ESP_ERR_NOT_FOUND;
} else if (g->n_secrets >= MAX_SECRETS || strlen(key) >= sizeof(g->secrets[0])) {
err = ESP_ERR_NO_MEM;
} else {
strcpy(g->secrets[g->n_secrets++], key);
}
xSemaphoreGive(s_lock);
return err;
}
// Group values for the API: secrets blanked.
static cJSON *public_values(const cfg_group_t *g)
{
cJSON *v = cJSON_Duplicate(g->values, true);
for (int i = 0; i < g->n_secrets; i++) {
cJSON_ReplaceItemInObjectCaseSensitive(v, g->secrets[i], cJSON_CreateString(""));
}
return v;
}
cJSON *cfg_get(const char *group)
{
if (!s_lock) {
@@ -232,6 +264,68 @@ cJSON *cfg_get(const char *group)
return copy;
}
esp_err_t cfg_set_number(const char *group, const char *key, double value, bool apply)
{
if (!s_lock) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
cfg_group_t *g = find(group);
cJSON *cur = g ? cJSON_GetObjectItemCaseSensitive(g->values, key) : NULL;
esp_err_t err = ESP_OK;
if (!cur || !cJSON_IsNumber(cur)) {
err = ESP_ERR_NOT_FOUND;
} else {
cJSON_SetNumberValue(cur, value);
nvs_handle_t h;
if (s_nvs_ok && (err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h)) == ESP_OK) {
err = store(h, g);
if (err == ESP_OK) {
err = nvs_commit(h);
}
nvs_close(h);
}
}
cJSON *copy = err == ESP_OK && apply && g->apply ? cJSON_Duplicate(g->values, true) : NULL;
xSemaphoreGive(s_lock);
if (copy) {
g->apply(copy);
cJSON_Delete(copy);
}
return err;
}
esp_err_t cfg_set_string(const char *group, const char *key, const char *value, bool apply)
{
if (!s_lock) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_lock, portMAX_DELAY);
cfg_group_t *g = find(group);
cJSON *cur = g ? cJSON_GetObjectItemCaseSensitive(g->values, key) : NULL;
esp_err_t err = ESP_OK;
if (!cur || !cJSON_IsString(cur)) {
err = ESP_ERR_NOT_FOUND;
} else {
cJSON_ReplaceItemInObjectCaseSensitive(g->values, key, cJSON_CreateString(value));
nvs_handle_t h;
if (s_nvs_ok && (err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &h)) == ESP_OK) {
err = store(h, g);
if (err == ESP_OK) {
err = nvs_commit(h);
}
nvs_close(h);
}
}
cJSON *copy = err == ESP_OK && apply && g->apply ? cJSON_Duplicate(g->values, true) : NULL;
xSemaphoreGive(s_lock);
if (copy) {
g->apply(copy);
cJSON_Delete(copy);
}
return err;
}
/* ----- HTTP ----- */
static esp_err_t config_get(httpd_req_t *req)
@@ -239,7 +333,7 @@ static esp_err_t config_get(httpd_req_t *req)
cJSON *all = cJSON_CreateObject();
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < s_group_n; i++) {
cJSON_AddItemToObject(all, s_groups[i].name, cJSON_Duplicate(s_groups[i].values, true));
cJSON_AddItemToObject(all, s_groups[i].name, public_values(&s_groups[i]));
}
xSemaphoreGive(s_lock);
esp_err_t err = web_send_json(req, all);
@@ -300,7 +394,18 @@ static esp_err_t config_post(httpd_req_t *req)
break;
}
cand[i] = cJSON_Duplicate(g->values, true);
ok = merge_known(cand[i], g->defaults, src, g->name, err, sizeof(err));
// Secrets: "" = unchanged (the API never returns the stored value), null = clear.
cJSON *in_g = cJSON_Duplicate(src, true);
for (int k = 0; k < g->n_secrets; k++) {
const cJSON *sv = cJSON_GetObjectItemCaseSensitive(in_g, g->secrets[k]);
if (cJSON_IsString(sv) && !sv->valuestring[0]) {
cJSON_DeleteItemFromObjectCaseSensitive(in_g, g->secrets[k]);
} else if (cJSON_IsNull(sv)) {
cJSON_ReplaceItemInObjectCaseSensitive(in_g, g->secrets[k], cJSON_CreateString(""));
}
}
ok = merge_known(cand[i], g->defaults, in_g, g->name, err, sizeof(err));
cJSON_Delete(in_g);
if (ok && g->validate) {
char verr[96] = "";
ok = g->validate(cand[i], verr, sizeof(verr));
+8
View File
@@ -18,8 +18,16 @@ esp_err_t cfg_override_defaults(const char *group, const char *json);
// Register a group. Stored values (NVS) are loaded immediately, merged over the defaults.
esp_err_t cfg_register(const char *group, const char *defaults_json,
cfg_validate_cb_t validate, cfg_apply_cb_t apply);
// Write-only key (e.g. a password): GET /api/config returns "" for it; a POST with "" keeps the
// stored value, null clears it. cfg_get() still returns the real value. Call after cfg_register().
esp_err_t cfg_mark_secret(const char *group, const char *key);
// Copy of a group's current values; caller frees with cJSON_Delete. NULL if not registered.
cJSON *cfg_get(const char *group);
// Firmware-side change of one number (e.g. aes67.session_ver): stored like a POST, no validation.
// apply = false skips the group's apply callback (e.g. to avoid restarting the stream).
esp_err_t cfg_set_number(const char *group, const char *key, double value, bool apply);
// Same for a string value.
esp_err_t cfg_set_string(const char *group, const char *key, const char *value, bool apply);
// Validation helpers for validate callbacks. Each returns false and fills err on failure.
bool cfg_check_num(const cJSON *g, const char *key, double min, double max, char *err, size_t n);
+49
View File
@@ -0,0 +1,49 @@
# Spotify Connect via cspot (philippe44 fork, git submodule external/cspot). GPL-3.0.
# Project component (not part of the reusable aes67_* core).
idf_component_register(SRCS "spotify.cpp"
INCLUDE_DIRS "include"
PRIV_REQUIRES aes67_web espressif__mdns mbedtls json pthread lwip esp_timer esp_http_server)
# bell: only what cspot needs (Tremor Vorbis inside; no codec wrapper, sinks, MQTT, web server).
set(BELL_DISABLE_CODECS ON CACHE BOOL "" FORCE)
set(BELL_DISABLE_SINKS ON CACHE BOOL "" FORCE)
set(BELL_DISABLE_MQTT ON CACHE BOOL "" FORCE)
set(BELL_DISABLE_WEBSERVER ON CACHE BOOL "" FORCE)
set(BELL_DISABLE_FMT ON CACHE BOOL "" FORCE)
set(BELL_DISABLE_REGEX ON CACHE BOOL "" FORCE)
set(BELL_ONLY_CJSON ON CACHE BOOL "" FORCE)
set(BELL_EXTERNAL_CJSON idf::json CACHE STRING "" FORCE)
option(BUILD_TESTING OFF)
# Our fixes to the pinned cspot / bell sources (newer GCC, protobuf, CMake), kept as patch files:
# patches/cspot/*.patch apply in external/cspot, patches/bell/*.patch in external/cspot/cspot/bell.
# Each is applied once (skipped when it already reverse-applies).
function(spotify_apply_patches dir repo)
file(GLOB patches "${CMAKE_CURRENT_LIST_DIR}/patches/${dir}/*.patch")
list(SORT patches)
foreach(p ${patches})
execute_process(COMMAND git apply --reverse --check "${p}" WORKING_DIRECTORY "${repo}"
RESULT_VARIABLE applied OUTPUT_QUIET ERROR_QUIET)
if(NOT applied EQUAL 0)
execute_process(COMMAND git apply "${p}" WORKING_DIRECTORY "${repo}" RESULT_VARIABLE rc)
if(NOT rc EQUAL 0)
message(FATAL_ERROR "spotify: patch does not apply: ${p}")
endif()
message(STATUS "spotify: applied ${p}")
endif()
endforeach()
endfunction()
spotify_apply_patches(cspot "${PROJECT_DIR}/external/cspot")
spotify_apply_patches(bell "${PROJECT_DIR}/external/cspot/cspot/bell")
# cspot/bell declare cmake_minimum_required(2.8.12); CMake 4 rejects < 3.5 unless told otherwise.
set(CMAKE_POLICY_VERSION_MINIMUM 3.5)
add_subdirectory(${PROJECT_DIR}/external/cspot/cspot ${CMAKE_CURRENT_BINARY_DIR}/cspot)
# bell adds Xtensa (ESP32) assembly for a DSP biquad; the P4 is RISC-V and cspot does not use it.
get_target_property(BELL_SRCS bell SOURCES)
list(FILTER BELL_SRCS EXCLUDE REGEX "\\.S$")
set_target_properties(bell PROPERTIES SOURCES "${BELL_SRCS}")
target_link_libraries(${COMPONENT_LIB} PRIVATE cspot)
target_compile_options(${COMPONENT_LIB} PRIVATE -std=gnu++20)
+64
View File
@@ -0,0 +1,64 @@
// Spotify Connect (cspot). Project code; GPL-3.0 through cspot.
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
SPOTIFY_EV_PLAY, // playback (re)started or resumed
SPOTIFY_EV_PAUSE,
SPOTIFY_EV_FLUSH, // skip, seek, new track: drop buffered audio
SPOTIFY_EV_VOLUME, // value: 0..65535
} spotify_event_t;
// PCM from Spotify: 44.1 kHz stereo s16 interleaved. Return the frames taken (may block).
typedef size_t (*spotify_pcm_cb_t)(const int16_t *pcm, size_t frames);
typedef void (*spotify_event_cb_t)(spotify_event_t ev, int value);
// Output positions in frames (monotonic, wrap at 2^32): written into the output buffer so far, and
// played out so far. Used to tell Spotify when a new track actually becomes audible.
typedef uint32_t (*spotify_pos_cb_t)(void);
// Registers the zeroconf endpoints (/spotify_info) and starts the session task (disabled until
// spotify_apply(true)).
esp_err_t spotify_init(spotify_pcm_cb_t pcm, spotify_event_cb_t event, spotify_pos_cb_t written,
spotify_pos_cb_t played);
// Enable (advertised, sessions accepted) when the player's mode needs Spotify and the client
// credentials are set; otherwise not advertised and a running session is ended. Re-reads name and
// credentials from the "source" config: a new device name ends the session and re-advertises.
void spotify_apply(bool enable);
typedef enum {
SPOTIFY_CMD_PLAY, SPOTIFY_CMD_PAUSE, SPOTIFY_CMD_NEXT, SPOTIFY_CMD_PREV,
SPOTIFY_CMD_SEEK, // arg: position in ms
} spotify_cmd_t;
// Control the running session (the Spotify app follows). Runs on the session task; waits until it
// has run (max 1 s). Returns false without a session.
bool spotify_command(spotify_cmd_t cmd, uint32_t arg);
// Suspend: end any running session (waits until its tasks are gone, max ~3 s) and refuse new ones.
// Resume: back to what the config says. Used around firmware uploads.
void spotify_suspend(bool suspend);
// The player's volume (0..100 %): reported to the Spotify app when a session starts (else the app
// shows 0 while we play at the player's level), and pushed to a running session.
void spotify_set_volume(int pct);
// A session is running (an app is connected to this device).
bool spotify_session_active(void);
typedef struct {
char artist[96], title[128], album[96]; // "" until the first track is audible
uint32_t duration_ms, position_ms; // position as the Spotify app sees it
bool paused;
} spotify_track_t;
// The current track of the running session. False without a session.
bool spotify_now_playing(spotify_track_t *t);
// Current state for status.spotify_state.
const char *spotify_state(void);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1,18 @@
diff --git a/external/nanopb/generator/nanopb_generator.py b/external/nanopb/generator/nanopb_generator.py
index e40f18b..64dad5e 100755
--- a/external/nanopb/generator/nanopb_generator.py
+++ b/external/nanopb/generator/nanopb_generator.py
@@ -1463,7 +1463,12 @@ class Message(ProtoElement):
optional_only.ClearField(str('extension'))
optional_only.ClearField(str('enum_type'))
desc = google.protobuf.descriptor.MakeDescriptor(optional_only)
- msg = reflection.MakeClass(desc)()
+ # protobuf >= 5 removed reflection.MakeClass (patch for this project)
+ try:
+ msg = reflection.MakeClass(desc)()
+ except AttributeError:
+ from google.protobuf import message_factory
+ msg = message_factory.GetMessageClass(desc)()
for field in optional_only.field:
if field.type == FieldD.TYPE_STRING:
@@ -0,0 +1,13 @@
diff --git a/main/io/URLParser.cpp b/main/io/URLParser.cpp
index 4a50ab1..af679ec 100644
--- a/main/io/URLParser.cpp
+++ b/main/io/URLParser.cpp
@@ -1,5 +1,8 @@
#include "URLParser.h"
+#include <cstdio> // sscanf (GCC 14 / ESP-IDF 5.5: not included transitively)
+#include <cstring> // strstr
+
namespace bell {
#ifdef BELL_DISABLE_REGEX
@@ -0,0 +1,172 @@
From philippe44/cspot PR #3 (open, 2026-08): "MercurySession: crash when a request
races the reconnection (null conn/shanConn)". Our sessions reconnect every ~6 min, so the
race is hit regularly. Drop this patch once the fix is in the pinned cspot commit.
diff --git a/cspot/include/Session.h b/cspot/include/Session.h
index df7f03c8..7cc8e32f 100644
--- a/cspot/include/Session.h
+++ b/cspot/include/Session.h
@@ -2,6 +2,7 @@
#include <stdint.h> // for uint8_t
#include <memory> // for shared_ptr, unique_ptr
+#include <mutex> // for mutex
#include <string> // for string
#include <vector> // for vector
@@ -23,6 +24,11 @@ class Session {
std::shared_ptr<cspot::PlainConnection> conn;
std::shared_ptr<LoginBlob> authBlob;
+ /* conn and shanConn are swapped by the session's task during reconnection,
+ * but other tasks send through them; they must hold this while copying the
+ * pointers, and the session's task while replacing them */
+ std::mutex connMutex;
+
std::string deviceId = "142137fd329622137a14901634264e6f332e2411";
public:
diff --git a/cspot/src/MercurySession.cpp b/cspot/src/MercurySession.cpp
index 7aafbb76..29a6e546 100644
--- a/cspot/src/MercurySession.cpp
+++ b/cspot/src/MercurySession.cpp
@@ -66,8 +66,11 @@ void MercurySession::reconnect() {
isReconnecting = true;
try {
- this->conn = nullptr;
- this->shanConn = nullptr;
+ {
+ std::scoped_lock lock(connMutex);
+ this->conn = nullptr;
+ this->shanConn = nullptr;
+ }
this->connectWithRandomAp();
this->authenticate(this->authBlob);
@@ -127,7 +130,17 @@ void MercurySession::unregisterAudioKey(uint32_t sequenceId) {
void MercurySession::disconnect() {
CSPOT_LOG(info, "Disconnecting mercury session");
this->isRunning = false;
- conn->close();
+
+ /* conn is null while a reconnection is in flight; isRunning above already
+ * makes the retry loop exit, closing is just to unblock a pending read */
+ std::shared_ptr<PlainConnection> conn;
+ {
+ std::scoped_lock lock(connMutex);
+ conn = this->conn;
+ }
+ if (conn)
+ conn->close();
+
std::scoped_lock lock(this->isRunningMutex);
}
@@ -305,8 +318,22 @@ uint64_t MercurySession::executeSubscription(RequestType method,
// Bump sequence id
this->sequenceId += 1;
+ /* the session's task may be swapping shanConn for a reconnection right now,
+ * and dereferencing it here would not be a catchable failure, so take a
+ * snapshot; when disconnected, the request is simply lost */
+ std::shared_ptr<ShannonConnection> shanConn;
+ {
+ std::scoped_lock lock(connMutex);
+ shanConn = this->shanConn;
+ }
+
+ if (!shanConn) {
+ CSPOT_LOG(info, "Mercury request skipped, session is reconnecting");
+ return this->sequenceId - 1;
+ }
+
try {
- this->shanConn->sendPacket(
+ shanConn->sendPacket(
static_cast<std::underlying_type<RequestType>::type>(method),
sequenceIdBytes);
} catch (...) {
@@ -337,8 +364,21 @@ uint32_t MercurySession::requestAudioKey(const std::vector<uint8_t>& trackId,
// Used for broken connection detection
// this->lastRequestTimestamp = timeProvider->getSyncedTimestamp();
+
+ // same snapshot as executeSubscription: this runs on the track queue's task
+ std::shared_ptr<ShannonConnection> shanConn;
+ {
+ std::scoped_lock lock(connMutex);
+ shanConn = this->shanConn;
+ }
+
+ if (!shanConn) {
+ CSPOT_LOG(info, "Audio key request skipped, session is reconnecting");
+ return audioKeySequence - 1;
+ }
+
try {
- this->shanConn->sendPacket(
+ shanConn->sendPacket(
static_cast<uint8_t>(RequestType::AUDIO_KEY_REQUEST_COMMAND), buffer);
} catch (...) {
// @TODO: Handle disconnect
diff --git a/cspot/src/Session.cpp b/cspot/src/Session.cpp
index 74bd0633..be154bbe 100644
--- a/cspot/src/Session.cpp
+++ b/cspot/src/Session.cpp
@@ -4,6 +4,7 @@
#include <cstdint> // for uint8_t
#include <functional> // for __base
#include <memory> // for shared_ptr, unique_ptr, make_unique
+#include <mutex> // for scoped_lock
#include <random> // for default_random_engine, independent_bi...
#include <type_traits> // for remove_extent_t
#include <utility> // for move
@@ -33,7 +34,10 @@ Session::Session() {
Session::~Session() {}
void Session::connect(std::unique_ptr<cspot::PlainConnection> connection) {
- this->conn = std::move(connection);
+ {
+ std::scoped_lock lock(connMutex);
+ this->conn = std::move(connection);
+ }
conn->timeoutHandler = [this]() {
return this->triggerTimeout();
};
@@ -48,11 +52,15 @@ void Session::connect(std::unique_ptr<cspot::PlainConnection> connection) {
CSPOT_LOG(debug, "Received shannon keys");
// Generates the public and priv key
- this->shanConn = std::make_shared<ShannonConnection>();
+ auto shanConn = std::make_shared<ShannonConnection>();
+
+ // Init shanno-encrypted connection, and only then publish it so another
+ // task cannot pick up a connection that is not wrapped yet
+ shanConn->wrapConnection(this->conn, challenges->shanSendKey,
+ challenges->shanRecvKey);
- // Init shanno-encrypted connection
- this->shanConn->wrapConnection(this->conn, challenges->shanSendKey,
- challenges->shanRecvKey);
+ std::scoped_lock lock(connMutex);
+ this->shanConn = shanConn;
}
void Session::connectWithRandomAp() {
diff --git a/cspot/src/TrackReference.cpp b/cspot/src/TrackReference.cpp
index b4fafcb5..203fe041 100644
--- a/cspot/src/TrackReference.cpp
+++ b/cspot/src/TrackReference.cpp
@@ -43,9 +43,9 @@ bool TrackReference::pbEncodeTrackList(pb_ostream_t* stream,
// concurrent rebuild cannot reallocate the vector under us
std::scoped_lock lock(*locked->mutex);
auto& trackQueue = *locked->tracks;
-#ifdef ESP_PLATFORM
+#ifdef ESP_PLATFORM
static TrackRef msg = TrackRef_init_zero;
-#else
+#else
TrackRef msg = TrackRef_init_zero;
#endif
@@ -0,0 +1,15 @@
diff --git a/cspot/src/PlainConnection.cpp b/cspot/src/PlainConnection.cpp
index 1bff6cf..b4ee6ff 100644
--- a/cspot/src/PlainConnection.cpp
+++ b/cspot/src/PlainConnection.cpp
@@ -150,6 +150,10 @@ void PlainConnection::readBlock(const uint8_t* dst, size_t size) {
case EINTR:
break;
default:
+ // diagnostic (project patch): n == 0 means the peer closed (FIN); n < 0 with errno
+ // e.g. ECONNRESET (RST). Note errno is not updated when n == 0.
+ CSPOT_LOG(error, "recv returned %d, errno %d, %u of %u bytes, retry %d", (int)n,
+ getErrno(), idx, (unsigned)size, retries);
if (retries++ > 4)
throw std::runtime_error("Error in read");
goto READ;
@@ -0,0 +1,74 @@
Keep-alive like librespot (core/src/session.rs): the server sends a Ping every ~2 min; send
the Pong 60 s later, not at once. With an immediate Pong the server reset the AP connection
(ECONNRESET) on the third Ping, i.e. every 6 minutes, and the Spotify app lost the device.
--- a/cspot/include/MercurySession.h
+++ b/cspot/include/MercurySession.h
@@ -120,6 +120,14 @@
unsigned long long timestampDiff;
unsigned long long lastPingTimestamp = -1;
+
+ // Keep-alive as librespot does it: Ping -> wait 60 s -> Pong -> PongAck. Answering at once made
+ // the server reset the connection on the third Ping (every 6 minutes).
+ const int PONG_DELAY_MS = 60 * 1000;
+ bool pongPending = false;
+ unsigned long long pongDueTimestamp = 0;
+ std::vector<uint8_t> pongData;
+ void sendPendingPong();
std::string countryCode = "";
std::mutex isRunningMutex;
--- a/cspot/src/MercurySession.cpp
+++ b/cspot/src/MercurySession.cpp
@@ -45,7 +45,10 @@
timeProvider->syncWithPingPacket(packet.data);
this->lastPingTimestamp = timeProvider->getSyncedTimestamp();
- this->shanConn->sendPacket(0x49, packet.data);
+ // Pong 60 s later (sent from triggerTimeout(), called on every 3 s receive timeout)
+ this->pongData = packet.data;
+ this->pongDueTimestamp = this->lastPingTimestamp + PONG_DELAY_MS;
+ this->pongPending = true;
} else {
this->packetQueue.push(packet);
}
@@ -80,6 +83,7 @@
BELL_SLEEP_MS(100);
lastPingTimestamp = timeProvider->getSyncedTimestamp();
+ pongPending = false; // a Ping on the old connection needs no Pong on the new one
isReconnecting = false;
this->executeEstabilishedCallback = true;
@@ -98,9 +102,30 @@
this->connectionReadyCallback = callback;
}
+void MercurySession::sendPendingPong() {
+ if (!pongPending ||
+ timeProvider->getSyncedTimestamp() < pongDueTimestamp)
+ return;
+ pongPending = false;
+ std::shared_ptr<ShannonConnection> shanConn;
+ {
+ std::scoped_lock lock(connMutex);
+ shanConn = this->shanConn;
+ }
+ if (!shanConn)
+ return;
+ try {
+ shanConn->sendPacket(0x49, pongData);
+ CSPOT_LOG(info, "Sent delayed Pong");
+ } catch (...) {
+ CSPOT_LOG(error, "Failed to send Pong");
+ }
+}
+
bool MercurySession::triggerTimeout() {
if (!isRunning)
return true;
+ sendPendingPong();
auto currentTimestamp = timeProvider->getSyncedTimestamp();
if (currentTimestamp - this->lastPingTimestamp > PING_TIMEOUT_MS) {
@@ -0,0 +1,14 @@
diff --git a/cspot/include/SpircHandler.h b/cspot/include/SpircHandler.h
index 7ff930b..c17caa0 100644
--- a/cspot/include/SpircHandler.h
+++ b/cspot/include/SpircHandler.h
@@ -44,6 +44,9 @@ class SpircHandler {
void subscribeToMercury();
std::shared_ptr<TrackPlayer> getTrackPlayer();
+ // Read access for the host (now-playing info: track position, play state).
+ std::shared_ptr<PlaybackState> getPlaybackState() { return playbackState; }
+ std::shared_ptr<cspot::Context> getContext() { return ctx; }
void setEventHandler(EventHandler handler);
+563
View File
@@ -0,0 +1,563 @@
#include "spotify.h"
#include <atomic>
#include <cstring>
#include <exception>
#include <deque>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include "BellLogger.h"
#include "CSpotContext.h"
#include "LoginBlob.h"
#include "PlaybackState.h"
#include "SpircHandler.h"
#include "TrackPlayer.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "mdns.h"
extern "C" {
#include "aes67_cfg.h"
#include "aes67_web.h"
}
#define BODY_MAX 8192
static const char *TAG = "spotify";
static std::shared_ptr<cspot::LoginBlob> s_blob; // guarded by s_mutex
static std::mutex s_mutex;
static std::string s_name; // advertised device name ("" = not advertised)
static std::atomic<bool> s_enabled{false};
static std::atomic<bool> s_want{false}; // last spotify_apply(): the player needs Spotify
static std::atomic<bool> s_stop{false}; // end the running session
static std::atomic<bool> s_got_blob{false};
static std::atomic<bool> s_in_session{false}; // session() running (its tasks may exist)
static std::atomic<int> s_volume{65535}; // player volume in Spotify units (0..65535)
static std::atomic<const char *> s_state{"disabled"};
static std::atomic<uint64_t> s_pcm_bytes{0};
static std::shared_ptr<cspot::SpircHandler> s_handler; // running session, else null
static spotify_pcm_cb_t s_pcm_cb;
static spotify_event_cb_t s_event_cb;
static spotify_pos_cb_t s_written, s_played;
// Track boundaries in the output buffer: when playback passes one, the new track is audible and
// Spotify must be told (notifyAudioReachedPlayback); without it the app's state stalls after the
// first track and it drops the device. Guarded by s_bound_mutex (data callback vs session loop).
struct Boundary {
uint32_t pos;
std::string id;
};
static std::mutex s_bound_mutex;
static std::deque<Boundary> s_bounds;
static std::string s_last_id; // track of the most recent data callback
static std::atomic<bool> s_depleted{false};
static std::mutex s_cmd_mutex;
enum { CMD_VOLUME = 100 }; // internal: push s_volume to the app
struct Command {
int cmd; // spotify_cmd_t or CMD_VOLUME
uint32_t arg;
};
static std::deque<Command> s_cmds; // from spotify_command(), run by the session loop
static uint32_t s_cmd_queued; // commands queued so far (s_cmd_mutex)
static std::atomic<uint32_t> s_cmd_done{0}; // commands run so far
static std::mutex s_track_mutex;
static cspot::TrackInfo s_track; // audible track (TRACK_INFO), guarded by s_track_mutex
static void clear_boundaries(bool new_load)
{
std::lock_guard<std::mutex> lock(s_bound_mutex);
s_bounds.clear();
if (new_load) {
s_last_id.clear(); // the next data (new track) marks a boundary
}
}
// Session loop, every <= 200 ms.
static void check_playback(const std::shared_ptr<cspot::SpircHandler> &handler)
{
if (!s_written || !s_played) {
return;
}
uint32_t played = s_played();
std::string reached;
{
std::lock_guard<std::mutex> lock(s_bound_mutex);
while (!s_bounds.empty() && (int32_t)(played - s_bounds.front().pos) >= 0) {
reached = s_bounds.front().id; // latest boundary passed wins
s_bounds.pop_front();
}
}
if (!reached.empty()) {
handler->notifyAudioReachedPlayback(reached);
ESP_LOGI(TAG, "track audible, Spotify notified");
}
if (s_depleted && played == s_written()) {
s_depleted = false;
handler->notifyAudioEnded();
ESP_LOGI(TAG, "playlist ended, Spotify notified");
}
}
extern "C" void spotify_suspend(bool suspend)
{
if (!suspend) {
spotify_apply(s_want);
return;
}
s_enabled = false;
s_stop = true;
s_got_blob = false;
s_state = "suspended";
for (int i = 0; i < 30 && s_in_session; i++) { // session loop exits within 200 ms, then disconnect
vTaskDelay(pdMS_TO_TICKS(100));
}
ESP_LOGI(TAG, "suspended%s", s_in_session ? " (session still ending)" : "");
}
extern "C" void spotify_set_volume(int pct)
{
pct = pct < 0 ? 0 : pct > 100 ? 100 : pct;
int v = pct * 65535 / 100;
if (v == s_volume) {
return;
}
s_volume = v;
if (s_handler) {
std::lock_guard<std::mutex> lock(s_cmd_mutex);
s_cmds.push_back({ CMD_VOLUME, 0 });
++s_cmd_queued;
}
}
extern "C" bool spotify_command(spotify_cmd_t cmd, uint32_t arg)
{
if (!s_handler) {
return false;
}
uint32_t seq;
{
std::lock_guard<std::mutex> lock(s_cmd_mutex);
s_cmds.push_back({ cmd, arg });
seq = ++s_cmd_queued;
}
// Wait until it has run (the loop runs every <= 200 ms), so callers can report the new state.
for (int i = 0; i < 50 && (int32_t)(s_cmd_done - seq) < 0 && s_handler; i++) {
vTaskDelay(pdMS_TO_TICKS(20));
}
return true;
}
// Session loop: run queued commands on the task that also handles Spotify's frames.
static void run_commands(const std::shared_ptr<cspot::SpircHandler> &handler)
{
std::deque<Command> cmds;
uint32_t seq;
{
std::lock_guard<std::mutex> lock(s_cmd_mutex);
cmds.swap(s_cmds);
seq = s_cmd_queued;
}
for (auto [cmd, arg] : cmds) {
switch (cmd) {
case SPOTIFY_CMD_PLAY:
case SPOTIFY_CMD_PAUSE:
handler->setPause(cmd == SPOTIFY_CMD_PAUSE); // notifies the app, sends PLAY_PAUSE
break;
case SPOTIFY_CMD_NEXT:
case SPOTIFY_CMD_PREV:
// The new track's load notifies the app and flushes our buffer (PLAYBACK_START).
if (!(cmd == SPOTIFY_CMD_NEXT ? handler->nextSong() : handler->previousSong())) {
ESP_LOGW(TAG, "no %s track", cmd == SPOTIFY_CMD_NEXT ? "next" : "previous");
}
break;
case SPOTIFY_CMD_SEEK:
// As for a seek from the app (SpircHandler::handleFrame): the buffered audio is void.
handler->getTrackPlayer()->seekMs(arg ? arg : 1); // 0 means "no seek" to TrackPlayer
handler->updatePositionMs(arg); // notifies the app
clear_boundaries(false);
s_depleted = false;
if (s_event_cb) {
s_event_cb(SPOTIFY_EV_FLUSH, 0);
}
break;
case CMD_VOLUME:
handler->setRemoteVolume(s_volume); // notifies the app
break;
}
ESP_LOGI(TAG, "command %d %lu", cmd, (unsigned long)arg);
}
s_cmd_done = seq;
}
extern "C" bool spotify_session_active(void)
{
return s_handler != nullptr;
}
extern "C" bool spotify_now_playing(spotify_track_t *t)
{
auto h = s_handler;
if (!h) {
return false;
}
{
std::lock_guard<std::mutex> lock(s_track_mutex);
strlcpy(t->artist, s_track.artist.c_str(), sizeof(t->artist));
strlcpy(t->title, s_track.name.c_str(), sizeof(t->title));
strlcpy(t->album, s_track.album.c_str(), sizeof(t->album));
t->duration_ms = s_track.duration;
}
// Same position the app shows: last reported position, plus the time since while playing.
const auto &st = h->getPlaybackState()->innerFrame.state;
t->paused = st.status != PlayStatus_kPlayStatusPlay;
uint64_t pos = st.position_ms;
if (!t->paused) {
pos += h->getContext()->timeProvider->getSyncedTimestamp() - st.position_measured_at;
}
t->position_ms = t->duration_ms && pos > t->duration_ms ? t->duration_ms : (uint32_t)pos;
return true;
}
const char *spotify_state(void)
{
return s_state.load();
}
/* ----- cspot/bell logging -> esp_log (UART + syslog) ----- */
// cspot logs through bell::bellGlobalLogger; without one, CSPOT_LOG dereferences NULL.
class EspLogger : public bell::AbstractLogger {
static void out(esp_log_level_t lvl, const std::string &file, int line, const std::string &sub,
const char *fmt, va_list ap)
{
char msg[256];
vsnprintf(msg, sizeof(msg), fmt, ap);
// CDN URLs carry signed tokens: keep them out of the log (syslog may leave the box).
char *q = strstr(msg, "?__token__=");
if (q) {
strcpy(q, "?__token__=...");
}
size_t slash = file.find_last_of('/');
const char *base = file.c_str() + (slash == std::string::npos ? 0 : slash + 1);
ESP_LOG_LEVEL(lvl, sub.empty() ? "cspot" : sub.c_str(), "%s:%d: %s", base, line, msg);
}
public:
void debug(std::string file, int line, std::string sub, const char *fmt, ...) override
{
va_list ap;
va_start(ap, fmt);
out(ESP_LOG_DEBUG, file, line, sub, fmt, ap);
va_end(ap);
}
void info(std::string file, int line, std::string sub, const char *fmt, ...) override
{
va_list ap;
va_start(ap, fmt);
out(ESP_LOG_INFO, file, line, sub, fmt, ap);
va_end(ap);
}
void error(std::string file, int line, std::string sub, const char *fmt, ...) override
{
va_list ap;
va_start(ap, fmt);
out(ESP_LOG_ERROR, file, line, sub, fmt, ap);
va_end(ap);
}
};
/* ----- zeroconf (Spotify Connect discovery) on our httpd ----- */
static std::shared_ptr<cspot::LoginBlob> blob()
{
std::lock_guard<std::mutex> lock(s_mutex);
return s_blob;
}
static esp_err_t info_get(httpd_req_t *req)
{
auto b = blob();
if (!s_enabled || !b) {
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Spotify Connect is disabled");
}
std::string json = b->buildZeroconfInfo();
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, json.data(), json.size());
}
static std::string url_decode(const char *s, size_t n)
{
std::string out;
for (size_t i = 0; i < n; i++) {
if (s[i] == '+') {
out += ' ';
} else if (s[i] == '%' && i + 2 < n && isxdigit((unsigned char)s[i + 1]) && isxdigit((unsigned char)s[i + 2])) {
char hex[3] = { s[i + 1], s[i + 2], 0 };
out += (char)strtol(hex, nullptr, 16);
i += 2;
} else {
out += s[i];
}
}
return out;
}
// The Spotify app posts its login blob (action=addUser&userName=...&blob=...&clientKey=...).
static esp_err_t info_post(httpd_req_t *req)
{
auto b = blob();
if (!s_enabled || !b) {
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "Spotify Connect is disabled");
}
if (req->content_len == 0 || req->content_len > BODY_MAX) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad body");
}
std::string body(req->content_len, '\0');
size_t got = 0;
while (got < body.size()) {
int r = httpd_req_recv(req, body.data() + got, body.size() - got);
if (r <= 0) {
return ESP_FAIL;
}
got += r;
}
std::map<std::string, std::string> query;
size_t pos = 0;
while (pos < body.size()) {
size_t amp = body.find('&', pos), end = amp == std::string::npos ? body.size() : amp;
size_t eq = body.find('=', pos);
if (eq != std::string::npos && eq < end) {
query[url_decode(&body[pos], eq - pos)] = url_decode(&body[eq + 1], end - eq - 1);
}
pos = end + 1;
}
ESP_LOGI(TAG, "zeroconf %s from \"%s\"", query["action"].c_str(), query["userName"].c_str());
b->loadZeroconfQuery(query);
s_got_blob = true;
static const char ok[] = "{\"status\":101,\"spotifyError\":0,\"statusString\":\"ERROR-OK\"}";
httpd_resp_set_type(req, "application/json");
return httpd_resp_send(req, ok, sizeof(ok) - 1);
}
/* ----- session ----- */
static const char *event_name(cspot::SpircHandler::EventType t)
{
using E = cspot::SpircHandler::EventType;
switch (t) {
case E::PLAY_PAUSE: return "PLAY_PAUSE";
case E::VOLUME: return "VOLUME";
case E::TRACK_INFO: return "TRACK_INFO";
case E::DISC: return "DISC";
case E::NEXT: return "NEXT";
case E::PREV: return "PREV";
case E::SEEK: return "SEEK";
case E::DEPLETED: return "DEPLETED";
case E::FLUSH: return "FLUSH";
case E::PLAYBACK_START: return "PLAYBACK_START";
}
return "?";
}
static void session(void)
{
cJSON *src = cfg_get("source");
std::string client_id = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_id")->valuestring;
std::string client_secret = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_secret")->valuestring;
int bitrate = (int)cJSON_GetObjectItemCaseSensitive(src, "spotify_bitrate")->valuedouble;
cJSON_Delete(src);
auto login = blob();
auto ctx = cspot::Context::createFromBlob(login);
ctx->config.clientId = client_id;
ctx->config.clientSecret = client_secret;
ctx->config.audioFormat = bitrate >= 320 ? AudioFormat_OGG_VORBIS_320
: bitrate >= 160 ? AudioFormat_OGG_VORBIS_160 : AudioFormat_OGG_VORBIS_96;
// createFromBlob() starts at volume 0, which the app would show; report what we actually play.
ctx->config.volume = s_volume;
s_state = "connecting";
ctx->session->connectWithRandomAp();
auto token = ctx->session->authenticate(login);
if (token.empty()) {
s_state = "login failed";
ESP_LOGE(TAG, "login failed (check the client ID/secret and that the account is Premium)");
return;
}
ctx->session->startTask();
auto handler = std::make_shared<cspot::SpircHandler>(ctx);
handler->subscribeToMercury();
// PCM (44.1 kHz stereo s16) to the player; returning fewer bytes makes cspot retry the rest,
// so the player's blocking write paces decoding to playback speed.
handler->getTrackPlayer()->setDataCallback([](uint8_t *data, size_t len, std::string_view id) -> size_t {
if (s_written) {
// First data of a new track: it becomes audible when playback reaches this position.
std::lock_guard<std::mutex> lock(s_bound_mutex);
if (id != s_last_id) {
s_last_id = std::string(id);
s_bounds.push_back({ s_written(), s_last_id });
}
}
size_t frames = len / 4;
size_t taken = s_pcm_cb ? s_pcm_cb(reinterpret_cast<const int16_t *>(data), frames) : frames;
s_pcm_bytes += taken * 4;
return taken * 4;
});
handler->setEventHandler([](std::unique_ptr<cspot::SpircHandler::Event> ev) {
using E = cspot::SpircHandler::EventType;
switch (ev->eventType) {
case E::TRACK_INFO: {
auto &ti = std::get<cspot::TrackInfo>(ev->data);
ESP_LOGI(TAG, "track: %s - %s (%lu ms)", ti.artist.c_str(), ti.name.c_str(), (unsigned long)ti.duration);
std::lock_guard<std::mutex> lock(s_track_mutex);
s_track = ti;
return;
}
case E::PLAY_PAUSE:
if (s_event_cb) {
s_event_cb(std::get<bool>(ev->data) ? SPOTIFY_EV_PAUSE : SPOTIFY_EV_PLAY, 0);
}
break;
case E::FLUSH:
case E::SEEK:
case E::PLAYBACK_START:
// The output buffer is dropped: pending boundaries are void. A new load (PLAYBACK_START)
// gets a new boundary with its first data; a seek stays within the same track.
clear_boundaries(ev->eventType == E::PLAYBACK_START);
s_depleted = false;
if (s_event_cb) {
s_event_cb(SPOTIFY_EV_FLUSH, 0);
if (ev->eventType == E::PLAYBACK_START) {
s_event_cb(SPOTIFY_EV_PLAY, 0);
}
}
break;
case E::VOLUME:
s_volume = std::get<int>(ev->data); // exact value from the app, no echo back
if (s_event_cb) {
s_event_cb(SPOTIFY_EV_VOLUME, std::get<int>(ev->data));
}
break;
case E::DEPLETED:
s_depleted = true; // queue done: tell Spotify once the buffer has played out
break;
default:
break;
}
ESP_LOGI(TAG, "event %s", event_name(ev->eventType));
});
s_handler = handler;
s_state = "connected";
ESP_LOGI(TAG, "connected as %s", ctx->config.username.c_str());
clear_boundaries(true);
s_depleted = false;
{
std::lock_guard<std::mutex> lock(s_cmd_mutex);
s_cmds.clear();
s_cmd_done = s_cmd_queued;
}
while (!s_stop) {
ctx->session->handlePacket(); // waits at most 200 ms
run_commands(handler);
check_playback(handler);
}
// Stops the queue and player tasks (waits for them), then closes the connection.
s_handler.reset();
{
std::lock_guard<std::mutex> lock(s_track_mutex);
s_track = {};
}
handler->disconnect();
ESP_LOGI(TAG, "session ended");
}
static void spotify_task(void *arg)
{
while (true) {
while (!s_enabled || !s_got_blob) {
if (s_enabled) {
s_state = "waiting for Spotify app";
}
vTaskDelay(pdMS_TO_TICKS(500));
}
s_got_blob = false;
s_stop = false;
s_in_session = true;
try {
session();
} catch (const std::exception &e) {
s_state = "error";
ESP_LOGE(TAG, "session ended: %s", e.what());
}
s_handler.reset();
s_in_session = false;
vTaskDelay(pdMS_TO_TICKS(2000));
}
}
extern "C" void spotify_apply(bool enable)
{
s_want = enable;
cJSON *src = cfg_get("source");
std::string name = cJSON_GetObjectItemCaseSensitive(src, "spotify_name")->valuestring;
bool creds = cJSON_GetObjectItemCaseSensitive(src, "spotify_client_id")->valuestring[0] &&
cJSON_GetObjectItemCaseSensitive(src, "spotify_client_secret")->valuestring[0];
cJSON_Delete(src);
bool want = enable && creds;
if (!want || name != s_name) {
// Disable, or re-advertise under a new name: end any session, drop the old entry.
s_enabled = false;
s_stop = true;
s_got_blob = false;
if (!s_name.empty()) {
mdns_service_remove("_spotify-connect", "_tcp");
ESP_LOGI(TAG, "Spotify Connect \"%s\" withdrawn", s_name.c_str());
s_name.clear();
}
}
if (!want) {
s_state = !creds ? "no client credentials" : "disabled (source mode)";
if (!creds && enable) {
ESP_LOGW(TAG, "not started: set the Spotify client ID and secret (web UI, Source)");
}
return;
}
if (s_name.empty()) {
{
std::lock_guard<std::mutex> lock(s_mutex);
s_blob = std::make_shared<cspot::LoginBlob>(name);
}
mdns_txt_item_t txt[] = { { "VERSION", "1.0" }, { "CPath", "/spotify_info" }, { "Stack", "SP" } };
esp_err_t err = mdns_service_add(name.c_str(), "_spotify-connect", "_tcp", 80, txt, 3);
s_name = name;
ESP_LOGI(TAG, "Spotify Connect \"%s\" advertised (%s)", name.c_str(), esp_err_to_name(err));
}
s_enabled = true;
}
extern "C" esp_err_t spotify_init(spotify_pcm_cb_t pcm, spotify_event_cb_t event, spotify_pos_cb_t written,
spotify_pos_cb_t played)
{
s_pcm_cb = pcm;
s_event_cb = event;
s_written = written;
s_played = played;
if (!bell::bellGlobalLogger) {
bell::bellGlobalLogger = new EspLogger();
}
static const httpd_uri_t get = { .uri = "/spotify_info", .method = HTTP_GET, .handler = info_get, .user_ctx = nullptr };
static const httpd_uri_t post = { .uri = "/spotify_info", .method = HTTP_POST, .handler = info_post, .user_ctx = nullptr };
web_register_uri(&get);
web_register_uri(&post);
if (xTaskCreate(spotify_task, "spotify", 32 * 1024, nullptr, 5, nullptr) != pdPASS) {
return ESP_ERR_NO_MEM;
}
return ESP_OK; // the player enables it (spotify_apply)
}
+31 -1
View File
@@ -1,4 +1,32 @@
dependencies:
espressif/esp_audio_codec:
component_hash: 16e2880dbdd5a72264051f750f33a6e5a38fd25621c83e3a32a85a152d2d2643
dependencies:
- name: idf
require: private
version: '>=4.4'
source:
registry_url: https://components.espressif.com/
type: service
version: 2.5.0
espressif/esp_audio_effects:
component_hash: 6ad72ee106e25b07c9ae5b8ec77b566ef8d697473095f1c982e13247005b9ba6
dependencies:
- name: espressif/gmf_fft
registry_url: https://components.espressif.com
require: private
version: ~1.0
source:
registry_url: https://components.espressif.com/
type: service
version: 1.3.0~1
espressif/gmf_fft:
component_hash: b59451ef2f96d22b80c27a162515b21f1b85954dda434c0b092172164028779d
dependencies: []
source:
registry_url: https://components.espressif.com
type: service
version: 1.0.0
espressif/mdns:
component_hash: b679eafd0acae2066e2645bd91d073e33ca5be515e2545cd3c4e55a3e3bce3cb
dependencies:
@@ -14,7 +42,9 @@ dependencies:
type: idf
version: 5.5.5
direct_dependencies:
- espressif/esp_audio_codec
- espressif/esp_audio_effects
- espressif/mdns
manifest_hash: e5eba11c864076c14a58153c7f761bec2b064244e66ca3f76c0dc170db907329
manifest_hash: 95404bd3492778da35a8aeee53935ee8ad13b09c56ae5fcbe77a4e921dafbb23
target: esp32p4
version: 2.0.0
+25 -15
View File
@@ -6,31 +6,34 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
## Web UI (web/index.html)
- Single file, no dependencies, minimal CSS. Embed in firmware (EMBED_TXTFILES, gzip optional).
- Theme: dark by default; a toggle (top right) switches to light, remembered per browser (localStorage).
- CORE sections: Status (incl. temperatures), PTP status (Riedel-style + Details), PTP, AES67 output, Network (+VLAN), Logging, SDP, Firmware.
- PROJECT blocks are marked `PROJECT START/END` in the HTML (live controls and config fieldsets) and in the script (`PROJECT` object: `title`, `def` defaults merged over core defaults, `toggle(f)`, `statusRows(st)`, `poll()`).
- Binding: every `<input|select name="group.key">` maps to `cfg[group][key]`. Adding a setting means adding an input and a default; no other JS needed. Number inputs and numeric selects are sent as JSON numbers.
- Status table values can be text or {cls: ok|warn|bad, text} for colour.
- Device config is merged over defaults on load, so older firmware missing keys still renders.
- Save bumps `aes67.session_ver` (SDP o= version). Save is blocked while any field is invalid (e.g. multicast out of range).
- UI uses IEEE 1588-2019 terms (TimeTransmitter / TimeReceiver), like Riedel. Config/API values stay master/slave/auto.
- UI uses IEEE 1588-2019 terms (TimeTransmitter / TimeReceiver), like Riedel. Config/API values stay slave/auto.
- AES67 fields carry Riedel Director-style "Default / Range" hints.
- PTP preset buttons: "Riedel SIC defaults" and "AES67 media profile defaults" fill the form (Save to apply).
- PTP preset buttons: "Riedel PTP defaults" and "AES67 Media PTP defaults" fill the form (Save to apply).
## Config schema (core groups)
- ptp: {mode: multicast|hybrid, role: slave|auto|master, domain, priority1, priority2, log_sync, log_announce, announce_timeout, log_delay_req, dscp, hw_ts}
- aes67: {name, enabled, discovery: manual|sap, mcast, port, ttl, dscp, channels, mono_sum, encoding: L16|L24, rate, ptime, pt, ssrc, clk_offset, session_id, session_ver}
- ptp: {mode: multicast|hybrid, role: slave|auto, domain, priority1, priority2, log_sync, log_announce, announce_timeout, log_delay_req, dscp} (hardware timestamps always; not configurable)
- aes67: {name, enabled, discovery: manual|sap, mcast, port, ttl, dscp, channels, mono_sum, encoding: L16|L24, rate: 48000 only (all sources are 48 kHz), ptime, pt, ssrc, clk_offset, session_id, session_ver}
- net: {hostname, vlan, web_on: both|inet|aes67, dhcp, ip, mask, gw, dns} (AES67 / untagged interface)
- inet: {vlan_id, pcp, dhcp, ip, mask, gw, dns} (internet / tagged, only if net.vlan)
- log: {syslog, host, port, level: error|warn|info|debug, facility, format: rfc5424|rfc3164}
## Core API
- GET/POST /api/config (full JSON; POST validates, stores to NVS, applies live where possible, returns 4xx with message on bad values)
- GET /api/status -> {model?, fw?, power?, ip, aes67_ip, inet_ip, inet_vlan, mac, link, tx_packets, underruns, uptime_s, heap_free, psram_free, temps:[…], ptp:{…}, …project fields}
- Write-only keys (`cfg_mark_secret`, e.g. passwords/client secrets): GET returns "" for them; a POST with "" keeps the stored value, null clears it. Stored in NVS in plain text (NVS encryption is not enabled).
- GET /api/status -> {model?, fw?, power?, ip, aes67_ip, mask, gw, dns, inet_ip, inet_vlan, mac, link, tx_packets, underruns, uptime_s, heap_free, psram_free, temps:[…], ptp:{…}, …project fields}
- model, fw, power are optional; rows only appear when present (power e.g. "PoE" / "USB" if the board can detect it).
- GET /stream.sdp, POST /api/reboot, POST /api/log/test
- Firmware: GET /api/ota, POST /api/ota, POST /api/ota/confirm, POST /api/ota/rollback (see Firmware update)
## Temperatures
- `status.ip/mask/gw/dns` = the addresses in use (from DHCP or static; "" when none). With DHCP on, the UI shows them in the greyed-out static fields; unticking DHCP keeps them there as the starting point for a static setup.
- `status.temps` = array of {name, c, min_c, max_c, warn_c}; min/max since boot, warn_c optional. Any number of sensors; the UI renders one row per sensor and marks HIGH (red) at or above warn_c.
- ESP32-P4: on-die sensor via the `temperature_sensor` driver (driver/temperature_sensor.h). Pick the measurement range to suit (e.g. -10..80 °C), sample every ~2 s in the health task, and report it as "SoC". It measures the die, not ambient: expect it to read well above room temperature.
- Implemented with range 20..100 °C (±2 °C; the warning level must lie inside the range), warn_c 85 °C. On the test board the die reads ~27 °C at idle in a cool room.
@@ -49,7 +52,7 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
- Roles / BMCA dataset:
- slave (TimeReceiver only): clockClass 255, never transmits time.
- auto (default): clockClass 248, priority1 250, priority2 250. Loses to any real GM (Riedel default 128); takes over only if none.
- master (preferred TimeTransmitter): clockClass 248, priority1 100 (UI suggestion, editable).
- To prefer this device as TimeTransmitter, use auto with a lower priority1 (e.g. 100). (A separate "master" role was dropped: it behaved like auto; a stored "master" is converted to auto at boot.)
- clockAccuracy 0xFE (unknown), offsetScaledLogVariance 0xFFFF, timeSource 0xA0 (internal oscillator).
- clockIdentity = EUI-64 from MAC (xx-xx-xx-FF-FE-xx-xx-xx).
- Note: Riedel Bolero reports its own clock class as 228.
@@ -60,6 +63,11 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
- RX timestamps: a hook on the driver's info input path (`esp_eth_update_input_path_info`) records port-319 event timestamps and forwards every frame to lwIP. TX: Delay_Req is a raw Eth/IPv4/UDP frame sent with `esp_eth_transmit_ctrl_vargs` for its HW timestamp. Needs `CONFIG_ETH_TRANSMIT_MUTEX`.
- Servo: step on the first Sync from a new GM (frequency seeded from the measured rate), then linuxptp-style PI (kp 0.7 / ki 0.3 at 1 Sync/s, scaled by the interval); re-step above 1 ms. Locked: 8 Syncs below 1 µs; unlocked after 3 above. GM loss keeps the frequency (holdover).
- Path delay is corrected for offset drift between t2 and t3 until the clock is syntonised; delay statistics start at lock.
- TimeTransmitter/BMCA (step 6): own dataset from the role; a foreign GM is followed only if better; LISTENING -> MASTER after the announce receipt timeout. Two-step Sync (raw frame, HW TX time in Follow_Up), Announce with the PTP timescale flag, Delay_Resp with HW RX time. Hybrid: as TimeReceiver, Delay_Req unicast to the GM (IP from Announce, MAC from its Sync) with the unicastFlag; as TimeTransmitter, a unicast Delay_Req gets a unicast Delay_Resp.
- The EMAC's PTP filter only timestamps multicast PTP; unicast Delay_Req got none. The EMAC now timestamps every received frame (`emac_ll_ts_all_enable`); the RX hook picks the port-319 PTP event messages.
- A unicast Delay_Resp carries logMessageInterval 0x7F; then ptp.log_delay_req is used.
- As GM without an earlier lock the clock starts at 0 (1970): no RTC/NTP. Media timing is unaffected; NTP seeding could follow with the internet interface (phase 2).
- Sync send times jitter by ~10 ms (FreeRTOS 100 Hz tick); accuracy is unaffected (two-step).
- Measured vs ptp4l (Intel i210 GM, non-PTP switch): lock in ~35 s cold, ~22 s after GM loss; offset within a few hundred ns; board crystal -39.8 ppm. Link asymmetry (1G GM / 100M board through a store-and-forward switch) adds a constant offset error of a few µs that no receiver can see.
### PTP status (`status.ptp`) — main panel modelled on Riedel Bolero "PTP Status"
@@ -68,15 +76,11 @@ Reference devices for UI and defaults: Riedel Bolero (PTP status), Riedel Direct
| PTP State | state | INITIALIZING/LISTENING/UNCALIBRATED/SLAVE/MASTER/PASSIVE/FAULTY/DISABLED, shown as TimeReceiver/TimeTransmitter/… |
| Lock State | locked | servo converged (e.g. \|offset\| < 1 µs for N consecutive syncs) |
| TimeTransmitter | gm_id | shown as MAC + "(FFFE)" when EUI-64 from MAC |
| Time Offset | offset_ns | Bolero brackets in ns: <100 (green), 100-500 (green), 500-1000 (amber), 1000-10000 (red), >10000 (red); exact value in brackets |
| Time Offset (2 min avg) | offset_avg_ns | mean \|offset\| over the last 2 min (reset on a clock step); Bolero brackets in ns: <100 (green), 100-500 (green), 500-1000 (amber), 1000-10000 (red), >10000 (red). The current offset_ns is in Details |
| Frequency Deviation | freq_ppb | servo frequency correction; buckets <100 ppb, 100-500 ppb, 500 ppb-1 ppm, 1-10 ppm, 10-50 ppm, >50 ppm |
| Network Delay | path_delay_ns ± path_delay_sd_ns | mean path delay ± std dev over the rolling window |
| Hops | steps_removed | |
| Time/Frequency Traceable | gm_time_traceable, gm_freq_traceable | Announce flagField bits |
| Version | version | 2 |
| Own Clock Class | own_class | 255 / 248 per role |
Details (collapsed): clock_id, gm_class, gm_accuracy, gm_p1, gm_p2, sync_avg_ms/min/max + sync_jitter_us (measured Sync interval over the last `window` = 64 messages; RX as receiver, TX as transmitter), announce_avg_ms, delay_req/delay_resp counters, hw_ts.
Details (collapsed): clock_id, current offset_ns, gm_class, gm_accuracy, gm_p1, gm_p2, hops (steps_removed), time/frequency traceable (gm_time_traceable, gm_freq_traceable: Announce flagField bits), version (2), own clock class (own_class: 255 / 248 per role), sync_avg_ms/min/max + sync_jitter_us (measured Sync interval over the last `window` = 64 messages; RX as receiver, TX as transmitter), announce_avg_ms, delay_req/delay_resp counters, hw_ts.
When this device is the GM, offset/frequency/delay show "–".
## AES67 TX
@@ -89,7 +93,7 @@ When this device is the GM, offset/frequency/delay show "–".
- SDP: v, o (aes67 IP, session_id, session_ver), s, c=mcast/ttl, t=0 0, a=clock-domain:PTPv2 <dom>, m=audio port RTP/AVP pt, a=rtpmap, a=recvonly, a=ptime, a=ts-refclk:ptp=IEEE1588-2008:<gm>:<dom>, a=mediaclk:direct.
- SAP to 239.255.255.255:9875 every 30 s, plus immediately on change; deletion packet on disable or shutdown.
- Implemented (aes67_sdp_sap): SAPv1, payload type `application/sdp`, msg id hash = 16-bit hash of the SDP, TTL = aes67.ttl. The SDP is checked once a second; on a change the old hash is deleted before the new one is announced. Nothing is announced until a PTP GM is known (else ts-refclk would be all zeros). Shutdown deletion via `esp_register_shutdown_handler` (covers reboot and OTA).
- Not done yet: bumping session_ver on a GM change (needs a firmware-side config write; relevant once the device can become GM, step 6). A GM change already re-announces immediately with the new ts-refclk.
- GM change: aes67.session_ver is bumped (stored via `cfg_set_number`, without re-applying the aes67 group so the stream keeps running) and SAP re-announces within 1 s. The first GM after boot is not counted as a change.
- Media 2 (ST 2022-7 redundancy): not possible on single-port boards like the ESP32-P4-ETH. Keep the schema open for a `mcast2`/`port2` pair on dual-NIC hardware (Riedel applies one PTP config to both Media 1 and Media 2).
## AES67 RX (future, for receiver projects) — Riedel Director 4-wire input defaults
@@ -105,13 +109,19 @@ When this device is the GM, offset/frequency/delay show "–".
- LLDP (IEEE 802.1AB), transmit only, own code (not in IDF/lwIP): every 30 s, TTL 120 s, plus immediately on a new IP or hostname. TLVs: chassis ID and port ID = MAC, port description "eth0", system name = net.hostname, system description = project + firmware version, capabilities station-only, management address = IPv4. With the VLAN split, send it on the AES67 (untagged) side; the 802.1 port VLAN ID TLV can be added then.
- Switch port: AES67 as native/untagged VLAN, internet tagged, PoE on. IGMP snooping + querier on the AES67 VLAN.
## Time / NTP (phase 2, not implemented yet)
- SNTP client for wall-clock time. Servers configurable as hostnames or IPs (e.g. `pool.ntp.org`, `0.pool.ntp.org`, a local server); several allowed, tried in order; names resolved via DNS and re-resolved when a server stops answering.
- Uses: set the EMAC PTP clock to real time (TAI = UTC + 37 s) before this device becomes GM when it has not learned time from another GM (without NTP it starts at 1970); RFC 5424/3164 syslog timestamps.
- Never step the PTP clock from NTP while locked to a GM or while GM with receivers locked; only seed it before becoming GM.
- Planned config group: time: {ntp, servers[] or a comma-separated string, sync_interval_s}; the UI needs matching fields.
## Syslog
- esp_log vprintf hook (chains to UART) -> queue -> low-priority UDP task. Non-blocking, drop and count on overflow, no recursion. RFC 5424 or 3164, PRI = facility*8 + severity (E3 W4 I6 D7 V7). Strip ANSI colour codes. HOSTNAME = net.hostname, APP-NAME = log tag.
- Buffer early boot logs in the queue until the netif has an IP. POST /api/log/test sends one info-level message.
## Firmware update (OTA)
- Partition table: nvs, otadata, phy_init, ota_0, ota_1 (no factory app). Size the slots from flash_id; e.g. on 16 MB, 2 × 6 MB leaves room for growth (cspot + TLS + codecs). Keep NVS outside the app slots so config survives updates.
- Version: `PROJECT_VER` from `git describe --tags --dirty`, read at runtime from `esp_app_get_description()`; also reported as `status.fw`.
- Version: `PROJECT_VER` = `<version.txt>-<git short hash>` (e.g. `0.0.1-1d613b1`; the first part set by hand), read at runtime from `esp_app_get_description()`; also reported as `status.fw`.
- API:
- GET /api/ota -> {version, project, build_date, idf, running, previous, previous_version, pending_verify, can_rollback}
- POST /api/ota: raw .bin as `application/octet-stream`, streamed with esp_ota_begin/write/end into the inactive slot (never buffered whole in RAM). 200 then reboot; 4xx with a message if rejected.
@@ -130,7 +140,7 @@ components/
aes67_board/ board pin profiles (waveshare_esp32p4_eth.h, …), eth init
aes67_net/ netif setup, optional VLAN split, DSCP/PCP helpers
aes67_ptp/ PTPv2 ordinary clock: BMCA, servo, master, multicast/hybrid, EMAC HW timestamps, stats
aes67_tx/ RTP sender task, PTP-paced, pull callback: size_t (*read)(int32_t *buf, size_t frames); optional mono sum
aes67_tx/ RTP sender task, PTP-paced, pull callback: size_t (*read)(int32_t *buf, size_t frames), always stereo (AES67_TX_SRC_CHANNELS); TX maps it to the stream (mono: L, or (L+R)/2 with mono_sum); built-in test signals: 1 kHz tone at -18 dBFS phase-locked to PTP (source NULL), pink noise at -18 dBFS RMS (aes67_tx_pink_noise)
aes67_sdp_sap/ SDP builder/parser + SAP announcer
aes67_syslog/ remote syslog
aes67_health/ uptime, heap/PSRAM, temperature sensors (temps[] with min/max/warn)
+6 -3
View File
@@ -17,7 +17,8 @@ Core AES67 parts (PTP, TX, SDP/SAP, network/VLAN, syslog, web UI base, config sc
- Sources: Waveshare wiki (waveshare.com/wiki/ESP32-P4-ETH), ESPHome device page (devices.esphome.io/devices/waveshare-esp32-p4-eth), espp board docs (esp-cpp.github.io/espp/dev_boards/waveshare/esp32_p4_eth.html).
## Project pipeline
source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44.1k->48k -> volume/gain -> PSRAM ring buffer -> aes67_tx pull callback
source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44.1k->48k -> PSRAM ring buffer -> volume/gain -> aes67_tx pull callback
- Volume is applied after the ring (in the pull callback) so a change is heard at once, not one ring length (4 s) later; ramped over one packet to avoid zipper noise. Curve: amplitude = (volume/100)^3 (about -18 dB at 50 %, 0 = mute). The built-in test signals (modes "tone", "pink") are not affected.
- Spotify Connect: cspot (feelfreelinux/cspot), needs Premium, zeroconf via mDNS (on the internet interface when VLAN split). Spotify occasionally changes auth for 3rd-party clients — expect breakage risk.
- HLS: HTTPS (mbedTLS), m3u8 parse (master->media playlist), segment fetch, TS demux or fMP4/ADTS, AAC decode (esp_audio_codec / esp-gmf).
- Stereo L24/48k at 1 ms is about 3 Mbit/s on the wire; 100 Mb has plenty of headroom.
@@ -30,8 +31,10 @@ source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44
- Firmware needs Spotify events: cspot connect, disconnect, play, pause.
## Project config group
- source: {mode: spotify|hls|auto|off, spotify_name, spotify_bitrate, hls_url, autoplay, gain_db, failover_delay_s, failover_on_pause}
- source: {mode: spotify|hls|auto|tone|pink|off, spotify_name, spotify_bitrate, hls_url, autoplay, gain_db, failover_delay_s, failover_on_pause, spotify_client_id, spotify_client_secret}
- spotify_client_id / spotify_client_secret: each user's own Spotify developer app (developer.spotify.com, Premium account), needed by the maintained cspot fork (philippe44/cspot) since Spotify's 2025 API restrictions. The secret is write-only (never returned by GET /api/config). spotify_state reports "no client credentials" while either is missing.
- Project status fields: active_source, source_state, spotify_state, buffer_ms
- mode "tone": the core's 1 kHz / -18 dBFS test tone, phase-locked to PTP (commissioning, e.g. Riedel import tests). "pink": the core's pink noise, -18 dBFS RMS (peaks about -6 dBFS), same on L and R (level/EQ checks). Neither is affected by volume or gain. "off": silence.
## Player control API (project routes)
- GET /api/player -> {source, forced, state(playing|paused|stopped|buffering|idle), artist, title, album, position_ms, duration_ms, volume(0-100), can:{pause,next,prev,seek}}
@@ -39,6 +42,6 @@ source (cspot Spotify Connect | HLS player) -> decode (Vorbis/AAC/MP3) -> SRC 44
- POST /api/player/seek {ms}; POST /api/player/volume {value} or {delta}
- POST /api/player/source {source: spotify|hls|off|config}: runtime override, not saved; "config" returns to the configured mode
- POST /api/player/url {url}: play an m3u8 now (runtime, not saved)
- On Spotify, commands go to cspot (the Spotify app stays in sync, including volume). On HLS (live): pause = stop fetching, resume = rejoin at live edge; next/prev/seek return 409 and `can` reflects that.
- On Spotify, commands go to cspot (the Spotify app stays in sync, including volume). stop = pause (the session stays). prev restarts the track after its first 3 s (cspot, like the apps). After next/prev the response can still show the old track; the new one follows within ~1 s. On HLS (live): pause/stop = stop fetching, resume = rejoin at live edge (a pause lasts until the next source switch); next/prev/seek return 409 and `can` reflects that. Tone/off, or Spotify without a session: transport returns 409.
- Volume = runtime player volume; source.gain_db is a fixed trim on top.
- No auth yet: LAN only.
+230
View File
@@ -0,0 +1,230 @@
# P4 AES67 Streamer: user guide
The P4 AES67 Streamer turns Spotify Connect or an internet radio stream (HLS / m3u8) into an **AES67 multicast stream**, locked to your PTP clock. Any AES67 receiver on the network can play it: a Riedel Artist 4-wire port, a Dante device in AES67 mode, a DAW, and so on.
It runs on a **Waveshare ESP32-P4-ETH** board, powered over PoE, and is set up entirely from a web page.
Contents: [Getting started](#getting-started) · [The web page](#the-web-page) · [Sources](#sources) · [Spotify](#spotify) · [AES67 output](#aes67-output) · [PTP](#ptp) · [Network](#network) · [Logging](#logging) · [Firmware updates](#firmware-updates) · [Player API](#player-api) · [Troubleshooting](#troubleshooting) · [Limitations](#limitations)
---
## Getting started
1. **Connect** the board's Ethernet port to a PoE switch port, or to a normal port and power it over USB-C. Use the same network (or VLAN) as your AES67 devices and your PTP grandmaster.
2. **Wait about 20 seconds.** The board gets an address by DHCP and locks to PTP.
3. **Open the web page** at **http://p4-aes67.local/**. Alternatively, look up the board's IP in your router's DHCP list (the name is `p4-aes67`) and open `http://<IP>/`.
4. **Pick a source** under *Source* and click **Save** (see [Sources](#sources)).
5. **On the receiver**, either find the stream via SAP, or copy the SDP from the page's *SDP* section (see [AES67 output](#aes67-output)).
Out of the box the board streams **2-channel, 24-bit, 48 kHz audio with 1 ms packets to 239.69.1.10:5004** and announces it by SAP under the name "P4 AES67".
> **More than one board?** Each board needs its own hostname, stream name and multicast address, or they clash. Change them under *Network* and *AES67 output*, or let `tools/flash_board.py` ask for them when you flash a new board.
---
## The web page
The page is split into sections, from top to bottom:
| Section | What it's for |
|---|---|
| **Status** | Firmware version, IP / MAC, link speed, active source, Spotify state, buffer, packets sent, underruns, uptime, memory, chip temperature. |
| **PTP status** | Whether the clock is locked, which grandmaster it follows, the time offset (bracket of the 2-minute average) and path delay. *Details* shows the current offset, hops and more. |
| **Player** | What's playing now, transport buttons, progress bar (drag to seek), volume. |
| **Source**, **PTP**, **AES67 output**, **Network**, **Logging** | Settings. They take effect only when you click **Save**. |
| **SDP** | The stream description, to copy or download for receivers. |
| **Firmware** | Update the firmware (see [Firmware updates](#firmware-updates)). |
**Saving:** *Save*, *Revert* (throw away unsaved edits) and *Reboot* stay at the bottom of the window while you scroll through the settings. Messages such as "Saved." or error texts appear next to them. Invalid values are rejected with the reason, and nothing is saved.
**Light / dark:** the page is dark by default. The **◐** button at the top right switches to light, and your browser remembers the choice.
---
## Sources
Choose the source under **Source → Source**:
| Source | What it plays |
|---|---|
| **Spotify Connect** | The board appears as a speaker in the Spotify app (default). Needs your own Spotify app credentials; see [Spotify](#spotify). |
| **HLS / M3U8 URL** | An internet radio stream, e.g. `https://…/playlist.m3u8`. Enter it under *Stream URL*. |
| **Spotify, fail over to HLS** | Spotify when someone plays to it, otherwise the stream (see below). |
| **Test tone** | 1 kHz sine at −18 dBFS, locked to PTP. For line-up and receiver tests. |
| **Pink noise** | Pink noise at −18 dBFS RMS (peaks around −6 dBFS), the same signal on both channels. For level and EQ checks. |
| **Off** | Silence. The stream keeps running. |
### Failover (Spotify, fail over to HLS)
- **Spotify playing:** the board plays Spotify, switching over within about a second of pressing play.
- **No Spotify connection:** after *Failover delay* seconds (default 5), the board switches to the HLS stream.
- **Paused:** with **Also fail over when paused** ticked, a paused Spotify counts as "not playing" and the stream takes over after the delay. Unticked (default), a pause gives silence and the board stays on Spotify.
- **Fades:** switches fade out and in over 30 ms, so there are no clicks.
- **Resuming:** Spotify is held while the stream plays. When you press play again, the song continues where you paused.
### Volume and gain
- **Volume (Player section):** the everyday volume. With Spotify it follows the app's volume slider, and the other way round.
- **Output gain (dB):** a fixed trim on top of the volume, −60 to +12 dB. Above 0 dB, loud passages can clip at full scale.
- **Neither affects** the test tone or pink noise. Those always come out at their calibrated level.
---
## Spotify
Since 2025, Spotify requires every Spotify Connect device to use a **developer app registered to your own account**. You need **Spotify Premium**. Setup takes about five minutes:
1. Go to **https://developer.spotify.com/dashboard** and log in.
2. **Create app**:
- Name and description: anything, e.g. "P4 AES67".
- Redirect URI: `http://127.0.0.1:8888/callback`. Spotify requires one, but this device never uses it.
- API: tick **Web API**, then save.
3. Open the app's **Settings**. Copy the **Client ID**, and click *View client secret* to copy the **Client secret**.
4. On the board's page under **Source**, paste them into **Spotify client ID** and **Spotify client secret**, then **Save**.
The secret is write-only: after saving, the field shows empty. Leave it empty to keep the stored secret, or type a new one to replace it.
**Connecting:** make sure your phone or computer is on the **same network** as the board. In the Spotify app, open the device list and pick **P4 AES67** (or the name you set under *Spotify device name*). Play, pause, skip, seek and volume all work from the app. The web page shows the track and position and can control playback too.
- **Spotify bitrate:** 96, 160 or 320 kbit/s (default 320).
- **Spotify device name:** the name shown in the app. Changing it disconnects a running session.
- **Status → Spotify** shows the state: e.g. *waiting for Spotify app*, *connected*, *no client credentials*, *login failed*.
---
## AES67 output
| Setting | Default | Notes |
|---|---|---|
| Stream name (s=) | P4 AES67 | The name receivers show. |
| Enabled | on | Off stops sending. |
| Discovery | SAP | **SAP**: announced every 30 s on 239.255.255.255:9875, so receivers that support SAP find it by themselves. **Manual**: no announcements; use the SDP. |
| RTP multicast IP / port | 239.69.1.10 : 5004 | Must be unique per stream on your network. |
| TTL | 32 | |
| DSCP (media) | 34 (AF41) | QoS marking for the audio packets. |
| Channels | 2 | 1 or 2. |
| Mono sum | off | Sends (left + right) / 2 as a 1-channel stream. Forces *Channels* to 1; it can't clip. |
| Bit depth | L24 | L24 or L16. |
| Sample rate | 48000 | Fixed; all sources are 48 kHz. |
| Packet time | 1 ms | 0.125, 0.25, 0.333, 1 or 4 ms. 1 ms is the AES67 default and works with nearly all receivers. |
| Payload type / SSRC / time stamp offset | 96 / 0 / 0 | Only change these if a receiver needs it. |
**Getting the SDP to a receiver:**
- **SAP:** receivers that listen for SAP (Riedel, many AES67 devices) list the stream by its name.
- **By hand:** in the *SDP* section, **Copy** or **Download .sdp** and import it on the receiver. The board also serves it at `http://p4-aes67.local/stream.sdp`.
- **When the SDP changes:** after a setting that changes the stream, the SDP gets a new version number. Re-import it on receivers that were set up by hand.
---
## PTP
The board locks its media clock to the PTP grandmaster on the network (IEEE 1588-2008, UDP/IPv4, E2E, always with hardware timestamps). *PTP status* shows the lock state and the grandmaster.
| Setting | Default | Notes |
|---|---|---|
| Mode | multicast | **hybrid** sends the delay requests unicast (fewer multicast packets). |
| Role | Auto | **TimeReceiver only**: never becomes grandmaster. **Auto**: becomes grandmaster only if there is none (fallback). To make this board the preferred grandmaster, keep *Auto* and set a low *Priority 1* (e.g. 100). |
| Domain | 0 | Must match your grandmaster. |
| Priority 1 / 2 | 250 / 250 | Lower wins the grandmaster election. |
| Intervals, timeout, DSCP (46) | | Presets below set them. |
**Presets:**
- **Riedel PTP defaults:** TimeReceiver only, priorities 128/126, Riedel's intervals. Use this when a Riedel system provides the clock.
- **AES67 Media PTP defaults:** the faster intervals of the AES67 profile.
A preset only fills in the fields; click **Save** to apply them.
Audio starts only when PTP is locked, usually about 20 s after power-up. When the board is itself the grandmaster (no other clock on the network), its clock starts at 1 January 1970. That's fine for AES67, but it isn't real time.
---
## Network
- **Hostname:** the name in DHCP, mDNS (`<hostname>.local`) and LLDP (the switch's neighbour list). Changing it applies at once.
- **DHCP (default):** with DHCP on, the greyed-out IP, netmask, gateway and DNS fields show the addresses DHCP handed out.
- **Static IP:** untick **DHCP**. The current addresses stay in the fields as a starting point; edit them and **Save**. The board **reboots** to apply them, and the page switches to the new address after 20 s. The page checks that the netmask is valid, that the IP isn't the subnet's network or broadcast address, and that the gateway is in the subnet.
- **A wrong static address makes the board unreachable** over the network. Double-check before saving; see [Troubleshooting](#troubleshooting) for recovery.
- With a static IP, your router's DNS name for the board can go stale. `http://<hostname>.local/` keeps working.
---
## Logging
The board can send its log to a syslog server (UDP):
- Tick **Send to syslog** and enter the server (hostname or IP) and port (default 514).
- **Minimum level:** Error, Warning, Info or Debug.
- **Facility and format:** RFC 5424 or RFC 3164 (BSD).
- **Send test message** checks the path.
The log shows PTP lock/unlock, source switches, stream errors and firmware updates, which makes it useful for troubleshooting.
---
## Firmware updates
**Over the network (normal way):** in the **Firmware** section, choose the new `aes67_p4.bin` and click **Upload & install**. The board installs it to its second firmware slot and reboots into it.
- The new firmware must **prove itself** within 60 s: network up and web page answering. Only then is it kept. If it fails or crashes, the board automatically goes back to the previous firmware.
- While the new firmware is on trial, the page offers **Keep this firmware** and **Roll back to previous**.
- During the upload the Spotify session ends and the stream pauses. Reconnect from the app afterwards.
- From a computer: `curl -f --data-binary @aes67_p4.bin -H 'Content-Type: application/octet-stream' http://p4-aes67.local/api/ota`
**Over USB (new board, or recovery):** `tools/flash_board.py` (needs ESP-IDF or `pip install esptool`, plus a build). It:
- checks the board (chip revision, 32 MB flash),
- optionally erases it (this clears all settings),
- flashes the firmware and finds the board's IP,
- asks for a hostname, stream name and multicast address.
**Making an update file:**
1. Set the version in **`version.txt`** (first line, e.g. `0.0.2`) and commit your changes.
2. Build: `idf.py build`. The firmware version becomes `<version>-<commit>`, e.g. `0.0.2-1d613b1`, as shown under *Firmware* and *Status*.
3. The update file is **`build/aes67_p4.bin`**. Upload it in the *Firmware* section, or with the `curl` command above.
The .bin is for ESP32-P4 chips of **revision v1.x** (the current Waveshare boards). A board with a v3 chip needs a build for that revision; the flash script refuses it with a hint.
---
## Player API
Everything the Player section does is also available over HTTP, e.g. for a control panel or Companion. Every command returns the current player state as JSON.
```
GET /api/player state, source, track, position, volume
POST /api/player/play | pause | toggle | stop | next | prev
POST /api/player/seek {"ms": 90000}
POST /api/player/volume {"value": 0-100} or {"delta": -5}
POST /api/player/source {"source": "spotify" | "hls" | "off" | "config"}
POST /api/player/url {"url": "https://…/playlist.m3u8"}
```
Example: `curl -X POST http://p4-aes67.local/api/player/next`
- **With Spotify:** the app follows every command. *stop* equals *pause*. *prev* restarts the song if it has played more than 3 s, like the Spotify apps.
- **With HLS (live radio):** *pause* stops downloading, and *play* rejoins the live stream. *next*, *prev* and *seek* return an error (409).
- **`source` and `url`:** temporary overrides; they're not saved, and a reboot or `"source": "config"` returns to the saved setting. `url` plays a stream right away.
- **Security:** there is no password. Keep the device on a trusted network.
The full device API (status, config, SDP, firmware) is described in `docs/aes67-core-base.md`.
---
## Troubleshooting
| Problem | What to try |
|---|---|
| **Can't find the page** | Try `http://p4-aes67.local/`, or the IP from your router's DHCP list. If the board has a static IP you no longer know, use `tools/flash_board.py` over USB with erase (resets all settings). |
| **Board doesn't appear in the Spotify app** | Phone or computer on the same network? *Status → Spotify* should say *waiting for Spotify app*. *no client credentials*: enter ID and secret. *login failed*: check them, and check that the account is Premium. |
| **"Can't connect" in Spotify on the first try** | Try again; a second attempt usually works. |
| **Spotify controls do nothing** after a long idle session | Quit and reopen the Spotify app, then connect again. |
| **No audio at the receiver** | *PTP status* locked? *Status → AES67 TX* counting packets? The receiver on the same grandmaster and domain? After changing stream settings, re-import the SDP. |
| **Stutter or dropouts** | *Status → underruns* rising? With HLS, check the internet connection. During a firmware upload short stutters are normal. |
| **HLS stream doesn't start** | Check the URL in a browser. *Status → Source* shows *buffering* while it loads, usually for a few seconds. |
---
## Limitations
These are known limitations in the current firmware:
- **Autoplay stream on boot:** the checkbox has no effect yet. HLS always starts on boot.
- **VLAN split** (separate VLANs for AES67 and internet) isn't available yet.
- **No password** on the web page or API.
- **HLS clock drift:** the radio station's clock and PTP drift slightly apart. Over many hours of continuous playback, the stream can skip ahead to catch up with the live edge.
Vendored Submodule
+1
Submodule external/cspot added at 3010349b46
+3 -3
View File
@@ -1,5 +1,5 @@
idf_component_register(SRCS "main.c" "project_cfg.c"
idf_component_register(SRCS "main.c" "project_cfg.c" "player.c" "audio_ring.c" "hls.c" "decoder.c" "audio_out.c"
INCLUDE_DIRS "."
REQUIRES esp_app_format esp_hw_support
REQUIRES esp_app_format esp_hw_support heap esp_http_client mbedtls esp_timer
aes67_board aes67_health aes67_net aes67_ota aes67_ptp aes67_sdp_sap
aes67_syslog aes67_tx aes67_web)
aes67_syslog aes67_tx aes67_web spotify)
+90
View File
@@ -0,0 +1,90 @@
#include "audio_out.h"
#include <stdlib.h>
#include "esp_ae_rate_cvt.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#define OUT_RATE 48000
#define CONV_FRAMES 4096 // per rate converter call
static const char *TAG = "audio_out";
struct audio_conv {
player_src_t src;
const char *name;
esp_ae_rate_cvt_handle_t cvt; // NULL: no conversion (source is 48 kHz)
uint32_t rate; // input rate the converter was opened for
int32_t *in32, *out32; // stereo int32 work buffers (PSRAM)
};
audio_conv_t *audio_conv_create(player_src_t src, const char *name)
{
audio_conv_t *c = calloc(1, sizeof(*c));
if (!c) {
return NULL;
}
c->src = src;
c->name = name;
c->in32 = heap_caps_malloc(CONV_FRAMES * 2 * sizeof(int32_t), MALLOC_CAP_SPIRAM);
c->out32 = heap_caps_malloc(CONV_FRAMES * 2 * 2 * sizeof(int32_t), MALLOC_CAP_SPIRAM);
if (!c->in32 || !c->out32) {
free(c->in32);
free(c->out32);
free(c);
return NULL;
}
return c;
}
static void set_rate(audio_conv_t *c, uint32_t rate)
{
if (c->cvt) {
esp_ae_rate_cvt_close(c->cvt);
c->cvt = NULL;
}
c->rate = rate;
if (rate == OUT_RATE) {
return;
}
esp_ae_rate_cvt_cfg_t cfg = {
.src_rate = rate, .dest_rate = OUT_RATE, .channel = 2, .bits_per_sample = 32,
.complexity = 3, .perf_type = ESP_AE_RATE_CVT_PERF_TYPE_SPEED,
};
if (esp_ae_rate_cvt_open(&cfg, &c->cvt) != ESP_AE_ERR_OK) {
ESP_LOGE(TAG, "%s: rate converter %lu -> %d Hz: open failed", c->name, (unsigned long)rate, OUT_RATE);
} else {
ESP_LOGI(TAG, "%s: rate converter %lu -> %d Hz", c->name, (unsigned long)rate, OUT_RATE);
}
}
size_t audio_conv_write(audio_conv_t *c, const int16_t *pcm, uint32_t frames, int ch, uint32_t rate)
{
if (rate != c->rate) {
set_rate(c, rate);
}
size_t produced = 0;
while (frames) {
uint32_t n = frames < CONV_FRAMES ? frames : CONV_FRAMES;
for (uint32_t i = 0; i < n; i++) { // to stereo int32 (full scale = INT32_MAX)
int32_t l = (int32_t)pcm[i * ch] << 16;
c->in32[i * 2] = l;
c->in32[i * 2 + 1] = ch > 1 ? (int32_t)pcm[i * ch + 1] << 16 : l;
}
const int32_t *out = c->in32;
uint32_t out_n = n;
if (c->cvt) {
out_n = CONV_FRAMES * 2;
if (esp_ae_rate_cvt_process(c->cvt, c->in32, n, c->out32, &out_n) != ESP_AE_ERR_OK) {
ESP_LOGW(TAG, "%s: rate conversion failed", c->name);
return produced;
}
out = c->out32;
}
produced += player_write(c->src, out, out_n);
pcm += n * ch;
frames -= n;
}
return produced;
}
+15
View File
@@ -0,0 +1,15 @@
// PCM from a source (s16, any rate/channels) -> 48 kHz stereo int32 -> player ring.
// One converter per source: each keeps its own resampler state.
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "player.h"
typedef struct audio_conv audio_conv_t;
audio_conv_t *audio_conv_create(player_src_t src, const char *name);
// Blocks while the ring is full; dropped when src is not the active source.
// Returns the 48 kHz frames produced.
size_t audio_conv_write(audio_conv_t *c, const int16_t *pcm, uint32_t frames, int channels, uint32_t rate);
+86
View File
@@ -0,0 +1,86 @@
#include "audio_ring.h"
#include <string.h>
#include "esp_heap_caps.h"
static int32_t *s_buf;
static size_t s_cap; // frames
static int s_ch;
// Monotonic frame counters; level = wr - rd. Written by one side each (acquire/release).
static uint32_t s_wr, s_rd;
esp_err_t audio_ring_init(size_t capacity_frames, int channels)
{
s_buf = heap_caps_malloc(capacity_frames * channels * sizeof(int32_t), MALLOC_CAP_SPIRAM);
if (!s_buf) {
return ESP_ERR_NO_MEM;
}
s_cap = capacity_frames;
s_ch = channels;
return ESP_OK;
}
size_t audio_ring_level(void)
{
return __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE) - __atomic_load_n(&s_rd, __ATOMIC_ACQUIRE);
}
size_t audio_ring_space(void)
{
return s_cap - audio_ring_level();
}
// Copy n frames between the ring (starting at frame index pos) and a linear buffer.
static void copy(int32_t *ring_to_lin, const int32_t *lin_to_ring, uint32_t pos, size_t n)
{
size_t start = pos % s_cap;
size_t first = n < s_cap - start ? n : s_cap - start;
size_t fb = first * s_ch * sizeof(int32_t), rb = (n - first) * s_ch * sizeof(int32_t);
if (ring_to_lin) {
memcpy(ring_to_lin, s_buf + start * s_ch, fb);
memcpy(ring_to_lin + first * s_ch, s_buf, rb);
} else {
memcpy(s_buf + start * s_ch, lin_to_ring, fb);
memcpy(s_buf, lin_to_ring + first * s_ch, rb);
}
}
size_t audio_ring_write(const int32_t *frames, size_t n)
{
uint32_t wr = __atomic_load_n(&s_wr, __ATOMIC_RELAXED);
size_t space = s_cap - (wr - __atomic_load_n(&s_rd, __ATOMIC_ACQUIRE));
n = n < space ? n : space;
if (n) {
copy(NULL, frames, wr, n);
__atomic_store_n(&s_wr, wr + n, __ATOMIC_RELEASE);
}
return n;
}
size_t audio_ring_read(int32_t *frames, size_t n)
{
uint32_t rd = __atomic_load_n(&s_rd, __ATOMIC_RELAXED);
size_t level = __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE) - rd;
n = n < level ? n : level;
if (n) {
copy(frames, NULL, rd, n);
__atomic_store_n(&s_rd, rd + n, __ATOMIC_RELEASE);
}
return n;
}
uint32_t audio_ring_written(void)
{
return __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE);
}
uint32_t audio_ring_read_pos(void)
{
return __atomic_load_n(&s_rd, __ATOMIC_ACQUIRE);
}
void audio_ring_flush(void)
{
__atomic_store_n(&s_rd, __atomic_load_n(&s_wr, __ATOMIC_ACQUIRE), __ATOMIC_RELEASE);
}
+18
View File
@@ -0,0 +1,18 @@
// Single-producer / single-consumer ring of interleaved int32 frames in PSRAM.
// The producer is a source task, the consumer the AES67 TX pull callback (must never block).
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
esp_err_t audio_ring_init(size_t capacity_frames, int channels);
size_t audio_ring_level(void); // frames available to read
size_t audio_ring_space(void); // frames that can be written
size_t audio_ring_write(const int32_t *frames, size_t n); // producer; returns frames written
size_t audio_ring_read(int32_t *frames, size_t n); // consumer; returns frames read
void audio_ring_flush(void); // consumer side: drop everything buffered
// Monotonic frame counters (wrap at 2^32): frames written so far / read (played) so far.
uint32_t audio_ring_written(void);
uint32_t audio_ring_read_pos(void);
+185
View File
@@ -0,0 +1,185 @@
#include "decoder.h"
#include <stdlib.h>
#include <string.h>
#include "esp_audio_dec_default.h"
#include "esp_audio_simple_dec.h"
#include "esp_audio_simple_dec_default.h"
#include "audio_out.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
static const char *TAG = "decoder";
#define OUT_RATE 48000
static audio_conv_t *s_conv; // HLS: s16 -> 48 kHz -> ring
static uint64_t s_seg_out; // 48 kHz frames written this segment
static esp_audio_simple_dec_handle_t s_dec;
static uint8_t *s_pcm;
static uint32_t s_pcm_size = 8192;
static esp_audio_simple_dec_info_t s_info;
static uint64_t s_seg_frames, s_seg_count, s_seg_es;
// MPEG-TS demux state: packets reassembled across HTTP chunks, PAT -> PMT -> ADTS-AAC PID.
static uint8_t s_pkt[188];
static size_t s_pkt_len;
static int s_pmt_pid = -1, s_audio_pid = -1;
static void report_segment(void)
{
if (s_seg_count && s_info.sample_rate) {
ESP_LOGI(TAG, "segment: %llu ES bytes -> %llu frames at %lu Hz = %.3f s -> %llu frames at 48 kHz = %.3f s",
s_seg_es, s_seg_frames, (unsigned long)s_info.sample_rate,
(double)s_seg_frames / s_info.sample_rate, s_seg_out, (double)s_seg_out / OUT_RATE);
}
s_seg_frames = 0;
s_seg_es = 0;
s_seg_out = 0;
s_seg_count++;
}
// Feed ADTS-AAC elementary stream bytes to the decoder.
static void decode_es(const uint8_t *data, size_t len)
{
s_seg_es += len;
esp_audio_simple_dec_raw_t raw = { .buffer = (uint8_t *)data, .len = len };
while (raw.len) {
esp_audio_simple_dec_out_t out = { .buffer = s_pcm, .len = s_pcm_size };
esp_audio_err_t err = esp_audio_simple_dec_process(s_dec, &raw, &out);
if (err == ESP_AUDIO_ERR_BUFF_NOT_ENOUGH) {
uint8_t *p = heap_caps_realloc(s_pcm, out.needed_size, MALLOC_CAP_SPIRAM);
if (!p) {
return;
}
s_pcm = p;
s_pcm_size = out.needed_size;
continue;
}
if (err != ESP_AUDIO_ERR_OK) {
ESP_LOGW(TAG, "decode error %d, resetting decoder", err);
esp_audio_simple_dec_reset(s_dec);
return;
}
if (out.decoded_size) {
if (!s_info.sample_rate) {
esp_audio_simple_dec_get_info(s_dec, &s_info);
ESP_LOGI(TAG, "stream: %lu Hz, %u ch, %u bit, %lu bit/s", (unsigned long)s_info.sample_rate,
s_info.channel, s_info.bits_per_sample, (unsigned long)s_info.bitrate);
}
uint32_t n = out.decoded_size / (s_info.channel * s_info.bits_per_sample / 8);
s_seg_frames += n;
if (s_info.bits_per_sample == 16) {
s_seg_out += audio_conv_write(s_conv, (const int16_t *)out.buffer, n, s_info.channel,
s_info.sample_rate);
}
}
raw.buffer += raw.consumed;
raw.len -= raw.consumed;
}
}
static void ts_packet(const uint8_t *p)
{
if (p[0] != 0x47) {
return;
}
bool pusi = p[1] & 0x40;
int pid = ((p[1] & 0x1f) << 8) | p[2];
int afc = (p[3] >> 4) & 3;
if (!(afc & 1)) {
return; // no payload
}
size_t off = 4 + ((afc & 2) ? 1 + p[4] : 0);
if (off >= 188) {
return;
}
const uint8_t *pl = p + off;
size_t len = 188 - off;
if (pid == 0 && pusi) { // PAT: first program's PMT PID
const uint8_t *sec = pl + 1 + pl[0];
s_pmt_pid = ((sec[10] & 0x1f) << 8) | sec[11];
} else if (pid == s_pmt_pid && pusi && s_audio_pid < 0) { // PMT: first ADTS-AAC stream
const uint8_t *sec = pl + 1 + pl[0];
int slen = ((sec[1] & 0x0f) << 8) | sec[2];
int i = 12 + (((sec[10] & 0x0f) << 8) | sec[11]);
while (i + 5 <= 3 + slen - 4 && sec + i + 5 <= p + 188) {
int type = sec[i], epid = ((sec[i + 1] & 0x1f) << 8) | sec[i + 2];
if (type == 0x0F) {
s_audio_pid = epid;
ESP_LOGI(TAG, "TS: PMT PID 0x%x, ADTS-AAC on PID 0x%x", s_pmt_pid, epid);
break;
}
i += 5 + (((sec[i + 3] & 0x0f) << 8) | sec[i + 4]);
}
} else if (pid == s_audio_pid) {
if (pusi) { // strip the PES header
if (len < 9 || pl[0] || pl[1] || pl[2] != 1 || 9u + pl[8] > len) {
return;
}
size_t h = 9 + pl[8];
pl += h;
len -= h;
}
decode_es(pl, len);
}
}
// hls_sink_t: MPEG-TS bytes in any chunking.
bool decoder_feed(const uint8_t *data, size_t len, bool segment_start)
{
if (segment_start) {
report_segment();
s_pkt_len = 0; // segments start on a packet boundary
}
while (len) {
if (!s_pkt_len) {
// resync on 0x47 if needed, then take whole packets straight from the input
while (len && data[0] != 0x47) {
data++;
len--;
}
while (len >= 188 && data[0] == 0x47) {
ts_packet(data);
data += 188;
len -= 188;
}
if (len && data[0] != 0x47) {
continue;
}
}
size_t n = 188 - s_pkt_len < len ? 188 - s_pkt_len : len;
memcpy(s_pkt + s_pkt_len, data, n);
s_pkt_len += n;
data += n;
len -= n;
if (s_pkt_len == 188) {
ts_packet(s_pkt);
s_pkt_len = 0;
}
}
return true;
}
esp_err_t decoder_init(void)
{
esp_audio_dec_register_default();
esp_audio_simple_dec_register_default();
// Own TS demux (the library's TS decoder lost ~8% of the frames); AAC with ADTS headers,
// AAC-Plus on so HE-AAC v1/v2 variants work too.
esp_aac_dec_cfg_t aac_cfg = ESP_AAC_DEC_CONFIG_DEFAULT();
aac_cfg.aac_plus_enable = true;
esp_audio_simple_dec_cfg_t cfg = {
.dec_type = ESP_AUDIO_SIMPLE_DEC_TYPE_AAC, .dec_cfg = &aac_cfg, .cfg_size = sizeof(aac_cfg),
};
if (esp_audio_simple_dec_open(&cfg, &s_dec) != ESP_AUDIO_ERR_OK) {
ESP_LOGE(TAG, "AAC decoder open failed");
return ESP_FAIL;
}
s_pcm = heap_caps_malloc(s_pcm_size, MALLOC_CAP_SPIRAM);
s_conv = audio_conv_create(PLAYER_SRC_HLS, "hls");
return s_pcm && s_conv ? ESP_OK : ESP_ERR_NO_MEM;
}
+12
View File
@@ -0,0 +1,12 @@
// Decoder for HLS segments (MPEG-TS with AAC-LC / HE-AAC), fed by the HLS client's sink.
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
esp_err_t decoder_init(void);
// hls_sink_t: segment bytes in; PCM out (7.3: counted and logged).
bool decoder_feed(const uint8_t *data, size_t len, bool segment_start);
+322
View File
@@ -0,0 +1,322 @@
#include "hls.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_crt_bundle.h"
#include "esp_heap_caps.h"
#include "esp_http_client.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define URL_MAX HLS_URL_MAX
#define PLAYLIST_MAX (64 * 1024)
#define MAX_SEGMENTS 64
#define LIVE_BACK 3 // start this many segments behind the live edge
#define CHUNK 4096
#define MAX_REDIRECTS 5
#define SEG_MAX (4 * 1024 * 1024) // largest segment we accept (PSRAM)
static const char *TAG = "hls";
typedef struct {
int target_s;
long long media_seq;
int count;
char uri[MAX_SEGMENTS][URL_MAX];
} media_pl_t;
static hls_sink_t s_sink;
static char *s_text; // playlist buffer (PSRAM)
static media_pl_t *s_pl; // parsed media playlist (PSRAM)
static char s_url[URL_MAX]; // URL being played
static char s_want_url[URL_MAX]; // from hls_set_url(), guarded by s_url_lock
static portMUX_TYPE s_url_lock = portMUX_INITIALIZER_UNLOCKED;
static char s_media_url[URL_MAX];
static uint8_t *s_seg; // current segment (PSRAM)
static volatile unsigned s_suspended; // HLS_SUSPEND_* bits
void hls_suspend(unsigned reason, bool suspend)
{
if (suspend) {
__atomic_or_fetch(&s_suspended, reason, __ATOMIC_SEQ_CST);
} else {
__atomic_and_fetch(&s_suspended, ~reason, __ATOMIC_SEQ_CST);
}
}
void hls_set_url(const char *url)
{
taskENTER_CRITICAL(&s_url_lock);
strlcpy(s_want_url, url, sizeof(s_want_url));
taskEXIT_CRITICAL(&s_url_lock);
}
static void wanted_url(char *out, size_t n)
{
taskENTER_CRITICAL(&s_url_lock);
strlcpy(out, s_want_url, n);
taskEXIT_CRITICAL(&s_url_lock);
}
static bool still_wanted(void)
{
if (s_suspended) {
return false;
}
char u[URL_MAX];
wanted_url(u, sizeof(u));
return strcmp(u, s_url) == 0;
}
/* ----- HTTP ----- */
// Open a GET and follow redirects. Returns the client with headers read, or NULL.
static esp_http_client_handle_t http_open(const char *url)
{
esp_http_client_config_t cfg = {
.url = url, .crt_bundle_attach = esp_crt_bundle_attach, .timeout_ms = 10000,
.buffer_size = CHUNK, .buffer_size_tx = 1024, .user_agent = "p4-aes67",
.disable_auto_redirect = true, .keep_alive_enable = true,
};
esp_http_client_handle_t c = esp_http_client_init(&cfg);
if (!c) {
return NULL;
}
for (int i = 0; i <= MAX_REDIRECTS; i++) {
esp_err_t err = esp_http_client_open(c, 0);
if (err != ESP_OK) {
ESP_LOGW(TAG, "open %s: %s", url, esp_err_to_name(err));
break;
}
esp_http_client_fetch_headers(c);
int st = esp_http_client_get_status_code(c);
if (st == 301 || st == 302 || st == 303 || st == 307 || st == 308) {
esp_http_client_flush_response(c, NULL);
esp_http_client_set_redirection(c);
esp_http_client_close(c);
continue;
}
if (st == 200) {
return c;
}
ESP_LOGW(TAG, "GET %s: HTTP %d", url, st);
break;
}
esp_http_client_cleanup(c);
return NULL;
}
// GET into s_text (NUL-terminated). Returns length or -1.
static int http_get_text(const char *url)
{
esp_http_client_handle_t c = http_open(url);
if (!c) {
return -1;
}
int n = 0, r;
while (n < PLAYLIST_MAX - 1 && (r = esp_http_client_read(c, s_text + n, PLAYLIST_MAX - 1 - n)) > 0) {
n += r;
}
s_text[n] = 0;
esp_http_client_close(c);
esp_http_client_cleanup(c);
return n;
}
/* ----- playlists ----- */
// Absolute, host-relative ("/x") or path-relative ("x") reference against base.
static void resolve(char *out, size_t n, const char *base, const char *ref)
{
if (strstr(ref, "://")) {
strlcpy(out, ref, n);
return;
}
char b[URL_MAX];
strlcpy(b, base, sizeof(b));
char *q = strchr(b, '?');
if (q) {
*q = 0;
}
if (ref[0] == '/') {
char *host_end = strchr(strstr(b, "://") + 3, '/');
if (host_end) {
*host_end = 0;
}
} else {
char *slash = strrchr(b, '/');
if (slash) {
slash[1] = 0;
}
}
snprintf(out, n, "%s%s", b, ref);
}
// Next line of s_text (CRLF tolerant); NULL at the end.
static char *next_line(char **p)
{
if (!*p || !**p) {
return NULL;
}
char *line = *p, *e = strchr(line, '\n');
*p = e ? e + 1 : NULL;
if (e) {
*e = 0;
}
size_t l = strlen(line);
while (l && (line[l - 1] == '\r' || line[l - 1] == ' ')) {
line[--l] = 0;
}
return line;
}
// Master playlist: pick the variant with the highest BANDWIDTH. false if s_text is a media playlist.
static bool pick_variant(const char *base, char *out, size_t n)
{
if (!strstr(s_text, "#EXT-X-STREAM-INF")) {
return false;
}
long best = -1, bw = -1;
char *p = s_text, *line;
while ((line = next_line(&p))) {
if (!strncmp(line, "#EXT-X-STREAM-INF:", 18)) {
const char *b = strstr(line, "BANDWIDTH=");
bw = b ? atol(b + 10) : 0;
} else if (line[0] && line[0] != '#' && bw >= 0) {
if (bw > best) {
best = bw;
resolve(out, n, base, line);
}
bw = -1;
}
}
ESP_LOGI(TAG, "variant %ld bit/s: %s", best, out);
return best >= 0;
}
static bool parse_media(const char *base)
{
s_pl->target_s = 10;
s_pl->media_seq = 0;
s_pl->count = 0;
char *p = s_text, *line;
bool is_m3u = false;
while ((line = next_line(&p))) {
if (!strcmp(line, "#EXTM3U")) {
is_m3u = true;
} else if (!strncmp(line, "#EXT-X-TARGETDURATION:", 22)) {
s_pl->target_s = atoi(line + 22);
} else if (!strncmp(line, "#EXT-X-MEDIA-SEQUENCE:", 22)) {
s_pl->media_seq = atoll(line + 22);
} else if (line[0] && line[0] != '#' && s_pl->count < MAX_SEGMENTS) {
resolve(s_pl->uri[s_pl->count++], URL_MAX, base, line);
}
}
return is_m3u && s_pl->count > 0;
}
/* ----- segments ----- */
static bool fetch_segment(long long seq, const char *url)
{
int64_t t0 = esp_timer_get_time();
esp_http_client_handle_t c = http_open(url);
if (!c) {
return false;
}
// Download completely first, then decode: the connection is not held open while the
// decoder waits for space in the ring (a stalled TCP stream for ~10 s may get cut by the CDN).
size_t total = 0;
int r = 0;
bool ok = true;
while (total < SEG_MAX && (r = esp_http_client_read(c, (char *)s_seg + total, SEG_MAX - total)) > 0) {
total += r;
}
if (r < 0 || total == SEG_MAX) {
ok = false;
}
esp_http_client_close(c);
esp_http_client_cleanup(c);
int64_t us = esp_timer_get_time() - t0;
ESP_LOGD(TAG, "segment %lld: %u bytes in %.2f s (%.1f Mbit/s)%s", seq, (unsigned)total, us / 1e6,
us ? total * 8.0 / us : 0.0, ok ? "" : ", failed");
if (ok && s_sink) {
ok = s_sink(s_seg, total, true); // blocks at playback speed while the ring is full
}
return ok;
}
static void hls_task(void *arg)
{
while (1) {
wanted_url(s_url, sizeof(s_url));
if (!s_url[0] || s_suspended) {
vTaskDelay(pdMS_TO_TICKS(1000));
continue;
}
ESP_LOGI(TAG, "start: %s", s_url);
// Master -> media playlist
if (http_get_text(s_url) < 0) {
vTaskDelay(pdMS_TO_TICKS(5000));
continue;
}
if (!pick_variant(s_url, s_media_url, sizeof(s_media_url))) {
strlcpy(s_media_url, s_url, sizeof(s_media_url));
}
long long next = -1;
int errors = 0;
while (still_wanted() && errors < 5) {
int64_t t0 = esp_timer_get_time();
if (http_get_text(s_media_url) < 0 || !parse_media(s_media_url)) {
errors++;
vTaskDelay(pdMS_TO_TICKS(2000));
continue;
}
long long first = s_pl->media_seq, last = first + s_pl->count - 1;
if (next < 0) {
next = last - LIVE_BACK + 1 > first ? last - LIVE_BACK + 1 : first;
ESP_LOGI(TAG, "live playlist: seq %lld..%lld, target %d s, starting at %lld",
first, last, s_pl->target_s, next);
} else if (next < first) {
ESP_LOGW(TAG, "fell behind the live window (%lld < %lld), skipping ahead", next, first);
next = first;
}
bool got_new = false;
for (; next <= last && still_wanted(); next++) {
if (!fetch_segment(next, s_pl->uri[next - first])) {
errors++;
break;
}
errors = 0;
got_new = true;
}
// No new segment: wait half the target duration before reloading (RFC 8216 6.3.4).
if (!got_new) {
int64_t wait = s_pl->target_s * 500000LL - (esp_timer_get_time() - t0);
if (wait > 0) {
vTaskDelay(pdMS_TO_TICKS(wait / 1000));
}
}
}
if (errors >= 5) {
ESP_LOGW(TAG, "too many errors, restarting from the playlist in 5 s");
vTaskDelay(pdMS_TO_TICKS(5000));
}
}
}
esp_err_t hls_start(hls_sink_t sink)
{
s_sink = sink;
s_text = heap_caps_malloc(PLAYLIST_MAX, MALLOC_CAP_SPIRAM);
s_pl = heap_caps_malloc(sizeof(media_pl_t), MALLOC_CAP_SPIRAM);
s_seg = heap_caps_malloc(SEG_MAX, MALLOC_CAP_SPIRAM);
if (!s_text || !s_pl || !s_seg) {
return ESP_ERR_NO_MEM;
}
return xTaskCreate(hls_task, "hls", 10240, NULL, 4, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
+23
View File
@@ -0,0 +1,23 @@
// HLS client: playlists, variant choice, live segment loop. Segment bytes go to a sink callback.
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
// Receives segment data in chunks (MPEG-TS etc.). Return false to abort the segment.
typedef bool (*hls_sink_t)(const uint8_t *data, size_t len, bool segment_start);
#define HLS_URL_MAX 384
esp_err_t hls_start(hls_sink_t sink);
// The playlist URL to play ("" = none). A different URL restarts fetching with it.
void hls_set_url(const char *url);
// Stop fetching (current download is abandoned) until resumed. Reasons are independent:
// fetching runs only when no reason holds it.
#define HLS_SUSPEND_OTA (1 << 0)
#define HLS_SUSPEND_FAILOVER (1 << 1)
#define HLS_SUSPEND_USER (1 << 2) // paused via the player API
void hls_suspend(unsigned reason, bool suspend);
+4
View File
@@ -0,0 +1,4 @@
dependencies:
# Newer versions use P4 assembly that needs chip rev >= 3.0; this board is rev 1.3 (see CLAUDE.md).
espressif/esp_audio_codec: "~2.5.0"
espressif/esp_audio_effects: "~1.3.0"
+2
View File
@@ -10,6 +10,7 @@
#include "esp_app_desc.h"
#include "esp_chip_info.h"
#include "esp_log.h"
#include "player.h"
#include "project_cfg.h"
static const char *TAG = "main";
@@ -39,6 +40,7 @@ void app_main(void)
project_cfg_register();
ESP_ERROR_CHECK(aes67_ota_init());
ESP_ERROR_CHECK(aes67_sdp_sap_init());
ESP_ERROR_CHECK(player_init());
ESP_ERROR_CHECK(aes67_tx_start());
ESP_ERROR_CHECK(aes67_web_start());
}
+641
View File
@@ -0,0 +1,641 @@
#include "player.h"
#include <math.h>
#include <string.h>
#include "aes67_cfg.h"
#include "aes67_ota.h"
#include "aes67_tx.h"
#include "aes67_web.h"
#include "audio_out.h"
#include "audio_ring.h"
#include "decoder.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "hls.h"
#include "spotify.h"
#define RATE 48000
#define CHANNELS AES67_TX_SRC_CHANNELS // the ring holds what TX pulls: stereo
#define RING_FRAMES (4 * RATE) // 4 s in PSRAM
#define PREFILL_FRAMES (RATE) // 1 s before (re)starting output
#define FADE_FRAMES (RATE * 30 / 1000) // 30 ms ramp at a source switch
#define SPOTIFY_WAIT_MS 100 // longest the Spotify data callback may wait (cspot holds a lock)
#define CONTROL_MS 250
static const char *TAG = "player";
typedef enum { MODE_TONE, MODE_OFF, MODE_HLS, MODE_SPOTIFY, MODE_AUTO, MODE_PINK } mode_t_;
static const char *const SRC_NAME[] = { "tone", "off", "hls", "spotify", "pink" };
static const char *const MODE_NAME[] = { "tone", "off", "hls", "spotify", "auto", "pink" };
static volatile mode_t_ s_mode = MODE_OFF;
static volatile player_src_t s_src = PLAYER_SRC_OFF; // what is playing now
static volatile player_src_t s_target = PLAYER_SRC_OFF; // switch to this (TX task, with fades)
static volatile bool s_playing; // ring output running (after prefill)
static volatile bool s_flush; // consumer drops buffered audio on the next read
static volatile bool s_paused; // Spotify paused: silence, buffer kept, no underrun
static volatile bool s_sp_playing; // Spotify has started playback and is not paused
static volatile bool s_hls_paused; // HLS paused via the API: not fetching, silence
static audio_conv_t *s_spotify_conv;
// Effective mode: the config's, or a runtime override from the API (not saved). Web server task.
static mode_t_ s_cfg_mode = MODE_OFF;
static char s_cfg_url[HLS_URL_MAX];
static int s_forced = -1; // mode forced via /api/player/source|url, -1 = none
static char s_forced_url[HLS_URL_MAX]; // from /api/player/url; "" = the config's URL
// Failover (mode auto)
static volatile int s_failover_delay_s = 5;
static volatile bool s_failover_on_pause;
// TX task only
static int s_fade_out; // frames left in the fade-out before a switch
static int s_fade_in; // frames left in the fade-in after a switch
// Player volume and the fixed output trim (source.gain_db), applied after the ring so a change is
// heard at once (not a ring length later).
static volatile float s_target_gain = 1.0f;
static float s_gain = 1.0f; // TX task only; ramps to s_target_gain
static volatile int s_volume_pct = 100;
static volatile float s_trim = 1.0f; // source.gain_db as amplitude
// 0..100 % -> amplitude: cubic curve (about -18 dB at 50 %, 0 % = mute), times the trim.
static void set_volume(int pct)
{
pct = pct < 0 ? 0 : pct > 100 ? 100 : pct;
float r = pct / 100.0f;
s_volume_pct = pct;
s_target_gain = r * r * r * s_trim;
}
// Scale one sample, clipping at full scale (the trim can boost up to +12 dB).
static inline int32_t scale(int32_t x, float g)
{
float v = x * g;
return v >= 2147483520.0f ? INT32_MAX : v <= -2147483648.0f ? INT32_MIN : (int32_t)v;
}
// Apply the gain, ramping linearly from the previous gain over this buffer (no zipper noise).
static void apply_gain(int32_t *buf, size_t frames)
{
float target = s_target_gain;
if (s_gain == target && target == 1.0f) {
return;
}
float step = (target - s_gain) / frames;
for (size_t i = 0; i < frames; i++) {
s_gain += step;
buf[i * 2] = scale(buf[i * 2], s_gain);
buf[i * 2 + 1] = scale(buf[i * 2 + 1], s_gain);
}
s_gain = target;
}
// Linear ramp over a fade: position counts down from FADE_FRAMES; fade-in rises, fade-out falls.
static void apply_fade(int32_t *buf, size_t frames, int *left, bool in)
{
for (size_t i = 0; i < frames && *left > 0; i++, (*left)--) {
float g = (float)(*left) / FADE_FRAMES; // 1 -> 0 over the fade
if (in) {
g = 1.0f - g;
}
buf[i * 2] = (int32_t)(buf[i * 2] * g);
buf[i * 2 + 1] = (int32_t)(buf[i * 2 + 1] * g);
}
}
static mode_t_ mode_of(const char *m)
{
return !strcmp(m, "tone") ? MODE_TONE : !strcmp(m, "hls") ? MODE_HLS : !strcmp(m, "spotify") ? MODE_SPOTIFY :
!strcmp(m, "auto") ? MODE_AUTO : !strcmp(m, "pink") ? MODE_PINK : MODE_OFF;
}
/* ----- output (AES67 TX pull callback, TX task, must not block) ----- */
// One buffer of the current source: ring audio, or silence while off / paused / buffering.
// Returns the frames produced (fewer = underrun).
static size_t read_current(int32_t *buf, size_t frames)
{
if (s_flush) {
audio_ring_flush();
s_flush = false;
s_playing = false;
}
if (s_src == PLAYER_SRC_OFF || (s_src == PLAYER_SRC_SPOTIFY && s_paused) ||
(s_src == PLAYER_SRC_HLS && s_hls_paused)) {
memset(buf, 0, frames * CHANNELS * sizeof(int32_t));
return frames;
}
if (!s_playing) {
if (audio_ring_level() < PREFILL_FRAMES) {
memset(buf, 0, frames * CHANNELS * sizeof(int32_t));
return frames;
}
s_playing = true;
s_fade_in = FADE_FRAMES; // (re)start without a click
}
size_t got = audio_ring_read(buf, frames);
if (got < frames) {
s_playing = false; // ran dry: underrun (counted by TX), prefill again
}
return got;
}
static size_t player_read(int32_t *buf, size_t frames)
{
// A switch is due: fade the current source out, then switch (ring flushed, new source prefills).
if (s_target != s_src && s_fade_out == 0) {
s_fade_out = FADE_FRAMES;
}
size_t got = read_current(buf, frames);
if (s_fade_in > 0) {
apply_fade(buf, got, &s_fade_in, true);
}
if (s_fade_out > 0) {
apply_fade(buf, got, &s_fade_out, false);
if (s_fade_out == 0 || got < frames) {
s_fade_out = 0;
audio_ring_flush(); // before s_src changes: writers only write for the active source
s_playing = false;
s_flush = false;
s_src = s_target;
}
}
apply_gain(buf, got);
return got;
}
// Test signals: straight from the core to TX, not through the ring, volume or gain.
static bool is_test_signal(player_src_t src)
{
return src == PLAYER_SRC_TONE || src == PLAYER_SRC_PINK;
}
// Set the source to play. Test signals come from the core (the tone phase-locked to PTP), so
// switches from/to them are immediate; everything else fades through player_read.
static void select_source(player_src_t src)
{
if (src == s_target) {
return;
}
ESP_LOGI(TAG, "source: %s -> %s", SRC_NAME[s_src], SRC_NAME[src]);
if (s_hls_paused) { // an API pause of HLS lasts until the next switch
s_hls_paused = false;
hls_suspend(HLS_SUSPEND_USER, false);
}
if (is_test_signal(src) || is_test_signal(s_src)) {
s_target = s_src = src;
s_flush = true;
aes67_tx_set_source(src == PLAYER_SRC_TONE ? NULL : src == PLAYER_SRC_PINK ? aes67_tx_pink_noise :
player_read);
return;
}
s_target = src; // player_read fades out and switches
}
// Apply the effective mode: Spotify on/off, the HLS URL, and the source to play.
static void apply_mode(void)
{
static char applied_url[HLS_URL_MAX];
mode_t_ mode = s_forced >= 0 ? (mode_t_)s_forced : s_cfg_mode;
if (s_spotify_conv) { // after spotify_init: follows mode / name / credentials live
spotify_apply(mode == MODE_SPOTIFY || mode == MODE_AUTO);
}
const char *url = mode != MODE_HLS && mode != MODE_AUTO ? "" : s_forced_url[0] ? s_forced_url : s_cfg_url;
if (strcmp(url, applied_url)) {
strlcpy(applied_url, url, sizeof(applied_url));
hls_set_url(url);
if (s_src == PLAYER_SRC_HLS) {
s_flush = true; // another stream: don't finish the old one's buffer
}
}
if (mode == s_mode) {
return;
}
s_mode = mode;
// HLS fetches only in hls mode, or in auto while it is the active source (control task).
hls_suspend(HLS_SUSPEND_FAILOVER, mode == MODE_AUTO);
switch (mode) {
case MODE_TONE: select_source(PLAYER_SRC_TONE); break;
case MODE_PINK: select_source(PLAYER_SRC_PINK); break;
case MODE_HLS: select_source(PLAYER_SRC_HLS); break;
case MODE_SPOTIFY: select_source(PLAYER_SRC_SPOTIFY); break;
case MODE_AUTO: select_source(PLAYER_SRC_SPOTIFY); break; // Spotify inactive: HLS after the delay
default: select_source(PLAYER_SRC_OFF); break;
}
}
void player_apply(const cJSON *source)
{
s_failover_delay_s = (int)cJSON_GetObjectItemCaseSensitive(source, "failover_delay_s")->valuedouble;
s_failover_on_pause = cJSON_IsTrue(cJSON_GetObjectItemCaseSensitive(source, "failover_on_pause"));
s_trim = powf(10.0f, (float)cJSON_GetObjectItemCaseSensitive(source, "gain_db")->valuedouble / 20.0f);
set_volume(s_volume_pct);
s_cfg_mode = mode_of(cJSON_GetObjectItemCaseSensitive(source, "mode")->valuestring);
strlcpy(s_cfg_url, cJSON_GetObjectItemCaseSensitive(source, "hls_url")->valuestring, sizeof(s_cfg_url));
apply_mode();
}
/* ----- source side ----- */
// Write converted 48 kHz frames, waiting for space at playback speed. Frames of a source that is
// neither playing nor about to play are dropped (returns n).
size_t player_write(player_src_t src, const int32_t *frames, size_t n)
{
size_t done = 0;
while (done < n) {
if (src == PLAYER_SRC_HLS && s_hls_paused) {
return n; // paused: let the decoder finish the segment it is on
}
if (s_src != src) {
if (s_target != src) {
return n; // not this source's turn: drop
}
vTaskDelay(pdMS_TO_TICKS(5)); // switch in progress (fade-out, ~30 ms)
continue;
}
size_t w = audio_ring_write(frames + done * CHANNELS, n - done);
if (!w) {
vTaskDelay(pdMS_TO_TICKS(20));
}
done += w;
}
return done;
}
/* ----- Spotify ----- */
// cspot calls this holding a lock that stopping the session also needs: never wait long. Take only
// what fits in the ring; return 0 after SPOTIFY_WAIT_MS and cspot retries (it can stop in between).
// When it isn't Spotify's turn, hold cspot back the same way: it doesn't stop decoding on pause, so
// dropping frames would let it race through the queue at full speed (CPU and network), starving HLS.
static size_t spotify_pcm(const int16_t *pcm, size_t frames)
{
int64_t until = esp_timer_get_time() + SPOTIFY_WAIT_MS * 1000LL;
while (true) {
if (s_src == PLAYER_SRC_SPOTIFY) {
// 44.1 kHz in -> about 1.09x as many 48 kHz frames out; keep a margin
size_t fit = audio_ring_space() * 44100 / 48000;
fit = fit > 64 ? fit - 64 : 0;
size_t n = frames < fit ? frames : fit;
if (n) {
audio_conv_write(s_spotify_conv, pcm, n, 2, 44100);
return n;
}
}
if (esp_timer_get_time() >= until) {
return 0;
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}
static void spotify_event(spotify_event_t ev, int value)
{
switch (ev) {
case SPOTIFY_EV_PLAY:
s_paused = false;
s_sp_playing = true;
break;
case SPOTIFY_EV_PAUSE:
s_paused = true;
s_sp_playing = false;
break;
case SPOTIFY_EV_FLUSH:
if (s_src == PLAYER_SRC_SPOTIFY) {
s_flush = true; // skip/seek: don't play out the old buffer
}
break;
case SPOTIFY_EV_VOLUME: {
// Spotify sends 0..65535; the app's slider stays the master of the player volume.
int pct = (value * 100 + 32767) / 65535;
set_volume(pct);
float g = s_target_gain;
ESP_LOGI(TAG, "volume %d%% (%.1f dB)", pct, g > 0 ? 20.0f * log10f(g) : -INFINITY);
break;
}
}
}
/* ----- failover (mode auto) ----- */
// Spotify stays advertised; HLS plays whenever Spotify is inactive for failover_delay_s, and Spotify
// takes over as soon as it plays. HLS is stopped while Spotify plays (no bandwidth/CPU).
static void control_task(void *arg)
{
int64_t inactive_since = esp_timer_get_time();
while (true) {
vTaskDelay(pdMS_TO_TICKS(CONTROL_MS));
if (s_mode != MODE_AUTO) {
inactive_since = esp_timer_get_time();
continue;
}
bool session = spotify_session_active();
if (!session) {
s_sp_playing = false; // session ended (app left, error, disabled)
}
bool playing = session && s_sp_playing;
// Inactive: no session; with failover_on_pause also a connected but paused/stopped one.
bool inactive = !session || (s_failover_on_pause && !playing);
int64_t now = esp_timer_get_time();
if (!inactive) {
inactive_since = now;
}
if (playing && s_target != PLAYER_SRC_SPOTIFY) {
ESP_LOGI(TAG, "auto: Spotify is playing, switching to it");
hls_suspend(HLS_SUSPEND_FAILOVER, true);
select_source(PLAYER_SRC_SPOTIFY);
} else if (inactive && s_target == PLAYER_SRC_SPOTIFY &&
now - inactive_since >= (int64_t)s_failover_delay_s * 1000000) {
ESP_LOGI(TAG, "auto: Spotify inactive for %d s, failing over to HLS", s_failover_delay_s);
hls_suspend(HLS_SUSPEND_FAILOVER, false);
select_source(PLAYER_SRC_HLS);
}
}
}
// Firmware upload: flash writes stall tasks for > 20 ms at a time; with a Spotify session running,
// uploads crawled and sometimes ended in a reset (pausing was not enough). End the session (its
// tasks and connections are gone before the first write) and stop HLS fetching meanwhile. The
// device reboots after a good upload anyway; after a failed one the sources come back (Spotify
// waits for the app to reconnect).
static void on_ota(bool starting)
{
if (starting) {
spotify_suspend(true);
hls_suspend(HLS_SUSPEND_OTA, true);
ESP_LOGI(TAG, "firmware update: Spotify session ended, HLS suspended");
} else {
hls_suspend(HLS_SUSPEND_OTA, false);
spotify_suspend(false);
ESP_LOGI(TAG, "firmware update failed: sources resumed");
}
}
static const char *source_state(player_src_t src)
{
return is_test_signal(src) ? "playing" : src == PLAYER_SRC_OFF ? "idle" :
src == PLAYER_SRC_SPOTIFY && !spotify_session_active() ? "idle" :
src == PLAYER_SRC_SPOTIFY && s_paused ? "paused" :
src == PLAYER_SRC_HLS && s_hls_paused ? "paused" : s_playing ? "playing" : "buffering";
}
static void player_status(cJSON *st)
{
player_src_t src = s_src;
const char *state = source_state(src);
cJSON_AddStringToObject(st, "active_source", SRC_NAME[src]);
cJSON_AddStringToObject(st, "source_state", state);
cJSON_AddStringToObject(st, "spotify_state", spotify_state());
cJSON_AddNumberToObject(st, "buffer_ms", (double)(audio_ring_level() * 1000 / RATE));
}
/* ----- Player API ----- */
static void add_str_or_null(cJSON *o, const char *key, const char *s)
{
if (s && s[0]) {
cJSON_AddStringToObject(o, key, s);
} else {
cJSON_AddNullToObject(o, key);
}
}
// Same JSON for GET /api/player and every POST.
static esp_err_t send_player(httpd_req_t *req)
{
player_src_t src = s_src;
spotify_track_t t;
bool sp = src == PLAYER_SRC_SPOTIFY && spotify_now_playing(&t);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "source", SRC_NAME[src]);
add_str_or_null(o, "forced", s_forced >= 0 ? MODE_NAME[s_forced] : NULL);
cJSON_AddStringToObject(o, "state", src == PLAYER_SRC_OFF ? "stopped" : source_state(src));
add_str_or_null(o, "artist", sp ? t.artist : NULL);
add_str_or_null(o, "title", sp ? t.title : NULL);
add_str_or_null(o, "album", sp ? t.album : NULL);
if (sp && t.duration_ms) {
cJSON_AddNumberToObject(o, "position_ms", t.position_ms);
cJSON_AddNumberToObject(o, "duration_ms", t.duration_ms);
} else {
cJSON_AddNullToObject(o, "position_ms");
cJSON_AddNullToObject(o, "duration_ms");
}
cJSON_AddNumberToObject(o, "volume", s_volume_pct);
cJSON *can = cJSON_AddObjectToObject(o, "can");
cJSON_AddBoolToObject(can, "pause", sp || src == PLAYER_SRC_HLS);
cJSON_AddBoolToObject(can, "next", sp);
cJSON_AddBoolToObject(can, "prev", sp);
cJSON_AddBoolToObject(can, "seek", sp);
esp_err_t err = web_send_json(req, o);
cJSON_Delete(o);
return err;
}
static esp_err_t player_get(httpd_req_t *req)
{
return send_player(req);
}
static void hls_pause(bool pause)
{
if (pause == s_hls_paused) {
return;
}
s_hls_paused = pause;
hls_suspend(HLS_SUSPEND_USER, pause);
s_flush = true; // live: resume rejoins at the live edge, never plays the old buffer
ESP_LOGI(TAG, "hls %s", pause ? "paused" : "resumed");
}
// Transport on the active source. Returns NULL, or the reason it can't be done (409).
static const char *transport(const char *cmd)
{
player_src_t src = s_src;
bool pause = !strcmp(cmd, "pause") || !strcmp(cmd, "stop");
bool play = !strcmp(cmd, "play");
bool next = !strcmp(cmd, "next"), prev = !strcmp(cmd, "prev");
if (!strcmp(cmd, "toggle")) {
bool paused = src == PLAYER_SRC_SPOTIFY ? s_paused : s_hls_paused;
pause = !paused;
play = paused;
}
if (src == PLAYER_SRC_SPOTIFY) {
spotify_cmd_t c = pause ? SPOTIFY_CMD_PAUSE : play ? SPOTIFY_CMD_PLAY :
next ? SPOTIFY_CMD_NEXT : SPOTIFY_CMD_PREV;
return spotify_command(c, 0) ? NULL : "no Spotify session";
}
if (src == PLAYER_SRC_HLS) {
if (next || prev) {
return "live stream: no next/previous";
}
hls_pause(pause);
return NULL;
}
return "no player source active";
}
// Small JSON body of a POST; NULL if missing or invalid.
static cJSON *read_body(httpd_req_t *req)
{
char buf[HLS_URL_MAX + 128]; // fits {"url": ...}
if (req->content_len == 0 || req->content_len >= sizeof(buf)) {
return NULL;
}
size_t got = 0;
while (got < req->content_len) {
int r = httpd_req_recv(req, buf + got, req->content_len - got);
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
continue;
}
if (r <= 0) {
return NULL;
}
got += r;
}
buf[got] = '\0';
return cJSON_Parse(buf);
}
static esp_err_t send_409(httpd_req_t *req, const char *msg)
{
httpd_resp_set_status(req, "409 Conflict");
return httpd_resp_sendstr(req, msg);
}
// POST /api/player/seek {ms}, /api/player/volume {value} or {delta}
static esp_err_t seek_or_volume(httpd_req_t *req, bool seek)
{
cJSON *body = read_body(req);
const cJSON *v = cJSON_GetObjectItemCaseSensitive(body, seek ? "ms" : "value");
const cJSON *d = seek ? NULL : cJSON_GetObjectItemCaseSensitive(body, "delta");
double val = cJSON_IsNumber(v) ? v->valuedouble : cJSON_IsNumber(d) ? s_volume_pct + d->valuedouble : -1;
cJSON_Delete(body);
if (val < 0 && !(cJSON_IsNumber(d) && !seek)) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, seek ? "expected {\"ms\": n}" :
"expected {\"value\": 0-100} or {\"delta\": n}");
}
if (seek) {
if (s_src != PLAYER_SRC_SPOTIFY) {
return send_409(req, "source can't seek");
}
if (!spotify_command(SPOTIFY_CMD_SEEK, (uint32_t)val)) {
return send_409(req, "no Spotify session");
}
} else {
int pct = val < 0 ? 0 : val > 100 ? 100 : (int)(val + 0.5);
set_volume(pct);
spotify_set_volume(pct); // the app follows (if a session runs)
}
return send_player(req);
}
// POST /api/player/source {source: spotify|hls|off|config}, /api/player/url {url}: runtime override
static esp_err_t force_source(httpd_req_t *req, bool url)
{
cJSON *body = read_body(req);
const cJSON *v = cJSON_GetObjectItemCaseSensitive(body, url ? "url" : "source");
const char *s = cJSON_IsString(v) ? v->valuestring : "";
const char *err = NULL;
if (url) {
if (strncmp(s, "http://", 7) && strncmp(s, "https://", 8)) {
err = "expected {\"url\": \"http(s)://...m3u8\"}";
} else if (strlen(s) >= sizeof(s_forced_url)) {
err = "url too long";
} else {
s_forced = MODE_HLS;
strlcpy(s_forced_url, s, sizeof(s_forced_url));
if (s_hls_paused && s_src == PLAYER_SRC_HLS) {
hls_pause(false); // a new stream starts playing
}
}
} else if (!strcmp(s, "config")) {
s_forced = -1;
s_forced_url[0] = '\0';
} else if (!strcmp(s, "spotify") || !strcmp(s, "hls") || !strcmp(s, "off")) {
s_forced = mode_of(s);
s_forced_url[0] = '\0';
} else {
err = "expected {\"source\": \"spotify|hls|off|config\"}";
}
if (!err) {
ESP_LOGI(TAG, "override: %s%s%s", s_forced >= 0 ? MODE_NAME[s_forced] : "none (config)",
s_forced_url[0] ? " " : "", s_forced_url);
apply_mode();
}
cJSON_Delete(body);
return err ? httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, err) : send_player(req);
}
// POST /api/player/<cmd>
static esp_err_t player_post(httpd_req_t *req)
{
static const char *const TRANSPORT[] = { "play", "pause", "toggle", "stop", "next", "prev" };
const char *cmd = req->uri + strlen("/api/player/");
char name[16];
size_t len = strcspn(cmd, "?");
if (len >= sizeof(name)) {
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "unknown player command");
}
memcpy(name, cmd, len);
name[len] = '\0';
for (int i = 0; i < sizeof(TRANSPORT) / sizeof(TRANSPORT[0]); i++) {
if (!strcmp(name, TRANSPORT[i])) {
const char *err = transport(name);
return err ? send_409(req, err) : send_player(req);
}
}
if (!strcmp(name, "seek") || !strcmp(name, "volume")) {
return seek_or_volume(req, name[0] == 's');
}
if (!strcmp(name, "source") || !strcmp(name, "url")) {
return force_source(req, name[0] == 'u');
}
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "unknown player command");
}
esp_err_t player_init(void)
{
esp_err_t err = audio_ring_init(RING_FRAMES, CHANNELS);
if (err != ESP_OK) {
ESP_LOGE(TAG, "ring buffer: %s", esp_err_to_name(err));
return err;
}
aes67_tx_set_source(player_read);
cJSON *src = cfg_get("source");
s_mode = (mode_t_)-1;
player_apply(src);
cJSON_Delete(src);
err = decoder_init();
if (err != ESP_OK) {
return err;
}
s_spotify_conv = audio_conv_create(PLAYER_SRC_SPOTIFY, "spotify");
if (!s_spotify_conv) {
return ESP_ERR_NO_MEM;
}
spotify_init(spotify_pcm, spotify_event, audio_ring_written, audio_ring_read_pos);
apply_mode(); // now with Spotify
aes67_ota_on_update(on_ota);
err = hls_start(decoder_feed);
if (err != ESP_OK) {
return err;
}
if (xTaskCreate(control_task, "player_ctl", 3072, NULL, 4, NULL) != pdPASS) {
return ESP_ERR_NO_MEM;
}
static const httpd_uri_t uris[] = {
{ .uri = "/api/player", .method = HTTP_GET, .handler = player_get },
{ .uri = "/api/player/*", .method = HTTP_POST, .handler = player_post },
};
for (int i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
err = web_register_uri(&uris[i]);
if (err != ESP_OK) {
return err;
}
}
return status_register(player_status);
}
+17
View File
@@ -0,0 +1,17 @@
// Project player: picks the audio source for AES67 TX (test tone, pink noise, silence, HLS, Spotify).
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "cJSON.h"
#include "esp_err.h"
typedef enum { PLAYER_SRC_TONE, PLAYER_SRC_OFF, PLAYER_SRC_HLS, PLAYER_SRC_SPOTIFY, PLAYER_SRC_PINK } player_src_t;
esp_err_t player_init(void);
// Apply the "source" config group (mode etc.).
void player_apply(const cJSON *source);
// Source side: write 48 kHz stereo int32 frames, blocking while the ring is full.
// Frames from a source that is not the active one are dropped (returns n).
size_t player_write(player_src_t src, const int32_t *frames, size_t n);
+9 -3
View File
@@ -3,19 +3,23 @@
#include "aes67_cfg.h"
#include "esp_err.h"
#include "player.h"
static const char SOURCE_DEFAULTS[] =
"{\"mode\":\"spotify\",\"spotify_name\":\"P4 AES67\",\"spotify_bitrate\":320,\"hls_url\":\"\","
"\"autoplay\":false,\"gain_db\":0,\"failover_delay_s\":5,\"failover_on_pause\":false}";
"\"autoplay\":false,\"gain_db\":0,\"failover_delay_s\":5,\"failover_on_pause\":false,"
"\"spotify_client_id\":\"\",\"spotify_client_secret\":\"\"}";
static bool source_validate(const cJSON *g, char *err, size_t n)
{
static const char *const modes[] = { "spotify", "hls", "auto", "off", NULL };
static const char *const modes[] = { "spotify", "hls", "auto", "tone", "pink", "off", NULL };
static const double bitrates[] = { 96, 160, 320 };
return cfg_check_enum(g, "mode", modes, err, n) &&
cfg_check_str(g, "spotify_name", 1, 63, err, n) &&
cfg_check_num_in(g, "spotify_bitrate", bitrates, 3, err, n) &&
cfg_check_str(g, "hls_url", 0, 255, err, n) &&
cfg_check_str(g, "spotify_client_id", 0, 64, err, n) &&
cfg_check_str(g, "spotify_client_secret", 0, 64, err, n) &&
cfg_check_num(g, "gain_db", -60, 12, err, n) &&
cfg_check_int(g, "failover_delay_s", 0, 3600, err, n);
}
@@ -29,5 +33,7 @@ void project_cfg_defaults(void)
void project_cfg_register(void)
{
ESP_ERROR_CHECK(cfg_register("source", SOURCE_DEFAULTS, source_validate, NULL));
ESP_ERROR_CHECK(cfg_register("source", SOURCE_DEFAULTS, source_validate, player_apply));
// Each user's own Spotify developer app (developer.spotify.com); the secret is write-only.
ESP_ERROR_CHECK(cfg_mark_secret("source", "spotify_client_secret"));
}
+17
View File
@@ -19,3 +19,20 @@ CONFIG_ESPTOOLPY_FLASHSIZE_32MB=y
# LLDP and PTP send raw frames from their own tasks next to lwIP: serialise EMAC transmits
CONFIG_ETH_TRANSMIT_MUTEX=y
# lwIP default is 10 sockets; PTP (2), AES67 TX, SAP, syslog and httpd's listen/control sockets
# use 7, leaving ~3 for web clients (httpd allows 7): a browser's keep-alive connections then
# starve new requests. 16 = 7 others + 7 web clients + OTA self-test client + 1 spare.
CONFIG_LWIP_MAX_SOCKETS=16
# 32 MB PSRAM in the P4 package (hex mode, 200 MHz; 250 MHz needs rev >= 3). Needed for step 7:
# HLS segment buffers, cspot, decoders. malloc() puts blocks >16 KB in PSRAM; DMA buffers stay internal.
CONFIG_SPIRAM=y
# cspot (Spotify Connect, step 7.5) needs C++ exceptions.
CONFIG_COMPILER_CXX_EXCEPTIONS=y
# esp_audio_codec's Vorbis decoder exports the same symbols (vorbis_info_init, ...) as cspot's
# Tremor (bell): keep it out of the link. HLS only needs AAC.
# CONFIG_AUDIO_DECODER_VORBIS_SUPPORT is not set
# CONFIG_AUDIO_SIMPLE_DEC_OGG_SUPPORT is not set
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""Flash this firmware onto another ESP32-P4 board over USB, then give it its own identity.
Steps: pick the port, check the chip (ESP32-P4, revision the image supports, flash size),
optionally erase, write bootloader + partition table + app, wait for the board's IP in its boot
log, then set hostname / stream name / multicast address over the web API so it doesn't clash
with other boards on the network.
Needs esptool (in the ESP-IDF Python env, or `pip install esptool`) and a build (`idf.py build`).
Every question can also be answered with an option, e.g.:
tools/flash_board.py --port /dev/ttyACM0 --erase --hostname p4-aes67-2 --name "P4 AES67 2" \\
--mcast 239.69.1.11
Boards already running this firmware and on the network update over the web (OTA) instead.
"""
import argparse
import json
import os
import re
import struct
import subprocess
import sys
import time
import urllib.request
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MIN_FLASH_MB = 32 # the bootloader header says 32 MB (sdkconfig); smaller chips aren't supported
def die(msg):
print(f"\nERROR: {msg}")
sys.exit(1)
def ask(prompt, default=None):
s = input(f"{prompt}{f' [{default}]' if default is not None else ''}: ").strip()
return s or (default if default is not None else "")
def yes(prompt, default):
s = input(f"{prompt} [{'Y/n' if default else 'y/N'}]: ").strip().lower()
return default if not s else s.startswith("y")
def esptool(port, *args, capture=True):
cmd = [sys.executable, "-m", "esptool", "--chip", "esp32p4", "--port", port, *args]
if not capture:
if subprocess.call(cmd) != 0:
die("esptool failed (see above)")
return ""
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
die(f"esptool {' '.join(args)} failed:\n{r.stdout}{r.stderr}")
return r.stdout
def pick_port(given):
if given:
return given
try:
from serial.tools import list_ports
except ImportError:
die("pyserial missing: run inside the ESP-IDF environment or `pip install esptool`")
ports = [p for p in list_ports.comports() if "ACM" in p.device or "USB" in p.device]
if not ports:
die("no USB serial port found: connect the board's USB-C port (not the PoE/Ethernet side)")
for i, p in enumerate(ports, 1):
print(f" {i}) {p.device} {p.description}")
if len(ports) == 1:
return ports[0].device if yes(f"Use {ports[0].device}?", True) else die("no port chosen")
n = ask("Port number", "1")
return ports[int(n) - 1].device
def load_images(build):
"""(offset, path) pairs and flash options from build/flash_args."""
fa = os.path.join(build, "flash_args")
if not os.path.exists(fa):
die(f"{fa} not found: build first (idf.py build)")
lines = open(fa).read().split("\n")
opts = lines[0].split()
images = []
for line in lines[1:]:
if line.strip():
off, path = line.split()
images.append((off, os.path.join(build, path)))
return opts, images
def image_rev_range(app):
"""Chip revision range from the app image header (esp_image_header_t), as (min, max) * 100."""
h = open(app, "rb").read(24)
if h[0] != 0xE9:
die(f"{app} is not an ESP app image")
min_full, max_full = struct.unpack_from("<HH", h, 15)
return min_full, max_full
def app_version(app):
# esp_app_desc_t after the image header (24 B) and first segment header (8 B): version at +16.
d = open(app, "rb").read(24 + 8 + 256)[32:]
return d[16:48].split(b"\0")[0].decode(errors="replace")
def check_chip(port, app):
out = esptool(port, "flash_id")
m = re.search(r"ESP32-P4 \(revision v(\d+)\.(\d+)\)", out)
if not m:
die(f"not an ESP32-P4?\n{out}")
rev = int(m.group(1)) * 100 + int(m.group(2))
lo, hi = image_rev_range(app)
print(f" chip: ESP32-P4 revision v{rev // 100}.{rev % 100}")
if not lo <= rev <= hi:
die(f"this build supports chip revisions v{lo // 100}.{lo % 100} to v{hi // 100}.{hi % 100}; "
f"the board is v{rev // 100}.{rev % 100}. Build with the matching "
"CONFIG_ESP32P4_SELECTS_REV_LESS_V3 setting (see CLAUDE.md).")
m = re.search(r"Detected flash size: (\d+)MB", out)
if not m:
die(f"could not read the flash size:\n{out}")
mb = int(m.group(1))
print(f" flash: {mb} MB")
if mb < MIN_FLASH_MB:
die(f"{mb} MB flash; this build needs {MIN_FLASH_MB} MB")
def wait_for_ip(port, timeout=90):
"""Read the boot log until the board reports its IP (the port open may reset it: fine here)."""
import serial
print(f" waiting for the board's IP (boot log on {port}, up to {timeout} s; Ethernet plugged in?)")
end = time.time() + timeout
with serial.Serial(port, 115200, timeout=1) as s:
buf = b""
while time.time() < end:
buf += s.read(4096)
m = re.search(rb"got IP (\d+\.\d+\.\d+\.\d+)", buf)
if m:
return m.group(1).decode()
buf = buf[-4096:]
return None
def api(ip, method, path, body=None):
req = urllib.request.Request(f"http://{ip}{path}", method=method,
data=json.dumps(body).encode() if body is not None else None,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
t = r.read()
return json.loads(t) if t else {}
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--port")
ap.add_argument("--build", default=os.path.join(REPO, "build"), help="build directory (default: build/)")
ap.add_argument("--erase", action=argparse.BooleanOptionalAction,
help="erase the whole flash first (clears any stored config)")
ap.add_argument("--hostname")
ap.add_argument("--name", help="stream / Spotify device name")
ap.add_argument("--mcast", help="AES67 multicast address")
ap.add_argument("--no-config", action="store_true", help="flash only, keep the default identity")
a = ap.parse_args()
opts, images = load_images(a.build)
app = next(p for off, p in images if p.endswith("aes67_p4.bin"))
print(f"Firmware: {app_version(app)} ({app})\n")
print("1) Port")
port = pick_port(a.port)
print("\n2) Checking the board")
check_chip(port, app)
print("\n3) Flashing")
erase = a.erase if a.erase is not None else yes(
" Erase the whole flash first? (yes for a new board or to clear an old config)", True)
if erase:
esptool(port, "erase_flash", capture=False)
args = ["write_flash", *opts]
for off, path in images:
args += [off, path]
esptool(port, *args, capture=False)
if a.no_config:
print("\nDone (default identity: hostname p4-aes67, multicast 239.69.1.10).")
return
print("\n4) Finding the board on the network")
ip = wait_for_ip(port)
if not ip:
die("no IP seen in the boot log. Check the Ethernet cable/DHCP; the board is flashed, set the "
"identity later in the web UI.")
print(f" board is at {ip}")
for _ in range(30): # web server comes up right after the IP
try:
cfg = api(ip, "GET", "/api/config")
break
except OSError:
time.sleep(1)
else:
die(f"web UI at http://{ip}/ does not answer")
print("\n5) Identity (must differ from every other board on this network)")
host = a.hostname or ask(" Hostname", "p4-aes67-2")
name = a.name or ask(" Stream / Spotify device name", "P4 AES67 2")
mcast = a.mcast or ask(" AES67 multicast address", "239.69.1.11")
cfg["net"]["hostname"] = host
cfg["aes67"]["name"] = name
cfg["aes67"]["mcast"] = mcast
cfg["source"]["spotify_name"] = name
try:
api(ip, "POST", "/api/config", cfg)
except urllib.error.HTTPError as e:
die(f"config rejected: {e.read().decode()}")
print(f"\nDone. Web UI: http://{ip}/ or http://{host}.local/")
print("Still to set in the web UI if needed: Spotify client ID/secret, source mode, PTP role.")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\naborted")
sys.exit(1)
+1
View File
@@ -0,0 +1 @@
0.0.1
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ben Nicholson
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.
+93 -29
View File
@@ -5,13 +5,18 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>AES67 device</title>
<!--
SPDX-License-Identifier: MIT (see web/LICENSE)
AES67 device web UI – reusable base.
CORE : status, PTP, AES67 output, network/VLAN, logging, SDP. Keep identical across projects.
PROJECT: blocks between "PROJECT START/END" markers (HTML and the PROJECT object in the script).
Form fields bind to config JSON by name="group.key". Add a field = add an input; no JS needed.
-->
<style>
:root{color-scheme:light dark}
/* Dark by default; the toggle (top right) switches to light and is remembered in this browser. */
:root{color-scheme:dark}
:root.light{color-scheme:light}
#theme{position:fixed;top:8px;right:8px;font-size:18px;line-height:1;padding:4px 8px;cursor:pointer}
[hidden]{display:none!important} /* else label{display:block} overrides it */
body{font:14px/1.4 system-ui,sans-serif;max-width:720px;margin:0 auto;padding:0 16px 32px}
fieldset{margin:12px 0}
label{display:block;margin:4px 0}
@@ -20,13 +25,23 @@ input:not([type=checkbox]),select{width:14em;max-width:100%}
textarea{width:100%;height:14em;font:12px monospace}
table td:first-child{padding-right:1em;opacity:.7}
pre{overflow-x:auto}
#msg{min-height:1.4em}
#msg{margin-left:1em}
/* Save bar: stays at the bottom of the window while the settings form is in view */
.bar{position:sticky;bottom:0;background:Canvas;padding:8px 0;border-top:1px solid color-mix(in srgb,CanvasText 20%,transparent)}
.ok{color:#2a2}.warn{color:#d80}.bad{color:#e33}
</style>
<script>
// Before the page is drawn, so a light choice doesn't flash dark first (and vice versa).
try { if (localStorage.getItem('theme') === 'light') document.documentElement.classList.add('light'); } catch {}
function toggleTheme() {
const light = document.documentElement.classList.toggle('light');
try { localStorage.setItem('theme', light ? 'light' : 'dark'); } catch {}
}
</script>
</head>
<body>
<button id="theme" type="button" onclick="toggleTheme()" title="Light / dark">&#x25D0;</button>
<h2 id="title">AES67 device</h2>
<p id="msg"></p>
<fieldset><legend>Status</legend><table id="status"></table></fieldset>
<fieldset><legend>PTP status</legend><table id="ptpstat"></table>
@@ -39,11 +54,11 @@ pre{overflow-x:auto}
<button onclick="ctl('toggle')">&#x23EF;</button>
<button onclick="ctl('next')">&#x23ED;</button>
<button onclick="ctl('stop')">&#x23F9;</button>
<label><span>Position</span><input id="pos" type="range" min="0" max="0" value="0" step="1000" disabled
oninput="seekDrag=true; showPos()" onchange="seekDrag=false; ctl('seek',{ms:+this.value})">
<small id="postime"></small></label>
<label><span>Volume</span><input id="vol" type="range" min="0" max="100"
onchange="ctl('volume',{value:+this.value})"></label>
<label><span>Force source</span><select id="force" onchange="ctl('source',{source:this.value})">
<option value="config">As configured</option><option value="spotify">Spotify</option>
<option value="hls">HLS</option><option value="off">Off</option></select></label>
<details><summary>API</summary><pre>
GET /api/player state, track, position, volume
POST /api/player/play|pause|toggle|stop|next|prev
@@ -64,12 +79,19 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
<option value="spotify">Spotify Connect</option>
<option value="hls">HLS / M3U8 URL</option>
<option value="auto">Spotify, fail over to HLS</option>
<option value="tone">Test tone (1 kHz, -18 dBFS)</option>
<option value="pink">Pink noise (-18 dBFS RMS)</option>
<option value="off">Off (silence)</option></select></label>
<label><span>Failover delay (s)</span><input name="source.failover_delay_s" type="number" min="0" max="3600"></label>
<label><span>Also fail over when paused</span><input name="source.failover_on_pause" type="checkbox"></label>
<label><span>Spotify device name</span><input name="source.spotify_name"></label>
<label><span>Spotify bitrate</span><select name="source.spotify_bitrate">
<option>96</option><option>160</option><option>320</option></select></label>
<label><span>Spotify client ID</span><input name="source.spotify_client_id" autocomplete="off"></label>
<label><span>Spotify client secret</span><input name="source.spotify_client_secret" type="password"
autocomplete="new-password" placeholder="stored; leave empty to keep"></label>
<small>Your own app from <a href="https://developer.spotify.com/dashboard" target="_blank">developer.spotify.com</a>
(Premium account). The secret is never shown again once saved.</small>
<label><span>Stream URL</span><input name="source.hls_url" type="url" placeholder="https://…/playlist.m3u8"></label>
<label><span>Autoplay stream on boot</span><input name="source.autoplay" type="checkbox"></label>
<label><span>Output gain (dB)</span><input name="source.gain_db" type="number" min="-60" max="12" step="0.5"></label>
@@ -77,15 +99,14 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
<!-- ===== PROJECT END ===== -->
<fieldset><legend>PTP</legend>
<button type="button" onclick="ptpPreset('riedel')">Riedel SIC defaults</button>
<button type="button" onclick="ptpPreset('aes67')">AES67 media profile defaults</button>
<button type="button" onclick="ptpPreset('riedel')">Riedel PTP defaults</button>
<button type="button" onclick="ptpPreset('aes67')">AES67 Media PTP defaults</button>
<label><span>Mode</span><select name="ptp.mode">
<option value="multicast">multicast</option><option value="hybrid">hybrid</option></select>
<small>hybrid: Delay_Req/Resp unicast</small></label>
<label><span>Role</span><select name="ptp.role">
<option value="slave">TimeReceiver only</option>
<option value="auto">Auto (TimeTransmitter if none)</option>
<option value="master">Preferred TimeTransmitter</option></select></label>
<option value="auto">Auto (TimeTransmitter if none)</option></select></label>
<label><span>Domain</span><input name="ptp.domain" type="number" min="0" max="127"></label>
<label><span>Priority 1</span><input name="ptp.priority1" type="number" min="0" max="255"></label>
<label><span>Priority 2</span><input name="ptp.priority2" type="number" min="0" max="255"></label>
@@ -101,7 +122,6 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
<option value="-4">-4 (16/s)</option><option value="-3">-3 (8/s)</option><option value="-2">-2 (4/s)</option>
<option value="-1">-1 (2/s)</option><option value="0">0 (1/s)</option><option value="1">1 (every 2 s)</option></select></label>
<label><span>DSCP (PTP)</span><input name="ptp.dscp" type="number" min="0" max="63"></label>
<label><span>HW timestamping</span><input name="ptp.hw_ts" type="checkbox"></label>
<small>Transport UDP/IPv4 224.0.1.129 (ports 319/320), delay mechanism E2E.</small>
</fieldset>
@@ -124,7 +144,7 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
<small>(Ch 1 + Ch 2) / 2 → 1-channel stream</small></label>
<label><span>Bit depth</span><select name="aes67.encoding"><option>L24</option><option>L16</option></select>
<small>Default L24</small></label>
<label><span>Sample rate</span><select name="aes67.rate"><option>48000</option><option>96000</option></select></label>
<label><span>Sample rate</span><select name="aes67.rate"><option>48000</option></select></label>
<label><span>Packet time</span><select name="aes67.ptime">
<option value="0.125">0.125 ms</option><option value="0.25">0.250 ms</option><option value="0.333">0.333 ms</option>
<option value="1">1.000 ms</option><option value="4">4.000 ms</option></select>
@@ -139,7 +159,8 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
<fieldset><legend>Network</legend>
<label><span>Hostname</span><input name="net.hostname"></label>
<label><span>VLAN split</span><input name="net.vlan" type="checkbox">
<!-- VLAN split: not implemented yet (phase 2); hidden until the firmware applies it. -->
<label hidden><span>VLAN split</span><input name="net.vlan" type="checkbox">
<small>off: one untagged interface for everything</small></label>
<p id="netlbl" hidden><b>AES67 interface (untagged)</b></p>
<label><span>DHCP</span><input name="net.dhcp" type="checkbox"></label>
@@ -179,9 +200,12 @@ e.g. curl -X POST http://p4-aes67.local/api/player/next
<button type="button" onclick="api('POST','/api/log/test').then(()=>msg.textContent='Test message sent.',()=>{})">Send test message</button>
</fieldset>
<div class="bar">
<button>Save</button>
<button type="button" onclick="load()">Revert</button>
<button type="button" onclick="confirm('Reboot device?')&&api('POST','/api/reboot')">Reboot</button>
<span id="msg"></span>
</div>
</form>
<fieldset><legend>SDP</legend>
@@ -207,7 +231,7 @@ const PROJECT = {
title: 'P4 AES67 Streamer',
def: {
source:{mode:'spotify',spotify_name:'P4 AES67',spotify_bitrate:'320',hls_url:'',autoplay:false,gain_db:0,
failover_delay_s:5,failover_on_pause:false},
failover_delay_s:5,failover_on_pause:false,spotify_client_id:'',spotify_client_secret:''},
aes67:{name:'P4 AES67'},
net:{hostname:'p4-aes67'}
},
@@ -215,6 +239,7 @@ const PROJECT = {
const m = f['source.mode'].value;
const sp = m === 'spotify' || m === 'auto', hl = m === 'hls' || m === 'auto';
f['source.spotify_name'].disabled = f['source.spotify_bitrate'].disabled = !sp;
f['source.spotify_client_id'].disabled = f['source.spotify_client_secret'].disabled = !sp;
f['source.hls_url'].disabled = !hl;
f['source.autoplay'].disabled = m !== 'hls';
f['source.failover_delay_s'].disabled = f['source.failover_on_pause'].disabled = m !== 'auto';
@@ -230,15 +255,27 @@ const PROJECT = {
async function ctl(cmd, body) {
try { showPlayer(await api('POST', '/api/player/' + cmd, body)); } catch {}
}
// Progress bar: follows the polled position, moves on locally while playing, seeks on release.
let np = null, npAt = 0, seekDrag = false;
const mmss = ms => `${Math.floor(ms/60000)}:${String(Math.floor(ms/1000)%60).padStart(2,'0')}`;
function showPos() {
const pos = document.getElementById('pos'), dur = np?.duration_ms;
pos.disabled = !(dur && np.can?.seek);
if (!seekDrag) {
const at = !dur ? 0 : np.state === 'playing' ? Math.min(np.position_ms + Date.now() - npAt, dur) : np.position_ms;
pos.max = dur || 0;
pos.value = at;
}
document.getElementById('postime').textContent = dur ? `${mmss(+pos.value)} / ${mmss(dur)}` : '';
}
setInterval(showPos, 500);
function showPlayer(p) {
if (!p || !p.state) return;
const t = s => s == null ? '' : `${Math.floor(s/60000)}:${String(Math.floor(s/1000)%60).padStart(2,'0')}`;
np = p; npAt = Date.now(); showPos();
document.getElementById('np').textContent =
`[${p.source}] ${p.state}: ${[p.artist, p.title].filter(Boolean).join(' – ') || '–'}` +
(p.duration_ms ? ` ${t(p.position_ms)} / ${t(p.duration_ms)}` : '');
`[${p.source}] ${p.state}: ${[p.artist, p.title].filter(Boolean).join(' – ') || '–'}`;
const v = document.getElementById('vol');
if (document.activeElement !== v) v.value = p.volume;
document.getElementById('force').value = p.forced || 'config';
}
/* ===== PROJECT END ===== */
@@ -246,7 +283,7 @@ function showPlayer(p) {
const CORE_DEF = {
// Intervals follow Riedel SIC AES67 defaults; role/priorities are the "fallback TimeTransmitter" setup.
ptp:{mode:'multicast',role:'auto',domain:0,priority1:250,priority2:250,log_sync:0,log_announce:1,
announce_timeout:3,log_delay_req:0,dscp:46,hw_ts:true},
announce_timeout:3,log_delay_req:0,dscp:46},
aes67:{name:'AES67',enabled:true,mcast:'239.69.1.10',port:5004,ttl:32,dscp:34,pt:96,encoding:'L24',
rate:'48000',channels:'2',ptime:'1',ssrc:0,clk_offset:0,mono_sum:false,discovery:'sap',session_id:1,session_ver:1},
net:{hostname:'aes67',vlan:false,web_on:'both',dhcp:true,ip:'',mask:'',gw:'',dns:''},
@@ -254,7 +291,7 @@ const CORE_DEF = {
log:{syslog:false,host:'',port:514,level:'info',facility:'16',format:'rfc5424'}
};
// Priority1 suggested when the role is changed in the UI (user can still edit it).
const ROLE_P1 = {auto:250, master:100};
const ROLE_P1 = {auto:250};
// PTP presets. riedel = Riedel Director defaults for a SIC AES67 card.
const PTP_PRESETS = {
riedel: {mode:'multicast', role:'slave', domain:0, priority1:128, priority2:126,
@@ -265,7 +302,7 @@ function ptpPreset(name) {
for (const [k, v] of Object.entries(PTP_PRESETS[name])) f['ptp.' + k].value = v;
toggle(); sdp(); msg.textContent = `Loaded ${name} PTP defaults – Save to apply.`;
}
const CLOCK_CLASS = {slave:255, auto:248, master:248};
const CLOCK_CLASS = {slave:255, auto:248};
const $ = id => document.getElementById(id);
const f = $('f'), sdpEl = $('sdp'), msg = $('msg');
@@ -317,6 +354,13 @@ function read() {
return out;
}
// With DHCP on, the greyed-out static fields show what DHCP gave us. Unticking DHCP leaves the values
// there (a starting point for static addressing) until they are edited.
function netLive() {
if (!f['net.dhcp'].checked || !st.ip) return;
for (const k of ['ip','mask','gw','dns']) f['net.' + k].value = st[k] ?? '';
}
function toggle() {
PROJECT.toggle?.(f);
const role = f['ptp.role'].value;
@@ -330,6 +374,7 @@ function toggle() {
}
// VLAN split: default route lives on the internet VLAN, so the AES67 side gets no gateway/DNS.
if (vlan) f['net.gw'].disabled = f['net.dns'].disabled = true;
netLive();
// RTP multicast must be 224.0.2.0 – 239.255.255.255 (same range Riedel Director enforces).
const m = f['aes67.mcast'], o = m.value.split('.').map(Number);
const ok = o.length === 4 && o.every(x => Number.isInteger(x) && x >= 0 && x <= 255) &&
@@ -385,7 +430,15 @@ async function save(e) {
const c = read();
c.aes67.session_ver = (Number(cfg.aes67?.session_ver) || 0) + 1; // SDP version bump per RFC 4566
await api('POST', '/api/config', c);
// A changed IP setup reboots the device: follow it to the new address.
const addr = n => n.dhcp ? 'dhcp' : [n.ip, n.mask, n.gw, n.dns].join('/');
const moved = addr(cfg.net || {}) !== addr(c.net);
cfg = c; fill(); msg.textContent = 'Saved.';
if (moved) {
const to = c.net.dhcp ? location.host : c.net.ip;
msg.textContent = `Rebooting with the new IP setup. Opening http://${to}/ in 20 s.`;
setTimeout(() => location.href = `http://${to}/`, 20000);
}
}
// PTP display follows the Riedel (Bolero/Artist) status layout, IEEE 1588-2019 terms.
@@ -406,7 +459,7 @@ function offsetBucket(ns) {
// Same brackets and colours as Riedel Bolero.
const [t, cls] = a < 100 ? ['< 100 ns','ok'] : a < 500 ? ['100-500 ns','ok'] : a < 1e3 ? ['500-1000 ns','warn']
: a < 1e4 ? ['1000-10000 ns','bad'] : ['> 10000 ns','bad'];
return {cls, text: `${t} (${n(ns)} ns)`};
return {cls, text: t};
}
function freqBucket(ppb) {
if (ppb == null) return '–';
@@ -416,6 +469,13 @@ function freqBucket(ppb) {
return `${t} (${n(ppb)} ppb)`;
}
const yn = v => v == null ? '–' : v ? 'Yes' : 'No';
// 93784 -> "1d 2h 3m 4s"; leading zero units left out.
function uptime(s) {
if (s == null) return '–';
const parts = [[Math.floor(s / 86400), 'd'], [Math.floor(s / 3600) % 24, 'h'], [Math.floor(s / 60) % 60, 'm'], [s % 60, 's']];
const i = parts.findIndex(([v]) => v > 0);
return parts.slice(i < 0 ? 3 : i).map(([v, u]) => v + u).join(' ');
}
function showPtp(p) {
if (!p) { table($('ptpmore'), {}); return table($('ptpstat'), {'PTP': 'no data'}); }
@@ -424,18 +484,21 @@ function showPtp(p) {
'PTP State': PTP_STATE[p.state] || p.state,
'Lock State': p.locked ? {cls:'ok', text:'Locked'} : {cls:'bad', text:'Unlocked'},
'TimeTransmitter': clockId(p.gm_id) + (gmSelf ? ' (this device)' : ''),
'Time Offset': gmSelf ? '–' : offsetBucket(p.offset_ns),
// Bracket from the mean |offset| over the last 2 min; the current value is in Details.
'Time Offset (2 min avg)': gmSelf ? '–' : offsetBucket(p.offset_avg_ns),
'Frequency Deviation': gmSelf ? '–' : freqBucket(p.freq_ppb),
'Network Delay': gmSelf ? '–' : `${n(p.path_delay_ns)} ± ${n(p.path_delay_sd_ns)} ns`,
'Hops': p.steps_removed,
'Time/Frequency Traceable': `${yn(p.gm_time_traceable)} / ${yn(p.gm_freq_traceable)}`,
'Version': p.version ?? 2,
'Own Clock Class': p.own_class
});
table($('ptpmore'), {
'This clock': clockId(p.clock_id),
// Same colours as the average's brackets, for the current value.
'Time offset now': gmSelf || p.offset_ns == null ? '–' : {cls: offsetBucket(p.offset_ns).cls, text: `${n(p.offset_ns)} ns`},
'TT class / accuracy': `${p.gm_class ?? '–'} / 0x${(p.gm_accuracy ?? 0).toString(16).toUpperCase()}`,
'TT priority 1 / 2': `${p.gm_p1 ?? '–'} / ${p.gm_p2 ?? '–'}`,
'Hops': p.steps_removed ?? '–',
'Time/Frequency Traceable': `${yn(p.gm_time_traceable)} / ${yn(p.gm_freq_traceable)}`,
'Version': p.version ?? 2,
'Own Clock Class': p.own_class ?? '–',
// Measured over the last p.window Sync messages (RX as receiver, TX as transmitter).
'Sync interval avg': `${n(p.sync_avg_ms, 3)} ms (min ${n(p.sync_min_ms, 3)} / max ${n(p.sync_max_ms, 3)}, jitter ${n(p.sync_jitter_us, 1)} µs)`,
'Announce interval avg': n(p.announce_avg_ms, 1) + ' ms',
@@ -469,10 +532,11 @@ async function poll() {
...(st.power ? {'Power source': st.power} : {}),
...PROJECT.statusRows?.(st),
'AES67 TX': `${st.tx_packets} pkts, ${st.underruns} underruns`,
'Uptime': st.uptime_s + ' s', 'Heap / PSRAM free': `${st.heap_free} / ${st.psram_free}`,
'Uptime': uptime(st.uptime_s), 'Heap / PSRAM free': `${st.heap_free} / ${st.psram_free}`,
...temps(st.temps)
});
showPtp(st.ptp);
netLive();
sdp();
} catch { table($('status'), {'Device': 'offline'}); showPtp(null); }
}
@@ -489,7 +553,7 @@ async function otaInfo() {
try {
const o = await api('GET', '/api/ota');
table($('fwinfo'), {
'Version': o.version, 'Project': o.project, 'Built': o.build_date, 'ESP-IDF': o.idf,
'Version': o.version,
'Running slot': o.running, 'Previous slot': o.previous ? `${o.previous} (${o.previous_version ?? '?'})` : '–',
'State': o.pending_verify ? {cls:'warn', text:'New firmware on trial – confirm or roll back'} : 'Confirmed'
});