Simplify setting the non-blocking flag when creating HTTP sockets.
[cubemap] / httpinput.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <math.h>
4 #include <netdb.h>
5 #include <netinet/in.h>
6 #include <poll.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/ioctl.h>
11 #include <sys/socket.h>
12 #include <sys/time.h>
13 #include <time.h>
14 #include <unistd.h>
15 #include <math.h>
16 #include <map>
17 #include <string>
18 #include <utility>
19 #include <vector>
20
21 #include "httpinput.h"
22 #include "log.h"
23 #include "metacube2.h"
24 #include "parse.h"
25 #include "serverpool.h"
26 #include "state.pb.h"
27 #include "stream.h"
28 #include "timespec.h"
29 #include "util.h"
30 #include "version.h"
31
32 using namespace std;
33
34 namespace {
35
36 string host_header(const string &host, const string &port)
37 {
38         if (port == "http" || atoi(port.c_str()) == 80) {
39                 return host;
40         } else {
41                 return host + ":" + port;
42         }
43 }
44
45 }  // namespace
46
47 extern ServerPool *servers;
48
49 HTTPInput::HTTPInput(const string &url, Input::Encoding encoding)
50         : state(NOT_CONNECTED),
51           url(url),
52           encoding(encoding)
53 {
54         stats.url = url;
55         stats.bytes_received = 0;
56         stats.data_bytes_received = 0;
57         stats.metadata_bytes_received = 0;
58         stats.connect_time = -1;
59         stats.latency_sec = HUGE_VAL;
60 }
61
62 HTTPInput::HTTPInput(const InputProto &serialized)
63         : state(State(serialized.state())),
64           url(serialized.url()),
65           encoding(serialized.is_metacube_encoded() ?
66                    Input::INPUT_ENCODING_METACUBE :
67                    Input::INPUT_ENCODING_RAW),
68           request(serialized.request()),
69           request_bytes_sent(serialized.request_bytes_sent()),
70           response(serialized.response()),
71           http_header(serialized.http_header()),
72           stream_header(serialized.stream_header()),
73           has_metacube_header(serialized.has_metacube_header()),
74           sock(serialized.sock())
75 {
76         pending_data.resize(serialized.pending_data().size());
77         memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
78
79         string protocol, user;
80         parse_url(url, &protocol, &user, &host, &port, &path);  // Don't care if it fails.
81
82         stats.url = url;
83         stats.bytes_received = serialized.bytes_received();
84         stats.data_bytes_received = serialized.data_bytes_received();
85         stats.metadata_bytes_received = serialized.metadata_bytes_received();
86         if (serialized.has_connect_time()) {
87                 stats.connect_time = serialized.connect_time();
88         } else {
89                 stats.connect_time = time(nullptr);
90         }
91         if (serialized.has_latency_sec()) {
92                 stats.latency_sec = serialized.latency_sec();
93         } else {
94                 stats.latency_sec = HUGE_VAL;
95         }
96
97         last_verbose_connection.tv_sec = -3600;
98         last_verbose_connection.tv_nsec = 0;
99 }
100
101 void HTTPInput::close_socket()
102 {
103         if (sock != -1) {
104                 safe_close(sock);
105                 sock = -1;
106         }
107
108         lock_guard<mutex> lock(stats_mutex);
109         stats.connect_time = -1;
110 }
111
112 InputProto HTTPInput::serialize() const
113 {
114         InputProto serialized;
115         serialized.set_state(state);
116         serialized.set_url(url);
117         serialized.set_request(request);
118         serialized.set_request_bytes_sent(request_bytes_sent);
119         serialized.set_response(response);
120         serialized.set_http_header(http_header);
121         serialized.set_stream_header(stream_header);
122         serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
123         serialized.set_has_metacube_header(has_metacube_header);
124         serialized.set_sock(sock);
125         serialized.set_bytes_received(stats.bytes_received);
126         serialized.set_data_bytes_received(stats.data_bytes_received);
127         if (isfinite(stats.latency_sec)) {
128                 serialized.set_latency_sec(stats.latency_sec);
129         }
130         serialized.set_connect_time(stats.connect_time);
131         if (encoding == Input::INPUT_ENCODING_METACUBE) {
132                 serialized.set_is_metacube_encoded(true);
133         } else {
134                 assert(encoding == Input::INPUT_ENCODING_RAW);
135                 serialized.set_is_metacube_encoded(false);
136         }
137         return serialized;
138 }
139
140 int HTTPInput::lookup_and_connect(const string &host, const string &port)
141 {
142         addrinfo *ai;
143         int err = getaddrinfo(host.c_str(), port.c_str(), nullptr, &ai);
144         if (err != 0) {
145                 if (!suppress_logging) {
146                         log(WARNING, "[%s] Lookup of '%s' failed (%s).",
147                                 url.c_str(), host.c_str(), gai_strerror(err));
148                 }
149                 return -1;
150         }
151
152         addrinfo *base_ai = ai;
153
154         // Connect to everything in turn until we have a socket.
155         for ( ; ai && !should_stop(); ai = ai->ai_next) {
156                 // Now do a non-blocking connect. This is important because we want to be able to be
157                 // woken up, even though it's rather cumbersome.
158                 int sock = socket(ai->ai_family, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
159                 if (sock == -1) {
160                         // Could be e.g. EPROTONOSUPPORT. The show must go on.
161                         continue;
162                 }
163
164                 // Do a non-blocking connect.
165                 do {
166                         err = connect(sock, ai->ai_addr, ai->ai_addrlen);
167                 } while (err == -1 && errno == EINTR);
168
169                 if (err == -1 && errno != EINPROGRESS) {
170                         log_perror("connect");
171                         safe_close(sock);
172                         continue;
173                 }
174
175                 // Wait for the connect to complete, or an error to happen.
176                 for ( ;; ) {
177                         bool complete = wait_for_activity(sock, POLLIN | POLLOUT, nullptr);
178                         if (should_stop()) {
179                                 safe_close(sock);
180                                 return -1;
181                         }
182                         if (complete) {
183                                 break;
184                         }
185                 }
186
187                 // Check whether it ended in an error or not.
188                 socklen_t err_size = sizeof(err);
189                 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
190                         log_perror("getsockopt");
191                         safe_close(sock);
192                         continue;
193                 }
194
195                 errno = err;
196
197                 if (err == 0) {
198                         // Successful connect.
199                         freeaddrinfo(base_ai);
200                         return sock;
201                 }
202
203                 safe_close(sock);
204         }
205
206         // Give the last one as error.
207         if (!suppress_logging) {
208                 log(WARNING, "[%s] Connect to '%s' failed (%s)",
209                         url.c_str(), host.c_str(), strerror(errno));
210         }
211         freeaddrinfo(base_ai);
212         return -1;
213 }
214         
215 bool HTTPInput::parse_response(const string &request)
216 {
217         vector<string> lines = split_lines(response);
218         if (lines.empty()) {
219                 if (!suppress_logging) {
220                         log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
221                 }
222                 return false;
223         }
224
225         vector<string> first_line_tokens = split_tokens(lines[0]);
226         if (first_line_tokens.size() < 2) {
227                 if (!suppress_logging) {
228                         log(WARNING, "[%s] Malformed response line '%s' from input.",
229                                 url.c_str(), lines[0].c_str());
230                 }
231                 return false;
232         }
233
234         int response = atoi(first_line_tokens[1].c_str());
235         if (response != 200) {
236                 if (!suppress_logging) {
237                         log(WARNING, "[%s] Non-200 response '%s' from input.",
238                                 url.c_str(), lines[0].c_str());
239                 }
240                 return false;
241         }
242
243         HTTPHeaderMultimap parameters = extract_headers(lines, url);
244
245         // Remove “Content-encoding: metacube”.
246         const auto encoding_it = parameters.find("Content-Encoding");
247         if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
248                 parameters.erase(encoding_it);
249         }
250
251         // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
252         // XXX: Use a Via: instead?
253         if (parameters.count("Server") == 0) {
254                 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
255         } else {
256                 for (auto &key_and_value : parameters) {
257                         if (key_and_value.first != "Server") {
258                                 continue;
259                         }
260                         key_and_value.second = SERVER_IDENTIFICATION " (reflecting: " + key_and_value.second + ")";
261                 }
262         }
263
264         // Erase “Connection: close”; we'll set it on the sending side if needed.
265         parameters.erase("Connection");
266
267         // Construct the new HTTP header.
268         http_header = "HTTP/1.0 200 OK\r\n";
269         for (const auto &key_and_value : parameters) {
270                 http_header.append(key_and_value.first + ": " + key_and_value.second + "\r\n");
271         }
272
273         for (int stream_index : stream_indices) {
274                 servers->set_header(stream_index, http_header, stream_header);
275         }
276
277         return true;
278 }
279
280 void HTTPInput::do_work()
281 {
282         timespec last_activity;
283
284         // TODO: Make the timeout persist across restarts.
285         if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
286                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
287                 assert(err != -1);
288         }
289
290         while (!should_stop()) {
291                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
292                         // Give the socket 30 seconds since last activity before we time out.
293                         static const int timeout_secs = 30;
294
295                         timespec now;
296                         int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
297                         assert(err != -1);
298
299                         timespec elapsed = clock_diff(last_activity, now);
300                         if (elapsed.tv_sec >= timeout_secs) {
301                                 // Timeout!
302                                 if (!suppress_logging) {
303                                         log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
304                                 }
305                                 state = CLOSING_SOCKET;
306                                 continue;
307                         }
308
309                         // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
310                         // Add a second of slack to account for differences between clocks.
311                         timespec timeout = clock_diff(now, last_activity);
312                         timeout.tv_sec += timeout_secs + 1;
313                         assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
314
315                         bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
316                         if (activity) {
317                                 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
318                                 assert(err != -1);
319                         } else {
320                                 // OK. Most likely, should_stop was set, or we have timed out.
321                                 continue;
322                         }
323                 }
324
325                 switch (state) {
326                 case NOT_CONNECTED:
327                         request.clear();
328                         request_bytes_sent = 0;
329                         response.clear();
330                         pending_data.clear();
331                         has_metacube_header = false;
332                         for (int stream_index : stream_indices) {
333                                 // Don't zero out the header; it might still be of use to HLS clients.
334                                 servers->set_unavailable(stream_index);
335                         }
336
337                         {
338                                 string protocol, user;  // Thrown away.
339                                 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
340                                         if (!suppress_logging) {
341                                                 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
342                                         }
343                                         break;
344                                 }
345
346                                 // Remove the brackets around IPv6 address literals.
347                                 // TODO: See if we can join this with the code in parse_ip_address(),
348                                 // or maybe even more it into parse_url().
349                                 if (!host.empty() && host[0] == '[' && host[host.size() - 1] == ']') {
350                                         host = host.substr(1, host.size() - 2);
351                                 }
352                         }
353
354                         if (suppress_logging) {
355                                 // See if there's more than one minute since last time we made a connection
356                                 // with logging enabled. If so, turn it on again.
357                                 timespec now;
358                                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
359                                 assert(err != -1);
360
361                                 double elapsed = now.tv_sec - last_verbose_connection.tv_sec +
362                                         1e-9 * (now.tv_nsec - last_verbose_connection.tv_nsec);
363                                 if (elapsed > 60.0) {
364                                         suppress_logging = false;
365                                 }
366                         }
367                         if (!suppress_logging) {
368                                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_verbose_connection);
369                                 assert(err != -1);
370                         }
371                         ++num_connection_attempts;
372                         sock = lookup_and_connect(host, port);
373                         if (sock != -1) {
374                                 // Yay, successful connect.
375                                 state = SENDING_REQUEST;
376                                 request = "GET " + path + " HTTP/1.0\r\nHost: " + host_header(host, port) + "\r\nUser-Agent: cubemap\r\n\r\n";
377                                 request_bytes_sent = 0;
378
379                                 lock_guard<mutex> lock(stats_mutex);
380                                 stats.connect_time = time(nullptr);
381                                 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
382                         }
383                         break;
384                 case SENDING_REQUEST: {
385                         size_t to_send = request.size() - request_bytes_sent;
386                         int ret;
387
388                         do {
389                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
390                         } while (ret == -1 && errno == EINTR);
391
392                         if (ret == -1) {
393                                 log_perror("write");
394                                 state = CLOSING_SOCKET;
395                                 continue;
396                         }
397
398                         assert(ret >= 0);
399                         request_bytes_sent += ret;
400
401                         if (request_bytes_sent == request.size()) {
402                                 state = RECEIVING_HEADER;
403                         }
404                         break;
405                 }
406                 case RECEIVING_HEADER: {
407                         char buf[4096];
408                         int ret;
409
410                         do {
411                                 ret = read(sock, buf, sizeof(buf));
412                         } while (ret == -1 && errno == EINTR);
413
414                         if (ret == -1) {
415                                 log_perror("read");
416                                 state = CLOSING_SOCKET;
417                                 continue;
418                         }
419
420                         if (ret == 0) {
421                                 // This really shouldn't happen...
422                                 if (!suppress_logging) {
423                                         log(ERROR, "[%s] Socket unexpectedly closed while reading header",
424                                                    url.c_str());
425                                 }
426                                 state = CLOSING_SOCKET;
427                                 continue;
428                         }
429                         
430                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
431                         
432                         if (status == RP_OUT_OF_SPACE) {
433                                 if (!suppress_logging) {
434                                         log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
435                                 }
436                                 state = CLOSING_SOCKET;
437                                 continue;
438                         } else if (status == RP_NOT_FINISHED_YET) {
439                                 continue;
440                         }
441         
442                         // OK, so we're fine, but there might be some of the actual data after the response.
443                         // We'll need to deal with that separately.
444                         string extra_data;
445                         if (status == RP_EXTRA_DATA) {
446                                 char *ptr = static_cast<char *>(
447                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
448                                 assert(ptr != nullptr);
449                                 extra_data = string(ptr + 4, &response[0] + response.size());
450                                 response.resize(ptr - response.data());
451                         }
452
453                         if (!parse_response(response)) {
454                                 state = CLOSING_SOCKET;
455                                 continue;
456                         }
457
458                         if (!extra_data.empty()) {
459                                 process_data(&extra_data[0], extra_data.size());
460                         }
461
462                         if (!suppress_logging) {
463                                 if (encoding == Input::INPUT_ENCODING_RAW) {
464                                         log(INFO, "[%s] Connected to '%s', receiving raw data.",
465                                                    url.c_str(), url.c_str());
466                                 } else {
467                                         assert(encoding == Input::INPUT_ENCODING_METACUBE);
468                                         log(INFO, "[%s] Connected to '%s', receiving data.",
469                                                    url.c_str(), url.c_str());
470                                 }
471                         }
472                         state = RECEIVING_DATA;
473                         break;
474                 }
475                 case RECEIVING_DATA: {
476                         char buf[4096];
477                         int ret;
478
479                         do {
480                                 ret = read(sock, buf, sizeof(buf));
481                         } while (ret == -1 && errno == EINTR);
482
483                         if (ret == -1) {
484                                 log_perror("read");
485                                 state = CLOSING_SOCKET;
486                                 continue;
487                         }
488
489                         if (ret == 0) {
490                                 // This really shouldn't happen...
491                                 if (!suppress_logging) {
492                                         log(ERROR, "[%s] Socket unexpectedly closed while reading data",
493                                                    url.c_str());
494                                 }
495                                 state = CLOSING_SOCKET;
496                                 continue;
497                         }
498
499                         num_connection_attempts = 0;  // Reset, since we have a successful read.
500                         if (suppress_logging) {
501                                 // This was suppressed earlier, so print it out now.
502                                 if (encoding == Input::INPUT_ENCODING_RAW) {
503                                         log(INFO, "[%s] Connected to '%s', receiving raw data.",
504                                                    url.c_str(), url.c_str());
505                                 } else {
506                                         assert(encoding == Input::INPUT_ENCODING_METACUBE);
507                                         log(INFO, "[%s] Connected to '%s', receiving data.",
508                                                    url.c_str(), url.c_str());
509                                 }
510                                 suppress_logging = false;
511                         }
512
513                         process_data(buf, ret);
514                         break;
515                 }
516                 case CLOSING_SOCKET: {
517                         close_socket();
518                         state = NOT_CONNECTED;
519                         break;
520                 }
521                 default:
522                         assert(false);
523                 }
524
525                 // If we are still in NOT_CONNECTED, either something went wrong,
526                 // or the connection just got closed.
527                 // The earlier steps have already given the error message, if any.
528                 if (state == NOT_CONNECTED && !should_stop()) {
529                         if (!suppress_logging) {
530                                 log(INFO, "[%s] Waiting 0.2 seconds and restarting...", url.c_str());
531                         }
532
533                         if (num_connection_attempts >= 3 && !suppress_logging) {
534                                 log(INFO, "[%s] %d failed connection attempts, suppressing logging for one minute.",
535                                         url.c_str(), num_connection_attempts);
536                                 suppress_logging = true;
537                         }
538                         timespec timeout_ts;
539                         timeout_ts.tv_sec = 0;
540                         timeout_ts.tv_nsec = 200000000;
541                         wait_for_wakeup(&timeout_ts);
542                 }
543         }
544 }
545
546 void HTTPInput::process_data(char *ptr, size_t bytes)
547 {
548         {
549                 lock_guard<mutex> lock(stats_mutex);
550                 stats.bytes_received += bytes;
551         }
552
553         if (encoding == Input::INPUT_ENCODING_RAW) {
554                 for (int stream_index : stream_indices) {
555                         servers->add_data(stream_index, ptr, bytes, /*metacube_flags=*/0, /*pts=*/RationalPTS());
556                 }
557                 return;
558         }
559
560         assert(encoding == Input::INPUT_ENCODING_METACUBE);
561         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
562
563         for ( ;; ) {
564                 // If we don't have enough data (yet) for even the Metacube header, just return.
565                 if (pending_data.size() < sizeof(metacube2_block_header)) {
566                         return;
567                 }
568
569                 // Make sure we have the Metacube sync header at the start.
570                 // We may need to skip over junk data (it _should_ not happen, though).
571                 if (!has_metacube_header) {
572                         char *ptr = static_cast<char *>(
573                                 memmem(pending_data.data(), pending_data.size(),
574                                        METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
575                         if (ptr == nullptr) {
576                                 // OK, so we didn't find the sync marker. We know then that
577                                 // we do not have the _full_ marker in the buffer, but we
578                                 // could have N-1 bytes. Drop everything before that,
579                                 // and then give up.
580                                 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
581                                 return;
582                         } else {
583                                 // Yay, we found the header. Drop everything (if anything) before it.
584                                 drop_pending_data(ptr - pending_data.data());
585                                 has_metacube_header = true;
586
587                                 // Re-check that we have the entire header; we could have dropped data.
588                                 if (pending_data.size() < sizeof(metacube2_block_header)) {
589                                         return;
590                                 }
591                         }
592                 }
593
594                 // Now it's safe to read the header.
595                 metacube2_block_header hdr;
596                 memcpy(&hdr, pending_data.data(), sizeof(hdr));
597                 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
598                 uint32_t size = ntohl(hdr.size);
599                 uint16_t flags = ntohs(hdr.flags);
600                 uint16_t expected_csum = metacube2_compute_crc(&hdr);
601
602                 if (expected_csum != ntohs(hdr.csum)) {
603                         log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
604                                 "not reading block claiming to be %d bytes (flags=%x).",
605                                 url.c_str(), expected_csum, ntohs(hdr.csum),
606                                 size, flags);
607
608                         // Drop only the first byte, and let the rest of the code handle resync.
609                         pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
610                         has_metacube_header = false;
611                         continue;
612                 }
613                 if (size > 10485760) {
614                         log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
615                                 url.c_str(), size, flags);
616                 }
617
618                 // See if we have the entire block. If not, wait for more data.
619                 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
620                         return;
621                 }
622
623                 // See if this is a metadata block. If so, we don't want to send it on,
624                 // but rather process it ourselves.
625                 // TODO: Keep metadata when sending on to other Metacube users.
626                 if (flags & METACUBE_FLAGS_METADATA) {
627                         {
628                                 lock_guard<mutex> lock(stats_mutex);
629                                 stats.metadata_bytes_received += size;
630                         }
631                         process_metacube_metadata_block(hdr, pending_data.data() + sizeof(hdr), size);
632                 } else {
633                         // Send this block on to the servers.
634                         {
635                                 lock_guard<mutex> lock(stats_mutex);
636                                 stats.data_bytes_received += size;
637                         }
638                         char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
639                         if (flags & METACUBE_FLAGS_HEADER) {
640                                 stream_header = string(inner_data, inner_data + size);
641                                 for (int stream_index : stream_indices) {
642                                         servers->set_header(stream_index, http_header, stream_header);
643                                 }
644                         }
645                         for (int stream_index : stream_indices) {
646                                 servers->add_data(stream_index, inner_data, size, flags, next_block_pts);
647                         }
648                         next_block_pts = RationalPTS();
649                 }
650
651                 // Consume the block. This isn't the most efficient way of dealing with things
652                 // should we have many blocks, but these routines don't need to be too efficient
653                 // anyway.
654                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
655                 has_metacube_header = false;
656         }
657 }
658
659 void HTTPInput::drop_pending_data(size_t num_bytes)
660 {
661         if (num_bytes == 0) {
662                 return;
663         }
664         log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
665                 url.c_str(), (long long)num_bytes);
666         assert(pending_data.size() >= num_bytes);
667         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
668 }
669
670 void HTTPInput::add_destination(int stream_index)
671 {
672         stream_indices.push_back(stream_index);
673         servers->set_header(stream_index, http_header, stream_header);
674 }
675
676 InputStats HTTPInput::get_stats() const
677 {
678         lock_guard<mutex> lock(stats_mutex);
679         return stats;
680 }
681
682 void HTTPInput::process_metacube_metadata_block(const metacube2_block_header &hdr, const char *payload, uint32_t payload_size)
683 {
684         if (payload_size < sizeof(uint64_t)) {
685                 log(WARNING, "[%s] Undersized Metacube metadata block (%d bytes); corrupted header?",
686                         url.c_str(), payload_size);
687                 return;
688         }
689
690         uint64_t type = be64toh(*(const uint64_t *)payload);
691         if (type == METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP) {
692                 timespec now;
693                 clock_gettime(CLOCK_REALTIME, &now);
694
695                 const metacube2_timestamp_packet *pkt = (const metacube2_timestamp_packet *)payload;
696                 if (payload_size != sizeof(*pkt)) {
697                         log(WARNING, "[%s] Metacube timestamp block of wrong size (%d bytes); ignoring.",
698                                 url.c_str(), payload_size);
699                         return;
700                 }
701
702                 double elapsed = now.tv_sec - be64toh(pkt->tv_sec) +
703                         1e-9 * (now.tv_nsec - long(be64toh(pkt->tv_nsec)));
704                 {
705                         lock_guard<mutex> lock(stats_mutex);
706                         stats.latency_sec = elapsed;
707                 }
708         } else if (type == METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS) {
709                 const metacube2_pts_packet *pkt = (const metacube2_pts_packet *)payload;
710                 if (payload_size != sizeof(*pkt)) {
711                         log(WARNING, "[%s] Metacube pts block of wrong size (%d bytes); ignoring.",
712                                 url.c_str(), payload_size);
713                         return;
714                 }
715                 next_block_pts.pts = be64toh(pkt->pts);
716                 next_block_pts.timebase_num = be64toh(pkt->timebase_num);
717                 next_block_pts.timebase_den = be64toh(pkt->timebase_den);
718         } else {
719                 // Unknown metadata block, ignore
720                 log(INFO, "[%s] Metadata block %llu\n", url.c_str(), type);
721                 return;
722         }
723 }