]> git.sesse.net Git - nageru/blob - httpd.cpp
Unify muxing between the local file and networking.
[nageru] / httpd.cpp
1 #include <string.h>
2 #include <microhttpd.h>
3 #include <assert.h>
4
5 extern "C" {
6 #include <libavcodec/avcodec.h>
7 }
8
9 #include "httpd.h"
10 #include "timebase.h"
11
12 using namespace std;
13
14 HTTPD::HTTPD(const char *output_filename, int width, int height)
15         : width(width), height(height)
16 {
17         AVFormatContext *avctx = avformat_alloc_context();
18         avctx->oformat = av_guess_format(NULL, output_filename, NULL);
19         strcpy(avctx->filename, output_filename);
20         if (avio_open2(&avctx->pb, output_filename, AVIO_FLAG_WRITE, &avctx->interrupt_callback, NULL) < 0) {
21                 fprintf(stderr, "%s: avio_open2() failed\n", output_filename);
22                 exit(1);
23         }
24
25         file_mux.reset(new Mux(avctx, width, height));
26 }
27
28 void HTTPD::start(int port)
29 {
30         MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL_INTERNALLY | MHD_USE_DUAL_STACK,
31                          port,
32                          nullptr, nullptr,
33                          &answer_to_connection_thunk, this, MHD_OPTION_END);
34 }
35
36 void HTTPD::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
37 {
38         for (Stream *stream : streams) {
39                 stream->add_packet(pkt, pts, dts);
40         }
41         file_mux->add_packet(pkt, pts, dts);
42 }
43
44 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
45                                       const char *url, const char *method,
46                                       const char *version, const char *upload_data,
47                                       size_t *upload_data_size, void **con_cls)
48 {
49         HTTPD *httpd = (HTTPD *)cls;
50         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
51 }
52
53 int HTTPD::answer_to_connection(MHD_Connection *connection,
54                                 const char *url, const char *method,
55                                 const char *version, const char *upload_data,
56                                 size_t *upload_data_size, void **con_cls)
57 {
58         printf("url %s\n", url);
59         AVOutputFormat *oformat = av_guess_format("mpegts", nullptr, nullptr);
60         assert(oformat != nullptr);
61         HTTPD::Stream *stream = new HTTPD::Stream(oformat, width, height);
62         streams.push_back(stream);
63         MHD_Response *response = MHD_create_response_from_callback(
64                 (size_t)-1, 1048576, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
65         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
66         //MHD_destroy_response(response);
67
68         return ret;
69 }
70
71 void HTTPD::free_stream(void *cls)
72 {
73         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
74         delete stream;
75 }
76
77 HTTPD::Mux::Mux(AVFormatContext *avctx, int width, int height)
78         : avctx(avctx)
79 {
80         AVCodec *codec_video = avcodec_find_encoder(AV_CODEC_ID_H264);
81         avstream_video = avformat_new_stream(avctx, codec_video);
82         if (avstream_video == nullptr) {
83                 fprintf(stderr, "avformat_new_stream() failed\n");
84                 exit(1);
85         }
86         avstream_video->time_base = AVRational{1, TIMEBASE};
87         avstream_video->codec->width = width;
88         avstream_video->codec->height = height;
89         avstream_video->codec->time_base = AVRational{1, TIMEBASE};
90         avstream_video->codec->ticks_per_frame = 1;  // or 2?
91
92         AVCodec *codec_audio = avcodec_find_encoder(AV_CODEC_ID_MP3);
93         avstream_audio = avformat_new_stream(avctx, codec_audio);
94         if (avstream_audio == nullptr) {
95                 fprintf(stderr, "avformat_new_stream() failed\n");
96                 exit(1);
97         }
98         avstream_audio->time_base = AVRational{1, TIMEBASE};
99         avstream_audio->codec->bit_rate = 256000;
100         avstream_audio->codec->sample_rate = 48000;
101         avstream_audio->codec->sample_fmt = AV_SAMPLE_FMT_FLTP;
102         avstream_audio->codec->channels = 2;
103         avstream_audio->codec->channel_layout = AV_CH_LAYOUT_STEREO;
104         avstream_audio->codec->time_base = AVRational{1, TIMEBASE};
105
106         if (avformat_write_header(avctx, NULL) < 0) {
107                 fprintf(stderr, "avformat_write_header() failed\n");
108                 exit(1);
109         }
110 }
111
112 HTTPD::Mux::~Mux()
113 {
114         av_write_trailer(avctx);
115         avformat_free_context(avctx);
116 }
117
118 void HTTPD::Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
119 {
120         AVPacket pkt_copy;
121         av_copy_packet(&pkt_copy, &pkt);
122         if (pkt.stream_index == 0) {
123                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base);
124                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base);
125         } else if (pkt.stream_index == 1) {
126                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
127                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
128         } else {
129                 assert(false);
130         }
131
132         if (av_interleaved_write_frame(avctx, &pkt_copy) < 0) {
133                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
134                 exit(1);
135         }
136 }
137
138 HTTPD::Stream::Stream(AVOutputFormat *oformat, int width, int height)
139 {
140         AVFormatContext *avctx = avformat_alloc_context();
141         avctx->oformat = oformat;
142         uint8_t *buf = (uint8_t *)av_malloc(1048576);
143         avctx->pb = avio_alloc_context(buf, 1048576, 1, this, nullptr, &HTTPD::Stream::write_packet_thunk, nullptr);
144         avctx->flags = AVFMT_FLAG_CUSTOM_IO;
145
146         mux.reset(new Mux(avctx, width, height));
147 }
148
149 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
150 {
151         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
152         return stream->reader_callback(pos, buf, max);
153 }
154
155 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
156 {
157         unique_lock<mutex> lock(buffer_mutex);
158         has_buffered_data.wait(lock, [this]{ return !buffered_data.empty(); });
159
160         ssize_t ret = 0;
161         while (max > 0 && !buffered_data.empty()) {
162                 const string &s = buffered_data.front();
163                 assert(s.size() > used_of_buffered_data);
164                 size_t len = s.size() - used_of_buffered_data;
165                 if (max >= len) {
166                         // Consume the entire (rest of the) string.
167                         memcpy(buf, s.data() + used_of_buffered_data, len);
168                         ret += len;
169                         max -= len;
170                         buffered_data.pop_front();
171                         used_of_buffered_data = 0;
172                 } else {
173                         // We don't need the entire string; just use the first part of it.
174                         memcpy(buf, s.data() + used_of_buffered_data, max);
175                         used_of_buffered_data += max;
176                         ret += max;
177                         max = 0;
178                 }
179         }
180
181         return ret;
182 }
183
184 void HTTPD::Stream::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
185 {
186         mux->add_packet(pkt, pts, dts);
187 }
188
189 int HTTPD::Stream::write_packet_thunk(void *opaque, uint8_t *buf, int buf_size)
190 {
191         HTTPD::Stream *stream = (HTTPD::Stream *)opaque;
192         return stream->write_packet(buf, buf_size);
193 }
194
195 int HTTPD::Stream::write_packet(uint8_t *buf, int buf_size)
196 {
197         unique_lock<mutex> lock(buffer_mutex);
198         buffered_data.emplace_back((char *)buf, buf_size);
199         has_buffered_data.notify_all(); 
200         return buf_size;
201 }
202