/
display.cpp
506 lines (413 loc) · 15.1 KB
/
display.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys.
// The pbrt source code is licensed under the Apache License, Version 2.0.
// SPDX: Apache-2.0
#include <pbrt/util/display.h>
#include <pbrt/util/error.h>
#include <pbrt/util/hash.h>
#include <pbrt/util/image.h>
#include <pbrt/util/print.h>
#include <pbrt/util/string.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <mutex>
#include <thread>
#ifdef PBRT_IS_WINDOWS
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Ws2tcpip.h>
#include <winsock2.h>
#undef NOMINMAX
using socket_t = SOCKET;
#else
using socket_t = int;
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#define SOCKET_ERROR (-1)
#define INVALID_SOCKET (-1)
#endif
namespace pbrt {
enum SocketError : int {
#ifdef PBRT_IS_WINDOWS
Again = EAGAIN,
ConnRefused = WSAECONNREFUSED,
WouldBlock = WSAEWOULDBLOCK,
#else
Again = EAGAIN,
ConnRefused = ECONNREFUSED,
WouldBlock = EWOULDBLOCK,
#endif
};
static int closeSocket(socket_t socket) {
#ifdef PBRT_IS_WINDOWS
return closesocket(socket);
#else
return close(socket);
#endif
}
static std::atomic<int> numActiveChannels{0};
class IPCChannel {
public:
IPCChannel(const std::string &host);
~IPCChannel();
IPCChannel(const IPCChannel &) = delete;
IPCChannel &operator=(const IPCChannel &) = delete;
bool Send(pstd::span<const uint8_t> message);
bool Connected() const { return socketFd != INVALID_SOCKET; }
private:
void Connect();
void Disconnect();
int numFailures = 0;
std::string address, port;
socket_t socketFd = INVALID_SOCKET;
};
IPCChannel::IPCChannel(const std::string &hostname) {
if (numActiveChannels++ == 0) {
#ifdef PBRT_IS_WINDOWS
WSADATA wsaData;
int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (err != NO_ERROR)
LOG_FATAL("Unable to initialize WinSock: %s", ErrorString(err));
#else
// We don't care about getting a SIGPIPE if the display server goes
// away...
signal(SIGPIPE, SIG_IGN);
#endif
}
size_t split = hostname.find_last_of(':');
if (split == std::string::npos)
ErrorExit("Expected \"host:port\" for display server address. Given \"%s\".",
hostname);
address = std::string(hostname.begin(), hostname.begin() + split);
port = std::string(hostname.begin() + split + 1, hostname.end());
Connect();
}
void IPCChannel::Connect() {
CHECK_EQ(socketFd, INVALID_SOCKET);
LOG_VERBOSE("Trying to connect to display server");
struct addrinfo hints = {}, *addrinfo;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(address.c_str(), port.c_str(), &hints, &addrinfo);
if (err)
ErrorExit("%s", gai_strerror(err));
socketFd = INVALID_SOCKET;
for (struct addrinfo *ptr = addrinfo; ptr; ptr = ptr->ai_next) {
socketFd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (socketFd == INVALID_SOCKET) {
LOG_VERBOSE("socket() failed: %s", ErrorString());
continue;
}
#ifdef PBRT_IS_LINUX
struct timeval timeout;
timeout.tv_sec = 3;
timeout.tv_usec = 0;
if (setsockopt(socketFd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) ==
SOCKET_ERROR) {
LOG_VERBOSE("setsockopt() failed: %s", ErrorString());
}
#endif // PBRT_IS_LINUX
if (connect(socketFd, ptr->ai_addr, ptr->ai_addrlen) == SOCKET_ERROR) {
#ifdef PBRT_IS_WINDOWS
int err = WSAGetLastError();
#else
int err = errno;
#endif
if (err == SocketError::ConnRefused)
LOG_VERBOSE("Connection refused. Will try again...");
else
LOG_VERBOSE("connect() failed: %s", ErrorString(err));
closeSocket(socketFd);
socketFd = INVALID_SOCKET;
continue;
}
break; // success
}
freeaddrinfo(addrinfo);
if (socketFd != INVALID_SOCKET)
LOG_VERBOSE("Connected to display server");
}
IPCChannel::~IPCChannel() {
if (Connected())
Disconnect();
if (--numActiveChannels == 0) {
#ifdef PBRT_IS_WINDOWS
WSACleanup();
#endif
}
}
void IPCChannel::Disconnect() {
CHECK(Connected());
closeSocket(socketFd);
socketFd = INVALID_SOCKET;
}
bool IPCChannel::Send(pstd::span<const uint8_t> message) {
if (!Connected()) {
Connect();
if (!Connected())
return false;
}
// Start with the length of the message.
// FIXME: annoying coupling w/sending code's message buffer layout...
int *startPtr = (int *)message.data();
*startPtr = message.size();
int bytesSent =
send(socketFd, (const char *)message.data(), message.size(), 0 /* flags */);
if (bytesSent == message.size())
return true;
LOG_ERROR("send to display server failed: %s", ErrorString());
Disconnect();
return false;
}
namespace {
enum DisplayDirective : uint8_t {
OpenImage = 0,
ReloadImage = 1,
CloseImage = 2,
UpdateImage = 3,
CreateImage = 4,
};
void Serialize(uint8_t **ptr, const std::string &s) {
for (size_t i = 0; i < s.size(); ++i, *ptr += 1)
**ptr = s[i];
**ptr = '\0';
*ptr += 1;
}
template <typename T>
void Serialize(uint8_t **ptr, T value) {
memcpy(*ptr, &value, sizeof(T));
*ptr += sizeof(T);
}
constexpr int tileSize = 128;
} // namespace
class DisplayItem {
public:
DisplayItem(
const std::string &title, Point2i resolution,
std::vector<std::string> channelNames,
std::function<void(Bounds2i b, pstd::span<pstd::span<float>>)> getTileValues);
bool Display(IPCChannel &channel);
private:
bool SendOpenImage(IPCChannel &channel);
bool openedImage = false;
std::string title;
Point2i resolution;
std::function<void(Bounds2i b, pstd::span<pstd::span<float>>)> getTileValues;
std::vector<std::string> channelNames;
struct ImageChannelBuffer {
ImageChannelBuffer(const std::string &channelName, int nTiles,
const std::string &title);
void SetTileBounds(int x, int y, int width, int height);
bool SendIfChanged(IPCChannel &channel, int tileIndex);
std::vector<uint8_t> buffer;
int tileBoundsOffset = 0, channelValuesOffset = 0;
std::vector<uint64_t> tileHashes;
int setCount, tileIndex;
};
std::vector<ImageChannelBuffer> channelBuffers;
};
DisplayItem::DisplayItem(
const std::string &baseTitle, Point2i resolution,
std::vector<std::string> channelNames,
std::function<void(Bounds2i b, pstd::span<pstd::span<float>>)> getTileValues)
: resolution(resolution), getTileValues(getTileValues), channelNames(channelNames) {
#ifdef PBRT_IS_WINDOWS
title = StringPrintf("%s (%d)", baseTitle, GetCurrentThreadId());
#else
title = StringPrintf("%s (%d)", baseTitle, getpid());
#endif
int nTiles = ((resolution.x + tileSize - 1) / tileSize) *
((resolution.y + tileSize - 1) / tileSize);
for (const std::string &channelName : channelNames)
channelBuffers.push_back(ImageChannelBuffer(channelName, nTiles, title));
}
DisplayItem::ImageChannelBuffer::ImageChannelBuffer(const std::string &channelName,
int nTiles,
const std::string &title) {
int bufferAlloc = tileSize * tileSize * sizeof(float) + title.size() + 32;
buffer.resize(bufferAlloc);
uint8_t *ptr = buffer.data();
Serialize(&ptr, int(0)); // reserve space for message length
Serialize(&ptr, DisplayDirective::UpdateImage);
uint8_t grabFocus = 0;
Serialize(&ptr, grabFocus);
Serialize(&ptr, title);
Serialize(&ptr, channelName);
tileBoundsOffset = ptr - buffer.data();
// Note: may not be float-aligned, but that's not a problem on x86...
// TODO: fix this. The problem is that it breaks the whole idea of
// passing a span<float> to the callback function...
channelValuesOffset = tileBoundsOffset + 4 * sizeof(int);
// Zero-initialize the buffer color contents before computing the hash
// for a fully-zero tile (which corresponds to the initial state on the
// viewer side.)
memset(buffer.data() + channelValuesOffset, 0, tileSize * tileSize * sizeof(float));
uint64_t zeroHash = HashBuffer(buffer.data() + channelValuesOffset,
tileSize * tileSize * sizeof(float));
tileHashes.assign(nTiles, zeroHash);
}
void DisplayItem::ImageChannelBuffer::SetTileBounds(int x, int y, int width, int height) {
uint8_t *ptr = buffer.data() + tileBoundsOffset;
Serialize(&ptr, x);
Serialize(&ptr, y);
Serialize(&ptr, width);
Serialize(&ptr, height);
setCount = width * height;
}
bool DisplayItem::ImageChannelBuffer::SendIfChanged(IPCChannel &ipcChannel,
int tileIndex) {
int excess = setCount - tileSize * tileSize;
if (excess > 0)
memset(buffer.data() + channelValuesOffset + setCount * sizeof(float), 0,
excess * sizeof(float));
uint64_t hash = HashBuffer(buffer.data() + channelValuesOffset,
tileSize * tileSize * sizeof(float));
if (hash == tileHashes[tileIndex])
return true;
if (!ipcChannel.Send(pstd::MakeSpan(buffer.data(),
channelValuesOffset + setCount * sizeof(float))))
return false;
tileHashes[tileIndex] = hash;
return true;
}
bool DisplayItem::Display(IPCChannel &ipcChannel) {
if (!openedImage) {
if (!SendOpenImage(ipcChannel))
// maybe next time
return false;
openedImage = true;
}
std::vector<pstd::span<float>> displayValues(channelBuffers.size());
for (int c = 0; c < channelBuffers.size(); ++c) {
float *ptr = (float *)(channelBuffers[c].buffer.data() +
channelBuffers[c].channelValuesOffset);
displayValues[c] = pstd::MakeSpan(ptr, tileSize * tileSize);
}
int tileIndex = 0;
for (int y = 0; y < resolution.y; y += tileSize)
for (int x = 0; x < resolution.x; x += tileSize, ++tileIndex) {
int height = std::min(y + tileSize, resolution.y) - y;
int width = std::min(x + tileSize, resolution.x) - x;
for (int c = 0; c < channelBuffers.size(); ++c)
channelBuffers[c].SetTileBounds(x, y, width, height);
Bounds2i b(Point2i(x, y), Point2i(x + width, y + height));
getTileValues(b, pstd::MakeSpan(displayValues));
// Send the RGB buffers only if they're different than
// the last version sent.
for (int c = 0; c < channelBuffers.size(); ++c)
if (!channelBuffers[c].SendIfChanged(ipcChannel, tileIndex)) {
// Welp. Stop for now...
openedImage = false;
return false;
}
}
return true;
}
bool DisplayItem::SendOpenImage(IPCChannel &ipcChannel) {
// Initial "open the image" message
uint8_t buffer[1024];
uint8_t *ptr = buffer;
Serialize(&ptr, int(0)); // reserve space for message length
Serialize(&ptr, DisplayDirective::CreateImage);
uint8_t grabFocus = 1;
Serialize(&ptr, grabFocus);
Serialize(&ptr, title);
int nChannels = channelNames.size();
Serialize(&ptr, resolution.x);
Serialize(&ptr, resolution.y);
Serialize(&ptr, nChannels);
for (int c = 0; c < nChannels; ++c)
Serialize(&ptr, channelNames[c]);
return ipcChannel.Send(pstd::MakeSpan(buffer, ptr - buffer));
}
static std::atomic<bool> exitThread{false};
static std::mutex mutex;
static std::thread updateThread;
static std::vector<DisplayItem> dynamicItems;
static IPCChannel *channel;
static void updateDynamicItems() {
while (!exitThread) {
std::this_thread::sleep_for(std::chrono::milliseconds(250));
std::lock_guard<std::mutex> lock(mutex);
for (auto &item : dynamicItems)
item.Display(*channel);
}
// One last time to get the last bits
std::lock_guard<std::mutex> lock(mutex);
for (auto &item : dynamicItems)
item.Display(*channel);
dynamicItems.clear();
delete channel;
channel = nullptr;
}
void ConnectToDisplayServer(const std::string &host) {
CHECK(channel == nullptr);
channel = new IPCChannel(host);
updateThread = std::thread(updateDynamicItems);
}
void DisconnectFromDisplayServer() {
if (updateThread.get_id() != std::thread::id()) {
exitThread = true;
updateThread.join();
updateThread = std::thread();
exitThread = false;
}
}
static DisplayItem GetImageDisplayItem(const std::string &title, const Image &image,
pstd::optional<ImageChannelDesc> channelDesc) {
auto getValues = [=](Bounds2i b, pstd::span<pstd::span<float>> displayValues) {
int offset = 0;
for (Point2i p : b) {
ImageChannelValues v =
channelDesc ? image.GetChannels(p, *channelDesc) : image.GetChannels(p);
for (int i = 0; i < v.size(); ++i)
displayValues[i][offset] = v[i];
++offset;
}
};
std::vector<std::string> channelNames;
if (channelDesc)
channelNames = image.ChannelNames(*channelDesc);
else {
if (image.NChannels() == 3)
channelNames = {"R", "G", "B"};
else
for (int i = 0; i < image.NChannels(); ++i)
channelNames.push_back(StringPrintf("channel %d", i));
}
return DisplayItem(title, image.Resolution(), channelNames, getValues);
}
void DisplayStatic(std::string title, const Image &image,
pstd::optional<ImageChannelDesc> channelDesc) {
DisplayItem item = GetImageDisplayItem(title, image, channelDesc);
std::lock_guard<std::mutex> lock(mutex);
if (!item.Display(*channel))
LOG_ERROR("Unable to display static content \"%s\".", title);
}
void DisplayDynamic(std::string title, const Image &image,
pstd::optional<ImageChannelDesc> channelDesc) {
std::lock_guard<std::mutex> lock(mutex);
dynamicItems.push_back(GetImageDisplayItem(title, image, channelDesc));
}
void DisplayStatic(
std::string title, Point2i resolution, std::vector<std::string> channelNames,
std::function<void(Bounds2i b, pstd::span<pstd::span<float>>)> getTileValues) {
DisplayItem item(title, resolution, channelNames, getTileValues);
std::lock_guard<std::mutex> lock(mutex);
if (!item.Display(*channel))
LOG_ERROR("Unable to display static content \"%s\".", title);
}
void DisplayDynamic(
std::string title, Point2i resolution, std::vector<std::string> channelNames,
std::function<void(Bounds2i b, pstd::span<pstd::span<float>>)> getTileValues) {
std::lock_guard<std::mutex> lock(mutex);
dynamicItems.push_back(DisplayItem(title, resolution, channelNames, getTileValues));
}
} // namespace pbrt