GCC Code Coverage Report


Directory: ./
File: mediaoutput/GStreamerOut.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 10 10 100.0%
Functions: 10 10 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-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 #include "MediaOutputBase.h"
15
16 #if __has_include(<gst/gst.h>)
17 #define HAS_GSTREAMER
18
19 #include <gst/gst.h>
20 #include <gst/app/gstappsink.h>
21 #include <array>
22 #include <atomic>
23 #include <deque>
24 #include <condition_variable>
25 #include <list>
26 #include <map>
27 #include <memory>
28 #include <mutex>
29 #include <set>
30 #include <vector>
31
32 #include "AES67Manager.h"
33 #include "AtomicSharedPtr.h"
34 #include "DrmCards.h"
35 #include "FeedSyncWindow.h"
36 #include "OpusRTPManager.h"
37
38 class PixelOverlayModel;
39 class PipeWireOutputStream;
40 class VideoDisplay;
41
42 class GStreamerOutput : public MediaOutputBase {
43 public:
44 GStreamerOutput(const std::string& mediaFilename, MediaOutputStatus* status, const std::string& videoOut = "", int streamSlot = 1);
45 virtual ~GStreamerOutput();
46
47 virtual int Start(int msTime = 0) override;
48 /// Build the pipeline and decode up to its first frame now, ahead of the
49 /// Start() that plays it, so that Start() only has to set it going.
50 /// Nothing the playing output owns is touched meanwhile: not the slot's
51 /// status, not the output stream's feed, not the display's. False where
52 /// this kind of output isn't prepared (anything but a video to the
53 /// persistent display, or with AES67 sending); Start() then builds it as
54 /// usual. An output prepared and never started is simply deleted.
55 bool Prepare();
56 virtual int Stop(void) override;
57 virtual int Process(void) override;
58 virtual int Close(void) override;
59 virtual int IsPlaying(void) override;
60 virtual int AdjustSpeed(float masterPos) override;
61 // True once the reported position -- already backed up to what is leaving
62 // the card -- has moved past the start of the media.
63 874 virtual bool IsAudible(void) override { return m_audible; }
64 336 virtual uint64_t SoundEndMS(void) override { return m_soundEndMs.load(); }
65
66 /// Flush-seek to an absolute position in seconds. Audible/visible glitch,
67 /// so this is for repairing a stream that has genuinely left the show
68 /// timeline, not for routine correction. Returns false if the seek failed.
69 bool SeekTo(float seconds);
70 virtual void SetVolume(int volume) override;
71 /// SetVolume() that says whether the output took the volume: false when
72 /// it has no volume element to set -- before Start(), once its teardown
73 /// (Stop() or Close()) has begun, and for media with no sound.
74 bool TrySetVolume(int volume);
75
76 /// Ask the output's owner to stop it, from a thread that doesn't own it
77 /// (a command, or the slot manager stopping a playlist's background
78 /// slots). Only the owner may Stop()/Close()/delete an output: the base
79 /// version flags it for the next Process() on the owner's thread; Play
80 /// Media's outputs override it to stop through their own registry.
81 1 virtual void RequestStop() { m_stopRequested = true; }
82
83 /// Whether StreamSlotManager must call Process() for this output. False
84 /// for outputs whose owner already does (a playlist entry, the remote's
85 /// synced media); Play Media's outputs have no other pump.
86 56192 virtual bool NeedsSlotPump() const { return false; }
87
88 // Static methods matching SDLOutput interface
89 static bool IsOverlayingVideo();
90 static bool ProcessVideoOverlay(unsigned int msTimestamp);
91 static bool GetAudioSamples(float* samples, int numSamples, int& sampleRate);
92
93 // One-time GStreamer + PipeWire env initialization (safe to call repeatedly)
94 static void EnsureGStreamerInit();
95 // Take `pipeline` to NULL on a reaper thread, waiting at most timeoutMs.
96 // False if it wedged: the reaper keeps its own ref and the pipeline (with
97 // whatever it holds) is left to it. The caller's ref is untouched.
98 static bool SetPipelineToNullBounded(GstElement* pipeline, int timeoutMs);
99 // Set the environment now, on the calling thread, and run gst_init() in the
100 // background so the first play doesn't pay for it (~1 s on an AM335x, and
101 // ~20 s the very first time, when GStreamer builds its plugin registry).
102 static void PreloadAsync();
103 // Make every videoconvert in `pipeline` -- including ones added later --
104 // read decoded frames from padded system memory rather than straight out
105 // of a hardware decoder's buffers. See the comment at the definition.
106 // Also has each decodebin note a hardware video decoder it chooses, for
107 // the wedge ladder.
108 static void GuardVideoConvertInputs(GstElement* pipeline);
109
110 // The PipeWire sink a slot's audio is routed to ("" = PipeWire's default).
111 static std::string PipeWireSinkNameForSlot(int slot);
112 // The rate the PipeWire graph runs at (48000 if it can't be determined).
113 static int PipeWireGraphRate();
114 // /proc/asound status file of a card the PipeWire sink `sinkName` (a group
115 // or an fpp_alsa_* adapter) plays into, or "" if it reaches no card -- a
116 // group of network senders only, or PipeWire's unnamed default sink.
117 static std::string AlsaSinkStatusPath(const std::string& sinkName);
118
119 // Resolve connector name (e.g., "HDMI-A-1") to DRM card path, connector ID,
120 // and display resolution by scanning sysfs. Works on all Pi models.
121 struct DrmConnectorInfo {
122 std::string cardPath; // e.g. "/dev/dri/card1"
123 int connectorId = -1; // integer ID for kmssink
124 bool connected = false;
125 int displayWidth = 0;
126 int displayHeight = 0;
127 int primaryPlaneId = -1; // DRM primary plane for this connector's CRTC
128 };
129 static DrmConnectorInfo ResolveDrmConnector(const std::string& connectorName);
130
131 // What went wrong, from a GStreamer error message: the last line of its
132 // debug text, which names the cause ("drmModeSetPlane failed: No space
133 // left on device (28)"), where the message itself is generic.
134 static std::string ErrorReason(const GError* err, const gchar* debug);
135
136
137 // GStreamer-specific
138 1882 void SetLoopCount(int loops) { m_loopCount = loops; }
139 // Whether this output's position paces the running sequence (the channel
140 // output servo). True for the show's own media -- a playlist entry's, or
141 // a remote's synced media -- and false for media played alongside it.
142 1882 void SetDrivesShowClock(bool drives) { m_drivesShowClock = drives; }
143 void SetVolumeAdjustment(int volAdj);
144
145 // Event callbacks (matching VLCOutput pattern).
146 //
147 // Playing(), Stopping() and Stopped() are called from Stop() and also from
148 // BusSyncHandler, on the GStreamer streaming thread that delivered the
149 // message, while that thread still holds the sink's internal locks. An override must only
150 // record state or hand work to the main loop (Timers): anything that
151 // seeks, changes pipeline state, stops or closes an output -- including
152 // running a command preset, which can do all of those -- deadlocks there.
153 2161 virtual void Starting() {}
154 917 virtual void Playing() {}
155 2405 virtual void Stopping() {}
156 2272 virtual void Stopped() {}
157
158 private:
159 // Serializes Start(), Stop() and Close() against each other and against
160 // Process(), SeekTo() and AdjustSpeed(), which a slot's pump and MultiSync
161 // run on the main loop while a command may be stopping the same output on
162 // an HTTP thread. The pump side only ever try-locks and skips a tick when
163 // the output is busy, so it never waits here; holders may take
164 // StreamSlotManager's lock, never the other way round.
165 std::recursive_mutex m_opMutex;
166 std::atomic<bool> m_stopRequested{false};
167
168 // Prepare(): Start() building without the side effects of playing,
169 // which StartPrepared() applies later, and what it set aside for them.
170 bool m_preparing = false;
171 // Read on streaming threads: a prepared output's errors are its own
172 // business until it plays (BusSyncHandler()).
173 std::atomic<bool> m_prepared{false};
174 std::atomic<bool> m_pipelineFailed{false}; // the bus reported a fatal error
175 // Started playing on its slot (ClaimSlot()). A prepared output thrown
176 // away unplayed never did: the slot's status, and the audio group delay
177 // lines and AES67 sends, belong to the track that is playing.
178 std::atomic<bool> m_claimedSlot{false};
179 bool OwnsSlotStatus();
180 // The delay-line and AES67 flushes a start makes between drained tracks,
181 // held back because this one will most likely carry on the output
182 // stream's timeline; made by the start thread if it doesn't after all.
183 bool m_flushesDeferred = false;
184 static void StartFlushes();
185 // When the end of the media's sound is heard (set at its end of stream).
186 std::atomic<uint64_t> m_soundEndMs{0};
187 std::atomic<bool> m_feedsStream{false}; // Go() attached m_pwFeed to m_pwStream
188 // OnNoMorePads() found no picture: the display is given back on the
189 // main loop (Process(), StartPrepared()), which owns m_display, not on
190 // the streaming thread that found out.
191 std::atomic<bool> m_releaseDisplayPending{false};
192 // Prepared with its sound sent to the output stream before its channel
193 // count was known; OnPadAdded() checks it (see Start()).
194 std::atomic<bool> m_prepareCheckChannels{false};
195 int m_preparedTotalSecs = -1;
196 std::string m_preparedSinkName;
197 double m_preparedTargetVolume = 1.0;
198 int StartPrepared();
199 // The part of Start() that sets a built pipeline playing.
200 int Go(int msTime, const std::string& pipelineSinkName, double targetVolume);
201
202 // An optional video branch -- a secondary display's kmssink, or the
203 // PipeWire video tap -- whose sink failed. Its GST_FLOW_ERROR would
204 // otherwise reach the tee and fail the whole pipeline, so the bus sync
205 // handler cuts it off at the tee (CutFailedBranch, on the failing sink's
206 // streaming thread) and Process() takes it out of the pipeline
207 // (RemoveFailedBranches, op lock held). Holds a ref on every object.
208 struct FailedBranch {
209 GstElement* tee = nullptr;
210 GstPad* teePad = nullptr;
211 std::vector<GstElement*> elements; // sink first, back to the queue
212 };
213 std::mutex m_failedBranchLock;
214 std::vector<FailedBranch> m_failedBranches;
215 std::atomic<bool> m_haveFailedBranches{false};
216 bool CutFailedBranch(GstElement* sink);
217 // The head of an optional branch, between the tee and the branch's
218 // queue: turns a sink's GST_FLOW_ERROR into OK, so even a buffer already
219 // waiting on the branch's full queue can't carry it back to the tee.
220 // nullptr where errorignore isn't installed.
221 static GstElement* MakeBranchErrorGuard();
222 void RemoveFailedBranches();
223 void ReleaseFailedBranches();
224 bool m_drivesShowClock = true;
225 // Cuts the decodebin and bus callbacks off from this object and waits for
226 // any that are running. See CallbackGuard.
227 void DetachCallbacks();
228 // This output's id for its PixelOverlayManager model listener.
229 std::string OverlayListenerId() const;
230
231 GstElement* m_pipeline = nullptr;
232 GstElement* m_volume = nullptr;
233 GstElement* m_appsink = nullptr; // audio sample tap
234 GstElement* m_videoAppsink = nullptr; // video frame sink for PixelOverlay
235 GstBus* m_bus = nullptr;
236 std::string m_videoOut;
237 int m_loopCount = 0;
238 int m_volumeAdjust = 0;
239 // Per-file loudness gain from the File Manager's Normalize (linear, 1.0
240 // = as recorded), looked up in media_gain.json when the song starts and
241 // multiplied into every value set on m_volume. See LookupNormalizeGain().
242 double m_fileGain = 1.0;
243 std::atomic<bool> m_playing{false}; // written from GStreamer thread (BusSyncHandler), read from main loop
244 std::atomic<bool> m_shutdownFlag{false}; // guards callbacks during teardown
245 bool m_teardownComplete = false; // makes Stop() idempotent — the expensive pipeline teardown (silence flush + DRM release sleeps) must run only once even when Stop() is called both directly and via Close()/dtor
246 // Set when the supervised pipeline-NULL transition timed out and the
247 // pipeline was abandoned to a reaper thread (wedged V4L2 decoder, issue
248 // #2695). Close() must then leak the pipeline's DRM planes and shared
249 // DRM fd refs — the still-alive kmssinks own them in the kernel.
250 bool m_teardownAbandoned = false;
251 // Cancellation token for the detached Start() PLAYING-transition thread.
252 // Shared (shared_ptr) so the thread can safely outlive this object: Stop()
253 // sets it to abort the volume ramp / deferred attach early, and the thread
254 // captures only this token (never `this`), eliminating use-after-free if it
255 // is still running when the object is torn down.
256 std::shared_ptr<std::atomic<bool>> m_startThreadCancel;
257 // Set while the Start() thread has yet to seek to a non-zero start
258 // position. The pipeline prerolls at 0 first, and Process() must not
259 // report that 0 as the media position (see Start()). Shared for the same
260 // reason as m_startThreadCancel.
261 std::shared_ptr<std::atomic<bool>> m_startSeekPending;
262 gulong m_appsinkSignalId = 0; // audio appsink signal handler ID
263 gulong m_videoAppsinkSignalId = 0; // video appsink signal handler ID
264
265 // Stall watchdog — detects when PipeWire sink stops consuming data.
266 // The *Ms stamps here are GetMonotonicTimeMS(): on the wall clock a step
267 // either way made the watchdogs stop playing media as stalled.
268 gint64 m_lastPosition = -1;
269 gint64 m_maxDuration = 0; // highest observed duration (handles VBR fluctuations)
270 uint64_t m_durationQueriedMs = 0;
271 uint64_t m_stallStartMs = 0;
272 uint64_t m_wallStartMs = 0;
273 // A SeekTo() that arrived before the pipeline prerolled, applied by
274 // Process() at the first position. -1 when none is waiting.
275 gint64 m_pendingSeekNs = -1;
276 uint64_t m_lastWallLogMs = 0;
277
278 // Audio still queued between pipewiresink's reported position and the DAC.
279 // Cached: the depth barely moves while a track plays, and Process() runs at
280 // frame rate. *notRunning (if given) is set when the card hasn't started
281 // playing this track yet -- opening, or waking from suspend -- so none of
282 // it is heard.
283 int64_t AudioSinkLatencyNs(bool* notRunning = nullptr);
284 // One-shot note that the position is going out uncorrected, and why.
285 void NoteNoSinkLatency(const std::string& why);
286 int64_t m_sinkLatencyNs = 0;
287 uint64_t m_sinkLatencyCheckedMs = 0;
288 std::string m_alsaStatusPath;
289 std::string m_alsaHwParamsPath;
290 int m_alsaRate = 0;
291 bool m_loggedSinkLatency = false;
292 bool m_sinkSeenRunning = false; // AudioSinkLatencyNs() has seen the card play this track
293 // The latency Process() last backed the position up by, when it was
294 // measured from the output stream, and when (GetMonotonicTimeMS(); 0:
295 // never). AdjustFeedSpeed() reads the position the same way.
296 int64_t m_measuredLatNs = 0;
297 uint64_t m_measuredLatMs = 0;
298 bool m_warnedNoSinkLatency = false;
299 uint64_t m_playStartMs = 0; // when Start() set m_playing=true (GetMonotonicTimeMS()) — anchors the preroll watchdog
300 static constexpr int STALL_TIMEOUT_MS = 5000; // 5 seconds before declaring stall
301 // Preroll watchdog: if the pipeline is set to PLAYING but never produces a
302 // valid position (never actually starts), it is wedged in preroll/PAUSED —
303 // e.g. the Pi's V4L2 hardware decoder can stop producing frames after a very
304 // long video-only loop (issue #2695), so the video sink never prerolls and
305 // the pipeline stays PAUSED forever. The regular stall watchdog can't catch
306 // this because it only runs once a position is available. Generous timeout:
307 // normal preroll completes in well under 1s even on slow HW decoders.
308 static constexpr int PREROLL_TIMEOUT_MS = 15000;
309
310 void ProcessMessages();
311 static GstBusSyncReply BusSyncHandler(GstBus* bus, GstMessage* msg, gpointer userData);
312
313 // Audio sample tap for WLED audio-reactive effects
314 static constexpr int SAMPLE_BUFFER_SIZE = 4096; // circular buffer size
315 static std::array<float, SAMPLE_BUFFER_SIZE> s_sampleBuffer;
316 static int s_sampleWritePos;
317 static int s_sampleRate;
318 // Guards the ring above and m_currentInstance, the one output allowed to
319 // write it.
320 static std::mutex s_sampleMutex;
321 // When the tap owner last wrote the ring. A paused or stalled owner
322 // stops writing, and its last half second of audio must not read as
323 // live.
324 static uint64_t s_sampleLastWriteMs;
325 static constexpr int SAMPLE_STALE_MS = 500;
326 // Make `o` the tap owner and empty the ring. s_sampleMutex held.
327 static void SetSampleTapOwnerLocked(GStreamerOutput* o);
328 static GstFlowReturn OnNewSample(GstAppSink* appsink, gpointer userData);
329 // The tap's branch only carries audio while something is reading it.
330 static constexpr int SAMPLE_TAP_IDLE_MS = 1000;
331 static std::atomic<uint64_t> s_sampleTapReadMs;
332 static GstPadProbeReturn GateSampleTap(GstPad* pad, GstPadProbeInfo* info, gpointer userData);
333
334 // Video overlay for PixelOverlayModel (Phase 3)
335 PixelOverlayModel* m_videoOverlayModel = nullptr;
336 std::mutex m_videoOverlayModelLock;
337 int m_videoOverlayWidth = 0;
338 int m_videoOverlayHeight = 0;
339 // Read by the channel output thread through the overlay registry
340 // (IsOverlayingVideo(), ProcessVideoOverlay()) while Close() and a removed
341 // video branch clear it, before the output leaves the registry.
342 std::atomic<bool> m_hasVideoStream{false};
343 bool m_wasOverlayDisabled = false;
344
345 // Latest video frame buffer — written by OnNewVideoSample, read by ProcessVideoOverlay
346 std::vector<uint8_t> m_videoFrameData;
347 // The channel output thread's side of the handoff: PushVideoOverlayFrame()
348 // swaps it with m_videoFrameData under m_videoFrameMutex instead of copying
349 // the frame, and the sample callback then refills the other one. Only the
350 // overlay push touches it (serialized by m_overlayOutputsLock).
351 std::vector<uint8_t> m_videoOverlayFrame;
352 int m_videoFrameWidth = 0; // dimensions of m_videoFrameData (packed RGB)
353 int m_videoFrameHeight = 0;
354 std::mutex m_videoFrameMutex;
355 bool m_videoFrameReady = false;
356 uint64_t m_videoFramesReceived = 0; // diagnostic counter
357 uint64_t m_videoFramesDelivered = 0; // diagnostic counter
358
359 static GstFlowReturn OnNewVideoSample(GstAppSink* appsink, gpointer userData);
360
361 // HDMI/DRM video output via kmssink (Phase 4)
362 bool m_wantHDMI = false; // true when outputting to HDMI via kmssink
363 bool m_macVideoWindow = false; // macOS: the "HDMI" output is this slot's video window
364 GstElement* m_kmssink = nullptr; // kmssink element (owned by pipeline bin)
365 int m_hdmiConnectorId = -1; // DRM connector ID from sysfs
366 std::string m_hdmiCardPath; // e.g. "/dev/dri/card1"
367 // The DRM lease of each of this pipeline's kmssinks (the primary one and
368 // any dkms_* branches). Released in Close(), strictly after the pipeline
369 // (and therefore every kmssink) has been unreffed.
370 std::vector<DrmCards::Lease> m_drmLeases;
371 // HDMI connectors this pipeline claimed from the video output manager's
372 // persistent consumers (ClaimConnectorForMedia); released in Close()
373 // after the leases, which brings those consumers back.
374 std::vector<int> m_mediaConnectors;
375 int m_hdmiDisplayWidth = 0; // display resolution
376 int m_hdmiDisplayHeight = 0;
377 // The primary display, when it runs on its own pipeline (VideoDisplay.h)
378 // rather than as a kmssink here. m_kmssink is then the appsink feeding
379 // it, and this pipeline holds no DRM resources of its own.
380 std::shared_ptr<VideoDisplay> m_display;
381 uint64_t m_displayFeedToken = 0;
382 // Stop feeding the display and give it back. It keeps showing the last
383 // frame while the next video (prepared ahead) holds it, and closes once
384 // nothing does.
385 void ReleaseDisplay();
386
387 // PipeWire video routing — when PipeWireVideoSinkName is set, video is
388 // tee'd to both kmssink (HDMI) and pipewiresink (PipeWire graph node).
389 std::string m_pwVideoSinkName; // target-object for video pipewiresink
390 bool m_videoPipeWireRouting = false; // true when video goes through PipeWire
391 std::set<int> m_directConnectorIds; // HDMI connectors driven by direct kmssink on vtee
392
393 // Dynamic pad linking for decodebin (video requires pad-added signal)
394 //
395 // decodebin emits these from its own streaming thread, on a pipeline that
396 // can outlive this GStreamerOutput: Start() hands an owning pipeline ref to
397 // a detached state-change thread, so Close()/~GStreamerOutput can complete
398 // while decodebin is still exposing pads. The callbacks therefore must not
399 // dereference `this` directly. Each Start() allocates a fresh guard whose
400 // `self` Close() clears while holding `mtx`; a callback holding a shared_ptr
401 // to it either runs to completion before that clear or sees nullptr and
402 // returns. Old pipelines keep their own (already cleared) guard, so a
403 // restarted output is never reached through a stale connection.
404 //
405 // The bus sync handler runs on streaming threads too, and gets the same
406 // guard -- but it does not hold `mtx` while it works. It registers itself
407 // in `busInFlight` instead, and Close() waits for that to drain after
408 // clearing `self`. Holding the lock across a handler would let one
409 // streaming thread block another inside GStreamer. `mtx` is recursive
410 // because OnNoMorePads changes element state while holding it, and the
411 // resulting bus messages reach BusSyncHandler on that same thread.
412 struct CallbackGuard {
413 std::recursive_mutex mtx;
414 GStreamerOutput* self = nullptr;
415 int busInFlight = 0;
416 std::condition_variable_any busIdle;
417 };
418 // Written only under m_opMutex (Start(), DetachCallbacks()), but read
419 // without it by RefVolumeElement() and from streaming threads.
420 AtomicSharedPtr<CallbackGuard> m_cbGuard;
421 GstElement* RefVolumeElement();
422 // Connects pad-added (and optionally no-more-pads) on `decoder`, passing a
423 // guard reference as the closure data. Takes no ref on `decoder`.
424 void ConnectPadSignals(GstElement* decoder, bool wantNoMorePads);
425 static void ReleaseCallbackGuard(gpointer data, GClosure* closure);
426 // GDestroyNotify for the guard reference handed to gst_bus_set_sync_handler.
427 static void ReleaseBusCallbackGuard(gpointer data);
428 // Restarts the output from the top for its next loop. Called from
429 // BusSyncHandler on EOS, it does the seek on the main loop: a flushing
430 // seek issued from the thread that delivered the EOS deadlocks, because
431 // that thread still holds the sink's preroll lock and the flush needs it.
432 static void ScheduleLoopSeek(const std::shared_ptr<CallbackGuard>& guard);
433 // Resolves the closure data back to a live output. Returns nullptr (with
434 // `lock` left unlocked) once the owning Close() has run.
435 static GStreamerOutput* LockCallbackGuard(gpointer userData,
436 std::shared_ptr<CallbackGuard>& guard,
437 std::unique_lock<std::recursive_mutex>& lock);
438 // Keeps the output alive for one BusSyncHandler call. `self` is nullptr
439 // once Close() has run; otherwise Close() blocks until this is destroyed.
440 struct BusCallbackScope {
441 explicit BusCallbackScope(gpointer userData);
442 ~BusCallbackScope();
443 std::shared_ptr<CallbackGuard> guard;
444 GStreamerOutput* self = nullptr;
445 };
446 static void OnPadAdded(GstElement* element, GstPad* pad, gpointer userData);
447 static void OnNoMorePads(GstElement* element, gpointer userData);
448 GstElement* m_audioChain = nullptr; // audio sub-bin for pad linking
449 GstElement* m_videoChain = nullptr; // video sub-bin for pad linking
450 bool m_audioLinked = false; // true when audio pad was connected
451 bool m_videoLinked = false; // true when video pad was connected
452
453 // True when Start() built the audio-only fallback (no video output for this
454 // item), which is the one pipeline shape that cannot survive a file with no
455 // playable audio -- see the no-audio handling in BusSyncHandler().
456 bool m_audioOnlyPipeline = false;
457 // Whether decodebin ever exposed a decoded audio pad. Written on the
458 // streaming thread from OnPadAdded, read on the bus thread.
459 std::atomic<bool> m_sawAudioPad{false};
460 // Set once the "file has no playable audio" case has been reported, so the
461 // demuxer's follow-on "Internal data stream error" is not logged as a second,
462 // unrelated-looking failure.
463 std::atomic<bool> m_reportedNoAudio{false};
464
465 // A banner is up for this run's failure. The first one wins: the errors
466 // after it (a demuxer's follow-on) describe the same event.
467 std::atomic<bool> m_reportedFailure{false};
468 void ReportFileFailure(const char* what, const std::string& reason);
469 void ReportVideoOutputFailure(const char* sinkName, const std::string& reason);
470 // dkms_<id> -> its connector's name, for that banner. Built before the pipeline runs.
471 std::map<int, std::string> m_dkmsConnectorNames;
472 // dkms_<id> -> the card it drives, for AspectMismatchWarning().
473 std::map<int, std::string> m_dkmsCardPaths;
474
475 #ifdef HAS_AES67_GSTREAMER
476 // Zero-hop AES67 RTP branches attached to the audio tee (Phase 7.9)
477 std::vector<AES67Manager::InlineRTPBranch> m_aes67Branches;
478 void AttachAES67Branches(GstElement* tee);
479 void DetachAES67Branches();
480 #endif
481
482 // Flush PipeWire filter-chain delay buffers between songs
483 static void FlushPipeWireDelayBuffers();
484 static int FindPipeWireNodeId(const std::string& key, const std::string& value);
485 static void SetPipeWireStreamRate(const std::string& streamId, float rate);
486
487 // ── Phase 5: MultiSync rate adjustment (ported from VLCOut) ──
488 bool m_allowSpeedAdjust = true;
489 float m_currentRate = 1.0f;
490
491 // Circular buffer of last MAX_DIFFS diff/rate pairs for trend detection
492 static constexpr int MAX_DIFFS = 10;
493 std::array<std::pair<int, float>, MAX_DIFFS> m_diffs{};
494 int m_diffsSize = 0;
495 int m_diffIdx = 0;
496 int m_diffSum = 0;
497 float m_rateSum = 0.0f;
498
499 void pushDiff(int diff, float rate);
500
501 int m_lastDiff = -1; // init at -1 so speedup/slowdown logic initially assumes slightly behind master
502 int m_rateDiff = 0;
503
504 // Running rate average (smooths jitter)
505 static constexpr int RATE_AVERAGE_COUNT = 20;
506 std::list<float> m_lastRates;
507 float m_lastRatesSum = 0.0f;
508
509 // Apply playback rate change via GStreamer instant-rate-change seek
510 void ApplyRate(float rate);
511 // fpp.stream.id of this pipeline's own pipewiresink, if it has one
512 std::string m_pwSinkStreamId;
513
514 // A video whose sound feeds the output stream: its picture is held back by
515 // as long as its sound takes to be heard (AlignPictureToSound(), given
516 // that whole delay), and a video that turns out to have no sound hands
517 // the stream back from the main loop.
518 void AlignPictureToSound(int64_t latNs);
519 int64_t m_pictureDelayNs = 0;
520 // How many of a pixel overlay video's frames were dropped late.
521 void LogVideoOverlayDrops();
522 // A track that carried on the output stream's timeline
523 // (PipeWireOutputStream::ContinueTimeline()) runs on a base time a feed
524 // lead earlier than its sound, with its feed's ts-offset at 0 rather than
525 // minus that lead: a sink can't render a buffer before its base time, so a
526 // negative ts-offset can't hand the first buffers over early, and the
527 // first of them would come only as the stream ran out. This is that lead
528 // while it applies, 0 otherwise: added to the picture's delay and taken off
529 // the position, so both still meet the sound. Shared with the start
530 // thread, which sets it.
531 std::shared_ptr<std::atomic<int64_t>> m_timelineShiftNs;
532 // The start thread's carrying on the timeline and a flushing seek's
533 // EndTimelineShift() take turns under `lock`; a seek that comes first
534 // marks it `ended`, and the start thread then starts the track drained
535 // rather than put the timeline's base time back after the seek.
536 struct TimelineHandover {
537 std::mutex lock;
538 bool ended = false;
539 };
540 std::shared_ptr<TimelineHandover> m_timelineHandover;
541 // Back to the usual feed offset, before a flushing seek starts the
542 // pipeline's running time again.
543 void EndTimelineShift();
544 std::atomic<bool> m_pwFeedOrphaned{ false };
545
546 // A MultiSync remote's media through the persistent output stream: held to
547 // the master by the speed of the stream's feed (see AdjustFeedSpeed()).
548 int AdjustFeedSpeed(float masterMediaPosition);
549 double m_feedSpeedErrInt = 0.0; // integral of the error, s*s
550 uint64_t m_feedSpeedLastMs = 0; // when the servo last ran
551 uint64_t m_feedResyncMs = 0; // when the last resync seek was made
552 bool m_feedResyncLanding = false; // the next error is how far it landed off
553 FeedSyncWindow m_feedErrWindow; // the last two seconds of error readings
554 // How far ahead of the master a resync seek aims: what a flushing seek
555 // takes to be heard again. Learnt from each landing, for the whole run.
556 static double s_feedResyncLeadS;
557 // A video's seeks are not alike: an accurate seek decodes from the
558 // previous keyframe, so what one takes depends on where its target falls
559 // and no single lead fits. Its lead is learnt per media (a lead learnt on
560 // one file carried into the next and kept it seeking), and a media that
561 // keeps missing stops seeking and is steered by speed alone.
562 double m_feedVideoLeadS = 0.06;
563 std::deque<uint64_t> m_feedSeekTimesMs; // this media's recent resync seeks
564 bool m_feedSeekGaveUp = false;
565 // A remote's sound reaches its card later or sooner than the master's
566 // does: each box's stream, graph and card add their own delay, and a
567 // track starting on both at once is heard that far apart. What its first
568 // readings say it was off is how much earlier (> 0: started that far in)
569 // or later (< 0: held) the next prepared track starts (StartPrepared()).
570 int m_startAdjustMs = 0; // what this track's start was moved by
571 int m_startSeekAdjMs = 0; // of that, what Go() still has to seek
572 bool m_startErrPending = false; // its first agreed error is still to learn from
573 // Starting a track part-way in is a seek, and one made as it starts takes
574 // tens of ms that vary from track to track: the prepare thread makes it
575 // instead, unless the track is claimed first and Go() has to.
576 struct PreparedSeek {
577 std::mutex lock;
578 enum { Pending, Done, Taken } state = Pending;
579 };
580 std::shared_ptr<PreparedSeek> m_preparedSeek;
581
582 int m_streamSlot = 1; // stream slot number (1-5), determines PipeWire node name
583
584 // Audio-only PipeWire playback feeds the slot's persistent output stream
585 // through this appsink instead of owning a pipewiresink (see
586 // PipeWireOutputStream.h). Both null on every other path.
587 PipeWireOutputStream* m_pwStream = nullptr;
588 GstElement* m_pwFeed = nullptr;
589 // Go() acquired m_pwStream. A prepared output that never played must
590 // not give back a use of the stream it never took.
591 bool m_pwStreamAcquired = false;
592 void ReleasePipeWireStream();
593
594 std::atomic<bool> m_audible{false};
595
596 // The output whose audio feeds the WLED tap. Only read or written
597 // under s_sampleMutex, and never dereferenced by the tap's reader: the
598 // owner can be closing on another thread.
599 static GStreamerOutput* m_currentInstance;
600
601 // Every output currently driving a PixelOverlay model. The overlay push
602 // is per-output, unlike the WLED audio tap, so it cannot hang off
603 // m_currentInstance -- slot 1 always claims that, which left a companion
604 // stream's model receiving nothing.
605 static std::mutex m_overlayOutputsLock;
606 static std::vector<GStreamerOutput*> m_overlayOutputs;
607 bool PushVideoOverlayFrame();
608 };
609
610 #endif
611