]> git.sesse.net Git - nageru/blob - httpd.cpp
Pull the Mux class out of HTTPD. (First step towards decoupling file and HTTP muxing.)
[nageru] / httpd.cpp
1 #include <assert.h>
2 #include <microhttpd.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6
7 extern "C" {
8 #include <libavcodec/avcodec.h>
9 #include <libavutil/channel_layout.h>
10 #include <libavutil/mathematics.h>
11 #include <libavutil/mem.h>
12 #include <libavutil/pixfmt.h>
13 #include <libavutil/rational.h>
14 #include <libavutil/samplefmt.h>
15 }
16
17 #include <vector>
18
19 #include "httpd.h"
20
21 #include "defs.h"
22 #include "flags.h"
23 #include "timebase.h"
24
25 struct MHD_Connection;
26 struct MHD_Response;
27
28 using namespace std;
29
30 HTTPD::HTTPD(int width, int height)
31         : width(width), height(height)
32 {
33 }
34
35 void HTTPD::start(int port)
36 {
37         MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL_INTERNALLY | MHD_USE_DUAL_STACK,
38                          port,
39                          nullptr, nullptr,
40                          &answer_to_connection_thunk, this,
41                          MHD_OPTION_NOTIFY_COMPLETED, &request_completed_thunk, this, 
42                          MHD_OPTION_END);
43 }
44
45 void HTTPD::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts, PacketDestination destination)
46 {
47         unique_lock<mutex> lock(streams_mutex);
48         if (destination != DESTINATION_FILE_ONLY) {
49                 for (Stream *stream : streams) {
50                         stream->add_packet(pkt, pts, dts);
51                 }
52         }
53         if (file_mux && destination != DESTINATION_HTTP_ONLY) {
54                 file_mux->add_packet(pkt, pts, dts);
55         }
56 }
57
58 void HTTPD::open_output_file(const string &filename)
59 {
60         AVFormatContext *avctx = avformat_alloc_context();
61         avctx->oformat = av_guess_format(NULL, filename.c_str(), NULL);
62         assert(filename.size() < sizeof(avctx->filename) - 1);
63         strcpy(avctx->filename, filename.c_str());
64
65         string url = "file:" + filename;
66         int ret = avio_open2(&avctx->pb, url.c_str(), AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL);
67         if (ret < 0) {
68                 char tmp[AV_ERROR_MAX_STRING_SIZE];
69                 fprintf(stderr, "%s: avio_open2() failed: %s\n", filename.c_str(), av_make_error_string(tmp, sizeof(tmp), ret));
70                 exit(1);
71         }
72
73         file_mux.reset(new Mux(avctx, width, height, Mux::CODEC_H264, TIMEBASE));
74 }
75
76 void HTTPD::close_output_file()
77 {
78         file_mux.reset();
79 }
80
81 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
82                                       const char *url, const char *method,
83                                       const char *version, const char *upload_data,
84                                       size_t *upload_data_size, void **con_cls)
85 {
86         HTTPD *httpd = (HTTPD *)cls;
87         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
88 }
89
90 int HTTPD::answer_to_connection(MHD_Connection *connection,
91                                 const char *url, const char *method,
92                                 const char *version, const char *upload_data,
93                                 size_t *upload_data_size, void **con_cls)
94 {
95         AVOutputFormat *oformat = av_guess_format(global_flags.stream_mux_name.c_str(), nullptr, nullptr);
96         assert(oformat != nullptr);
97
98         int time_base = global_flags.stream_coarse_timebase ? COARSE_TIMEBASE : TIMEBASE;
99         HTTPD::Stream *stream = new HTTPD::Stream(oformat, width, height, time_base);
100         {
101                 unique_lock<mutex> lock(streams_mutex);
102                 streams.insert(stream);
103         }
104         *con_cls = stream;
105
106         // Does not strictly have to be equal to MUX_BUFFER_SIZE.
107         MHD_Response *response = MHD_create_response_from_callback(
108                 (size_t)-1, MUX_BUFFER_SIZE, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
109         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
110         //MHD_destroy_response(response);
111
112         return ret;
113 }
114
115 void HTTPD::free_stream(void *cls)
116 {
117         // FIXME: When is this actually called, if ever?
118         // Also, shouldn't we remove it from streams?
119         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
120         delete stream;
121 }
122
123 void HTTPD::request_completed_thunk(void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe)
124 {
125         HTTPD *httpd = (HTTPD *)cls;
126         return httpd->request_completed(connection, con_cls, toe);
127 }
128
129 void HTTPD::request_completed(struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe)
130 {
131         if (con_cls == nullptr) {
132                 // Request was never set up.
133                 return;
134         }
135         HTTPD::Stream *stream = (HTTPD::Stream *)*con_cls;
136         {
137                 unique_lock<mutex> lock(streams_mutex);
138                 delete stream;
139                 streams.erase(stream);
140         }
141 }
142
143 HTTPD::Stream::Stream(AVOutputFormat *oformat, int width, int height, int time_base)
144 {
145         AVFormatContext *avctx = avformat_alloc_context();
146         avctx->oformat = oformat;
147         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
148         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, &HTTPD::Stream::write_packet_thunk, nullptr);
149
150         Mux::Codec video_codec;
151         if (global_flags.uncompressed_video_to_http) {
152                 video_codec = Mux::CODEC_NV12;
153         } else {
154                 video_codec = Mux::CODEC_H264;
155         }
156
157         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
158
159         mux.reset(new Mux(avctx, width, height, video_codec, time_base));
160 }
161
162 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
163 {
164         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
165         return stream->reader_callback(pos, buf, max);
166 }
167
168 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
169 {
170         unique_lock<mutex> lock(buffer_mutex);
171         has_buffered_data.wait(lock, [this]{ return !buffered_data.empty(); });
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_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
200 {
201         mux->add_packet(pkt, pts, dts);
202 }
203
204 int HTTPD::Stream::write_packet_thunk(void *opaque, uint8_t *buf, int buf_size)
205 {
206         HTTPD::Stream *stream = (HTTPD::Stream *)opaque;
207         return stream->write_packet(buf, buf_size);
208 }
209
210 int HTTPD::Stream::write_packet(uint8_t *buf, int buf_size)
211 {
212         unique_lock<mutex> lock(buffer_mutex);
213         buffered_data.emplace_back((char *)buf, buf_size);
214         has_buffered_data.notify_all(); 
215         return buf_size;
216 }
217