]> git.sesse.net Git - nageru/blob - mux.cpp
Support switching Y'CbCr coefficients midway, which will allow doing the Right Thing...
[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 "timebase.h"
27
28 using namespace std;
29
30 struct PacketBefore {
31         PacketBefore(const AVFormatContext *ctx) : ctx(ctx) {}
32
33         bool operator() (const AVPacket *a, const AVPacket *b) const {
34                 int64_t a_dts = (a->dts == AV_NOPTS_VALUE ? a->pts : a->dts);
35                 int64_t b_dts = (b->dts == AV_NOPTS_VALUE ? b->pts : b->dts);
36                 AVRational a_timebase = ctx->streams[a->stream_index]->time_base;
37                 AVRational b_timebase = ctx->streams[b->stream_index]->time_base;
38                 if (av_compare_ts(a_dts, a_timebase, b_dts, b_timebase) != 0) {
39                         return av_compare_ts(a_dts, a_timebase, b_dts, b_timebase) < 0;
40                 } else {
41                         return av_compare_ts(a->pts, a_timebase, b->pts, b_timebase) < 0;
42                 }
43         }
44
45         const AVFormatContext * const ctx;
46 };
47
48 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)
49         : avctx(avctx), write_callback(write_callback)
50 {
51         avstream_video = avformat_new_stream(avctx, nullptr);
52         if (avstream_video == nullptr) {
53                 fprintf(stderr, "avformat_new_stream() failed\n");
54                 exit(1);
55         }
56         avstream_video->time_base = AVRational{1, time_base};
57         avstream_video->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
58         if (video_codec == CODEC_H264) {
59                 avstream_video->codecpar->codec_id = AV_CODEC_ID_H264;
60         } else {
61                 assert(video_codec == CODEC_NV12);
62                 avstream_video->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
63                 avstream_video->codecpar->codec_tag = avcodec_pix_fmt_to_codec_tag(AV_PIX_FMT_NV12);
64         }
65         avstream_video->codecpar->width = width;
66         avstream_video->codecpar->height = height;
67
68         // Colorspace details. Closely correspond to settings in EffectChain_finalize,
69         // as noted in each comment.
70         // Note that the H.264 stream also contains this information and depending on the
71         // mux, this might simply get ignored. See sps_rbsp().
72         // Note that there's no way to change this per-frame as the H.264 stream
73         // would like to be able to.
74         avstream_video->codecpar->color_primaries = AVCOL_PRI_BT709;  // RGB colorspace (inout_format.color_space).
75         avstream_video->codecpar->color_trc = AVCOL_TRC_UNSPECIFIED;  // Gamma curve (inout_format.gamma_curve).
76         // YUV colorspace (output_ycbcr_format.luma_coefficients).
77         if (global_flags.ycbcr_rec709_coefficients) {
78                 avstream_video->codecpar->color_space = AVCOL_SPC_BT709;
79         } else {
80                 avstream_video->codecpar->color_space = AVCOL_SPC_SMPTE170M;
81         }
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         avstream_audio = avformat_new_stream(avctx, nullptr);
93         if (avstream_audio == nullptr) {
94                 fprintf(stderr, "avformat_new_stream() failed\n");
95                 exit(1);
96         }
97         avstream_audio->time_base = AVRational{1, time_base};
98         if (avcodec_parameters_copy(avstream_audio->codecpar, audio_codecpar) < 0) {
99                 fprintf(stderr, "avcodec_parameters_copy() failed\n");
100                 exit(1);
101         }
102
103         AVDictionary *options = NULL;
104         vector<pair<string, string>> opts = MUX_OPTS;
105         for (pair<string, string> opt : opts) {
106                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
107         }
108         if (avformat_write_header(avctx, &options) < 0) {
109                 fprintf(stderr, "avformat_write_header() failed\n");
110                 exit(1);
111         }
112
113         // Make sure the header is written before the constructor exits.
114         avio_flush(avctx->pb);
115 }
116
117 Mux::~Mux()
118 {
119         av_write_trailer(avctx);
120         if (!(avctx->oformat->flags & AVFMT_NOFILE) &&
121             !(avctx->flags & AVFMT_FLAG_CUSTOM_IO)) {
122                 avio_closep(&avctx->pb);
123         }
124         avformat_free_context(avctx);
125 }
126
127 void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
128 {
129         AVPacket pkt_copy;
130         if (av_copy_packet(&pkt_copy, &pkt) < 0) {
131                 fprintf(stderr, "av_copy_packet() failed\n");
132                 exit(1);
133         }
134         if (pkt.stream_index == 0) {
135                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base);
136                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base);
137                 pkt_copy.duration = av_rescale_q(pkt.duration, AVRational{1, TIMEBASE}, avstream_video->time_base);
138         } else if (pkt.stream_index == 1) {
139                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
140                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
141                 pkt_copy.duration = av_rescale_q(pkt.duration, AVRational{1, TIMEBASE}, avstream_audio->time_base);
142         } else {
143                 assert(false);
144         }
145
146         {
147                 lock_guard<mutex> lock(mu);
148                 if (plug_count > 0) {
149                         plugged_packets.push_back(av_packet_clone(&pkt_copy));
150                 } else {
151                         write_packet_or_die(pkt_copy);
152                 }
153         }
154
155         av_packet_unref(&pkt_copy);
156
157         // Note: This will be wrong in the case of plugged packets, but that only happens
158         // for network streams, not for files, and write callbacks are only really relevant
159         // for files. (We don't want to do this from write_packet_or_die, as it only has
160         // the rescaled pts, which is unsuitable for callback.)
161         if (pkt.stream_index == 0 && write_callback != nullptr) {
162                 write_callback(pts);
163         }
164 }
165
166 void Mux::write_packet_or_die(const AVPacket &pkt)
167 {
168         if (av_interleaved_write_frame(avctx, const_cast<AVPacket *>(&pkt)) < 0) {
169                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
170                 exit(1);
171         }
172         avio_flush(avctx->pb);
173 }
174
175 void Mux::plug()
176 {
177         lock_guard<mutex> lock(mu);
178         ++plug_count;
179 }
180
181 void Mux::unplug()
182 {
183         lock_guard<mutex> lock(mu);
184         if (--plug_count > 0) {
185                 return;
186         }
187         assert(plug_count >= 0);
188
189         sort(plugged_packets.begin(), plugged_packets.end(), PacketBefore(avctx));
190
191         for (AVPacket *pkt : plugged_packets) {
192                 write_packet_or_die(*pkt);
193                 av_packet_free(&pkt);
194         }
195         plugged_packets.clear();
196 }