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