-
-
Notifications
You must be signed in to change notification settings - Fork 452
/
CEncoder.cpp
294 lines (242 loc) · 8.69 KB
/
CEncoder.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
#include "CEncoder.h"
#include <chrono>
#include <exception>
#include <memory>
#include <poll.h>
#include <sstream>
#include <stdexcept>
#include <stdlib.h>
#include <string>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <iostream>
#include "ALVR-common/packet_types.h"
#include "alvr_server/ClientConnection.h"
#include "alvr_server/Logger.h"
#include "alvr_server/PoseHistory.h"
#include "alvr_server/Settings.h"
#include "alvr_server/Statistics.h"
#include "protocol.h"
#include "ffmpeg_helper.h"
#include "EncodePipeline.h"
#include "FrameRender.h"
#include "amf_helper.h"
extern "C" {
#include <libavutil/avutil.h>
}
CEncoder::CEncoder(std::shared_ptr<ClientConnection> listener,
std::shared_ptr<PoseHistory> poseHistory)
: m_listener(listener), m_poseHistory(poseHistory) {}
CEncoder::~CEncoder() { Stop(); }
namespace {
void read_exactly(pollfd pollfds, char *out, size_t size, std::atomic_bool &exiting) {
while (not exiting and size != 0) {
int timeout = 1; // poll api doesn't fit perfectly(100 mircoseconds) poll uses milliseconds we do the best we can(1000 mircoseconds)
pollfds.events = POLLIN;
int count = poll(&pollfds, 1, timeout);
if (count < 0) {
throw MakeException("poll failed: %s", strerror(errno));
} else if (count == 1) {
int s = read(pollfds.fd, out, size);
if (s == -1) {
throw MakeException("read failed: %s", strerror(errno));
}
out += s;
size -= s;
}
}
}
void read_latest(pollfd pollfds, char *out, size_t size, std::atomic_bool &exiting) {
read_exactly(pollfds, out, size, exiting);
while (not exiting)
{
int timeout = 0; // poll api fixes the original perfectly(0 microseconds)
pollfds.events = POLLIN;
int count = poll(&pollfds, 1 , timeout);
if (count == 0)
return;
read_exactly(pollfds, out, size, exiting);
}
}
int accept_timeout(pollfd socket, std::atomic_bool &exiting) {
while (not exiting) {
int timeout = 15; // poll api also fits the original perfectly(15000 microseconds)
socket.events = POLLIN;
int count = poll(&socket, 1, timeout);
if (count < 0) {
throw MakeException("poll failed: %s", strerror(errno));
} else if (count == 1) {
return accept4(socket.fd, NULL, NULL, SOCK_CLOEXEC);
}
}
return -1;
}
void av_logfn(void*, int level, const char* data, va_list va)
{
if (level >
#ifdef DEBUG
AV_LOG_DEBUG)
#else
AV_LOG_VERBOSE)
#endif
return;
char buf[256];
vsnprintf(buf, sizeof(buf), data, va);
if (level <= AV_LOG_ERROR)
Error("Encoder: %s", buf);
else
Info("Encoder: %s", buf);
}
} // namespace
void CEncoder::GetFds(int client, int (*received_fds)[6]) {
struct msghdr msg;
struct cmsghdr *cmsg;
union {
struct cmsghdr cm;
u_int8_t pktinfo_sizer[sizeof(struct cmsghdr) + 1024];
} control_un;
struct iovec iov[1];
char data[1];
int ret;
msg.msg_control = &control_un;
msg.msg_controllen = sizeof(control_un);
msg.msg_flags = 0;
msg.msg_name = NULL;
msg.msg_namelen = 0;
iov[0].iov_base = data;
iov[0].iov_len = 1;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
ret = recvmsg(client, &msg, 0);
if (ret == -1) {
throw MakeException("recvmsg failed: %s", strerror(errno));
}
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
memcpy(received_fds, CMSG_DATA(cmsg), sizeof(*received_fds));
break;
}
}
if (cmsg == NULL) {
throw MakeException("cmsg is NULL");
}
}
void CEncoder::Run() {
Info("CEncoder::Run\n");
m_socketPath = getenv("XDG_RUNTIME_DIR");
m_socketPath += "/alvr-ipc";
int ret;
// we don't really care about what happends with unlink, it's just incase we crashed before this
// run
ret = unlink(m_socketPath.c_str());
m_socket.fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
struct sockaddr_un name;
if (m_socket.fd == -1) {
perror("socket");
exit(1);
}
memset(&name, 0, sizeof(name));
name.sun_family = AF_UNIX;
strncpy(name.sun_path, m_socketPath.c_str(), sizeof(name.sun_path) - 1);
ret = bind(m_socket.fd, (const struct sockaddr *)&name, sizeof(name));
if (ret == -1) {
perror("bind");
exit(1);
}
ret = listen(m_socket.fd, 1024);
if (ret == -1) {
perror("listen");
exit(1);
}
Info("CEncoder Listening\n");
struct pollfd client;
client.fd = accept_timeout(m_socket, m_exiting);
if (m_exiting)
return;
init_packet init;
client.events = POLLIN;
read_exactly(client, (char *)&init, sizeof(init), m_exiting);
if (m_exiting)
return;
// check that pointer types are null, other values would not make sense over a socket
assert(init.image_create_info.queueFamilyIndexCount == 0);
assert(init.image_create_info.pNext == NULL);
char ifbuf[256];
char ifbuf2[256];
sprintf(ifbuf, "/proc/%d/cmdline", (int)init.source_pid);
std::ifstream ifscmdl(ifbuf);
ifscmdl >> ifbuf2;
Info("CEncoder client connected, pid %d, cmdline %s\n", (int)init.source_pid, ifbuf2);
try {
GetFds(client.fd, &m_fds);
m_connected = true;
fprintf(stderr, "\n\nWe are initalizing Vulkan in CEncoder thread\n\n\n");
av_log_set_callback(av_logfn);
bool useAmf = alvr::AMFContext::get()->isValid();
std::vector<const char*> deviceExtensions;
if (useAmf) {
deviceExtensions = alvr::AMFContext::get()->requiredDeviceExtensions();
}
alvr::VkContext vk_ctx(init.device_name.data(), deviceExtensions);
FrameRender render(vk_ctx, init, m_fds);
auto output = render.CreateOutput();
alvr::VkFrameCtx vk_frame_ctx(vk_ctx, output.imageInfo);
alvr::VkFrame frame(vk_ctx, output.image, output.imageInfo, output.size, output.memory, output.drm);
auto encode_pipeline = alvr::EncodePipeline::Create(&render, vk_ctx, frame, vk_frame_ctx, render.GetEncodingWidth(), render.GetEncodingHeight());
fprintf(stderr, "CEncoder starting to read present packets");
present_packet frame_info;
std::vector<uint8_t> encoded_data;
while (not m_exiting) {
read_latest(client, (char *)&frame_info, sizeof(frame_info), m_exiting);
if (m_listener->GetStatistics()->CheckBitrateUpdated()) {
encode_pipeline->SetBitrate(m_listener->GetStatistics()->GetBitrate() * 1000000L); // in bits;
}
auto pose = m_poseHistory->GetBestPoseMatch((const vr::HmdMatrix34_t&)frame_info.pose);
if (!pose)
{
continue;
}
if (m_captureFrame) {
m_captureFrame = false;
render.Wait(frame_info.image, frame_info.semaphore_value);
render.CaptureInputFrame(Settings::Instance().m_captureFrameDir + "/alvr_frame_input.ppm");
render.CaptureOutputFrame(Settings::Instance().m_captureFrameDir + "/alvr_frame_output.ppm");
}
render.Render(frame_info.image, frame_info.semaphore_value);
encode_pipeline->PushFrame(pose->targetTimestampNs, m_scheduler.CheckIDRInsertion());
static_assert(sizeof(frame_info.pose) == sizeof(vr::HmdMatrix34_t&));
encoded_data.clear();
uint64_t pts;
if (!encode_pipeline->GetEncoded(encoded_data, &pts)) {
Error("Failed to get encoded data!");
continue;
}
auto timestamps = render.GetTimestamps();
uint64_t timestamp_present = timestamps.renderBegin;
uint64_t timestamp_composed = encode_pipeline->GetTimestamp() ? encode_pipeline->GetTimestamp() : timestamps.renderComplete;
ReportPresent(pose->targetTimestampNs, timestamps.now - timestamp_present);
ReportComposed(pose->targetTimestampNs, timestamps.now - timestamp_composed);
m_listener->SendVideo(encoded_data.data(), encoded_data.size(), pts);
m_listener->GetStatistics()->EncodeOutput();
}
}
catch (std::exception &e) {
std::stringstream err;
err << "error in encoder thread: " << e.what();
Error(err.str().c_str());
}
client.events = POLLHUP;
close(client.fd);
}
void CEncoder::Stop() {
m_exiting = true;
m_socket.events = POLLHUP;
close(m_socket.fd);
unlink(m_socketPath.c_str());
}
void CEncoder::OnPacketLoss() { m_scheduler.OnPacketLoss(); }
void CEncoder::InsertIDR() { m_scheduler.InsertIDR(); }
void CEncoder::CaptureFrame() { m_captureFrame = true; }