]> git.sesse.net Git - nageru/blob - httpd.cpp
Add the GPU memory metrics to the Grafana dashboard.
[nageru] / httpd.cpp
1 #include "httpd.h"
2
3 #include <assert.h>
4 #include <byteswap.h>
5 #include <endian.h>
6 #include <microhttpd.h>
7 #include <netinet/in.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <sys/time.h>
11 #include <time.h>
12 #include <memory>
13 extern "C" {
14 #include <libavutil/avutil.h>
15 }
16
17 #include "defs.h"
18 #include "metacube2.h"
19 #include "metrics.h"
20
21 struct MHD_Connection;
22 struct MHD_Response;
23
24 using namespace std;
25
26 HTTPD::HTTPD()
27 {
28         global_metrics.add("num_connected_clients", &metric_num_connected_clients, Metrics::TYPE_GAUGE);
29 }
30
31 HTTPD::~HTTPD()
32 {
33         stop();
34 }
35
36 void HTTPD::start(int port)
37 {
38         mhd = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL_INTERNALLY | MHD_USE_DUAL_STACK,
39                                port,
40                                nullptr, nullptr,
41                                &answer_to_connection_thunk, this,
42                                MHD_OPTION_NOTIFY_COMPLETED, nullptr, this,
43                                MHD_OPTION_END);
44         if (mhd == nullptr) {
45                 fprintf(stderr, "Warning: Could not open HTTP server. (Port already in use?)\n");
46         }
47 }
48
49 void HTTPD::stop()
50 {
51         if (mhd) {
52                 MHD_quiesce_daemon(mhd);
53                 for (Stream *stream : streams) {
54                         stream->stop();
55                 }
56                 MHD_stop_daemon(mhd);
57                 mhd = nullptr;
58         }
59 }
60
61 void HTTPD::add_data(const char *buf, size_t size, bool keyframe, int64_t time, AVRational timebase)
62 {
63         unique_lock<mutex> lock(streams_mutex);
64         for (Stream *stream : streams) {
65                 stream->add_data(buf, size, keyframe ? Stream::DATA_TYPE_KEYFRAME : Stream::DATA_TYPE_OTHER, time, timebase);
66         }
67 }
68
69 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
70                                       const char *url, const char *method,
71                                       const char *version, const char *upload_data,
72                                       size_t *upload_data_size, void **con_cls)
73 {
74         HTTPD *httpd = (HTTPD *)cls;
75         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
76 }
77
78 int HTTPD::answer_to_connection(MHD_Connection *connection,
79                                 const char *url, const char *method,
80                                 const char *version, const char *upload_data,
81                                 size_t *upload_data_size, void **con_cls)
82 {
83         // See if the URL ends in “.metacube”.
84         HTTPD::Stream::Framing framing;
85         if (strstr(url, ".metacube") == url + strlen(url) - strlen(".metacube")) {
86                 framing = HTTPD::Stream::FRAMING_METACUBE;
87         } else {
88                 framing = HTTPD::Stream::FRAMING_RAW;
89         }
90
91         if (strcmp(url, "/metrics") == 0) {
92                 string contents = global_metrics.serialize();
93                 MHD_Response *response = MHD_create_response_from_buffer(
94                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
95                 MHD_add_response_header(response, "Content-type", "text/plain");
96                 int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
97                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
98                 return ret;
99         }
100         if (endpoints.count(url)) {
101                 pair<string, string> contents_and_type = endpoints[url].callback();
102                 MHD_Response *response = MHD_create_response_from_buffer(
103                         contents_and_type.first.size(), &contents_and_type.first[0], MHD_RESPMEM_MUST_COPY);
104                 MHD_add_response_header(response, "Content-type", contents_and_type.second.c_str());
105                 if (endpoints[url].cors_policy == ALLOW_ALL_ORIGINS) {
106                         MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
107                 }
108                 int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
109                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
110                 return ret;
111         }
112
113         // Small hack; reject unknown /channels/foo.
114         if (string(url).find("/channels/") == 0) {
115                 string contents = "Not found.";
116                 MHD_Response *response = MHD_create_response_from_buffer(
117                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
118                 MHD_add_response_header(response, "Content-type", "text/plain");
119                 int ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
120                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
121                 return ret;
122         }
123
124         HTTPD::Stream *stream = new HTTPD::Stream(this, framing);
125         stream->add_data(header.data(), header.size(), Stream::DATA_TYPE_HEADER, AV_NOPTS_VALUE, AVRational{ 1, 0 });
126         {
127                 unique_lock<mutex> lock(streams_mutex);
128                 streams.insert(stream);
129         }
130         ++metric_num_connected_clients;
131         *con_cls = stream;
132
133         // Does not strictly have to be equal to MUX_BUFFER_SIZE.
134         MHD_Response *response = MHD_create_response_from_callback(
135                 (size_t)-1, MUX_BUFFER_SIZE, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
136         // TODO: Content-type?
137         if (framing == HTTPD::Stream::FRAMING_METACUBE) {
138                 MHD_add_response_header(response, "Content-encoding", "metacube");
139         }
140
141         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
142         MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
143
144         return ret;
145 }
146
147 void HTTPD::free_stream(void *cls)
148 {
149         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
150         HTTPD *httpd = stream->get_parent();
151         {
152                 unique_lock<mutex> lock(httpd->streams_mutex);
153                 delete stream;
154                 httpd->streams.erase(stream);
155         }
156         --httpd->metric_num_connected_clients;
157 }
158
159 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
160 {
161         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
162         return stream->reader_callback(pos, buf, max);
163 }
164
165 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
166 {
167         unique_lock<mutex> lock(buffer_mutex);
168         has_buffered_data.wait(lock, [this]{ return should_quit || !buffered_data.empty(); });
169         if (should_quit) {
170                 return 0;
171         }
172
173         ssize_t ret = 0;
174         while (max > 0 && !buffered_data.empty()) {
175                 const string &s = buffered_data.front();
176                 assert(s.size() > used_of_buffered_data);
177                 size_t len = s.size() - used_of_buffered_data;
178                 if (max >= len) {
179                         // Consume the entire (rest of the) string.
180                         memcpy(buf, s.data() + used_of_buffered_data, len);
181                         buf += len;
182                         ret += len;
183                         max -= len;
184                         buffered_data.pop_front();
185                         used_of_buffered_data = 0;
186                 } else {
187                         // We don't need the entire string; just use the first part of it.
188                         memcpy(buf, s.data() + used_of_buffered_data, max);
189                         buf += max;
190                         used_of_buffered_data += max;
191                         ret += max;
192                         max = 0;
193                 }
194         }
195
196         return ret;
197 }
198
199 void HTTPD::Stream::add_data(const char *buf, size_t buf_size, HTTPD::Stream::DataType data_type, int64_t time, AVRational timebase)
200 {
201         if (buf_size == 0) {
202                 return;
203         }
204         if (data_type == DATA_TYPE_KEYFRAME) {
205                 seen_keyframe = true;
206         } else if (data_type == DATA_TYPE_OTHER && !seen_keyframe) {
207                 // Start sending only once we see a keyframe.
208                 return;
209         }
210
211         unique_lock<mutex> lock(buffer_mutex);
212
213         if (framing == FRAMING_METACUBE) {
214                 int flags = 0;
215                 if (data_type == DATA_TYPE_HEADER) {
216                         flags |= METACUBE_FLAGS_HEADER;
217                 } else if (data_type == DATA_TYPE_OTHER) {
218                         flags |= METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
219                 }
220
221                 // If we're about to send a keyframe, send a pts metadata block
222                 // to mark its time.
223                 if ((flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) == 0 && time != AV_NOPTS_VALUE) {
224                         metacube2_pts_packet packet;
225                         packet.type = htobe64(METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS);
226                         packet.pts = htobe64(time);
227                         packet.timebase_num = htobe64(timebase.num);
228                         packet.timebase_den = htobe64(timebase.den);
229
230                         metacube2_block_header hdr;
231                         memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
232                         hdr.size = htonl(sizeof(packet));
233                         hdr.flags = htons(METACUBE_FLAGS_METADATA);
234                         hdr.csum = htons(metacube2_compute_crc(&hdr));
235                         buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
236                         buffered_data.emplace_back((char *)&packet, sizeof(packet));
237                 }
238
239                 metacube2_block_header hdr;
240                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
241                 hdr.size = htonl(buf_size);
242                 hdr.flags = htons(flags);
243                 hdr.csum = htons(metacube2_compute_crc(&hdr));
244                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
245         }
246         buffered_data.emplace_back(buf, buf_size);
247
248         // Send a Metacube2 timestamp every keyframe.
249         if (framing == FRAMING_METACUBE && data_type == DATA_TYPE_KEYFRAME) {
250                 timespec now;
251                 clock_gettime(CLOCK_REALTIME, &now);
252
253                 metacube2_timestamp_packet packet;
254                 packet.type = htobe64(METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP);
255                 packet.tv_sec = htobe64(now.tv_sec);
256                 packet.tv_nsec = htobe64(now.tv_nsec);
257
258                 metacube2_block_header hdr;
259                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
260                 hdr.size = htonl(sizeof(packet));
261                 hdr.flags = htons(METACUBE_FLAGS_METADATA);
262                 hdr.csum = htons(metacube2_compute_crc(&hdr));
263                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
264                 buffered_data.emplace_back((char *)&packet, sizeof(packet));
265         }
266
267         has_buffered_data.notify_all(); 
268 }
269
270 void HTTPD::Stream::stop()
271 {
272         unique_lock<mutex> lock(buffer_mutex);
273         should_quit = true;
274         has_buffered_data.notify_all();
275 }