]> git.sesse.net Git - nageru/blob - mux.cpp
Import a bunch of http/mux code from Nageru.
[nageru] / mux.cpp
1 #include "mux.h"
2
3 #include <assert.h>
4 #include <stdint.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <algorithm>
9 #include <mutex>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
14 extern "C" {
15 #include <libavformat/avio.h>
16 #include <libavutil/avutil.h>
17 #include <libavutil/dict.h>
18 #include <libavutil/mathematics.h>
19 #include <libavutil/mem.h>
20 #include <libavutil/pixfmt.h>
21 #include <libavutil/rational.h>
22 }
23
24 #include "defs.h"
25 #include "timebase.h"
26
27 using namespace std;
28
29 struct PacketBefore {
30         PacketBefore(const AVFormatContext *ctx) : ctx(ctx) {}
31
32         bool operator() (const Mux::QueuedPacket &a_qp, const Mux::QueuedPacket &b_qp) const {
33                 const AVPacket *a = a_qp.pkt;
34                 const AVPacket *b = b_qp.pkt;
35                 int64_t a_dts = (a->dts == AV_NOPTS_VALUE ? a->pts : a->dts);
36                 int64_t b_dts = (b->dts == AV_NOPTS_VALUE ? b->pts : b->dts);
37                 AVRational a_timebase = ctx->streams[a->stream_index]->time_base;
38                 AVRational b_timebase = ctx->streams[b->stream_index]->time_base;
39                 if (av_compare_ts(a_dts, a_timebase, b_dts, b_timebase) != 0) {
40                         return av_compare_ts(a_dts, a_timebase, b_dts, b_timebase) < 0;
41                 } else {
42                         return av_compare_ts(a->pts, a_timebase, b->pts, b_timebase) < 0;
43                 }
44         }
45
46         const AVFormatContext * const ctx;
47 };
48
49 Mux::Mux(AVFormatContext *avctx, int width, int height, Codec video_codec, const string &video_extradata, const AVCodecParameters *audio_codecpar, int time_base, std::function<void(int64_t)> write_callback, WriteStrategy write_strategy, const vector<MuxMetrics *> &metrics)
50         : write_strategy(write_strategy), avctx(avctx), write_callback(write_callback), metrics(metrics)
51 {
52         avstream_video = avformat_new_stream(avctx, nullptr);
53         if (avstream_video == nullptr) {
54                 fprintf(stderr, "avformat_new_stream() failed\n");
55                 exit(1);
56         }
57         avstream_video->time_base = AVRational{1, time_base};
58         avstream_video->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
59         if (video_codec == CODEC_H264) {
60                 avstream_video->codecpar->codec_id = AV_CODEC_ID_H264;
61         } else {
62                 assert(video_codec == CODEC_NV12);
63                 avstream_video->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
64                 avstream_video->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag(AV_PIX_FMT_NV12);
65         }
66         avstream_video->codecpar->width = width;
67         avstream_video->codecpar->height = height;
68
69         // Colorspace details. Closely correspond to settings in EffectChain_finalize,
70         // as noted in each comment.
71         // Note that the H.264 stream also contains this information and depending on the
72         // mux, this might simply get ignored. See sps_rbsp().
73         // Note that there's no way to change this per-frame as the H.264 stream
74         // would like to be able to.
75         avstream_video->codecpar->color_primaries = AVCOL_PRI_BT709;  // RGB colorspace (inout_format.color_space).
76         avstream_video->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;  // Gamma curve (inout_format.gamma_curve).
77         // YUV colorspace (output_ycbcr_format.luma_coefficients).
78         avstream_video->codecpar->color_space = AVCOL_SPC_BT709;
79         avstream_video->codecpar->color_range = AVCOL_RANGE_MPEG;  // Full vs. limited range (output_ycbcr_format.full_range).
80         avstream_video->codecpar->chroma_location = AVCHROMA_LOC_LEFT;  // Chroma sample location. See chroma_offset_0[] in Mixer::subsample_chroma().
81         avstream_video->codecpar->field_order = AV_FIELD_PROGRESSIVE;
82
83         if (!video_extradata.empty()) {
84                 avstream_video->codecpar->extradata = (uint8_t *)av_malloc(video_extradata.size());
85                 avstream_video->codecpar->extradata_size = video_extradata.size();
86                 memcpy(avstream_video->codecpar->extradata, video_extradata.data(), video_extradata.size());
87         }
88
89         avstream_audio = avformat_new_stream(avctx, nullptr);
90         if (avstream_audio == nullptr) {
91                 fprintf(stderr, "avformat_new_stream() failed\n");
92                 exit(1);
93         }
94         avstream_audio->time_base = AVRational{1, time_base};
95         if (avcodec_parameters_copy(avstream_audio->codecpar, audio_codecpar) < 0) {
96                 fprintf(stderr, "avcodec_parameters_copy() failed\n");
97                 exit(1);
98         }
99
100         AVDictionary *options = NULL;
101         vector<pair<string, string>> opts = MUX_OPTS;
102         for (pair<string, string> opt : opts) {
103                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
104         }
105         if (avformat_write_header(avctx, &options) < 0) {
106                 fprintf(stderr, "avformat_write_header() failed\n");
107                 exit(1);
108         }
109         for (MuxMetrics *metric : metrics) {
110                 metric->metric_written_bytes += avctx->pb->pos;
111         }
112
113         // Make sure the header is written before the constructor exits.
114         avio_flush(avctx->pb);
115
116         if (write_strategy == WRITE_BACKGROUND) {
117                 writer_thread = thread(&Mux::thread_func, this);
118         }
119 }
120
121 Mux::~Mux()
122 {
123         assert(plug_count == 0);
124         if (write_strategy == WRITE_BACKGROUND) {
125                 writer_thread_should_quit = true;
126                 packet_queue_ready.notify_all();
127                 writer_thread.join();
128         }
129         int64_t old_pos = avctx->pb->pos;
130         av_write_trailer(avctx);
131         for (MuxMetrics *metric : metrics) {
132                 metric->metric_written_bytes += avctx->pb->pos - old_pos;
133         }
134
135         if (!(avctx->oformat->flags & AVFMT_NOFILE) &&
136             !(avctx->flags & AVFMT_FLAG_CUSTOM_IO)) {
137                 avio_closep(&avctx->pb);
138         }
139         avformat_free_context(avctx);
140 }
141
142 void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts, AVRational timebase, int stream_index_override)
143 {
144         AVPacket pkt_copy;
145         av_init_packet(&pkt_copy);
146         if (av_packet_ref(&pkt_copy, &pkt) < 0) {
147                 fprintf(stderr, "av_copy_packet() failed\n");
148                 exit(1);
149         }
150         if (stream_index_override != -1) {
151                 pkt_copy.stream_index = stream_index_override;
152         }
153         if (pkt_copy.stream_index == 0) {
154                 pkt_copy.pts = av_rescale_q(pts, timebase, avstream_video->time_base);
155                 pkt_copy.dts = av_rescale_q(dts, timebase, avstream_video->time_base);
156                 pkt_copy.duration = av_rescale_q(pkt.duration, timebase, avstream_video->time_base);
157         } else if (pkt_copy.stream_index == 1) {
158                 pkt_copy.pts = av_rescale_q(pts, timebase, avstream_audio->time_base);
159                 pkt_copy.dts = av_rescale_q(dts, timebase, avstream_audio->time_base);
160                 pkt_copy.duration = av_rescale_q(pkt.duration, timebase, avstream_audio->time_base);
161         } else {
162                 assert(false);
163         }
164
165         {
166                 lock_guard<mutex> lock(mu);
167                 if (write_strategy == WriteStrategy::WRITE_BACKGROUND) {
168                         packet_queue.push_back(QueuedPacket{ av_packet_clone(&pkt_copy), pts });
169                         if (plug_count == 0) packet_queue_ready.notify_all();
170                 } else if (plug_count > 0) {
171                         packet_queue.push_back(QueuedPacket{ av_packet_clone(&pkt_copy), pts });
172                 } else {
173                         write_packet_or_die(pkt_copy, pts);
174                 }
175         }
176
177         av_packet_unref(&pkt_copy);
178 }
179
180 void Mux::write_packet_or_die(const AVPacket &pkt, int64_t unscaled_pts)
181 {
182         for (MuxMetrics *metric : metrics) {
183                 if (pkt.stream_index == 0) {
184                         metric->metric_video_bytes += pkt.size;
185                 } else if (pkt.stream_index == 1) {
186                         metric->metric_audio_bytes += pkt.size;
187                 } else {
188                         assert(false);
189                 }
190         }
191         int64_t old_pos = avctx->pb->pos;
192         if (av_interleaved_write_frame(avctx, const_cast<AVPacket *>(&pkt)) < 0) {
193                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
194                 exit(1);
195         }
196         avio_flush(avctx->pb);
197         for (MuxMetrics *metric : metrics) {
198                 metric->metric_written_bytes += avctx->pb->pos - old_pos;
199         }
200
201         if (pkt.stream_index == 0 && write_callback != nullptr) {
202                 write_callback(unscaled_pts);
203         }
204 }
205
206 void Mux::plug()
207 {
208         lock_guard<mutex> lock(mu);
209         ++plug_count;
210 }
211
212 void Mux::unplug()
213 {
214         lock_guard<mutex> lock(mu);
215         if (--plug_count > 0) {
216                 return;
217         }
218         assert(plug_count >= 0);
219
220         sort(packet_queue.begin(), packet_queue.end(), PacketBefore(avctx));
221
222         if (write_strategy == WRITE_BACKGROUND) {
223                 packet_queue_ready.notify_all();
224         } else {
225                 for (QueuedPacket &qp : packet_queue) {
226                         write_packet_or_die(*qp.pkt, qp.unscaled_pts);
227                         av_packet_free(&qp.pkt);
228                 }
229                 packet_queue.clear();
230         }
231 }
232
233 void Mux::thread_func()
234 {
235         unique_lock<mutex> lock(mu);
236         for ( ;; ) {
237                 packet_queue_ready.wait(lock, [this]() {
238                         return writer_thread_should_quit || (!packet_queue.empty() && plug_count == 0);
239                 });
240                 if (writer_thread_should_quit && packet_queue.empty()) {
241                         // All done.
242                         break;
243                 }
244
245                 assert(!packet_queue.empty() && plug_count == 0);
246                 vector<QueuedPacket> packets;
247                 swap(packets, packet_queue);
248
249                 lock.unlock();
250                 for (QueuedPacket &qp : packets) {
251                         write_packet_or_die(*qp.pkt, qp.unscaled_pts);
252                         av_packet_free(&qp.pkt);
253                 }
254                 lock.lock();
255         }
256 }
257
258 void MuxMetrics::init(const vector<pair<string, string>> &labels)
259 {
260         // TODO: See if we want to reintroduce these.
261 }