GCC Code Coverage Report


Directory: ./
File: mediaoutput/AES67Manager.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 12 16 75.0%
Functions: 6 6 100.0%
Branches: 11 18 61.1%

Line Branch Exec Source
1 #pragma once
2 /*
3 * This file is part of the Falcon Player (FPP) and is Copyright (C)
4 * 2013-2025 by the Falcon Player Developers.
5 *
6 * The Falcon Player (FPP) is free software, and is covered under
7 * multiple Open Source licenses. Please see the included 'LICENSES'
8 * file for descriptions of what files are covered by each license.
9 *
10 * This source file is covered under the LGPL v2.1 as described in the
11 * included LICENSE.LGPL file.
12 */
13
14 // AES67Manager — GStreamer-based AES67 audio-over-IP send/receive
15 //
16 // Replaces the previous PipeWire RTP module approach with GStreamer pipelines
17 // and uses ptp4l (linuxptp) for IEEE 1588 PTP clock synchronization on the
18 // network, achieving true AES67 compliance.
19 //
20 // Features:
21 // - Send: pipewiresrc → audioconvert → rtpL24pay → udpsink
22 // - Receive: udpsrc → rtpjitterbuffer → rtpL24depay → audioconvert → pipewiresink
23 // - ptp4l for IEEE 1588 PTP on the network (grandmaster or follower via BMCA)
24 // - Built-in SAP announcer (replaces external fpp_aes67_sap Python daemon)
25 // - SAP receiver for inbound stream discovery
26 // - Config format: same pipewire-aes67-instances.json (backward-compatible)
27
28 #if __has_include(<gst/gst.h>)
29 #define HAS_AES67_GSTREAMER
30
31 #include <gst/gst.h>
32
33 #include "fpphttp_types.h"
34
35 #include <atomic>
36 #include <chrono>
37 #include <cstdint>
38 #include <functional>
39 #include <map>
40 #include <mutex>
41 #include <string>
42 #include <thread>
43 #include <vector>
44
45 // ──────────────────────────────────────────────────────────────────────────────
46 // AES67 Protocol Constants (mirror fpp_aes67_common.py)
47 // ──────────────────────────────────────────────────────────────────────────────
48 namespace AES67 {
49
50 constexpr int RTP_PAYLOAD_TYPE = 96;
51 constexpr int AUDIO_RATE = 48000;
52 constexpr int AUDIO_RTP_TTL = 4;
53 // 1ms is mandatory for every AES67 device and is the only packet time Dante
54 // will transmit, so it is the interoperable default. It is also the only one
55 // that fits above stereo (see MaxPtimeForChannels), and measured better than
56 // 4ms here rather than worse: over 180k packets, worst-case transmission
57 // lateness 0.235ms against 0.64ms at 4ms ptime, because smaller buffers give
58 // the pacing thread less to slip. Existing configs keep whatever they have --
59 // this only applies where no ptime was ever stored.
60 constexpr int DEFAULT_PTIME_MS = 1; // 1ms packet time
61 constexpr int DEFAULT_PORT = 5004;
62 constexpr int DEFAULT_CHANNELS = 2;
63
64 // Warning raised when a pipeline will not start. WarningHolder::RemoveWarning()
65 // matches on the id *and* the exact message text, and these warnings have no
66 // timeout, so the strings have to be shared between the code that raises one
67 // and the code that retracts it -- otherwise a warning outlives the problem it
68 // describes and the banner only clears on an fppd restart.
69 constexpr int WARNING_ID_PIPELINE = 44;
70 constexpr const char* WARNING_SEND_FAILED = "AES67: audio send stream failed to start";
71 constexpr const char* WARNING_RECV_FAILED = "AES67: audio receive stream failed to start";
72
73 // Warning slot for the PTP daemon itself, kept separate from the pipeline one
74 // so a clock problem and a stream problem do not overwrite each other.
75 constexpr int WARNING_ID_PTP = 45;
76 constexpr const char* WARNING_PTP_NO_LOCK =
77 "AES67: PTP did not reach a usable lock before the streams started — "
78 "audio may be mistimed until the clock settles";
79
80 // The ways PTP can fail to come up at all. Every one of these describes
81 // something the user can fix without restarting fppd -- install linuxptp, free
82 // the interface, make the config path writable -- so every one of them has to
83 // be retractable, or the banner goes on naming a problem that has already been
84 // solved. InitPTP() retracts all four once ptp4l is confirmed running and
85 // ShutdownPTP() retracts them on the way down; a still-failing start raises
86 // them again.
87 constexpr const char* WARNING_PTP_NOT_INSTALLED =
88 "AES67: ptp4l not found — install the linuxptp package";
89 constexpr const char* WARNING_PTP_CONF_WRITE =
90 "AES67: could not write PTP configuration file";
91 constexpr const char* WARNING_PTP_SPAWN_FAILED =
92 "AES67: could not start the ptp4l clock-sync process";
93 constexpr const char* WARNING_PTP_START_FAILED =
94 "AES67: PTP clock sync (ptp4l) could not start on the configured interface";
95
96 // The PTP interface has no hardware clock, so ptp4l runs free_running and
97 // does not follow the grandmaster it has selected (see WritePtpConf()).
98 // Polled: re-raised with a timeout on each watchdog pass while it holds,
99 // removed once it does not -- this box becomes the grandmaster, the
100 // grandmaster goes, or PTP stops.
101 constexpr const char* WARNING_PTP_FREE_RUNNING =
102 "AES67: the PTP interface has no hardware clock, so this player is not synced "
103 "to the PTP grandmaster (following it would reset the system clock) — "
104 "streams are timed from NTP instead";
105
106 // AES67 allows up to 8 channels per stream and FPP now carries all of them.
107 //
108 // This sat at 2 for a while because anything above stereo produced "Internal
109 // data stream error" and not one packet, which read as multichannel being
110 // unimplemented. It was one missing caps field: above stereo GStreamer needs
111 // an explicit channel-mask or negotiation fails (see ChannelMaskFor). The
112 // PipeWire side was already channel-aware -- the delay chain emits one delay
113 // node per channel with the right positions at any width.
114 //
115 // Verified end to end at 8 channels, 1ms ptime, with an 8-channel source:
116 // uniform 1152-byte payload, 1000 packets/s, all eight channels carrying
117 // audio, media clock within 0.1 ppm of PTP, jitter inside the 1ms AES67
118 // recommends.
119 //
120 // The stream's channel count and its output group's channel count are
121 // separate settings and both have to be set -- the group builds the delay
122 // chain that feeds this stream.
123 constexpr int MAX_SUPPORTED_CHANNELS = 8;
124
125 // Above this channel count pipewiresrc gets always-copy=true regardless of the
126 // sourceBufferCopy setting.
127 //
128 // Zero-copy hands out PipeWire's own buffers, and one is only returned to the
129 // pool once everything downstream has dropped its reference. audiobuffersplit
130 // fans a graph quantum into ~21 one-millisecond buffers, and past stereo it
131 // holds them long enough that the source misses cycles: buffers reach udpsink
132 // already past their PTS, so sync=true cannot pace what is already late and
133 // sends back-to-back to catch up. Measured, same box, same audio:
134 //
135 // channels payload back-to-back past the 1ms AES67 recommends
136 // 2 288B clean 0.0%
137 // 4 576B clean 0.0%
138 // 6 864B 7% 5.6%
139 // 8 1152B 32-50% 90.4%
140 //
141 // A deeper pool does not substitute: sourceMinBuffers=64 on its own still left
142 // 64% back-to-back. The copy does -- at 8 channels it restores clean pacing,
143 // jitter inside the 1ms recommendation, and the full presentation lead.
144 //
145 // Stereo keeps the zero-copy path, which is what the long soaks and the
146 // hardware testing to date actually ran. The copy is ~1.5MB/s at 8 channels.
147 constexpr int MULTICHANNEL_NEEDS_BUFFER_COPY = 2;
148 constexpr int DEFAULT_LATENCY_MS = 10;
149
150 // DSCP codepoints (AES67-2018 / AES-R16 QoS recommendations)
151 constexpr int AUDIO_DSCP = 34; // AF41 -- RTP audio (udpsink qos-dscp)
152 constexpr int PTP_DSCP = 46; // EF -- PTP event/general messages (ptp4l dscp_event/dscp_general)
153
154 // SCHED_FIFO priority for the thread that paces RTP packets onto the wire.
155 //
156 // Left at SCHED_OTHER nice 0 this thread misses a timeslice every few
157 // thousand packets, and each miss is a packet transmitted up to a full ptime
158 // late. Measured over 60k packets at 4ms ptime: worst-case lateness 8.6ms
159 // and 0.08% of packets past the 1ms AES67 recommends, versus 0.64ms worst
160 // case and none past 1ms once the thread is SCHED_FIFO. The load average
161 // was 0.24 on 4 cores in both runs -- this is wakeup latency, not
162 // contention, so no amount of spare CPU fixes it.
163 //
164 // 80 sits deliberately below the 88 PipeWire gives its data-loop: if both
165 // are ever runnable at once the audio graph must win, because starving it
166 // underruns every stream on the box, not just this one. Kernel RT
167 // throttling (sched_rt_runtime_us, 95% by default) is the backstop.
168 constexpr int SINK_RT_PRIORITY = 80;
169
170 // How much audio FlushSendPipelines() discards at a track boundary. Zero:
171 // it discards nothing, and the mechanism is kept only so this can be raised
172 // if some source ever does need it.
173 //
174 // The flush existed to throw away "stale audio queued between the old track
175 // stopping and the new one starting", but pipewiresrc is a live source -- it
176 // delivers the graph in real time and holds no backlog to discard. There was
177 // never anything stale there, so the drop only ever cut a hole in a stream
178 // that was already continuous, and everything downstream was machinery built
179 // to survive that hole: the drift probe reported it as a "source gap", the
180 // silence fill patched the timeline over it, and the sink queue had to be
181 // deep enough to cover it or a receiver heard the wire stop.
182 //
183 // Measured across track transitions, same box, same audio:
184 //
185 // flush source gaps worst wire gap worst tx jitter
186 // 213ms 213-232ms 157.7ms 156.7ms
187 // 50ms 23.2ms 6.13ms 5.18ms
188 // 0ms none (54 1.14ms 0.172ms
189 // transitions)
190 //
191 // At zero a transition is indistinguishable from steady state and clears the
192 // 1ms AES67 recommends, not just the 17ms it requires. It is also the only
193 // setting where AES67 carries exactly what the local sound card carries, so
194 // any artefact at a boundary is FPP's own audio rather than something this
195 // path invented.
196 constexpr int SOURCE_FLUSH_MS = 0;
197
198 // PTP (IEEE 1588) profile defaults
199 constexpr int DEFAULT_PTP_DOMAIN = 0;
200
201 // BMCA priority1 values selected by the "ptpRole" setting. Most professional
202 // AES67 gear ships priority1=128, so an FPP box left at 128 ties on priority
203 // and wins on clock identity (lowest MAC) -- silently hijacking the clock
204 // domain of a console or DSP. See issue #2848.
205 constexpr int PTP_PRIORITY_PREFER_MASTER = 127; // deliberately beat the usual 128
206 constexpr int PTP_PRIORITY_AUTO = 248; // yield to real gear; still GM when alone
207
208 // How long the SAP announcer re-checks the grandmaster every second after
209 // startup, to catch BMCA settling rather than waiting a whole announce cycle.
210 constexpr int PTP_CONVERGENCE_WINDOW_S = 60;
211
212 // TTL for the cached pmc query result. /aes67/status is HTTP-facing and each
213 // query forks a pmc process, so repeated hits must not fork per request.
214 constexpr int PTP_QUERY_CACHE_MS = 1000;
215
216 // ─── Waiting for the PTP clock before anchoring anything to it ──────────────
217 //
218 // A send pipeline is anchored to PTP time exactly once, when it is built:
219 // rtpL24pay latches "timestamp-offset" on the segment, so the RTP timeline
220 // cannot be re-anchored in place afterwards (setting it from a probe on the
221 // first buffer was measured to do nothing at all). That makes it a hard
222 // requirement that the clock read at build time is the clock the stream will
223 // keep running on.
224 //
225 // On a cold boot it was not. ptp4l was launched, confirmed alive 500ms later,
226 // and PTP declared "initialized" -- and GetOrCreateMediaClock() only proves
227 // the PHC can be *read*, which says nothing about whether it has been
228 // disciplined. As a follower it has not: the PHC free-runs from whatever the
229 // NIC came up with, and ptp4l steps it to grandmaster time seconds later, on
230 // entering SLAVE. Everything anchored in between is anchored to a time base
231 // that is about to jump.
232 //
233 // Reported on issue #2848 from a Pi 5 into a Yamaha MRX7-D, with the whole
234 // sequence in the log:
235 //
236 // 11:34:37.306 PTP initialized -- media clock using PHC /dev/ptp0
237 // 11:34:37.340 stream 1 RTP timeline anchored (timestamp-offset 3260165294)
238 // 11:34:39 selected best master clock 001dc1.fffe.149b4a
239 // 11:34:40 UNCALIBRATED -> SLAVE, then a first servo sample of
240 // rms 1265019998642539520 -- the pre-step offset
241 // 11:34:41 rms 1030ns <- the PHC has now moved under the anchor
242 //
243 // The grandmaster's epoch was ~6.81 hours ahead of the Pi's PHC, so the four
244 // streams declared a playout time 24,472 seconds in the past. They were not
245 // silent, which is what made it hard to see: aes67_verify measured 40.8
246 // packets/s in correctly-spaced bursts separated by 6.5 second holes, a media
247 // clock of 1857.83 samples/s (-961,298 ppm), and Dante red -- while
248 // /aes67/status still reported 4/4 pipelines running and PTP synced. The
249 // watchdog rebuilt the stack 90 seconds later and everything was correct on
250 // the first try, because by then the PHC was already disciplined.
251 //
252 // So: wait for the clock to settle before building anything on it.
253 //
254 // SLAVE alone is not the signal. The log above shows the step arriving
255 // *after* the transition, so a wait that stopped at SLAVE would still race it.
256 // The offset from master is the signal, and reaching it means the step has
257 // already happened.
258 constexpr int64_t PTP_LOCK_OFFSET_NS = 1000000; // 1ms
259
260 // How long InitPTP() will wait for that. This blocks fppd's startup, so it is
261 // deliberately short: it only runs on a box with AES67 enabled *and* PTP on,
262 // and the measured lock on the reference hardware is 3.2s to SLAVE and ~4s to
263 // microsecond offsets, which this covers with margin. Timing out is not a
264 // failure path -- the streams still start, and the step detector below picks
265 // up a clock that locks later (a grandmaster that boots slower than the Pi is
266 // an ordinary thing at a commissioning). Set "ptpLockWaitMs" to 0 in
267 // pipewire-aes67-instances.json to skip the wait entirely.
268 constexpr int PTP_LOCK_WAIT_MS = 5000;
269
270 // Poll cadence for that wait. Each poll forks two pmc queries, so 250ms is
271 // 40 forks across the whole 5s cap in the worst case, and none at all once the
272 // clock settles. PTP_QUERY_CACHE_MS does not help here -- the wait needs the
273 // live answer, not a second-old one -- so it queries with force.
274 constexpr int PTP_LOCK_POLL_MS = 250;
275
276 // The step detector, for a clock that moves *after* the pipelines were built:
277 // a grandmaster that appears late, or a BMCA changeover to a device on a
278 // different epoch. Both leave the anchor as wrong as the cold-boot race did,
279 // and neither can be fixed in place -- so the watchdog rebuilds.
280 //
281 // Measured as the change in (PTP - CLOCK_MONOTONIC) between two watchdog
282 // checks, which is the quantity the anchor actually depends on, so the test is
283 // "did the anchor become wrong" rather than a proxy for it. 100ms sits in a
284 // wide gap. Below it: a free-running PHC against the Pi's own crystal, which
285 // is the worst case since a disciplined one moves less -- measured on a Pi 5,
286 // -1.581ms across a 30 second check interval (52.7ppm, in line with the ~56ppm
287 // the drift loop corrects), so a 63x margin. Above it: ptp4l is configured to
288 // step anything at or above 1 second and slew everything below, so every step
289 // it can make trips this.
290 constexpr int64_t PTP_STEP_DETECT_NS = 100000000; // 100ms
291
292 // The send path's source-gap and silence-fill lines are per buffer, and a
293 // source starved of CPU gaps on nearly every one: ~85 lines a second on a
294 // PocketBeagle 2, a 260MB fppd.log in a day, and log writes competing for the
295 // CPU whose shortage caused the gaps. The first GAP_LOG_IN_FULL of each kind
296 // are logged in full, which is what the onset diagnostics read; after that
297 // they are totalled and logged once per GAP_LOG_SUMMARY_MS.
298 constexpr unsigned GAP_LOG_IN_FULL = 20;
299 constexpr int GAP_LOG_SUMMARY_MS = 10000;
300
301 // PTP Announce listener. No PTP management response carries the
302 // grandmaster's IP address -- TIME_STATUS_NP names it only by clock identity
303 // -- so the address is read off the source of the Announce messages ptp4l is
304 // already following, on the same multicast group and general-message port.
305 constexpr const char* PTP_MCAST_ADDRESS = "224.0.1.129";
306 constexpr int PTP_GENERAL_PORT = 320;
307
308 // An Announce arrives every 2s (logAnnounceInterval 1) and ptp4l declares the
309 // master gone after 3 missed ones, so an address older than this is no longer
310 // the live path to the clock and must not be reported as if it were.
311 constexpr int PTP_ANNOUNCE_STALE_MS = 10000;
312
313 // Anything on the LAN can send Announce and SAP packets, and each one with a
314 // new identity used to add an entry that only aged out minutes later -- a
315 // flood of made-up ones grew both maps until the board ran out of memory.
316 // A real domain has a handful of masters and a real network a few dozen
317 // streams; past these caps the entry heard from longest ago makes room.
318 constexpr size_t MAX_PTP_ANNOUNCE_SOURCES = 32;
319 constexpr size_t MAX_SAP_DISCOVERED = 256;
320 // SDP fields kept from an announcement, which can be up to a datagram long.
321 constexpr size_t MAX_SAP_FIELD_LEN = 256;
322
323 constexpr const char* DEFAULT_MULTICAST_IP = "239.69.0.1";
324 constexpr const char* AUDIO_FORMAT = "S24BE";
325 constexpr const char* SAP_MCAST_ADDRESS = "239.255.255.255";
326 constexpr int SAP_PORT = 9875;
327 constexpr int SAP_VERSION = 1;
328 constexpr int SAP_ANNOUNCE_INTERVAL_S = 30;
329 constexpr int SAP_TTL = 255;
330
331 // Largest RTP packet we will emit. AES67 forbids IP fragmentation, so one
332 // ptime of audio has to fit in a single datagram: 1500 (Ethernet MTU) - 20
333 // (IPv4) - 8 (UDP) = 1472 bytes of RTP. 1440 keeps headroom for the RTP
334 // header and for a VLAN tag or tunnel on the path. GStreamer's payloader
335 // defaults to 1400 and SPLITS anything larger, which silently breaks the
336 // min-ptime=max-ptime contract and emits packets that do not match the
337 // a=ptime we advertise -- so we always set this explicitly.
338 constexpr int MAX_RTP_PACKET_BYTES = 1440;
339
340 // L24 is 3 bytes per sample per channel.
341 206 inline int L24PayloadBytes(int ptime, int channels) {
342 206 return ptime * (AUDIO_RATE / 1000) * channels * 3;
343 }
344
345 // GStreamer channel mask for an AES67 channel count.
346 //
347 // Above stereo, caps without a channel-mask do not negotiate: audioconvert
348 // warns "Upstream caps contain no channel mask" and pipewiresrc's streaming
349 // thread stops with not-negotiated (-4), surfacing only as "Internal data
350 // stream error" on the bus and not one packet on the wire. Mono and stereo
351 // carry an implicit layout, which is why stereo worked and nothing above it
352 // did -- and why this looked like multichannel being unimplemented rather
353 // than one missing caps field.
354 //
355 // Bits are GstAudioChannelPosition values, and the layouts match what
356 // FPPINIT_Audio emits for the delay chain (FL FR / FL FR RL RR / 5.1 / 7.1).
357 185 inline guint64 ChannelMaskFor(int channels) {
358
2/6
✗ Branch 0 not taken.
✓ Branch 1 taken 177 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 8 times.
✗ Branch 5 not taken.
185 switch (channels) {
359 ✗ case 1: return 0x1; // FL (mono is positionless, but harmless)
360 177 case 2: return 0x3; // FL FR
361 ✗ case 4: return 0x33; // FL FR RL RR
362 ✗ case 6: return 0x3F; // FL FR FC LFE RL RR
363 8 case 8: return 0xC3F; // FL FR FC LFE RL RR SL SR
364 ✗ default: return 0; // unknown: omit the field
365 }
366 }
367
368 // Valid AES67 ptimes
369
3/4
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 200 times.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
203 inline bool IsValidPtime(int ptime) { return ptime == 1 || ptime == 4; }
370
371 // The largest valid ptime whose payload still fits in one datagram at this
372 // channel count. At 8 channels, 4ms of L24 is 4608 bytes -- over three
373 // times the limit -- so anything above stereo is 1ms only:
374 //
375 // ch 1ms 4ms
376 // 2 288 1152
377 // 4 576 2304 (too big)
378 // 6 864 3456 (too big)
379 // 8 1152 4608 (too big)
380 //
381 // 1ms is also the packet time Dante requires when receiving an AES67 flow,
382 // so it is the safe choice for interoperability as well as for MTU.
383 203 inline int MaxPtimeForChannels(int channels) {
384
2/2
✓ Branch 0 taken 195 times.
✓ Branch 1 taken 8 times.
203 return (L24PayloadBytes(4, channels) + 12 <= MAX_RTP_PACKET_BYTES) ? 4 : 1;
385 }
386
387 // Channel position names for SDP
388 const char* GetSDPChannelNames(int channels);
389
390 } // namespace AES67
391
392 // ──────────────────────────────────────────────────────────────────────────────
393 // Instance configuration — mirrors the JSON schema
394 // ──────────────────────────────────────────────────────────────────────────────
395 struct AES67Instance {
396 int id = 0;
397 std::string name;
398 bool enabled = true;
399 std::string mode = "send"; // "send" | "receive" | "both"
400 std::string multicastIP = AES67::DEFAULT_MULTICAST_IP;
401 int port = AES67::DEFAULT_PORT;
402 int channels = AES67::DEFAULT_CHANNELS;
403 std::string interface; // network interface (e.g., "eth0")
404 std::string sessionName;
405 int latency = AES67::DEFAULT_LATENCY_MS;
406 bool sapEnabled = true;
407 int ptime = AES67::DEFAULT_PTIME_MS;
408 };
409
410 struct AES67Config {
411 std::vector<AES67Instance> instances;
412 bool ptpEnabled = true;
413 std::string ptpInterface = "eth0";
414 int ptpDomain = AES67::DEFAULT_PTP_DOMAIN;
415
416 // BMCA participation:
417 // "auto" (default) -- priority1 248: still becomes grandmaster when
418 // it is the only clock on the domain, but yields
419 // to gear that wants the role.
420 // "follower" -- ptp4l slaveOnly: never becomes grandmaster.
421 // "master" -- priority1 127: prefer to win the election.
422 std::string ptpRole = "auto";
423
424 // How long InitPTP() waits for ptp4l to reach a settled clock before the
425 // send pipelines are anchored to it. See AES67::PTP_LOCK_WAIT_MS for why
426 // the wait exists and why it is short; 0 skips it, which restores the
427 // pre-#2848 behaviour and is only useful for reproducing that failure.
428 int ptpLockWaitMs = AES67::PTP_LOCK_WAIT_MS;
429
430 // Hold a sender idle until something in the audio graph actually feeds it.
431 //
432 // A send instance is a PipeWire *sink*: its pipewiresrc is created with
433 // node.autoconnect=false, so nothing links into it unless an Audio Output
434 // Group member names it as node.target. With nothing linked the pipeline
435 // cannot preroll, and gst_element_set_state() sits there for 30 seconds
436 // before returning FAILURE -- per instance, on every Apply. That is the
437 // chicken and egg a new instance walks straight into: it cannot be added
438 // to a group until it has been saved, and saving it costs half a minute
439 // of dead UI and a "stream failed to start" warning for a stream the user
440 // has not finished configuring yet.
441 //
442 // So when nothing feeds it, do not start it at all: the instance stays
443 // configured, ApplyConfig() returns promptly, GetStatus() reports it as
444 // waiting rather than failed, and the next apply -- which the Audio Output
445 // Groups page performs anyway, by restarting the stack -- starts it for
446 // real. See GraphFeedsSendNode().
447 //
448 // Set false in pipewire-aes67-instances.json for a graph FPP did not
449 // generate (a hand-written PipeWire conf, or nodes linked by hand with
450 // pw-link), where the group config cannot answer the question.
451 bool requireGroupSource = true;
452
453 // Diagnostic switches for the AES67 send path. Both default on; set
454 // either to false in pipewire-aes67-instances.json and hit Apply to take
455 // that change out of the pipeline without rebuilding, which is what makes
456 // a sender problem bisectable against real receiver hardware.
457 //
458 // ptpMediaClock -- drive the pipeline from PTP time and derive the RTP
459 // timestamps from it (AES67 "a=mediaclk:direct=0").
460 // sourcePacing -- ask PipeWire for a packet-sized quantum so RTP leaves
461 // evenly instead of one graph quantum at a time.
462 bool ptpMediaClock = true;
463 // Default OFF, and do not turn it on without solving what follows.
464 //
465 // It does fix the transmit cadence -- no gaps over 8ms in a 500-packet
466 // capture, and a Dante receiver's subscription state goes green -- but the
467 // audio is severely distorted, on both a 44100 and a genuine 48000 graph
468 // (confirmed on Yamaha MRX7-D hardware, issue #2848). The fractional
469 // quantum theory (192/48000 being 176.4 samples at 44100) is therefore
470 // wrong: it distorts just as badly where the request divides exactly.
471 //
472 // The cause is still unknown. It is not packet loss or timeline damage:
473 // sequence is unbroken, timestamp increments are exact, and the payload is
474 // statistically normal music with no splices at packet boundaries. The
475 // corruption is inside the packets, which is why no packet-level metric
476 // catches it.
477 //
478 // Note the priority this deserves: the bursty default path plays cleanly on
479 // real hardware even at the MRX7-D's minimum 0.25ms receive latency, so the
480 // cadence this would fix is not currently blocking anything.
481 //
482 // Prefer sinkPacing below, which fixes the same cadence without touching
483 // the graph and measurably does not distort. The distortion this one
484 // causes is now measurable too -- scripts/aes67_verify decodes the RTP
485 // payload and correlates it against the source file, which is the check
486 // that was missing when the note above was written.
487 bool sourcePacing = false;
488
489 // Pace the packets at the sink instead of at the source.
490 //
491 // The default path bursts: pipewiresrc hands over one graph quantum at a
492 // time and udpsink (sync=false) puts the whole lot on the wire in
493 // microseconds. Measured on a 1024-sample/44100 graph that is 5.8 packets
494 // back-to-back every 23.22ms -- 83% of packets arrive under 1ms after the
495 // one before, then nothing for 23ms.
496 //
497 // Which receivers that breaks depends entirely on how they clock playout.
498 // Hardware that places samples by RTP timestamp against its own PTP time
499 // does not care when a packet arrived, only that it arrived before its
500 // deadline -- which is why a Yamaha MRX7-D plays this cleanly even at
501 // 0.25ms. Software monitors generally play out by arrival into a small
502 // jitter buffer, so a 23ms silence underruns them every quantum and the
503 // audio fragments. Both reports on issue #2848 are the same defect seen
504 // from those two sides.
505 //
506 // sourcePacing fixes the cadence by shrinking the quantum, but it shrinks
507 // it for the whole graph -- the sound card included -- and the audio comes
508 // out distorted. This does not touch the graph: the queue below gives the
509 // sink its own thread, so it can wait for each packet's running time
510 // without the backpressure reaching the live source. That backpressure is
511 // what cost ~36% of the stream the last time sync=true was tried without a
512 // queue in between.
513 //
514 // sinkPacingMs is how long each packet is held back so that it is still in
515 // the future when the sink gets it. It must exceed one graph quantum
516 // (23.22ms at 1024/44100) or every buffer arrives late and goes out
517 // immediately, which is the burst all over again. 40ms leaves real margin
518 // on top of that on purpose: too small a value does not fail loudly, it
519 // silently reverts to bursting, which is expensive to diagnose. It costs
520 // sender latency, but the receiver no longer has to absorb the burst as
521 // link offset.
522 //
523 // Measured on a 1024/44100 graph, 4ms ptime, against the source audio:
524 //
525 // default path sinkPacing
526 // median gap 0.028ms 3.999ms
527 // packets per burst 5.8 1.00
528 // back-to-back 83% 0.0%
529 // content vs source 0.995 correlation 1.000 correlation
530 //
531 // Unlike sourcePacing it does not touch the graph, so it does not distort.
532 //
533 // It is NOT yet a fix on its own, and default OFF for a concrete reason:
534 // the queue drains. The sink releases packets on the PTP clock while the
535 // audio arrives on the sound card crystal, and on this hardware those are
536 // 56ppm apart (see adaptiveResample). Starting from a 40-60ms queue that
537 // is 12-18 minutes to empty, which matches what was measured: cadence held
538 // at exactly 4.000ms and 250.2 packets/s for ~15 minutes, then the queue
539 // touched 0 and in that same instant the median gap went to 0.031ms, 60%
540 // of packets went back-to-back and the rate fell to 187.6/s. It does not
541 // recover -- with nothing buffered every packet arrives past its send time
542 // and udpsink dumps them all immediately.
543 //
544 // So sink pacing is correct but not self-sufficient: it needs the audio
545 // rate locked to the PTP clock, i.e. a working adaptiveResample, or the
546 // queue empties and it fails worse than not pacing at all. Raising
547 // sinkPacingMs only buys time proportionally; it does not fix a systematic
548 // rate difference.
549 //
550 // Verified with scripts/aes67_verify, not yet against Dante or Yamaha
551 // hardware.
552 // Default ON since 2026-09: this is the validated configuration, proven on
553 // a Pi 5 against a Yamaha MRX7-D / Brooklyn II grandmaster (2.5h and 5h50m
554 // continuous, follower mode, Dante Controller green) as well as a 4h soak
555 // here. The four are not independent -- see the incoherence warnings in
556 // ParseConfig -- so they move together. Only AES67 send pipelines are
557 // affected; a box with no AES67 instance sees no change.
558 bool sinkPacing = true;
559 int sinkPacingMs = 40;
560
561 // Reconcile the audio clock with the PTP clock by inserting or dropping
562 // samples, instead of by varying a resampler's rate.
563 //
564 // The drift is a fixed ~56ppm between the sound card's crystal and the
565 // NIC's PHC (see adaptiveResample), and both variable-rate elements that
566 // could correct it have been measured and rejected -- "speed" and "pitch"
567 // each accept a rate property and neither applies it to a live stream.
568 //
569 // "audiorate" attacks it from the other side. It does not resample: it
570 // compares each buffer's timestamp against the sample count it has already
571 // emitted and inserts or drops samples to make the two agree. Since
572 // pipewiresrc timestamps buffers on the pipeline clock (the PHC) while the
573 // sample count comes from the card, that difference IS the drift, so the
574 // correction needs no control loop, no gains and no dead time -- the thing
575 // that made the previous attempt oscillate.
576 //
577 // It also settles the actuation question directly: "add" and "drop" are
578 // readable sample counters, so whether it is doing anything is a fact
579 // rather than an inference from a property read-back. At 56ppm expect
580 // ~2.7 samples/s of correction.
581 //
582 // rateMatchToleranceNs is how far the two may diverge before it acts. 0
583 // corrects continuously; the element's own default of 40ms lets the error
584 // build and then dumps a 40ms correction, which is plainly audible.
585 //
586 // MEASURED, AND IT DOES NOT WORK. Keep it default OFF. audiorate is the
587 // third rejected actuator, after "speed" and "pitch", and it fails
588 // differently from both -- it actuates, but wrongly, and then unrecoverably:
589 //
590 // - It over-corrects by more than an order of magnitude. Steady state it
591 // inserted ~40 samples/s (833ppm) where 2.7 samples/s (56ppm) was
592 // needed. It is reconciling per-buffer timestamp rounding, not drift,
593 // and no tolerance from 0 to 5ms changed that.
594 // - After ~11 minutes it enters permanent runaway, inserting ~12,000
595 // samples/s -- a quarter of the stream becomes fabricated silence, and
596 // it never recovers. Reproduced twice, at 10-12 and 11 minutes, on an
597 // otherwise healthy system. The shape fits a single forward jump in
598 // the timeline leaving a deficit it then chases forever.
599 //
600 // What this experiment DID establish, and the reason the switch is kept:
601 // with the rate corrected, sinkPacing's queue stops draining. Over 28
602 // minutes the cadence held at 4.00ms with uniform 1152-byte payloads and
603 // 250.0 packets/s, and the queue oscillated 56-80ms with no downward trend,
604 // against a collapse at ~15 minutes without it. So "correct the sample
605 // rate, then pace at the sink" is the right architecture; what is missing
606 // is only a correct rate corrector.
607 //
608 // That corrector needs to (a) apply a slow, near-constant ~56ppm
609 // correction rather than tracking per-buffer jitter, (b) preserve exact
610 // ptime blocking, and (c) reset rather than accumulate across a timeline
611 // discontinuity. No stock GStreamer element on the Pi image does all
612 // three, so it likely has to be written -- a fractional-delay resampler
613 // with its own read pointer, which keeps every output buffer exactly one
614 // packet long while consuming slightly more or fewer input samples.
615 bool rateMatch = false;
616 guint64 rateMatchToleranceNs = 0;
617
618 // Correct the sound card / PHC rate difference with libsamplerate, which
619 // is what the three rejected elements above were each trying to be.
620 //
621 // See the DriftResampleProbe comment in AES67Manager.cpp for the control
622 // law. In short: the ratio is computed directly from (input frames / PHC
623 // seconds) rather than servoed towards a target, because that quantity is
624 // the difference between two crystals and is therefore near-constant --
625 // which is why this does not oscillate the way the earlier loops did.
626 //
627 // Requires libsamplerate at build time; without it the switch does nothing
628 // and the send path behaves exactly as before.
629 //
630 // MEASURED. The resampler itself is transparent and the correction is
631 // right, but this is default OFF because it does not survive past ~11
632 // minutes -- see below.
633 //
634 // Transparency, measured warp-insensitively by comparing power spectra
635 // against the source file (a 57ppm warp moves a bin by 0.006%, so a PSD
636 // sees straight through it): OFF gives mean -3.01 dB / stdev 0.00 dB, ON
637 // gives mean -3.01 dB / stdev 0.09 dB. Indistinguishable.
638 //
639 // Do NOT judge this with correlation against the source: the stream is
640 // deliberately time-warped, so a fixed alignment cannot match a whole
641 // window and correlation reads ~0.93 on audio that is provably clean. It
642 // recovers as the window shrinks -- 0.42 at 2s, 0.85 at 100ms, tracking
643 // intra-window slip -- which is a property of the measurement, not the
644 // audio.
645 //
646 // Correction: trim converges to +57ppm and holds, leaving ~2.5ppm residual
647 // against 56ppm uncorrected, with the alignment slipping exactly -5.5
648 // samples per 2s as intended.
649 //
650 // With sinkPacing this produced the first fully correct AES67 stream in
651 // this file's history: 4.000ms cadence, 1.00 packets per burst, 250.1
652 // packets/s, uniform 1152-byte payloads, pacing queue stable at 56-80ms.
653 // That held for 9-11 minutes and then degraded -- send rate falling to
654 // 155/s with ragged payloads, and the media timeline stepping by +/-23.2ms,
655 // which is exactly one graph quantum at 1024/44100.
656 //
657 // That degradation is NOT this code. The same ~11 minute onset appeared
658 // with audiorate, and sinkPacing alone collapsed at ~15 minutes; the media
659 // file is 220 minutes long and playback was never restarted, so it is
660 // neither a track boundary nor a restart. Something starves the AES67
661 // branch after ten-odd minutes of playback and that is the next thing to
662 // find -- it is very likely the original "sounds fine then goes fragmented"
663 // report on #2848, which every fix so far has merely postponed.
664 // Default ON since 2026-09: this is the validated configuration, proven on
665 // a Pi 5 against a Yamaha MRX7-D / Brooklyn II grandmaster (2.5h and 5h50m
666 // continuous, follower mode, Dante Controller green) as well as a 4h soak
667 // here. The four are not independent -- see the incoherence warnings in
668 // ParseConfig -- so they move together. Only AES67 send pipelines are
669 // affected; a box with no AES67 instance sees no change.
670 bool driftResample = true;
671
672 // Count bytes in at pipewiresrc and out at udpsink, and log both rates.
673 //
674 // Diagnostic for the send rate collapsing partway through a long playback
675 // (250/s to 188/s at ~11 minutes, then to 151/s at ~19 minutes, with
676 // PipeWire reporting no xruns and CPU, memory, thread and fd counts all
677 // flat). Since PipeWire says it is delivering, the audio is going missing
678 // between pipewiresrc and udpsink, and these two counters say which side
679 // of the pipeline loses it.
680 bool pipelineStats = false;
681
682 // Take audio from PipeWire at the graph's own rate and convert to the AES67
683 // rate inside GStreamer, instead of asking PipeWire to deliver 48kHz from a
684 // 44.1kHz graph.
685 //
686 // This is the fault behind "AES67 sounds fine, then goes fragmented". With
687 // a 44100 graph, pipewiresrc negotiates 48000 and PipeWire resamples for
688 // that node alone; measured at the pipewiresrc pad, delivery holds at
689 // 287,968 B/s for 13 minutes, then steps to exactly 0.750x, then to 0.600x,
690 // and stays there. PipeWire reports no xruns for the node throughout, and
691 // CPU, memory, threads, fds, temperature and the graph quantum are all flat
692 // across the whole run.
693 //
694 // Our own pipeline is not involved: byte counters at pipewiresrc and
695 // udpsink track each other at a constant 1.010 ratio the entire time, so
696 // nothing downstream loses a sample -- there is simply less audio arriving.
697 // The physical sinks are unaffected because they run at the graph rate and
698 // are never resampled, which is exactly why the sound card stays clean
699 // while the AES67 stream falls apart.
700 //
701 // Default OFF: this was written as a candidate fix for the collapse and it
702 // is not one -- delivery degrades identically whether the source is taken
703 // at 48kHz or at the graph's own rate. PipeWire's per-node resampling is
704 // not at fault either way; pw-record's own 48k-from-44.1k stream runs at
705 // 99.9% of realtime indefinitely. Kept as a knob, not a fix.
706 bool nativeSourceRate = false;
707
708 // Copy each buffer out of PipeWire's pool instead of referencing it, and
709 // negotiate a deeper pool.
710 //
711 // Candidate fix for the send rate collapsing partway through playback.
712 // Delivery to pipewiresrc steps to exactly 3/4 then 3/5 of nominal and
713 // stays there, with no xruns on the node and every resource metric flat --
714 // the shape of PipeWire skipping cycles because no buffer is free to fill.
715 // pipewiresrc negotiates min-buffers=2 and, with always-copy off, a buffer
716 // is only returned to the pool once everything downstream has dropped its
717 // reference, so anything that holds one starves the next cycle.
718 //
719 // Ruled out first, so this is not a guess at the level above: the graph is
720 // healthy (recording the sound card's monitor gives 99.9% of realtime while
721 // AES67 is at 52%), our own pipeline loses nothing (byte counters at
722 // pipewiresrc and udpsink hold a constant 1.010 ratio), and it is not
723 // per-node resampling (it degrades identically at the graph's native rate,
724 // and pw-record's own 48k-from-44.1k stream is unaffected).
725 // THIS is the fix. Isolated by A/B: a 16 buffer pool on its own holds the
726 // send rate flat for 26 minutes, with always-copy off and the source still
727 // taken at 48kHz. So the copy is not needed -- the pool was simply too
728 // shallow to absorb normal downstream reference-holding, and PipeWire
729 // skipped the cycles it could not fill.
730 //
731 // always-copy remains available for the case where something downstream
732 // genuinely retains buffers, at the cost of a memcpy per buffer.
733 //
734 // Above stereo that case is real, so the pipeline turns the copy on by
735 // itself -- see MULTICHANNEL_NEEDS_BUFFER_COPY. Setting this true forces
736 // it on at any channel count; it is never forced off.
737 bool sourceBufferCopy = false;
738 int sourceMinBuffers = 16;
739
740 // Schedule the capture node from PTP instead of from the sound card.
741 //
742 // This is the producer-side half of the pool problem. pipewiresrc receives
743 // into sourceMinBuffers slots that PipeWire fills at the graph's rate --
744 // the card crystal, ~54ppm slow of PTP here -- while the pipeline drains
745 // them against the PTP clock. driftResample corrects the rate downstream
746 // of the pool, so it cannot refill it; the pool empties after (N-1) quanta
747 // and the source then skips a cycle per rotation for good.
748 //
749 // PipeWire supports exactly this case. A support.node.driver clocked from
750 // the NIC's PHC drives any node that joins its node.group, and PipeWire
751 // rate-matches at the boundary with the card-driven graph using the
752 // adapter's DLL-driven adaptive resampler -- upstream of our pool rather
753 // than downstream of it. It is the same mechanism pipewire-aes67.conf
754 // uses, where the comment on aes67.driver-group calls it "force rate
755 // matching on the AES67 node rather than other nodes".
756 //
757 // Requires a driver node to exist with a matching group; FPP ships one in
758 // 98-fpp-ptp-driver.conf. Harmless if absent -- the node keeps the graph
759 // driver and behaves exactly as before.
760 // Run the pipeline on the graph's clock and use PTP only for the media
761 // clock and the RTP timestamps.
762 //
763 // MEASURED, AND IT IS THE WRONG ARCHITECTURE. Keep it default OFF.
764 //
765 // It does fix the source side -- the ring stops draining, because
766 // pipewiresrc no longer pulls on PTP time while PipeWire fills at the card's
767 // rate. But rtpL24pay derives RTP timestamps from the pipeline's running
768 // time, so moving the pipeline off PTP unanchors the whole RTP timeline:
769 // presentation timing measured -36,135,744 ms, and aes67_verify put the
770 // media clock at -56.3ppm, i.e. not locked at all. A ts-offset servo does
771 // not rescue that; the timestamps themselves would have to be re-derived.
772 //
773 // The deeper reason not to pursue it: it keeps the sound card as clock
774 // master and bolts PTP on beside it, and that is the opposite of how AES67
775 // is done. In professional practice the audio sample clock is slaved to
776 // PTP -- Dante and RAVENNA interfaces derive their word clock from the
777 // network. The Linux reference implementation (bondagit/aes67-linux-daemon)
778 // uses Merging's MergingRavennaALSA.ko, a kernel module presenting a virtual
779 // ALSA device that IS the PTP clock domain; everything else adapts to it.
780 // That is the same shape as PipeWire's node.group = pipewire.ptp0, which
781 // means the "graph takeover" that approach causes -- the sound cards moving
782 // onto the PTP driver and being rate-matched -- is not a side effect to be
783 // avoided. It is the intended behaviour, and the point of a clock domain.
784 // Default ON since 2026-09: this is the validated configuration, proven on
785 // a Pi 5 against a Yamaha MRX7-D / Brooklyn II grandmaster (2.5h and 5h50m
786 // continuous, follower mode, Dante Controller green) as well as a 4h soak
787 // here. The four are not independent -- see the incoherence warnings in
788 // ParseConfig -- so they move together. Only AES67 send pipelines are
789 // affected; a box with no AES67 instance sees no change.
790 bool splitClockDomains = true;
791
792 // Transmit lead the splitClockDomains servo holds, in milliseconds.
793 //
794 // How far ahead of its own declared playout time each packet goes on the
795 // wire. Bounded from both directions, and the window is narrower than it
796 // looks.
797 //
798 // Too small and the sender's own jitter eats the margin: a packet that
799 // slips past its playout time arrives late, and a conformant receiver
800 // discards it and plays silence -- that is the -23.7ms failure that
801 // silenced a Yamaha MRX7-D in issue #2848.
802 //
803 // Too large and the packet arrives before the receiver has anywhere to put
804 // it. The lead has to be held in the receiver's playout buffer, and that
805 // buffer is sized by the device's link offset -- so the ceiling is set by
806 // the smallest buffer on the network, not by anything here. The 20ms this
807 // used to default to was chosen against a Dante/RAVENNA link offset of
808 // 0.25-5ms "with a wide margin", which was the wrong reading: the margin is
809 // the buffer, and 20ms overruns it. It survived a Brooklyn II, which has
810 // the depth to absorb it, and failed on the Ultimo-class receivers that do
811 // not -- reported as late and missing packets, on a stream whose payload,
812 // sequence, timestamps and pacing all measured clean.
813 //
814 // 3ms sits inside both bounds and is verified on both: Ultimo and Brooklyn
815 // II receiving the same stream, where 20ms worked only on the Brooklyn. It
816 // still clears the sender's measured worst-case transmission lateness --
817 // 0.235ms at 1ms ptime over 180k packets, 0.64ms at 4ms -- by an order of
818 // magnitude. What it no longer clears is a pacing thread that failed to
819 // reach SCHED_FIFO, which can transmit a whole ptime late; that already
820 // warns at pipeline start, and now it matters.
821 //
822 // Global, not per-instance: one lead for every stream on the box. Raising
823 // it for a receiver with a deep buffer raises it for the shallow ones too.
824 int targetLeadMs = 3;
825
826 // Mix a permanent silence source in with the captured audio.
827 //
828 // The AES67 media clock is a sample count, so audio that never arrives puts
829 // the timeline permanently behind PTP -- it cannot be corrected later,
830 // because the samples are not late, they are absent. FPP tearing down and
831 // rebuilding its media pipeline at a track change leaves a ~232ms hole, and
832 // measured with a 25s file on repeat that ran the media clock to -6589ppm:
833 // AES67 drifting ahead of the local sound card by ~180ms per track, and
834 // accumulating. The listener hears tracks butted together on AES67 while
835 // the sound card has the pause.
836 //
837 // Silence is the additive identity, so mixing a constant silence source
838 // with the real audio needs no arbitration: silence alone when nothing is
839 // playing, the audio itself when something is. Proven by hand -- linking a
840 // silence source alongside the media took the media clock from -6589ppm to
841 // +0.9ppm. That was done in FPP's routing matrix and killed the audio, so
842 // it belongs here in our own pipeline instead, where nothing else is
843 // arbitrating the links.
844 // Default ON since 2026-09: this is the validated configuration, proven on
845 // a Pi 5 against a Yamaha MRX7-D / Brooklyn II grandmaster (2.5h and 5h50m
846 // continuous, follower mode, Dante Controller green) as well as a 4h soak
847 // here. The four are not independent -- see the incoherence warnings in
848 // ParseConfig -- so they move together. Only AES67 send pipelines are
849 // affected; a box with no AES67 instance sees no change.
850 bool sourceSilenceFloor = true;
851
852 bool sourcePtpGroup = false;
853 std::string sourcePtpGroupName = "pipewire.ptp0";
854
855 // Schedule the capture node asynchronously from its producer. Required
856 // whenever sourcePtpGroup is on: crossing driver domains without it stalls
857 // the stream outright. See the comment at the node.async call site.
858 bool sourceAsync = true;
859
860 // Adaptive resampling: continuously trim the send stream's rate so the
861 // media timeline advances at exactly PTP rate.
862 //
863 // Without it the audio is clocked by the sound card's crystal while the RTP
864 // timestamps advance on PTP, so the two walk apart -- measured at -111ppm,
865 // i.e. 6.7ms per minute. A receiver holding 5ms (the Yamaha MRX7-D's
866 // maximum) runs out in under a minute and mutes; at its 0.25ms minimum, in
867 // seconds. That is why AES67 audio plays cleanly right after a restart and
868 // then dies, which cost a lot of confusing test reports on #2848.
869 // Default OFF: the loop is implemented but NOT yet working. With the
870 // gains it shipped with it drove the stream to +890ppm (worse than the
871 // -111ppm it corrects); with the gains fixed it now makes no correction at
872 // all -- measured -112.6ppm against a -110.9ppm uncorrected baseline.
873 //
874 // Next step is to find out which half is broken, which needs the
875 // per-iteration numbers this loop already logs at debug level: either
876 // gst_element_query_position() is not reporting the post-"speed" media
877 // timeline (so `ratio` is always ~1 and no correction is ever computed), or
878 // the speed property is not taking effect on a running pipeline. Check
879 // `ratio` in the log first: if it tracks the real drift the measurement is
880 // fine and the element is at fault, and vice versa.
881 //
882 // UPDATE: the "speed" element is not a working actuator. Driven from 0 to
883 // the full -500ppm clamp on a live stereo stream, the measured drift moved
884 // by ~35ppm (-80 -> -45) where ~500ppm was asked for. It accepts the
885 // property and reads it back -- which is what earlier notes here wrongly
886 // took as proof of actuation -- but does not apply it to a live source,
887 // having been written for changing playback rate of seekable media.
888 //
889 // The measurement half of the loop IS sound: on a stereo stream it reads a
890 // steady -40 to -100ppm, consistent with the -110.9ppm measured
891 // independently from packet captures. So what needs replacing is the
892 // actuator, not the control loop.
893 //
894 // "pitch" (soundtouch) was the next candidate and it is also not usable:
895 //
896 // - It does not actuate either. Over six actuations the trim ramped
897 // 83ppm (+11.8 -> -71.4) while the measured ratio just wandered around
898 // -50ppm with +/-35ppm of noise -- no systematic response, the same
899 // signature "speed" gave.
900 // - It destroys the transmit cadence. soundtouch emits in large internal
901 // blocks, so everything downstream arrives late in clumps: with pitch in
902 // the chain, 16.05 packets per burst and 93.8% back-to-back with the
903 // pacing queue pinned at 0, against 1.00 packets and 0.0% with it
904 // removed (A/B on the same track, same build).
905 //
906 // Why this matters more than it looks: this is not a nice-to-have. The
907 // drift is two free-running crystals -- the NIC's PHC against the sound
908 // card's -- measured at -55.8ppm over 10s, -56.36ppm over 60s and -56.9ppm
909 // from packet captures, three independent methods agreeing to ~1ppm. When
910 // FPP is PTP master (as it is by default with no other grandmaster on the
911 // network) ptp4l never disciplines the PHC at all, so there is nothing to
912 // lock to and no PTP setting can remove this. It also drains the sinkPacing
913 // queue, so both the drift and the pacing failure are this one cause.
914 //
915 // What is still needed is a variable-rate resampler that (a) actually
916 // responds to a rate property on a live stream and (b) preserves buffer
917 // cadence. Neither "speed" nor "pitch" does both.
918 bool adaptiveResample = false;
919 };
920
921 // ──────────────────────────────────────────────────────────────────────────────
922 // Pipeline wrapper — one per send or receive direction of an instance
923 // ──────────────────────────────────────────────────────────────────────────────
924 struct AES67Pipeline {
925 int instanceId = 0;
926 bool isSend = true;
927 GstElement* pipeline = nullptr;
928 GstElement* rtpbin = nullptr;
929 GstBus* bus = nullptr; // polled by watchdog (no GLib main loop)
930
931 // Pipeline state
932 bool running = false;
933 std::string errorMessage;
934 // Posted an ERROR on its bus. The pipeline stays in PLAYING with its
935 // streaming stopped and says so only once, so the watchdog keeps this
936 // until the rebuild replaces the pipeline.
937 bool busError = false;
938
939 // Buffer-drop probe: while > 0, the probe drops buffers and subtracts
940 // each one's duration. Used by FlushSendPipelines() to discard stale
941 // audio between tracks.
942 //
943 // This is a DURATION, not a buffer count, and that distinction was the
944 // whole of the track-transition fault. The old code dropped a fixed 10
945 // buffers, sized against a 256-sample quantum ("~53ms" per its comment).
946 // Nothing runs a 256-sample quantum: at the 1024 both a Pi 5 and this box
947 // actually use, 10 buffers is 213ms at 48kHz and 232ms at 44.1kHz -- four
948 // times the audio it meant to discard. That self-inflicted gap is what
949 // the drift probe then reported as a "source gap" and filled with
950 // silence, and what a receiver saw as ~158ms of dead wire once the sink
951 // queue had drained through it. Both numbers matched to the millisecond
952 // on two different machines.
953 std::atomic<gint64> dropRemainingNs = 0;
954 GstPad* probePad = nullptr; // pad where probe is installed
955 gulong probeId = 0; // installed probe handle (0 = none)
956
957 // Zombie detection: track bytes pushed by udpsink across watchdog cycles.
958 // If bytes haven't increased for 2 consecutive checks while pipeline
959 // reports PLAYING, the pipewiresrc has lost its PipeWire connection.
960 uint64_t lastByteCount = 0;
961 int stallCount = 0; // consecutive checks with no progress
962 // Under-delivery detection. A stall is easy -- bytes stop entirely -- but
963 // the failure that actually bites is partial: after roughly 105-110
964 // minutes of pipeline uptime the send rate settles around 90% of nominal
965 // with periodic RTP timestamp gaps, and it never recovers on its own, so
966 // the stream plays broken until fppd is restarted. bytes-served keeps
967 // climbing throughout, so the stall check above cannot see it.
968 //
969 // The cause is the source buffer pool draining, and the interval is set by
970 // clock drift, not by uptime. pipewiresrc receives into sourceMinBuffers
971 // slots while the pipeline consumes against PTP; the PipeWire graph clock
972 // free-runs ~54ppm slow of the NIC's PHC on this hardware, so the pool
973 // loses that difference steadily and empties after (N-1) quanta of
974 // accumulated slip. From then on the source skips exactly one graph cycle
975 // every N buffers, forever, until the pipeline is rebuilt with a full pool.
976 //
977 // Measured both ways round, which is what confirmed it:
978 //
979 // min-buffers onset buffer onset gap spacing implied drift
980 // 16 273985 97.4m every 16 54.7 ppm
981 // 8 128604 45.7m every 8 54.4 ppm
982 //
983 // against 54.2ppm measured directly with phc_ctl. Onset ratio 2.130 vs
984 // 15/7 = 2.143 predicted. Forcing the graph to 48000 shifts the onset to
985 // 98 minutes from 108 -- 10% off in wall time, but the same buffer count,
986 // which is what first showed the trigger counts cycles rather than seconds.
987 //
988 // So sourceMinBuffers is a reservoir, not a fix: it sets how long the
989 // stream survives, not whether it degrades. Raising it buys proportional
990 // time and nothing else. A reporter whose clock drifts ~17ppm sees the
991 // same failure at 5h18m for the same reason.
992 //
993 // Earlier notes here read this as uptime-driven. That was fitted to runs
994 // that happened to contain no restarts; the cadence in fact continues
995 // straight through an fppd restart, which is what ruled uptime out.
996 std::chrono::steady_clock::time_point lastByteTime{};
997 int lowRateCount = 0;
998 int channels = AES67::DEFAULT_CHANNELS; // for the expected byte rate
999 int ptime = AES67::DEFAULT_PTIME_MS; // packets/s, for the header bytes in it
1000 bool pacingTuned = false; // latency-derived shift applied yet?
1001 };
1002
1003 // ──────────────────────────────────────────────────────────────────────────────
1004 // SAP discovered stream (from remote announcements)
1005 // ──────────────────────────────────────────────────────────────────────────────
1006 struct SAPDiscoveredStream {
1007 uint16_t msgIdHash = 0;
1008 std::string originAddress;
1009 std::string sessionName;
1010 std::string multicastIP;
1011 int port = 0;
1012 int channels = 2;
1013 int ptime = 4;
1014 std::string ptpClockId;
1015 uint64_t lastSeenMs = 0;
1016 int autoCreatedInstanceId = -1; // ID of auto-created receive pipeline, or -1
1017 };
1018
1019 // ──────────────────────────────────────────────────────────────────────────────
1020 // AES67Manager — singleton managing all AES67 GStreamer pipelines
1021 // ──────────────────────────────────────────────────────────────────────────────
1022 class AES67Manager {
1023 public:
1024 static AES67Manager& INSTANCE;
1025
1026 // HTTP API endpoint (registered at /aes67)
1027 HttpResponsePtr render_GET(const HttpRequestPtr& req);
1028
1029 // Lifecycle
1030 bool Init(); // Called from fppd startup
1031 void Shutdown(); // Called from fppd shutdown
1032
1033 // Apply configuration — reads JSON and rebuilds pipelines
1034 // Called from PHP API (POST /api/pipewire/aes67/apply) and boot
1035 bool ApplyConfig();
1036
1037 // Cleanup — stop all pipelines, remove PipeWire configs
1038 void Cleanup();
1039
1040 // Status query — for PHP API (GET /api/pipewire/aes67/status)
1041 struct Status {
1042 struct PipelineStatus {
1043 int instanceId;
1044 std::string name;
1045 std::string mode; // "send" or "receive"
1046 bool running;
1047 std::string error;
1048 // Rate pipewiresrc actually negotiated with the graph, before our
1049 // resampler. 48000 means the audio reaches AES67 untouched; any
1050 // other value means we are rate-converting off the sound card's
1051 // clock. This is the number that matters for AES67 -- the graph's
1052 // default.clock.rate does not tell you what this stream is fed,
1053 // because per-card and per-group rates sit in between.
1054 int sourceRate = 0;
1055 // Configured and enabled, but deliberately not started because
1056 // nothing in the audio graph feeds it -- see
1057 // AES67Config::requireGroupSource. Not an error: `note` carries
1058 // the reason for the UI to render as guidance rather than a
1059 // failure.
1060 bool waitingForSource = false;
1061 std::string note;
1062 };
1063 std::vector<PipelineStatus> pipelines;
1064 bool ptpSynced = false;
1065 int64_t ptpOffsetNs = 0; // offset from PTP master
1066 // False when pmc gave no usable master_offset, so ptpOffsetNs is a
1067 // default rather than a measurement. Reported as a null offsetNs
1068 // rather than a zero that reads as a perfect lock.
1069 bool ptpOffsetValid = false;
1070 std::string ptpGrandmasterId;
1071 // IP the grandmaster's Announce messages come from -- our own
1072 // interface address when we hold the role. Empty when no Announce
1073 // for this identity has been seen recently (see PTP_ANNOUNCE_STALE_MS).
1074 std::string ptpGrandmasterAddress;
1075 // True when that address is the boundary clock relaying the domain
1076 // rather than the grandmaster itself, i.e. stepsRemoved > 0.
1077 bool ptpGrandmasterViaBoundary = false;
1078 std::string ptpPortState; // ptp4l portState (MASTER/SLAVE/LISTENING/...)
1079 bool ptpIsGrandmaster = false; // true when *we* hold the grandmaster role
1080 // False when the current pipelines anchored their RTP timelines to a
1081 // clock that had not settled, so the anchors may be wrong by however
1082 // far it has moved since -- the failure on #2848, where every other
1083 // field here read healthy while the wire was not. True when the
1084 // clock was settled, and also when nothing is anchored to PTP.
1085 bool ptpLockedAtStart = false;
1086 bool ptpFreeRunning = false;
1087 // Copied out of m_config under m_configMutex so the HTTP handler can
1088 // render them without touching shared config itself.
1089 bool ptpEnabled = false;
1090 int ptpDomain = 0;
1091 std::string ptpRole;
1092 // The graph's clock rate, for context only -- see PipelineStatus::sourceRate
1093 // for what actually feeds a given AES67 stream.
1094 int graphSampleRate = 0;
1095 std::vector<SAPDiscoveredStream> discoveredStreams;
1096 };
1097 Status GetStatus();
1098
1099 // Self-test — validates AES67 subsystem components.
1100 // Returns JSON with pass/fail for each test.
1101 struct TestResult {
1102 std::string testName;
1103 bool passed;
1104 std::string message;
1105 };
1106 std::vector<TestResult> RunSelfTest();
1107
1108 // Check if manager is active
1109 3554 bool IsActive() const { return m_active.load(); }
1110
1111 // A zero-hop RTP branch on a media pipeline's tee. The branches are
1112 // disabled (see GStreamerOutput::AttachAES67Branches()); the type stays
1113 // for that member.
1114 struct InlineRTPBranch {
1115 int instanceId;
1116 GstElement* queue = nullptr; // branch entry point (added to caller's bin)
1117 GstPad* teeSrcPad = nullptr; // requested pad on tee (must be released)
1118 };
1119 void FlushSendPipelines();
1120
1121 // Apply the master volume to every send pipeline. A sender's PipeWire
1122 // node is a capture stream, not a sink, so the master's pactl pass over
1123 // the output sinks never reaches it; the gain is a volume element in the
1124 // pipeline instead. New pipelines take it from getVolume() as they start.
1125 void SetMasterVolume(int volume);
1126
1127 AES67Manager();
1128 virtual ~AES67Manager();
1129
1130 private:
1131
1132 // Config
1133 AES67Config m_config;
1134 std::string m_configPath;
1135 bool LoadConfig();
1136
1137 // Guards every access to m_config.
1138 //
1139 // LoadConfig() clears and refills m_config.instances, which reallocates
1140 // the vector and reassigns its std::strings. ApplyConfig() and the SAP
1141 // threads are safe (ApplyConfig joins those threads before loading), but
1142 // GetStatus(), RunSelfTest() and the PTP query helpers all run on HTTP or
1143 // command threads and read m_config concurrently -- iterating a vector
1144 // that is being reallocated, or reading a std::string that is being
1145 // reassigned, is a use-after-free. UIs poll status, so this is the
1146 // likeliest crash in the field.
1147 //
1148 // Held only for the duration of a read or the final swap in LoadConfig(),
1149 // and NEVER together with m_pipelineMutex -- readers snapshot what they
1150 // need, release, then take the pipeline lock. That keeps the two locks
1151 // unordered with respect to each other and makes deadlock impossible.
1152 std::mutex m_configMutex;
1153
1154 // Snapshot accessors -- copy under the lock, use the copy afterwards.
1155 AES67Config GetConfigSnapshot();
1156 bool IsPtpEnabled();
1157 int GetPtpDomain();
1158 std::string GetPtpInterface();
1159
1160 // PTP (managed via ptp4l subprocess)
1161 bool m_ptpInitialized = false;
1162 pid_t m_ptp4lPid = -1; // ptp4l child process ID
1163 pid_t m_phc2sysPid = -1; // phc2sys child process ID
1164 // pidfds for the two, or -1 (no pidfd support). fppd's SA_NOCLDWAIT
1165 // reaps a child the moment it exits, so its PID can be reused at once;
1166 // a pidfd always refers to our child, where kill(pid) could hit
1167 // whatever took the number.
1168 int m_ptp4lPidfd = -1;
1169 // m_ptp4lPid and m_ptp4lPidfd: IsPtp4lRunning() reads them from HTTP
1170 // threads (status, self-test) while the main loop starts and stops
1171 // ptp4l, and closing the pidfd under a reader polled a closed -- or
1172 // reused -- descriptor. Held only to read or swap them, never across a
1173 // wait for the child.
1174 mutable std::mutex m_ptp4lProcMutex;
1175 // ptp4l is running with hardware timestamping, i.e. disciplining the
1176 // NIC's PHC. With software timestamping it disciplines CLOCK_REALTIME
1177 // and leaves the PHC free-running, so only this makes the PHC the
1178 // domain's time.
1179 std::atomic<bool> m_ptpHwTimestamping{false};
1180 int m_phc2sysPidfd = -1;
1181 void ForgetPtp4l();
1182 std::string m_ptpConfPath; // temp config file for ptp4l
1183 bool InitPTP();
1184 // Wait (up to ptpLockWaitMs) for the clock to settle before the streams
1185 // anchor to it, and record whether it did. Part of InitPTP(), and run on
1186 // its own when a rebuild keeps the running ptp4l.
1187 void AnchorToPtpLock();
1188 // What the running ptp4l was started with. A rebuild that leaves these
1189 // alone keeps it: restarting it drops every receiver in the domain off
1190 // the clock, and with this box as grandmaster that is all of them.
1191 struct PtpParams {
1192 std::string interface;
1193 int domain = 0;
1194 std::string role;
1195 11 bool operator==(const PtpParams& o) const {
1196
4/6
✓ Branch 0 taken 11 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 7 times.
✓ Branch 3 taken 4 times.
✓ Branch 4 taken 7 times.
✗ Branch 5 not taken.
11 return interface == o.interface && domain == o.domain && role == o.role;
1197 }
1198 };
1199 PtpParams m_ptpStartedWith;
1200 void ShutdownPTP();
1201 bool IsPtp4lRunning() const; // check if ptp4l process is alive
1202 std::string GetPTPClockId(); // EUI-64 from interface MAC (this node's own identity)
1203 std::string GetPtp4lState(); // query ptp4l port state via pmc (MASTER/SLAVE/LISTENING/...)
1204
1205 // Write an AES67-profile ptp4l config. Split out so the three start
1206 // attempts (hardware, software, software-without-DSCP) cannot drift apart
1207 // -- they used to be copy-pasted blocks.
1208 bool WritePtpConf(const std::string& path, bool hwTimestamping, bool includeDscp);
1209
1210 // fork/exec ptp4l with the given config. Returns true if it is still
1211 // alive shortly afterwards.
1212 bool StartPtp4l(bool hwTimestamping, bool includeDscp);
1213
1214 // What one poll of ptp4l says about whether the clock will still move
1215 // under anything anchored to it. See the comment above PtpSettledNow()
1216 // in the .cpp for what each outcome means and why the offset, rather than
1217 // the port state, is the signal.
1218 enum class PtpSettleState {
1219 NotSettled, // still converging, or the query told us nothing
1220 Grandmaster, // we hold the role -- the PHC is the domain's time
1221 SlaveLocked, // measured against the GM, correction already applied
1222 NoGrandmasterYet, // LISTENING and gmPresent actually read false
1223 FreeRunning, // software timestamping: ptp4l never moves the clock
1224 };
1225
1226 // One poll of the above. Factored out of WaitForPtpLock() so the watchdog
1227 // can ask the same question later without a second copy of the answer to
1228 // drift out of step with this one. portState and offsetNs, when given,
1229 // receive the readings the verdict was reached on, for logging.
1230 //
1231 // NoGrandmasterYet is deliberately not folded into "settled" here: while
1232 // the initial wait is still running, "no announce seen" and "no announce
1233 // yet" look identical, so only a caller that knows it has waited long
1234 // enough may treat it as an answer.
1235 PtpSettleState PtpSettledNow(std::string* portState = nullptr,
1236 int64_t* offsetNs = nullptr);
1237
1238 // Block until ptp4l reports a clock that will not step under us, or until
1239 // timeoutMs elapses. Returns true if it settled. See
1240 // AES67::PTP_LOCK_OFFSET_NS for what "settled" means and why waiting for
1241 // it is a precondition of anchoring anything to PTP.
1242 bool WaitForPtpLock(int timeoutMs);
1243
1244 // Restart ptp4l/phc2sys if they have died (link flap, OOM, manual kill),
1245 // and notice a PTP clock that has stepped out from under the pipelines'
1246 // RTP anchors. Returns true when the caller should rebuild everything.
1247 // Called from WatchdogLoop() alongside the pipeline watchdog.
1248 bool CheckPtpWatchdog();
1249
1250 // Retract WARNING_PTP_NO_LOCK once the clock it complains about has
1251 // settled -- or ask for a rebuild, if settling moved the clock far enough
1252 // that the anchors really are wrong. Called from CheckPtpWatchdog();
1253 // returns true when the caller should rebuild.
1254 bool ReviewPtpNoLockWarning();
1255
1256 // Raise/retract WARNING_PTP_NO_LOCK. Nothing else should touch that
1257 // warning directly: the banner and the m_ptpNoLockWarned flag have to move
1258 // together, or the watchdog either never reviews a warning that is up or
1259 // reviews one that is not. (The baseline is seeded separately, by
1260 // ResetPtpStepReference() -- see there.)
1261 void RaisePtpNoLockWarning();
1262
1263 // Raise WARNING_PTP_FREE_RUNNING while ptp4l is free-running and has
1264 // selected a grandmaster other than this box, and take it down otherwise.
1265 // Called once the streams are anchored and on every watchdog pass.
1266 void ReviewPtpFreeRunningWarning();
1267
1268 // ptp4l is running with software timestamping, and so free_running.
1269 bool PtpFreeRunning() const;
1270 void ClearPtpNoLockWarning();
1271
1272 // Step detector state: (PTP - CLOCK_MONOTONIC) as it stood at the last
1273 // sample. ResetPtpStepReference() takes one when ApplyConfig() has
1274 // finished building pipelines, so the first watchdog check 30s later can
1275 // already catch a step; PtpClockStepped() compares and re-samples, so the
1276 // comparison is only ever across one watchdog interval and steady drift
1277 // between the two crystals never accumulates into a false positive.
1278 // See AES67::PTP_STEP_DETECT_NS.
1279 int64_t m_ptpMonotonicDeltaNs = 0;
1280 bool m_ptpMonotonicDeltaValid = false;
1281 std::mutex m_ptpStepMutex;
1282 void ResetPtpStepReference();
1283 bool PtpClockStepped();
1284 // PTP minus CLOCK_MONOTONIC, or false when there is no PTP clock to read.
1285 bool PtpMonotonicDelta(int64_t& deltaNs);
1286
1287 // WARNING_PTP_NO_LOCK bookkeeping. m_ptpNoLockWarned says the banner is
1288 // up; the baseline is (PTP - CLOCK_MONOTONIC) as it stood when it went up,
1289 // which is the clock the pipelines were about to anchor to.
1290 //
1291 // The step detector's own reference cannot answer this question: it
1292 // re-samples on every pass, so it only ever sees one watchdog interval's
1293 // worth of movement, and a clock that slews half a second into lock over
1294 // ten minutes moves ~28ms per interval and never trips it. This baseline
1295 // is the one that does not move, so total distance travelled since the
1296 // anchors were built can be measured against it.
1297 //
1298 // Guarded by m_ptpStepMutex, except the atomic flag.
1299 std::atomic<bool> m_ptpNoLockWarned{false};
1300 int64_t m_ptpNoLockBaselineNs = 0;
1301 bool m_ptpNoLockBaselineValid = false;
1302
1303 // Whether the current pipelines' RTP anchors can be trusted: false while
1304 // they are known to have been built against a clock that had not settled.
1305 // Set by InitPTP() from the WaitForPtpLock() result, and cleared again by
1306 // ReviewPtpNoLockWarning() if the clock settles close enough to where the
1307 // anchors were placed that they turned out fine after all. Reported as
1308 // ptp.lockedAtStart, which drives the "streams started before PTP settled"
1309 // badge -- so it has to stop being false whenever the warning does, or the
1310 // page keeps promising a rebuild that is no longer coming.
1311 std::atomic<bool> m_ptpLockedAtStart{false};
1312
1313 // Query the actual PTP grandmaster (may be a remote clock, not this node)
1314 // via `pmc GET TIME_STATUS_NP`. Returns false if ptp4l isn't running or
1315 // the query fails, leaving the out-params untouched.
1316 //
1317 // offsetNs is only meaningful when offsetValid says so: a missing or
1318 // malformed master_offset leaves it at zero, which is indistinguishable
1319 // from a perfectly locked clock. Ask for it anywhere the number is shown
1320 // or acted on; the grandmaster identity alone does not need it.
1321 bool QueryPtp4lTimeStatus(bool& gmPresent, std::string& gmIdentity, int64_t& offsetNs,
1322 bool* offsetValid = nullptr);
1323
1324 // The AES67 media clock -- PTP time, shared by every send pipeline so they
1325 // all sit on one timeline. Created on first use, released in Shutdown().
1326 // Null when PTP is disabled or no PTP time source could be opened, in
1327 // which case pipelines fall back to GStreamer's default clock.
1328 GstClock* m_ptpClock = nullptr;
1329 std::mutex m_ptpClockMutex;
1330 GstClock* GetOrCreateMediaClock();
1331 void ReleaseMediaClock();
1332
1333 // Grandmaster identity to advertise in SDP / report over HTTP: the remote
1334 // clock we follow, or our own identity when we hold the role. Empty when
1335 // PTP is enabled but no grandmaster has been settled on yet.
1336 std::string GetActiveGrandmasterId();
1337
1338 // Cached pmc results -- see AES67::PTP_QUERY_CACHE_MS.
1339 struct PtpQueryCache {
1340 std::chrono::steady_clock::time_point when{};
1341 bool valid = false;
1342 bool gmPresent = false;
1343 bool gmPresentValid = false;
1344 std::string gmIdentity;
1345 int64_t offsetNs = 0;
1346 bool offsetValid = false;
1347 std::string portState;
1348 };
1349 PtpQueryCache m_ptpCache;
1350 std::mutex m_ptpCacheMutex;
1351 void RefreshPtpCache(bool force = false);
1352
1353 // Where a grandmaster identity is announcing from. Populated by the
1354 // Announce listener below, which is the only source of this: pmc reports
1355 // clock identities, never addresses, and a clock identity is an EUI-64
1356 // derived from a MAC that need not belong to the interface carrying PTP,
1357 // so it cannot be resolved to an address by inspection.
1358 struct PtpAnnounceSource {
1359 std::string address;
1360 bool direct = false; // sender IS the grandmaster (stepsRemoved 0)
1361 int64_t lastSeenMs = 0;
1362 };
1363 std::map<std::string, PtpAnnounceSource> m_ptpAnnounceSources; // keyed by GM id
1364 std::mutex m_ptpAnnounceMutex;
1365 std::thread m_ptpAnnounceThread;
1366 std::atomic<bool> m_ptpAnnounceRunning{false};
1367 void PtpAnnounceListenLoop();
1368 void HandlePtpAnnounce(const uint8_t* data, size_t len, const std::string& senderAddr);
1369
1370 // Address the given grandmaster is currently announcing from. False when
1371 // nothing recent has been heard from it, leaving the out-params untouched.
1372 bool GetGrandmasterAddress(const std::string& gmId, std::string& address, bool& viaBoundary);
1373
1374 // Sink-pacing timestamp shift per instance, updatable once the pipeline
1375 // reports its real latency. Owned here so the pad probe can read a live
1376 // value rather than one baked in before the latency is known.
1377 std::map<int, std::atomic<GstClockTime>*> m_sinkPacingShift;
1378
1379 // Drift control loop -- see AES67Config::adaptiveResample. Runs on its own
1380 // thread because it has to sample far more often than the 30s watchdog.
1381 std::thread m_driftThread;
1382 std::atomic<bool> m_driftRunning{false};
1383 void DriftControlLoop();
1384
1385 // Pipeline watchdog — called from WatchdogLoop() to poll bus messages
1386 // and restart any pipeline that isn't in PLAYING state.
1387 // Returns true if a full pipeline rebuild is needed.
1388 bool PollPipelinesWatchdog();
1389 // Rebuilds asked for by bus errors, for the backoff. A rebuild restarts
1390 // ptp4l for the whole domain, so an error that comes straight back must
1391 // not do that every pass. Watchdog thread only.
1392 int m_errorRebuilds = 0;
1393 // Streams whose pipeline failed to build or start in the last apply
1394 // (PipeWire not up yet, say). Nothing else would try them again, so the
1395 // watchdog rebuilds for them on the bus-error backoff. Set by
1396 // ApplyConfig() under m_pipelineMutex.
1397 int m_failedStarts = 0;
1398 // PTP enabled but not running (its start, or a watchdog restart, failed):
1399 // when the watchdog tries again, backing off 30s..5min. Watchdog thread
1400 // only; reset by a successful start.
1401 std::chrono::steady_clock::time_point m_ptpRetryAt{};
1402 int m_ptpRetryDelayS = 0;
1403 std::chrono::steady_clock::time_point m_lastErrorRebuild{};
1404
1405 // Deferred pipeline-rebuild thread — spawned by WatchdogLoop()'s
1406 // watchdog rebuild path to call ApplyConfig() from a thread other than
1407 // the one ApplyConfig() needs to join (m_sapAnnounceThread). Tracked
1408 // as a member (rather than detached) so Shutdown() can join it before
1409 // tearing anything else down -- see Shutdown() and WatchdogLoop().
1410 std::thread m_rebuildThread;
1411
1412 // Rebuild bookkeeping. m_rebuildMutex guards m_rebuildThread. A rebuild
1413 // is scheduled with the apply generation it was asked for and runs only
1414 // if nothing has applied, cleaned up or shut down since (see
1415 // ScheduleRebuild()); m_stopping is set once by Shutdown() and keeps
1416 // ApplyConfig() from bringing anything back after it.
1417 std::mutex m_rebuildMutex;
1418 std::atomic<bool> m_rebuildRunning{false};
1419 std::atomic<bool> m_stopping{false};
1420 std::atomic<uint64_t> m_applyGeneration{0};
1421 void ScheduleRebuild();
1422 bool ApplyConfigLocked();
1423
1424 // Serializes the whole tear-down/rebuild sequence in ApplyConfig(),
1425 // Shutdown() and Cleanup(). ApplyConfig() joins the SAP threads at the
1426 // top and re-creates them ~70 lines later, after loading config and
1427 // building pipelines; that window is wide, and ApplyConfig() has three
1428 // independent callers (the boot sequence, AES67ApplyCommand::run on a
1429 // command thread, and m_rebuildThread from the watchdog). Two overlapping
1430 // calls both pass the join, then both assign m_sapAnnounceThread -- and
1431 // assigning over a still-joinable std::thread is an unconditional
1432 // std::terminate().
1433 //
1434 // Shutdown() must join m_rebuildThread BEFORE taking this lock: that
1435 // thread calls ApplyConfig(), so holding the lock across the join would
1436 // deadlock.
1437 std::mutex m_applyMutex;
1438
1439 // Pipeline management
1440 std::map<int, AES67Pipeline> m_sendPipelines; // keyed by instance ID
1441 std::map<int, AES67Pipeline> m_recvPipelines;
1442 std::mutex m_pipelineMutex;
1443
1444 // Send instances ApplyConfig() chose not to start because nothing feeds
1445 // them -- see AES67Config::requireGroupSource. Instance ID to the reason,
1446 // which is shown to the user, so phrase it as guidance rather than as an
1447 // error. Guarded by m_pipelineMutex alongside the pipeline maps, so a
1448 // status reader sees the whole picture -- running, failed and waiting --
1449 // under one lock.
1450 std::map<int, std::string> m_deferredSenders;
1451
1452 bool CreateSendPipeline(const AES67Instance& inst);
1453 bool CreateRecvPipeline(const AES67Instance& inst);
1454 void StopPipeline(AES67Pipeline& p);
1455 void StopAllPipelines();
1456
1457 // Get source IP for the network interface
1458 std::string GetInterfaceIP(const std::string& iface);
1459
1460 // SAP announcer thread
1461 std::thread m_sapAnnounceThread;
1462 std::atomic<bool> m_sapAnnounceRunning{false};
1463 void SAPAnnounceLoop();
1464
1465 // Recovery and PTP supervision; see WatchdogLoop().
1466 std::thread m_watchdogThread;
1467 std::atomic<bool> m_watchdogRunning{false};
1468 void WatchdogLoop();
1469 void StopWorkerThreads();
1470 std::string BuildSDP(const AES67Instance& inst, const std::string& sourceIP,
1471 const std::string& ptpClockId, uint32_t sdpVersion);
1472 std::vector<uint8_t> BuildSAPPacket(const std::string& sourceIP,
1473 uint16_t msgIdHash,
1474 const std::string& sdp,
1475 bool isDeletion = false);
1476
1477 // The SDP for one instance as the announcer would emit it right now, for
1478 // the /aes67/sdp export. Deliberately the same BuildSDP() the SAP path
1479 // uses: a file the user hands to Stream Monitor or VLC has to describe the
1480 // stream that is actually on the wire, refclk and all, or it is worse than
1481 // no file at all when the point of it is troubleshooting.
1482 std::string ExportSDPFor(const AES67Instance& inst, const AES67Config& cfg);
1483
1484 // RFC 2974 requires the message id hash to change whenever the announced
1485 // payload changes, so it is computed over the SDP text itself rather than
1486 // over the instance -- otherwise receivers dedupe an updated announcement
1487 // as a repeat and never see the corrected refclk.
1488 uint16_t ComputeSAPHash(const std::string& sdp);
1489
1490 // SDP o= version for a given announcement body. Only advances when the
1491 // announced content actually changes: the msg id hash is derived from the
1492 // SDP text, so bumping the version on every rebuild would mint a new hash
1493 // each time and leave SAP receivers listing a phantom stream per restart
1494 // until their timeout (~10 announce intervals) cleared it.
1495 //
1496 // The mapping is persisted so an fppd restart with unchanged config
1497 // re-announces byte-identical SDP rather than a new session.
1498 uint32_t SDPVersionFor(const std::string& body);
1499 void LoadSDPVersion();
1500 void SaveSDPVersion();
1501 std::string m_sdpVersionPath;
1502 std::string m_sdpBodyKey; // hash of the last announced body
1503 uint32_t NextSDPVersion();
1504 // Bumped from the SAP thread on every rebuild and from RunSelfTest() on
1505 // whichever thread asked for the test, so it cannot be a plain int.
1506 std::atomic<uint32_t> m_lastSdpVersion{0};
1507
1508 // SAP receiver thread
1509 std::thread m_sapRecvThread;
1510 std::atomic<bool> m_sapRecvRunning{false};
1511 void SAPReceiveLoop();
1512 // Keyed by (origin address, message id hash): RFC 2974 identifies an
1513 // announcement by both, and the 16-bit hash alone collides between
1514 // senders.
1515 std::map<std::pair<std::string, uint16_t>, SAPDiscoveredStream> m_discoveredStreams;
1516 std::mutex m_discoveredMutex;
1517 void HandleSAPPacket(const uint8_t* data, size_t len,
1518 const std::string& senderAddr);
1519
1520 // State
1521 std::atomic<bool> m_active{false};
1522 std::atomic<bool> m_initialized{false};
1523
1524 // Safe node name (matches fpp_aes67_common.py safe_node_name)
1525 static std::string SafeNodeName(const std::string& name);
1526 };
1527
1528 #endif // HAS_AES67_GSTREAMER
1529