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