]> git.sesse.net Git - nageru/blob - httpd.cpp
Work around some false positives found by Coverity Scan.
[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 "httpd.h"
18
19 #include "defs.h"
20 #include "timebase.h"
21
22 struct MHD_Connection;
23 struct MHD_Response;
24
25 using namespace std;
26
27 HTTPD::HTTPD(int width, int height)
28         : width(width), height(height)
29 {
30 }
31
32 void HTTPD::start(int port)
33 {
34         MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL_INTERNALLY | MHD_USE_DUAL_STACK,
35                          port,
36                          nullptr, nullptr,
37                          &answer_to_connection_thunk, this, MHD_OPTION_END);
38 }
39
40 void HTTPD::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
41 {
42         for (Stream *stream : streams) {
43                 stream->add_packet(pkt, pts, dts);
44         }
45         if (file_mux) {
46                 file_mux->add_packet(pkt, pts, dts);
47         }
48 }
49
50 void HTTPD::open_output_file(const string &filename)
51 {
52         AVFormatContext *avctx = avformat_alloc_context();
53         avctx->oformat = av_guess_format(NULL, filename.c_str(), NULL);
54         assert(filename.size() < sizeof(avctx->filename) - 1);
55         strcpy(avctx->filename, filename.c_str());
56
57         string url = "file:" + filename;
58         int ret = avio_open2(&avctx->pb, url.c_str(), AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL);
59         if (ret < 0) {
60                 char tmp[AV_ERROR_MAX_STRING_SIZE];
61                 fprintf(stderr, "%s: avio_open2() failed: %s\n", filename.c_str(), av_make_error_string(tmp, sizeof(tmp), ret));
62                 exit(1);
63         }
64
65         file_mux.reset(new Mux(avctx, width, height));
66 }
67
68 void HTTPD::close_output_file()
69 {
70         file_mux.reset();
71 }
72
73 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
74                                       const char *url, const char *method,
75                                       const char *version, const char *upload_data,
76                                       size_t *upload_data_size, void **con_cls)
77 {
78         HTTPD *httpd = (HTTPD *)cls;
79         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
80 }
81
82 int HTTPD::answer_to_connection(MHD_Connection *connection,
83                                 const char *url, const char *method,
84                                 const char *version, const char *upload_data,
85                                 size_t *upload_data_size, void **con_cls)
86 {
87         printf("url %s\n", url);
88         AVOutputFormat *oformat = av_guess_format(STREAM_MUX_NAME, nullptr, nullptr);
89         assert(oformat != nullptr);
90         HTTPD::Stream *stream = new HTTPD::Stream(oformat, width, height);
91         streams.push_back(stream);
92
93         // Does not strictly have to be equal to MUX_BUFFER_SIZE.
94         MHD_Response *response = MHD_create_response_from_callback(
95                 (size_t)-1, MUX_BUFFER_SIZE, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
96         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
97         //MHD_destroy_response(response);
98
99         return ret;
100 }
101
102 void HTTPD::free_stream(void *cls)
103 {
104         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
105         delete stream;
106 }
107
108 HTTPD::Mux::Mux(AVFormatContext *avctx, int width, int height)
109         : avctx(avctx)
110 {
111         AVCodec *codec_video = avcodec_find_encoder(AV_CODEC_ID_H264);
112         avstream_video = avformat_new_stream(avctx, codec_video);
113         if (avstream_video == nullptr) {
114                 fprintf(stderr, "avformat_new_stream() failed\n");
115                 exit(1);
116         }
117         avstream_video->time_base = AVRational{1, TIMEBASE};
118         avstream_video->codec->width = width;
119         avstream_video->codec->height = height;
120         avstream_video->codec->time_base = AVRational{1, TIMEBASE};
121         avstream_video->codec->ticks_per_frame = 1;  // or 2?
122
123         // Colorspace details. Closely correspond to settings in EffectChain_finalize,
124         // as noted in each comment.
125         // Note that the H.264 stream also contains this information and depending on the
126         // mux, this might simply get ignored. See sps_rbsp().
127         avstream_video->codec->color_primaries = AVCOL_PRI_BT709;  // RGB colorspace (inout_format.color_space).
128         avstream_video->codec->color_trc = AVCOL_TRC_UNSPECIFIED;  // Gamma curve (inout_format.gamma_curve).
129         avstream_video->codec->colorspace = AVCOL_SPC_SMPTE170M;  // YUV colorspace (output_ycbcr_format.luma_coefficients).
130         avstream_video->codec->color_range = AVCOL_RANGE_MPEG;  // Full vs. limited range (output_ycbcr_format.full_range).
131         avstream_video->codec->chroma_sample_location = AVCHROMA_LOC_LEFT;  // Chroma sample location. See chroma_offset_0[] in Mixer::subsample_chroma().
132         avstream_video->codec->field_order = AV_FIELD_PROGRESSIVE;
133
134         AVCodec *codec_audio = avcodec_find_encoder(AUDIO_OUTPUT_CODEC);
135         avstream_audio = avformat_new_stream(avctx, codec_audio);
136         if (avstream_audio == nullptr) {
137                 fprintf(stderr, "avformat_new_stream() failed\n");
138                 exit(1);
139         }
140         avstream_audio->time_base = AVRational{1, TIMEBASE};
141         avstream_audio->codec->bit_rate = AUDIO_OUTPUT_BIT_RATE;
142         avstream_audio->codec->sample_rate = OUTPUT_FREQUENCY;
143         avstream_audio->codec->sample_fmt = AUDIO_OUTPUT_SAMPLE_FMT;
144         avstream_audio->codec->channels = 2;
145         avstream_audio->codec->channel_layout = AV_CH_LAYOUT_STEREO;
146         avstream_audio->codec->time_base = AVRational{1, TIMEBASE};
147
148         AVDictionary *options = NULL;
149         vector<pair<string, string>> opts = MUX_OPTS;
150         for (pair<string, string> opt : opts) {
151                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
152         }
153         if (avformat_write_header(avctx, &options) < 0) {
154                 fprintf(stderr, "avformat_write_header() failed\n");
155                 exit(1);
156         }
157 }
158
159 HTTPD::Mux::~Mux()
160 {
161         av_write_trailer(avctx);
162         avformat_free_context(avctx);
163 }
164
165 void HTTPD::Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
166 {
167         AVPacket pkt_copy;
168         av_copy_packet(&pkt_copy, &pkt);
169         if (pkt.stream_index == 0) {
170                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base);
171                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base);
172         } else if (pkt.stream_index == 1) {
173                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
174                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
175         } else {
176                 assert(false);
177         }
178
179         if (av_interleaved_write_frame(avctx, &pkt_copy) < 0) {
180                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
181                 exit(1);
182         }
183 }
184
185 HTTPD::Stream::Stream(AVOutputFormat *oformat, int width, int height)
186 {
187         AVFormatContext *avctx = avformat_alloc_context();
188         avctx->oformat = oformat;
189         uint8_t *buf = (uint8_t *)av_malloc(MUX_BUFFER_SIZE);
190         avctx->pb = avio_alloc_context(buf, MUX_BUFFER_SIZE, 1, this, nullptr, &HTTPD::Stream::write_packet_thunk, nullptr);
191         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
192
193         mux.reset(new Mux(avctx, width, height));
194 }
195
196 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
197 {
198         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
199         return stream->reader_callback(pos, buf, max);
200 }
201
202 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
203 {
204         unique_lock<mutex> lock(buffer_mutex);
205         has_buffered_data.wait(lock, [this]{ return !buffered_data.empty(); });
206
207         ssize_t ret = 0;
208         while (max > 0 && !buffered_data.empty()) {
209                 const string &s = buffered_data.front();
210                 assert(s.size() > used_of_buffered_data);
211                 size_t len = s.size() - used_of_buffered_data;
212                 if (max >= len) {
213                         // Consume the entire (rest of the) string.
214                         memcpy(buf, s.data() + used_of_buffered_data, len);
215                         ret += len;
216                         max -= len;
217                         buffered_data.pop_front();
218                         used_of_buffered_data = 0;
219                 } else {
220                         // We don't need the entire string; just use the first part of it.
221                         memcpy(buf, s.data() + used_of_buffered_data, max);
222                         used_of_buffered_data += max;
223                         ret += max;
224                         max = 0;
225                 }
226         }
227
228         return ret;
229 }
230
231 void HTTPD::Stream::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
232 {
233         mux->add_packet(pkt, pts, dts);
234 }
235
236 int HTTPD::Stream::write_packet_thunk(void *opaque, uint8_t *buf, int buf_size)
237 {
238         HTTPD::Stream *stream = (HTTPD::Stream *)opaque;
239         return stream->write_packet(buf, buf_size);
240 }
241
242 int HTTPD::Stream::write_packet(uint8_t *buf, int buf_size)
243 {
244         unique_lock<mutex> lock(buffer_mutex);
245         buffered_data.emplace_back((char *)buf, buf_size);
246         has_buffered_data.notify_all(); 
247         return buf_size;
248 }
249