]> git.sesse.net Git - nageru/blob - mux.cpp
Fix a memory leak in interleaving.
[nageru] / mux.cpp
1 #include <assert.h>
2
3 #include <algorithm>
4 #include <mutex>
5 #include <string>
6 #include <vector>
7
8 #include "defs.h"
9 #include "mux.h"
10 #include "timebase.h"
11
12 using namespace std;
13
14 struct PacketBefore {
15         PacketBefore(const AVFormatContext *ctx) : ctx(ctx) {}
16
17         bool operator() (const AVPacket *a, const AVPacket *b) const {
18                 int64_t a_dts = (a->dts == AV_NOPTS_VALUE ? a->pts : a->dts);
19                 int64_t b_dts = (b->dts == AV_NOPTS_VALUE ? b->pts : b->dts);
20                 AVRational a_timebase = ctx->streams[a->stream_index]->time_base;
21                 AVRational b_timebase = ctx->streams[b->stream_index]->time_base;
22                 if (av_compare_ts(a_dts, a_timebase, b_dts, b_timebase) != 0) {
23                         return av_compare_ts(a_dts, a_timebase, b_dts, b_timebase) < 0;
24                 } else {
25                         return av_compare_ts(a->pts, a_timebase, b->pts, b_timebase) < 0;
26                 }
27         }
28
29         const AVFormatContext * const ctx;
30 };
31
32 Mux::Mux(AVFormatContext *avctx, int width, int height, Codec video_codec, const string &video_extradata, const AVCodecContext *audio_ctx, int time_base, KeyFrameSignalReceiver *keyframe_signal_receiver)
33         : avctx(avctx), keyframe_signal_receiver(keyframe_signal_receiver)
34 {
35         AVCodec *codec_video = avcodec_find_encoder((video_codec == CODEC_H264) ? AV_CODEC_ID_H264 : AV_CODEC_ID_RAWVIDEO);
36         avstream_video = avformat_new_stream(avctx, codec_video);
37         if (avstream_video == nullptr) {
38                 fprintf(stderr, "avformat_new_stream() failed\n");
39                 exit(1);
40         }
41         avstream_video->time_base = AVRational{1, time_base};
42         avstream_video->codec->codec_type = AVMEDIA_TYPE_VIDEO;
43         if (video_codec == CODEC_H264) {
44                 avstream_video->codec->codec_id = AV_CODEC_ID_H264;
45         } else {
46                 assert(video_codec == CODEC_NV12);
47                 avstream_video->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
48                 avstream_video->codec->codec_tag = avcodec_pix_fmt_to_codec_tag(AV_PIX_FMT_NV12);
49         }
50         avstream_video->codec->width = width;
51         avstream_video->codec->height = height;
52         avstream_video->codec->time_base = AVRational{1, time_base};
53         avstream_video->codec->ticks_per_frame = 1;  // or 2?
54
55         // Colorspace details. Closely correspond to settings in EffectChain_finalize,
56         // as noted in each comment.
57         // Note that the H.264 stream also contains this information and depending on the
58         // mux, this might simply get ignored. See sps_rbsp().
59         avstream_video->codec->color_primaries = AVCOL_PRI_BT709;  // RGB colorspace (inout_format.color_space).
60         avstream_video->codec->color_trc = AVCOL_TRC_UNSPECIFIED;  // Gamma curve (inout_format.gamma_curve).
61         avstream_video->codec->colorspace = AVCOL_SPC_SMPTE170M;  // YUV colorspace (output_ycbcr_format.luma_coefficients).
62         avstream_video->codec->color_range = AVCOL_RANGE_MPEG;  // Full vs. limited range (output_ycbcr_format.full_range).
63         avstream_video->codec->chroma_sample_location = AVCHROMA_LOC_LEFT;  // Chroma sample location. See chroma_offset_0[] in Mixer::subsample_chroma().
64         avstream_video->codec->field_order = AV_FIELD_PROGRESSIVE;
65
66         if (!video_extradata.empty()) {
67                 avstream_video->codec->extradata = (uint8_t *)av_malloc(video_extradata.size());
68                 avstream_video->codec->extradata_size = video_extradata.size();
69                 memcpy(avstream_video->codec->extradata, video_extradata.data(), video_extradata.size());
70         }
71
72         avstream_audio = avformat_new_stream(avctx, nullptr);
73         if (avstream_audio == nullptr) {
74                 fprintf(stderr, "avformat_new_stream() failed\n");
75                 exit(1);
76         }
77         avstream_audio->time_base = AVRational{1, time_base};
78         avcodec_copy_context(avstream_audio->codec, audio_ctx);
79
80         AVDictionary *options = NULL;
81         vector<pair<string, string>> opts = MUX_OPTS;
82         for (pair<string, string> opt : opts) {
83                 av_dict_set(&options, opt.first.c_str(), opt.second.c_str(), 0);
84         }
85         if (avformat_write_header(avctx, &options) < 0) {
86                 fprintf(stderr, "avformat_write_header() failed\n");
87                 exit(1);
88         }
89
90         // Make sure the header is written before the constructor exits.
91         avio_flush(avctx->pb);
92 }
93
94 Mux::~Mux()
95 {
96         av_write_trailer(avctx);
97         av_free(avctx->pb->buffer);
98         av_free(avctx->pb);
99         avformat_free_context(avctx);
100 }
101
102 void Mux::add_packet(const AVPacket &pkt, int64_t pts, int64_t dts)
103 {
104         AVPacket pkt_copy;
105         if (av_copy_packet(&pkt_copy, &pkt) < 0) {
106                 fprintf(stderr, "av_copy_packet() failed\n");
107                 exit(1);
108         }
109         if (pkt.stream_index == 0) {
110                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_video->time_base);
111                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_video->time_base);
112                 pkt_copy.duration = av_rescale_q(pkt.duration, AVRational{1, TIMEBASE}, avstream_video->time_base);
113         } else if (pkt.stream_index == 1) {
114                 pkt_copy.pts = av_rescale_q(pts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
115                 pkt_copy.dts = av_rescale_q(dts, AVRational{1, TIMEBASE}, avstream_audio->time_base);
116                 pkt_copy.duration = av_rescale_q(pkt.duration, AVRational{1, TIMEBASE}, avstream_audio->time_base);
117         } else {
118                 assert(false);
119         }
120
121         {
122                 lock_guard<mutex> lock(mu);
123                 if (plug_count > 0) {
124                         plugged_packets.push_back(av_packet_clone(&pkt_copy));
125                 } else {
126                         add_interleaved_packet(pkt_copy);
127                 }
128         }
129
130         av_packet_unref(&pkt_copy);
131 }
132
133 void Mux::add_interleaved_packet(const AVPacket &pkt)
134 {
135         if (waiting_packets.empty() || waiting_packets.front()->stream_index == pkt.stream_index) {
136                 // We could still get packets of the other type with earlier pts/dts,
137                 // so we'll have to queue and wait.
138                 waiting_packets.push(av_packet_clone(const_cast<AVPacket *>(&pkt)));
139                 return;
140         }
141
142         // Flush all the queued packets that are supposed to go before this.
143         PacketBefore before(avctx);
144         while (!waiting_packets.empty() && !before(&pkt, waiting_packets.front())) {
145                 AVPacket *queued_pkt = waiting_packets.front();
146                 waiting_packets.pop();
147                 write_packet_with_signal(*queued_pkt);
148                 av_packet_free(&queued_pkt);
149         }
150
151         if (waiting_packets.empty()) {
152                 waiting_packets.push(av_packet_clone(const_cast<AVPacket *>(&pkt)));
153         } else {
154                 write_packet_with_signal(pkt);
155         }
156 }
157
158 void Mux::write_packet_with_signal(const AVPacket &pkt)
159 {
160         if (keyframe_signal_receiver) {
161                 if (pkt.flags & AV_PKT_FLAG_KEY) {
162                         av_write_frame(avctx, nullptr);
163                         keyframe_signal_receiver->signal_keyframe();
164                 }
165         }
166         if (av_write_frame(avctx, const_cast<AVPacket *>(&pkt)) < 0) {
167                 fprintf(stderr, "av_interleaved_write_frame() failed\n");
168                 exit(1);
169         }
170         avio_flush(avctx->pb);
171 }
172
173 void Mux::plug()
174 {
175         lock_guard<mutex> lock(mu);
176         ++plug_count;
177 }
178
179 void Mux::unplug()
180 {
181         lock_guard<mutex> lock(mu);
182         if (--plug_count > 0) {
183                 return;
184         }
185         assert(plug_count >= 0);
186
187         sort(plugged_packets.begin(), plugged_packets.end(), PacketBefore(avctx));
188
189         for (AVPacket *pkt : plugged_packets) {
190                 add_interleaved_packet(*pkt);
191                 av_packet_free(&pkt);
192         }
193         plugged_packets.clear();
194 }