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