]> git.sesse.net Git - nageru/blob - httpd.cpp
Add functionality for MJPEG export.
[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(StreamType stream_type, 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                 if (stream->get_stream_type() == stream_type) {
66                         stream->add_data(buf, size, keyframe ? Stream::DATA_TYPE_KEYFRAME : Stream::DATA_TYPE_OTHER, time, timebase);
67                 }
68         }
69 }
70
71 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
72                                       const char *url, const char *method,
73                                       const char *version, const char *upload_data,
74                                       size_t *upload_data_size, void **con_cls)
75 {
76         HTTPD *httpd = (HTTPD *)cls;
77         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
78 }
79
80 int HTTPD::answer_to_connection(MHD_Connection *connection,
81                                 const char *url, const char *method,
82                                 const char *version, const char *upload_data,
83                                 size_t *upload_data_size, void **con_cls)
84 {
85         // See if the URL ends in “.metacube”.
86         HTTPD::Stream::Framing framing;
87         if (strstr(url, ".metacube") == url + strlen(url) - strlen(".metacube")) {
88                 framing = HTTPD::Stream::FRAMING_METACUBE;
89         } else {
90                 framing = HTTPD::Stream::FRAMING_RAW;
91         }
92         HTTPD::StreamType stream_type;
93         if (strcmp(url, "/multicam.mp4") == 0) {
94                 stream_type = HTTPD::StreamType::MULTICAM_STREAM;
95         } else {
96                 stream_type = HTTPD::StreamType::MAIN_STREAM;
97         }
98
99         if (strcmp(url, "/metrics") == 0) {
100                 string contents = global_metrics.serialize();
101                 MHD_Response *response = MHD_create_response_from_buffer(
102                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
103                 MHD_add_response_header(response, "Content-type", "text/plain");
104                 int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
105                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
106                 return ret;
107         }
108         if (endpoints.count(url)) {
109                 pair<string, string> contents_and_type = endpoints[url].callback();
110                 MHD_Response *response = MHD_create_response_from_buffer(
111                         contents_and_type.first.size(), &contents_and_type.first[0], MHD_RESPMEM_MUST_COPY);
112                 MHD_add_response_header(response, "Content-type", contents_and_type.second.c_str());
113                 if (endpoints[url].cors_policy == ALLOW_ALL_ORIGINS) {
114                         MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
115                 }
116                 int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
117                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
118                 return ret;
119         }
120
121         // Small hack; reject unknown /channels/foo.
122         if (string(url).find("/channels/") == 0) {
123                 string contents = "Not found.";
124                 MHD_Response *response = MHD_create_response_from_buffer(
125                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
126                 MHD_add_response_header(response, "Content-type", "text/plain");
127                 int ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
128                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
129                 return ret;
130         }
131
132         HTTPD::Stream *stream = new HTTPD::Stream(this, framing, stream_type);
133         stream->add_data(header[stream_type].data(), header[stream_type].size(), Stream::DATA_TYPE_HEADER, AV_NOPTS_VALUE, AVRational{ 1, 0 });
134         {
135                 unique_lock<mutex> lock(streams_mutex);
136                 streams.insert(stream);
137         }
138         ++metric_num_connected_clients;
139         *con_cls = stream;
140
141         // Does not strictly have to be equal to MUX_BUFFER_SIZE.
142         MHD_Response *response = MHD_create_response_from_callback(
143                 (size_t)-1, MUX_BUFFER_SIZE, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
144         // TODO: Content-type?
145         if (framing == HTTPD::Stream::FRAMING_METACUBE) {
146                 MHD_add_response_header(response, "Content-encoding", "metacube");
147         }
148
149         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
150         MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
151
152         return ret;
153 }
154
155 void HTTPD::free_stream(void *cls)
156 {
157         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
158         HTTPD *httpd = stream->get_parent();
159         {
160                 unique_lock<mutex> lock(httpd->streams_mutex);
161                 delete stream;
162                 httpd->streams.erase(stream);
163         }
164         --httpd->metric_num_connected_clients;
165 }
166
167 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
168 {
169         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
170         return stream->reader_callback(pos, buf, max);
171 }
172
173 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
174 {
175         unique_lock<mutex> lock(buffer_mutex);
176         has_buffered_data.wait(lock, [this]{ return should_quit || !buffered_data.empty(); });
177         if (should_quit) {
178                 return 0;
179         }
180
181         ssize_t ret = 0;
182         while (max > 0 && !buffered_data.empty()) {
183                 const string &s = buffered_data.front();
184                 assert(s.size() > used_of_buffered_data);
185                 size_t len = s.size() - used_of_buffered_data;
186                 if (max >= len) {
187                         // Consume the entire (rest of the) string.
188                         memcpy(buf, s.data() + used_of_buffered_data, len);
189                         buf += len;
190                         ret += len;
191                         max -= len;
192                         buffered_data.pop_front();
193                         used_of_buffered_data = 0;
194                 } else {
195                         // We don't need the entire string; just use the first part of it.
196                         memcpy(buf, s.data() + used_of_buffered_data, max);
197                         buf += max;
198                         used_of_buffered_data += max;
199                         ret += max;
200                         max = 0;
201                 }
202         }
203
204         return ret;
205 }
206
207 void HTTPD::Stream::add_data(const char *buf, size_t buf_size, HTTPD::Stream::DataType data_type, int64_t time, AVRational timebase)
208 {
209         if (buf_size == 0) {
210                 return;
211         }
212         if (data_type == DATA_TYPE_KEYFRAME) {
213                 seen_keyframe = true;
214         } else if (data_type == DATA_TYPE_OTHER && !seen_keyframe) {
215                 // Start sending only once we see a keyframe.
216                 return;
217         }
218
219         unique_lock<mutex> lock(buffer_mutex);
220
221         if (framing == FRAMING_METACUBE) {
222                 int flags = 0;
223                 if (data_type == DATA_TYPE_HEADER) {
224                         flags |= METACUBE_FLAGS_HEADER;
225                 } else if (data_type == DATA_TYPE_OTHER) {
226                         flags |= METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
227                 }
228
229                 // If we're about to send a keyframe, send a pts metadata block
230                 // to mark its time.
231                 if ((flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) == 0 && time != AV_NOPTS_VALUE) {
232                         metacube2_pts_packet packet;
233                         packet.type = htobe64(METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS);
234                         packet.pts = htobe64(time);
235                         packet.timebase_num = htobe64(timebase.num);
236                         packet.timebase_den = htobe64(timebase.den);
237
238                         metacube2_block_header hdr;
239                         memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
240                         hdr.size = htonl(sizeof(packet));
241                         hdr.flags = htons(METACUBE_FLAGS_METADATA);
242                         hdr.csum = htons(metacube2_compute_crc(&hdr));
243                         buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
244                         buffered_data.emplace_back((char *)&packet, sizeof(packet));
245                 }
246
247                 metacube2_block_header hdr;
248                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
249                 hdr.size = htonl(buf_size);
250                 hdr.flags = htons(flags);
251                 hdr.csum = htons(metacube2_compute_crc(&hdr));
252                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
253         }
254         buffered_data.emplace_back(buf, buf_size);
255
256         // Send a Metacube2 timestamp every keyframe.
257         if (framing == FRAMING_METACUBE && data_type == DATA_TYPE_KEYFRAME) {
258                 timespec now;
259                 clock_gettime(CLOCK_REALTIME, &now);
260
261                 metacube2_timestamp_packet packet;
262                 packet.type = htobe64(METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP);
263                 packet.tv_sec = htobe64(now.tv_sec);
264                 packet.tv_nsec = htobe64(now.tv_nsec);
265
266                 metacube2_block_header hdr;
267                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
268                 hdr.size = htonl(sizeof(packet));
269                 hdr.flags = htons(METACUBE_FLAGS_METADATA);
270                 hdr.csum = htons(metacube2_compute_crc(&hdr));
271                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
272                 buffered_data.emplace_back((char *)&packet, sizeof(packet));
273         }
274
275         has_buffered_data.notify_all(); 
276 }
277
278 void HTTPD::Stream::stop()
279 {
280         unique_lock<mutex> lock(buffer_mutex);
281         should_quit = true;
282         has_buffered_data.notify_all();
283 }