GCC Code Coverage Report


Directory: ./
File: MultiSync.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 4 4 100.0%
Functions: 3 3 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-2022 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 // PLUGIN ABI: native plugins compile against this header and are loaded with
15 // dlopen(), so parts of it are baked into binaries FPP did not build.
16 // - MultiSyncPlugin is subclassed by plugins and FPP calls its virtuals:
17 // inserting, removing, reordering or even appending a virtual breaks
18 // them (appending reads past the end of an older plugin's vtable).
19 // - MultiSync's data layout: plugins call the inline isMultiSyncEnabled().
20 // - The MultiSyncSystemType enum values.
21 // Any such change must bump FPP_PLUGIN_API_VERSION in Plugin.h. Without the
22 // bump, a plugin built against the previous header still loads and silently
23 // uses the old layout - FPP 10.2 shipped exactly that and crash-looped fppd.
24 // See .claude/PLUGIN-ABI.md for which plugins use what.
25
26 #include <netinet/in.h>
27 #include "fpp-json-fwd.h"
28 #include <sys/types.h>
29 #include <atomic>
30 #include <deque>
31 #include <functional>
32 #include <mutex>
33 #include <pthread.h>
34 #include <map>
35 #include <set>
36 #include <string>
37 #include <vector>
38
39 #include "SysSocket.h"
40 #include "settings.h"
41
42 #define FPP_CTRL_PORT 32320
43
44 #define CTRL_PKT_CMD 0 // deprecated in favor of FPP Commands
45 #define CTRL_PKT_SYNC 1
46 #define CTRL_PKT_EVENT 2 // deprecated in favor of FPP Commands
47 #define CTRL_PKT_BLANK 3
48 #define CTRL_PKT_PING 4
49 #define CTRL_PKT_PLUGIN 5
50 #define CTRL_PKT_FPPCOMMAND 6
51
52 typedef struct __attribute__((packed)) {
53 char fppd[4]; // 'FPPD'
54 uint8_t pktType; // Control Packet Type
55 uint16_t extraDataLen; // Length of extra data following Control Packet
56 } ControlPkt;
57
58 typedef struct {
59 char command[1]; // Null-terminated Command to process
60 } CommandPkt;
61
62 #define SYNC_PKT_START 0
63 #define SYNC_PKT_STOP 1
64 #define SYNC_PKT_SYNC 2
65 #define SYNC_PKT_OPEN 3
66 // Media only: the master's playlist expects to play this next, in a second
67 // or so. A remote readies its media for it (PrepareRemoteMediaOutput()), and
68 // the Open that follows finds it ready. Only a hint: the master may play
69 // something else, whose Open then discards it. Remotes from before this
70 // ignore an action they don't know.
71 #define SYNC_PKT_PREPARE 4
72
73 #define SYNC_FILE_SEQ 0
74 #define SYNC_FILE_MEDIA 1
75
76 typedef struct __attribute__((packed)) {
77 uint8_t pktType; // Sync Packet Type
78 uint8_t fileType; // File Type being synced
79 uint32_t frameNumber; // Sequence frames displayed on Master
80 float secondsElapsed; // Seconds elapsed in file on Master
81 char filename[1]; // Null-terminated File Name to play on Slave
82 // (data may continue past this header)
83 } SyncPkt;
84
85 typedef enum systemType {
86 kSysTypeUnknown = 0x00,
87 kSysTypeFPP = 0x01,
88 kSysTypeFPPRaspberryPiA,
89 kSysTypeFPPRaspberryPiB,
90 kSysTypeFPPRaspberryPiAPlus,
91 kSysTypeFPPRaspberryPiBPlus,
92 kSysTypeFPPRaspberryPi2B,
93 kSysTypeFPPRaspberryPi2BNew,
94 kSysTypeFPPRaspberryPi3B,
95 kSysTypeFPPRaspberryPi3BPlus,
96 kSysTypeFPPRaspberryPiZero,
97 kSysTypeFPPRaspberryPiZeroW,
98 kSysTypeFPPRaspberryPi3APlus,
99 kSysTypeFPPRaspberryPi4,
100 kSysTypeFPPRaspberryPi5,
101 kSysTypeFPPRaspberryPiZero2W,
102 kSysTypeFPPBeagleBoneBlack = 0x41,
103 kSysTypeFPPBeagleBoneBlackWireless = 0x42,
104 kSysTypeFPPBeagleBoneGreen = 0x43,
105 kSysTypeFPPBeagleBoneGreenWireless = 0x44,
106 kSysTypeFPPPocketBeagle = 0x45,
107 kSysTypeFPPSanCloudBeagleBoneEnhanced = 0x46,
108 kSysTypeFPPPocketBeagle2 = 0x47,
109 kSysTypeFPPArmbian = 0x60,
110 kSysTypeMacOS = 0x70,
111 // Values under 0x80 are "FPP based" and run full FPP
112 kSysTypeFalconController = 0x80,
113 kSysTypeFalconF16v2 = 0x81,
114 kSysTypeFalconF4v2_64Mb = 0x82,
115 kSysTypeFalconF16v2R = 0x83,
116 kSysTypeFalconF4v2 = 0x84,
117 kSysTypeFalconF16v3 = 0x85,
118 kSysTypeFalconF4v3 = 0x86,
119 kSysTypeFalconF48 = 0x87,
120 kSysTypeFalconF16v4 = 0x88,
121 kSysTypeFalconF48v4 = 0x89,
122 kSysTypeFalconF16v5 = 0x8a,
123 kSysTypeFalconF48v5 = 0x8b,
124 kSysTypeFalconF32v5 = 0x8c,
125 kSysTypeExperienceGP16 = 0xA0,
126 kSysTypeExperienceGP8 = 0xA1,
127 kSysTypeExperienceGLR = 0xA2,
128 kSysTypeExperienceG16Pro = 0xA3,
129 kSysTypeExperienceG32Pro = 0xA4,
130 kSysTypeExperienceAURORACORE16 = 0xA5,
131 kSysTypeExperienceVIVID8 = 0xA6,
132 kSysTypeExperiencePIXELLINK4 = 0xA7,
133 kSysTypeExperienceGenius = 0xAF,
134 kSysTypeOtherSystem = 0xC0,
135 kSysTypexSchedule = 0xC1,
136 kSysTypeESPixelStick = 0xC2,
137 kSysTypeESPixelStickESP32 = 0xC3,
138 kSysTypeBaldrick = 0xC4,
139 kSysTypeNonMultiSyncCapable = 0xF0,
140 kSysTypeTwinkly = 0xFA,
141 kSysTypeWLED = 0xFB,
142 kSysTypeDIYLEDExpress = 0xFC,
143 kSysTypeHinksPix = 0xFD,
144 kSysTypeAlphaPix = 0xFE,
145 kSysTypeSanDevices = 0xFF
146 } MultiSyncSystemType;
147
148 // The two records below hold the slow-changing detail the multisync UI needs
149 // about every discovered FPP remote -- OS version, host description, background
150 // color, git branch/commit, whether channel inputs/outputs are enabled, and what
151 // cape is installed. None of it fits in (or belongs in) the UDP ping packet, so
152 // fppd collects it over HTTP instead; see MultiSync::CheckSystemInfoRefreshes().
153 //
154 // Both deliberately hold plain members rather than a Json::Value: MultiSync.h
155 // only forward-declares Json::Value (fpp-json-fwd.h), and spelling the fields
156 // out documents exactly what is relayed to peers.
157 class MultiSyncSystemInfo {
158 public:
159 bool valid = false;
160
161 std::string platform;
162 std::string variant;
163 std::string subPlatform;
164 std::string osVersion;
165 std::string osRelease;
166 std::string kernel;
167 std::string hostDescription;
168 std::string backgroundColor;
169 std::string branch;
170 std::string localGitVersion;
171 std::string remoteGitVersion;
172 std::string upgradeSource;
173 std::vector<std::string> ips;
174 // Tri-state: -1 when the remote is too old to report the field at all, in
175 // which case the UI still has to go look for itself.
176 int channelInputsEnabled = -1;
177 int channelOutputsEnabled = -1;
178
179 Json::Value toJSON() const;
180 };
181
182 class MultiSyncCapeInfo {
183 public:
184 bool valid = false;
185 // False when the remote answered but has no cape installed (/api/cape
186 // returns 404). That is a real answer and worth caching, as distinct from
187 // valid == false meaning "we have not managed to ask yet".
188 bool present = false;
189
190 std::string id;
191 std::string name;
192 std::string description;
193 std::string version;
194 std::string designer;
195 // Deliberately NOT carrying the cape's serialNumber: it is a per-board
196 // hardware identifier with no use in the UI, and this record is handed to
197 // every peer that asks for the systems list.
198 std::string vendorName;
199 std::string vendorURL;
200 std::string vendorEmail;
201 std::string vendorImage;
202 // The cape's own opt-out of hardware detail in the usage statistics. Only
203 // a signed cape can carry it -- CapeUtils strips it from an unsigned one --
204 // and it is relayed so that a peer-side collector can honour the flag of
205 // the cape it actually describes, rather than the reporting host's.
206 // Default true: absent means the cape never asked to be excluded.
207 bool sendStats = true;
208
209 Json::Value toJSON() const;
210 // Build from a /api/cape style object (a remote's reply, or the local
211 // media/tmp/cape-info.json). Result is valid+present.
212 static MultiSyncCapeInfo fromCapeJSON(const Json::Value& v);
213 };
214
215 // Identity synthesised from a device's MAC when it reports no UUID of its own.
216 // The prefix marks it as a stand-in so a real UUID arriving later can replace
217 // it -- see MultiSyncSystem::update().
218 #define MAC_UUID_PREFIX "MAC:"
219
220 class MultiSyncSystem {
221 public:
222 7683 MultiSyncSystem() {
223 7683 }
224 unsigned long lastSeen = 0;
225 std::string lastSeenStr;
226 bool multiSync = false;
227 MultiSyncSystemType type = kSysTypeUnknown;
228 unsigned int majorVersion = 0;
229 unsigned int minorVersion = 0;
230 FPPMode fppMode = FPPMode::PLAYER_MODE;
231 bool sendingMultiSync = false;
232 // True if this is a full FPP instance running in Remote mode and is therefore
233 // a valid target for "Send MultiSync to ALL KNOWN remotes via Unicast". This
234 // excludes non-FPP devices (WLED, ESPixelStick, Falcon controllers, etc.) and
235 // FPP instances not in Remote mode. Computed in update().
236 bool supportsUnicast = false;
237 std::string address;
238 std::string hostname;
239 std::string version;
240 std::string model;
241 std::string ranges;
242 std::string uuid;
243
244 // Fetched by MultiSync::CheckSystemInfoRefreshes(), relayed by toJSON().
245 // All six are guarded by MultiSync::m_systemsLock.
246 MultiSyncSystemInfo systemInfo; // subset of the remote's /api/system/info
247 MultiSyncCapeInfo capeInfo; // subset of the remote's /api/cape
248 std::string infoFetchedVersion; // 'version' the cached info was fetched for
249 // Earliest wall clock at which this remote may be fetched again. 0 means
250 // "due, but not yet scheduled": the sweep turns that into a jittered time
251 // rather than fetching immediately, so a fleet-wide event doesn't converge
252 // on one target. See CheckSystemInfoRefreshes().
253 time_t infoNextFetch = 0;
254 bool infoFetchPending = false; // a fetch is in flight right now
255
256 unsigned char ipa = 0;
257 unsigned char ipb = 0;
258 unsigned char ipc = 0;
259 unsigned char ipd = 0;
260
261 void update(MultiSyncSystemType type,
262 unsigned int majorVersion, unsigned int minorVersion,
263 FPPMode fppMode,
264 const std::string& address,
265 const std::string& hostname,
266 const std::string& version,
267 const std::string& model,
268 const std::string& ranges,
269 const std::string& uuid,
270 const bool multiSync,
271 const bool sendingMultiSync);
272 Json::Value toJSON(bool local, bool timestamps);
273 };
274
275 class MultiSyncStats {
276 public:
277 MultiSyncStats(std::string ip, std::string host);
278
279 Json::Value toJSON();
280
281 std::string sourceIP;
282 std::string hostname;
283 time_t lastReceiveTime;
284 uint32_t pktCommand;
285 uint32_t pktSyncSeqOpen;
286 uint32_t pktSyncSeqStart;
287 uint32_t pktSyncSeqStop;
288 uint32_t pktSyncSeqSync;
289 uint32_t pktSyncMedOpen;
290 uint32_t pktSyncMedStart;
291 uint32_t pktSyncMedStop;
292 uint32_t pktSyncMedSync;
293 uint32_t pktBlank;
294 uint32_t pktPing;
295 uint32_t pktPlugin;
296 uint32_t pktFPPCommand;
297 uint32_t pktError;
298 };
299
300 class MultiSyncPlugin {
301 public:
302 MultiSyncPlugin() {}
303 virtual ~MultiSyncPlugin() {}
304
305 virtual void SendSeqOpenPacket(const std::string& filename) {}
306 virtual void SendSeqSyncStartPacket(const std::string& filename) {}
307 virtual void SendSeqSyncStopPacket(const std::string& filename) {}
308 virtual void SendSeqSyncPacket(const std::string& filename, int frames, float seconds) {}
309 virtual void ShutdownSync(void) {}
310
311 virtual void SendMediaOpenPacket(const std::string& filename) {}
312 virtual void SendMediaSyncStartPacket(const std::string& filename) {}
313 virtual void SendMediaSyncStopPacket(const std::string& filename) {}
314 virtual void SendMediaSyncPacket(const std::string& filename, float seconds) {}
315
316 virtual void SendBlankingDataPacket(void) {}
317
318 virtual void SendPluginData(const std::string& name, const uint8_t* data, int len) {}
319 virtual void SendFPPCommandPacket(const std::string& host, const std::string& cmd, const std::vector<std::string>& args) {}
320
321 virtual void ReceivedSeqOpenPacket(const std::string& filename) {}
322 virtual void ReceivedSeqSyncStartPacket(const std::string& filename) {}
323 virtual void ReceivedSeqSyncStopPacket(const std::string& filename) {}
324 virtual void ReceivedSeqSyncPacket(const std::string& filename, int frames, float seconds) {}
325
326 virtual void ReceivedMediaOpenPacket(const std::string& filename) {}
327 virtual void ReceivedMediaSyncStartPacket(const std::string& filename) {}
328 virtual void ReceivedMediaSyncStopPacket(const std::string& filename) {}
329 virtual void ReceivedMediaSyncPacket(const std::string& filename, float seconds) {}
330
331 virtual void ReceivedBlankingDataPacket(void) {}
332 virtual void ReceivedPluginData(const std::string& name, const uint8_t* data, int len) {}
333 virtual void ReceivedFPPCommandPacket(const std::string& cmd, const std::vector<std::string>& args) {}
334 };
335
336 class NetInterfaceInfo {
337 public:
338 NetInterfaceInfo();
339 ~NetInterfaceInfo();
340
341 std::string interfaceName;
342 std::string interfaceAddress;
343 uint32_t address;
344 uint32_t broadcastAddress;
345 int multicastSocket;
346 };
347
348 class MultiSync {
349 public:
350 static MultiSync INSTANCE;
351
352 MultiSync();
353 ~MultiSync();
354
355 int Init(void);
356
357 667272 bool isMultiSyncEnabled() { return m_multiSyncEnabled; }
358
359 2650 int GetControlSocket(void) { return m_receiveSock; }
360 void ProcessControlPacket(bool pingOnly = false);
361
362 void UpdateSystem(MultiSyncSystemType type,
363 unsigned int majorVersion,
364 unsigned int minorVersion,
365 FPPMode fppMode,
366 const std::string& address,
367 const std::string& hostname,
368 const std::string& version,
369 const std::string& model,
370 const std::string& range,
371 const std::string& uuid,
372 const bool multiSync,
373 const bool sendingMultiSync);
374
375 Json::Value GetSystems(bool localOnly = false, bool timestamps = true);
376 Json::Value GetSyncStats();
377 void ResetSyncStats();
378
379 void WriteRuntimeInfoFile();
380
381 void Ping(int discover = 0, bool broadcast = true);
382 void PingSingleRemote(const char* address, int discover = 0);
383 void QueueDiscoverReply(const std::string& address, const std::string& srcIp);
384 // Detect/refresh a single non-multisync remote (e.g. a WLED node found
385 // via mDNS) by fetching its HTTP root and running controller detection.
386 void PingSingleRemoteViaHTTP(const std::string& address);
387 void Discover(void);
388 void PeriodicPing();
389
390 void SendSeqOpenPacket(const std::string& filename);
391 void SendSeqSyncStartPacket(const std::string& filename);
392 void SendSeqSyncStopPacket(const std::string& filename);
393 void SendSeqSyncPacket(const std::string& filename, int frames, float seconds);
394 void ShutdownSync(void);
395
396 void SendMediaOpenPacket(const std::string& filename);
397 // SYNC_PKT_PREPARE. Not offered to MultiSyncPlugins: a virtual for it
398 // would change their vtable (see the PLUGIN ABI note above).
399 void SendMediaPreparePacket(const std::string& filename);
400 void SendMediaSyncStartPacket(const std::string& filename);
401 void SendMediaSyncStopPacket(const std::string& filename);
402 void SendMediaSyncPacket(const std::string& filename, float seconds);
403
404 void SendFPPCommandPacket(const std::string& host, const std::string& cmd, const std::vector<std::string>& args);
405 void SendBlankingDataPacket(void);
406
407 void SendPluginData(const std::string& name, const uint8_t* data, int len);
408
409 void addMultiSyncPlugin(MultiSyncPlugin* p);
410 void removeMultiSyncPlugin(MultiSyncPlugin* p);
411
412 void OpenSyncedSequence(const std::string& filename);
413 void StartSyncedSequence(const std::string& filename);
414 void StopSyncedSequence(const std::string& filename);
415 void SyncSyncedSequence(const std::string& filename, int frameNumber, float secondsElapsed);
416
417 void OpenSyncedMedia(const std::string& filename);
418 void PrepareSyncedMedia(const std::string& filename);
419 void StartSyncedMedia(const std::string& filename, float secondsElapsed = 0.0f);
420 void StopSyncedMedia(const std::string& filename);
421 void SyncSyncedMedia(const std::string& filename, int frameNumber, float secondsElapsed);
422 void CheckSyncedMediaIdleTimeout();
423
424 void SyncPlaylistToMS(uint64_t ms, const std::string& pl = "", bool sendSyncPackets = false);
425 void SyncPlaylistToMS(uint64_t ms, int pos, const std::string& pl = "", bool sendSyncPackets = false);
426 void SyncStopAll();
427
428 int OpenControlSockets();
429
430 static std::string GetTypeString(MultiSyncSystemType type, bool local = false);
431 static MultiSyncSystemType ModelStringToType(std::string model);
432
433 // Was the curl write callback for the HTTP discovery scan, which now
434 // receives whole responses from CurlManager instead. Retained as a no-op
435 // only because it is public and an external plugin could reference it.
436 void StoreHTTPResponse(std::string* ipp, uint8_t* data, int sz) {}
437
438 [[nodiscard]] std::vector<MultiSyncSystem> const& GetLocalSystems() { return m_localSystems; }
439 [[nodiscard]] std::vector<MultiSyncSystem> const& GetRemoteSystems() { return m_remoteSystems; }
440
441 private:
442 bool isSupportedForMultisync(const char* address, const char* intface);
443
444 void setupMulticastReceive(bool cycle);
445 void PingSingleRemote(MultiSyncSystem& sys, int discover = 0);
446 int CreatePingPacket(MultiSyncSystem& sys, char* outBuf, int discover);
447
448 bool FillLocalSystemInfo(void);
449 std::string GetHardwareModel(void);
450
451 // Rebuild m_configuredOutputRanges from co-universes.json. Called once at
452 // startup and again whenever the file changes (via a FileMonitor watch).
453 void ReloadConfiguredOutputRanges();
454
455 int OpenBroadcastSocket(void);
456 void SendBroadcastPacket(void* outBuf, int len);
457 void SendControlPacket(void* outBuf, int len);
458 void SendControlPacketViaMsgs(std::vector<struct mmsghdr>& msgs, struct iovec& iovec, void* outBuf, int len);
459 void SendMulticastPacket(void* outBuf, int len);
460 void SendUnicastPacket(const std::string& address, void* outBuf, int len);
461 // Rebuild the cached "all known remotes" unicast destination list from the
462 // currently-known remote systems that support unicast. Only used when the
463 // MultiSyncUnicast ("send to ALL known remotes") setting is enabled.
464 // When MultiSyncUnicastSubnets is set, only remotes inside one of its
465 // subnets are kept.
466 // Neither form may be called with m_systemsLock held: they take
467 // m_unicastUpdateLock, and that lock is only ever acquired ahead of
468 // m_systemsLock, never behind it. The no-arg form snapshots the addresses
469 // under m_systemsLock and then releases it before doing the rebuild; a
470 // caller that already holds m_systemsLock takes its own snapshot while it
471 // has the lock and passes it to the overload after releasing it.
472 void UpdateUnicastDestinations();
473 void UpdateUnicastDestinations(const std::vector<std::string>& addrsToResolve);
474 // Re-read the sync send methods (MultiSyncBroadcast/Multicast/Unicast, and
475 // the MultiSyncUnicastSubnets filter) and
476 // the statically-configured unicast remote list (MultiSyncRemotes plus
477 // MultiSyncExtraRemotes) from the settings and swap the resulting
478 // destination list into place. Called once from OpenControlSockets() and
479 // again from a settings listener whenever any of those settings change, so
480 // editing the remote list on the MultiSync page takes effect immediately
481 // instead of requiring an fppd restart.
482 void ReloadSyncDestinations();
483 bool FillInInterfaces();
484 bool RemoveInterface(const std::string& interface);
485
486 void InitControlPacket(ControlPkt* pkt);
487
488 int OpenReceiveSocket(void);
489
490 void PerformHTTPDiscovery(void);
491 void DiscoverViaHTTP(const std::set<std::string>& ips, const std::set<std::string>& exacts);
492
493 // Twinkly lights answer neither mDNS nor SSDP, and serve a 404 at "/", so
494 // they are invisible to the mDNS listener and are dropped by the HTTP subnet
495 // scan before any detector sees them. They do answer a short UDP broadcast
496 // on port 5555, which is the only way to find one that has not been
497 // configured as a channel output. See PerformTwinklyDiscovery().
498 bool OpenTwinklyDiscoverySocket();
499 void PerformTwinklyDiscovery();
500 bool ProcessTwinklyDiscoveryReplies();
501 void DiscoverIPViaHTTP(const std::string& ip, const std::string& html, bool allowUnknown = false);
502
503 // Both HTTP probe paths are queue-and-pump rather than fire-everything:
504 // each hands its addresses to a queue and then starts as many requests as
505 // the in-flight cap allows, and each completion starts the next one. See
506 // the cap defines in MultiSync.cpp for why an unbounded fan-out is the
507 // wrong thing on a show network.
508 void PumpHTTPPings();
509 void StartHTTPPing(const std::string& address);
510 void FinishHTTPPing();
511 void PumpHTTPDiscovery();
512 void FinishHTTPDiscovery();
513
514 void ProcessSyncPacket(ControlPkt* pkt, int len, MultiSyncStats* stats);
515 void ProcessCommandPacket(ControlPkt* pkt, int len, MultiSyncStats* stats);
516 void ProcessPingPacket(ControlPkt* pkt, int len, const std::string& src, MultiSyncStats* stats, const std::string& incomingIp = "");
517 void ProcessPluginPacket(ControlPkt* pkt, int len, MultiSyncStats* stats);
518 void ProcessFPPCommandPacket(ControlPkt* pkt, int len, MultiSyncStats* stats);
519
520 std::recursive_mutex m_systemsLock;
521 std::vector<MultiSyncSystem> m_localSystems;
522 std::vector<MultiSyncSystem> m_remoteSystems;
523 // Identities learned second-hand: some vendors report a stable id for each
524 // neighbour they can see but none for themselves, so a device's identity
525 // arrives while a DIFFERENT address is being probed. Kept rather than
526 // applied and discarded, because the neighbour is often identified before
527 // the device it describes has been discovered at all. Guarded by
528 // m_systemsLock. Keyed by address.
529 std::map<std::string, std::string> m_peerUUIDHints;
530
531 // Channel-output ranges parsed from co-universes.json, keyed by each output
532 // target's configured address and its resolved IP. Used to backfill the
533 // advertised channel range of non-FPP remotes that don't report their own
534 // range via MultiSync. Rebuilt only when co-universes.json changes (see
535 // ReloadConfiguredOutputRanges()) so the frequently-polled GetSystems() path
536 // is just a map lookup with no file IO or DNS resolution. Guarded by
537 // m_systemsLock.
538 std::map<std::string, std::string> m_configuredOutputRanges;
539
540 std::map<std::string, NetInterfaceInfo> m_interfaces;
541 // Which send methods are active. Read on the output thread from
542 // SendControlPacket() without any lock and rewritten by
543 // ReloadSyncDestinations() on the settings-reload thread, hence atomic.
544 std::atomic<bool> m_sendMulticast;
545 std::atomic<bool> m_sendBroadcast;
546 std::atomic<bool> m_sendUnicast = false;
547
548 int m_broadcastSock;
549 int m_controlSock;
550 int m_receiveSock;
551 // Sends the Twinkly discovery broadcast and receives the replies. They come
552 // back to the port the request went out from, so this stays on an ephemeral
553 // port and never binds 5555. Registered with EPollManager, so replies are
554 // handled on the main loop.
555 int m_twinklyDiscoverySock = -1;
556
557 // Guards the one-shot listener teardown in ShutdownSync(); see the comment
558 // there for why the second call has to be a no-op.
559 std::atomic<bool> m_settingsListenersRemoved{ false };
560
561 std::string m_hostname;
562 struct sockaddr_in m_srcAddr;
563 struct sockaddr_in m_receiveSrcAddr;
564 std::mutex m_socketLock;
565
566 // Serializes UpdateUnicastDestinations() calls against each other (DNS
567 // resolution happens without any other lock held, so overlapping calls are
568 // otherwise possible). Lock order: this lock is never acquired while
569 // m_systemsLock is held -- ReloadSyncDestinations() takes it first and then
570 // reaches m_systemsLock only indirectly, so the reverse order would be an
571 // ABBA deadlock against the discovery paths. m_socketLock is taken under
572 // it, for the brief swap step only.
573 std::mutex m_unicastUpdateLock;
574
575 // Async HTTP enrichment of discovered FPP remotes; see the comment above
576 // the definition of CheckSystemInfoRefreshes() in MultiSync.cpp.
577 void CheckSystemInfoRefreshes();
578 // Marks a remote's cached detail stale so a later sweep re-fetches it (at a
579 // jittered time, not immediately -- see CheckSystemInfoRefreshes()). Called
580 // when the remote announces itself with a discover ping, i.e. its fppd just
581 // started. Public because ProcessPingPacket reaches it through the global
582 // multiSync pointer.
583 public:
584 void InvalidateSystemInfo(const std::string& address);
585
586 private:
587 // Makes every entry for one device agree on its identity; see the comment
588 // above the definition. Caller must hold m_systemsLock.
589 void ReconcileDeviceIdentity(const std::string& hostname, FPPMode fppMode);
590 void ApplyPeerUUIDs(const std::map<std::string, std::string>& peerUUIDs);
591 // Fills in a system's identity from m_peerUUIDHints. Caller holds
592 // m_systemsLock.
593 void ApplyUUIDHint(MultiSyncSystem& sys);
594 void FetchSystemInfo(const std::string& address);
595 void FetchCapeInfo(const std::string& address);
596 // Runs `apply` on every remote entry describing the same device as
597 // `address` -- the same address, or the same non-empty uuid. A device with
598 // more than one NIC has one entry per address (the UI merges them into a
599 // single row by uuid), and one fetch should update all of them. Takes
600 // m_systemsLock.
601 void ForEachRemoteMatching(const std::string& address,
602 const std::function<void(MultiSyncSystem&)>& apply);
603
604 // Wall clock of the next CheckSystemInfoRefreshes() sweep, and how many of
605 // its HTTP fetches are outstanding. Both are touched only on the main loop
606 // -- the sweep and the CurlManager completions run on the same thread. The
607 // counter would be stranded high (and infoFetchPending stuck set) if a
608 // request were ever cancelled without running its callback, but
609 // CurlManager::cancelRequests() only ever cancels a named owner and these
610 // are issued with FPP's own empty owner, so that cannot happen.
611 time_t m_nextInfoScan = 0;
612 std::atomic<int> m_infoFetchesInFlight{ 0 };
613
614 unsigned long m_lastPingTime;
615 unsigned long m_lastCheckTime;
616 int m_lastMediaHalfSecond;
617 int m_lastFrame;
618 int m_lastFrameSent;
619
620 // Wall-clock ms of the last media sync packet we acted on as a remote.
621 // 0 when no synced media is open. Read/written from the sync-receive path
622 // and the main loop's idle check, hence atomic. See
623 // CheckSyncedMediaIdleTimeout().
624 std::atomic<uint64_t> m_lastSyncedMediaPacketMS{ 0 };
625
626 float m_remoteOffset;
627
628 // Statically-configured unicast remotes (MultiSyncRemotes plus
629 // MultiSyncExtraRemotes). Rebuilt by ReloadSyncDestinations() whenever
630 // those settings change. Guarded by m_socketLock (same as the send path).
631 struct iovec m_destIovec;
632 std::vector<struct mmsghdr> m_destMsgs;
633 std::vector<struct sockaddr_in> m_destAddr;
634
635 // Dynamic destination list for the "send to ALL KNOWN remotes via Unicast"
636 // mode. Rebuilt by UpdateUnicastDestinations() as remotes are discovered,
637 // change mode, or time out. Guarded by m_socketLock (same as the send path).
638 struct iovec m_unicastDestIovec;
639 std::vector<struct mmsghdr> m_unicastDestMsgs;
640 std::vector<struct sockaddr_in> m_unicastDestAddr;
641
642 // Guards m_plugins against add/removeMultiSyncPlugin() (which can run on any
643 // thread that owns a plugin) racing the many Send*/Received*/Process* sites
644 // that iterate it, some of which run on the output thread or the main loop.
645 // Iteration sites take a snapshot under this lock via getPluginsCopy() and
646 // iterate the copy so callbacks never run with the lock held.
647 std::mutex m_pluginsLock;
648 std::vector<MultiSyncPlugin*> m_plugins;
649 std::vector<MultiSyncPlugin*> getPluginsCopy();
650
651 #define MAX_MS_RCV_MSG 12
652 #define MAX_MS_RCV_BUFSIZE 1500
653 struct mmsghdr rcvMsgs[MAX_MS_RCV_MSG];
654 struct iovec rcvIovecs[MAX_MS_RCV_MSG];
655 unsigned char rcvBuffers[MAX_MS_RCV_MSG][MAX_MS_RCV_BUFSIZE + 1];
656 unsigned char rcvCmbuf[MAX_MS_RCV_MSG][0x100];
657 struct sockaddr_storage rcvSrcAddr[MAX_MS_RCV_MSG];
658
659 // Pending work for the two HTTP probe paths, plus how many of each are
660 // outstanding. A lock rather than bare atomics because a CurlManager
661 // completion does not reliably land on the main loop: processCurls() is
662 // also called from UDPOutput's init and teardown, so a callback can run on
663 // whichever thread is reloading channel outputs.
664 std::mutex m_httpProbeLock;
665 std::deque<std::string> m_httpPingQueue;
666 int m_httpPingsInFlight = 0;
667 std::deque<std::pair<std::string, bool>> m_httpDiscoveryQueue; // address, isExact
668 int m_httpDiscoveriesInFlight = 0;
669 // Addresses already handed to an HTTP probe by the current Twinkly sweep.
670 // The lights answer each broadcast more than once. Guarded by
671 // m_httpProbeLock, like the queues above.
672 std::set<std::string> m_twinklyDiscoverySeen;
673
674 std::recursive_mutex m_statsLock;
675 std::map<std::string, MultiSyncStats*> m_syncStats;
676 std::string m_syncMaster;
677 bool m_multiSyncEnabled = false;
678 };
679
680 extern MultiSync* multiSync;
681