GCC Code Coverage Report


Directory: ./
File: mediaoutput/PipeWireOutputStream.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 1 1 100.0%
Functions: 1 1 100.0%
Branches: 0 0 -%

Line Branch Exec Source
1 #pragma once
2 /*
3 * This file is part of the Falcon Player (FPP) and is Copyright (C)
4 * 2013-2026 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 #include "GStreamerOut.h"
15
16 #ifdef HAS_GSTREAMER
17
18 #include <gst/gst.h>
19
20 #include <atomic>
21 #include <condition_variable>
22 #include <cstdint>
23 #include <deque>
24 #include <mutex>
25 #include <string>
26 #include <utility>
27 #include <vector>
28
29 struct pw_thread_loop;
30 struct pw_stream;
31
32 // A PipeWire playback stream that outlives the media played through it.
33 //
34 // Giving every track its own pipewiresink costs ~700 ms on an AM335x before the
35 // first sample reaches the card, and almost none of it is the card: opening a
36 // full-speed USB card directly takes ~25 ms. The rest is the new stream node
37 // appearing, WirePlumber linking it (~300 ms of policy on one slow core), the
38 // group and filter-chain nodes waking and the ALSA node starting. A sequence
39 // started alongside the media runs ahead of the sound for all of that.
40 //
41 // One stream per slot, opened ahead of need and held open between tracks, pays
42 // that once. A track fed into a stream that is already open reaches the graph
43 // in tens of milliseconds. Media pipelines feed it through an appsink (see
44 // AttachFeed()), converted to the stream's one fixed format (CapsFields()).
45 // While open and idle the stream plays silence, which keeps the card running.
46 //
47 // It is a native PipeWire stream fed from a queue of our own, so that
48 // PipeWire's timing for each cycle (pw_stream_get_time_n(): when the samples
49 // it takes reach the device) says exactly when every sample queued is heard
50 // (HeardRunningTime()). Through a pipewiresink, where a track's sound landed
51 // could only be estimated, and a track started on a drained stream landed
52 // anywhere within a graph cycle of the estimate.
53 //
54 // The stream presents exactly the node a per-track pipewiresink used to --
55 // node.name fppd_stream_N, same description, same target and stream
56 // properties -- so routing, input mixing and the graph view are unaffected.
57 class PipeWireOutputStream {
58 public:
59 // How long a stream stays open after its last track stops feeding it, and
60 // how far ahead of a scheduled playlist it is opened. Matches how long
61 // the channel output thread keeps running after output goes idle.
62 static constexpr int LINGER_MS = 5000;
63
64 // The slot's stream, or nullptr for a slot outside 1..MAX_SLOTS or when
65 // PipeWire is not the media backend.
66 static PipeWireOutputStream* ForSlot(int slot);
67
68 // Open the slot's stream now if it isn't, and keep it open for at least
69 // holdMs. Never blocks.
70 static void Prewarm(int slot, int holdMs);
71
72 // Close every stream immediately (fppd shutdown).
73 static void ShutdownAll();
74
75 // Keep slot 1's stream open while set (the PipeWireKeepOutputOpen
76 // setting, applied live), so media triggered at any moment -- GPIO, a
77 // command, the API -- never waits for it to open. Costs the CPU of a
78 // stream that is always running. Clearing it lets the stream close after
79 // the usual linger.
80 static void SetKeepOpen(bool keepOpen);
81
82 // The fixed format every stream carries, as caps fields to append to
83 // "audio/x-raw" (",format=F32LE,rate=...,channels=2,layout=interleaved").
84 // A feed must deliver exactly this: the stream's PipeWire format is fixed
85 // when it connects, so a feed in any other format would be reinterpreted,
86 // not converted.
87 static std::string CapsFields();
88
89 // A track is about to play through this stream. Opens it (or reopens it
90 // on `target`, if it is open on another sink) and keeps it open until
91 // Release(). Never blocks.
92 void Acquire(const std::string& target);
93 // The track stopped. Its feed is detached and the stream closes after
94 // LINGER_MS unless something acquires it again first.
95 void Release(GstElement* feed);
96
97 // Block until audio fed now will reach the card, or timeoutMs passes.
98 bool WaitReady(int timeoutMs);
99 // Block until what earlier feeds (and the silence pushed behind them)
100 // queued has played out, or maxMs passes. A track that starts right
101 // behind another must not go to PLAYING before then: its position runs
102 // from PLAYING, so audio still queued ahead of it would leave the lights
103 // ahead of the sound for the whole track.
104 //
105 // Then flush the stream, unless nothing was handed to it since the last
106 // flush: what that wait can't see -- audio held up by a stall in the
107 // graph -- would otherwise sit ahead of every track to come, and every
108 // track starts from the same empty queue (see Flush()).
109 void WaitDrained(int maxMs);
110 // Instead of WaitDrained(), for a track that starts right behind another:
111 // carry on the stream's timeline rather than wait for it to drain.
112 //
113 // A stopped track's feed leaves the stream bridged with silence, laid
114 // exactly behind its last sample (see Release()), for a few seconds. If
115 // the timeline is still running, nothing is backed up in front of the
116 // stream, and a card is watched for xruns (DisciplineClock()), this
117 // stops the bridge and returns, in *baseTime, the clock time (on
118 // Clock()) where the queue ends. A pipeline given that base time (and
119 // no start time) hands its first sample over so that it plays right after
120 // the last one queued, and its position then maps onto the sound exactly
121 // as the track before's did. If the queue is about to run out, it is
122 // first extended with silence, just long enough for the pipeline to get
123 // going. Otherwise false, and the caller uses WaitDrained().
124 //
125 // *earlyNs is how far ahead of `baseTime` the pipeline may hand its first
126 // sample over: the feed's lead (FeedLeadNs()), or less when less than
127 // that is left queued. A sink can't render before its base time, so the
128 // caller runs the pipeline on baseTime - *earlyNs with its feed's
129 // ts-offset at *earlyNs - FeedLeadNs() rather than minus the lead, and
130 // allows for that in its position and picture.
131 bool ContinueTimeline(GstClockTime* baseTime, int64_t* earlyNs);
132
133 // Whether slot's stream (if it exists; none is created) has a timeline
134 // the next track could carry on: a track starting now most likely will.
135 // Its sound then runs on behind the last track's without a break, so
136 // nothing that only makes sense between drained tracks (flushing an
137 // audio group's delay lines) should run.
138 static bool SlotMayCarryOn(int slot);
139
140 // How long until the last sample handed over is heard, or -1 if that
141 // isn't known (nothing is queued, or PipeWire hasn't timed a cycle yet).
142 int64_t QueuedAheadNs();
143 // The same for slot's stream, if it exists (none is created).
144 static int64_t QueuedAheadNsForSlot(int slot);
145
146 // What `feed` is being heard at: the running time (in the feeding
147 // pipeline) of the sample leaving the speaker now. PipeWire reports for
148 // every cycle when the samples it takes from the stream reach the device,
149 // and each buffer a feed hands over is kept with its running time and
150 // where it went in the queue, so this is measured, not modelled: however
151 // the track started, and through any stall in the graph.
152 // 1: *runningTime is set.
153 // 0: none of `feed`'s sound has been heard yet.
154 // -1: not known (no timing from PipeWire, or `feed` isn't feeding).
155 // -2: all `feed` gave has been heard and nothing more is queued (a seek
156 // flushed it, or it ran dry): nothing of it is being heard now.
157 int HeardRunningTime(GstElement* feed, GstClockTime* runningTime);
158
159 // Route `appsink`'s samples into this stream, replacing any previous
160 // feed. Samples from a feed that has since been replaced are dropped, so
161 // a track still tearing down can't interleave with the next one. The
162 // appsink must sync (on Clock()): it paces the audio, and this
163 // stream forwards each buffer as soon as it arrives.
164 void AttachFeed(GstElement* appsink);
165
166 // How far ahead of the clock a feed delivers (see AttachFeed()).
167 static int64_t FeedLeadNs();
168 // The clock this stream's own pipeline runs on (a new reference). It runs
169 // at the rate the card plays samples, not the system's: see
170 // DisciplineClock().
171 GstClock* Clock();
172 // The clock every pipeline feeding this stream must run on (a new
173 // reference): the card clock, run faster or slower by SetFeedSpeed().
174 // Until a feed sets a speed it is the card clock exactly.
175 GstClock* FeedClock();
176 // Play `feed`'s media `speed` times as fast as the card plays samples (1.0
177 // is the card's own pace). A MultiSync remote steers its copy of the
178 // show audio onto the master's timeline with this. The feed clock runs
179 // `speed` times as fast, so the feed hands over media at that pace, and
180 // each buffer is resampled to the card's rate on the way in: the stream
181 // still gets exactly what the card plays, so nothing queues up or runs
182 // dry. A GStreamer rate seek can't do it -- this stream plays at a fixed
183 // rate, so a faster feed only builds a queue the position can't see, and
184 // mp3 and FLAC refuse instant rate changes anyway (GstBaseParse). No-op
185 // for a feed that isn't the current one; reset for each new feed.
186 void SetFeedSpeed(GstElement* feed, double speed);
187 // Drop what `feed` has handed over and not yet played, when it seeks:
188 // left in place, the sound from before the seek plays out first and
189 // everything after it is that much late, by an amount its position can't
190 // show. No-op for a feed that isn't the current one.
191 void FlushFeed(GstElement* feed);
192 // That rate, relative to the system clock, smoothed over the last couple
193 // of minutes (1.000432 for a card 432 ppm fast). 1.0 until measured.
194 162352 double ClockRate() const { return m_clockRate.load(std::memory_order_relaxed); }
195
196 private:
197 explicit PipeWireOutputStream(int slot);
198
199 enum class State { Closed,
200 Opening,
201 Ready,
202 Failed };
203
204 // Worker-thread side.
205 static void WorkerLoop();
206 static void WakeWorker();
207 void Service(uint64_t now); // takes and may drop/retake m_lock
208 bool OpenLocked(std::unique_lock<std::mutex>& lock);
209 void CloseLocked(const char* why);
210 void ForgetFailureLocked();
211 // Queue `frames` frames (silence when `data` is null); the queue position
212 // of the first, or UINT64_MAX if the queue had no room for them.
213 uint64_t WriteQueueLocked(const float* data, size_t frames);
214 // Forget where `feed`'s buffers went (HeardRunningTime()).
215 void DropFeedSpansLocked(GstElement* feed);
216 // The queue position heard at CLOCK_MONOTONIC `nowNs`, from the cycle
217 // records; false while there are none.
218 bool FrameHeardAt(int64_t nowNs, uint64_t* frame);
219 static void OnProcess(void* data);
220 static void OnStreamError(void* data, const char* error);
221 // Silence laid on the timeline right behind its end, up to `until`.
222 void ExtendTimelineLocked(GstClockTime until);
223 // Keep a bridged timeline from running out (see Release()); whether it
224 // is still bridging.
225 bool ServiceBridge();
226 void EndTimelineLocked();
227 // A feed buffer starting at `start` (on m_clock) and `frames` long was
228 // handed over, `lateNs` after its sink was due to hand it over.
229 void NoteTimelineLocked(GstClockTime start, size_t frames, GstClockTimeDiff lateNs);
230 // Until everything queued has gone to the graph, or the deadline.
231 bool WaitQueueEmpty(int64_t deadlineUs);
232 // Why the stream is flushed (for the log; the flush itself is the same).
233 enum class FlushFor { NextTrack,
234 MidFeed,
235 Seek };
236 void Flush(FlushFor why);
237 bool CardRunning();
238 // Measure m_cardCorrNs from the card's own pointers; how many ms until it
239 // wants to be called again (INT_MAX: no card to measure). Worker thread
240 // only.
241 int MeasureCardQueue(uint64_t nowMs);
242 void ResetCardQueue();
243 bool StreamLinked();
244
245 static GstFlowReturn OnFeedSample(GstElement* appsink, gpointer userData);
246 // Whether the card lost time (an xrun) while a track was feeding the stream.
247 bool DisciplineClock();
248 void ResetClockSyncLocked();
249 void EnsureClocksLocked();
250 // Re-derive the feed clock from the card clock and m_feedSpeed, continuous
251 // at `internal` (called whenever either changes).
252 void RecalibrateFeedClockLocked(GstClockTime internal);
253 // `in` resampled by m_feedSpeed (a new buffer), carrying m_rs* across calls.
254 GstBuffer* ResampleLocked(GstBuffer* in);
255 void KeepResampleHistoryLocked(GstBuffer* in);
256
257 const int m_slot;
258 std::mutex m_lock;
259 std::condition_variable m_stateChanged;
260
261 State m_state = State::Closed;
262 std::string m_target; // sink the stream is (or is being) linked to
263 std::string m_wantTarget; // sink the next Acquire/Prewarm asked for
264 bool m_wantOpen = false;
265 int m_users = 0;
266 uint64_t m_holdUntilMs = 0;
267 uint64_t m_openStartedMs = 0;
268 uint64_t m_failedMs = 0; // when the stream last failed (keep-open retry)
269 bool m_linked = false;
270 bool m_cardWasRunning = false; // someone else had the card running when we opened
271 uint64_t m_linkedMs = 0;
272 uint64_t m_lastLinkCheckMs = 0;
273
274 // The native PipeWire stream, and the thread loop it runs on. OnProcess()
275 // runs on PipeWire's data thread and takes no lock: it reads the queue
276 // below through m_writePos/m_dropTo and publishes m_readPos and the cycle
277 // records.
278 struct pw_thread_loop* m_pwLoop = nullptr;
279 struct pw_stream* m_pwStream = nullptr;
280 std::atomic<bool> m_pwError{ false };
281 GstCaps* m_caps = nullptr; // the stream's fixed caps, set at open
282 // The queue: a ring of m_ringFrames frames, written under m_lock (feeds,
283 // silence), read by OnProcess(). Positions count frames ever written or
284 // read; a flush moves m_dropTo up to m_writePos and OnProcess() skips to it.
285 std::vector<float> m_ring;
286 uint64_t m_ringFrames = 0;
287 std::atomic<uint64_t> m_writePos{ 0 };
288 std::atomic<uint64_t> m_readPos{ 0 };
289 std::atomic<uint64_t> m_dropTo{ 0 };
290 bool m_warnedFull = false;
291 // One per graph cycle, newest at m_cycleCount - 1: the queue position of
292 // the first frame given to that cycle, how many were given (the rest was
293 // silence), and when (CLOCK_MONOTONIC ns) PipeWire says the first is
294 // heard -- before the card correction below. For that correction, also
295 // the frames handed to the graph in the cycle (silence included) and in
296 // all cycles up to it, and when PipeWire says the cycle's first sample
297 // reaches the device (its time plus its delay, without what the stream
298 // itself holds). `seq` is odd while OnProcess() writes the record.
299 struct CycleRecord {
300 std::atomic<uint32_t> seq{ 0 };
301 std::atomic<uint64_t> readPos{ 0 };
302 std::atomic<uint32_t> frames{ 0 };
303 std::atomic<int64_t> heardNs{ 0 };
304 std::atomic<uint32_t> outFrames{ 0 };
305 std::atomic<uint64_t> outEnd{ 0 };
306 std::atomic<int64_t> deviceNs{ 0 };
307 };
308 static constexpr int kCycleRecords = 64;
309 CycleRecord m_cycles[kCycleRecords];
310 std::atomic<uint64_t> m_cycleCount{ 0 };
311 uint64_t m_outFrames = 0; // frames handed to the graph (OnProcess() only)
312 // How much later than PipeWire says the card really plays each cycle's
313 // samples (MeasureCardQueue()), added to every record's heardNs.
314 std::atomic<int64_t> m_cardCorrNs{ 0 };
315 // Where each feed buffer went in the queue, and its running time in the
316 // feeding pipeline (HeardRunningTime()); `speed` is the feed's media
317 // seconds per second of sound (SetFeedSpeed()). Under m_lock.
318 struct FeedSpan {
319 uint64_t queuePos;
320 uint64_t frames;
321 GstClockTime runningTime;
322 double speed;
323 GstElement* feed;
324 };
325 std::deque<FeedSpan> m_feedSpans;
326 // Nothing has been handed to the stream since it was last flushed.
327 bool m_flushed = false;
328 // The stream's timeline (ContinueTimeline()). Valid from the first feed
329 // buffer after a flush or an open for as long as what is handed over
330 // stays contiguous: m_timelineEnd is the time on m_clock at which the last
331 // sample handed over is due, in the terms a feed's position maps by.
332 bool m_timelineValid = false;
333 GstClockTime m_timelineEnd = 0;
334 // No feed is attached and the timeline is kept running with silence
335 // until m_bridgeUntilMs (Release()).
336 bool m_bridging = false;
337 uint64_t m_bridgeUntilMs = 0;
338 // When the last track was released, and how much silence the bridge has
339 // laid since (logged when the next track carries on).
340 int64_t m_releasedUs = 0;
341 GstClockTime m_bridgedNs = 0;
342 // The feed attached by ContinueTimeline() has handed nothing over yet
343 // (NoteTimelineLocked()). m_flushNow: its sound starts so far into its
344 // timeline that it is taken for a fault, and the worker flushes.
345 bool m_continuedFirst = false;
346 bool m_flushNow = false;
347 int m_rate = 0; // ...and their rate
348 bool m_warnedCaps = false; // logged a feed in the wrong format
349 GstElement* m_feed = nullptr; // appsink currently allowed to feed (no ref held)
350 std::string m_cardStatusPath; // /proc/asound/.../status of the sink's card, "" if none
351
352 // The card clock (DisciplineClock()). Created on first use, never freed.
353 GstClock* m_clock = nullptr;
354 // The feed clock (FeedClock()), and the speed it runs at against the card
355 // clock. Both are under m_lock.
356 GstClock* m_feedClock = nullptr;
357 double m_feedSpeed = 1.0;
358 // The feed clock has run at a speed other than 1 since the feed attached,
359 // so it no longer reads what the card clock does.
360 bool m_feedDiverged = false;
361 // Resampling the feed (SetFeedSpeed()): on from the first speed other than
362 // 1 to the end of the feed. m_rsPos is where the next output frame falls,
363 // in input frames from the start of the next buffer; m_rsHist the last
364 // fifteen input frames, the resampler's filter span less one (kept even
365 // while not resampling, so starting is seamless), oldest first,
366 // m_rsHistFrames of them valid.
367 bool m_rsActive = false;
368 double m_rsPos = 0.0;
369 float m_rsHist[15 * 2] = {};
370 int m_rsHistFrames = 0;
371 std::atomic<double> m_clockRate{ 1.0 };
372 std::string m_syncPath; // the card the fields below describe
373 int m_syncCardRate = 0; // its nominal rate
374 bool m_syncAnchored = false;
375 int64_t m_syncHw0 = 0; // hw_ptr at the anchor...
376 GstClockTime m_syncInt0 = 0; // ...the clock's internal time then...
377 GstClockTime m_syncExt0 = 0; // ...and its own time then
378 int64_t m_syncLastHw = 0; // hw_ptr as last read
379 int64_t m_syncWrap = 0; // added to hw_ptr for each time it wrapped
380 std::string m_syncTrigger; // the card's trigger_time as last read
381 // The card was seen stopped under a feed (an xrun): flush once it runs
382 // again (see DisciplineClock()).
383 bool m_xrunPending = false;
384 uint64_t m_lastFlushMs = 0; // NowMs() of the last Flush() (under m_lock)
385 GstClockTime m_syncLastInt = 0;
386 // (seconds of internal time, seconds of card time) since the anchor.
387 std::deque<std::pair<double, double>> m_syncWindow;
388 // MeasureCardQueue()'s state, on the worker thread only.
389 std::string m_cqPath; // the card being measured
390 std::string m_cqTrigger; // its trigger_time: a change is a restart
391 int m_cqCardRate = 0;
392 uint64_t m_cqStartMs = 0; // NowMs() when the card was seen to (re)start
393 uint64_t m_cqNextMs = 0; // NowMs() when the next reading is due
394 std::deque<int64_t> m_cqOffsets; // appl_ptr less frames handed over, last few samples
395 bool m_cqOffsetValid = false;
396 int64_t m_cqOffset = 0; // ...and the value they agree on
397 std::deque<int64_t> m_cqCorr; // the last few corrections measured
398 bool m_cqLogged = false;
399 };
400
401 #endif
402