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