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>
32 PacketBefore(const AVFormatContext *ctx) : ctx(ctx) {}
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;
42 return av_compare_ts(a->pts, a_timebase, b->pts, b_timebase) < 0;
46 const AVFormatContext * const ctx;
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)
52 avstream_video = avformat_new_stream(avctx, nullptr);
53 if (avstream_video == nullptr) {
54 fprintf(stderr, "avformat_new_stream() failed\n");
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;
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);
66 avstream_video->codecpar->width = width;
67 avstream_video->codecpar->height = height;
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;
81 avstream_video->codecpar->color_space = AVCOL_SPC_SMPTE170M;
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;
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());
93 avstream_audio = avformat_new_stream(avctx, nullptr);
94 if (avstream_audio == nullptr) {
95 fprintf(stderr, "avformat_new_stream() failed\n");
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");
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);
109 if (avformat_write_header(avctx, &options) < 0) {
110 fprintf(stderr, "avformat_write_header() failed\n");
113 for (MuxMetrics *metric : metrics) {
114 metric->metric_written_bytes += avctx->pb->pos;
117 // Make sure the header is written before the constructor exits.
118 avio_flush(avctx->pb);
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;
129 if (!(avctx->oformat->flags & AVFMT_NOFILE) &&
130 !(avctx->flags & AVFMT_FLAG_CUSTOM_IO)) {
131 avio_closep(&avctx->pb);
133 avformat_free_context(avctx);
136 void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
139 if (av_copy_packet(&pkt_copy, &pkt) < 0) {
140 fprintf(stderr, "av_copy_packet() failed\n");
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);
156 lock_guard<mutex> lock(mu);
157 if (plug_count > 0) {
158 plugged_packets.push_back(av_packet_clone(&pkt_copy));
160 write_packet_or_die(pkt_copy);
164 av_packet_unref(&pkt_copy);
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) {
175 void Mux::write_packet_or_die(const AVPacket &pkt)
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;
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");
191 avio_flush(avctx->pb);
192 for (MuxMetrics *metric : metrics) {
193 metric->metric_written_bytes += avctx->pb->pos - old_pos;
199 lock_guard<mutex> lock(mu);
205 lock_guard<mutex> lock(mu);
206 if (--plug_count > 0) {
209 assert(plug_count >= 0);
211 sort(plugged_packets.begin(), plugged_packets.end(), PacketBefore(avctx));
213 for (AVPacket *pkt : plugged_packets) {
214 write_packet_or_die(*pkt);
215 av_packet_free(&pkt);
217 plugged_packets.clear();
220 void MuxMetrics::init(const vector<pair<string, string>> &labels)
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);
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);
230 global_metrics.add("mux_written_bytes", labels, &metric_written_bytes);