GCC Code Coverage Report


Directory: ./
File: mediaoutput/VideoOutputManager.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 32 32 100.0%
Functions: 6 6 100.0%
Branches: 18 30 60.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 <atomic>
15 #include <chrono>
16 #include <condition_variable>
17 #include <map>
18 #include <memory>
19 #include <mutex>
20 #include <set>
21 #include <string>
22 #include <thread>
23 #include <vector>
24
25 #include <arpa/inet.h>
26
27 #include "DrmCards.h"
28
29 #if __has_include(<gst/gst.h>)
30 #define HAS_GSTREAMER_VIDEO_OUTPUT
31 #include <gst/gst.h>
32 #include <gst/app/gstappsink.h>
33 #endif
34
35 class PixelOverlayModel;
36
37 /**
38 * A sub-region of the source frame, as fractions (0.0-1.0) of its width and
39 * height. Fractions rather than pixels so one configuration works for any
40 * source resolution — the pixel crop is computed from the negotiated caps at
41 * runtime, and re-computed if the source resolution changes mid-stream.
42 *
43 * Used to split one decoded video across several displays: give each output a
44 * different region (e.g. left half / right half of a 3840x1080 file) and each
45 * shows its own slice of a single decode.
46 */
47 struct VideoCropRect {
48 double x = 0.0;
49 double y = 0.0;
50 double width = 1.0;
51 double height = 1.0;
52
53 /// When > 0, the selected region is narrowed further -- centred -- until
54 /// its width:height matches this ratio. That is how "fill" scaling is
55 /// expressed: crop the source to the display's shape so the
56 /// aspect-preserving scale that follows covers the display exactly, with
57 /// nothing letterboxed. Resolved against the negotiated caps alongside
58 /// the fractions above, so it costs no extra element. 0 leaves the
59 /// region exactly as selected ("fit").
60 double targetAspect = 0.0;
61
62 /// True when this selects the whole frame, i.e. no crop element is needed.
63 /// A target aspect always needs one: whether it actually trims anything
64 /// depends on the source resolution, which is not known until caps arrive.
65 1007 bool IsFullFrame() const {
66 2013 return targetAspect <= 0.0 &&
67
8/10
✓ Branch 0 taken 1006 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 1005 times.
✓ Branch 3 taken 1 times.
✓ Branch 4 taken 1005 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 1004 times.
✓ Branch 7 taken 1 times.
✓ Branch 8 taken 1004 times.
✗ Branch 9 not taken.
1007 x <= 0.0 && y <= 0.0 && width >= 1.0 && height >= 1.0;
68 }
69
70 /// True when the values describe a usable region. A zero/negative extent
71 /// or one starting past the right/bottom edge would crop everything away.
72 5 bool IsValid() const {
73
3/6
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 5 times.
✗ Branch 5 not taken.
5 return width > 0.0 && height > 0.0 && x >= 0.0 && y >= 0.0 &&
74
3/6
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 5 times.
✗ Branch 5 not taken.
10 (x + width) <= 1.0001 && (y + height) <= 1.0001;
75 }
76 };
77
78 /**
79 * VideoOutputManager — manages PipeWire video consumer pipelines.
80 *
81 * Each video output destination (HDMI display, pixel overlay, network stream)
82 * runs a GStreamer consumer pipeline:
83 * pipewiresrc → videoconvert → videoscale → destination sink
84 *
85 * Consumer pipelines are started on-demand when a video producer appears
86 * (GStreamerOut calls StartConsumers after pipewiresink is attached) and
87 * stopped when playback ends (StopConsumers). The pipewiresrc target-object
88 * is set to the producer's node name so PipeWire links them automatically.
89 *
90 * Config file: $mediaDirectory/config/pipewire-video-consumers.json
91 */
92 class VideoOutputManager {
93 public:
94 static VideoOutputManager& Instance();
95
96 /// Load config at startup. Does NOT start consumer pipelines.
97 void Init();
98
99 /// Reload config (called when Apply is triggered from UI).
100 /// If consumers are currently running, restarts them with new config.
101 void Reload();
102
103 /// Stop all consumer pipelines and clean up.
104 void Shutdown();
105
106 /// Info about an HDMI consumer for direct kmssink attachment.
107 struct HdmiConsumerInfo {
108 int connectorId = -1;
109 std::string connector; // e.g. "HDMI-A-2"
110 std::string cardPath;
111 int width = 0;
112 int height = 0;
113 int primaryPlaneId = -1; // DRM primary plane for this connector's CRTC
114 VideoCropRect crop; // region of the source this display shows
115 // "fit", "fill" or "stretch". "fill" needs nothing here -- it is
116 // already folded into `crop` as a target aspect -- but "stretch" has
117 // to defeat the aspect-preserving scale kmssink always does, so the
118 // caller needs to know about it. See CreateScaleElements.
119 std::string scaling = "fit";
120 };
121
122 /// True when an overlay or RTP member of a playback group (no fixed
123 /// source) takes stream slot `streamSlot`. Those read the slot's
124 /// intervideo channel, which media playback publishes only when asked.
125 bool HasSlotChannelConsumers(int streamSlot) const;
126
127 /// Return HDMI consumer info for consumers that match the given stream
128 /// slot but whose connectorId is NOT in skipConnectorIds.
129 std::vector<HdmiConsumerInfo> GetHdmiConsumers(
130 int streamSlot,
131 const std::set<int>& skipConnectorIds = {}) const;
132
133 /// Region configured for the display on `connectorId`, whole frame if none.
134 /// Unlike GetHdmiConsumers this does not skip the connector driven by the
135 /// primary pipeline — that display is one half of a split too, so its
136 /// kmssink needs the crop even though no consumer pipeline is started for
137 /// it. Matches the on-demand consumer entries and the stream-slot filter
138 /// exactly as GetHdmiConsumers does.
139 VideoCropRect GetHdmiCropForConnector(int streamSlot, int connectorId) const;
140
141 /// Scaling mode configured for the display on `connectorId`, "fit" if none.
142 /// Matches entries exactly as GetHdmiCropForConnector does, and for the
143 /// same reason: the primary display is a configured output too.
144 std::string GetHdmiScalingForConnector(int streamSlot, int connectorId) const;
145
146 /// The warning text naming the resolution to set when a kmssink on
147 /// `display` ("HDMI-A-1") failed with `reason` because of the display's
148 /// screen shape (DrmCards::CheckAspectMismatch), else "". On failure only.
149 static std::string AspectMismatchWarning(const std::string& display, const std::string& cardPath,
150 int connectorId, const std::string& reason);
151
152 #ifdef HAS_GSTREAMER_VIDEO_OUTPUT
153 /// Build a videocrop element that resolves `crop` against the negotiated
154 /// caps at runtime. Returns nullptr when the whole frame is selected (no
155 /// element needed) or when the crop is invalid/videocrop is unavailable.
156 /// The caller owns the floating ref — add it to a bin as usual.
157 ///
158 /// Place it immediately upstream of kmssink: kmssink advertises
159 /// GstVideoCropMeta, so videocrop then crops by metadata (it becomes the
160 /// DRM plane's source rectangle, applied by the display hardware during
161 /// scanout) instead of copying pixels. With any other element in between
162 /// it silently falls back to a full per-frame copy.
163 static GstElement* CreateCropElement(const VideoCropRect& crop,
164 const std::string& name);
165
166 /// Elements needed upstream of kmssink to honour `scaling`, in link order.
167 ///
168 /// Empty for "fit" and "fill": kmssink always scales its input to the
169 /// display preserving aspect ratio, which IS "fit", and "fill" is reached
170 /// by handing it an already display-shaped region (VideoCropRect::
171 /// targetAspect) so that same scale covers the display exactly. Both are
172 /// free -- the DRM plane does the scaling during scanout.
173 ///
174 /// "stretch" is the one mode the sink cannot express: kmssink has no
175 /// force-aspect-ratio property, so the frame has to arrive already at the
176 /// display's exact size. That costs a real videoscale pass, and the
177 /// display size has to be known -- with displayWidth/Height <= 0 the mode
178 /// is dropped back to "fit" rather than guessed at.
179 ///
180 /// Place these AFTER any crop element (the region must be selected at
181 /// source resolution, before anything rescales the frame) and before the
182 /// sink. The caller owns the floating refs.
183 static std::vector<GstElement*> CreateScaleElements(const std::string& scaling,
184 int displayWidth,
185 int displayHeight,
186 const std::string& namePrefix);
187 #endif
188
189 /// Start all configured consumers targeting the given producer node.
190 /// Called by GStreamerOut after pipewiresink is attached to PipeWire graph.
191 /// HDMI connectors the producer's own kmssinks drive were claimed with
192 /// ClaimConnectorForMedia() and are skipped.
193 /// producerGeneration: ProducerGeneration() as read when the producer was
194 /// set up; if StopConsumers() has run since, the producer is gone and
195 /// nothing is started. 0 skips the check.
196 void StartConsumers(const std::string& producerNodeName,
197 uint64_t producerGeneration = 0);
198
199 /// Stop all running consumer pipelines.
200 /// Called by GStreamerOut when video playback ends. Overlay and RTP
201 /// members are parked rather than torn down -- PAUSED, showing nothing,
202 /// the model handed back -- and kept for LINGER_MS, so the next video
203 /// needn't build them again.
204 void StopConsumers();
205
206 /// Media is about to start on this slot (a video was opened, or a
207 /// scheduled playlist is near): build the slot's overlay and RTP members
208 /// now, PAUSED, so that StartConsumers() only has to set them PLAYING,
209 /// and keep them for holdMs if no video comes. Building one takes about
210 /// half a second on a BeagleBone; done here it overlaps the producer's
211 /// own start. Never blocks: the work is done on the warm worker.
212 void Prewarm(int streamSlot, int holdMs);
213
214 /// How long a parked or prewarmed member is kept, as the audio stream
215 /// lingers (PipeWireOutputStream::LINGER_MS).
216 static constexpr int LINGER_MS = 5000;
217
218 /// Bumped by every StopConsumers(). A producer reads it when it is set
219 /// up and hands it back to StartConsumers(), which then refuses to start
220 /// consumers for a producer that has been stopped in between.
221 4322 uint64_t ProducerGeneration() const { return m_producerGeneration.load(); }
222
223 /// Called by VideoInputManager when a producer source pipeline reaches
224 /// PLAYING and is about to deliver its first video frames. Starts any
225 /// persistent consumers that target the given intervideo channel.
226 void NotifyProducerReady(const std::string& channelName);
227
228 /// Retry the persistent consumers on a source's channel after a
229 /// backoff (2s, doubling to 60s; back to 2s after five quiet minutes):
230 /// one whose pipeline errored or ended while the source kept running,
231 /// or one that could not start (a display not connected yet). Runs on
232 /// its own worker, and only while the source runs -- a dead source
233 /// restarts itself and fires NotifyProducerReady(). Never takes
234 /// m_mutex.
235 void ScheduleConsumerRestart(const std::string& channelName);
236 /// The same retry after a fixed delay, outside the failure backoff.
237 void ScheduleConsumerResume(const std::string& channelName, int delayMs);
238
239 /// Media playback is about to show on this HDMI connector. A persistent
240 /// consumer there (a camera group, say) stops and waits; this returns
241 /// once its kmssink has let go of the connector, so the caller can take
242 /// it. Refcounted: every call needs a ReleaseConnectorFromMedia().
243 void ClaimConnectorForMedia(int connectorId);
244
245 /// The media on this connector is gone (its kmssink released). Once
246 /// nothing else holds it, what stood aside comes back after a moment --
247 /// long enough that the next video in a playlist claims the connector
248 /// first, rather than the consumer flashing up between them.
249 void ReleaseConnectorFromMedia(int connectorId);
250
251 /// Check if any consumers are configured.
252 bool HasConsumers() const;
253
254 /// Check if any consumers are currently running.
255 bool HasActiveConsumers() const;
256
257 /// Get count of running consumer pipelines.
258 int ActiveConsumerCount() const;
259
260 private:
261 2651 VideoOutputManager() = default;
262 ~VideoOutputManager();
263
264 VideoOutputManager(const VideoOutputManager&) = delete;
265 VideoOutputManager& operator=(const VideoOutputManager&) = delete;
266
267 /// Thread-safe overlay state shared between appsink callback and manager.
268 struct OverlayState {
269 std::mutex mtx;
270 PixelOverlayModel* model = nullptr;
271 int width = 0;
272 int height = 0;
273 bool wasDisabled = false;
274 std::atomic<bool> active{false};
275 };
276
277 struct ConsumerInfo {
278 int id = 0;
279 std::string name;
280 std::string type; // "hdmi", "overlay", "rtp"
281 std::string pipeWireNodeName;
282
283 // HDMI-specific
284 std::string connector;
285 std::string cardPath;
286 int connectorId = -1;
287 int width = 0;
288 int height = 0;
289 std::string scaling; // "fit", "fill", "stretch"
290 VideoCropRect crop; // region of the source shown on this output
291 // The DRM lease this consumer's kmssink runs on (fd < 0: none --
292 // non-HDMI, or it couldn't get one). Released in StopConsumer's
293 // teardown thread, strictly after the pipeline (and its kmssink) has
294 // been unreffed.
295 DrmCards::Lease drmLease;
296
297 // Overlay-specific
298 std::string overlayModel;
299 std::shared_ptr<OverlayState> overlayState;
300
301 // RTP-specific
302 std::string address;
303 int port = 5004;
304 std::string rtpEncoding; // "raw", "h264", "h265", "mjpeg"
305
306 // Source video stream (e.g. "fppd_video_stream_1")
307 std::string sourceNode;
308
309 // Stream slots this consumer should receive (empty = all slots)
310 std::vector<int> streamSlots;
311
312 // When >= 0, this consumer is part of a grouped pipeline and
313 // the GstElement* pipeline is owned by m_consumers[groupPipelineOwnerIdx].
314 // -1 means standalone (owns its own pipeline or not grouped).
315 int groupPipelineOwnerIdx = -1;
316
317 #ifdef HAS_GSTREAMER_VIDEO_OUTPUT
318 GstElement* pipeline = nullptr;
319 #endif
320 std::thread startThread;
321 // Shared (not raw-pointer-captured) so the bus-monitor thread spawned
322 // in StartConsumer can safely outlive this ConsumerInfo: Reload()/
323 // Shutdown() clear() m_consumers, which would invalidate a raw
324 // `&consumer.shutdownRequested` pointer while the detached thread may
325 // still be inside gst_bus_timed_pop(). The thread captures this
326 // shared_ptr by value instead. Re-assigned to a fresh instance each
327 // time StartConsumer runs so a still-draining prior thread can never
328 // have its flag reset out from under it by a later restart.
329 std::shared_ptr<std::atomic<bool>> shutdownRequested = std::make_shared<std::atomic<bool>>(false);
330 // Set by the bus-monitor thread when it exits due to
331 // GST_MESSAGE_ERROR/EOS (i.e. the pipeline died on its own, not via
332 // StopConsumer). Without this, `running` stays true forever for
333 // persistent (sourceNode) consumers and nothing ever restarts them —
334 // a zombie that holds its DRM plane and CMA indefinitely. Same
335 // shared_ptr-per-run rationale as shutdownRequested.
336 std::shared_ptr<std::atomic<bool>> pipelineDead = std::make_shared<std::atomic<bool>>(false);
337 bool running = false;
338 // Stood aside for media playback on its connector, to come back when
339 // the media releases it (ReleaseConnectorFromMedia).
340 bool suspendedForMedia = false;
341 // An on-demand overlay/RTP member that is built but PAUSED (Prewarm,
342 // or parked by StopConsumers), on `channel`, until holdUntilMs.
343 // `running` stays true: the pipeline exists.
344 bool parked = false;
345 std::string channel;
346 uint64_t holdUntilMs = 0;
347 // The PLAYING/PAUSED state the pipeline should be in, and the lock
348 // its start thread, ActivateConsumer and ParkConsumer take to set it,
349 // so a start thread can't PAUSE a member that was just activated.
350 // Fresh per run, like shutdownRequested.
351 std::shared_ptr<std::atomic<bool>> playing = std::make_shared<std::atomic<bool>>(false);
352 std::shared_ptr<std::mutex> stateLock = std::make_shared<std::mutex>();
353
354
4/8
✓ Branch 0 taken 385 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 385 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 385 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 385 times.
✗ Branch 7 not taken.
385 ConsumerInfo() = default;
355 634 ConsumerInfo(ConsumerInfo&& o) noexcept
356 634 : id(o.id), name(std::move(o.name)), type(std::move(o.type)),
357 634 pipeWireNodeName(std::move(o.pipeWireNodeName)),
358 634 connector(std::move(o.connector)), cardPath(std::move(o.cardPath)),
359 634 connectorId(o.connectorId), width(o.width), height(o.height),
360 634 scaling(std::move(o.scaling)), crop(o.crop),
361 634 drmLease(o.drmLease),
362 634 overlayModel(std::move(o.overlayModel)),
363 634 overlayState(std::move(o.overlayState)),
364 634 address(std::move(o.address)), port(o.port),
365 634 rtpEncoding(std::move(o.rtpEncoding)),
366 634 sourceNode(std::move(o.sourceNode)),
367 634 streamSlots(std::move(o.streamSlots)),
368 634 groupPipelineOwnerIdx(o.groupPipelineOwnerIdx),
369 #ifdef HAS_GSTREAMER_VIDEO_OUTPUT
370 634 pipeline(o.pipeline),
371 #endif
372 634 startThread(std::move(o.startThread)),
373 634 shutdownRequested(std::move(o.shutdownRequested)),
374 634 pipelineDead(std::move(o.pipelineDead)),
375 634 running(o.running), suspendedForMedia(o.suspendedForMedia),
376 634 parked(o.parked), channel(std::move(o.channel)), holdUntilMs(o.holdUntilMs),
377 634 playing(std::move(o.playing)), stateLock(std::move(o.stateLock)) {
378 #ifdef HAS_GSTREAMER_VIDEO_OUTPUT
379 634 o.pipeline = nullptr;
380 #endif
381 634 }
382 ConsumerInfo(const ConsumerInfo&) = delete;
383 ConsumerInfo& operator=(const ConsumerInfo&) = delete;
384 };
385
386 /// Load consumer config from JSON file.
387 bool LoadConfig();
388
389 /// Start a single consumer pipeline, on `channel` (default: its
390 /// sourceNode, or the active producer), PLAYING or (startPlaying false)
391 /// built and PAUSED.
392 bool StartConsumer(ConsumerInfo& consumer, const std::string& channel = "",
393 bool startPlaying = true);
394
395 /// Set a parked member PLAYING and let it show again.
396 void ActivateConsumer(ConsumerInfo& consumer);
397 /// Pause a member, hand its overlay model back, and keep it until
398 /// holdUntilMs.
399 void ParkConsumer(ConsumerInfo& consumer, uint64_t holdUntilMs);
400 /// An on-demand overlay or RTP member that serves this stream slot.
401 static bool IsSlotChannelMember(const ConsumerInfo& c, int streamSlot);
402
403 /// Start a group of HDMI consumers sharing the same PipeWire source
404 /// as a single combined pipeline with tee. PipeWire mode=provide
405 /// doesn't fan-out buffers to multiple consumers; this works around
406 /// that by using one pipewiresrc with a GStreamer tee.
407 bool StartHdmiConsumerGroup(const std::vector<size_t>& indices);
408
409 /// Stop a single consumer pipeline.
410 void StopConsumer(ConsumerInfo& consumer);
411
412 /// Stop all consumers.
413 void StopAllConsumers();
414
415 /// Write an SDP file for an RTP consumer so receivers (VLC, ffplay) can connect.
416 void WriteSdpFile(const ConsumerInfo& consumer, const std::string& encoding);
417
418 /// Build the SDP body for an RTP consumer.
419 std::string BuildSdp(const ConsumerInfo& consumer, const std::string& encoding);
420
421 /// Build a raw RFC 2974 SAP packet wrapping the given SDP.
422 static std::vector<uint8_t> BuildSAPPacket(const std::string& sourceIP,
423 uint16_t msgIdHash,
424 const std::string& sdp,
425 bool isDeletion = false);
426
427 /// Start/stop the SAP multicast announcer thread.
428 ///
429 /// Both MUST be called with m_mutex NOT held: they join m_sapThread, and
430 /// SAPAnnounceLoop() takes m_mutex, so joining under it deadlocks. Every
431 /// call site already does this deliberately.
432 void StartSAPAnnouncer();
433 bool HasRunningRtpLocked() const; // caller holds m_mutex
434 void StopSAPAnnouncer();
435
436 /// SAP announcer background loop.
437 void SAPAnnounceLoop();
438
439 std::thread m_sapThread;
440 std::atomic<bool> m_sapRunning{false};
441 /// Serializes the announcer's lifecycle (m_sapThread + m_sapRunning as a
442 /// pair). Deliberately NOT m_mutex: SAPAnnounceLoop() takes m_mutex, and
443 /// Stop joins that thread, so the two must stay separate -- which is also
444 /// why the call sites all sit outside m_mutex. SAPAnnounceLoop() never
445 /// takes this lock, so there is no cycle.
446 ///
447 /// m_sapRunning alone was not enough: it was tested and set as two steps
448 /// from unsynchronized threads (a detached GStreamer start thread reaching
449 /// StartConsumers(), and the command/API thread reaching Reload()), so two
450 /// callers could both pass the check and both assign m_sapThread --
451 /// assigning over a joinable std::thread calls std::terminate().
452 std::mutex m_sapLock;
453
454 #ifdef HAS_GSTREAMER_VIDEO_OUTPUT
455 /// Appsink callback for overlay consumers (runs on GStreamer streaming thread).
456 static GstFlowReturn OnOverlaySample(GstAppSink* appsink, gpointer userData);
457 #endif
458
459 /// Wait for pending pipeline teardown threads to finish (releases DRM/CMA).
460 /// Returns true if all teardowns completed, false on timeout.
461 bool WaitForPendingTeardowns(int timeoutMs);
462 // CmaFree from /proc/meminfo in kB, or -1.
463 static long ReadCmaFreeKB();
464 static constexpr long CMA_WARN_KB = 20480;
465 // WaitForPendingTeardowns(), but only when CMA is short. Never call it
466 // with m_mutex held.
467 void WaitForCmaIfLow();
468
469 // ScheduleConsumerRestart()'s worker. m_restartMutex guards these; it
470 // is taken after m_mutex, never before.
471 struct RestartState {
472 std::chrono::steady_clock::time_point due;
473 std::chrono::steady_clock::time_point lastFailure;
474 int delayMs = 0;
475 bool pending = false;
476 };
477 std::mutex m_restartMutex;
478 std::condition_variable m_restartCv;
479 std::thread m_restartThread;
480 bool m_restartRunning = false;
481 bool m_stopRestarts = false;
482 std::map<std::string, RestartState> m_restarts;
483 static constexpr int RESTART_MIN_DELAY_MS = 2000;
484 static constexpr int RESTART_MAX_DELAY_MS = 60000;
485 static constexpr int RESTART_QUIET_RESET_MS = 5 * 60 * 1000;
486 void RestartWorker();
487
488 // Prewarm()'s worker: builds the requested slots' members and tears down
489 // parked ones whose hold has run out. m_warmMutex guards these; it is
490 // taken after m_mutex, never before (the worker drops it first).
491 std::mutex m_warmMutex;
492 std::condition_variable m_warmCv;
493 std::thread m_warmThread;
494 bool m_stopWarm = false;
495 std::map<int, uint64_t> m_prewarmRequests; // slot -> hold until (GetTimeMS)
496 void KickWarmWorker();
497 void WarmWorker();
498 void ServiceWarm(const std::map<int, uint64_t>& requests);
499
500 mutable std::mutex m_mutex;
501 std::vector<ConsumerInfo> m_consumers;
502 std::string m_activeProducer; // node name of the current producer, empty if none
503 std::atomic<uint64_t> m_producerGeneration{ 1 };
504 // HDMI connectors media playback holds (ClaimConnectorForMedia), with how
505 // many claims each. A persistent consumer stands aside on these.
506 std::map<int, int> m_mediaConnectors;
507 static constexpr int MEDIA_RESUME_DELAY_MS = 1500;
508 bool m_initialized = false;
509 // Guards Shutdown() so the destructor doesn't re-run it after main() already
510 // did (the "Shutdown complete" was logged twice). Harmless today since it
511 // only locks our own mutex, but keeps teardown single-shot and future-proof.
512 std::atomic<bool> m_shutdownDone{false};
513
514 // Pipeline teardown tracking — detached threads decrement the counter
515 // and notify the CV when done, so callers can wait for CMA to be freed.
516 std::mutex m_teardownMutex;
517 std::condition_variable m_teardownCV;
518 int m_pendingTeardowns = 0;
519 // Up while a teardown has outlived WaitForPendingTeardowns(); comes down
520 // when the last one finishes. Under m_teardownMutex.
521 bool m_teardownStuckWarned = false;
522 static constexpr const char* TEARDOWN_STUCK_WARNING =
523 "Video output: a pipeline teardown is stuck (its display memory is not freed)";
524 };
525