]> git.sesse.net Git - nageru/blob - shared/mux.cpp
Combine ref_counted_gl_sync.h from Nageru and Futatabi. (Only whitespace differences.)
[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/mux_opts.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, WithAudio with_audio, int time_base, function<void(int64_t)> write_callback, WriteStrategy write_strategy, const vector<MuxMetrics *> &metrics)
51         : write_strategy(write_strategy), avctx(avctx), write_callback(write_callback), metrics(metrics)
52 {
53         avstream_video = avformat_new_stream(avctx, nullptr);
54         if (avstream_video == nullptr) {
55                 fprintf(stderr, "avformat_new_stream() failed\n");
56                 exit(1);
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_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         } else {
66                 assert(video_codec == CODEC_MJPEG);
67                 avstream_video->codecpar->codec_id = AV_CODEC_ID_MJPEG;
68         }
69         avstream_video->codecpar->width = width;
70         avstream_video->codecpar->height = height;
71
72         // Colorspace details. Closely correspond to settings in EffectChain_finalize,
73         // as noted in each comment.
74         // Note that the H.264 stream also contains this information and depending on the
75         // mux, this might simply get ignored. See sps_rbsp().
76         // Note that there's no way to change this per-frame as the H.264 stream
77         // would like to be able to.
78         avstream_video->codecpar->color_primaries = AVCOL_PRI_BT709;  // RGB colorspace (inout_format.color_space).
79         avstream_video->codecpar->color_trc = AVCOL_TRC_IEC61966_2_1;  // Gamma curve (inout_format.gamma_curve).
80         // YUV colorspace (output_ycbcr_format.luma_coefficients).
81         avstream_video->codecpar->color_space = color_space;
82         avstream_video->codecpar->color_range = AVCOL_RANGE_MPEG;  // Full vs. limited range (output_ycbcr_format.full_range).
83         avstream_video->codecpar->chroma_location = AVCHROMA_LOC_LEFT;  // Chroma sample location. See chroma_offset_0[] in Mixer::subsample_chroma().
84         avstream_video->codecpar->field_order = AV_FIELD_PROGRESSIVE;
85
86         if (!video_extradata.empty()) {
87                 avstream_video->codecpar->extradata = (uint8_t *)av_malloc(video_extradata.size());
88                 avstream_video->codecpar->extradata_size = video_extradata.size();
89                 memcpy(avstream_video->codecpar->extradata, video_extradata.data(), video_extradata.size());
90         }
91
92         if (with_audio == WITH_AUDIO) {
93                 avstream_audio = avformat_new_stream(avctx, nullptr);
94                 if (avstream_audio == nullptr) {
95                         fprintf(stderr, "avformat_new_stream() failed\n");
96                         exit(1);
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                         exit(1);
102                 }
103         } else {
104                 assert(with_audio == WITHOUT_AUDIO);
105                 avstream_audio = nullptr;
106         }
107
108         AVDictionary *options = NULL;
109         vector<pair<string, string>> opts = MUX_OPTS;
110         for (pair<string, string> opt : opts) {
111                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
112         }
113         if (avformat_write_header(avctx, &options) < 0) {
114                 fprintf(stderr, "avformat_write_header() failed\n");
115                 exit(1);
116         }
117         for (MuxMetrics *metric : metrics) {
118                 metric->metric_written_bytes += avctx->pb->pos;
119         }
120
121         // Make sure the header is written before the constructor exits.
122         avio_flush(avctx->pb);
123
124         if (write_strategy == WRITE_BACKGROUND) {
125                 writer_thread = thread(&Mux::thread_func, this);
126         }
127 }
128
129 Mux::~Mux()
130 {
131         assert(plug_count == 0);
132         if (write_strategy == WRITE_BACKGROUND) {
133                 writer_thread_should_quit = true;
134                 packet_queue_ready.notify_all();
135                 writer_thread.join();
136         }
137         int64_t old_pos = avctx->pb->pos;
138         av_write_trailer(avctx);
139         for (MuxMetrics *metric : metrics) {
140                 metric->metric_written_bytes += avctx->pb->pos - old_pos;
141         }
142
143         if (!(avctx->oformat->flags & AVFMT_NOFILE) &&
144             !(avctx->flags & AVFMT_FLAG_CUSTOM_IO)) {
145                 avio_closep(&avctx->pb);
146         }
147         avformat_free_context(avctx);
148 }
149
150 void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts, AVRational timebase, int stream_index_override)
151 {
152         AVPacket pkt_copy;
153         av_init_packet(&pkt_copy);
154         if (av_packet_ref(&pkt_copy, &pkt) < 0) {
155                 fprintf(stderr, "av_copy_packet() failed\n");
156                 exit(1);
157         }
158         if (stream_index_override != -1) {
159                 pkt_copy.stream_index = stream_index_override;
160         }
161         if (pkt_copy.stream_index == 0) {
162                 pkt_copy.pts = av_rescale_q(pts, timebase, avstream_video->time_base);
163                 pkt_copy.dts = av_rescale_q(dts, timebase, avstream_video->time_base);
164                 pkt_copy.duration = av_rescale_q(pkt.duration, timebase, avstream_video->time_base);
165         } else if (pkt_copy.stream_index == 1) {
166                 pkt_copy.pts = av_rescale_q(pts, timebase, avstream_audio->time_base);
167                 pkt_copy.dts = av_rescale_q(dts, timebase, avstream_audio->time_base);
168                 pkt_copy.duration = av_rescale_q(pkt.duration, timebase, avstream_audio->time_base);
169         } else {
170                 assert(false);
171         }
172
173         {
174                 lock_guard<mutex> lock(mu);
175                 if (write_strategy == WriteStrategy::WRITE_BACKGROUND) {
176                         packet_queue.push_back(QueuedPacket{ av_packet_clone(&pkt_copy), pts });
177                         if (plug_count == 0)
178                                 packet_queue_ready.notify_all();
179                 } else if (plug_count > 0) {
180                         packet_queue.push_back(QueuedPacket{ av_packet_clone(&pkt_copy), pts });
181                 } else {
182                         write_packet_or_die(pkt_copy, pts);
183                 }
184         }
185
186         av_packet_unref(&pkt_copy);
187 }
188
189 void Mux::write_packet_or_die(const AVPacket &pkt, int64_t unscaled_pts)
190 {
191         for (MuxMetrics *metric : metrics) {
192                 if (pkt.stream_index == 0) {
193                         metric->metric_video_bytes += pkt.size;
194                 } else if (pkt.stream_index == 1) {
195                         metric->metric_audio_bytes += pkt.size;
196                 } else {
197                         assert(false);
198                 }
199         }
200         int64_t old_pos = avctx->pb->pos;
201         if (av_interleaved_write_frame(avctx, const_cast<AVPacket *>(&pkt)) < 0) {
202                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
203                 abort();
204         }
205         avio_flush(avctx->pb);
206         for (MuxMetrics *metric : metrics) {
207                 metric->metric_written_bytes += avctx->pb->pos - old_pos;
208         }
209
210         if (pkt.stream_index == 0 && write_callback != nullptr) {
211                 write_callback(unscaled_pts);
212         }
213 }
214
215 void Mux::plug()
216 {
217         lock_guard<mutex> lock(mu);
218         ++plug_count;
219 }
220
221 void Mux::unplug()
222 {
223         lock_guard<mutex> lock(mu);
224         if (--plug_count > 0) {
225                 return;
226         }
227         assert(plug_count >= 0);
228
229         sort(packet_queue.begin(), packet_queue.end(), PacketBefore(avctx));
230
231         if (write_strategy == WRITE_BACKGROUND) {
232                 packet_queue_ready.notify_all();
233         } else {
234                 for (QueuedPacket &qp : packet_queue) {
235                         write_packet_or_die(*qp.pkt, qp.unscaled_pts);
236                         av_packet_free(&qp.pkt);
237                 }
238                 packet_queue.clear();
239         }
240 }
241
242 void Mux::thread_func()
243 {
244         pthread_setname_np(pthread_self(), "Mux");
245
246         unique_lock<mutex> lock(mu);
247         for ( ;; ) {
248                 packet_queue_ready.wait(lock, [this]() {
249                         return writer_thread_should_quit || (!packet_queue.empty() && plug_count == 0);
250                 });
251                 if (writer_thread_should_quit && packet_queue.empty()) {
252                         // All done.
253                         break;
254                 }
255
256                 assert(!packet_queue.empty() && plug_count == 0);
257                 vector<QueuedPacket> packets;
258                 swap(packets, packet_queue);
259
260                 lock.unlock();
261                 for (QueuedPacket &qp : packets) {
262                         write_packet_or_die(*qp.pkt, qp.unscaled_pts);
263                         av_packet_free(&qp.pkt);
264                 }
265                 lock.lock();
266         }
267 }
268
269 void MuxMetrics::init(const vector<pair<string, string>> &labels)
270 {
271         vector<pair<string, string>> labels_video = labels;
272         labels_video.emplace_back("stream", "video");
273         global_metrics.add("mux_stream_bytes", labels_video, &metric_video_bytes);
274
275         vector<pair<string, string>> labels_audio = labels;
276         labels_audio.emplace_back("stream", "audio");
277         global_metrics.add("mux_stream_bytes", labels_audio, &metric_audio_bytes);
278
279         global_metrics.add("mux_written_bytes", labels, &metric_written_bytes);
280 }