GCC Code Coverage Report


Directory: ./
File: channeloutput/UDPOutput.h
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 22 22 100.0%
Functions: 10 10 100.0%
Branches: 3 6 50.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 GPL v2 as described in the
11 * included LICENSE.GPL file.
12 */
13
14 #include <set>
15 #include <atomic>
16 #include "fpp-json-fwd.h"
17 #include <condition_variable>
18 #include <list>
19 #include <map>
20 #include <memory>
21 #include <mutex>
22 #include <string>
23 #include <thread>
24 #include <vector>
25
26 #include "../SysSocket.h"
27 #include <netinet/in.h>
28
29 #include "ChannelOutput.h"
30
31 typedef void CURLM;
32
33 #define MULTICAST_MESSAGES_KEY 0x00000001
34 #define ANY_MESSAGES_KEY 0x00000002
35 #define ARTNET_MESSAGES_KEY 0x00000003
36
37 #define LATE_MESSAGES_START 0xFFFFFFF0
38 #define E131_SYNC_KEY 0xFFFFFFFC
39 #define ARTNET_SYNC_KEY 0xFFFFFFFD
40 #define LATE_MULTICAST_MESSAGES_KEY 0xFFFFFFFE
41 #define BROADCAST_MESSAGES_KEY 0xFFFFFFFF
42
43 class SendSocketInfo;
44
45 class UDPOutputMessages {
46 public:
47 UDPOutputMessages();
48 ~UDPOutputMessages();
49
50 void ForceSocket(unsigned int key, int socket, bool preventClose = false);
51 int GetSocket(unsigned int key);
52
53 std::vector<struct mmsghdr>& GetMessages(unsigned int key);
54 1016219 std::vector<struct mmsghdr>& operator[](unsigned int key) { return GetMessages(key); }
55
56 private:
57 std::map<unsigned int, std::vector<struct mmsghdr>> messages;
58 std::map<unsigned int, std::shared_ptr<SendSocketInfo>> sendSockets;
59 // While set, every key an output asks for is noted here (once), so
60 // UDPOutput knows which destinations each output's packets go to.
61 std::vector<unsigned int>* recordKeys = nullptr;
62
63 void clearMessages();
64 void clearSockets();
65
66 friend class UDPOutput;
67 };
68
69 class UDPOutputData {
70 public:
71 UDPOutputData(const Json::Value& config);
72 virtual ~UDPOutputData();
73
74 virtual bool IsPingable() = 0;
75 1143 virtual bool Monitor() const { return monitor; }
76 virtual void PrepareData(unsigned char* channelData, UDPOutputMessages& msgs) = 0;
77 122010 virtual void PostPrepareData(unsigned char* channelData, UDPOutputMessages& msgs) {}
78
79 virtual void DumpConfig() = 0;
80
81 // min is the first channel, 0-based; max is one past the last (every
82 // protocol works it out as startChannel + count - 1 from the 1-based
83 // startChannel). UDPOutput converts it for ChannelOutput's inclusive max.
84 1863 virtual void GetRequiredChannelRange(int& min, int& max) {
85 1863 min = startChannel - 1;
86 1863 max = startChannel + channelCount - 1;
87 1863 }
88
89 1199 virtual void StartingOutput() {}
90 1197 virtual void StoppingOutput() {}
91
92 virtual const std::string& GetOutputTypeString() const;
93
94 // The messages last prepared are being sent. A frame can be prepared
95 // more than once before it goes out (its data changed in between), and
96 // only the last preparation is sent, so a protocol sequence number
97 // assigned in PrepareData() is committed here: advanced as it was
98 // assigned, the discarded preparation skipped one on the wire.
99 11572 virtual void FrameSent() {}
100
101 static in_addr_t toInetAddr(const std::string& ip, bool& valid);
102 1140 static in_addr_t toInetAddr(const std::string& ip, std::atomic<bool>& valid) {
103 1140 bool v = false;
104
1/2
✓ Branch 0 taken 1140 times.
✗ Branch 1 not taken.
1140 in_addr_t a = toInetAddr(ip, v);
105 1140 valid = v;
106 1140 return a;
107 }
108
109 std::string description;
110 bool active;
111 int startChannel;
112 int channelCount;
113 int type;
114 std::string ipAddress;
115 // Flipped by the ping thread (SetHostValid) while the output thread reads
116 // it in PrepData().
117 std::atomic<bool> valid;
118 bool monitor;
119
120 // per-destination pacing override in Mbps; -1 means "use the global rate".
121 // 0 means this controller is explicitly unpaced (line rate). A mix of a
122 // gigabit FPP instance and a 30Mbps-class ESP32 controller can each get an
123 // appropriate cap instead of one global setting for all of them.
124 int pacingRateMbps = -1;
125
126 // Set while StartingOutput() is owed its StoppingOutput(). valid can change
127 // at runtime (a failed ping clears it), so it cannot say which outputs were
128 // started; UDPOutput pairs the two calls through this instead.
129 bool started = false;
130
131 UDPOutputData(UDPOutputData const&) = delete;
132 void operator=(UDPOutputData const& x) = delete;
133
134 protected:
135 void SaveFrame(unsigned char* channelData, int len);
136 bool NeedToOutputFrame(unsigned char* channelData, int startChannel, int savedIdx, int count);
137 bool deDuplicate = false;
138 int skippedFrames;
139 unsigned char* lastData;
140 // Bytes allocated in lastData, and bytes written by the last SaveFrame().
141 // The buffer is grown when a frame needs more than lastDataSize; a range
142 // beyond lastDataLen is never compared against older contents.
143 int lastDataSize = 0;
144 int lastDataLen = 0;
145 };
146
147 class UDPOutput : public ChannelOutput {
148 public:
149 UDPOutput(unsigned int startChannel, unsigned int channelCount);
150 virtual ~UDPOutput();
151
152 1284 virtual std::string GetOutputType() const override {
153
1/2
✓ Branch 0 taken 1284 times.
✗ Branch 1 not taken.
2568 return "UDPOutput";
154 }
155 virtual int Init(Json::Value config) override;
156 virtual int Close(void) override;
157
158 virtual void PrepData(unsigned char* channelData) override;
159 virtual int SendData(unsigned char* channelData) override;
160
161 virtual void DumpConfig(void) override;
162
163 virtual void GetRequiredChannelRanges(const std::function<void(int, int)>& addRange) override;
164
165 void addOutput(UDPOutputData*);
166
167 // Outputs another channel output plugin (GenericUDP) sends through this
168 // one. Registered by owner with a factory rather than as data: this
169 // instance is replaced whenever co-universes.json reloads, and the new one
170 // has to rebuild them. Unregistering only retires the data - a worker may
171 // still be sending from its buffers - and it is freed with this instance.
172 static void RegisterExternalOutput(const void* owner, std::function<UDPOutputData*()> create);
173 static void UnregisterExternalOutput(const void* owner);
174
175 int createSocket(int port = 0, bool broadCast = false, bool multiCast = false);
176
177 static UDPOutput* INSTANCE;
178
179 void BackgroundOutputWork();
180
181 virtual void StartingOutput() override;
182 virtual void StoppingOutput() override;
183
184 private:
185 int SendMessages(unsigned int key, SendSocketInfo* socketInfo, std::vector<struct mmsghdr>& sendmsgs);
186 struct sockaddr_in localAddress;
187 std::string outInterface;
188 bool needsBroadcast = false;
189 bool hasArtNet = false;
190 // between StartingOutput() and StoppingOutput(); output thread only
191 bool outputRunning = false;
192 // tags this output's CurlManager requests so the destructor can cancel them
193 const std::string curlOwner = "UDPOutput-" + std::to_string((uintptr_t)this);
194 bool interfaceUp;
195 // the "Invalid interface" banner InitNetwork() raised, while it is up;
196 // InitNetwork() takes it down when the address arrives, Close() otherwise
197 std::string interfaceWarning;
198
199 // rebuildSockets: the address changed; drop the sockets made on the old one
200 bool InitNetwork(bool rebuildSockets = false);
201 std::shared_ptr<SendSocketInfo> findOrCreateSocket(unsigned int key, int sc = 1);
202
203 // Reachability is a property of the controller, not of each universe sent
204 // to it: one PingHost per address, shared by every output sending there,
205 // so a controller that stops answering takes all its universes out of the
206 // frame, and it is pinged once rather than once per universe.
207 struct PingHost;
208 std::map<std::string, std::shared_ptr<PingHost>> pingHosts;
209 // Guards pingHosts, pingsStarted and pingsStopped. Init() fills the map,
210 // and outputs attached later (GenericUDP's, from the thread loading the
211 // other outputs) add to and take from it while the output thread and the
212 // network callback ping through it. Taken after socketMutex when both are
213 // held, and never with a PingHost's lock held.
214 std::mutex pingHostsLock;
215 // Init() has started the pings: outputs attached after that are pinged as
216 // they attach.
217 bool pingsStarted = false;
218 // Adds a pingable output to its controller's PingHost, creating the host
219 // if it is new (returned, so the caller can ping it). pingHostsLock held.
220 std::shared_ptr<PingHost> addPingTarget(UDPOutputData* o);
221 // Takes an output back off its controller's host, and stops pinging a
222 // controller left with no outputs. pingHostsLock held.
223 void removePingTarget(UDPOutputData* o);
224 void OnPingResult(const std::shared_ptr<PingHost>& host, int ms);
225 void SetHostValid(PingHost& host, bool valid);
226
227 std::mutex socketMutex;
228 UDPOutputMessages messages;
229 bool enabled;
230
231 std::list<UDPOutputData*> outputs;
232
233 static std::mutex externalLock;
234 static std::map<const void*, std::function<UDPOutputData*()>> externalFactories;
235 std::map<const void*, UDPOutputData*> externalOutputs;
236 void attachExternalOutput(const void* owner, UDPOutputData* d);
237 static UDPOutputData* createExternalOutput(const std::function<UDPOutputData*()>& create);
238
239 int networkCallbackId;
240
241 void PingControllers(bool failedOnly);
242 // Takes this output's periodic pings back out of the PingManager (their
243 // callbacks capture this) and its "unreachable" warnings down. Close()
244 // does it; the destructor does it for an output deleted without Close(),
245 // as the loader deletes one whose Init() failed. Once only: after
246 // Close(), a replacement output may hold pings for the same hosts.
247 void StopPinging();
248 bool pingsStopped = false;
249 // controllers that have not answered yet; Init() waits on it
250 std::atomic_int failedCount;
251 std::string HexToIP(unsigned int hex);
252
253 void CheckLocalDrops();
254
255 // A WorkItem owns a copy of the mmsghdr list and a reference on the socket
256 // info so a worker that outlives its frame (stuck send to a dead controller)
257 // cannot hit freed memory when PrepData rebuilds the message vectors or
258 // an address change drops the sockets. Note the copy is shallow: the iovecs
259 // still point at per-output buffers, so a late send may transmit the
260 // *current* frame's bytes - acceptable, and no worse than it ever was.
261 // generation identifies which frame queued it.
262 class WorkItem {
263 public:
264 151095 WorkItem(unsigned int i, std::shared_ptr<SendSocketInfo> si, const std::vector<struct mmsghdr>& m, unsigned int g) :
265 151095 id(i),
266 151095 socketInfo(si),
267
1/2
✓ Branch 0 taken 151095 times.
✗ Branch 1 not taken.
151095 msgs(m),
268 151095 generation(g) {}
269 unsigned int id;
270 std::shared_ptr<SendSocketInfo> socketInfo;
271 std::vector<struct mmsghdr> msgs;
272 unsigned int generation;
273 };
274
275 std::mutex workMutex;
276 std::condition_variable workSignal;
277 std::list<WorkItem> workQueue;
278 // Keys a worker is sending to right now (under workMutex). With the keys
279 // still queued, these are the destinations whose packet buffers a worker
280 // may be reading, which PrepData() must not rewrite.
281 std::multiset<unsigned int> sendingKeys;
282 // The destination keys each output's packets went to when it was last
283 // prepared, and the outputs PrepData() left alone this frame (both under
284 // socketMutex).
285 std::map<UDPOutputData*, std::vector<unsigned int>> outputKeys;
286 std::set<UDPOutputData*> skippedOutputs;
287 std::atomic_int doneWorkCount;
288 std::atomic_int numWorkThreads;
289 std::atomic_uint workGeneration;
290 volatile bool runWorkThreads;
291 bool useThreadedOutput;
292 bool blockingOutput;
293
294 // fq/SO_MAX_PACING_RATE based pacing; when active the kernel clocks packets
295 // out at pacingRate per socket and the SIOCOUTQ drain waits are skipped
296 bool pacingEnabled = false;
297 unsigned int pacingRate = 0; // bytes per second (global default)
298
299 // rate (bytes/sec) used only for the pre-sync drain-sleep estimate; the
300 // smallest positive rate among the global rate and all per-destination
301 // overrides, so a mixed set sleeps long enough for the slowest queue and we
302 // never divide by a zero global rate when only overrides are paced.
303 unsigned int pacingDrainRate = 0;
304
305 // per-destination-IP pacing rate in bytes/sec, built in Init() from the
306 // per-output pacingRate overrides. A destination not present here uses the
307 // global pacingRate; a value of ~0U means the controller was explicitly set
308 // to unpaced. The socket is shared per destination IP, so when several
309 // outputs target the same controller with differing overrides the most
310 // conservative (lowest) rate wins.
311 std::map<in_addr_t, unsigned int> perDestPacingRate;
312
313 // local drop diagnostics; the check runs on a short detached thread since
314 // reading qdisc stats forks tc, which is too slow for the frame path
315 int statCheckCounter = 0;
316 std::atomic_bool statCheckRunning{ false };
317 bool statBaselineValid = false;
318 bool dropWarningActive = false;
319 uint64_t lastSndbufErrors = 0;
320 uint64_t lastTxDropped = 0;
321 uint64_t lastQdiscDropped = 0;
322 };
323