]> git.sesse.net Git - nageru/blob - mux.cpp
Update the queue length metric after trimming, not before.
[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 "flags.h"
26 #include "metrics.h"
27 #include "timebase.h"
28
29 using namespace std;
30
31 struct PacketBefore {
32         PacketBefore(const AVFormatContext *ctx) : ctx(ctx) {}
33
34         bool operator() (const AVPacket *a, const AVPacket *b) const {
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, const vector<MuxMetrics *> &metrics)
50         : 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_UNSPECIFIED;  // Gamma curve (inout_format.gamma_curve).
77         // YUV colorspace (output_ycbcr_format.luma_coefficients).
78         if (global_flags.ycbcr_rec709_coefficients) {
79                 avstream_video->codecpar->color_space = AVCOL_SPC_BT709;
80         } else {
81                 avstream_video->codecpar->color_space = AVCOL_SPC_SMPTE170M;
82         }
83         avstream_video->codecpar->color_range = AVCOL_RANGE_MPEG;  // Full vs. limited range (output_ycbcr_format.full_range).
84         avstream_video->codecpar->chroma_location = AVCHROMA_LOC_LEFT;  // Chroma sample location. See chroma_offset_0[] in Mixer::subsample_chroma().
85         avstream_video->codecpar->field_order = AV_FIELD_PROGRESSIVE;
86
87         if (!video_extradata.empty()) {
88                 avstream_video->codecpar->extradata = (uint8_t *)av_malloc(video_extradata.size());
89                 avstream_video->codecpar->extradata_size = video_extradata.size();
90                 memcpy(avstream_video->codecpar->extradata, video_extradata.data(), video_extradata.size());
91         }
92
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
104         AVDictionary *options = NULL;
105         vector<pair<string, string>> opts = MUX_OPTS;
106         for (pair<string, string> opt : opts) {
107                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
108         }
109         if (avformat_write_header(avctx, &options) < 0) {
110                 fprintf(stderr, "avformat_write_header() failed\n");
111                 exit(1);
112         }
113         for (MuxMetrics *metric : metrics) {
114                 metric->metric_written_bytes += avctx->pb->pos;
115         }
116
117         // Make sure the header is written before the constructor exits.
118         avio_flush(avctx->pb);
119 }
120
121 Mux::~Mux()
122 {
123         int64_t old_pos = avctx->pb->pos;
124         av_write_trailer(avctx);
125         for (MuxMetrics *metric : metrics) {
126                 metric->metric_written_bytes += avctx->pb->pos - old_pos;
127         }
128
129         if (!(avctx->oformat->flags & AVFMT_NOFILE) &&
130             !(avctx->flags & AVFMT_FLAG_CUSTOM_IO)) {
131                 avio_closep(&avctx->pb);
132         }
133         avformat_free_context(avctx);
134 }
135
136 void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
137 {
138         AVPacket pkt_copy;
139         if (av_copy_packet(&pkt_copy, &pkt) < 0) {
140                 fprintf(stderr, "av_copy_packet() failed\n");
141                 exit(1);
142         }
143         if (pkt.stream_index == 0) {
144                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base);
145                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base);
146                 pkt_copy.duration = av_rescale_q(pkt.duration, AVRational{1, TIMEBASE}, avstream_video->time_base);
147         } else if (pkt.stream_index == 1) {
148                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
149                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
150                 pkt_copy.duration = av_rescale_q(pkt.duration, AVRational{1, TIMEBASE}, avstream_audio->time_base);
151         } else {
152                 assert(false);
153         }
154
155         {
156                 lock_guard<mutex> lock(mu);
157                 if (plug_count > 0) {
158                         plugged_packets.push_back(av_packet_clone(&pkt_copy));
159                 } else {
160                         write_packet_or_die(pkt_copy);
161                 }
162         }
163
164         av_packet_unref(&pkt_copy);
165
166         // Note: This will be wrong in the case of plugged packets, but that only happens
167         // for network streams, not for files, and write callbacks are only really relevant
168         // for files. (We don't want to do this from write_packet_or_die, as it only has
169         // the rescaled pts, which is unsuitable for callback.)
170         if (pkt.stream_index == 0 && write_callback != nullptr) {
171                 write_callback(pts);
172         }
173 }
174
175 void Mux::write_packet_or_die(const AVPacket &pkt)
176 {
177         for (MuxMetrics *metric : metrics) {
178                 if (pkt.stream_index == 0) {
179                         metric->metric_video_bytes += pkt.size;
180                 } else if (pkt.stream_index == 1) {
181                         metric->metric_audio_bytes += pkt.size;
182                 } else {
183                         assert(false);
184                 }
185         }
186         int64_t old_pos = avctx->pb->pos;
187         if (av_interleaved_write_frame(avctx, const_cast<AVPacket *>(&pkt)) < 0) {
188                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
189                 exit(1);
190         }
191         avio_flush(avctx->pb);
192         for (MuxMetrics *metric : metrics) {
193                 metric->metric_written_bytes += avctx->pb->pos - old_pos;
194         }
195 }
196
197 void Mux::plug()
198 {
199         lock_guard<mutex> lock(mu);
200         ++plug_count;
201 }
202
203 void Mux::unplug()
204 {
205         lock_guard<mutex> lock(mu);
206         if (--plug_count > 0) {
207                 return;
208         }
209         assert(plug_count >= 0);
210
211         sort(plugged_packets.begin(), plugged_packets.end(), PacketBefore(avctx));
212
213         for (AVPacket *pkt : plugged_packets) {
214                 write_packet_or_die(*pkt);
215                 av_packet_free(&pkt);
216         }
217         plugged_packets.clear();
218 }
219
220 void MuxMetrics::init(const vector<pair<string, string>> &labels)
221 {
222         vector<pair<string, string>> labels_video = labels;
223         labels_video.emplace_back("stream", "video");
224         global_metrics.add("mux_stream_bytes", labels_video, &metric_video_bytes);
225
226         vector<pair<string, string>> labels_audio = labels;
227         labels_audio.emplace_back("stream", "audio");
228         global_metrics.add("mux_stream_bytes", labels_audio, &metric_audio_bytes);
229
230         global_metrics.add("mux_written_bytes", labels, &metric_written_bytes);
231 }