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