GCC Code Coverage Report


Directory: ./
File: channeloutput/HTTPVirtualDisplay.cpp
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 338 358 94.4%
Functions: 14 15 93.3%
Branches: 268 452 59.3%

Line Branch Exec Source
1 /*
2 * This file is part of the Falcon Player (FPP) and is Copyright (C)
3 * 2013-2022 by the Falcon Player Developers.
4 *
5 * The Falcon Player (FPP) is free software, and is covered under
6 * multiple Open Source licenses. Please see the included 'LICENSES'
7 * file for descriptions of what files are covered by each license.
8 *
9 * This source file is covered under the GPL v2 as described in the
10 * included LICENSE.GPL file.
11 */
12
13 #include "fpp-pch.h"
14
15 #include "fpp-json.h"
16
17
18 #include <netinet/in.h>
19 #include <poll.h>
20 #include <sys/socket.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23
24 #include <algorithm>
25 #include <ctime>
26 #include <iomanip>
27
28 #include "../fppversion.h"
29 #include "../log.h"
30 #include "../common.h"
31
32 #include "HTTPVirtualDisplay.h"
33 #include "ChannelOutputSetup.h"
34
35 #include "Plugin.h"
36 #include "../SysSocket.h"
37
38 // RGB666 components and pixel locations travel as these characters, since
39 // SSE carries text. The page decodes with the same table.
40 static const char SSE_BASE64[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
41
42 class HTTPVirtualDisplayPlugin : public FPPPlugins::Plugin, public FPPPlugins::ChannelOutputPlugin {
43 public:
44 18 HTTPVirtualDisplayPlugin() :
45
2/4
✓ Branch 0 taken 18 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 18 times.
✗ Branch 3 not taken.
54 FPPPlugins::Plugin("HTTPVirtualDisplay") {
46 18 }
47 27 virtual ChannelOutput* createChannelOutput(unsigned int startChannel, unsigned int channelCount) override {
48
2/6
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 27 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
54 return new HTTPVirtualDisplayOutput(startChannel, channelCount);
49 }
50 };
51
52 extern "C" {
53 18 FPPPlugins::Plugin* createPlugin() {
54
2/6
✓ Branch 0 taken 18 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 18 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
36 return new HTTPVirtualDisplayPlugin();
55 }
56 }
57 /////////////////////////////////////////////////////////////////////////////
58
59 /*
60 *
61 */
62 27 HTTPVirtualDisplayOutput::HTTPVirtualDisplayOutput(unsigned int startChannel,
63 27 unsigned int channelCount) :
64 VirtualDisplayBaseOutput(startChannel, channelCount),
65 27 m_port(HTTPVIRTUALDISPLAYPORT),
66 27 m_screenSize(0),
67 27 m_updateInterval(25), // Default: 25ms (40fps), about all a browser can render
68 27 m_nextSendMS(0),
69 27 m_socket(-1),
70 27 m_running(true),
71 27 m_connListChanged(true),
72 27 m_resetCache(false),
73 27 m_connThread(nullptr),
74 54 m_selectThread(nullptr) {
75
1/2
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
27 LogDebug(VB_CHANNELOUT, "HTTPVirtualDisplayOutput::HTTPVirtualDisplayOutput(%u, %u)\n",
76 startChannel, channelCount);
77
78 27 m_bytesPerPixel = 3;
79 27 m_bpp = 24;
80 27 }
81
82 /*
83 *
84 */
85 108 HTTPVirtualDisplayOutput::~HTTPVirtualDisplayOutput() {
86 54 LogDebug(VB_CHANNELOUT, "HTTPVirtualDisplayOutput::~HTTPVirtualDisplayOutput()\n");
87
88 54 m_running = false;
89
90
2/2
✓ Branch 0 taken 25 times.
✓ Branch 1 taken 2 times.
54 if (m_connThread) {
91 50 m_connThread->join();
92
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
50 delete m_connThread;
93 50 m_connThread = nullptr;
94 }
95
96
2/2
✓ Branch 0 taken 25 times.
✓ Branch 1 taken 2 times.
54 if (m_selectThread) {
97 50 m_selectThread->join();
98
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
50 delete m_selectThread;
99 50 m_selectThread = nullptr;
100 }
101
102
2/2
✓ Branch 0 taken 25 times.
✓ Branch 1 taken 2 times.
54 if (m_socket >= 0) {
103 50 close(m_socket);
104 50 m_socket = -1;
105 }
106
107
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 26 times.
54 if (m_connList.size()) {
108
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1 times.
4 for (int i = m_connList.size() - 1; i >= 0; i--) {
109 2 close(m_connList[i]);
110 2 m_connList.erase(m_connList.begin() + i);
111 }
112 }
113 108 }
114
115 /*
116 *
117 */
118 25 void RunConnectionThread(HTTPVirtualDisplayOutput* VirtualDisplay) {
119 25 LogDebug(VB_CHANNELOUT, "Started ConnectionThread()\n");
120 25 VirtualDisplay->ConnectionThread();
121 25 }
122
123 /*
124 *
125 */
126 25 void RunSelectThread(HTTPVirtualDisplayOutput* VirtualDisplay) {
127 25 LogDebug(VB_CHANNELOUT, "Started SelectThread()\n");
128 25 VirtualDisplay->SelectThread();
129 25 }
130
131 /*
132 *
133 */
134 27 int HTTPVirtualDisplayOutput::Init(Json::Value config) {
135
1/2
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
27 LogDebug(VB_CHANNELOUT, "HTTPVirtualDisplayOutput::Init()\n");
136
137
3/6
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 27 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 27 times.
27 if (!VirtualDisplayBaseOutput::Init(config))
138 ✗ return 0;
139
140
2/4
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 27 times.
✗ Branch 3 not taken.
27 if (config.isMember("port"))
141
2/4
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 27 times.
✗ Branch 3 not taken.
27 m_port = config["port"].asInt();
142
143
2/4
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 27 times.
27 if (config.isMember("updateInterval"))
144 ✗ m_updateInterval = config["updateInterval"].asInt();
145
146 // Clamp to reasonable values (10-100ms between updates)
147 // Typical: 25ms for 40fps, 16ms for 60fps, 50ms for 20fps
148
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 if (m_updateInterval < 10) m_updateInterval = 10;
149
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 if (m_updateInterval > 100) m_updateInterval = 100;
150
151 // Signal base class to allocate m_virtualDisplay buffer
152 27 m_width = -1;
153 27 m_height = -1;
154
155
3/4
✓ Branch 0 taken 27 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 26 times.
27 if (!InitializePixelMap()) {
156
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogErr(VB_CHANNELOUT, "Error, unable to initialize pixel map\n");
157
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 AddOutputConfigWarning(37, "Virtual Display preview: could not initialize pixel map");
158 1 return 0;
159 }
160
161 // An empty map parses "successfully" but allocates nothing (and absurd map
162 // dimensions fail the allocation above the same way): refuse to run with
163 // no buffer or dimensions that cannot form one, instead of crashing on
164 // the first draw/status poll.
165
4/4
✓ Branch 0 taken 25 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 25 times.
51 if (m_virtualDisplay == nullptr ||
166
2/4
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 25 times.
25 virtualDisplayBufferBytes(m_width, m_height, m_bytesPerPixel) == 0) {
167
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogErr(VB_CHANNELOUT, "Error, virtual display has no usable buffer (%dx%d)\n",
168 m_width, m_height);
169
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 AddOutputConfigWarning(37, "Virtual Display preview: could not initialize pixel map");
170 1 return 0;
171 }
172
173
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_screenSize = (int)virtualDisplayBufferBytes(m_width, m_height, m_bytesPerPixel);
174
175 // Worst case a frame touches every pixel; size this once so the hot loop
176 // never reallocates
177
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_cacheRollback.reserve(m_pixels.size() * 3);
178
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_changedColor.reserve(m_pixels.size());
179
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_changedIndex.reserve(m_pixels.size());
180
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_sortColor.reserve(m_pixels.size());
181
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_sortIndex.reserve(m_pixels.size());
182
183 // Each pixel's location key never changes, so spell it once here. It
184 // must take the same form as the page's scaleMap keys
185 // (virtualdisplaybody.php), or the browser finds no entry for the pixel
186 // and drops the rest of the frame.
187 25 m_pixelLocs.clear();
188
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_pixelLocs.reserve(m_pixels.size());
189
2/2
✓ Branch 0 taken 20375 times.
✓ Branch 1 taken 25 times.
20400 for (const auto& px : m_pixels) {
190 PixelLoc loc;
191 20375 int x = px.x;
192 20375 int y = m_previewHeight - px.y;
193
3/4
✓ Branch 0 taken 20351 times.
✓ Branch 1 taken 24 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 20351 times.
20375 if ((x >= 4096) || (y >= 4096)) {
194 24 loc.s[0] = SSE_BASE64[(x >> 12) & 0x3f];
195 24 loc.s[1] = SSE_BASE64[(x >> 6) & 0x3f];
196 24 loc.s[2] = SSE_BASE64[x & 0x3f];
197 24 loc.s[3] = SSE_BASE64[(y >> 12) & 0x3f];
198 24 loc.s[4] = SSE_BASE64[(y >> 6) & 0x3f];
199 24 loc.s[5] = SSE_BASE64[y & 0x3f];
200 24 loc.len = 6;
201 } else {
202 20351 loc.s[0] = SSE_BASE64[(x >> 6) & 0x3f];
203 20351 loc.s[1] = SSE_BASE64[x & 0x3f];
204 20351 loc.s[2] = SSE_BASE64[(y >> 6) & 0x3f];
205 20351 loc.s[3] = SSE_BASE64[y & 0x3f];
206 20351 loc.len = 4;
207 }
208
1/2
✓ Branch 0 taken 20375 times.
✗ Branch 1 not taken.
20375 m_pixelLocs.push_back(loc);
209 }
210
211 25 bzero(m_virtualDisplay, m_screenSize);
212
213 // Bind a dual-stack socket (IPv6 with V6ONLY off) so the SSE feed
214 // is reachable on both IPv4 and IPv6 clients without needing two
215 // listeners. Apache's mod_proxy talks to us on localhost; both
216 // 127.0.0.1 and ::1 land here.
217 25 m_socket = OpenSocket(AF_INET6, SOCK_STREAM, 0);
218
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 25 times.
25 if (m_socket < 0) {
219 ✗ LogErr(VB_CHANNELOUT, "Could not create socket: %s\n", FPPstrerror(errno));
220 ✗ AddOutputConfigWarning(37, "Virtual Display preview: could not create socket");
221 ✗ return 0;
222 }
223
224
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 fcntl(m_socket, F_SETFL, O_NONBLOCK);
225
226 // SO_REUSEADDR so a reload can rebind while the previous instance's
227 // connections sit in TIME_WAIT. Not SO_REUSEPORT: that lets a listener
228 // that was never closed keep taking a share of the new connections.
229 25 int optval = 1;
230
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 25 times.
25 if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) {
231 ✗ LogErr(VB_CHANNELOUT, "Error turning on SO_REUSEADDR; %s\n", FPPstrerror(errno));
232 ✗ return 0;
233 }
234 25 int v6only = 0;
235 25 setsockopt(m_socket, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
236
237 struct sockaddr_in6 addr;
238 25 memset(&addr, 0, sizeof(addr));
239 25 addr.sin6_family = AF_INET6;
240 25 addr.sin6_addr = in6addr_any;
241 25 addr.sin6_port = htons(m_port);
242
243 25 int rc = bind(m_socket, (struct sockaddr*)&addr, sizeof(addr));
244
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 25 times.
25 if (rc < 0) {
245 ✗ LogErr(VB_CHANNELOUT, "Could not bind socket: %s\n", FPPstrerror(errno));
246 ✗ AddOutputConfigWarning(37, "Virtual Display preview: could not bind to its port (already in use?)");
247 ✗ return 0;
248 }
249
250 25 rc = listen(m_socket, 5);
251
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 25 times.
25 if (rc < 0) {
252 ✗ LogErr(VB_CHANNELOUT, "Could not listen on socket: %s\n", FPPstrerror(errno));
253 ✗ AddOutputConfigWarning(37, "Virtual Display preview: could not listen on its socket");
254 ✗ return 0;
255 }
256
257
3/8
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 25 times.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
25 m_connThread = new std::thread(RunConnectionThread, this);
258
3/8
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 25 times.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
25 m_selectThread = new std::thread(RunSelectThread, this);
259 25 return 1;
260 }
261
262 /*
263 *
264 */
265 25 int HTTPVirtualDisplayOutput::Close(void) {
266 25 LogDebug(VB_CHANNELOUT, "HTTPVirtualDisplayOutput::Close()\n");
267
268 25 return VirtualDisplayBaseOutput::Close();
269 }
270
271 /*
272 *
273 */
274 25 void HTTPVirtualDisplayOutput::ConnectionThread(void) {
275
2/4
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
25 SetThreadName("FPP-HTTPVD-Con");
276 int client;
277
278
2/2
✓ Branch 0 taken 828 times.
✓ Branch 1 taken 25 times.
853 while (m_running) {
279
1/2
✓ Branch 0 taken 828 times.
✗ Branch 1 not taken.
828 client = AcceptSocket(m_socket, NULL, NULL);
280
281
2/2
✓ Branch 0 taken 91 times.
✓ Branch 1 taken 737 times.
828 if (client >= 0) {
282 // Enable TCP keepalive to detect dead connections
283 91 int keepalive = 1;
284 91 setsockopt(client, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
285
286 // Accepted sockets don't inherit O_NONBLOCK from the listener, so
287 // set it explicitly - otherwise a browser that stops draining its
288 // socket blocks write() on the channel output thread, which stalls
289 // the actual light output, not just this preview.
290
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 int flags = fcntl(client, F_GETFL, 0);
291
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 fcntl(client, F_SETFL, (flags < 0 ? 0 : flags) | O_NONBLOCK);
292
293 91 auto t = std::time(nullptr);
294 struct tm tm;
295 91 localtime_r(&t, &tm);
296
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 std::stringstream sstr;
297
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 sstr << std::put_time(&tm, "%a %b %d %H:%M:%S %Z %Y");
298
299 91 std::string sseResp;
300 sseResp =
301 "HTTP/1.1 200 OK\r\n"
302 "Content-Type: text/event-stream;charset=UTF-8\r\n"
303 "Transfer-Encoding: chunked\r\n"
304 "Connection: close\r\n"
305
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 "Date: ";
306
2/4
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 91 times.
✗ Branch 3 not taken.
91 sseResp += sstr.str();
307 sseResp +=
308 "\r\n"
309 "Server: fppd\r\n"
310
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 "X-Powered-By: FPP/";
311
2/4
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 91 times.
✗ Branch 3 not taken.
91 sseResp += getFPPVersion();
312 sseResp += "\r\n"
313 "Cache-Control: no-cache, private\r\n"
314 "Access-Control-Allow-Origin: *\r\n"
315 "Access-Control-Allow-Credentials: true\r\n"
316
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 "\r\n";
317
318 // Have the output thread reset its display cache so the next frame
319 // draws everything; set before the client is listed, so a frame that
320 // sees the client also sees the reset.
321
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 std::unique_lock<std::mutex> lock(m_connListLock);
322 91 m_resetCache = true;
323
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 m_connList.push_back(client);
324
325
1/2
✓ Branch 0 taken 91 times.
✗ Branch 1 not taken.
91 write(client, sseResp.c_str(), sseResp.length());
326
327 91 m_connListChanged = true;
328 91 }
329
330
1/2
✓ Branch 0 taken 828 times.
✗ Branch 1 not taken.
828 usleep(100000);
331 }
332 25 }
333
334 /*
335 *
336 */
337 25 void HTTPVirtualDisplayOutput::SelectThread(void) {
338
2/4
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
25 SetThreadName("FPP-HTTPVD-Sel");
339 fd_set active_fd_set;
340 fd_set read_fd_set;
341 int selectResult;
342 struct timeval timeout;
343 char buf[1024];
344 int bytesRead;
345
346
2/2
✓ Branch 0 taken 400 times.
✓ Branch 1 taken 25 times.
425 FD_ZERO(&active_fd_set);
347
348
2/2
✓ Branch 0 taken 119 times.
✓ Branch 1 taken 25 times.
144 while (m_running) {
349
2/2
✓ Branch 0 taken 78 times.
✓ Branch 1 taken 41 times.
119 if (m_connListChanged) {
350
1/2
✓ Branch 0 taken 78 times.
✗ Branch 1 not taken.
78 LogDebug(VB_CHANNELOUT, "Connection list changed, rebuilding active_fd-set\n");
351
2/2
✓ Branch 0 taken 1248 times.
✓ Branch 1 taken 78 times.
1326 FD_ZERO(&active_fd_set);
352
353
1/2
✓ Branch 0 taken 78 times.
✗ Branch 1 not taken.
78 std::unique_lock<std::mutex> lock(m_connListLock);
354
355
2/2
✓ Branch 0 taken 49 times.
✓ Branch 1 taken 78 times.
127 for (int i = 0; i < m_connList.size(); i++) {
356 49 FD_SET(m_connList[i], &active_fd_set);
357 }
358
359 78 m_connListChanged = false;
360 78 }
361
362 119 timeout.tv_sec = 1;
363 119 timeout.tv_usec = 0;
364
365 119 read_fd_set = active_fd_set;
366
367
1/2
✓ Branch 0 taken 119 times.
✗ Branch 1 not taken.
119 selectResult = select(FD_SETSIZE, &read_fd_set, NULL, NULL, &timeout);
368
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 119 times.
119 if (selectResult < 0) {
369 ✗ if (errno == EINTR) {
370 93 continue;
371 } else {
372 ✗ LogErr(VB_CHANNELOUT, "Main select() failed\n");
373 }
374
2/2
✓ Branch 0 taken 93 times.
✓ Branch 1 taken 26 times.
119 } else if (selectResult == 0) {
375 // Nothing to do
376 93 continue;
377 }
378
379
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 std::unique_lock<std::mutex> lock(m_connListLock);
380
2/2
✓ Branch 0 taken 47 times.
✓ Branch 1 taken 26 times.
73 for (int i = m_connList.size() - 1; i >= 0; i--) {
381
2/2
✓ Branch 0 taken 42 times.
✓ Branch 1 taken 5 times.
47 if (FD_ISSET(m_connList[i], &read_fd_set)) {
382
1/2
✓ Branch 0 taken 42 times.
✗ Branch 1 not taken.
42 bytesRead = recv(m_connList[i], buf, sizeof(buf), 0);
383
384
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 42 times.
42 if (bytesRead > 0) {
385 ✗ LogDebug(VB_CHANNELOUT, "Data read from socket %d, connection %d \n", m_connList[i], i);
386
2/2
✓ Branch 0 taken 17 times.
✓ Branch 1 taken 25 times.
42 } else if (bytesRead == 0) {
387
1/2
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
17 LogDebug(VB_CHANNELOUT, "Closing socket %d, connection %d\n", m_connList[i], i);
388
1/2
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
17 close(m_connList[i]);
389
1/2
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
17 m_connList.erase(m_connList.begin() + i);
390 17 m_connListChanged = true;
391 } else {
392
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 LogErr(VB_CHANNELOUT, "Read failed for socket %d, connection %d. Closing connection.\n", m_connList[i], i);
393
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 close(m_connList[i]);
394
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 m_connList.erase(m_connList.begin() + i);
395 25 m_connListChanged = true;
396 }
397 }
398 }
399 26 }
400 25 }
401
402 /*
403 *
404 */
405 // The output thread's whole budget for preview writes in one frame, and how
406 // many frames in a row a client may refuse before it is dropped.
407 static constexpr uint64_t SSE_FRAME_BUDGET_MS = 20;
408 static constexpr int SSE_MAX_DROPPED_FRAMES = 200;
409
410 1040 int HTTPVirtualDisplayOutput::WriteSSEPacket(int fd, const std::string& data, uint64_t deadlineMS) {
411 1040 int len = data.size();
412 1040 std::string sendData;
413
414 // Pre-allocate to avoid reallocations
415
1/2
✓ Branch 0 taken 1040 times.
✗ Branch 1 not taken.
1040 sendData.reserve(20 + len); // hex length + delimiters + data
416
417 // Convert length to hex directly into string
418 char hexBuf[16];
419 1040 snprintf(hexBuf, sizeof(hexBuf), "%x", len);
420
421
1/2
✓ Branch 0 taken 1040 times.
✗ Branch 1 not taken.
1040 sendData = hexBuf;
422
1/2
✓ Branch 0 taken 1040 times.
✗ Branch 1 not taken.
1040 sendData += "\r\n";
423
1/2
✓ Branch 0 taken 1040 times.
✗ Branch 1 not taken.
1040 sendData += data;
424
1/2
✓ Branch 0 taken 1040 times.
✗ Branch 1 not taken.
1040 sendData += "\r\n";
425
426 1040 size_t total = sendData.size();
427 1040 size_t sent = 0;
428
429
2/2
✓ Branch 0 taken 1044 times.
✓ Branch 1 taken 775 times.
1819 while (sent < total) {
430
1/2
✓ Branch 0 taken 1044 times.
✗ Branch 1 not taken.
1044 ssize_t written = write(fd, sendData.c_str() + sent, total - sent);
431
432
2/2
✓ Branch 0 taken 778 times.
✓ Branch 1 taken 266 times.
1044 if (written > 0) {
433 778 sent += written;
434 778 continue;
435 }
436
437
2/4
✓ Branch 0 taken 266 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 266 times.
266 if (written < 0 && errno == EINTR) {
438 ✗ continue;
439 }
440
441
4/6
✓ Branch 0 taken 266 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 45 times.
✓ Branch 3 taken 221 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 45 times.
266 if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
442
2/2
✓ Branch 0 taken 218 times.
✓ Branch 1 taken 3 times.
221 if (sent == 0) {
443 // The client isn't draining fast enough and the send buffer is
444 // full. Drop this frame rather than the connection - nothing is
445 // on the wire yet. The caller resyncs the client afterwards,
446 // since the pixel changes in this payload are only sent once.
447
1/2
✓ Branch 0 taken 218 times.
✗ Branch 1 not taken.
218 LogExcess(VB_CHANNELOUT, "SSE send buffer full, dropping frame\n");
448 220 return 0;
449 }
450
451 // We're part way through a chunk. We can't abandon it - the client
452 // is counting out the bytes we promised in the chunk header, so a
453 // truncated chunk desyncs the stream permanently. Wait (briefly)
454 // for room and finish it.
455 struct pollfd pfd;
456 3 pfd.fd = fd;
457 3 pfd.events = POLLOUT;
458 // Bounded by the frame's budget, not per client per stall: a
459 // client trickling a few bytes at a time otherwise held the
460 // output thread (and every output) for as long as it liked.
461
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 long long left = (long long)deadlineMS - (long long)GetMonotonicTimeMS();
462
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 2 times.
3 if (left <= 0) {
463
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogDebug(VB_CHANNELOUT, "SSE client too slow for this frame (%zu/%zu bytes), closing connection\n", sent, total);
464 1 return -1;
465 }
466
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 int pr = poll(&pfd, 1, (int)std::min<long long>(left, 250));
467
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1 times.
2 if (pr > 0) {
468 1 continue;
469 }
470
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
1 if (pr < 0 && errno == EINTR) {
471 ✗ continue;
472 }
473
474
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogDebug(VB_CHANNELOUT, "SSE stalled part way through a chunk (%zu/%zu bytes), closing connection\n",
475 sent, total);
476 1 return -1;
477 }
478
479 // EPIPE/ECONNRESET/ENOTCONN and anything else: the connection is gone
480
2/4
✓ Branch 0 taken 45 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 45 times.
✗ Branch 3 not taken.
45 LogDebug(VB_CHANNELOUT, "SSE write failed (connection closed): %s\n", FPPstrerror(errno));
481 45 return -1;
482 }
483
484 775 return 1;
485 1040 }
486
487 /*
488 *
489 */
490 1420 void HTTPVirtualDisplayOutput::PrepData(unsigned char* channelData) {
491
1/2
✓ Branch 0 taken 1420 times.
✗ Branch 1 not taken.
1420 LogExcess(VB_CHANNELOUT, "HTTPVirtualDisplayOutput::PrepData(%p)\n",
492 channelData);
493
494 {
495 // Short circuit if no current connections
496
1/2
✓ Branch 0 taken 1420 times.
✗ Branch 1 not taken.
1420 std::unique_lock<std::mutex> lock(m_connListLock);
497
2/2
✓ Branch 0 taken 463 times.
✓ Branch 1 taken 957 times.
1420 if (!m_connList.size()) {
498 463 m_sseData.clear();
499 463 return;
500 }
501
2/2
✓ Branch 0 taken 957 times.
✓ Branch 1 taken 463 times.
1420 }
502
503 // We run at the sequence frame rate, which can now be well above anything a
504 // browser can render. Sending faster than the client drains just piles
505 // frames up in the socket and proxy buffers, so the preview falls further
506 // and further behind playback. Rate limit to m_updateInterval instead.
507 //
508 // Skipping a frame here is safe even though we send deltas: m_virtualDisplay
509 // is only updated for pixels we actually emit, so it always holds what the
510 // client was last sent and the next diff simply spans a longer gap.
511 //
512 // The deadline is advanced by whole intervals rather than reset to "now" so
513 // that an update interval which isn't a multiple of the frame time still
514 // averages out to the requested rate instead of aliasing down to the next
515 // frame boundary (eg. 25ms against a 20ms sequence gives 40fps, not 25fps).
516
1/2
✓ Branch 0 taken 957 times.
✗ Branch 1 not taken.
957 long long now = GetMonotonicTimeMS();
517
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 957 times.
957 if (now < m_nextSendMS) {
518 ✗ m_sseData.clear();
519 ✗ return;
520 }
521 957 m_nextSendMS += m_updateInterval;
522
2/2
✓ Branch 0 taken 931 times.
✓ Branch 1 taken 26 times.
957 if (m_nextSendMS <= now) {
523 // First frame, or we've been idle/stalled long enough that the deadline
524 // is stale - resync rather than sending a burst to catch up.
525 931 m_nextSendMS = now + m_updateInterval;
526 }
527
528 // Start a fresh rollback record for this frame's cache writes
529 957 m_cacheRollback.clear();
530
531 // A client joined: it has nothing yet, so diff this frame against black.
532
2/2
✓ Branch 0 taken 67 times.
✓ Branch 1 taken 890 times.
957 if (m_resetCache.exchange(false)) {
533 67 bzero(m_virtualDisplay, m_screenSize);
534 }
535
536 // Fast black detection - check if all channel data is zero (sequence ended/stopped)
537 // Only do this check occasionally to reduce CPU overhead
538 957 bool allBlack = false;
539 957 bool forceBlackUpdate = false;
540
541 // Check for black every 10th frame to reduce CPU, but always check if last frame was black
542 // to catch the transition back to color quickly
543
5/6
✓ Branch 0 taken 957 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 92 times.
✓ Branch 3 taken 865 times.
✓ Branch 4 taken 92 times.
✓ Branch 5 taken 865 times.
957 if (m_lastFrameWasBlack || (++m_blackCheckCounter >= 10)) {
544 92 m_blackCheckCounter = 0;
545 92 allBlack = true;
546
6/6
✓ Branch 0 taken 10128 times.
✓ Branch 1 taken 55 times.
✓ Branch 2 taken 10091 times.
✓ Branch 3 taken 37 times.
✓ Branch 4 taken 10091 times.
✓ Branch 5 taken 92 times.
10183 for (int i = 0; i < m_pixels.size() && allBlack; i++) {
547 unsigned char r, g, b;
548
1/2
✓ Branch 0 taken 10091 times.
✗ Branch 1 not taken.
10091 GetPixelRGB(m_pixels[i], channelData, r, g, b);
549
6/6
✓ Branch 0 taken 10028 times.
✓ Branch 1 taken 63 times.
✓ Branch 2 taken 10013 times.
✓ Branch 3 taken 15 times.
✓ Branch 4 taken 13 times.
✓ Branch 5 taken 10000 times.
10091 if (r != 0 || g != 0 || b != 0) {
550 91 allBlack = false;
551 }
552 }
553
554 // If transitioning to black, force update of all pixels
555
3/4
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 91 times.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
92 forceBlackUpdate = (allBlack && !m_lastFrameWasBlack);
556 92 m_lastFrameWasBlack = allBlack;
557 }
558
559 // Collect the changed pixels, then group them by colour by sorting: the
560 // payload is "RGB:loc;loc|RGB:loc..." and the page does not care in which
561 // order the colours come. This runs on the channel output thread for
562 // every changed pixel, so nothing here formats or allocates per pixel.
563 957 m_changedColor.clear();
564 957 m_changedIndex.clear();
565 unsigned char r, g, b;
566
2/2
✓ Branch 0 taken 1544909 times.
✓ Branch 1 taken 957 times.
1545866 for (int i = 0; i < m_pixels.size(); i++) {
567
1/2
✓ Branch 0 taken 1544909 times.
✗ Branch 1 not taken.
1544909 GetPixelRGB(m_pixels[i], channelData, r, g, b);
568
569 // 18-bit RGB666 pixel data passed over Event Stream in 3 bytes
570 // using Base64 allowed characters since SSE is non-binary
571 1544909 r = r >> 2;
572 1544909 g = g >> 2;
573 1544909 b = b >> 2;
574
575 // Send pixels that changed OR when forcing black update (sequence ended)
576 3079818 if (forceBlackUpdate ||
577
2/2
✓ Branch 0 taken 1159725 times.
✓ Branch 1 taken 375184 times.
1534909 (m_virtualDisplay[m_pixels[i].r] != r) ||
578
6/6
✓ Branch 0 taken 1534909 times.
✓ Branch 1 taken 10000 times.
✓ Branch 2 taken 955456 times.
✓ Branch 3 taken 204269 times.
✓ Branch 4 taken 693483 times.
✓ Branch 5 taken 851426 times.
4035274 (m_virtualDisplay[m_pixels[i].g] != g) ||
579
2/2
✓ Branch 0 taken 104030 times.
✓ Branch 1 taken 851426 times.
955456 (m_virtualDisplay[m_pixels[i].b] != b)) {
580 // Remember the pre-send values so SendData can undo them if this
581 // frame never makes it to the client
582
1/2
✓ Branch 0 taken 693483 times.
✗ Branch 1 not taken.
693483 m_cacheRollback.emplace_back(m_pixels[i].r, m_virtualDisplay[m_pixels[i].r]);
583
1/2
✓ Branch 0 taken 693483 times.
✗ Branch 1 not taken.
693483 m_cacheRollback.emplace_back(m_pixels[i].g, m_virtualDisplay[m_pixels[i].g]);
584
1/2
✓ Branch 0 taken 693483 times.
✗ Branch 1 not taken.
693483 m_cacheRollback.emplace_back(m_pixels[i].b, m_virtualDisplay[m_pixels[i].b]);
585
586 693483 m_virtualDisplay[m_pixels[i].r] = r;
587 693483 m_virtualDisplay[m_pixels[i].g] = g;
588 693483 m_virtualDisplay[m_pixels[i].b] = b;
589
590
1/2
✓ Branch 0 taken 693483 times.
✗ Branch 1 not taken.
693483 m_changedColor.push_back(((uint32_t)r << 12) | ((uint32_t)g << 6) | b);
591
1/2
✓ Branch 0 taken 693483 times.
✗ Branch 1 not taken.
693483 m_changedIndex.push_back((uint32_t)i);
592 }
593 }
594
595 957 m_sseData.clear();
596
1/2
✓ Branch 0 taken 957 times.
✗ Branch 1 not taken.
957 m_sseData += "id: ";
597
1/2
✓ Branch 0 taken 957 times.
✗ Branch 1 not taken.
957 m_sseData += std::to_string(m_sseId);
598
1/2
✓ Branch 0 taken 957 times.
✗ Branch 1 not taken.
957 m_sseData += "\r\n";
599 957 const size_t changed = m_changedColor.size();
600
2/2
✓ Branch 0 taken 402 times.
✓ Branch 1 taken 555 times.
957 if (changed) {
601 // LSD radix sort on the 18-bit colour, two 9-bit digits. Stable, so
602 // each colour's pixels stay in map order.
603
1/2
✓ Branch 0 taken 402 times.
✗ Branch 1 not taken.
402 m_sortColor.resize(changed);
604
1/2
✓ Branch 0 taken 402 times.
✗ Branch 1 not taken.
402 m_sortIndex.resize(changed);
605
2/2
✓ Branch 0 taken 804 times.
✓ Branch 1 taken 402 times.
1206 for (int shift = 0; shift < 18; shift += 9) {
606 804 uint32_t start[513] = { 0 };
607
2/2
✓ Branch 0 taken 1386966 times.
✓ Branch 1 taken 804 times.
1387770 for (uint32_t c : m_changedColor) {
608 1386966 start[((c >> shift) & 511) + 1]++;
609 }
610
2/2
✓ Branch 0 taken 411648 times.
✓ Branch 1 taken 804 times.
412452 for (int d = 0; d < 512; d++) {
611 411648 start[d + 1] += start[d];
612 }
613
2/2
✓ Branch 0 taken 1386966 times.
✓ Branch 1 taken 804 times.
1387770 for (size_t k = 0; k < changed; k++) {
614 1386966 uint32_t at = start[(m_changedColor[k] >> shift) & 511]++;
615 1386966 m_sortColor[at] = m_changedColor[k];
616 1386966 m_sortIndex[at] = m_changedIndex[k];
617 }
618 804 m_changedColor.swap(m_sortColor);
619 804 m_changedIndex.swap(m_sortIndex);
620 }
621
622 static const char header[] = "event: message\r\ndata: ";
623 // Worst case: every pixel a new colour ("|RGB:", 5) with a 6-byte
624 // location, plus the closing "\r\n\r\n". Written through a pointer
625 // and trimmed after: per-character appends were most of the cost.
626 402 const size_t prefix = m_sseData.size();
627
1/2
✓ Branch 0 taken 402 times.
✗ Branch 1 not taken.
402 m_sseData.resize(prefix + sizeof(header) - 1 + changed * 11 + 4);
628 402 char* out = m_sseData.data() + prefix;
629 402 memcpy(out, header, sizeof(header) - 1);
630 402 out += sizeof(header) - 1;
631
632 402 uint32_t lastColor = UINT32_MAX;
633 402 int colorCount = 0;
634
2/2
✓ Branch 0 taken 693483 times.
✓ Branch 1 taken 402 times.
693885 for (size_t k = 0; k < changed; k++) {
635 693483 uint32_t color = m_changedColor[k];
636 693483 const PixelLoc& loc = m_pixelLocs[m_changedIndex[k]];
637
2/2
✓ Branch 0 taken 671 times.
✓ Branch 1 taken 692812 times.
693483 if (color != lastColor) {
638
2/2
✓ Branch 0 taken 269 times.
✓ Branch 1 taken 402 times.
671 if (colorCount++)
639 269 *out++ = '|';
640 671 out[0] = SSE_BASE64[(color >> 12) & 0x3f];
641 671 out[1] = SSE_BASE64[(color >> 6) & 0x3f];
642 671 out[2] = SSE_BASE64[color & 0x3f];
643 671 out[3] = ':';
644 671 out += 4;
645 671 lastColor = color;
646 } else {
647 692812 *out++ = ';';
648 }
649 693483 memcpy(out, loc.s, loc.len);
650 693483 out += loc.len;
651 }
652 402 memcpy(out, "\r\n\r\n", 4);
653 402 out += 4;
654
1/2
✓ Branch 0 taken 402 times.
✗ Branch 1 not taken.
402 m_sseData.resize(out - m_sseData.data());
655
656
1/2
✓ Branch 0 taken 402 times.
✗ Branch 1 not taken.
402 LogExcess(VB_CHANNELOUT, "PixelsChanged: %d, Colors: %d, Data Size: %d\n",
657 (int)changed, colorCount, (int)m_sseData.size());
658 } else {
659 // Send empty update to keep connection alive and maintain frame timing
660
1/2
✓ Branch 0 taken 555 times.
✗ Branch 1 not taken.
555 m_sseData += "event: ping\r\ndata: \r\n\r\n";
661 }
662
663 957 m_sseId++;
664 }
665
666 /*
667 *
668 */
669 1387 int HTTPVirtualDisplayOutput::SendData(unsigned char* channelData) {
670 1387 bool dropped = false;
671
672
2/2
✓ Branch 0 taken 950 times.
✓ Branch 1 taken 437 times.
1387 if (m_sseData != "") {
673
1/2
✓ Branch 0 taken 950 times.
✗ Branch 1 not taken.
950 std::unique_lock<std::mutex> lock(m_connListLock);
674
1/2
✓ Branch 0 taken 950 times.
✗ Branch 1 not taken.
950 const uint64_t deadline = GetMonotonicTimeMS() + SSE_FRAME_BUDGET_MS;
675 // Iterate backwards so we can safely remove elements
676
2/2
✓ Branch 0 taken 1040 times.
✓ Branch 1 taken 950 times.
1990 for (int i = m_connList.size() - 1; i >= 0; i--) {
677
1/2
✓ Branch 0 taken 1040 times.
✗ Branch 1 not taken.
1040 int result = WriteSSEPacket(m_connList[i], m_sseData, deadline);
678
7/8
✓ Branch 0 taken 218 times.
✓ Branch 1 taken 822 times.
✓ Branch 2 taken 218 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✓ Branch 5 taken 217 times.
✓ Branch 6 taken 1 times.
✓ Branch 7 taken 1039 times.
1040 if (result == 0 && ++m_dropCounts[m_connList[i]] > SSE_MAX_DROPPED_FRAMES) {
679 // A client that has taken nothing for this long is gone or
680 // stuck; dropping its frames forever also cost every frame a
681 // resync of the pixels it never received.
682
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogDebug(VB_CHANNELOUT, "SSE client %d took no frames for %d frames, closing it\n", m_connList[i], SSE_MAX_DROPPED_FRAMES);
683 1 result = -1;
684
2/2
✓ Branch 0 taken 775 times.
✓ Branch 1 taken 264 times.
1039 } else if (result > 0) {
685
1/2
✓ Branch 0 taken 775 times.
✗ Branch 1 not taken.
775 m_dropCounts.erase(m_connList[i]);
686 }
687
2/2
✓ Branch 0 taken 48 times.
✓ Branch 1 taken 992 times.
1040 if (result < 0) {
688 // Connection is dead, remove it
689
1/2
✓ Branch 0 taken 48 times.
✗ Branch 1 not taken.
48 LogDebug(VB_CHANNELOUT, "Removing dead SSE connection %d\n", m_connList[i]);
690
1/2
✓ Branch 0 taken 48 times.
✗ Branch 1 not taken.
48 close(m_connList[i]);
691
1/2
✓ Branch 0 taken 48 times.
✗ Branch 1 not taken.
48 m_connList.erase(m_connList.begin() + i);
692 48 m_connListChanged = true;
693
2/2
✓ Branch 0 taken 217 times.
✓ Branch 1 taken 775 times.
992 } else if (result == 0) {
694 217 dropped = true;
695 }
696 }
697 // forget counts for connections the select thread has since closed
698
2/2
✓ Branch 0 taken 221 times.
✓ Branch 1 taken 950 times.
1171 for (auto it = m_dropCounts.begin(); it != m_dropCounts.end();) {
699
3/4
✓ Branch 0 taken 221 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✓ Branch 3 taken 217 times.
221 if (std::find(m_connList.begin(), m_connList.end(), it->first) == m_connList.end()) {
700
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 it = m_dropCounts.erase(it);
701 } else {
702 217 ++it;
703 }
704 }
705 950 }
706
707
2/2
✓ Branch 0 taken 203 times.
✓ Branch 1 taken 1184 times.
1387 if (dropped) {
708 // The payload held the only copy of this frame's pixel changes, so put
709 // the cache back the way it was and let the next frame re-send them.
710
2/2
✓ Branch 0 taken 30450 times.
✓ Branch 1 taken 203 times.
30653 for (auto it = m_cacheRollback.rbegin(); it != m_cacheRollback.rend(); ++it) {
711
2/4
✓ Branch 0 taken 30450 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 30450 times.
✗ Branch 3 not taken.
30450 m_virtualDisplay[it->first] = it->second;
712 }
713 203 m_cacheRollback.clear();
714 }
715
716 1387 return m_channelCount;
717 }
718