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